答:
Try this in the controller while updating</p>

```<code>if(isset($_FILES['file_to_upload']['name'])){
   //Image uploading...
}
//Updating other data...
</code>```

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');
     }

}

Body:
Try this in the controller while updating

if(isset($_FILES['file_to_upload']['name'])){
   //Image uploading...
}
//Updating other data...


来源: stackexchange

问:
Grid Hosting for Windows
Are there any good grid-hosting companies out there that offer .NET stacks? Something like MediaTemple - which won't host the worlds fastest websites, but for the price is far better than "shared hosting". I've used Rackspace's Mosso, but it sucked - it never felt like a normal .NET stack (caching was odd, site recompilation was odd).

答:
I've heard good things about Mosso .

http://www.mosso.com/

ContentLicense: CC BY-SA 2.5

Title: Grid Hosting for Windows


问:
What to do with XML node names (hard coded values)?
I've been working with xml lately.  And have noticed a bit of a phenomenon (maybe not that big of a deal to the rest of the world, but to me it was).  Perhaps, it is me being a newb.  But shouldn't most hard coded or magic numbers be broken out to a configuration file?  For example,

```<code>    string url = "http://www.domain.com/aDocument.xml";
    XmlDocument feed = new XmlDocument();
    feed.Load(url);

    XmlNode errorsNode = feed.SelectSingleNode("Errors");

    if (errorsNode != null)
    {
        XmlNode error = errorsNode.FirstChild;
        lblError.Text = "Error: " + error.SelectSingleNode("Code").InnerText;
    }
</code>```

Here is the xml document:

```<code>  <Errors>
    <Error>
        <Code>AWS.MissingParameters</Code>
        <Message>You are missing an parameter</Message>
    </Error>
 </Errors>
</code>```

How would you parse this without hardcoding "code" or "message"?

答: I don't know if it's the best option, but I've typically seen this kind of thing handled by using a set of string constants.  At least then, if you're processing the same XML schema in multiple places, your magic strings are all defined in one place.  I'd think relegating this to a configuration file would be overkill unless the schema changes frequently.

Body:
I've been working with xml lately.  And have noticed a bit of a phenomenon (maybe not that big of a deal to the rest of the world, but to me it was).  Perhaps, it is me being a newb.  But shouldn't most hard coded or magic numbers be broken out to a configuration file?  For example,

    string url = "http://www.domain.com/aDocument.xml";
    XmlDocument feed = new XmlDocument();
    feed.Load(url);

    XmlNode errorsNode = feed.SelectSingleNode("Errors");

    if (errorsNode != null)
    {
        XmlNode error = errorsNode.FirstChild;
        lblError.Text = "Error: " + error.SelectSingleNode("Code").InnerText;
    }

Here is the xml document:

  <Errors>
    <Error>
        AWS.MissingParameters
        <Message>You are missing an parameter</Message>
    </Error>
 </Errors>

How would you parse this without hardcoding "code" or "message"?

OwnerDisplayName: Mike Powell


问:
Why SUPER privileges are disabled when binary logging option is on?
there are lot of recommendations over the Internet on how to enable SUPER privileges in case if someone hit the following error:

"ERROR 1419 (HY000): You do not have the SUPER Privilege and Binary Logging is Enabled"

But I wasn't be able to find WHY MySQL disables these privileges when binary logging option is on.

Are there some issues with replication if I use e.g. triggers which modify DB or something else? Whether it's safe and, if no, what kind of issues and under which circumstances I can hit if I will return SUPER privileges back? I think there should be some rationale behind this restriction but don't understand which one.

Does anybody have an answer on this?

Thank you.

答:
Here is some detailed explaination I had found in documentation. Hopefully this could help you to understand.

The CREATE FUNCTION and INSERT statements are written to the
binary log, so the slave will execute them. Because the slave SQL
thread has full privileges, it will execute the dangerous statement.
Thus, the function invocation has different effects on the master and
slave and is not replication-safe.

To guard against this danger for servers that have binary logging
enabled, stored function creators must have the SUPER privilege, in
addition to the usual CREATE ROUTINE privilege that is required.
Similarly, to use ALTER FUNCTION, you must have the SUPER
privilege in addition to the ALTER ROUTINE privilege. Without the
SUPER privilege, an error will occur:

ERROR 1419 (HY000): You do not have the SUPER privilege and
binary logging is enabled (you *might* want to use the less safe
log_bin_trust_function_creators variable)
```

If you do not want to require function creators to have the SUPER
privilege (for example, if all users with the CREATE ROUTINE
privilege on your system are experienced application developers), set
the global log_bin_trust_function_creators system variable to 1. You
can also set this variable by using the
--log-bin-trust-function-creators=1 option when starting the server.
If binary logging is not enabled, log_bin_trust_function_creators
does not apply. SUPER is not required for function creation unless,
as described previously, the DEFINER value in the function
definition requires it.

Source: https://dev.mysql.com/doc/refman/8.0/en/stored-programs-logging.html

ContentLicense: CC BY-SA 4.0

Body:
Here is some detailed explaination I had found in documentation. Hopefully this could help you to understand.

The CREATE FUNCTION and INSERT statements are written to the
binary log, so the slave will execute them. Because the slave SQL
thread has full privileges, it will execute the dangerous statement.
Thus, the function invocation has different effects on the master and
slave and is not replication-safe.

To guard against this danger for servers that have binary logging
enabled, stored function creators must have the SUPER privilege, in
addition to the usual CREATE ROUTINE privilege that is required.
Similarly, to use ALTER FUNCTION, you must have the SUPER
privilege in addition to the ALTER ROUTINE privilege. Without the
SUPER privilege, an error will occur:

ERROR 1419 (HY000): You do not have the SUPER privilege and
binary logging is enabled (you *might* want to use the less safe
log_bin_trust_function_creators variable)

If you do not want to require function creators to have the SUPER
privilege (for example, if all users with the CREATE ROUTINE
privilege on your system are experienced application developers), set
the global log_bin_trust_function_creators system variable to 1. You
can also set this variable by using the
--log-bin-trust-function-creators=1 option when starting the server.
If binary logging is not enabled, log_bin_trust_function_creators
does not apply. SUPER is not required for function creation unless,
as described previously, the DEFINER value in the function
definition requires it.

Source: https://dev.mysql.com/doc/refman/8.0/en/stored-programs-logging.html


问:
Why doesn't it match
I'm confused about the macro pattern of scheme

```<code>(define-syntax test

  (syntax-rules ()

    ((_ (head ... (x y) . tail))

     (syntax-error

      'tail

      "tail is"))

    ((_ any ...)

     (syntax-error "fallback"))))
</code>```

why (test (1 7 (2 4) 34)) dosen't match the first rule

答:
A list is a pair whose cdr is () so your input is considered like this:

(1 7 (2 4) 34 . ())
```

So the (2 4) is consumed by the head and 34 doesn't match with (x y).

Title: Why doesn't it match

Body:
I'm confused about the macro pattern of scheme

(define-syntax test

  (syntax-rules ()

    ((_ (head ... (x y) . tail))

     (syntax-error

      'tail

      "tail is"))

    ((_ any ...)

     (syntax-error "fallback"))))

why (test (1 7 (2 4) 34)) dosen't match the first rule

Body:
A list is a pair whose cdr is () so your input is considered like this:

(1 7 (2 4) 34 . ())

So the (2 4) is consumed by the head and 34 doesn't match with (x y).


问:
Httpclient cannot read json locally or on server
I am in using the HttpClient module built into angular 7 to read a JSON from a server. When using the HttpClient it always returns

ERROR TypeError: Cannot read property 'get' of undefined
      at push../src/app/info/info.component.ts.info.getVars (info.component.ts:37)
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
      at Object.onInvokeTask (core.js:17290)
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
      at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
      at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:498)
      at ZoneTask.invoke (zone.js:487)
      at timer (zone.js:2281)

I thought that this meant that the JSON couldn't be found/or was blank.

I have tried to read the JSON from the server (no success) and I have put the JSON into the assets folder to read it and I get the same error. I know that it should work in the assets folder because I can import it from the assets folder with no problem:

 import infoJson from '../../assets/info.json

This is what I have currently tried: (.component.ts)

```<code>import { HttpClient } from '@angular/common/http'

export class VehicleinfoComponent implements OnInit {
    constructor(private httpService: HttpClient ) { }

    getVars() {
        this.httpService.get('../../assets/info.json').subscribe(data => {
          console.log(data);
        })
      }
}
</code>```

I have also tried creating a service, but I get the same error: (.service.ts):

```<code>import { HttpClient } from '@angular/common/http';
import { Observable} from 'rxjs'

@Injectable({
  providedIn: 'root'
})
export class GetJsonService {

  constructor(private http: HttpClient) { }

  public getJsonInfo(): Observable<any> {
    return this.http.get('./assets/info.json')
  }
}
</code>```

.component.ts:

```<code>import { GetJsonService } from '../get-json.service'

export class VehicleinfoComponent implements OnInit {
    constructor(private GetJson: GetJsonService) { }

    getVars() {
        this.GetJson.getJsonInfo().subscribe(data => {
          console.log(data);
        })
    }
}
</code>```

The reason why I want to use HttpClient is because the JSON automatically updates with new data and I want to be able to read and display this.

Any help is appreciated.

EDIT

This is an example of the JSON I am trying to read:

```<code>{
    "playerdata": [
        {
            "USER_ID": "7a8f",
            "Status": 1,
            "Start_Time": "2016-12-21 09:41:57",
            "Finish_Time": "2016-12-21 09:43:17",
        }
    ]
}
</code>```

Also, this is my app.module.ts:

```<code>import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    //components declared
  ],
  imports: [
    HttpClientModule,
    //other imports here
  ],
  providers: [  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
this.httpService
here httpService is undefined meaning that injection did not happen.

Double check your module configuration if you have proper providers declared (and it it s working if custom made).

Propert import should look like this:

```<code>import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule, // HERE
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
</code>```

Body:
I am in using the HttpClient module built into angular 7 to read a JSON from a server. When using the HttpClient it always returns

ERROR TypeError: Cannot read property 'get' of undefined
      at push../src/app/info/info.component.ts.info.getVars (info.component.ts:37)
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
      at Object.onInvokeTask (core.js:17290)
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
      at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
      at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:498)
      at ZoneTask.invoke (zone.js:487)
      at timer (zone.js:2281)

I thought that this meant that the JSON couldn't be found/or was blank.

I have tried to read the JSON from the server (no success) and I have put the JSON into the assets folder to read it and I get the same error. I know that it should work in the assets folder because I can import it from the assets folder with no problem:

 import infoJson from '../../assets/info.json

This is what I have currently tried: (.component.ts)

import { HttpClient } from '@angular/common/http'

export class VehicleinfoComponent implements OnInit {
    constructor(private httpService: HttpClient ) { }

    getVars() {
        this.httpService.get('../../assets/info.json').subscribe(data => {
          console.log(data);
        })
      }
}

I have also tried creating a service, but I get the same error: (.service.ts):

import { HttpClient } from '@angular/common/http';
import { Observable} from 'rxjs'

@Injectable({
  providedIn: 'root'
})
export class GetJsonService {

  constructor(private http: HttpClient) { }

  public getJsonInfo(): Observable<any> {
    return this.http.get('./assets/info.json')
  }
}

.component.ts:

import { GetJsonService } from '../get-json.service'

export class VehicleinfoComponent implements OnInit {
    constructor(private GetJson: GetJsonService) { }

    getVars() {
        this.GetJson.getJsonInfo().subscribe(data => {
          console.log(data);
        })
    }
}

The reason why I want to use HttpClient is because the JSON automatically updates with new data and I want to be able to read and display this.

Any help is appreciated.

EDIT

This is an example of the JSON I am trying to read:

{
    "playerdata": [
        {
            "USER_ID": "7a8f",
            "Status": 1,
            "Start_Time": "2016-12-21 09:41:57",
            "Finish_Time": "2016-12-21 09:43:17",
        }
    ]
}

Also, this is my app.module.ts:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    //components declared
  ],
  imports: [
    HttpClientModule,
    //other imports here
  ],
  providers: [  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
this.httpService
here httpService is undefined meaning that injection did not happen.

Double check your module configuration if you have proper providers declared (and it it s working if custom made).

Propert import should look like this:

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule, // HERE
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}


问:
Subtract Col A - Col B in pandas dataframe
I have two string columns in a dataframe and I'm looking to subtract common words in B from A.

```<code>A ->  Stack Overlflow is great

B -> stack great

A-B -> overflow is
</code>```

I have tried the following code. But it only works if the column B has one word.

```<code>df['A-B'] = [' '.join(set(a.split())-set(b.split())) for a, b in zip(df['A'], df['B'])]
</code>```

Is there any change I can make so that it works when B has multiple words?

答:
Try this one liner:

```<code>' '.join(list(set(list(df.A.str.lower().str.split(' '))[0])-set(list(df.B.str.lower().str.split(' '))[0])))
</code>```

just convert both the column values into lower case and split by space and put it into a list followed by taking a set of those lists and joining them by space.

Body:
I have two string columns in a dataframe and I'm looking to subtract common words in B from A.

A ->  Stack Overlflow is great

B -> stack great

A-B -> overflow is

I have tried the following code. But it only works if the column B has one word.

df['A-B'] = [' '.join(set(a.split())-set(b.split())) for a, b in zip(df['A'], df['B'])]

Is there any change I can make so that it works when B has multiple words?

Body:
Try this one liner:

' '.join(list(set(list(df.A.str.lower().str.split(' '))[0])-set(list(df.B.str.lower().str.split(' '))[0])))

just convert both the column values into lower case and split by space and put it into a list followed by taking a set of those lists and joining them by space.


问:
How to set rootPage in IONIC 4
This is what i have now and really can't seem to find the right answer to my question i've looked everywhere so maybe someone that knows can help me?. How do i set RootPage like in ionic 3 into Ionic 4 because i tried everything and this is what is left with trying</p>

```<code>import {Component, ViewChild} from '@angular/core';
import {NavController, Platform} from '@ionic/angular';
import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';
import {Router} from '@angular/router';
import {GettingStartedPage} from './getting-started/getting-started.page';

@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
})

export class AppComponent {
@ViewChild(NavController) nav: NavController;
rootPage;

constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private NavCtrl: NavController) {
    this.initializeApp();
}

// Eindigt constructor

initializeApp() {
    this.platform.ready().then(() => {
        this.splashScreen.hide();
        // set status bar naar onze app kleur
        this.statusBar.backgroundColorByHexString('#E84B56');
    });
}

openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.rootPage.navigateRoot('/getting-started');

}
}
</code>```

答:
I hope the following helps you:</p>

```<code>constructor(private nav: NavController){}

private setRoot(){
  this.nav.navigateRoot('/getting-started');
}
</code>```

Title: How to set rootPage in IONIC 4

Body:
This is what i have now and really can't seem to find the right answer to my question i've looked everywhere so maybe someone that knows can help me?. How do i set RootPage like in ionic 3 into Ionic 4 because i tried everything and this is what is left with trying

import {Component, ViewChild} from '@angular/core';
import {NavController, Platform} from '@ionic/angular';
import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';
import {Router} from '@angular/router';
import {GettingStartedPage} from './getting-started/getting-started.page';

@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
})

export class AppComponent {
@ViewChild(NavController) nav: NavController;
rootPage;

constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private NavCtrl: NavController) {
    this.initializeApp();
}

// Eindigt constructor

initializeApp() {
    this.platform.ready().then(() => {
        this.splashScreen.hide();
        // set status bar naar onze app kleur
        this.statusBar.backgroundColorByHexString('#E84B56');
    });
}

openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.rootPage.navigateRoot('/getting-started');

}
}

Body:
I hope the following helps you:

constructor(private nav: NavController){}

private setRoot(){
  this.nav.navigateRoot('/getting-started');
}


问:
TFS 2010 Build Automation and post-build event
In the project I've inherited, the original developer used a number of post-build events in his Visual Studio projects to copy around DLL's and stuff when building inside VS.

This is causing some grief now that I'm trying to move these things to the TFS 2010 Build system.

I was hoping to be able to create a new "Continuous" project configuration, and exclude those post-build events from Visual Studio in that configuration - but it seems those calls aren't configurable based on your project configuration....

Any ideas? Is there something I could check for to know I'm running under TFS Build and then just skip those CMD files? Any ideas would be most welcome!

答:
I use a similar approach to do this.  I add the following to each project's post-build steps:

```<code>if '$(TeamBuild)'=='True' exit 0
</code>```

Then when configuring the Build Definition I simply add:

```<code>/p:TeamBuild=True
</code>```

...to the MSBuild Arguments.

This gives me the flexibility to keep all the configuration in the projects and the build definition.

Body:
I use a similar approach to do this.  I add the following to each project's post-build steps:

if '$(TeamBuild)'=='True' exit 0

Then when configuring the Build Definition I simply add:

/p:TeamBuild=True

...to the MSBuild Arguments.

This gives me the flexibility to keep all the configuration in the projects and the build definition.

ContentLicense: CC BY-SA 3.0


问:
Grep using a regular expression and capturing using groups
I have multiple text files containing lines as below:
"""Version       : 3.4.0.0
xxx
xxx
xxx"""
I'm trying to capture 3.4.0.0 from each text file and display on the terminal.
the command i've written is this :

```<code>grep -m1 'Version[\s\S]*?(\d[\s\S]+?)\n' *.txt

grep -m1 'Version[\s\S]*?(\d[\s\S]+?)\n' *.txt
</code>```

I'm unable to get any results using the above code. Can someone assist me on this?

答:
Your pattern is a PCRE compliant regex, [\s\S] matches any char in a PCRE pattern, but not with POSIX BRE regex flavor that you are using with your grep since you did not use-P option.

If you want to do it with GNU grep use

```<code>grep  -oPm 1 'Version\s*:\s*\K\d+(?:\.\d+)+' *.txt
</code>```

See this online demo

Details

Version - Version string

\s*:\s* - a colon enclosed with 0+ whitespaces

\K - match reset operator

\d+ - 1+ digits and then

(?:\.\d+)+ - 1 or more repetitions of . and 1+ digits.

You may do that with awk:

```<code>awk '/^Version : [0-9]+/{print $3; exit}' *.txt
</code>```

See the online awk demo:

```<code>s="Text
Version : 3.4.0.0 xxx xxx xxx
More text
Version : 5.6.0.0 xxx xxx xxx"
awk '/^Version : [0-9]+/{print $3; exit}' <<< "$s"
# => 3.4.0.0
</code>```

Details

^Version : [0-9]+ finds a line that starts with Version : <1 or more digits>

{print $3; exit} outputs the value of Field 3 and stops processing getting you just the first match.

Body:
I have multiple text files containing lines as below:
"""Version       : 3.4.0.0
xxx
xxx
xxx"""
I'm trying to capture 3.4.0.0 from each text file and display on the terminal.
the command i've written is this :

grep -m1 'Version[\s\S]*?(\d[\s\S]+?)\n' *.txt

grep -m1 'Version[\s\S]*?(\d[\s\S]+?)\n' *.txt

I'm unable to get any results using the above code. Can someone assist me on this?

Body:
Your pattern is a PCRE compliant regex, [\s\S] matches any char in a PCRE pattern, but not with POSIX BRE regex flavor that you are using with your grep since you did not use-P option.

If you want to do it with GNU grep use

grep  -oPm 1 'Version\s*:\s*\K\d+(?:\.\d+)+' *.txt

See this online demo

Details

Version - Version string

\s*:\s* - a colon enclosed with 0+ whitespaces

\K - match reset operator

\d+ - 1+ digits and then

(?:\.\d+)+ - 1 or more repetitions of . and 1+ digits.

You may do that with awk:

awk '/^Version : [0-9]+/{print $3; exit}' *.txt

See the online awk demo:

s="Text
Version : 3.4.0.0 xxx xxx xxx
More text
Version : 5.6.0.0 xxx xxx xxx"
awk '/^Version : [0-9]+/{print $3; exit}' <<< "$s"
# => 3.4.0.0

Details

^Version : [0-9]+ finds a line that starts with Version : <1 or more digits>

{print $3; exit} outputs the value of Field 3 and stops processing getting you just the first match.


问:
How do I change file name that contains a date automatically in python
I am trying to copy data from one excel file to another automatically using python, currently i have to manually update the date in the excel file name every morning. Is there a way to automatically update the date in the excel file name. I am very new to any form of programming, trying to learn to keep my job.

I have tried to use the time date function and declare this as a variable and copy this into code but no luck

```<code>import datetime

Filedate= (datetime.date.today()-datetime.timedelta(1))

exceldate= Filedate.strftime("%Y",)+Filedate.strftime("%m",)+Filedate.strftime("%d",)

import pyexcel as p

p.save_book_as(file_name="Q:\Valuations\Currency Options\YieldX Daily Statsexceldate.xls",#CHANGE DATE #manual entry.
               dest_file_name='YieldX Daily Stats20190522.xlsx')#CHANGE DATE manual entry
</code>```

答:
My approach is to split filename into part that contains date and the rest, then replace date with current one.</p>

```<code>import os
import datetime
import re

# get xls files
xls_files = [file for file in os.listdir(os.getcwd()) if file.endswith('.xls')]

# get current date
now = datetime.datetime.now()

# change names
for item in xls_files:
    # split name and date part
    name_parts = item.split('.')
    get_date = re.findall('\d+-\d+-\d+', name_parts[0])
    name_string_part = name_parts[0].replace(get_date[0], '')
    # create new name
    new_name = name_string_part + str(now.day) + '-' + str(now.month) + '-' + str(now.year) + '_' + '.xls'
    # rename file
    os.rename(item, new_name)
</code>```

Body:
I am trying to copy data from one excel file to another automatically using python, currently i have to manually update the date in the excel file name every morning. Is there a way to automatically update the date in the excel file name. I am very new to any form of programming, trying to learn to keep my job.

I have tried to use the time date function and declare this as a variable and copy this into code but no luck

import datetime

Filedate= (datetime.date.today()-datetime.timedelta(1))

exceldate= Filedate.strftime("%Y",)+Filedate.strftime("%m",)+Filedate.strftime("%d",)

import pyexcel as p

p.save_book_as(file_name="Q:\Valuations\Currency Options\YieldX Daily Statsexceldate.xls",#CHANGE DATE #manual entry.
               dest_file_name='YieldX Daily Stats20190522.xlsx')#CHANGE DATE manual entry

Body:
My approach is to split filename into part that contains date and the rest, then replace date with current one.

import os
import datetime
import re

# get xls files
xls_files = [file for file in os.listdir(os.getcwd()) if file.endswith('.xls')]

# get current date
now = datetime.datetime.now()

# change names
for item in xls_files:
    # split name and date part
    name_parts = item.split('.')
    get_date = re.findall('\d+-\d+-\d+', name_parts[0])
    name_string_part = name_parts[0].replace(get_date[0], '')
    # create new name
    new_name = name_string_part + str(now.day) + '-' + str(now.month) + '-' + str(now.year) + '_' + '.xls'
    # rename file
    os.rename(item, new_name)


问:
How can I define overloaded operators with operands whose type definitions I do not control in F#?
I have 3 types, A, B, and C in F#. Two of the types, A and B I do not have the ability to modify code for. Type C is a type that I control.

I with to write overloaded operators such as -

```<code>type C () =
    static member (><) (alpha : A) (beta : B) : C = zeta alpha beta
    static member (><) (beta : B) (alpha : A) : C = omega alpha beta
</code>```

When I attempt to invoke the operator, the compile issues the following error -

Error  FS0043  None of the types 'A, B' support the operator '><'

How can I workaround the issue such that I can define overloaded operators with operands whose type definitions I do not control? The only type whose definition I do control is the result type, C!

答:
Since C doesn't appear in the input parameters it won't work, at least as long as type extensions are not taken into account in overload resolution with trait calls.

So you'll have to include C and define the operator at global level:

```<code>type A = A
type B = B

type C () = class end

let zeta  _ _ = C ()
let omega _ _ = C ()

type C with
    static member (><) (_:C, alpha : A) = fun (beta  : B) -> zeta alpha beta : C
    static member (><) (_:C, beta  : B) = fun (alpha : A) -> omega alpha beta: C

let inline (><) x y = (Unchecked.defaultof<C> >< x) y

// Test
let x = A >< B
// val x : C
</code>```

Note: you can use a different operator name internally if you want

Body:
I have 3 types, A, B, and C in F#. Two of the types, A and B I do not have the ability to modify code for. Type C is a type that I control.

I with to write overloaded operators such as -

type C () =
    static member (><) (alpha : A) (beta : B) : C = zeta alpha beta
    static member (><) (beta : B) (alpha : A) : C = omega alpha beta

When I attempt to invoke the operator, the compile issues the following error -

Error  FS0043  None of the types 'A, B' support the operator '><'

How can I workaround the issue such that I can define overloaded operators with operands whose type definitions I do not control? The only type whose definition I do control is the result type, C!

Body:
Since C doesn't appear in the input parameters it won't work, at least as long as type extensions are not taken into account in overload resolution with trait calls.

So you'll have to include C and define the operator at global level:

type A = A
type B = B

type C () = class end

let zeta  _ _ = C ()
let omega _ _ = C ()

type C with
    static member (><) (_:C, alpha : A) = fun (beta  : B) -> zeta alpha beta : C
    static member (><) (_:C, beta  : B) = fun (alpha : A) -> omega alpha beta: C

let inline (><) x y = (Unchecked.defaultof<C> >< x) y

// Test
let x = A >< B
// val x : C

Note: you can use a different operator name internally if you want


问:
How get trainable variable count when using Tf Estimator?
I created a CNN classifier model using the tf estimator framework. However, I could not access variables defined in the model. tf.trainable_variables() always return 0.
  How can i access variables using tf estimator? In particular, how can i get a count of the total number of parameters (adding up the dimensions of all variables.

Thanks,
Harold

答:
You can use get_variable_names() to get all variable names,
and use get_variable_value(name) to get the variable value by name.

Please use your code like:

```<code>estimator = tf.estimator.Estimator(...)
params = estimator.get_variable_names()
for p in params:
    print(p, estimator.get_variable_value(p).shape)
</code>```

The more information is https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#get_variable_names
and
https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#get_variable_value.

Note: you must create the graph first and then will get the variables.

Body:
You can use get_variable_names() to get all variable names,
and use get_variable_value(name) to get the variable value by name.

Please use your code like:

estimator = tf.estimator.Estimator(...)
params = estimator.get_variable_names()
for p in params:
    print(p, estimator.get_variable_value(p).shape)

The more information is https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#get_variable_names
and
https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#get_variable_value.

Note: you must create the graph first and then will get the variables.


问:
Can intermediate layers be accessed directly within keras loss function?
I am curious whether a loss function can implement intermediate layer outputs within keras, without designing the model to feed the intermediate layers as outputs. I have seen a solution can be to redesign the architecture to return the intermediate layer in addition to the final prediction and use that as a workaround, but I'm unclear whether a layer output can be accessed directly from a loss function </p>

答:
I'm unclear whether a layer output can be accessed directly from a loss function

It certainly can.

By way of an example, consider this model using the functional API:

inp = keras.layers.Input(shape=(28, 28))
flat = keras.layers.Flatten()(inp)
dense = keras.layers.Dense(128, activation=tf.nn.relu)(flat)
out = keras.layers.Dense(10, activation=tf.nn.softmax)(dense)

model = keras.models.Model(inputs=inp, outputs=out )
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
```

<p>If, say, we wanted to introduce a new loss function that also penalised the largest weight of the outputs of our <code>dense</code> layer then we could write a custom loss function something like this:</p>

<pre class="lang-py prettyprint-override"><code>def my_funky_loss_fn(y_true, y_pred):
  return (keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
        + keras.backend.max(dense))
</code>```

which we can use in our model just by passing our new loss function to the compile() method:

model.compile(optimizer='adam',
              loss=my_funky_loss_fn,
              metrics=['accuracy'])
```

Body:
I'm unclear whether a layer output can be accessed directly from a loss function

It certainly can.

By way of an example, consider this model using the functional API:

inp = keras.layers.Input(shape=(28, 28))
flat = keras.layers.Flatten()(inp)
dense = keras.layers.Dense(128, activation=tf.nn.relu)(flat)
out = keras.layers.Dense(10, activation=tf.nn.softmax)(dense)

model = keras.models.Model(inputs=inp, outputs=out )
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

If, say, we wanted to introduce a new loss function that also penalised the largest weight of the outputs of our dense layer then we could write a custom loss function something like this:

def my_funky_loss_fn(y_true, y_pred):
  return (keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
        + keras.backend.max(dense))

which we can use in our model just by passing our new loss function to the compile() method:

model.compile(optimizer='adam',
              loss=my_funky_loss_fn,
              metrics=['accuracy'])


问:
Show Action Menu in Xamarin Forms Application

In my application, there is a button Action on right bottom corner of my screen and on click of that, something like in the image should appear. I am not sure how to get this, looks something similar to context menu in android. Need Help!

答:
As comment mentioned there, you can use Rg.Plugins.Popup to achieve your requirement. I write some simple code and you can have a look at:

Action menu page, it inherits PopupPage, I use a listView to show the choices and you can custom the viewCell to add image on the right side. Also handle the click event in the ListView_ItemSelected:

```<code>public partial class Page1 : PopupPage
{
    public Page1 ()
    {
        InitializeComponent ();

        listView.ItemsSource = new List<string>
        {
            "first",
            "second",
            "third",
            "fourth",
            "fifth",
        };
    }

    private async void OnClose(object sender, EventArgs e)
    {
        await PopupNavigation.Instance.PopAsync();
    }

    private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        //
        var index = (listView.ItemsSource as List<string>).IndexOf(e.SelectedItem as string);

        Console.WriteLine(index);
    }
}
</code>```

And in the Xaml:

```<code><StackLayout VerticalOptions="End" HorizontalOptions="FillAndExpand" Padding="20, 20, 20, 20" >
    <Frame CornerRadius="25" Padding="0" Margin="0,0,0,0" BorderColor="Red" HasShadow="False" IsClippedToBounds="True">
        <StackLayout BackgroundColor="White" VerticalOptions="End" >

            <ListView x:Name="listView" HeightRequest="250" RowHeight="50" ItemSelected="ListView_ItemSelected">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell TextColor="Black" Text="{Binding .}"></TextCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </StackLayout>
    </Frame>

    <Frame CornerRadius="25"  Padding="0" BackgroundColor="White" IsClippedToBounds="True">
        <StackLayout BackgroundColor="White" VerticalOptions="End" HeightRequest="50">

            <Button Text="Close" TextColor="#A9D1DE" Clicked="OnClose"></Button>

        </StackLayout>
    </Frame>

</StackLayout>
</code>```

To use this page:

```<code>   await PopupNavigation.Instance.PushAsync(new Page1());
</code>```

You should modify the details to meet you requirement. Such as custom the viewCell, disable the scroll ability of ListView and etc.

Here is what it looks like in iOS:

Body:
As comment mentioned there, you can use Rg.Plugins.Popup to achieve your requirement. I write some simple code and you can have a look at:

Action menu page, it inherits PopupPage, I use a listView to show the choices and you can custom the viewCell to add image on the right side. Also handle the click event in the ListView_ItemSelected:

public partial class Page1 : PopupPage
{
    public Page1 ()
    {
        InitializeComponent ();

        listView.ItemsSource = new List<string>
        {
            "first",
            "second",
            "third",
            "fourth",
            "fifth",
        };
    }

    private async void OnClose(object sender, EventArgs e)
    {
        await PopupNavigation.Instance.PopAsync();
    }

    private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        //
        var index = (listView.ItemsSource as List<string>).IndexOf(e.SelectedItem as string);

        Console.WriteLine(index);
    }
}

And in the Xaml:

<StackLayout VerticalOptions="End" HorizontalOptions="FillAndExpand" Padding="20, 20, 20, 20" >
    <Frame CornerRadius="25" Padding="0" Margin="0,0,0,0" BorderColor="Red" HasShadow="False" IsClippedToBounds="True">
        <StackLayout BackgroundColor="White" VerticalOptions="End" >

            <ListView x:Name="listView" HeightRequest="250" RowHeight="50" ItemSelected="ListView_ItemSelected">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell TextColor="Black" Text="{Binding .}"></TextCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </StackLayout>
    </Frame>

    <Frame CornerRadius="25"  Padding="0" BackgroundColor="White" IsClippedToBounds="True">
        <StackLayout BackgroundColor="White" VerticalOptions="End" HeightRequest="50">

            <Button Text="Close" TextColor="#A9D1DE" Clicked="OnClose"></Button>

        </StackLayout>
    </Frame>

</StackLayout>

To use this page:

   await PopupNavigation.Instance.PushAsync(new Page1());

You should modify the details to meet you requirement. Such as custom the viewCell, disable the scroll ability of ListView and etc.

Here is what it looks like in iOS:


问:
Rollup [!] Error: Unexpected token for antd lib
I am creating npm package for antd and redux-form wrapper. i use RollUp for jsx compilation. i installed antd lib for dependency. when i run script it will show following error.

```<code>> rollup -c

src/index.tsx → dist/index.js, dist/index.es.js...
[!] Error: Unexpected token
node_modules/antd/package.json (2:9)
1: {
2:   "_from": "antd@3.19.1",
            ^
3:   "_id": "antd@3.19.1",
4:   "_inBundle": false,
</code>```

my rollup.config.js

```<code>import typescript from 'rollup-plugin-typescript2'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
// import postcss from 'rollup-plugin-postcss-modules'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import url from 'rollup-plugin-url'
import svgr from '@svgr/rollup'
import globals from "rollup-plugin-node-globals";
import builtins from "rollup-plugin-node-builtins";
import json from "rollup-plugin-json";
import pkg from './package.json'

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      exports: 'named',
      sourcemap: true
    },
    {
      file: pkg.module,
      format: 'es',
      exports: 'named',
      sourcemap: true
    }
  ],
  plugins: [
    external(),
    postcss({
      modules: true
    }),
    url(),
    svgr(),
    resolve({preferBuiltins: false}),
    typescript({
      rollupCommonJSResolveHack: true,
      clean: true
    }),
    commonjs(),
    globals(),
    builtins(),
    json()
  ]
}

</code>```

my package.json

```<code>{
  "name": "a8formelements",
  "version": "1.0.1",
  "description": "sample",
  "author": "",
  "license": "MIT",
  "repository": "/formelements",
  "main": "dist/index.js",
  "module": "dist/index.es.js",
  "jsnext:main": "dist/index.es.js",
  "engines": {
    "node": ">=8",
    "npm": ">=5"
  },
  "scripts": {
    "test": "cross-env CI=1 react-scripts-ts test --env=jsdom",
    "test:watch": "react-scripts-ts test --env=jsdom",
    "build": "rollup -c",
    "start": "rollup -c -w",
    "prepare": "npm run build",
    "predeploy": "cd example && npm install && npm ru  n build",
    "deploy": "gh-pages -d example/build"
  },
  "dependencies": {
    "antd": "3.19.1",
    "classnames": "^2.2.6",
    "moment": "^2.24.0",
    "uuid": "^3.3.2",
    "validate.js": "^0.12.0"
  },
  "peerDependencies": {
    "prop-types": "^15.5.4",
    "react": "^15.0.0 || ^16.0.0",
    "react-dom": "^15.0.0 || ^16.0.0"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.7",
    "@types/uuid": "^3.4.4",
    "@svgr/rollup": "^2.4.1",
    "@types/jest": "^23.1.5",
    "@types/node": "^11.13.5",
    "@types/react": "^16.8.13",
    "@types/react-dom": "^16.0.5",
    "@types/redux-form": "^8.1.1",
    "babel-core": "^6.26.3",
    "babel-runtime": "^6.26.0",
    "cross-env": "^5.1.4",
    "gh-pages": "^1.2.0",
    "react": "^16.4.1",
    "rollup-plugin-json": "^4.0.0",
    "react-dom": "^16.4.1",
    "react-scripts-ts": "^2.16.0",
    "rollup": "^0.62.0",
    "rollup-plugin-babel": "^3.0.7",
    "rollup-plugin-commonjs": "^9.1.3",
    "rollup-plugin-node-builtins": "^2.1.2",
    "rollup-plugin-node-globals": "^1.4.0",
    "rollup-plugin-node-resolve": "^3.4.0",
    "rollup-plugin-peer-deps-external": "^2.2.0",
    "rollup-plugin-postcss": "^1.6.2",
    "rollup-plugin-typescript2": "^0.20.1",
    "rollup-plugin-url": "^1.4.0",
    "typescript": "^2.8.3"
  },
  "files": [
    "dist"
  ]
}

</code>```

I updated my rollup.config.js with rollup-plugin-json integration. when i add this config i got another error like below :

```<code>node_modules/rc-editor-mention/es/index.js (2:9)
1: // export this package's api
2: import { ContentState } from 'draft-js';
            ^
3: import Mention from './component/Mention.react';
4: import toString from './utils/exportContent';
</code>```

答:
You can find an interresting discussion here.
It's suggested that you should use rollup-plugin-json.

Is somehow weird, but axios node adapter requires its own package.json
  which rollup doesn't understand by default.

To make rollup understand json files, just use rollup-plugin-json.
  I've just tried and it's working fine.

Someone has the same issue as yours but with axios and I think it's the same concept.

You can try it out.

Body:
I am creating npm package for antd and redux-form wrapper. i use RollUp for jsx compilation. i installed antd lib for dependency. when i run script it will show following error.

> rollup -c

src/index.tsx → dist/index.js, dist/index.es.js...
[!] Error: Unexpected token
node_modules/antd/package.json (2:9)
1: {
2:   "_from": "antd@3.19.1",
            ^
3:   "_id": "antd@3.19.1",
4:   "_inBundle": false,

my rollup.config.js

import typescript from 'rollup-plugin-typescript2'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
// import postcss from 'rollup-plugin-postcss-modules'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import url from 'rollup-plugin-url'
import svgr from '@svgr/rollup'
import globals from "rollup-plugin-node-globals";
import builtins from "rollup-plugin-node-builtins";
import json from "rollup-plugin-json";
import pkg from './package.json'

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      exports: 'named',
      sourcemap: true
    },
    {
      file: pkg.module,
      format: 'es',
      exports: 'named',
      sourcemap: true
    }
  ],
  plugins: [
    external(),
    postcss({
      modules: true
    }),
    url(),
    svgr(),
    resolve({preferBuiltins: false}),
    typescript({
      rollupCommonJSResolveHack: true,
      clean: true
    }),
    commonjs(),
    globals(),
    builtins(),
    json()
  ]
}

my package.json

{
  "name": "a8formelements",
  "version": "1.0.1",
  "description": "sample",
  "author": "",
  "license": "MIT",
  "repository": "/formelements",
  "main": "dist/index.js",
  "module": "dist/index.es.js",
  "jsnext:main": "dist/index.es.js",
  "engines": {
    "node": ">=8",
    "npm": ">=5"
  },
  "scripts": {
    "test": "cross-env CI=1 react-scripts-ts test --env=jsdom",
    "test:watch": "react-scripts-ts test --env=jsdom",
    "build": "rollup -c",
    "start": "rollup -c -w",
    "prepare": "npm run build",
    "predeploy": "cd example && npm install && npm ru  n build",
    "deploy": "gh-pages -d example/build"
  },
  "dependencies": {
    "antd": "3.19.1",
    "classnames": "^2.2.6",
    "moment": "^2.24.0",
    "uuid": "^3.3.2",
    "validate.js": "^0.12.0"
  },
  "peerDependencies": {
    "prop-types": "^15.5.4",
    "react": "^15.0.0 || ^16.0.0",
    "react-dom": "^15.0.0 || ^16.0.0"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.7",
    "@types/uuid": "^3.4.4",
    "@svgr/rollup": "^2.4.1",
    "@types/jest": "^23.1.5",
    "@types/node": "^11.13.5",
    "@types/react": "^16.8.13",
    "@types/react-dom": "^16.0.5",
    "@types/redux-form": "^8.1.1",
    "babel-core": "^6.26.3",
    "babel-runtime": "^6.26.0",
    "cross-env": "^5.1.4",
    "gh-pages": "^1.2.0",
    "react": "^16.4.1",
    "rollup-plugin-json": "^4.0.0",
    "react-dom": "^16.4.1",
    "react-scripts-ts": "^2.16.0",
    "rollup": "^0.62.0",
    "rollup-plugin-babel": "^3.0.7",
    "rollup-plugin-commonjs": "^9.1.3",
    "rollup-plugin-node-builtins": "^2.1.2",
    "rollup-plugin-node-globals": "^1.4.0",
    "rollup-plugin-node-resolve": "^3.4.0",
    "rollup-plugin-peer-deps-external": "^2.2.0",
    "rollup-plugin-postcss": "^1.6.2",
    "rollup-plugin-typescript2": "^0.20.1",
    "rollup-plugin-url": "^1.4.0",
    "typescript": "^2.8.3"
  },
  "files": [
    "dist"
  ]
}

I updated my rollup.config.js with rollup-plugin-json integration. when i add this config i got another error like below :

node_modules/rc-editor-mention/es/index.js (2:9)
1: // export this package's api
2: import { ContentState } from 'draft-js';
            ^
3: import Mention from './component/Mention.react';
4: import toString from './utils/exportContent';


问:
Why do I receive a UnsupportedMediaType message when trying to analyze a form?
I am using the forms recognizer preview.  I have already trained a model using the documentation provided in this documentation.

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/curl-train-extract

However when I attempt to execute the curl command to analyze the request; I get an error message indicating:

{"error":{"code":"UnsupportedMediaType","message":"In case of HTML form data, the multipart request must contain a document with a media type of - 'application/pdf', 'image/jpeg' or 'image/png'."}

The file I am uploading is a PDF (I've verified the response headers).  I have also indicated this in the curl request as:

curl -X POST "https://[omitted]/formrecognizer/v1.0-preview/custom/models/[omitted]/analyze" -H "Content-Type: multipart/form-data" -F "form=[omitted];type=application/pdf" -H "Ocp-Apim-Subscription-Key: [omitted]"

答: Could you please share your PDF document, The issue may be with the PDF document containing different media types.</p>


问:
struggling in understanding terms in the Delegate world
I'm new to C#, I'm very confused with the terms used like 'listener', 'caller', 'callback', 'EventHandler', let's say we have the following code below:

```<code>public class Car
{
    public delegate void CarEngineHandler();
    public CarEngineHandler listOfHandlers;
    public void Accelerate(int delta)
    {
       if (delta > 80)
          listOfHandlers();    // not checking null for simplicity
    }
}

class Program
{
    static void Main(string[] args)
    {
         Car myCar = new Car();
         myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded);
         myCar.Accelerate(120);
    }

    static void CallWhenExploded()
    {
       Console.WriteLine("Sorry, this car is dead...");
    }
}

</code>```

so in this scenario:

Who is the caller?

Who is the listener? listen to what?

Who is the callback?

Who is the EventHandler?

and my answer is:

The caller is myCar

not sure

The callback is CallWhenExploded() static function

EventHandler is listOfHandlers

am I correct? I really don't know who is the listener and listen to what.

答:
You should be able to answer those questions when you understand 'broadcaster/subscriber' pattern used by delegates. 'broadcaster' holds the delegate instance and decides when to call target methods in its 'invocation list'. These target methods are the 'subscribers' and they can decide when to stop or start 'listening' by calling '-=' or '+=' on broadcaster's delegate field. </p>

```<code>public class Car
{
    // This is the 'delegate type'
    // ‘Delegate type’ is what is responsible for defining the method such as its signature
    // which include return type and parameters
    // In this ‘Delegate type’ named:'CarEngineHandler', the return type is 'void' and there are no parameters
    public delegate void CarEngineHandler();

    //this is the ‘Delegate instance’
    //‘Delegate instance’ is responsible for holding the reference to the actual methods
    //that adheres to the delegate type.
    //Delegate instance can be used to then ‘invoke’ that method whenever needed.
    public CarEngineHandler listOfHandlers;

    public void Accelerate(int delta)
    {
       if (delta > 80)
            //this is where you use the 'Delegate instance' to ‘invoke’ the methods
            // You can also you use: listOfHandlers.Invoke();
            // which is same as calling 'listOfHandlers();'
            // When delegate instance is invoked, all its actions in its invocation list are executed in order
            //In this example it will first dispaly: "Sorry, this car is dead..."
            // then display: "Calling, emergency..."
          listOfHandlers();    // not checking null for simplicity
    }
}

class Program
{
    static void Main(string[] args)
    {
            Car myCar = new Car();
            //This is where you add to the 'delegate instance', the 'target method's' that matches delegate signature
            //A 'delegate instance' can contain more than one action. This list of actions is called the “invocation list”.
            //You can also add multiple methods to invocation list like this: myCar.listOfHandlers += CallWhenExploded;
            myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded);
            // For example you can add another target method like this:
            myCar.listOfHandlers += CallEmergencyService;

            // you get details about the 'target methods' attached to the “invocation list” like this:
            var listOfTargets = myCar.listOfHandlers.GetInvocationList();
            Console.WriteLine(listOfTargets[0].Method.Name);

            myCar.Accelerate(120);
    }

    static void CallWhenExploded()
    {
       Console.WriteLine("Sorry, this car is dead...");
    }
    static void CallEmergencyService()
    {
       Console.WriteLine("Calling, emergency...");
    }
}
</code>```

Body:
I'm new to C#, I'm very confused with the terms used like 'listener', 'caller', 'callback', 'EventHandler', let's say we have the following code below:

public class Car
{
    public delegate void CarEngineHandler();
    public CarEngineHandler listOfHandlers;
    public void Accelerate(int delta)
    {
       if (delta > 80)
          listOfHandlers();    // not checking null for simplicity
    }
}

class Program
{
    static void Main(string[] args)
    {
         Car myCar = new Car();
         myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded);
         myCar.Accelerate(120);
    }

    static void CallWhenExploded()
    {
       Console.WriteLine("Sorry, this car is dead...");
    }
}

so in this scenario:

Who is the caller?

Who is the listener? listen to what?

Who is the callback?

Who is the EventHandler?

and my answer is:

The caller is myCar

not sure

The callback is CallWhenExploded() static function

EventHandler is listOfHandlers

am I correct? I really don't know who is the listener and listen to what.

Body:
You should be able to answer those questions when you understand 'broadcaster/subscriber' pattern used by delegates. 'broadcaster' holds the delegate instance and decides when to call target methods in its 'invocation list'. These target methods are the 'subscribers' and they can decide when to stop or start 'listening' by calling '-=' or '+=' on broadcaster's delegate field.

public class Car
{
    // This is the 'delegate type'
    // ‘Delegate type’ is what is responsible for defining the method such as its signature
    // which include return type and parameters
    // In this ‘Delegate type’ named:'CarEngineHandler', the return type is 'void' and there are no parameters
    public delegate void CarEngineHandler();

    //this is the ‘Delegate instance’
    //‘Delegate instance’ is responsible for holding the reference to the actual methods
    //that adheres to the delegate type.
    //Delegate instance can be used to then ‘invoke’ that method whenever needed.
    public CarEngineHandler listOfHandlers;

    public void Accelerate(int delta)
    {
       if (delta > 80)
            //this is where you use the 'Delegate instance' to ‘invoke’ the methods
            // You can also you use: listOfHandlers.Invoke();
            // which is same as calling 'listOfHandlers();'
            // When delegate instance is invoked, all its actions in its invocation list are executed in order
            //In this example it will first dispaly: "Sorry, this car is dead..."
            // then display: "Calling, emergency..."
          listOfHandlers();    // not checking null for simplicity
    }
}

class Program
{
    static void Main(string[] args)
    {
            Car myCar = new Car();
            //This is where you add to the 'delegate instance', the 'target method's' that matches delegate signature
            //A 'delegate instance' can contain more than one action. This list of actions is called the “invocation list”.
            //You can also add multiple methods to invocation list like this: myCar.listOfHandlers += CallWhenExploded;
            myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded);
            // For example you can add another target method like this:
            myCar.listOfHandlers += CallEmergencyService;

            // you get details about the 'target methods' attached to the “invocation list” like this:
            var listOfTargets = myCar.listOfHandlers.GetInvocationList();
            Console.WriteLine(listOfTargets[0].Method.Name);

            myCar.Accelerate(120);
    }

    static void CallWhenExploded()
    {
       Console.WriteLine("Sorry, this car is dead...");
    }
    static void CallEmergencyService()
    {
       Console.WriteLine("Calling, emergency...");
    }
}


问:
Delete specific or selected property from json data .I do not want to delete all key value pairs just those with Category :null
This is my json data and i wanted to remove the category with null value from my json.

I mean not to delete the "Category":"start" but delete "Category":null.

I have seen some answers regarding this but it deletes all the category including "Category":"start" which I do not want.

"First": [{
        "category": "Start",
        "name": "Start",
        "key": 1,
        "lastname": "xyz"
    }, {
        "category": null,
        "text": "Step",
        "key": 2,
        "lastname": "xyz"
    }, {
        "category": null,
        "text": "Condition",
        "key": 3,
        "loc": "xyz"
    }
```

答:
See the code below. This will give you the output you expect.</p>

```<code>const array = [{
  "category": "Start",
  "name": "Start",
  "key": 1,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Step",
  "key": 2,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Condition",
  "key": 3,
  "loc": "xyz"
}];

const list = array.map(item => {
  let object = item;
  [undefined, null].includes(object.category) && delete object.category;
  return object;
});

console.log(list);
</code>```

Body:
See the code below. This will give you the output you expect.

const array = [{
  "category": "Start",
  "name": "Start",
  "key": 1,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Step",
  "key": 2,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Condition",
  "key": 3,
  "loc": "xyz"
}];

const list = array.map(item => {
  let object = item;
  [undefined, null].includes(object.category) && delete object.category;
  return object;
});

console.log(list);


问:
Android: Text not visible on writing using drawText()
```<code>          @Override
          protected void onDraw(Canvas canvas)
          {
            //Note:I do not  want to use the canvas object from this function param
            //If i do so its working , But i would like to understand why the following is not working

         Canvas c =new Canvas();
             Paint paint = new Paint();
             paint.setStyle(Paint.Style.FILL);
             paint.setAntiAlias(true);
             paint.setColor(Color.WHITE);
             c.drawText("HELLO CANVAS",200,300,paint);
        }
</code>```

MORE CODE

```<code>public class graphicProj extends Activity {

   private Canvas canvas;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    {
        ....

        SimpleView simpleview_obj = new SimpleView(this);
        setContentView(simpleview_obj);
        simpleview_obj.onDraw(canvas);
         .....

     new GetData().execute();

     }
    private static class SimpleView extends View {
        private ShapeDrawable mDrawable = new ShapeDrawable();
....
    protected void onDraw(Canvas canvas) {

    //draw graphic objects
    ....
        }
     }

    public class GetData extends AsyncTask<Void, String, Void> {

         @Override
        protected void onPreExecute() {
             Log.d("PROJ","STARTIN");
        }

        @Override
        protected Void doInBackground(Void... unused) {
        ////My calculation and reading frm DataStream

         }

        @Override
        protected void onProgressUpdate(String... data) {

           //I Keep updating the result...
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);
            paint.setColor(Color.WHITE);
            canvas.drawText(result, 200, 300, paint);

        }

        @Override
        protected void onPostExecute(Void unused) {
             Log.d("PROJ","END");
        }
    }

}
</code>```

答:
Not here or in your other question have you provided enough information on why you can't do that. There is no reason to draw on a new canvas instead of the already existing one.

The code is not working because your new Canvas c isn't assigned to anything. Its like creating a String myString for a log but never using Log.d(tag, myString)

edit (after reading all the comments)

If you calculate a value in your onCreate() and want to display that value in your onDraw(), that simply do that. Store the result in a member variable and you can access it in the onDraw().

Otherwise: Please provide your complete code. I guess you just do it way more complex than it should be...

edit2

Your code is a bit messy and does a lot of stuff in areas where you shouldn't do it. So drawing inside the onProgressUpdate() is seriously wrong. You should encapsulate your calculation and drawing.

What you should do (I recommend using SurfaceView instead of View, anyway...):

You should start your AsynchTask which updates the string you want to draw. The string should be a variable inside your View, where you use it for drawing.
The drawing itself should be called by a drawing thread (I remember: use the SurfaceView instead of the View as a parent class). Inside that onDraw() you should just use your paint object, the given canvas and the string you want to draw (don't forget to make the paint variable also a member variable to prevent recreating the same object over and over again for performance/memory reasons).

If you do not know how to work with a SurfaceView or if you want to learn how you could work with a drawing thread please read my tutorial about 2d drawing: www.droidnova.com/2d-tutorial-series

A short last sentence: You did a lot of things in the right way, you just mixed up with the places where you do it. You should try to rethink what you really want to achieve and how it could be done the easiest way. Maybe my tutorial helps to clear your mind a bit.

Body:
          @Override
          protected void onDraw(Canvas canvas)
          {
            //Note:I do not  want to use the canvas object from this function param
            //If i do so its working , But i would like to understand why the following is not working

         Canvas c =new Canvas();
             Paint paint = new Paint();
             paint.setStyle(Paint.Style.FILL);
             paint.setAntiAlias(true);
             paint.setColor(Color.WHITE);
             c.drawText("HELLO CANVAS",200,300,paint);
        }

MORE CODE

public class graphicProj extends Activity {

   private Canvas canvas;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    {
        ....

        SimpleView simpleview_obj = new SimpleView(this);
        setContentView(simpleview_obj);
        simpleview_obj.onDraw(canvas);
         .....

     new GetData().execute();

     }
    private static class SimpleView extends View {
        private ShapeDrawable mDrawable = new ShapeDrawable();
....
    protected void onDraw(Canvas canvas) {

    //draw graphic objects
    ....
        }
     }

    public class GetData extends AsyncTask<Void, String, Void> {

         @Override
        protected void onPreExecute() {
             Log.d("PROJ","STARTIN");
        }

        @Override
        protected Void doInBackground(Void... unused) {
        ////My calculation and reading frm DataStream

         }

        @Override
        protected void onProgressUpdate(String... data) {

           //I Keep updating the result...
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);
            paint.setColor(Color.WHITE);
            canvas.drawText(result, 200, 300, paint);

        }

        @Override
        protected void onPostExecute(Void unused) {
             Log.d("PROJ","END");
        }
    }

}


问:
Why are pose estimators so slow?
I'm new to the ML field and have a question about computer vision. Why can face detection and object detection software (such as Instagram's face filters) be run on our smart phones at 30 - 60 FPS smoothly, while pose estimation software (e.g OpenPose) struggle to process real time video at above 10 FPS (with decent specs too)?

Correct me if I'm wrong, but Snapchat's software can track your face until poor lighting and pretty abrupt movement and he same can be done with pose estimation, but requiring better/more GPUS and running at a lower FPS.

What would be the fastest type of neural network to use for real time pose estimation and what components make up a robust neural network that can accurately predict a person's pose in real time?

Is it even possible to perform some much computation and still achieve relatively high FPS?

Any response is appreciated

答:
Pure detection is always slow. The most common walk around is to use detection -> tracking -> update framework.

In display thread,  video is shown at constant 30 fps. <- this is what user will see and will not feel the pain in the ass lag.

Backend, you pose detection is constantly update to the pose model( predicted by e.g. EKF or another way). EKF is able to output model at 30 hz corresponding to the display thread frequency.   In between, if you have face update, you can also update the correlation face model to local predict the small step/baseline pose motion with larger varance. At key pose update step, give low variance to this update to perform the major update.

Title: Why are pose estimators so slow?


答:
You can use map() and destructuring of parameters of the function.

const arr = [{ "category": "Start", "name": "Start", "key": 1, "lastname": "xyz" }, { "category": null, "text": "Step", "key": 2, "lastname": "xyz" }, { "category": null, "text": "Condition", "key": 3, "loc": "xyz" } ]

const res = arr.map(({category,...rest}) => category === null ? {...rest} : {category,...rest})
console.log(res)```

Title: Delete specific or selected property from json data .I do not want to delete all key value pairs just those with Category :null

Body:
This is my json data and i wanted to remove the category with null value from my json.

I mean not to delete the "Category":"start" but delete "Category":null.

I have seen some answers regarding this but it deletes all the category including "Category":"start" which I do not want.

"First": [{
        "category": "Start",
        "name": "Start",
        "key": 1,
        "lastname": "xyz"
    }, {
        "category": null,
        "text": "Step",
        "key": 2,
        "lastname": "xyz"
    }, {
        "category": null,
        "text": "Condition",
        "key": 3,
        "loc": "xyz"
    }


问:
Python Regex Capturing Group
```<code>string1 = "abcdbcdbcde"
</code>```

I want to extract string1 into three parts:
(first part and third part can be empty string)

first part:  a

second part (repeitions of some string):  bcdbcdbcd

third part: e

```<code>import re

string1 = "abcdbcdbcde"
m = re.match("(.*)(.+){2,}(.*)", string1)
print m.groups()[0], m.groups()[1], m.groups()[2]
</code>```

Of cuz, the code above doesn't work.

As I know, parentheses operator can be used as RegEx capturing group or reference to the pattern. How to use the parentheses operator in these 2 cases at the same time?

What I want:

```<code>m.groups()[0] = "a"
m.groups()[1] = "bcdbcdbcd"
m.groups()[2] = "e"
</code>```

答:
My take on the problem:

```<code>import re

def match(s, m):
    m = re.match("(.*?)?((?:" + m + "){2,})(.*?)?$", s)
    return (m.groups()[0], m.groups()[1], m.groups()[2]) if m else (None, None, None)

print(match("abcdbcdbcde", "bcd"))
print(match("bcdbcdbcd", "bcd"))
print(match("abcdbcdbcd", "bcd"))
print(match("bcdbcdbcde", "bcd"))
print(match("axxbcdbcdxxe", "bcd"))
print(match("axxbcdxxe", "bcd")) # only one bcd in the middle
</code>```

Prints:

```<code>('a', 'bcdbcdbcd', 'e')
('', 'bcdbcdbcd', '')
('a', 'bcdbcdbcd', '')
('', 'bcdbcdbcd', 'e')
('axx', 'bcdbcd', 'xxe')
(None, None, None)
</code>```

Title: Python Regex Capturing Group

Body:
string1 = "abcdbcdbcde"

I want to extract string1 into three parts:
(first part and third part can be empty string)

first part:  a

second part (repeitions of some string):  bcdbcdbcd

third part: e

import re

string1 = "abcdbcdbcde"
m = re.match("(.*)(.+){2,}(.*)", string1)
print m.groups()[0], m.groups()[1], m.groups()[2]

Of cuz, the code above doesn't work.

As I know, parentheses operator can be used as RegEx capturing group or reference to the pattern. How to use the parentheses operator in these 2 cases at the same time?

What I want:

m.groups()[0] = "a"
m.groups()[1] = "bcdbcdbcd"
m.groups()[2] = "e"

Body:
My take on the problem:

import re

def match(s, m):
    m = re.match("(.*?)?((?:" + m + "){2,})(.*?)?$", s)
    return (m.groups()[0], m.groups()[1], m.groups()[2]) if m else (None, None, None)

print(match("abcdbcdbcde", "bcd"))
print(match("bcdbcdbcd", "bcd"))
print(match("abcdbcdbcd", "bcd"))
print(match("bcdbcdbcde", "bcd"))
print(match("axxbcdbcdxxe", "bcd"))
print(match("axxbcdxxe", "bcd")) # only one bcd in the middle

Prints:

('a', 'bcdbcdbcd', 'e')
('', 'bcdbcdbcd', '')
('a', 'bcdbcdbcd', '')
('', 'bcdbcdbcd', 'e')
('axx', 'bcdbcd', 'xxe')
(None, None, None)


问:
How to display the suggestion for autocomplete field using json file?
I have this json that has " product code" inside this product code has another jsonobject and string.

What I want is that when I input the "product code" the suggested description will show.

I already get the display for suggested description when I input the product description code but it seems that it displaying in wrong way.

What I mean is that when I type the "product code" "BI" the display for suggested description is like this

{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}

here is my json

```<code>{
    "BI": {
        "desc": {
            "MBIK": "MOUNTAIN BIKE",
            "FBIK": "FOLDING BIKE",
            "EBIK": "E-BIKE",
            "OTHER": "OTHER"
        },
        "brand": {
            "GNT": "GIANT",
            "TRL": "TREEK",
            "CNN": "CNDALE",
            "STC": "SANTA",
            "SCT": "SCOTT"
        },
        "category": "BICYCLE & EBIKE STORE"
    },
    "CA": {
        "desc": {
            "CARA": "CAR AUDIO",
            "CARS": "CAR SPEAKER",
            "TIRE": "CAR TIRE",
            "OTHER": "OTHER"
        },
        "brand": {
            "AIC": "AICHI",
            "BRI": "BRIGDESTONE",
            "CON": "CONTINENTAL",
            "DUN": "DUNLOP",
            "FAL": "FALKEN GR"
        }
                "category": "CAR ACCESORIES"
    },
        and so on.. {
                    }
}
</code>```

here is the my code to parse my json to my fragment

private void loadLookupCategoryJson() {

        mLookupProducts = new ArrayList<>();
        mArrayStringLookupProduct = new ArrayList<>();

        try {
            JSONObject json = new JSONObject(loadLookupBrandJSON());
            Iterator<String> keys = json.keys();

            while(keys.hasNext()) {
                String key = keys.next();
                JSONObject obj = (JSONObject) json.get(key);

                JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
                JSONObject desc =  obj.getJSONObject(Keys.CATEGORY_DESC);
                String category = obj.getString(Keys.CATEGORY);

                LookupProducts lookupProduct = new LookupProducts(key, brand, desc, category);
                mLookupProducts.add(lookupProduct);
                mArrayStringLookupProduct.add(String.valueOf(brand));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
```

<p>and here is my to get the brand dynamic field</p>

<pre class="lang-java prettyprint-override"><code>} else if (format.equalsIgnoreCase(Keys.AUTO_COMPLETE_FIELD)) {
 addTextViews(title);
 addAutoCompleteField(desc, inputType, title, mKeys.get(i), mArrayStringLookupProduct, maxLength, minLength);
}
</code>```

I expect the output should be like this

INPUT TEXT: T

SUGGESTED DISPLAY:GIANT
                  TREEK
                  SANTA
                  SCOTT

Display all values with "T"

actual output

INPUT TEXT: BI

SUGGESTED DISPLAY:{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}

答:
In this line of code -  mArrayStringLookupProduct.add(String.valueOf(brand));
You are adding whole jsonObject into mArrayStringLookupProduct ArrayList.

You only want JSONObject brand's values in this ArrayList.

You can make the following changes-

   JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
   JSONObject desc =  obj.getJSONObject(Keys.CATEGORY_DESC);
   String category = obj.getString(Keys.CATEGORY);
   lookupProduct = new LookupProducts(key, brand, desc, category);
   mLookupProducts.add(lookupProduct);

   // iterate every brand key, fetch its value and add in arrayList
   Iterator<String> brandKeys = brand.keys();
   while(brandKeys.hasNext()) {
        String bKey = brandKeys.next();
        mArrayStringLookupProduct.add((String) brand.get(bKey));
   }

```

Body:
I have this json that has " product code" inside this product code has another jsonobject and string.

What I want is that when I input the "product code" the suggested description will show.

I already get the display for suggested description when I input the product description code but it seems that it displaying in wrong way.

What I mean is that when I type the "product code" "BI" the display for suggested description is like this

{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}

here is my json

{
    "BI": {
        "desc": {
            "MBIK": "MOUNTAIN BIKE",
            "FBIK": "FOLDING BIKE",
            "EBIK": "E-BIKE",
            "OTHER": "OTHER"
        },
        "brand": {
            "GNT": "GIANT",
            "TRL": "TREEK",
            "CNN": "CNDALE",
            "STC": "SANTA",
            "SCT": "SCOTT"
        },
        "category": "BICYCLE & EBIKE STORE"
    },
    "CA": {
        "desc": {
            "CARA": "CAR AUDIO",
            "CARS": "CAR SPEAKER",
            "TIRE": "CAR TIRE",
            "OTHER": "OTHER"
        },
        "brand": {
            "AIC": "AICHI",
            "BRI": "BRIGDESTONE",
            "CON": "CONTINENTAL",
            "DUN": "DUNLOP",
            "FAL": "FALKEN GR"
        }
                "category": "CAR ACCESORIES"
    },
        and so on.. {
                    }
}

here is the my code to parse my json to my fragment

private void loadLookupCategoryJson() {

        mLookupProducts = new ArrayList<>();
        mArrayStringLookupProduct = new ArrayList<>();

        try {
            JSONObject json = new JSONObject(loadLookupBrandJSON());
            Iterator<String> keys = json.keys();

            while(keys.hasNext()) {
                String key = keys.next();
                JSONObject obj = (JSONObject) json.get(key);

                JSONObject brand = obj.getJSONObject(Keys.CATEGORY_BRAND);
                JSONObject desc =  obj.getJSONObject(Keys.CATEGORY_DESC);
                String category = obj.getString(Keys.CATEGORY);

                LookupProducts lookupProduct = new LookupProducts(key, brand, desc, category);
                mLookupProducts.add(lookupProduct);
                mArrayStringLookupProduct.add(String.valueOf(brand));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

and here is my to get the brand dynamic field

} else if (format.equalsIgnoreCase(Keys.AUTO_COMPLETE_FIELD)) {
 addTextViews(title);
 addAutoCompleteField(desc, inputType, title, mKeys.get(i), mArrayStringLookupProduct, maxLength, minLength);
}

I expect the output should be like this

INPUT TEXT: T

SUGGESTED DISPLAY:GIANT
                  TREEK
                  SANTA
                  SCOTT

Display all values with "T"

actual output

INPUT TEXT: BI

SUGGESTED DISPLAY:{"GNT": "GIANT","TRL": "TREEK","CNN": "CNDALE","ST": "SANTA","SCT": "SCOTT"}