问:
Unable to delete record in CodeIgniter
home.php
This is my controller, I am getting right URL through Id but unable to delete record.

```<code><?php
class home extends CI_Controller
{
    function __construct(){
        parent::__construct();
        $this->load->model('select');
        $this->load->helper(array('form','url','html'));
        $this->load->library(array('form_validation','session'));
    }

  public function index(){
     //load the database
     //$this->load->database();
     //load the model
     $this->load->model('select');
     //load the method of model
     $data['h']=$this->select->select();
     //return the data in view
     $this->load->view('fetch_view', $data);
  }

  function records(){
      $ytl['dta']=$this->users->datas();
       //$this->load->view('info',$ytl);
       //echo "```controller";print_r($ytl);
  }

  function primezone(){
       $ytl['dta']=$this->users->datas();
    echo "```controller";print_r($ytl);
  }

  function form($id=null){
    //die($id);
    if($this->input->post())
    {
        //echo"```";print_r( $this->input->post());die;
        $this->form_validation->set_rules('fname','First Name','required|min_length[5]');
        $this->form_validation->set_rules('lname','Last Name','required|callback_check_picture[lname]');
        //$this->form_validation->set_rules('email','Email','required');
        $this->form_validation->set_rules('mobile','Mobile Number','required|callback_valid_phone_number[mobile]');
        $this->form_validation->set_error_delimiters('
', '
');
        if($this->form_validation->run()==True)
        {
            $data=[
            'fname'=>$this->input->post('fname'),
            'lname'=>$this->input->post('lname'),
            'email'=>$this->input->post('email'),
            'mobile'=>$this->input->post('mobile'),
            'message'=>$this->input->post('message'),
            ];
            if(empty($id))
            {
              $ytl=$this->select->insertdata($data);

            } else {
                $ytl=$this->select->updatedata($data,$id);
            }
          if($ytl){
              $this->session->set_flashdata('message', 'Successfully Added.');
          redirect('home');
          }
        } else {
                //$this->load->view('form');
        }
    }
    $ytl['dta']=$this->select->getDataById($id);
    //echo "```";print_r($ytl);die;
    $this->load->view('form',$ytl);
  }

  public function check_picture($a){
    if(!is_numeric($a))
    {
       return true;
    }else{
       $this->form_validation->set_message('check_picture', 'Please enter only char value');
       return False;
    }
  }

  function valid_phone_number($value){
  $value = strlen($value);
   //echo $value;die;
    if ($value == 10) {
        return true;
    } else {
        $this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}
        return false;
    }
  }

  public function delete(){
    $this->load->model('select');
    $id=$this->input->get('id');
       //echo $id;
     if($this->select->deleteuser($id))
     {
         $data['h']=$this->select->select();
         $this->load->view('fetch_view', $data);
     }
  }
}
?>
</code>```

fetch_view.php
This is my view, I am getting right URL through Id but unable to delete record.

```<code><!DOCTYPE html>
<html>
<head>

  <link href="<?php echo base_url().'assets/bootstrap.min.css'; ?>" rel="stylesheet" type='text/css'>
  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css"/>
  <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" />
  <script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>

  <style>
     .error{color:red}
   </style>
</head>
    <body>
      <h1>User List</h1>
      <?php if($this->session->flashdata('message')){?>
      <div class="alert alert-success alert-dismissable">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        <strong>Success!</strong> <?= $this->session->flashdata('message') ?>
      </div>
      <?php } ?>

    <table border="1" class="table table-bordered table-striped table-hover" id="">
      <tbody>
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Mobile Number</th>
            <th>Message</th>
            <th>Update</th>
            <th>Delete</th>
          </tr>
        </thead>
      </tbody>
      <?php
          foreach ($h->result() as $row)
        { ?>
        <tr>
          <td><?php echo $row->fname; ?></td>
          <td><?php echo $row->lname; ?></td>
          <td><?php echo $row->email; ?></td>
          <td><?php echo $row->mobile; ?></td>
          <td><?php echo $row->message; ?></td>
          <td><a href="<?= site_url('home/form').'/'.$row->id ?>">Edit</a></td>
          <td><a href="<?php echo site_url('home/delete').'/'.$row->id; ?>">Delete</a></td>
        </tr>
      <?php } ?>
    </table>
  </form>
</body>
</html>
</code>```

select.php
This is my Model, I am getting right URL through Id but unable to delete record.

```<code><?php
class select extends CI_model
{
    function __construct(){
      // Call the Model constructor
      parent::__construct();
      $this->load->database();
    }

    function insertdata($data){
      if(!empty($data['id'])){
          $this->db->where('id', $data['id'])->update('student', $data);
          return $data['id'];
      } else {
          unset($data['id']);
          $this->db->insert('student',  $data);
          return $this->db->insert_id();
      }
    }

    public function select(){
       //data is retrive from this query
        $query = $this->db->get('student');
        return $query;
        //return $query->row();
    }

    function getDataById($id)
    {
      $this->db->select('*');
      $this->db->where('id',$id);
      $this->db->from('student');
      $query = $this->db->get()->row_array();
           return $query;
    }

    function updatedata($data, $id)
    {
      //print_r($data);die;
      $this->db->where('id', $id);
      return $this->db->update('student' ,$data);
    }

    public function deleteuser($id)
    {
      //echo $id;
      //die;
      // $this->load->database();
      $this->db->where('id', $id);
      $this->db->delete('student');
      return true;
    }

}
?>
</code>```

I know that I have to paste only specific code but I am pasting full code.

答:
I hope to help you

```<code><body>
 echo $msg;
.....your code....
  <a href="<?php echo base_url() . "index.php/home/delete/" . $row->id; ?>">Delete</a>
</code>```

home.php

```<code>  public function index($msg = NULL){
     $this->load->model('select');
         $data = array(
         'h' => $this->select->select(),
         'msg' => $msg
          );
     $this->load->view('fetch_view', $data);
  }
         public function delete()

          {
         $this->load->model('select');
         $id = $this->uri->segment(3);
         //echo $id;
         $result=  $this->select->deleteuser($id);
         if($result==TRUE)
         {
         $msg = '<script>alert("delete successful!!! ")</script>';
           $this->index($msg);
         }
    }
</code>```

select.php

```<code> public function select(){
   //data is retrive from this query
    $this->db->select('*');
    $query = $this->db->get('student');
    return $query;
    //return $query->row();
}

 public function deleteuser($id=NULL)
    {

     $this->db->where('id', $id);
     $result= $this->db->delete('student');
     return $result;
    }
</code>```

Title: Unable to delete record in CodeIgniter

Body:
home.php
This is my controller, I am getting right URL through Id but unable to delete record.

<?php
class home extends CI_Controller
{
    function __construct(){
        parent::__construct();
        $this->load->model('select');
        $this->load->helper(array('form','url','html'));
        $this->load->library(array('form_validation','session'));
    }

  public function index(){
     //load the database
     //$this->load->database();
     //load the model
     $this->load->model('select');
     //load the method of model
     $data['h']=$this->select->select();
     //return the data in view
     $this->load->view('fetch_view', $data);
  }

  function records(){
      $ytl['dta']=$this->users->datas();
       //$this->load->view('info',$ytl);
       //echo "
controller";print_r($ytl);
  }

  function primezone(){
       $ytl['dta']=$this->users->datas();
    echo "
controller";print_r($ytl);
  }

  function form($id=null){
    //die($id);
    if($this->input->post())
    {
        //echo"
";print_r( $this->input->post());die;
        $this->form_validation->set_rules('fname','First Name','required|min_length[5]');
        $this->form_validation->set_rules('lname','Last Name','required|callback_check_picture[lname]');
        //$this->form_validation->set_rules('email','Email','required');
        $this->form_validation->set_rules('mobile','Mobile Number','required|callback_valid_phone_number[mobile]');
        $this->form_validation->set_error_delimiters('
', '
');
        if($this->form_validation->run()==True)
        {
            $data=[
            'fname'=>$this->input->post('fname'),
            'lname'=>$this->input->post('lname'),
            'email'=>$this->input->post('email'),
            'mobile'=>$this->input->post('mobile'),
            'message'=>$this->input->post('message'),
            ];
            if(empty($id))
            {
              $ytl=$this->select->insertdata($data);

            } else {
                $ytl=$this->select->updatedata($data,$id);
            }
          if($ytl){
              $this->session->set_flashdata('message', 'Successfully Added.');
          redirect('home');
          }
        } else {
                //$this->load->view('form');
        }
    }
    $ytl['dta']=$this->select->getDataById($id);
    //echo "
";print_r($ytl);die;
    $this->load->view('form',$ytl);
  }

  public function check_picture($a){
    if(!is_numeric($a))
    {
       return true;
    }else{
       $this->form_validation->set_message('check_picture', 'Please enter only char value');
       return False;
    }
  }

  function valid_phone_number($value){
  $value = strlen($value);
   //echo $value;die;
    if ($value == 10) {
        return true;
    } else {
        $this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}
        return false;
    }
  }

  public function delete(){
    $this->load->model('select');
    $id=$this->input->get('id');
       //echo $id;
     if($this->select->deleteuser($id))
     {
         $data['h']=$this->select->select();
         $this->load->view('fetch_view', $data);
     }
  }
}
?>

fetch_view.php
This is my view, I am getting right URL through Id but unable to delete record.

<!DOCTYPE html>

  <link href="<?php echo base_url().'assets/bootstrap.min.css'; ?>" rel="stylesheet" type='text/css'>

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css"/>

  <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" />

User List

      <?php if($this->session->flashdata('message')){?>

        ×
        Success! <?= $this->session->flashdata('message') ?>

      <?php } ?>

            First Name
            Last Name
            Email
            Mobile Number
            Message
            Update
            Delete

      <?php
          foreach ($h->result() as $row)
        { ?>

          <?php echo $row->fname; ?>
          <?php echo $row->lname; ?>
          <?php echo $row->email; ?>
          <?php echo $row->mobile; ?>
          <?php echo $row->message; ?>
          <a href="<?= site_url('home/form').'/'.$row->id ?>">Edit
          <a href="<?php echo site_url('home/delete').'/'.$row->id; ?>">Delete

      <?php } ?>

  </form>

select.php
This is my Model, I am getting right URL through Id but unable to delete record.

<?php
class select extends CI_model
{
    function __construct(){
      // Call the Model constructor
      parent::__construct();
      $this->load->database();
    }

    function insertdata($data){
      if(!empty($data['id'])){
          $this->db->where('id', $data['id'])->update('student', $data);
          return $data['id'];
      } else {
          unset($data['id']);
          $this->db->insert('student',  $data);
          return $this->db->insert_id();
      }
    }

    public function select(){
       //data is retrive from this query
        $query = $this->db->get('student');
        return $query;
        //return $query->row();
    }

    function getDataById($id)
    {
      $this->db->select('*');
      $this->db->where('id',$id);
      $this->db->from('student');
      $query = $this->db->get()->row_array();
           return $query;
    }

    function updatedata($data, $id)
    {
      //print_r($data);die;
      $this->db->where('id', $id);
      return $this->db->update('student' ,$data);
    }

    public function deleteuser($id)
    {
      //echo $id;
      //die;
      // $this->load->database();
      $this->db->where('id', $id);
      $this->db->delete('student');
      return true;
    }

}
?>

I know that I have to paste only specific code but I am pasting full code.

Body:
I hope to help you

<body>
 echo $msg;
.....your code....
  <a href="<?php echo base_url() . "index.php/home/delete/" . $row->id; ?>">Delete</a>

home.php

  public function index($msg = NULL){
     $this->load->model('select');
         $data = array(
         'h' => $this->select->select(),
         'msg' => $msg
          );
     $this->load->view('fetch_view', $data);
  }
         public function delete()

          {
         $this->load->model('select');
         $id = $this->uri->segment(3);
         //echo $id;
         $result=  $this->select->deleteuser($id);
         if($result==TRUE)
         {
         $msg = '<script>alert("delete successful!!! ")</script>';
           $this->index($msg);
         }
    }

select.php

 public function select(){
   //data is retrive from this query
    $this->db->select('*');
    $query = $this->db->get('student');
    return $query;
    //return $query->row();
}

 public function deleteuser($id=NULL)
    {

     $this->db->where('id', $id);
     $result= $this->db->delete('student');
     return $result;
    }


来源: stackexchange

问:
git: Why doesn't git diff show any differences?
If I run 'git status' on my repo it gives:

```<code># On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified: myfile
</code>```

However, if I do a 'git diff myfile' it shows no differences. Is this because I have made a change and removed it so it is back to the original?

Should I run 'git checkout myfile' to clear it?

答:
Your file is already staged to be committed. You can show it's diff using the --cached option of git.

```<code>git diff --cached myfile
</code>```

To unstage it, just do what git status suggests in it's output ;)

You can check The Git Index For more info.

ContentLicense: CC BY-SA 2.5

Body:
If I run 'git status' on my repo it gives:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified: myfile

However, if I do a 'git diff myfile' it shows no differences. Is this because I have made a change and removed it so it is back to the original?

Should I run 'git checkout myfile' to clear it?

Body:
Your file is already staged to be committed. You can show it's diff using the --cached option of git.

git diff --cached myfile

To unstage it, just do what git status suggests in it's output ;)

You can check The Git Index For more info.

ContentLicense: CC BY-SA 3.0


问:
How to access keyWindow in share extension in ios?
I need to access keyWindow in share extension for my app to

- Add some indicator view

- Access the width and height of window

I wrote the following line in the share extension classes:

```<code>UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];
</code>```

But, it's saying 'sharedApplication' is unavailable.

How can i access keyWindow in share extension?

Need your valuable suggestions.

Thanks in advance

答:
```<code>UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
UIWindow *keyWindow = application.keyWindow;
</code>```

however, keyWindow is nil...

Body:
I need to access keyWindow in share extension for my app to

- Add some indicator view

- Access the width and height of window

I wrote the following line in the share extension classes:

UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];

But, it's saying 'sharedApplication' is unavailable.

How can i access keyWindow in share extension?

Need your valuable suggestions.

Thanks in advance

Body:
UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
UIWindow *keyWindow = application.keyWindow;

however, keyWindow is nil...


问:
Repeat command automatically in Linux
Is it possible in Linux command line to have a command repeat every n seconds?

Say, I have an import running, and I am doing

```<code>ls -l
</code>```

to check if the file size is increasing. I would like to have a command to have this repeat automatically.

答:
```<code>watch -n 5 'ls -l
</code>```

Will Runls -l command after every 5s

Output :-

```<code>Every 5.0s: ls -l                                                                                Fri Nov 17 16:28:25 2017

total 169548
-rw-rw-r--  1 sachin sachin     4292 Oct 18 12:16 About_us_Admission.doc
-rw-rw-r--  1 sachin sachin      865 Oct 13 15:26 About_us_At_glance.doc
-rw-rw-r--  1 sachin sachin     1816 Oct 13 16:11 About_us_Principle.doc
-rw-rw-r--  1 sachin sachin     1775 Oct 13 15:59 About_us_Vission_mission.doc
-rw-rw-r--  1 sachin sachin     1970 Oct 13 16:41 Academic_Middle_school.doc
-rw-rw-r--  1 sachin sachin      772 Oct 16 16:07 academics_High_School.doc
-rw-rw-r--  1 sachin sachin      648 Oct 16 13:34 academics_pre_primary.doc
-rw-rw-r--  1 sachin sachin      708 Oct 16 13:39 academics_primary.doc
-rwxrwxr-x  1 sachin sachin     8816 Nov  1 12:10 a.out
-rw-rw-r--  1 sachin sachin    23956 Oct 23 18:14 Ass1.c++
-rw-rw-r--  1 sachin sachin      342 Oct 23 22:13 Ass2.doc
drwxrwxr-x  2 sachin sachin     4096 Oct 19 10:45 Backtracking
drwxrwxr-x  3 sachin sachin     4096 Sep 23 20:09 BeautifulSoup
drwxrwxr-x  2 sachin sachin     4096 Nov  2 00:18 CL_1
drwxrwxr-x  2 sachin sachin     4096 Oct 23 20:16 Code
drwxr-xr-x  2 sachin sachin     4096 Nov 15 12:05 Desktop
-rw-rw-r--  1 sachin sachin        0 Oct 13 23:12 doc
drwxr-xr-x  4 sachin sachin     4096 Nov  6 21:18 Documents
drwxr-xr-x 27 sachin sachin    12288 Nov 17 13:23 Downloads
-rw-r--r--  1 sachin sachin     8980 Sep 19 23:58 examples.desktop
</code>```

ContentLicense: CC BY-SA 4.0

Title: Repeat command automatically in Linux

Body:
Is it possible in Linux command line to have a command repeat every n seconds?

Say, I have an import running, and I am doing

ls -l

to check if the file size is increasing. I would like to have a command to have this repeat automatically.

Body:
watch -n 5 'ls -l

Will Runls -l command after every 5s

Output :-

Every 5.0s: ls -l                                                                                Fri Nov 17 16:28:25 2017

total 169548
-rw-rw-r--  1 sachin sachin     4292 Oct 18 12:16 About_us_Admission.doc
-rw-rw-r--  1 sachin sachin      865 Oct 13 15:26 About_us_At_glance.doc
-rw-rw-r--  1 sachin sachin     1816 Oct 13 16:11 About_us_Principle.doc
-rw-rw-r--  1 sachin sachin     1775 Oct 13 15:59 About_us_Vission_mission.doc
-rw-rw-r--  1 sachin sachin     1970 Oct 13 16:41 Academic_Middle_school.doc
-rw-rw-r--  1 sachin sachin      772 Oct 16 16:07 academics_High_School.doc
-rw-rw-r--  1 sachin sachin      648 Oct 16 13:34 academics_pre_primary.doc
-rw-rw-r--  1 sachin sachin      708 Oct 16 13:39 academics_primary.doc
-rwxrwxr-x  1 sachin sachin     8816 Nov  1 12:10 a.out
-rw-rw-r--  1 sachin sachin    23956 Oct 23 18:14 Ass1.c++
-rw-rw-r--  1 sachin sachin      342 Oct 23 22:13 Ass2.doc
drwxrwxr-x  2 sachin sachin     4096 Oct 19 10:45 Backtracking
drwxrwxr-x  3 sachin sachin     4096 Sep 23 20:09 BeautifulSoup
drwxrwxr-x  2 sachin sachin     4096 Nov  2 00:18 CL_1
drwxrwxr-x  2 sachin sachin     4096 Oct 23 20:16 Code
drwxr-xr-x  2 sachin sachin     4096 Nov 15 12:05 Desktop
-rw-rw-r--  1 sachin sachin        0 Oct 13 23:12 doc
drwxr-xr-x  4 sachin sachin     4096 Nov  6 21:18 Documents
drwxr-xr-x 27 sachin sachin    12288 Nov 17 13:23 Downloads
-rw-r--r--  1 sachin sachin     8980 Sep 19 23:58 examples.desktop


问:
Selectively remove preprocessor directives using Roslyn
I want to use Roslyn to clean the code of some of the older preprocessor directives.

For example, from this code

```<code>#define TEST_1_0
#define TEST_1_1
namespace ConsoleApplication1
{
class TypeName
{
   public static void Main(string[] args)
   {
#if TEST_1_0
        int TEST_1_0 = 1;
#if TEST_1_1
        int TEST_1_1 = 1;
#else//TEST_1_1
        int TEST_1_1 = 0;
#endif//TEST_1_1
#else//TEST_1_0
        int TEST_1_0 = 0;
#endif//TEST_1_0
    }
}
}
</code>```

I'd like to remove else//TEST_1_0, but keep the else//TEST_1_1. I cannot count on the comments, so I should related a #if with its corresponding #else, if there is one.

Finding the #if is easy, but finding the corresponding #else is less easy.

I tried two strategies:

Here i lookup  #else//TEST_1_0 in the analyzer, and create a codefix for that location

Here I just create a codefix for #if TEST_1_0 in analyzer, and try to get to the corresponding else from the CodeFixprovider

Both get quite complicated quickly, it seems problematic that directives are trivia, which are spread out over the leadingTrivia of different SyntaxTokens. Changes in the code affect the location directives around quite a bit so it looks like lots of work to program all cases..

Am I missing something? Is there an easier way to do this without programming all the different cases by hand?

Would you go for strategy 1 or 2?

答:
I concluded that roslyn is not the way to go here.

Roslyn models preprocesessor directives as trivia in the syntax tree, and the location of trivia has great variation depending on the structure of the actual code.

Therefore working on the syntax tree introduces lookup complexities that are not an issue when working text based, and more complexity means more RISK. Binaries should be the same before/after processing!

So I chose to abandon Roslyn and simply parse the code/directive mix as text, using regex to parse and the good-old stack to handle the directive logic.

Now it's much easier, even a piece of cake ..
Still need to handle some encoding issues, then I'm done! :)
Happy parsing!

Body:
I want to use Roslyn to clean the code of some of the older preprocessor directives.

For example, from this code

#define TEST_1_0
#define TEST_1_1
namespace ConsoleApplication1
{
class TypeName
{
   public static void Main(string[] args)
   {
#if TEST_1_0
        int TEST_1_0 = 1;
#if TEST_1_1
        int TEST_1_1 = 1;
#else//TEST_1_1
        int TEST_1_1 = 0;
#endif//TEST_1_1
#else//TEST_1_0
        int TEST_1_0 = 0;
#endif//TEST_1_0
    }
}
}

I'd like to remove else//TEST_1_0, but keep the else//TEST_1_1. I cannot count on the comments, so I should related a #if with its corresponding #else, if there is one.

Finding the #if is easy, but finding the corresponding #else is less easy.

I tried two strategies:

Here i lookup  #else//TEST_1_0 in the analyzer, and create a codefix for that location

Here I just create a codefix for #if TEST_1_0 in analyzer, and try to get to the corresponding else from the CodeFixprovider

Both get quite complicated quickly, it seems problematic that directives are trivia, which are spread out over the leadingTrivia of different SyntaxTokens. Changes in the code affect the location directives around quite a bit so it looks like lots of work to program all cases..

Am I missing something? Is there an easier way to do this without programming all the different cases by hand?

Would you go for strategy 1 or 2?


问:
Copying object values not referencing
```<code>public class Track {int size; int count; Luggage front; Luggage rear}

class Luggage {String name; Luggage next; Luggage prev;}

class Cart {int position; Luggage luggage;}

class Step {
   Cart cart;
   Track track[];
   String moves = "";}
</code>```

I'm trying to make a program that hard-force solves a solution. For that I queue elements in a queue with all different moves that can be made via STEP. There are 5 different moves that you can make each turn and STEP keeps all the values inside, but the values inside STEP are objects that further point to objects.

How do I copy an object Step, which contains further references to objects inside? (each turn I have to make 5 new different STEPs from the STEP that was in this turn)

答: Generally, in Java you can clone() objects that implement the Cloneable interface. However, the default implementation of clone() only performs a shallow copy (for example, if your object contains an array, a copy of the array will be made, but not of elements within the array). If you want to perform a deep clone, you will have to override the clone() method to do it yourself (you usually want to override clone() anyway to make it public as it's protected by default).

Title: Copying object values not referencing

Body:
public class Track {int size; int count; Luggage front; Luggage rear}

class Luggage {String name; Luggage next; Luggage prev;}

class Cart {int position; Luggage luggage;}

class Step {
   Cart cart;
   Track track[];
   String moves = "";}

I'm trying to make a program that hard-force solves a solution. For that I queue elements in a queue with all different moves that can be made via STEP. There are 5 different moves that you can make each turn and STEP keeps all the values inside, but the values inside STEP are objects that further point to objects.

How do I copy an object Step, which contains further references to objects inside? (each turn I have to make 5 new different STEPs from the STEP that was in this turn)


问:
Mysql query to retrieve single image from an array of images?
Table to store array of Images:

```<code>`products` and  `products_photos`

`products` includes only `id` field
`products_photos` includes `product_id` and `filename`
</code>```

Table values:

```<code>products
--------
id-6

id-7

products_photos
---------------
6 - filename1

6 - filename2

7 - filename3
</code>```

In these two table id 6 includes 2 images but i need to fetch only one image from that. How to write a query for that in mysql or laravel.

答:
You can give limit to your query to get single result

```<code>SELECT * FROM products_photos WHERE product_id = 6 ORDER BY id LIMIT 1;
</code>```

Which will give single image only for id = 6 product

For retrieve all data use group by

```<code>SELECT * FROM GemSellerPortal.products pr
LEFT JOIN GemSellerPortal.products_photos ph
ON ph.product_id = pr.id
GROUP BY pr.id
</code>```

Body:
Table to store array of Images:

`products` and  `products_photos`

`products` includes only `id` field
`products_photos` includes `product_id` and `filename`

Table values:

products
--------
id-6

id-7

products_photos
---------------
6 - filename1

6 - filename2

7 - filename3

In these two table id 6 includes 2 images but i need to fetch only one image from that. How to write a query for that in mysql or laravel.

Body:
You can give limit to your query to get single result

SELECT * FROM products_photos WHERE product_id = 6 ORDER BY id LIMIT 1;

Which will give single image only for id = 6 product

For retrieve all data use group by

SELECT * FROM GemSellerPortal.products pr
LEFT JOIN GemSellerPortal.products_photos ph
ON ph.product_id = pr.id
GROUP BY pr.id


问:
Uncaught ReferenceError: models is not defined in the html file in a backbone.js application
demo.js

```<code>var CommentsCollection = Backbone.Collection.extend({

    url : "http://0.0.0.0:8080/"

});

var CommentsListView = Backbone.View.extend({

    el: '.page',

    render : function(){
        var that = this;
        var commentsCollection = new CommentsCollection();
        commentsCollection.fetch({
            success: () => {
                    var models = commentsCollection.models;
                    // _.each(models, function(models){
                    //  console.log(models.get('firstname'));
                    // });

                  var template = _.template($('#reddit-comments-template').html());
                  that.$el.html(template(models));
            }
        })
    }
});

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home'
    }
});

Backbone.history.start();
</code>```

index.html

```<code><html>
<head>
    <title> </title>
</head>
<body>
    <div class="container">
        <h1>Top posts</h1>
        <hr />
        <div class="page"></div>
    </div>

    <script type="text/template" id="reddit-comments-template">
        <table class = "comments table">
            <thead>
                <tr>
                    <th>Row</th>
                    <th>Commments</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <% _.each(models, function(models){ %>
                    <tr>
                        <td><%= models.get('firstname') %></td>
                        <td><%= models.get('lastname') %></td>
                        <td><%= models.get('id') %></td>
                    </tr>
                    <% }); %>
                </tr>
            </tbody>
        </table>
    </script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="underscore-min.js"></script>
    <script type="text/javascript" src="backbone-min.js"></script>
    <script type="text/javascript" src="demo.js"></script>

</body>
</html>
</code>```

Actually if you see, I tried some getting some data from the api and updating the view according to the changes in the data, the collection gets the data from the api and then I get the models of the collection to loop over the data from the model, the variables in the models get printed in the log I added in the js script in the comments as you can see but I guess the value is not passed to the html file, giving rise to that error. Can you please tell me how to correct it.

答:
Before sending the collection or model to the template first serialize it with toJSON() method that is available on both Backbone's model and collection. When we use toJSON over a collection, it returns an array containing the attributes hash of each model.

```<code>var CommentsListView = Backbone.View.extend({
    el: '.page',
    // read and compile the template once
    template: _.template($('#reddit-comments-template').html()),

    render: function() {
        var commentsCollection = new CommentsCollection();
        commentsCollection.fetch({
            context: this, // avoids "that = this;"
            success: function(collection, response, options) {
                that.$el.html(this.template({ models: collection.toJSON() }));
            }
        });
    }
});
</code>```

PS:  I have added the default arguments in success callback.

Body:
demo.js

var CommentsCollection = Backbone.Collection.extend({

    url : "http://0.0.0.0:8080/"

});

var CommentsListView = Backbone.View.extend({

    el: '.page',

    render : function(){
        var that = this;
        var commentsCollection = new CommentsCollection();
        commentsCollection.fetch({
            success: () => {
                    var models = commentsCollection.models;
                    // _.each(models, function(models){
                    //  console.log(models.get('firstname'));
                    // });

                  var template = _.template($('#reddit-comments-template').html());
                  that.$el.html(template(models));
            }
        })
    }
});

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home'
    }
});

Backbone.history.start();

index.html

    <title> </title>

Top posts

Actually if you see, I tried some getting some data from the api and updating the view according to the changes in the data, the collection gets the data from the api and then I get the models of the collection to loop over the data from the model, the variables in the models get printed in the log I added in the js script in the comments as you can see but I guess the value is not passed to the html file, giving rise to that error. Can you please tell me how to correct it.

Body:
Before sending the collection or model to the template first serialize it with toJSON() method that is available on both Backbone's model and collection. When we use toJSON over a collection, it returns an array containing the attributes hash of each model.

var CommentsListView = Backbone.View.extend({
    el: '.page',
    // read and compile the template once
    template: _.template($('#reddit-comments-template').html()),

    render: function() {
        var commentsCollection = new CommentsCollection();
        commentsCollection.fetch({
            context: this, // avoids "that = this;"
            success: function(collection, response, options) {
                that.$el.html(this.template({ models: collection.toJSON() }));
            }
        });
    }
});

PS:  I have added the default arguments in success callback.


问:
Can you explain closures (as they relate to Python)?
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible.  I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>

答: Here's a typical use case for closures - callbacks for GUI elements (this would be an alternative to subclassing the button class). For example, you can construct a function that will be called in response to a button press, and "close" over the relevant variables in the parent scope that are necessary for processing the click. This way you can wire up pretty complicated interfaces from the same initialization function, building all the dependencies into the closure.</p>

LastEditorDisplayName: knowncitizen

OwnerDisplayName: Naveen Michaud-Agrawal


问:
Excluding in Live HTTP Headers plugin for Firefox
I am trying to exclude gmail's requests from Live Http headers, but I cant
seem to get the exclude reg ex to work.

My exclude regex is this: .gif$|.jpg$|.ico$|.css$|.js$|.*mail.google.com.*

Any ideas/suggestions?

答:
I have had the same problem and its soultion was stupid simple:

do you have enabled the check box ("exclude URL by RegExp" (or similar - I have only the german version))?

Hint: you do need to add the .* at start and end of your expression, because the request will be excludes if it contains the pattern (is must not match the complate url).


问:
How to set the height of table in mpdf
I am generating invoices using MPDF. My item rows are dynamic so the height of table which shows items should be flexible. When I am printing the PDF using following code:

```<code>    <!-- Latest compiled and minified CSS -->
<?php echo $this->Html->css(array('bootstrap.min','AdminLTE.min','skin-green','font-awesome.min')); ?>
<style type="text/css">
  .products{
    width: 100%;
    border-collapse: collapse;
  }
  h2,h3{
    margin: 0;
    padding:0;
  }
  .border{
    border: 1px solid black;
    padding:5px;
  }
  table.products{
    border: 1px solid black;
    height: 500px;
    margin-left: -6px;
    margin-right: -6px;
    margin-bottom: -6px;
  }
  .products tr td{
    padding:5px;
    border:1px solid #333;
  }
  .products tr th{
    padding:5px;
    border:1px solid #333;
  }
  .pull-right{
    float: right;
  }
</style>
<!-- title row -->
<div class="border">
  <table width="100%">
    <tr>
      <td style="width:35%">

      </td>
      <td style="width:35%" align="center">
        Estimate
      </td>
      <td style="width:35%" align="right">
        Date: <?php echo  date('d-m-Y',strtotime($invoice['Invoice']['dated'])); ?>
      </td>
    </tr>
    <tr>
      <td colspan="3" align="center">
        <br>
        <h3>Invoice Heading</h3>

      </td>
    </tr>
  </table>
  <hr/>
  <div class="row">
    <div class="col-xs-12 border-right">
      To: <?php echo $invoice['Invoice']['user']; ?><br>
      Mobile.: <?php echo $invoice['Invoice']['mobile']; ?><br>
      Address: <?php echo $invoice['Invoice']['address']; ?><br>

    </div>
  </div>
  <hr/>
  <!-- Table row -->
  <div class="row">
    <div class="col-xs-12 table-responsive">
      <table class="products">
        <thead>
          <tr>
            <th width="60"><?php echo __('Sr. No.'); ?></th>
            <th><?php echo __('Quantity'); ?></th>
            <th width="250"><?php echo __('Particulars'); ?></th>
            <th><?php echo __('Rate'); ?></th>
            <th><?php echo __('Amount'); ?></th>
          </tr>
        </thead>
        <tbody>
          <?php $i = 0; foreach ($invoice['InvoiceDetail'] as $invoiceDetail): $i++; ?>
            <tr>
              <td><?php echo $i; ?></td>
              <td><?php echo $invoiceDetail['quantity']; ?></td>
              <td><?php echo $invoiceDetail['Item']['name']; ?></td>
              <td><?php echo $invoiceDetail['price']; ?></td>
              <td align="right"><?php echo $invoiceDetail['amount'] ?></td>
            </tr>
          <?php endforeach; ?>
            <tr>
              <td colspan="3"></td>
              <td>Total: </td>
              <td align="right"><i class="fa fa-inr"></i> <?php echo number_format((float)$invoice['Invoice']['total'], 2, '.', ''); ?>
              </td>
            </tr>
            <tr>
              <td colspan="5">Amount in words: Rs.<?php echo $c2w ?></td>
            </tr>
        </tbody>
      </table>
    </div><!-- /.col -->
  </div><!-- /.row -->
</div>
</code>```

It prints the pdf as follows:

But I need to print it as follows:

I have tried using line-height but it distorts the view because valign in td will not align the content at top.

With line-height:100px in TD print looks like follows:

Is there a way to fill the complete page by increasing the height of items table dynamically.

答:
According to the documentation of mPDF library here, we can set the height of block level elements only. I was facing the same problem, then I moved my table inside a div and added height to the div like below.</p>

```<code><div height="870" style="border:solid 1px #ccc">
    <table class="table>
         Your table content here...
    </table>
</div>
</code>```

Title: How to set the height of table in mpdf

Body:
I am generating invoices using MPDF. My item rows are dynamic so the height of table which shows items should be flexible. When I am printing the PDF using following code:

<?php echo $this->Html->css(array('bootstrap.min','AdminLTE.min','skin-green','font-awesome.min')); ?>

        Estimate

        Date: <?php echo  date('d-m-Y',strtotime($invoice['Invoice']['dated'])); ?>

Invoice Heading

      To: <?php echo $invoice['Invoice']['user']; ?>

      Mobile.: <?php echo $invoice['Invoice']['mobile']; ?>

      Address: <?php echo $invoice['Invoice']['address']; ?>

            <?php echo __('Sr. No.'); ?>
            <?php echo __('Quantity'); ?>
            <?php echo __('Particulars'); ?>
            <?php echo __('Rate'); ?>
            <?php echo __('Amount'); ?>

          <?php $i = 0; foreach ($invoice['InvoiceDetail'] as $invoiceDetail): $i++; ?>

              <?php echo $i; ?>
              <?php echo $invoiceDetail['quantity']; ?>
              <?php echo $invoiceDetail['Item']['name']; ?>
              <?php echo $invoiceDetail['price']; ?>
              <?php echo $invoiceDetail['amount'] ?>

          <?php endforeach; ?>

              Total:
               <?php echo number_format((float)$invoice['Invoice']['total'], 2, '.', ''); ?>

              Amount in words: Rs.<?php echo $c2w ?>

It prints the pdf as follows:

But I need to print it as follows:

I have tried using line-height but it distorts the view because valign in td will not align the content at top.

With line-height:100px in TD print looks like follows:

Is there a way to fill the complete page by increasing the height of items table dynamically.

Body:
According to the documentation of mPDF library here, we can set the height of block level elements only. I was facing the same problem, then I moved my table inside a div and added height to the div like below.

<div height="870" style="border:solid 1px #ccc">
    <table class="table>
         Your table content here...
    </table>
</div>


问:
How to mock ObjectContext or ObjectQuery<T> in Entity Framework?
How to mock ObjectContext or ObjectQuery in Entity Framework?</p>

答:
I agree with the others you cannot really Mock ObjectContext. You should use EF DbContext because you can mock the underlying DbSet There are quite a lot of post how to do that. So I won't write how to do it. However if you absolutely must use ObjectContext (for some reason) and you want to Unit test it you can use InMemory database.

First install this Nuget package: Effort (Entity Framework Fake ObjectContext Realization Tool), which uses NMemory as the database. Install Effort.EF6 package:

PM> Install-Package Effort.EF6

```<code>using System;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Effort;

public class DbContextHelper
{
    //Fake object you can drop this if you are using your own EF context
    private class DbObject
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }

    //Fake EF context you can switch with you own EF context
    private class FakeDbContext : DbContext
    {
        public FakeDbContext(DbConnection connection)
            : base(connection, true) { }

        public virtual DbSet<DbObject> DbObjects { get; set; }
    }

    private FakeDbContext _dbContext;

    public DbContextHelper()
    {
        //In memory DB connection
        DbConnection effortConnection = DbConnectionFactory.CreatePersistent("TestInstanceName");
        _dbContext = new FakeDbContext(effortConnection);
    }

    //You can expose your context instead of the DbContext base type
    public DbContext DbContext => _dbContext;

    public ObjectContext ObjectContext => ((IObjectContextAdapter)_dbContext).ObjectContext;

    //Method to add Fake object to the fake EF context
    public void AddEntityWithState(string value, EntityState entityState)
    {
        DbContext.Entry(new DbObject() { Id = Guid.NewGuid(), Name = value }).State = entityState;
    }
}
</code>```

Usage:

```<code>DbContextHelper _dbContextHelper = new DbContextHelper();
_dbContextHelper.AddEntityWithState("added", System.Data.Entity.EntityState.Added);
_dbContextHelper.AddEntityWithState("added", System.Data.Entity.EntityState.Modified);

var objs = _dbContextHelper.ObjectContext.GetObjectStateEntries(EntityState.Modified | EntityState.Added);
</code>```

There you are you have your object in memory DB.

OwnerDisplayName: saeed

LastEditorDisplayName: saeed

Body:
I agree with the others you cannot really Mock ObjectContext. You should use EF DbContext because you can mock the underlying DbSet There are quite a lot of post how to do that. So I won't write how to do it. However if you absolutely must use ObjectContext (for some reason) and you want to Unit test it you can use InMemory database.

First install this Nuget package: Effort (Entity Framework Fake ObjectContext Realization Tool), which uses NMemory as the database. Install Effort.EF6 package:

PM> Install-Package Effort.EF6

using System;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Effort;

public class DbContextHelper
{
    //Fake object you can drop this if you are using your own EF context
    private class DbObject
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }

    //Fake EF context you can switch with you own EF context
    private class FakeDbContext : DbContext
    {
        public FakeDbContext(DbConnection connection)
            : base(connection, true) { }

        public virtual DbSet<DbObject> DbObjects { get; set; }
    }

    private FakeDbContext _dbContext;

    public DbContextHelper()
    {
        //In memory DB connection
        DbConnection effortConnection = DbConnectionFactory.CreatePersistent("TestInstanceName");
        _dbContext = new FakeDbContext(effortConnection);
    }

    //You can expose your context instead of the DbContext base type
    public DbContext DbContext => _dbContext;

    public ObjectContext ObjectContext => ((IObjectContextAdapter)_dbContext).ObjectContext;

    //Method to add Fake object to the fake EF context
    public void AddEntityWithState(string value, EntityState entityState)
    {
        DbContext.Entry(new DbObject() { Id = Guid.NewGuid(), Name = value }).State = entityState;
    }
}

Usage:

DbContextHelper _dbContextHelper = new DbContextHelper();
_dbContextHelper.AddEntityWithState("added", System.Data.Entity.EntityState.Added);
_dbContextHelper.AddEntityWithState("added", System.Data.Entity.EntityState.Modified);

var objs = _dbContextHelper.ObjectContext.GetObjectStateEntries(EntityState.Modified | EntityState.Added);

There you are you have your object in memory DB.


问:
Custom semi-generalized Factory for ViewModels
I'm trying to create a generalized ViewModelProvider.Factory to instantiate my ViewModels

```<code>class BundledAppFactory(private var bundle: AppParameterBundle) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
    Log.d("Factory", "Creating ${modelClass.canonicalName}")
    Log.d("Factory", "${modelClass.canonicalName} has ${modelClass.constructors.size} constructors and ${modelClass.declaredConstructors.size} declaredConstructors")

    modelClass.constructors.forEach {
        Log.d("Factory", "Constructor: $it")
    }
    return when {
        AppViewModel::class.java.isAssignableFrom(modelClass)               -> modelClass.getDeclaredConstructor(AppParameterBundle::class.java).newInstance(bundle)
        AppTeamUserViewModel::class.java.isAssignableFrom(modelClass)       -> modelClass.getDeclaredConstructor(AppTeamUserParameterBundle::class.java).newInstance(bundle)
        AppTeamUserHuntIdViewModel::class.java.isAssignableFrom(modelClass) -> modelClass.getDeclaredConstructor(AppTeamUserHuntIdParameterBundle::class.java).newInstance(bundle)
        AppStringViewModel::class.java.isAssignableFrom(modelClass)         -> modelClass.getDeclaredConstructor(AppStringParameterBundle::class.java).newInstance(bundle)
        else                                                                -> super.create(modelClass)
    }
}
}
</code>```

These are my bundles:

```<code>open class AppParameterBundle(val application: Application)

class AppStringParameterBundle(app: Application, val string: String) : AppParameterBundle(app)

class AppTeamUserParameterBundle(app: Application,
                             val team: Team,
                             val user: User) :
AppParameterBundle(app)

class AppTeamUserHuntIdParameterBundle(app: Application,
                                   val huntId: String,
                                   val team: Team,
                                   val user: User) : AppParameterBundle(app)
</code>```

And these are the base ViewModels that I extend with custom ViewModels:

```<code>abstract class AppViewModel<MODEL, EVENT : Any>(bundle: AppParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)
abstract class AppTeamUserViewModel<MODEL, EVENT : Any>(bundle: AppTeamUserParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)
abstract class AppTeamUserHuntIdViewModel<MODEL, EVENT : Any>(bundle: AppTeamUserHuntIdParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)
abstract class AppStringViewModel<MODEL, EVENT : Any>(bundle: AppStringParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)
</code>```

And an example of a ViewModel that extends from one of these:

```<code>class TeamViewModel(bundle: AppParameterBundle) : AppViewModel<TeamUiModel, TeamEvent>(bundle) {
...
}
</code>```

My problem is that

```<code>modelClass.getDeclaredConstructor(AppParameterBundle::class.java).newInstance(bundle)
</code>```

will not find any constructor and this lines

```<code>Log.d("Factory", "${modelClass.canonicalName} has ${modelClass.constructors.size} constructors and ${modelClass.declaredConstructors.size} declaredConstructors")
</code>```

comes up as this in the logs

```<code>mypackage.viewmodels.TeamViewModel has 0 constructors and 0 declaredConstructors
</code>```

This is what I get in the stacktrace:

```<code>Caused by: java.lang.NoSuchMethodException: <init> [class mypackage.ParameterBundle]
                                                   at java.lang.Class.getConstructor(Class.java:528)
                                                   at java.lang.Class.getDeclaredConstructor(Class.java:507)
                                                   at mypackage.viewmodels.BundledAppFactory.create(FactoriesAndBundles.kt:39)
                                                   at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:128)
                                                   at mypackage.TeamActivity.onCreate(TeamActivity.kt:41)
</code>```

Is this a Kotlin problem that there are no constructors? How do I fix this?

答:
It was a Proguard problem.
I had to add this lines to the .pro rules file</p>

```<code>-keep class mypackage.** { *; }

-keepclassmembers public class mypackage.** { *; }
</code>```

Body:
I'm trying to create a generalized ViewModelProvider.Factory to instantiate my ViewModels

class BundledAppFactory(private var bundle: AppParameterBundle) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
    Log.d("Factory", "Creating ${modelClass.canonicalName}")
    Log.d("Factory", "${modelClass.canonicalName} has ${modelClass.constructors.size} constructors and ${modelClass.declaredConstructors.size} declaredConstructors")

    modelClass.constructors.forEach {
        Log.d("Factory", "Constructor: $it")
    }
    return when {
        AppViewModel::class.java.isAssignableFrom(modelClass)               -> modelClass.getDeclaredConstructor(AppParameterBundle::class.java).newInstance(bundle)
        AppTeamUserViewModel::class.java.isAssignableFrom(modelClass)       -> modelClass.getDeclaredConstructor(AppTeamUserParameterBundle::class.java).newInstance(bundle)
        AppTeamUserHuntIdViewModel::class.java.isAssignableFrom(modelClass) -> modelClass.getDeclaredConstructor(AppTeamUserHuntIdParameterBundle::class.java).newInstance(bundle)
        AppStringViewModel::class.java.isAssignableFrom(modelClass)         -> modelClass.getDeclaredConstructor(AppStringParameterBundle::class.java).newInstance(bundle)
        else                                                                -> super.create(modelClass)
    }
}
}

These are my bundles:

open class AppParameterBundle(val application: Application)

class AppStringParameterBundle(app: Application, val string: String) : AppParameterBundle(app)

class AppTeamUserParameterBundle(app: Application,
                             val team: Team,
                             val user: User) :
AppParameterBundle(app)

class AppTeamUserHuntIdParameterBundle(app: Application,
                                   val huntId: String,
                                   val team: Team,
                                   val user: User) : AppParameterBundle(app)

And these are the base ViewModels that I extend with custom ViewModels:

abstract class AppViewModel<MODEL, EVENT : Any>(bundle: AppParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)
abstract class AppTeamUserViewModel<MODEL, EVENT : Any>(bundle: AppTeamUserParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)
abstract class AppTeamUserHuntIdViewModel<MODEL, EVENT : Any>(bundle: AppTeamUserHuntIdParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)
abstract class AppStringViewModel<MODEL, EVENT : Any>(bundle: AppStringParameterBundle) : BaseViewModel<MODEL, EVENT>(bundle)

And an example of a ViewModel that extends from one of these:

class TeamViewModel(bundle: AppParameterBundle) : AppViewModel<TeamUiModel, TeamEvent>(bundle) {
...
}

My problem is that

modelClass.getDeclaredConstructor(AppParameterBundle::class.java).newInstance(bundle)

will not find any constructor and this lines

Log.d("Factory", "${modelClass.canonicalName} has ${modelClass.constructors.size} constructors and ${modelClass.declaredConstructors.size} declaredConstructors")

comes up as this in the logs

mypackage.viewmodels.TeamViewModel has 0 constructors and 0 declaredConstructors

This is what I get in the stacktrace:

Caused by: java.lang.NoSuchMethodException: <init> [class mypackage.ParameterBundle]
                                                   at java.lang.Class.getConstructor(Class.java:528)
                                                   at java.lang.Class.getDeclaredConstructor(Class.java:507)
                                                   at mypackage.viewmodels.BundledAppFactory.create(FactoriesAndBundles.kt:39)
                                                   at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:128)
                                                   at mypackage.TeamActivity.onCreate(TeamActivity.kt:41)

Is this a Kotlin problem that there are no constructors? How do I fix this?

Body:
It was a Proguard problem.
I had to add this lines to the .pro rules file

-keep class mypackage.** { *; }

-keepclassmembers public class mypackage.** { *; }


问:
Vue.js one-way binding forms
I'm new with Vue.js and I'm trying to test some features of this framework.
Now I'm testing the input forms, and I would like to make a one-way binding, without using the v-model directive, but I can't find any example. Anyone could help me, please?

答:
Here is example of one way and two way binding

var V = new Vue({
  el:'#vue-instance',
  data:{
    name:'Niklesh'
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.4/vue.js"></script>
<div id="vue-instance">
<div>One Way binding with input box <input type="text" :value="name"></div>
<div>One Way binding as text {{name}}</div>

<div>Two way binding : <input type="text" v-model="name"></div>
</div></code>```

Title: Vue.js one-way binding forms

Body:
Here is example of one way and two way binding

var V = new Vue({
  el:'#vue-instance',
  data:{
    name:'Niklesh'
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.4/vue.js"></script>
<div id="vue-instance">
<div>One Way binding with input box <input type="text" :value="name"></div>
<div>One Way binding as text {{name}}</div>

<div>Two way binding : <input type="text" v-model="name"></div>
</div>


问:
What is the difference between map and flatMap and a good use case for each?
Can someone explain to me the difference between map and flatMap and what is a good use case for each?

What does "flatten the results" mean?
What is it good for?

答:
The difference can be seen from below sample pyspark code:</p>

```<code>rdd = sc.parallelize([2, 3, 4])
rdd.flatMap(lambda x: range(1, x)).collect()
Output:
[1, 1, 2, 1, 2, 3]

rdd.map(lambda x: range(1, x)).collect()
Output:
[[1], [1, 2], [1, 2, 3]]
</code>```

Body:
The difference can be seen from below sample pyspark code:

rdd = sc.parallelize([2, 3, 4])
rdd.flatMap(lambda x: range(1, x)).collect()
Output:
[1, 1, 2, 1, 2, 3]

rdd.map(lambda x: range(1, x)).collect()
Output:
[[1], [1, 2], [1, 2, 3]]


问:
Python code modification to make output file as XML and not CSV
The following code gives me the data for all the folders, subfolders and files along with the size of each. Currently, this is saving the data in a CSV file. But I believe this kind of data (nested data) is best suited for XML. I am not very well versed with XML. Any help to modify the code will be appreciated </p>

```<code>import os
import csv

def GetHumanReadable(size,precision=2):
    suffixes=['KB','MB','GB','TB']
    suffixIndex = 0
    while size > 1024:
        suffixIndex += 1 #increment the index of the suffix
        size = size/1024.0 #apply the division
    return "%.*f %s"%(precision,size,suffixes[suffixIndex])

def list_files(startpath):
    with open('output.csv','w') as file:
        for root, dirs, files in os.walk(startpath):
            level = root.replace(startpath, '').count(os.sep)
            indent = ' ,' * 4 * (level)
            file.write('{}{}/\n'.format(indent, os.path.basename(root)))
            subindent = ' ,' * 4 * (level + 1)
            for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
                converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
                file.write('{}{},{}\n'.format(subindent, f, converted_size))
</code>```

答:
You can take help of import xml.etree.ElementTree to make an output xml file.
here is an example</p>

```<code>import xml.etree.ElementTree as ET
data='''
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
'''
root= ET.XML(data)

with open('d:\output.xml', 'wb') as file:
    Et.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)
</code>```

Body:
The following code gives me the data for all the folders, subfolders and files along with the size of each. Currently, this is saving the data in a CSV file. But I believe this kind of data (nested data) is best suited for XML. I am not very well versed with XML. Any help to modify the code will be appreciated

import os
import csv

def GetHumanReadable(size,precision=2):
    suffixes=['KB','MB','GB','TB']
    suffixIndex = 0
    while size > 1024:
        suffixIndex += 1 #increment the index of the suffix
        size = size/1024.0 #apply the division
    return "%.*f %s"%(precision,size,suffixes[suffixIndex])

def list_files(startpath):
    with open('output.csv','w') as file:
        for root, dirs, files in os.walk(startpath):
            level = root.replace(startpath, '').count(os.sep)
            indent = ' ,' * 4 * (level)
            file.write('{}{}/\n'.format(indent, os.path.basename(root)))
            subindent = ' ,' * 4 * (level + 1)
            for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
                converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
                file.write('{}{},{}\n'.format(subindent, f, converted_size))

Body:
You can take help of import xml.etree.ElementTree to make an output xml file.
here is an example

import xml.etree.ElementTree as ET
data='''
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
'''
root= ET.XML(data)

with open('d:\output.xml', 'wb') as file:
    Et.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)


问:
Text Changed Event in UserControl is not firing in windows application
I create a usercontrol with textbox. But textbox text changedevent is not there. so i add textchanged event in the user control. Text changedevent is listing on the proerties window, but its not working(firing).

```<code>    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace TextBoxBorederUserControl
    {
    public partial class UserControl1 : UserControl
    {
    public event EventHandler TextBoxTextChanged;
    TextBox textBox;
    public void HandleTextBoxTextChanged(object sender, EventArgs e)
    {
        this.OnTextChanged(EventArgs.Empty);
    }
    protected virtual void OnTextBoxTextChanged(EventArgs e)
    {
        EventHandler handler = this.TextBoxTextChanged;
        if (handler != null)
        {
            handler(this,e);
        }

    }

        public UserControl1()
        {
            textBox = new TextBox()
            {
                BorderStyle = BorderStyle.FixedSingle,
                Multiline   = true,

                Location = new Point(-1, -1),
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                         AnchorStyles.Left | AnchorStyles.Right
            };
            textBox.TextChanged += this.HandleTextBoxTextChanged;
            Control container = new ContainerControl()
            {
                Dock = DockStyle.Fill,
                Padding = new Padding(-1)
            };
            container.Controls.Add(textBox);
            this.Controls.Add(container);
            FocusedBorderColor = System.Drawing.ColorTranslator.FromHtml("#66AFE9");////BLUE
            DefaultBorderColor = System.Drawing.ColorTranslator.FromHtml("#F1F1F1");///////////////////GRAY

            BackColor = DefaultBorderColor;
            Padding = new Padding(1);
            Size = textBox.Size;
        }

        public Color DefaultBorderColor { get; set; }

        public Color FocusedBorderColor { get; set; }

        public override string Text
        {
            get { return textBox.Text; }
            set { textBox.Text = value; }
        }

        protected override void OnEnter(EventArgs e)
        {
            BackColor = FocusedBorderColor;
            base.OnEnter(e);
        }

        protected override void OnLeave(EventArgs e)
        {
            BackColor = DefaultBorderColor;
            base.OnLeave(e);
        }

        protected override void SetBoundsCore(int x, int y,
            int width, int height, BoundsSpecified specified)
        {
            base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
        }

}
    }
</code>```

I create a usercontrol with textbox. But textbox text changedevent is not there. so i add textchanged event in the user control. Text changedevent is listing on the proerties window, but its not working(firing).

答:
Try this:</p>

```<code>public void HandleTextBoxTextChanged(object sender, EventArgs e)
{
    this.OnTextBoxTextChanged(EventArgs.Empty);
}
</code>```

Body:
I create a usercontrol with textbox. But textbox text changedevent is not there. so i add textchanged event in the user control. Text changedevent is listing on the proerties window, but its not working(firing).

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace TextBoxBorederUserControl
    {
    public partial class UserControl1 : UserControl
    {
    public event EventHandler TextBoxTextChanged;
    TextBox textBox;
    public void HandleTextBoxTextChanged(object sender, EventArgs e)
    {
        this.OnTextChanged(EventArgs.Empty);
    }
    protected virtual void OnTextBoxTextChanged(EventArgs e)
    {
        EventHandler handler = this.TextBoxTextChanged;
        if (handler != null)
        {
            handler(this,e);
        }

    }

        public UserControl1()
        {
            textBox = new TextBox()
            {
                BorderStyle = BorderStyle.FixedSingle,
                Multiline   = true,

                Location = new Point(-1, -1),
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                         AnchorStyles.Left | AnchorStyles.Right
            };
            textBox.TextChanged += this.HandleTextBoxTextChanged;
            Control container = new ContainerControl()
            {
                Dock = DockStyle.Fill,
                Padding = new Padding(-1)
            };
            container.Controls.Add(textBox);
            this.Controls.Add(container);
            FocusedBorderColor = System.Drawing.ColorTranslator.FromHtml("#66AFE9");////BLUE
            DefaultBorderColor = System.Drawing.ColorTranslator.FromHtml("#F1F1F1");///////////////////GRAY

            BackColor = DefaultBorderColor;
            Padding = new Padding(1);
            Size = textBox.Size;
        }

        public Color DefaultBorderColor { get; set; }

        public Color FocusedBorderColor { get; set; }

        public override string Text
        {
            get { return textBox.Text; }
            set { textBox.Text = value; }
        }

        protected override void OnEnter(EventArgs e)
        {
            BackColor = FocusedBorderColor;
            base.OnEnter(e);
        }

        protected override void OnLeave(EventArgs e)
        {
            BackColor = DefaultBorderColor;
            base.OnLeave(e);
        }

        protected override void SetBoundsCore(int x, int y,
            int width, int height, BoundsSpecified specified)
        {
            base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
        }

}
    }

I create a usercontrol with textbox. But textbox text changedevent is not there. so i add textchanged event in the user control. Text changedevent is listing on the proerties window, but its not working(firing).

Body:
Try this:

public void HandleTextBoxTextChanged(object sender, EventArgs e)
{
    this.OnTextBoxTextChanged(EventArgs.Empty);
}


问:
List comprehensions in Haskell
I want to write a simple list comprehension in Haskell which consists of a list of infinite primes.

My attempt:

```<code>isPrime 1 = False
isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]

primes = [x | x <-[1..], isPrime x ]
</code>```

But when I try running this on console as take 10 primes it gets stuck! What is the issue?

答:
The issue is in your isPrime function:

```<code>isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]
</code>```

You take each element from 1 to x-1, and check if the remainder is not equal to zero. If any values are equal to zero, then isPrime will return false.

However, you start your list comprehension at one, which every number is divisible by.

So, we just need to start at two instead.

```<code>isPrime x = and [x `mod` z /= 0 | z <- [2..x-1]]
</code>```

Now it works as expected.

```<code>λ> take 10 primes
[2,3,5,7,11,13,17,19,23,29]
</code>```

If you get a problem in a larger function, try breaking it down and running each individual part to ensure the results are as you expect. In this case, isPrime 2 == False hints to where the problem is.

Title: List comprehensions in Haskell

Body:
I want to write a simple list comprehension in Haskell which consists of a list of infinite primes.

My attempt:

isPrime 1 = False
isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]

primes = [x | x <-[1..], isPrime x ]

But when I try running this on console as take 10 primes it gets stuck! What is the issue?

Body:
The issue is in your isPrime function:

isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]

You take each element from 1 to x-1, and check if the remainder is not equal to zero. If any values are equal to zero, then isPrime will return false.

However, you start your list comprehension at one, which every number is divisible by.

So, we just need to start at two instead.

isPrime x = and [x `mod` z /= 0 | z <- [2..x-1]]

Now it works as expected.

λ> take 10 primes
[2,3,5,7,11,13,17,19,23,29]

If you get a problem in a larger function, try breaking it down and running each individual part to ensure the results are as you expect. In this case, isPrime 2 == False hints to where the problem is.


问:
Javascript regular expression string-replacement of multi-line strings
With JavaScript regular expression replace, trying to replace anything between  and  tags so that:

```<code><head>
   Multiline foo
</head>
<body>
  Multi line bar
</body>
</code>```

gets replaced into:

```<code><body>
  Multi line bar
</body>
</code>```

and trying with the very basic: /m which doesn't work. It works fine when line breaks are removed from string. No matter what type of line breaks, what's the magic?

答:
Alan is right, to summarize, use // and it should do what you wish.

The actual regex i'd use for the job is /([\s\S]*?)<\/head>/ but the difference probably won't matter, since it just assures there is no greedy matching with a 2nd head tag that should never be there :)

Body:
With JavaScript regular expression replace, trying to replace anything between  and  tags so that:

   Multiline foo

  Multi line bar

gets replaced into:

  Multi line bar

and trying with the very basic: /m which doesn't work. It works fine when line breaks are removed from string. No matter what type of line breaks, what's the magic?

Body:
Alan is right, to summarize, use /<head([\s\S]*)\/head>/ and it should do what you wish.

The actual regex i'd use for the job is /<head>([\s\S]*?)<\/head>/ but the difference probably won't matter, since it just assures there is no greedy matching with a 2nd head tag that should never be there :)


问:
Searching a nested list with recursion
I want to check if a certain number exists in a nested list

```<code>Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

if t==L:
    return True
else:

    return  ASearch(t, L[0]) or ASearch(t, L[1])

ASearch(15,Slist)
</code>```

What is the problem?

Update:

The OP meant to post this:

```<code>Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

    if t==L:
        return True
    return ASearch(t, L[0]) or ASearch(t, L[1])

print(ASearch(15, Slist))
print(ASearch(50, Slist))
</code>```

Expected output:

```<code>False
True
</code>```

Actual output:

```<code>TypeError: 'int' object is not subscriptable
</code>```

答:
One of the few problems in your code is that it can only return True.

What you want is probably this:

```<code>def ASearch(t, L):
    if type(L) == list:
        return any(ASearch(t, l) for l in L)
    else:
        return t == L
</code>```

Title: Searching a nested list with recursion

Body:
I want to check if a certain number exists in a nested list

Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

if t==L:
    return True
else:

    return  ASearch(t, L[0]) or ASearch(t, L[1])

ASearch(15,Slist)

What is the problem?

Update:

The OP meant to post this:

Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

    if t==L:
        return True
    return ASearch(t, L[0]) or ASearch(t, L[1])

print(ASearch(15, Slist))
print(ASearch(50, Slist))

Expected output:

False
True

Actual output:

TypeError: 'int' object is not subscriptable

Body:
One of the few problems in your code is that it can only return True.

What you want is probably this:

def ASearch(t, L):
    if type(L) == list:
        return any(ASearch(t, l) for l in L)
    else:
        return t == L


问:
why is my html root blank when using react-router into express locally
I am trying to get two routes working at the moment '/' and 'login' atm just using the same page. However, when I load the page through express and not webpack-dev-sever, I get a blank html page instead of the react-router loading. Not sure where to go from here.

I've seen examples I believe for express to just route directly to the html page, which I do here, I get no errors just a blank html, with 'root' id that it connects the react to.

folder
├── server.js
├── index.js(for final react render)
├── Src
│   ├── public
│   │   ├── index.js(empty html for react)
│   │
│   │__ components
│   │
│   │__routes
│   │  |__index.js(react-routes)
    |
    |__index.js(gathers all components to push to index.js next directory up)```
</div>
</div>
</p>

<p><strong>Server.js</strong></p>

```const express = require('express');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

app.get('/**', (req, res) => {
  res.sendFile(path.join(__dirname, '/src/public/index.html'));
});

app.listen(PORT, () => {
  console.log('server has started at:' + PORT);
});
```

<p><strong>Package.json</strong></p>

```{
  "name": "chauffeurus",
  "version": "1.0.0",
  "description": "new repo of previous group project similar to uber website",
  "main": "./index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server",
    "postinstall": "webpack -p",
    "start": "node server.js"
  },
  "keywords": [
    "reactjs",
    "javascript",
    "webpack",
    "mongoose",
    "mongodb"
  ],
  "author": "christian a.",
  "license": "ISC",
  "devDependencies": {
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-preset-latest": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "bcrypt-nodejs": "0.0.3",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.26.0",
    "mongoose": "^4.13.2",
    "passport": "^0.4.0",
    "react": "^15.4.1",
    "react-bootstrap": "^0.31.5",
    "react-dom": "^15.4.1",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^4.0.8",
    "redux": "^3.7.2",
    "webpack": "^1.14.0"
  }
}
```

<p><strong>Routes index.js</strong></p>

```import React from 'react'
import { Homepage } from '../index.js';
import { BrowserRouter, Route } from 'react-router-dom';

export default () => (
  <BrowserRouter>

      <Route path="/" exact component={Homepage} />
      <Route path="/login" exact component={Homepage} />

  </BrowserRouter>
)
```

<p><strong>index.js outside of src folder</strong></p>

```import React from 'react'
import ReactDOM from 'react-dom';
import { Homepage } from './src/index.js';
import Routes from './src/index.js';

ReactDOM.render(<Routes />, document.getElementById('root'));
```

<p><strong>Webpack.config.js</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const path = require('path');

//NPM Install that "tells the plugin to add any JavaScript into the bootom of the page...
// just before the closing body tag"
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './src/public/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = {
  entry: './index.js',
  output: {
    path:  __dirname + './dist',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.(png|jpg|gif)$/, loader: 'file-loader' }
    ]
  },
  plugins: [HtmlWebpackPluginConfig]
}</code>```

答:
I think the problem is you also need to serve your static assets. Include this line in your server.js:

```<code>// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
</code>```

You have to replace the code with your directories, I think public is the folder in your case ( where the built js files and images reside ).

Body:
I am trying to get two routes working at the moment '/' and 'login' atm just using the same page. However, when I load the page through express and not webpack-dev-sever, I get a blank html page instead of the react-router loading. Not sure where to go from here.

I've seen examples I believe for express to just route directly to the html page, which I do here, I get no errors just a blank html, with 'root' id that it connects the react to.

folder
├── server.js
├── index.js(for final react render)
├── Src
│   ├── public
│   │   ├── index.js(empty html for react)
│   │
│   │__ components
│   │
│   │__routes
│   │  |__index.js(react-routes)
    |
    |__index.js(gathers all components to push to index.js next directory up)

Server.js

const express = require('express');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

app.get('/**', (req, res) => {
  res.sendFile(path.join(__dirname, '/src/public/index.html'));
});

app.listen(PORT, () => {
  console.log('server has started at:' + PORT);
});

Package.json

{
  "name": "chauffeurus",
  "version": "1.0.0",
  "description": "new repo of previous group project similar to uber website",
  "main": "./index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server",
    "postinstall": "webpack -p",
    "start": "node server.js"
  },
  "keywords": [
    "reactjs",
    "javascript",
    "webpack",
    "mongoose",
    "mongodb"
  ],
  "author": "christian a.",
  "license": "ISC",
  "devDependencies": {
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-preset-latest": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "bcrypt-nodejs": "0.0.3",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.26.0",
    "mongoose": "^4.13.2",
    "passport": "^0.4.0",
    "react": "^15.4.1",
    "react-bootstrap": "^0.31.5",
    "react-dom": "^15.4.1",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^4.0.8",
    "redux": "^3.7.2",
    "webpack": "^1.14.0"
  }
}

Routes index.js

import React from 'react'
import { Homepage } from '../index.js';
import { BrowserRouter, Route } from 'react-router-dom';

export default () => (
  <BrowserRouter>

      <Route path="/" exact component={Homepage} />
      <Route path="/login" exact component={Homepage} />

  </BrowserRouter>
)

index.js outside of src folder

import React from 'react'
import ReactDOM from 'react-dom';
import { Homepage } from './src/index.js';
import Routes from './src/index.js';

ReactDOM.render(<Routes />, document.getElementById('root'));

Webpack.config.js

const path = require('path');

//NPM Install that "tells the plugin to add any JavaScript into the bootom of the page...
// just before the closing body tag"
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './src/public/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = {
  entry: './index.js',
  output: {
    path:  __dirname + './dist',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.(png|jpg|gif)$/, loader: 'file-loader' }
    ]
  },
  plugins: [HtmlWebpackPluginConfig]
}

Body:
I think the problem is you also need to serve your static assets. Include this line in your server.js:

// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));

You have to replace the code with your directories, I think public is the folder in your case ( where the built js files and images reside ).


问:
Angular 2, can't get data after subscribe in ngOnInit
I have a problem, maybe I don't understand how to do but when I try to catch data from an HttpRequest during angular ngOnInit, my console.log return me an "undefined" value.
The thing is that when I use this value in my template view it works !

Here is my Component

```<code>export class ReferentielFormComponent implements OnInit {
  id: number;
  currentUser;
  referentiel;
  progressValue: number;
  formGroup: FormGroup;
  isNew: boolean;

  constructor(private service: AppService,
          private referentiels: ReferentielService,
          private router: ActivatedRoute,
          private config: NgbTabsetConfig) {
  }

  ngOnInit() {
    this.router.params.subscribe((params: Params) => this.id = params['id']);
    if (this.id) {
      this.referentiels.getReferentiel(this.id).subscribe(data => this.referentiel = data);
    } else {
      this.referentiel = {};
    }
    this.isNew = !this.referentiel;

    console.log(this.referentiel);
    console.log(this.isNew);
    this.progressValue = 20;

    this.formGroup = new FormGroup({
      titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
        Validators.required,
      ]),
      description: new FormControl(!this.isNew ? this.referentiel.description : '', [
        Validators.required,
      ])
    });
  }
}
</code>```

The variable this.referentiel return me an undefined so I can't bind my Form whith existing value because of that...

Any suggestions ?

答:
Try this:

```<code>    ngOnInit() {
        this.router.params.subscribe((params: Params) => this.id = params['id']
        if (this.id) {
          this.referentiels.getReferentiel(this.id).subscribe(data => this.referentiel = data);
        } else {
          this.referentiel = {};
        }
        this.isNew = !this.referentiel;

        console.log(this.referentiel);
        console.log(this.isNew);
        this.progressValue = 20;

        this.formGroup = new FormGroup({
          titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
            Validators.required,
          ]),
          description: new FormControl(!this.isNew ? this.referentiel.description : '', [
            Validators.required,
          ])
        });
        );
      }
</code>```

this.is isn't defined yet outside the subscribe.

Body:
I have a problem, maybe I don't understand how to do but when I try to catch data from an HttpRequest during angular ngOnInit, my console.log return me an "undefined" value.
The thing is that when I use this value in my template view it works !

Here is my Component

export class ReferentielFormComponent implements OnInit {
  id: number;
  currentUser;
  referentiel;
  progressValue: number;
  formGroup: FormGroup;
  isNew: boolean;

  constructor(private service: AppService,
          private referentiels: ReferentielService,
          private router: ActivatedRoute,
          private config: NgbTabsetConfig) {
  }

  ngOnInit() {
    this.router.params.subscribe((params: Params) => this.id = params['id']);
    if (this.id) {
      this.referentiels.getReferentiel(this.id).subscribe(data => this.referentiel = data);
    } else {
      this.referentiel = {};
    }
    this.isNew = !this.referentiel;

    console.log(this.referentiel);
    console.log(this.isNew);
    this.progressValue = 20;

    this.formGroup = new FormGroup({
      titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
        Validators.required,
      ]),
      description: new FormControl(!this.isNew ? this.referentiel.description : '', [
        Validators.required,
      ])
    });
  }
}

The variable this.referentiel return me an undefined so I can't bind my Form whith existing value because of that...

Any suggestions ?

Body:
Try this:

    ngOnInit() {
        this.router.params.subscribe((params: Params) => this.id = params['id']
        if (this.id) {
          this.referentiels.getReferentiel(this.id).subscribe(data => this.referentiel = data);
        } else {
          this.referentiel = {};
        }
        this.isNew = !this.referentiel;

        console.log(this.referentiel);
        console.log(this.isNew);
        this.progressValue = 20;

        this.formGroup = new FormGroup({
          titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
            Validators.required,
          ]),
          description: new FormControl(!this.isNew ? this.referentiel.description : '', [
            Validators.required,
          ])
        });
        );
      }

this.is isn't defined yet outside the subscribe.


答:
Try like this :

Type 1 :

```<code>ngOnInit() {
    this.router.params.subscribe((params: Params) => {
        this.load(params['id']);
    });
}

load(id) {
    this.id = id;
    console.log('this.id', this.id);
}
</code>```

Type 2 :

```<code>ngOnInit() {
    this.router.params.subscribe((params: Params) => {
        this.id = params['id'];
    }, () => {
        console.log('this.id', this.id);
    });
}
</code>```

Title: Angular 2, can't get data after subscribe in ngOnInit

Body:
Try like this :

Type 1 :

ngOnInit() {
    this.router.params.subscribe((params: Params) => {
        this.load(params['id']);
    });
}

load(id) {
    this.id = id;
    console.log('this.id', this.id);
}

Type 2 :

ngOnInit() {
    this.router.params.subscribe((params: Params) => {
        this.id = params['id'];
    }, () => {
        console.log('this.id', this.id);
    });
}


问:
How can I create a data structure starting at a specified memory address (without using new)?
I asked a similar question before, but I only realized now that the answer I received isn't totally what I wanted.

If I simply have a pointer of some structure type, how can I either move to, or create an instance of the same structure type starting at an address specified by the struct pointer (which I have assigned an address to) without using "new".

答:
If you are considering only C, where there is no constructors, once you have a pointer to a block of memory that is at least as big as the struct, then just casting that pointer to the appropriate type is sufficient.

If you are talking about C++, then it depends on the actual type. Whether it is spelled as struct or class does not make a real difference here. If the type has a trivial constructor then you can use the same approach than in C, as the constructor  will effectively do nothing at all. If the object has a non-trivial constructor, then you need to call the constructor, and that has to be done with placement new.


问:
Linq order IEnumerable (by the enumerated elements themselves)
This might seem like an obvious question, and probably there will be previous questions about this topic, please point out and close if necesary because I can't find them.

Is there any Linq extension method that returns an ordered sequence by the elements themselves? I know it can be achieved by:

```<code>IEnumerable<int> myIntegers = new int[]{4, 6, 34, 987, -13};
IEnumerable<int> myOrderedIntegers = myIntegers.OrderBy(i => i);
</code>```

I don't like this, it seems too verbose for such a simple operation. I know I could also do:

```<code>List<int> myOtherOrderedIntegers = myIntegers.ToList();
myOtherOrderedIntegers.Sort();
</code>```

But uugh... bye bye deferred evaluation, and even more verbose. I could write my extension methods like...

```<code>public static IEnumerable<T> Order<T>(this IEnumerable<T> elements) => elements.OrderBy(e => e);
public static IEnumerable<T> OrderDescending<T>(this IEnumerable<T> elements) => elements.OrderByDescending(e => e);
</code>```

Is there already any Linq extension method that can achieve this simple operation? I find it extrange that it isn't implemented already.

Thanks in advance.

答: Is there any other, less verbose method than myIntegers.OrderBy(i => i)? Like myIntegers.Order()? No there is not. You can write them yourself if you want to, you already pasted the code. You will have to live with the 8 bytes of wasted space in your source.

Body:
This might seem like an obvious question, and probably there will be previous questions about this topic, please point out and close if necesary because I can't find them.

Is there any Linq extension method that returns an ordered sequence by the elements themselves? I know it can be achieved by:

IEnumerable<int> myIntegers = new int[]{4, 6, 34, 987, -13};
IEnumerable<int> myOrderedIntegers = myIntegers.OrderBy(i => i);

I don't like this, it seems too verbose for such a simple operation. I know I could also do:

List<int> myOtherOrderedIntegers = myIntegers.ToList();
myOtherOrderedIntegers.Sort();

But uugh... bye bye deferred evaluation, and even more verbose. I could write my extension methods like...

public static IEnumerable<T> Order<T>(this IEnumerable<T> elements) => elements.OrderBy(e => e);
public static IEnumerable<T> OrderDescending<T>(this IEnumerable<T> elements) => elements.OrderByDescending(e => e);

Is there already any Linq extension method that can achieve this simple operation? I find it extrange that it isn't implemented already.

Thanks in advance.


问:
how to fetch json with foreach in angular2
Hi guys I'm working on Angular application and I would like some help to fetch the data from the json. I've got my conpoments.ts with my method but it is not working. I included the json file. please help me to display the data on html page.Thank you</p>

```<code>label: "car"
manufacture:Array(3)
{id: "1", label: "name", question: "", type: "type", value: {…}}
{id: "2", label: "name", question: "", type: "type", value: {…}}
{id: "3", label: "name", question: "", type: "type", value: {…}}

import { Component, OnInit } from '@angular/core';

import { ManufactureService } from '../../services/ManufactureService/manufacture.service';

@Component({
  selector: 'body-content',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component.less']
})
export class BodyComponent implements OnInit {
  constructor(public
  manufactureService:ManufactureService) { }
  async ngOnInit() {

  const [err,data] = await  this. manufactureService.getManufature('car','man').toPromise()

   if (err) {
        console.log(err)
        return false
    }

    showCar(data){
    data.forEach(el=>{
      this.manufactureService.getManufature.push();
    })
  }

  }
}
</code>```

答:
Try This :

import HttpClientModule in app.module.ts

```<code>export class MyComponent implements OnInit {

  constructor(private manufactureService: ManufactureService) {}

  ngOnInit(): void {
    this. manufactureService.getManufature(subscribe(data => {
      console.log("results :", data)
      data.forEach(el=>{
        this.manufactureService.getManufature.push();
    })
    },error => {
      console.log("Error :", error)
    });
  }
}
</code>```

Service Function :

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

constructor(private http: HttpClient) {}

getManufature(){
    return this.http.get('path or url to JSON');
}
</code>```

Body:
Hi guys I'm working on Angular application and I would like some help to fetch the data from the json. I've got my conpoments.ts with my method but it is not working. I included the json file. please help me to display the data on html page.Thank you

label: "car"
manufacture:Array(3)
{id: "1", label: "name", question: "", type: "type", value: {…}}
{id: "2", label: "name", question: "", type: "type", value: {…}}
{id: "3", label: "name", question: "", type: "type", value: {…}}

import { Component, OnInit } from '@angular/core';

import { ManufactureService } from '../../services/ManufactureService/manufacture.service';

@Component({
  selector: 'body-content',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component.less']
})
export class BodyComponent implements OnInit {
  constructor(public
  manufactureService:ManufactureService) { }
  async ngOnInit() {

  const [err,data] = await  this. manufactureService.getManufature('car','man').toPromise()

   if (err) {
        console.log(err)
        return false
    }

    showCar(data){
    data.forEach(el=>{
      this.manufactureService.getManufature.push();
    })
  }

  }
}

Body:
Try This :

import HttpClientModule in app.module.ts

export class MyComponent implements OnInit {

  constructor(private manufactureService: ManufactureService) {}

  ngOnInit(): void {
    this. manufactureService.getManufature(subscribe(data => {
      console.log("results :", data)
      data.forEach(el=>{
        this.manufactureService.getManufature.push();
    })
    },error => {
      console.log("Error :", error)
    });
  }
}

Service Function :

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

constructor(private http: HttpClient) {}

getManufature(){
    return this.http.get('path or url to JSON');
}


问:
ActiveRecord::SerializationTypeMismatch: attribute was supposed to be a Hash, but was a String
To get a hash I have this:

```<code>serialize :colors, Hash
</code>```

But I have an error where it the result of this attribute looks like this:

To show this I took out the "Hash" from "serialize :colors, Hash" to see the error in the console.

```<code>"--- !map:ActiveSupport::HashWithIndifferentAccess \none: \"#87466d\"\ntwo: \"#307065\"\nthree: \"#c04992\"\nfour: \"#ffffff\"\nfive: \"#636467\"\n"
</code>```

Not sure what's happened but seems like the Hash has become a string and I don't' know why. I didn't used to have this problem but I now have two versions of this project where the first is in rails 2 and the other is in rails 3 and I switch between the two. I feel like the error has occurred since going to rails 3 and coming back into rails 2. Anyone know how I can fix this error and why it has occurred?

I looked at a similar post and it hasn't helped me:
"Attribute was supposed to be a Hash, but was a String"

答:
OK so I fixed it by going into the database and setting the attribute to NULL so that it clears it. As I use MySQL I did the following:

Open Mysql

mysql -u root -D database_name -p

Updated the attribute in Mysql to reset the value:

UPDATE colors_table SET colors = null WHERE id = 1;

Then I was able to update the values in the rails console without errors.

Body:
To get a hash I have this:

serialize :colors, Hash

But I have an error where it the result of this attribute looks like this:

To show this I took out the "Hash" from "serialize :colors, Hash" to see the error in the console.

"--- !map:ActiveSupport::HashWithIndifferentAccess \none: \"#87466d\"\ntwo: \"#307065\"\nthree: \"#c04992\"\nfour: \"#ffffff\"\nfive: \"#636467\"\n"

Not sure what's happened but seems like the Hash has become a string and I don't' know why. I didn't used to have this problem but I now have two versions of this project where the first is in rails 2 and the other is in rails 3 and I switch between the two. I feel like the error has occurred since going to rails 3 and coming back into rails 2. Anyone know how I can fix this error and why it has occurred?

I looked at a similar post and it hasn't helped me:
"Attribute was supposed to be a Hash, but was a String"


问:
Get first 9 elements from Google RSS feed xml in PHP
I'm currently working with Google RSS feeds. I received this XML response.

```<code><rss version="2.0">
<channel>
<generator>NFE/1.0</generator>
<title>blockchain - Google News</title>
<link>...</link>
<language>en</language>
<webMaster>news-feedback@google.com</webMaster>
<copyright>©2017 Google</copyright>
<pubDate>Fri, 17 Nov 2017 09:41:26 GMT</pubDate>
<lastBuildDate>Fri, 17 Nov 2017 09:41:26 GMT</lastBuildDate>
<image>...</image>
<description>Google News</description>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</channel>
</rss>
</code>```

I'm using this foreach() to loop through all items:

```<code>$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

foreach ($rss->channel->item as $item) {
    echo $item->title."<br/>";
    echo $item->link."<br/>";
    echo $item->pubDate."<br/>";
}
</code>```

But this foreach returns me all items.

How can I get only first 9 items from this XML?

答:
Well I found the answer:</p>

```<code>   $i = 0;

   foreach ($rss->channel->item as $item) {
      $i++;

      echo $item->title."<br/>";
      echo $item->link."<br/>";
      echo $item->pubDate."<br/>";

      if($i == 10) break;
   }
</code>```

Body:
I'm currently working with Google RSS feeds. I received this XML response.

<rss version="2.0">
<channel>
<generator>NFE/1.0</generator>
<title>blockchain - Google News</title>
<link>...</link>
<language>en</language>
<webMaster>news-feedback@google.com</webMaster>
<copyright>©2017 Google</copyright>
<pubDate>Fri, 17 Nov 2017 09:41:26 GMT</pubDate>
<lastBuildDate>Fri, 17 Nov 2017 09:41:26 GMT</lastBuildDate>
<image>...</image>
<description>Google News</description>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</channel>
</rss>

I'm using this foreach() to loop through all items:

$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

foreach ($rss->channel->item as $item) {
    echo $item->title."
";
    echo $item->link."
";
    echo $item->pubDate."
";
}

But this foreach returns me all items.

How can I get only first 9 items from this XML?

Body:
Well I found the answer:

   $i = 0;

   foreach ($rss->channel->item as $item) {
      $i++;

      echo $item->title."<br/>";
      echo $item->link."<br/>";
      echo $item->pubDate."<br/>";

      if($i == 10) break;
   }