问:
dropdown not updating from Knockout array
I am updating my Knockout object in Knockout and am verifying via the console that it is getting updated correctly.  But the dropdown is not getting refreshed with the new value.  If I refresh the page manually, the dropdown will be updated.  I think I need to make something observable, but not totally sure.

This is my KO viewmodel:

```<code>var SellerViewModel = function(groups) {
        var self = this;

        self.json = groups;
        self.groups = ko.computed(function() {
            var opts = [];
            for(var key in self.json)
            {
                if(self.json.hasOwnProperty(key))
                {
                    opts.push({Text: self.json[key].majorGroup + " / " + self.json[key].minorGroup, Value: self.json[key].groupId});
                }
            }
            return opts;
        });

        self.addGroup = function(json) {
            var group = JSON.parse(json);
            self.json.push(
                {
                    "ExtensionData":{},
                    "contractId":"10006",
                    "groupId":group.groupID,
                    "imageId":null,
                    "majorGroup":group.majorGroup,
                    "minorGroup":group.minorGroup
                }
            );
            console.log(JSON.stringify(self.json));
        };
</code>```

And my HTML dropdown:

```<code><select data-bind="value: roomID, options: $root.groups, optionsValue: 'Value', optionsText: 'Text', optionsCaption: ' -- select a room --', disable: disableRoom" class="form-control" id="@roomID"></select>
</code>```

And finally, this is how the dropdown gets populated on pageload:

```<code>var groups = @Html.Raw( Json.Encode(ViewBag.GroupDetail.SellerGroup) );
sellerViewModel = new SellerViewModel(groups);
</code>```

Forgot to add one last snippet.  This is how I am adding an additional item into the knockout object, which is supposed to update the dropdown.

```<code>var json = '{"majorGroup" : "' + major + '", "minorGroup" : "' + minor + '", "groupID" : "' + groupID + '" }';
sellerViewModel.addGroup(json);
</code>```

My guess is that self.groups needs to be an observable array.  But I don't know how to do that because I set it equal to ko.computed already.

答:
As @pimbrouwers already mentioned, you need to make json an observableArray if you want the UI updated whenever the array changes.

```<code>self.json = ko.observableArray(groups);
</code>```

You can make some improvements to your code. Instead of looping through indexes of self.json and checking hasOwnProperty, you could use map:

```<code>self.groups = ko.computed(function() {
    // if "json" is not an observableArray, then "self.json.map"
    return self.json().map(function(group) {
      return {
        Text: group.majorGroup + " / " + group.minorGroup,
        Value: group.groupId
      }
    })
});
</code>```

And you are concatenating and forming a json in string format and then parsing it back. Instead, you could send an object itself.

```<code>var group = {
  majorGroup: major,
  minorGroup: minor,
  groupID: groupID
}

sellerViewModel.addGroup(group);
</code>```

And remove the JSON.parse() from the self.addGroup.

Here's a fiddle for testing with all these changes

You can also go through this answer to know more about the difference between json and javascript object literal

Body:
I am updating my Knockout object in Knockout and am verifying via the console that it is getting updated correctly.  But the dropdown is not getting refreshed with the new value.  If I refresh the page manually, the dropdown will be updated.  I think I need to make something observable, but not totally sure.

This is my KO viewmodel:

var SellerViewModel = function(groups) {
        var self = this;

        self.json = groups;
        self.groups = ko.computed(function() {
            var opts = [];
            for(var key in self.json)
            {
                if(self.json.hasOwnProperty(key))
                {
                    opts.push({Text: self.json[key].majorGroup + " / " + self.json[key].minorGroup, Value: self.json[key].groupId});
                }
            }
            return opts;
        });

        self.addGroup = function(json) {
            var group = JSON.parse(json);
            self.json.push(
                {
                    "ExtensionData":{},
                    "contractId":"10006",
                    "groupId":group.groupID,
                    "imageId":null,
                    "majorGroup":group.majorGroup,
                    "minorGroup":group.minorGroup
                }
            );
            console.log(JSON.stringify(self.json));
        };

And my HTML dropdown:

<select data-bind="value: roomID, options: $root.groups, optionsValue: 'Value', optionsText: 'Text', optionsCaption: ' -- select a room --', disable: disableRoom" class="form-control" id="@roomID"></select>

And finally, this is how the dropdown gets populated on pageload:

var groups = @Html.Raw( Json.Encode(ViewBag.GroupDetail.SellerGroup) );
sellerViewModel = new SellerViewModel(groups);

Forgot to add one last snippet.  This is how I am adding an additional item into the knockout object, which is supposed to update the dropdown.

var json = '{"majorGroup" : "' + major + '", "minorGroup" : "' + minor + '", "groupID" : "' + groupID + '" }';
sellerViewModel.addGroup(json);

My guess is that self.groups needs to be an observable array.  But I don't know how to do that because I set it equal to ko.computed already.

Body:
As @pimbrouwers already mentioned, you need to make json an observableArray if you want the UI updated whenever the array changes.

self.json = ko.observableArray(groups);

You can make some improvements to your code. Instead of looping through indexes of self.json and checking hasOwnProperty, you could use map:

self.groups = ko.computed(function() {
    // if "json" is not an observableArray, then "self.json.map"
    return self.json().map(function(group) {
      return {
        Text: group.majorGroup + " / " + group.minorGroup,
        Value: group.groupId
      }
    })
});

And you are concatenating and forming a json in string format and then parsing it back. Instead, you could send an object itself.

var group = {
  majorGroup: major,
  minorGroup: minor,
  groupID: groupID
}

sellerViewModel.addGroup(group);

And remove the JSON.parse() from the self.addGroup.

Here's a fiddle for testing with all these changes

You can also go through this answer to know more about the difference between json and javascript object literal


来源: stackexchange

问:
Correct way to check if value exists and is an array with items
So one way to do it would be..

```<code>if(isset($arrayVar)) {
    if(is_array($arrayVar)) {
        if(count($arrayVar) > 0) {
            // Success
            print_r($arrayVar);
        }
    }
}
</code>```

Are there any better ways?

答:
You can do it using is_array and empty:

```<code>if (!empty($arrayVar) && is_array($arrayVar)) {
 // ...
}
</code>```

empty() will check if isset and not empty at once.

ContentLicense: CC BY-SA 3.0

Body:
So one way to do it would be..

if(isset($arrayVar)) {
    if(is_array($arrayVar)) {
        if(count($arrayVar) > 0) {
            // Success
            print_r($arrayVar);
        }
    }
}

Are there any better ways?

Body:
You can do it using is_array and empty:

if (!empty($arrayVar) && is_array($arrayVar)) {
 // ...
}

empty() will check if isset and not empty at once.


问:
How to upload Images in codeigniter with mysql database
Note is that : All data is inserted properly.
               But if i'm upload an image with the help of
               $this->upload->do_upload();and validate id,

               this is not properly working. can u suggest..

```<code>//Controller

public function saveEmployeea()
    {

      $config = [ 'upload_path'=>'./uploads',
          'allowed_types'=>'gif|jpg|png|jpeg'];

      $this->load->library('upload', $config);

      $this->form_validation->set_rules('dept_name', 'Department', 'required');

      $this->form_validation->set_rules('firstname', 'First Name','required');

      $this->form_validation->set_rules('middlename', 'Middle Name','required');

      $this->form_validation->set_rules('lastname', 'Last Name','required');

      $this->form_validation->set_rules('gendar', 'Gendar','required');

      $this->form_validation->set_rules('address1', 'Local Address','required');

      $this->form_validation->set_rules('address2', 'Permant Address','required');

      $this->form_validation->set_rules('nationality', 'Nationality','required');

      $this->form_validation->set_rules('date_of_joining', 'Joinig Date','required');

      $this->form_validation->set_rules('current_designation', 'Designation_Curnt','required');

      // $this->form_validation->set_rules('profile_image', 'Please Upload image','required');

      $this->form_validation->set_rules('prof_email_id', 'Professional Email Id','required|valid_email');

      $this->form_validation->set_rules('personal_email', 'Personal Email Id','required|valid_email');
      $this->form_validation->set_rules('personal_no', 'Personal Contact No','required');

      $this->form_validation->set_rules('emergency_no', 'Emergency No','required');

      $this->form_validation->set_rules('highest_qualification', 'Highest Qualificatio','required');

      $this->form_validation->set_rules('year_of_passing', 'Year Of Passing','required');

      $this->form_validation->set_rules('university', 'University','required');

      $this->form_validation->set_rules('no_experience', 'No Experience','required');

      $this->form_validation->set_rules('pre_compony', 'Previus Compony','required');

      $this->form_validation->set_rules('pre_designation', 'Previus Designation','required');
      $this->form_validation->set_rules('pre_organisation_location', 'Previus organisation_location','required');

      if ( $this->form_validation->run() && $this->upload->do_upload())
      {

        $data = $this->input->post();

        // insert images in data variables by using upload object oprater.
        $upload_info = $this->upload->data();

        //set path for images store
        $path = base_url("uploads/".$upload_info['raw_name'].$upload_info['file_ext']);

        $data['profile_image'] = $path;

        // echo '```';
        // print_r($data);
        // echo '```';
        // var_dump($data);
        // exit();

        // Load Model to Call Model class
        $this->load->model('Loginm');

        if($this->Loginm->insertEmployee($data))
        {
          $this->session->set_flashdata('employee_details','Employee Details Added Successfully');
        }
        else
        {
          $this->session->set_flashdata('employee_details','Failed To Added Employee Details.');
        }
          return redirect('Employee/EmployeeList');

      }
      else
      {
        $upload_error = $this->upload->display_errors();
        $this->createEmployee();
      }
    }

// Model

public function insertEmployee($data)
{
    return $this->db->insert('employee',$data);
}`enter code here`
</code>```

答:
Try this code</p>

```<code>$config['upload_path']    = 'd:/www/project_name/uploads/'; //document root path
$config['allowed_types']  = 'jpg|gif|png';
$config['file_name']      = $_FILES['profile_image']['name'];

//load upload class library
$this->load->library('upload', $config);

if (!$this->upload->do_upload('profile_image'))
{
        // case - failure
        echo $this->upload->display_errors();
}
else
{
    // case - SUCCESS
}
</code>```

Body:
Note is that : All data is inserted properly.
               But if i'm upload an image with the help of
               $this->upload->do_upload();and validate id,

               this is not properly working. can u suggest..

//Controller

public function saveEmployeea()
    {

      $config = [ 'upload_path'=>'./uploads',
          'allowed_types'=>'gif|jpg|png|jpeg'];

      $this->load->library('upload', $config);

      $this->form_validation->set_rules('dept_name', 'Department', 'required');

      $this->form_validation->set_rules('firstname', 'First Name','required');

      $this->form_validation->set_rules('middlename', 'Middle Name','required');

      $this->form_validation->set_rules('lastname', 'Last Name','required');

      $this->form_validation->set_rules('gendar', 'Gendar','required');

      $this->form_validation->set_rules('address1', 'Local Address','required');

      $this->form_validation->set_rules('address2', 'Permant Address','required');

      $this->form_validation->set_rules('nationality', 'Nationality','required');

      $this->form_validation->set_rules('date_of_joining', 'Joinig Date','required');

      $this->form_validation->set_rules('current_designation', 'Designation_Curnt','required');

      // $this->form_validation->set_rules('profile_image', 'Please Upload image','required');

      $this->form_validation->set_rules('prof_email_id', 'Professional Email Id','required|valid_email');

      $this->form_validation->set_rules('personal_email', 'Personal Email Id','required|valid_email');
      $this->form_validation->set_rules('personal_no', 'Personal Contact No','required');

      $this->form_validation->set_rules('emergency_no', 'Emergency No','required');

      $this->form_validation->set_rules('highest_qualification', 'Highest Qualificatio','required');

      $this->form_validation->set_rules('year_of_passing', 'Year Of Passing','required');

      $this->form_validation->set_rules('university', 'University','required');

      $this->form_validation->set_rules('no_experience', 'No Experience','required');

      $this->form_validation->set_rules('pre_compony', 'Previus Compony','required');

      $this->form_validation->set_rules('pre_designation', 'Previus Designation','required');
      $this->form_validation->set_rules('pre_organisation_location', 'Previus organisation_location','required');

      if ( $this->form_validation->run() && $this->upload->do_upload())
      {

        $data = $this->input->post();

        // insert images in data variables by using upload object oprater.
        $upload_info = $this->upload->data();

        //set path for images store
        $path = base_url("uploads/".$upload_info['raw_name'].$upload_info['file_ext']);

        $data['profile_image'] = $path;

        // echo '
';
        // print_r($data);
        // echo '
';
        // var_dump($data);
        // exit();

        // Load Model to Call Model class
        $this->load->model('Loginm');

        if($this->Loginm->insertEmployee($data))
        {
          $this->session->set_flashdata('employee_details','Employee Details Added Successfully');
        }
        else
        {
          $this->session->set_flashdata('employee_details','Failed To Added Employee Details.');
        }
          return redirect('Employee/EmployeeList');

      }
      else
      {
        $upload_error = $this->upload->display_errors();
        $this->createEmployee();
      }
    }

// Model

public function insertEmployee($data)
{
    return $this->db->insert('employee',$data);
}`enter code here`

Body:
Try this code

$config['upload_path']    = 'd:/www/project_name/uploads/'; //document root path
$config['allowed_types']  = 'jpg|gif|png';
$config['file_name']      = $_FILES['profile_image']['name'];

//load upload class library
$this->load->library('upload', $config);

if (!$this->upload->do_upload('profile_image'))
{
        // case - failure
        echo $this->upload->display_errors();
}
else
{
    // case - SUCCESS
}


答:
```<code>if (!empty($arrayVar) && is_array($arrayVar))
</code>```

!empty covers both isset and empty arrays (all falsey values in fact), you then just need to confirm that it's also actually an array.

Title: Correct way to check if value exists and is an array with items

Body:
if (!empty($arrayVar) && is_array($arrayVar))

!empty covers both isset and empty arrays (all falsey values in fact), you then just need to confirm that it's also actually an array.


问:
Specialize templated function in class
I am currently getting into templates and I am trying to fully specialize a class function here in my class (only relevant code):

```<code>class item_t
{
public:
    template<class T>
    void set(const std::string &key, const T &value);
    template<>
    void set(const std::string &key, const std::string &value);
};
</code>```

which will result in this compiler error (gcc 6.3.0):

```<code>Fehler: explicit specialization in non-namespace scope ‘class base::data::item_t’
  template<>
           ^
</code>```

What am I missing here? From what I understood, it is not possible to partially specialize a function template, but this is a full specialization.

答:
You cannot explicitly specialize a template member function inside the class definition. You have to do it outside (in a namespace scope):

```<code>class item_t
{
public:
    template<class T>
    void set(const std::string &key, const T &value);

};

template<>
void item_t::set<std::string>(const std::string &key, const std::string &value)
{
}
</code>```

In your particular use case, you don't even need a specialization - an overload will work just fine:

```<code>template<class T>
void set(const std::string &key, const T &value);

void set(const std::string &key, const std::string &value);
</code>```

Title: Specialize templated function in class

Body:
I am currently getting into templates and I am trying to fully specialize a class function here in my class (only relevant code):

class item_t
{
public:
    template<class T>
    void set(const std::string &key, const T &value);
    template<>
    void set(const std::string &key, const std::string &value);
};

which will result in this compiler error (gcc 6.3.0):

Fehler: explicit specialization in non-namespace scope ‘class base::data::item_t’
  template<>
           ^

What am I missing here? From what I understood, it is not possible to partially specialize a function template, but this is a full specialization.

Body:
You cannot explicitly specialize a template member function inside the class definition. You have to do it outside (in a namespace scope):

class item_t
{
public:
    template<class T>
    void set(const std::string &key, const T &value);

};

template<>
void item_t::set<std::string>(const std::string &key, const std::string &value)
{
}

In your particular use case, you don't even need a specialization - an overload will work just fine:

template<class T>
void set(const std::string &key, const T &value);

void set(const std::string &key, const std::string &value);


问:
Why overloaded methods defined in OOPS?
Interviewer had asked me what is method overloading and I had given answer saying, method overloading is within same class where two or more methods have same name but different signature, with following example -

```<code>//method with two parameters
public int add(int a, int b){
  return a + b;
}

//method with three parameters
public int add(int a, int b, int c){
  return a + b + c;
}
</code>```

To this example, he said why do we need two methods with same name i.e. add. Instead we can have two methods with different names i.e. addTwoNumbers and addThreeNumbers which indicates, method names are more verbose and if we follow this approach, we don't need method overloading. (And same is true for other Java apis where method overloading is used.)

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

答: In my opinion it was introduced in order to avoid any confusion. Since both the methods performs same operation it might be easy for a programmer to search for the same method name performing the same functionality rather than finding methods with different name performing same functionality.</p>

Title: Why overloaded methods defined in OOPS?

Body:
Interviewer had asked me what is method overloading and I had given answer saying, method overloading is within same class where two or more methods have same name but different signature, with following example -

//method with two parameters
public int add(int a, int b){
  return a + b;
}

//method with three parameters
public int add(int a, int b, int c){
  return a + b + c;
}

To this example, he said why do we need two methods with same name i.e. add. Instead we can have two methods with different names i.e. addTwoNumbers and addThreeNumbers which indicates, method names are more verbose and if we follow this approach, we don't need method overloading. (And same is true for other Java apis where method overloading is used.)

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?


问:
Interacting with multiple servers over SSH in PHP
I'm currently writing a deployment framework in PHP.  The framework connects to servers and executes commands over SSH.  I've been looking for quite a while trying to find a way in PHP to do this better.  Here are the requirements.  The technique should be able to:

Enter the SSH password programmatically.  I know that using SSH keys is the way to go when you want password-less SSH logons, but remember, this is a deployment framework.  It could potentially be deploying to 25 servers at a time.  It doesn't seem right to require the user to have set up SSH keys to use the framework, and who wants to enter their password 25 times?  I'm using Capistrano as a model here - it asks for your password once, then uses it to establish the SSH connections without re-prompting the user.  I'm not suggesting the passwords be stored in the deploy script, just (silently) entered once and used until the deploy tasks are finished.

Send output to the PHP script.  I would like to be able to intercept the terminal output from each of the SSH sessions independently, modify it, then send it back to the terminal for the user to see.  This way, I can prepend the name of the server onto each line of output to show what's going on.

Provide write (as well as read) access to the terminal.  It's important that the user (or the script) be able to enter other information into the terminal besides just the SSH password.

Support SSH v2.

Currently, my framework "compiles" the commands from the deploy script into one giant string and executes them by using the SSH command.  Each final deploy command looks something like this:

ssh -t -t -p 12345 user@server.com 'command1; command2;'

Each of these SSH commands is executed via PHP's built-in passthru function:

<?php passthru("ssh -t -t -p 12345 user@server.com 'command1; command2;'"); ?>

I have tried using proc_open and nearly all of PHP's other command-executing functions to no avail - none of them provide all the functionality I've listed above.  In addition, I've tried several pure PHP SSH implementations, also to no avail.  The libraries either don't supply write access to the terminal or don't support SSH v2.

Any help on this would be greatly appreciated - thanks in advance!

答:
I'm not sure php is the right tool here. Why not use something that is closer to the shell environment, like a bash script?

The only reason I can imagine you want to use PHP is so you can start the process by clicking a link on a page somewhere, and thereby punch a large hole in whatever security your system supposedly has. But if you really must, then it is still easier to write a script in a more shell friendly language and simply use php as a gateway to invoke the script.

ContentLicense: CC BY-SA 2.5


问:
How to use Type as a parameter but restrict it to a base class at compile time
When a user changes an answer to a question, I want them to specify the reason from a set of reasons, and depending on the reason chosen, I want to create a specific subclass. So I want to hold the type to create in the ChangeReason class. I can do it like this, checking that the type is specified correctly at run-time:

```<code>public class ChangeReason
{
    Type _TypeToCreate;

    public void SetQuestionType(Type value)
    {
        if (!value.IsSubclassOf(typeof(BaseAnsweredQuestion)))
            throw new InvalidOperationException("Invalid Type");

        _TypeToCreate = value;
    }
}
</code>```

Is there a way to restrict the type at compile time, perhaps using a generic method? I'd like to call it like this:

```<code>var reason = new ChangeReason();
reason.SetQuestionType(typeof(AnsweredQuestion));
</code>```

答:
A generic method definition has a placeholder for the type e.g. <T>. This is the type parameter or argument.
It is a way of making the method type safe, and the type argument can be accessed from inside the method. There is therefore no need to pass the type as a method argument.

Generic methods can be restricted to a specified base class or derivatives of that base class by adding a constraint: where T : <base class name>.

And if the base class is abstract, adding the new() constraint also prevents the base type being used.

```<code>public void SetQuestionType<T>() where T: BaseAnsweredQuestion, new()
{
    _TypeToCreate = typeof(T);
}
</code>```

And then you can call it using:

```<code>reason.SetQuestionType<AnsweredQuestion>();
</code>```

instead of:

```<code>reason.SetQuestionType(typeof(AnsweredQuestion));
</code>```

Body:
When a user changes an answer to a question, I want them to specify the reason from a set of reasons, and depending on the reason chosen, I want to create a specific subclass. So I want to hold the type to create in the ChangeReason class. I can do it like this, checking that the type is specified correctly at run-time:

public class ChangeReason
{
    Type _TypeToCreate;

    public void SetQuestionType(Type value)
    {
        if (!value.IsSubclassOf(typeof(BaseAnsweredQuestion)))
            throw new InvalidOperationException("Invalid Type");

        _TypeToCreate = value;
    }
}

Is there a way to restrict the type at compile time, perhaps using a generic method? I'd like to call it like this:

var reason = new ChangeReason();
reason.SetQuestionType(typeof(AnsweredQuestion));

Body:
A generic method definition has a placeholder for the type e.g. <T>. This is the type parameter or argument.
It is a way of making the method type safe, and the type argument can be accessed from inside the method. There is therefore no need to pass the type as a method argument.

Generic methods can be restricted to a specified base class or derivatives of that base class by adding a constraint: where T : <base class name>.

And if the base class is abstract, adding the new() constraint also prevents the base type being used.

public void SetQuestionType<T>() where T: BaseAnsweredQuestion, new()
{
    _TypeToCreate = typeof(T);
}

And then you can call it using:

reason.SetQuestionType<AnsweredQuestion>();

instead of:

reason.SetQuestionType(typeof(AnsweredQuestion));


问:
Unable to get file stream on Xiaomi
I've build a blogger client where you can pick photos from gallery to embed on blog posts.

For some reason it doesn't work on Xiaomi phones on the majority of phones it works.

I'm picking files from gallery this way:

```<code>Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);

startActivityForResult(i, 2);
</code>```

I'm using the following to load the pictures after selection:

```<code>String imagePath=data.getData().ToString();
Uri fileURI = Uri.parse(imagePath);
 try {
      fileInputStream = ((Context)mView).getContentResolver().openInputStream(fileURI);
 } catch (Exception e) {
/* Send logs to analyse later */
 }
</code>```

Which results on the following error on some phones

```<code>Non-fatal Exception: java.io.FileNotFoundException: file:/storage/emulated/0/Download/FILE_NAME.png: open failed: ENOENT (No such file or directory)
       at libcore.io.IoBridge.open(IoBridge.java:456)
       at java.io.FileInputStream.(FileInputStream.java)
</code>```

I'm only letting the user try to pick files after receiving permission on Marshmallow+ versions, so it's not a permission issue.

It works on 95 ish % of users so this is something very specific.
Tried to reproduce the issue on 4.2, 4.4, 5.0.2, 7.0.2 on LG G2, Huawei Nova, Nexus 7 and emulator images, i was unable to reproduce it.

Any thoughts ?

答:
In onActivityResult() use

```<code>  InputStream is = getContentResolver().openInputStream(data.getData());
</code>```

Do not try to find a file.

Use the input stream as if it were the file input stream.

Title: Unable to get file stream on Xiaomi

Body:
I've build a blogger client where you can pick photos from gallery to embed on blog posts.

For some reason it doesn't work on Xiaomi phones on the majority of phones it works.

I'm picking files from gallery this way:

Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);

startActivityForResult(i, 2);

I'm using the following to load the pictures after selection:

String imagePath=data.getData().ToString();
Uri fileURI = Uri.parse(imagePath);
 try {
      fileInputStream = ((Context)mView).getContentResolver().openInputStream(fileURI);
 } catch (Exception e) {
/* Send logs to analyse later */
 }

Which results on the following error on some phones

Non-fatal Exception: java.io.FileNotFoundException: file:/storage/emulated/0/Download/FILE_NAME.png: open failed: ENOENT (No such file or directory)
       at libcore.io.IoBridge.open(IoBridge.java:456)
       at java.io.FileInputStream.(FileInputStream.java)

I'm only letting the user try to pick files after receiving permission on Marshmallow+ versions, so it's not a permission issue.

It works on 95 ish % of users so this is something very specific.
Tried to reproduce the issue on 4.2, 4.4, 5.0.2, 7.0.2 on LG G2, Huawei Nova, Nexus 7 and emulator images, i was unable to reproduce it.

Any thoughts ?

Body:
In onActivityResult() use

  InputStream is = getContentResolver().openInputStream(data.getData());

Do not try to find a file.

Use the input stream as if it were the file input stream.


问:
predict is not giving the highest probability
I am using SVM from sklearn (Python 3). The predicted class probability is lesser than the highest probability among all classes. Can somebody explain this.

```<code>    clf = Pipeline([('vect', TfidfVectorizer()), ('clf', svm.SVC())])
    parameters = {'vect__ngram_range': [(1, 2)], 'vect__stop_words': ['english'],
                  'vect__lowercase': [True], 'clf__C': [1,2, 5, 10, 20, 100],
                  'clf__kernel': [str('linear')], 'clf__class_weight':['balanced'],
                  'clf__probability': [True]}
    vec_clf = GridSearchCV(clf, parameters, scoring='f1_weighted')
    vec_clf.fit(x_train, y_train)
</code>```

Print statements.

```<code>    pred_data = model.predict(input_series)
    probability_lst = model.predict_proba(input_series)[0]
    print ("probability lst: ", probability_lst)
    print ("predicted data: ", pred_data)
    print ("classes: ", model.best_estimator_.classes_)
</code>```

This is the code I am using. Please find the below print output.

```<code>    probability lst:  [ 0.29004279  0.38866277  0.04441053  0.1173824   0.0300703   0.0983329   0.03109831]
    predicted data:  ['1']
    classes:  ['1' '2' '3' '4' '5' '6' '7']
</code>```

Logically it should predict class "2" as it has highest probability. Please explain this output

答:
I have read some docs on predict, I think it works in different way not synced with predict_proba.

So using predic_proba and taking the highest probability and its corresponding class(from model.classes_)

We can close this ticket.

Body:
I am using SVM from sklearn (Python 3). The predicted class probability is lesser than the highest probability among all classes. Can somebody explain this.

    clf = Pipeline([('vect', TfidfVectorizer()), ('clf', svm.SVC())])
    parameters = {'vect__ngram_range': [(1, 2)], 'vect__stop_words': ['english'],
                  'vect__lowercase': [True], 'clf__C': [1,2, 5, 10, 20, 100],
                  'clf__kernel': [str('linear')], 'clf__class_weight':['balanced'],
                  'clf__probability': [True]}
    vec_clf = GridSearchCV(clf, parameters, scoring='f1_weighted')
    vec_clf.fit(x_train, y_train)

Print statements.

    pred_data = model.predict(input_series)
    probability_lst = model.predict_proba(input_series)[0]
    print ("probability lst: ", probability_lst)
    print ("predicted data: ", pred_data)
    print ("classes: ", model.best_estimator_.classes_)

This is the code I am using. Please find the below print output.

    probability lst:  [ 0.29004279  0.38866277  0.04441053  0.1173824   0.0300703   0.0983329   0.03109831]
    predicted data:  ['1']
    classes:  ['1' '2' '3' '4' '5' '6' '7']

Logically it should predict class "2" as it has highest probability. Please explain this output


问:
How to read macOS desktop file in cocoa app
I want to make cocoa app execute .sh file or other Operation,
this my code:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);
}

- (NSString *)cmd:(NSString *)cmd
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/bash"];
    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
    [task setArguments: arguments];
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    NSFileHandle *file = [pipe fileHandleForReading];
    [task launch];
    NSData *data = [file readDataToEndOfFile];
    return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}
</code>```

but log error：

```<code>ls: .: Operation not permitted
</code>```

how to do that?I search about macOS permit,Do I need use SMJobBless ?

答:
Sandbox applications aren't allowed to read outside the application folder. So in order for your script to work you need to turn off Sandbox.

Also you need to change the path like Sangram S. mentioned or set the current directory to the home folder:

```<code>[task setCurrentDirectoryPath:NSHomeDirectory()];
</code>```

Body:
I want to make cocoa app execute .sh file or other Operation,
this my code:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);
}

- (NSString *)cmd:(NSString *)cmd
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/bash"];
    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
    [task setArguments: arguments];
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    NSFileHandle *file = [pipe fileHandleForReading];
    [task launch];
    NSData *data = [file readDataToEndOfFile];
    return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}

but log error：

ls: .: Operation not permitted

how to do that?I search about macOS permit,Do I need use SMJobBless ?

Body:
Sandbox applications aren't allowed to read outside the application folder. So in order for your script to work you need to turn off Sandbox.

Also you need to change the path like Sangram S. mentioned or set the current directory to the home folder:

[task setCurrentDirectoryPath:NSHomeDirectory()];


问:
Make input type file required based on condition in AngularJS
I am receiving a JSON data from backend like these

```<code>{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Vertrag unterzeichnen",
        "long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"HR unterrichten",
        "long_text":"HR hat eigene Workflows",
        "is_photo":true
      }
    ]
  }
}
</code>```

And in the html i am populating a form by ng-repeat

```<code><tr data-ng-repeat="choice in choices track  by $index">
    <td>{{choice.number}}</td>
    <td><p>{{choice.short_text}}</p></td>
    <td><input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required></td>
    <td><input type="checkbox"  ng-model="choice.include"></td>
    <td><input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">
    </td>
</tr>
</code>```

Now I want to make the input type file required if the value of is_photo is true in the JSON I am receiving. For each row if the value if is_photo is false then it will be not required.

From the given JSON the condition will be the first input type file will be not required as first row is_photo is false, but the second one will be required as the value of is_photo is true.

How will I do that?

答:
you use this use

it will set automatically if _photo is true it make as required

```<code><input name="myInput" ng-model="myInput" ng-required="_photo">
</code>```

Body:
I am receiving a JSON data from backend like these

{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Vertrag unterzeichnen",
        "long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"HR unterrichten",
        "long_text":"HR hat eigene Workflows",
        "is_photo":true
      }
    ]
  }
}

And in the html i am populating a form by ng-repeat

    {{choice.number}}

{{choice.short_text}}

    <input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required>
    <input type="checkbox"  ng-model="choice.include">
    <input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">

Now I want to make the input type file required if the value of is_photo is true in the JSON I am receiving. For each row if the value if is_photo is false then it will be not required.

From the given JSON the condition will be the first input type file will be not required as first row is_photo is false, but the second one will be required as the value of is_photo is true.

How will I do that?

Body:
you use this use

it will set automatically if _photo is true it make as required

<input name="myInput" ng-model="myInput" ng-required="_photo">


问:
Trying to assign a value in a variable and used it in proc in Oracle
i am trying to assign a value in a variable "slno" use it to insert value in table "Par_conn" . but it is giving error while executing the Procedure with parameter.Any help would be appreciated.
Table

```<code>create table PAR_CONN

    (
      CUSTOMER_ID   NUMBER(10) not null,
      CUSTOMER_NAME VARCHAR2(50) not null,
      CITY          VARCHAR2(50)
    )
</code>```

Store Procedure

```<code>CREATE OR REPLACE PROCEDURE sp_insert(CUSTOMER_NAME IN VARCHAR2,CITY IN VARCHAR2)
IS
   Declare  slno number;
BEGIN
    select count(*) into slno from Par_conn;
    insert into Par_conn values(slno,CUSTOMER_NAME,CITY);
    commit;
 END;
</code>```

Executing SP:

```<code>Begin
   sp_insert('ramesh','dispur');
  end;
</code>```

答:
Please do not reinvent wheel.

You probably aimed for:

```<code>CREATE OR REPLACE PROCEDURE sp_insert(CUSTOMER_NAME IN VARCHAR2,CITY IN VARCHAR2)
IS
    slno number;
BEGIN
    select max(id_col_name)+1 into slno from Par_conn;
    insert into Par_conn values(slno,CUSTOMER_NAME,CITY);
    commit;
 END;
</code>```

to set id value. I would strongly recommend to use SEQUENCE or IDENTITY.
Also you should always specify column list:

```<code>insert into Par_conn(col1_name, col2_name, col3_name)
values(slno,CUSTOMER_NAME,CITY);
</code>```

Body:
i am trying to assign a value in a variable "slno" use it to insert value in table "Par_conn" . but it is giving error while executing the Procedure with parameter.Any help would be appreciated.
Table

create table PAR_CONN

    (
      CUSTOMER_ID   NUMBER(10) not null,
      CUSTOMER_NAME VARCHAR2(50) not null,
      CITY          VARCHAR2(50)
    )

Store Procedure

CREATE OR REPLACE PROCEDURE sp_insert(CUSTOMER_NAME IN VARCHAR2,CITY IN VARCHAR2)
IS
   Declare  slno number;
BEGIN
    select count(*) into slno from Par_conn;
    insert into Par_conn values(slno,CUSTOMER_NAME,CITY);
    commit;
 END;

Executing SP:

Begin
   sp_insert('ramesh','dispur');
  end;

Body:
Please do not reinvent wheel.

You probably aimed for:

CREATE OR REPLACE PROCEDURE sp_insert(CUSTOMER_NAME IN VARCHAR2,CITY IN VARCHAR2)
IS
    slno number;
BEGIN
    select max(id_col_name)+1 into slno from Par_conn;
    insert into Par_conn values(slno,CUSTOMER_NAME,CITY);
    commit;
 END;

to set id value. I would strongly recommend to use SEQUENCE or IDENTITY.
Also you should always specify column list:

insert into Par_conn(col1_name, col2_name, col3_name)
values(slno,CUSTOMER_NAME,CITY);


问:
Can not read property 'push' of undefined
I can not read property of push of undefined. Why is it undefined? When I do console.log(columnsArray[i]) it shows me the value. I don't understand.

```<code>var columnsArray = ["col1","col2","col3"];
var indexArray = [];
function submitIndex() {
  for (var i = 0; i <= columnsArray.length ; i++) {
    if ($("#" + columnsArray[i]).is(":checked") === true) {
      indexArray.push(columnsArray[i]);
    } else {
      console.log(columnsArray[i] + "is not checked");
    }
  }
  var indexArray = indexArray.filter(onlyUnique);
  console.log(indexArray);
}
</code>```

答:
Please see my fiddle here for error replicated and then see the solution here

Things to note are these

```<code>var columnsArray = ["col1","col2","col3"];
var indexArray = [];
function submitIndex(indexArray) {
  for (var i = 0; i < columnsArray.length ; i++) //you dont need to go till
  columnsArray length as this is 0 based indexed array not 1 so removed =
  from here
  {
 console.log('i='+i+' and columnsArray[i]='+columnsArray[i]);
  if ($("#" + columnsArray[i]).is(":checked") === true) {
     indexArray.push(columnsArray[i]);
   } else {
     console.log(columnsArray[i] + "is not checked");
   }
  }
 // var indexArray = indexArray.filter(onlyUnique); I dont have onlyUnique
 filter so commented out
 console.log(indexArray);
 }
 submitIndex(indexArray);
</code>```

You need to iterate array upto length-1 so you can remove equality comparison for .length of an array

Pass the parameter to function and use that it would be more cleaner and you can do this with other checkboxes as well

Not sure about your onlyUnique filter so commented out but you should be able to use it and

Dont use var to declare variable again to declare the array again instead place the filtered result in another array and return that array.

Body:
I can not read property of push of undefined. Why is it undefined? When I do console.log(columnsArray[i]) it shows me the value. I don't understand.

var columnsArray = ["col1","col2","col3"];
var indexArray = [];
function submitIndex() {
  for (var i = 0; i <= columnsArray.length ; i++) {
    if ($("#" + columnsArray[i]).is(":checked") === true) {
      indexArray.push(columnsArray[i]);
    } else {
      console.log(columnsArray[i] + "is not checked");
    }
  }
  var indexArray = indexArray.filter(onlyUnique);
  console.log(indexArray);
}

Body:
Please see my fiddle here for error replicated and then see the solution here

Things to note are these

var columnsArray = ["col1","col2","col3"];
var indexArray = [];
function submitIndex(indexArray) {
  for (var i = 0; i < columnsArray.length ; i++) //you dont need to go till
  columnsArray length as this is 0 based indexed array not 1 so removed =
  from here
  {
 console.log('i='+i+' and columnsArray[i]='+columnsArray[i]);
  if ($("#" + columnsArray[i]).is(":checked") === true) {
     indexArray.push(columnsArray[i]);
   } else {
     console.log(columnsArray[i] + "is not checked");
   }
  }
 // var indexArray = indexArray.filter(onlyUnique); I dont have onlyUnique
 filter so commented out
 console.log(indexArray);
 }
 submitIndex(indexArray);

You need to iterate array upto length-1 so you can remove equality comparison for .length of an array

Pass the parameter to function and use that it would be more cleaner and you can do this with other checkboxes as well

Not sure about your onlyUnique filter so commented out but you should be able to use it and

Dont use var to declare variable again to declare the array again instead place the filtered result in another array and return that array.


问:
How to get data in deeply nested JSON (more than 5 layers)
I use a Teleport API. Their JSON data is heavily nested and I'm struggling to get the relevant data.

The data is as below. I want to get the data in categories.

```<code>{
 "_embedded": {
 "city:search-results": [
  {
    "_embedded": {
      "city:item": {
        "_embedded": {
          "city:urban_area": {
            "_embedded": {
              "ua:scores": {
                "_links": {
                  "self": {
                    "href": "https://api.teleport.org/api/urban_areas/slug:tokyo/scores/"
                  }
                },
                "categories": [
                  {
                    "color": "#f3c32c",
                    "name": "Housing",
                    "score_out_of_10": 5.710999999999999
                  },
                  {
                    "color": "#f3d630",
                    "name": "Cost of Living",
                    "score_out_of_10": 3.343
                  },.....
</code>```

The code.  I use React, Redux and Lodash and I tried to iterate the data by map function.

```<code> let item;
   if(this.props.data) {
          item = _.map(this.props.data._embedded.city:search-results._embedded.city:item._embedded.city:urban_area._embedded.ua:scores.categories,
    /** This nested props doesn't work **/
    data => {
    return (
             <div>
             <h2>{data.name}</h2>
             <p>{data.score_out_of_10}</p>
             </div>
         )
     })
</code>```

Is there a better way to iterate the data in heavily nested JSON data?

答:
You seem to have a syntax error in your code as : is a reserved word. You should access your properties this way instead

this.props.data["_embedded.city:search-results"] ...

Side Note: You might want to check if nested properties exist before accessing them in order to avoid the error cannot access property pp of undefined

Body:
I use a Teleport API. Their JSON data is heavily nested and I'm struggling to get the relevant data.

The data is as below. I want to get the data in categories.

{
 "_embedded": {
 "city:search-results": [
  {
    "_embedded": {
      "city:item": {
        "_embedded": {
          "city:urban_area": {
            "_embedded": {
              "ua:scores": {
                "_links": {
                  "self": {
                    "href": "https://api.teleport.org/api/urban_areas/slug:tokyo/scores/"
                  }
                },
                "categories": [
                  {
                    "color": "#f3c32c",
                    "name": "Housing",
                    "score_out_of_10": 5.710999999999999
                  },
                  {
                    "color": "#f3d630",
                    "name": "Cost of Living",
                    "score_out_of_10": 3.343
                  },.....

The code.  I use React, Redux and Lodash and I tried to iterate the data by map function.

 let item;
   if(this.props.data) {
          item = _.map(this.props.data._embedded.city:search-results._embedded.city:item._embedded.city:urban_area._embedded.ua:scores.categories,
    /** This nested props doesn't work **/
    data => {
    return (

{data.name}

{data.score_out_of_10}

         )
     })

Is there a better way to iterate the data in heavily nested JSON data?


问:
junit spring boot profile properties not being read
I am trring to read a value from the properties file in my junit setup using spring boot.
I can not read the value. Below is my content:-

application-test.properties

```<code>my.user.name=Amar
</code>```

COnfig file to create beans:

```<code>@Configuration
@ActiveProfiles("test")
@Profile("test")
public class RdbmsTestConfig {

    @Value("${my.user.name}")
    private String name;

    @Bean
    public String myString(){
        return "Amar";
    }

    @Bean
    public PropsHolder propsHolder() {
        PropsHolder propsHolder = new PropsHolder();
        propsHolder.setUserName(name);
        return propsHolder;
    }
 }
</code>```

My test class:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
public class TestRoomService {

    @Autowired
    @Qualifier("myString")
    private String myString;

    @Autowired
    private PropsHolder propsHolder;

    @Autowired
    private Environment env;

    @Test
    public void userTest() {
        Arrays.stream(env.getActiveProfiles()).forEach(System.out::println);
        System.out.println(propsHolder.getUserName());
        Assert.assertNotNull(myString);
        Assert.assertEquals("Amar",myString);
    }
}
</code>```

The value for propsHolder.getUserName comes out to be ${my.user.name}

答:
I created a base test class that has the required annotations:-

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
@SpringBootTest
public abstract class BastTest { }
</code>```

@ActiveProfiles set the profile to use used, I dont have to mention it in the application.properties file

My test class now extends this:-

```<code>public class TestRoomService extends BastTest
</code>```

In my RdbmsTestConfig remove @ActiveProfiles annotation.

Body:
I am trring to read a value from the properties file in my junit setup using spring boot.
I can not read the value. Below is my content:-

application-test.properties

my.user.name=Amar

COnfig file to create beans:

@Configuration
@ActiveProfiles("test")
@Profile("test")
public class RdbmsTestConfig {

    @Value("${my.user.name}")
    private String name;

    @Bean
    public String myString(){
        return "Amar";
    }

    @Bean
    public PropsHolder propsHolder() {
        PropsHolder propsHolder = new PropsHolder();
        propsHolder.setUserName(name);
        return propsHolder;
    }
 }

My test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
public class TestRoomService {

    @Autowired
    @Qualifier("myString")
    private String myString;

    @Autowired
    private PropsHolder propsHolder;

    @Autowired
    private Environment env;

    @Test
    public void userTest() {
        Arrays.stream(env.getActiveProfiles()).forEach(System.out::println);
        System.out.println(propsHolder.getUserName());
        Assert.assertNotNull(myString);
        Assert.assertEquals("Amar",myString);
    }
}

The value for propsHolder.getUserName comes out to be ${my.user.name}

Body:
I created a base test class that has the required annotations:-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
@SpringBootTest
public abstract class BastTest { }

@ActiveProfiles set the profile to use used, I dont have to mention it in the application.properties file

My test class now extends this:-

public class TestRoomService extends BastTest

In my RdbmsTestConfig remove @ActiveProfiles annotation.


问:
JS function split not working letters uppercase
Example 1:

```<code>var string_1 = "My name is Tom Jelly";
var param = string_1.split('Tom');
console.log(param);
</code>```

["My name is ", " Jelly"]

Example 2:

```<code>var string_2 = "My name is tom Jelly";
var param = string_2.split('Tom');
console.log(param);
</code>```

["My name is tom Jelly"]

How can I get the result as Example 1?

答:
Firstly, .split() is case insensitive.
so,

```<code>var param = string_2.split('Tom');
</code>```

should be like

```<code>var param = string_2.split('tom');
</code>```

Body:
Example 1:

var string_1 = "My name is Tom Jelly";
var param = string_1.split('Tom');
console.log(param);

["My name is ", " Jelly"]

Example 2:

var string_2 = "My name is tom Jelly";
var param = string_2.split('Tom');
console.log(param);

["My name is tom Jelly"]

How can I get the result as Example 1?

Body:
Firstly, .split() is case insensitive.
so,

var param = string_2.split('Tom');

should be like

var param = string_2.split('tom');


问:
Have you ever obtained a significant speedup by using boost::pool?
I've played with boost::pool a few times in places where it seemed to me I was seriously hammering the heap with a lot of object "churn".  Generally I've used boost::object_pool, or boost::pool_alloc as an STL template parameter.  However the result is invariably that performance is virtually unchanged, or significantly worsened.

I'm curious to hear of any success stories with it.

What sort of things should I look for in profiling output which might indicate boost::pool is likely to help ?

Is it just actually pretty hard to improve on good old malloc ?

答:
You might want to track down your performance problems to memory allocations first before you start to optimize for that.

So, narrow down your profiling to pinpoint the location of the problem. This can be lots of calls to the same code that might not take long when only called once.

OwnerDisplayName: timday

OwnerDisplayName: HS


问:
Limit on how much data can be returned by Json Post?
I have read that you should not use get json for retrieving sensitive data and you should instead use json post.

I am wondering though what is the limit you can send back. I know with http post there is a limited(I forgot how much).

Does the same limit apply to json post?

答: If you use JSON over an unencrypted http connection, it doesn't really matter if it's a POST or a GET, your data will be sent in clear text and anyone with a network sniffer will be able to read the sensitive data.</p>


问:
The second parameter in my class is an array. I am not sure how to write in the main Program
In the following code :

```<code>#include<iostream>
#include <string>
using namespace std;

class BookType{

private:

    string Title;
    string Authors[4];
    string Authors;
}
</code>```

Here is the main program:

```<code>int main() {
    BookType Book2("Sweet",["lil,lool,lal,ln"],"ssss",29288308.47,8,3,2);
}
</code>```

I get this error: expected primary-expression before '[' token

答:
You are calling the constructor of BookType but you didn't define one. Here is an example

```<code>#include <iostream>
#include <string>
#include <vector>
#include <initializer_list>

class BookType {
public:
    BookType(std::string s1, std::initializer_list<std::string> l, std::string s2, double d, int i1, int i2, int i3): title(s1), authors(l) {}

private:

    std::string title;
    std::vector<std::string> authors;
    std::string Authors;
};

int main() {
    BookType Book2("Sweet",{"lil","lool","lal","ln"},"ssss",29288308.47,8,3,2);
    return 0;
}
</code>```

I added the constructor

```<code>BookType(std::string s1, std::initializer_list<std::string> l, std::string s2, double d, int i1, int i2, int i3): title(s1), authors(l) {}
</code>```

and changed your array of Authors into a std::vector of authors. std::vectors are easier to handle and can be initialized with an std::initializer_list. Also a std::initializer_list is passed to the constructor. ["lil,lool,lal,ln"] is no array.

Body:
In the following code :

#include<iostream>
#include <string>
using namespace std;

class BookType{

private:

    string Title;
    string Authors[4];
    string Authors;
}

Here is the main program:

int main() {
    BookType Book2("Sweet",["lil,lool,lal,ln"],"ssss",29288308.47,8,3,2);
}

I get this error: expected primary-expression before '[' token

Body:
You are calling the constructor of BookType but you didn't define one. Here is an example

#include <iostream>
#include <string>
#include <vector>
#include <initializer_list>

class BookType {
public:
    BookType(std::string s1, std::initializer_list<std::string> l, std::string s2, double d, int i1, int i2, int i3): title(s1), authors(l) {}

private:

    std::string title;
    std::vector<std::string> authors;
    std::string Authors;
};

int main() {
    BookType Book2("Sweet",{"lil","lool","lal","ln"},"ssss",29288308.47,8,3,2);
    return 0;
}

I added the constructor

BookType(std::string s1, std::initializer_list<std::string> l, std::string s2, double d, int i1, int i2, int i3): title(s1), authors(l) {}

and changed your array of Authors into a std::vector of authors. std::vectors are easier to handle and can be initialized with an std::initializer_list. Also a std::initializer_list is passed to the constructor. ["lil,lool,lal,ln"] is no array.


问:
My set tag for aiml does not work
I am trying to use the set tag in my aiml file but it seems that nothing works. It never match.

color.aiml file

```<code>     <?xml version="1.0" encoding="UTF-8"?>
      <aiml version="2.0">
         <category>
           <pattern>IS <set>colors</set> A COLOR</pattern>
           <template>Yes, <star /> is a color.</template>
         </category>

         <category>
           <pattern>IS * A COLOR</pattern>
           <template>No, <star /> is not a color.</template>
         </category>
      </aiml>
</code>```

colors.set file

```<code>[["red"],["orange"],["yellow"],["green"],["blue"],["indigo"]]
</code>```

The results:

```<code>Human: Is green a color?
Bot: No, green is not a color.
</code>```

The expected results:

```<code>Human: Is green a color?
Bot: Yes, green is a color.
</code>```

Could anyone help me with this problem?

答:
I tried the same example with below change

Added "colors.txt" file under "sets" folder with values like

red

green

blue

green

Title: My set tag for aiml does not work

Body:
I am trying to use the set tag in my aiml file but it seems that nothing works. It never match.

color.aiml file

     <?xml version="1.0" encoding="UTF-8"?>
      <aiml version="2.0">
         <category>
           <pattern>IS <set>colors</set> A COLOR</pattern>
           <template>Yes, <star /> is a color.</template>
         </category>

         <category>
           <pattern>IS * A COLOR</pattern>
           <template>No, <star /> is not a color.</template>
         </category>
      </aiml>

colors.set file

[["red"],["orange"],["yellow"],["green"],["blue"],["indigo"]]

The results:

Human: Is green a color?
Bot: No, green is not a color.

The expected results:

Human: Is green a color?
Bot: Yes, green is a color.

Could anyone help me with this problem?


答:
You can't have : in a JS object property:

```<code>const obj = {
  "ua:scores": 1000
};

console.log(obj.ua:scores); // Throws an error
console.log(obj['ua:scores']); // returns 1000
</code>```

You can use lodash _.get to circumvent that issue and safely get your nested value

```<code>const categories = _.get(this.props, 'data._embedded.city:search-results._embedded.city:item._embedded.city:urban_area._embedded.ua:scores.categories', []);

return categories.map(data =>
  <div>
    <h2>{data.name}</h2>
    <p>{data.score_out_of_10}</p>
  </div>
);
</code>```

Title: How to get data in deeply nested JSON (more than 5 layers)

Body:
You can't have : in a JS object property:

const obj = {
  "ua:scores": 1000
};

console.log(obj.ua:scores); // Throws an error
console.log(obj['ua:scores']); // returns 1000

You can use lodash _.get to circumvent that issue and safely get your nested value

const categories = _.get(this.props, 'data._embedded.city:search-results._embedded.city:item._embedded.city:urban_area._embedded.ua:scores.categories', []);

return categories.map(data =>
  <div>
    <h2>{data.name}</h2>
    <p>{data.score_out_of_10}</p>
  </div>
);


问:
populate list using ajax in codeigniter
im working in a project using codeigniter, im trying to fill a dropdown list from database using ajax, but i get erreur :
"Uncaught SyntaxError: missing ) after argument list"

this is my view:

```<code><?php echo form_open('patient/nouveau_patient'); ?>

              <input type="text"  name="no_dossier_pt" class="sr-only"  value="" >
              <div class="form-group">

                <label>Patient :</label>
                <select class="form-control" id="patients_list" name="idP">
                  <option>Sélectionner un patient</option>
                </select>

             </div>
             <button class="btn btn-primary btn-block">Enregistrer</button>
           <?php echo form_close(); ?>

          </div>
</code>```

this is the code ajax:

```<code><script type="text/javascript">

$(document).ready(function(){
  var listePatient;
  showRecords();
  function showRecords(){
      $.ajax({
          type: "GET",
          url: '<?php echo base_url() ?>traitement/aff_patient',
          dataType: 'json',
          success: function(res){
             listePatient = res.patients;
             var select = document.getElementById("patients_list");
              for(i=select.options.length-1;i>=0;i--)
              {
                  select.remove(i);
              }

              for(var i = 0; i < listePatient.length; i++) {
                  var opt = listePatient[i].patient;
                  var opt1 = listePatient[i].id;
                  var el = document.createElement("option");
                  el.textContent = opt;
                  el.value = opt1;
                  select.appendChild(el);
              }
          },
          error: function(){
              alert('Could not load the data');
          },
      });
  }
}

</script>
</code>```

and this is the controller:

```<code>  public function aff_patient()
     {

         $patients = $this->patient_m->afficher_patients();

          $data_patient = array();

          foreach($patients->result() as $r) {

               $data_patient[] = array(

                    "id" => $r->id,
                    "patient" => $r->nom_pt." ".$r->prenom_pt

               );

           }

         echo json_encode(array("patients" =>$data_patient));
         exit();
     }
</code>```

i thing i did something wrong in my script but im new in ajax
thanks for helping

答:
Here the right syntax of your Ajax :

```

As I say you forgot to close your function.

Title: populate list using ajax in codeigniter

Body:
im working in a project using codeigniter, im trying to fill a dropdown list from database using ajax, but i get erreur :
"Uncaught SyntaxError: missing ) after argument list"

this is my view:

<?php echo form_open('patient/nouveau_patient'); ?>

              <input type="text"  name="no_dossier_pt" class="sr-only"  value="" >

                Patient :
                <select class="form-control" id="patients_list" name="idP">
                  <option>Sélectionner un patient</option>
                </select>

             <button class="btn btn-primary btn-block">Enregistrer</button>
           <?php echo form_close(); ?>

this is the code ajax:

and this is the controller:

  public function aff_patient()
     {

         $patients = $this->patient_m->afficher_patients();

          $data_patient = array();

          foreach($patients->result() as $r) {

               $data_patient[] = array(

                    "id" => $r->id,
                    "patient" => $r->nom_pt." ".$r->prenom_pt

               );

           }

         echo json_encode(array("patients" =>$data_patient));
         exit();
     }

i thing i did something wrong in my script but im new in ajax
thanks for helping

Body:
Here the right syntax of your Ajax :

<script type="text/javascript">

$(document).ready(function(){
  var listePatient;
  showRecords();
  function showRecords(){
      $.ajax({
          type: "GET",
          url: '<?php echo base_url() ?>traitement/aff_patient',
          dataType: 'json',
          success: function(res){
             listePatient = res.patients;
             var select = document.getElementById("patients_list");
              for(i=select.options.length-1;i>=0;i--)
              {
                  select.remove(i);
              }

              for(var i = 0; i < listePatient.length; i++) {
                  var opt = listePatient[i].patient;
                  var opt1 = listePatient[i].id;
                  var el = document.createElement("option");
                  el.textContent = opt;
                  el.value = opt1;
                  select.appendChild(el);
              }
          },
          error: function(){
              alert('Could not load the data');
          },
      });
  }
});

</script>

As I say you forgot to close your function.


问:
Docker Image of Jersey Web Application
I'm trying to create a Docker image from my Jersey web application running on a Tomcat server. I'm developing on a Windows 7 machine.

I have deployed the web application on a local Tomcat 8.0.14 application server on my development machine and everything works as expected.

To create the Docker image I put the following Dockerfile. in the same directory as the my-web-app.war file.

```<code>FROM tomcat:8.0-jre8
ADD /my-web-app.war /usr/local/tomcat/webapps/
CMD ["catalina.sh", "run"]
</code>```

After that I'm creating the image with the following command:

```<code>docker build -t my-web-app .
</code>```

This is done sucessfully and the images shows up with the docker images -a command.

After that I start the image through this:

```<code>winpty docker run --rm -it -p 8080:8080 my-web-app
</code>```

The command prompt show that the server is successfully started and when I tried to access the web application this also works:

```<code>http://192.168.99.100:8080/my-web-app
</code>```

shows the appropriate HTML welcome page.

The issue arises when I try to access any of the actual Jersey RESTful web services. Any time I try to access something different than an HTML page I get the following error message:

```<code>javax.servlet.ServletException: Servlet.init() for servlet My Web Application threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)
root cause

java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
    org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:308)
    org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:337)
    org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:178)
    org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:370)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)
</code>```

I assume there might be something wrong with the creation of the WAR file but if so how can the application be successfully deployed on my local Tomcat server.

If this is of any interest here is the pom.xml file I used to build the WAR:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>my.webapp.host</groupId>
    <artifactId>my-web-app</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>my-web-app</name>

    <build>
        <finalName>my-web-app</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.26-b03</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>2.26-b03</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.26-b03</version>
        </dependency>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>4.0.0-b05</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.19.3</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.19.3</version>
        </dependency>

        <!-- persistence api -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.6.4</version>
        </dependency>

        <!-- additional apis -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

         <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>

        <!-- own apis -->
        <dependency>
            <groupId>my.own.utility.api</groupId>
            <artifactId>utility-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>
</code>```

Does anyone know what the issue here is?

Any help is appreciated.

Greetings

答:
Here is an indepth overview and a solution to all who encounter NoSuchMethodError especially in jersey context.

The problem is

java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;

In Java NoSuchMethodError is thrown when the JVM cant find the method specified in the specified class.
From https://docs.oracle.com/javase/9/docs/api/java/lang/NoSuchMethodError.html

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

In your case JVM is complaining that javax.ws.rs.core.Application doesnot have  getProperties() method.

Jesey 2.x uses JEE 7. In JEE 7 version of javax.ws.rs.core.Application has

getClasses()

getSingeltons()

getProperties()
methods defined. https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Application.html

Jesey 1.x uses JEE 6. In JEE 6 version of javax.ws.rs.core.Application only has

getClasses()

getclass()

But getProperties() is not defined. https://jersey.github.io/apidocs/1.19.1/jersey/javax/ws/rs/core/Application.html

Solution

You have jersey 2.x and 1.x versions defined in your pom.xml. Therefore there are both JEE6 and 7 versions of javax.ws.rs.core.Application in your classpath and classloader loads JEE 6 version of appliction class which doesnot have getProperties() defined but yor application wants to execute getProperties() anyway. Hence the error.

Remove all jersey 1.x versions from your pom.xml and stick to jersey 2.x version. The classloader will take care of the rest.

Title: Docker Image of Jersey Web Application

Body:
I'm trying to create a Docker image from my Jersey web application running on a Tomcat server. I'm developing on a Windows 7 machine.

I have deployed the web application on a local Tomcat 8.0.14 application server on my development machine and everything works as expected.

To create the Docker image I put the following Dockerfile. in the same directory as the my-web-app.war file.

FROM tomcat:8.0-jre8
ADD /my-web-app.war /usr/local/tomcat/webapps/
CMD ["catalina.sh", "run"]

After that I'm creating the image with the following command:

docker build -t my-web-app .

This is done sucessfully and the images shows up with the docker images -a command.

After that I start the image through this:

winpty docker run --rm -it -p 8080:8080 my-web-app

The command prompt show that the server is successfully started and when I tried to access the web application this also works:

http://192.168.99.100:8080/my-web-app

shows the appropriate HTML welcome page.

The issue arises when I try to access any of the actual Jersey RESTful web services. Any time I try to access something different than an HTML page I get the following error message:

javax.servlet.ServletException: Servlet.init() for servlet My Web Application threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)
root cause

java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
    org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:308)
    org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:337)
    org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:178)
    org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:370)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)

I assume there might be something wrong with the creation of the WAR file but if so how can the application be successfully deployed on my local Tomcat server.

If this is of any interest here is the pom.xml file I used to build the WAR:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>my.webapp.host</groupId>
    <artifactId>my-web-app</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>my-web-app</name>

    <build>
        <finalName>my-web-app</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.26-b03</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>2.26-b03</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.26-b03</version>
        </dependency>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>4.0.0-b05</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.19.3</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.19.3</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.6.4</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

         <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>

        <dependency>
            <groupId>my.own.utility.api</groupId>
            <artifactId>utility-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

Does anyone know what the issue here is?

Any help is appreciated.

Greetings


问:
Pointer to variable inside a struct
I have a struct like this:

```<code>typedef struct{
    char *lexema;
    int comp_lexico;
    union{
        double v;
        double (*fnctptr)();
    } valor;
}tipoelem;

struct celda {
    tipoelem info;
    struct celda *izq, *der;
};

typedef struct celda * abb;
</code>```

Then I define a global variable abb, which has a global scope. If I get somehow the memory direction of the field info of celda, would I be able to modify it safely or It is better to define the field as a tipoelem pointer such as (tipoelem *info)?

The thing is, is it safe to edit the tipoelem info field with a tipoelem *pointerToInfo from other part of the prrogram or it is better to declare it as a pointer tipoelem *info in the struct celda?

Edited with more information:
The way I want to modify tipoelem info is the next one, and I do not know if it is safe.

```<code>abb a;
int main(){
    tipoelem *ptr = a->info;
    ptr->comp_lexico = 2;
}
</code>```

答:
Yes, it is safe to access like that.
Consider this example,

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

struct stOne {
    int a;
    int b;
    char c;
};

struct stTwo {
    struct stOne ObjectOne;
    struct sttwo *pTwo;
};

struct stOne *pOne;
struct stTwo *pTwo;
struct stTwo ObjectstTwo;

int main() {

    pTwo = &ObjectstTwo;
    pTwo->ObjectOne.c = 'H';
    printf("%c", ObjectstTwo.ObjectOne.c);

    pOne = &pTwo->ObjectOne;
    pOne->c = 'D';
    printf(" %c", ObjectstTwo.ObjectOne.c);
}
</code>```

This code prints

```<code>H
</code>```

as output.

Similarly you can modify a member of the struct tipoelem, for example comp_lexico which is an int.

```<code>struct celda objectCelda;

//Assuming abb is a pointer, Make abb point to an object
abb = &objectCelda;

//Modify the value of comp_lexico
abb->info.comp_lexico = 0xAA;
</code>```

Now changing the code,

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

struct stOne {
    int a;
    int b;
    char c;
};

struct stTwo {
  struct stOne ObjectOne;
  struct sttwo *pTwo;
};

struct stOne *pOne;
struct stTwo *pTwo;
struct stTwo ObjectstTwo;

int main() {

    pTwo = &ObjectstTwo;
    pTwo->ObjectOne.c = 'H';
    printf("%c", ObjectstTwo.ObjectOne.c);

    pOne = &pTwo->ObjectOne;
    pOne->c = 'D';
    printf(" %c", ObjectstTwo.ObjectOne.c);
}
</code>```

This prints

```<code>H D
</code>```

on console as output. So it is perfectly okay to do it either way.

Title: Pointer to variable inside a struct

Body:
I have a struct like this:

typedef struct{
    char *lexema;
    int comp_lexico;
    union{
        double v;
        double (*fnctptr)();
    } valor;
}tipoelem;

struct celda {
    tipoelem info;
    struct celda *izq, *der;
};

typedef struct celda * abb;

Then I define a global variable abb, which has a global scope. If I get somehow the memory direction of the field info of celda, would I be able to modify it safely or It is better to define the field as a tipoelem pointer such as (tipoelem *info)?

The thing is, is it safe to edit the tipoelem info field with a tipoelem *pointerToInfo from other part of the prrogram or it is better to declare it as a pointer tipoelem *info in the struct celda?

Edited with more information:
The way I want to modify tipoelem info is the next one, and I do not know if it is safe.

abb a;
int main(){
    tipoelem *ptr = a->info;
    ptr->comp_lexico = 2;
}

Body:
Yes, it is safe to access like that.
Consider this example,

#include<stdio.h>

struct stOne {
    int a;
    int b;
    char c;
};

struct stTwo {
    struct stOne ObjectOne;
    struct sttwo *pTwo;
};

struct stOne *pOne;
struct stTwo *pTwo;
struct stTwo ObjectstTwo;

int main() {

    pTwo = &ObjectstTwo;
    pTwo->ObjectOne.c = 'H';
    printf("%c", ObjectstTwo.ObjectOne.c);

    pOne = &pTwo->ObjectOne;
    pOne->c = 'D';
    printf(" %c", ObjectstTwo.ObjectOne.c);
}

This code prints

H

as output.

Similarly you can modify a member of the struct tipoelem, for example comp_lexico which is an int.

struct celda objectCelda;

//Assuming abb is a pointer, Make abb point to an object
abb = &objectCelda;

//Modify the value of comp_lexico
abb->info.comp_lexico = 0xAA;

Now changing the code,

#include<stdio.h>

struct stOne {
    int a;
    int b;
    char c;
};

struct stTwo {
  struct stOne ObjectOne;
  struct sttwo *pTwo;
};

struct stOne *pOne;
struct stTwo *pTwo;
struct stTwo ObjectstTwo;

int main() {

    pTwo = &ObjectstTwo;
    pTwo->ObjectOne.c = 'H';
    printf("%c", ObjectstTwo.ObjectOne.c);

    pOne = &pTwo->ObjectOne;
    pOne->c = 'D';
    printf(" %c", ObjectstTwo.ObjectOne.c);
}

This prints

H D

on console as output. So it is perfectly okay to do it either way.


问:
Do subclasses ALWAYS need to implement a designated initializer in Objective-C?
Do subclasses that don't need to add class-specific initialization code have to implement the designated initializer of the super class?

The Apple's documentation for NSObject's init method provides some discussion:

"Every class must guarantee that the
init method either returns a fully
functional instance of the class or
raises an exception. Subclasses should
override the init method to add
class-specific initialization code."

"If a subclass does any initialization
of its own, it must define its own
designated initializer. This method
should begin by sending a message to
super to invoke the designated
initializer of its superclass."

However, nothing is specified for the case when a subclass needs no extra initialization code.

The code below attempts to clarify my question. ClassA has the designated initializer named initWithX:Y:. ClassB does not need to an extra initialization, everything is provided by ClassA.

Explanatory Code:

```<code>@interface ClassA : NSObject {
  NSInteger x;
  NSInteger y;
}

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;

@end

@implementation ClassA

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super init]) {
    x = initX;
    y = initY;
  }
  return self;
}
@end

@interface ClassB : ClassA {
  //no extra variables
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;

@end

@implementation ClassB

/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
//  with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super initWithX:initX Y:initY]) {
    /* Don't need class-specific initialization code */
  }
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}

@end
</code>```

答: You don't need a designated initializer if your new class does not need any extra initialization. However, you might want to do so anyway, in case you decide to change your subclass later. </p>

Body:
Do subclasses that don't need to add class-specific initialization code have to implement the designated initializer of the super class?

The Apple's documentation for NSObject's init method provides some discussion:

"Every class must guarantee that the
init method either returns a fully
functional instance of the class or
raises an exception. Subclasses should
override the init method to add
class-specific initialization code."

"If a subclass does any initialization
of its own, it must define its own
designated initializer. This method
should begin by sending a message to
super to invoke the designated
initializer of its superclass."

However, nothing is specified for the case when a subclass needs no extra initialization code.

The code below attempts to clarify my question. ClassA has the designated initializer named initWithX:Y:. ClassB does not need to an extra initialization, everything is provided by ClassA.

Explanatory Code:

@interface ClassA : NSObject {
  NSInteger x;
  NSInteger y;
}

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;

@end

@implementation ClassA

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super init]) {
    x = initX;
    y = initY;
  }
  return self;
}
@end

@interface ClassB : ClassA {
  //no extra variables
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;

@end

@implementation ClassB

/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
//  with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super initWithX:initX Y:initY]) {
    /* Don't need class-specific initialization code */
  }
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}

@end


问:
.NET Core Unit Testing - Mock IOptions<T>
I feel like I'm missing something really obvious here. I have classes that require injecting of options using the .NET Core IOptions pattern(?). When I unit test that class, I want to mock various versions of the options to validate the functionality of the class. Does anyone know how to correctly mock/instantiate/populate IOptions<T> outside of the Startup class?

Here are some samples of the classes I'm working with:

Settings/Options Model

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OptionsSample.Models
{
    public class SampleOptions
    {
        public string FirstSetting { get; set; }
        public int SecondSetting { get; set; }
    }
}
</code>```

Class to be tested which uses the Settings:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OptionsSample.Models
using System.Net.Http;
using Microsoft.Extensions.Options;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Dynamic;
using Microsoft.Extensions.Logging;

namespace OptionsSample.Repositories
{
    public class SampleRepo : ISampleRepo
    {
        private SampleOptions _options;
        private ILogger<AzureStorageQueuePassthru> _logger;

        public SampleRepo(IOptions<SampleOptions> options)
        {
            _options = options.Value;
        }

        public async Task Get()
        {
        }
    }
}
</code>```

Unit test in a different assembly from the other classes:

```<code>using OptionsSample.Repositories;
using OptionsSample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace OptionsSample.Repositories.Tests
{
    public class SampleRepoTests
    {
        private IOptions<SampleOptions> _options;
        private SampleRepo _sampleRepo;

        public SampleRepoTests()
        {
            //Not sure how to populate IOptions<SampleOptions> here
            _options = options;

            _sampleRepo = new SampleRepo(_options);
        }
    }
}
</code>```

答:
You can avoid using MOQ at all.
Use in your tests .json configuration file. One file for many test class files. It will be fine to use ConfigurationBuilder in this case.

Example of appsetting.json

```<code>{
    "someService" {
        "someProp": "someValue
    }
}
</code>```

Example of settings mapping class:

```<code>public class SomeServiceConfiguration
{
     public string SomeProp { get; set; }
}
</code>```

Example of service which is needed to test:

```<code>public class SomeService
{
    public SomeService(IOptions<SomeServiceConfiguration> config)
    {
        _config = config ?? throw new ArgumentNullException(nameof(_config));
    }
}
</code>```

NUnit test class:

```<code>[TestFixture]
public class SomeServiceTests
{

    private IOptions<SomeServiceConfiguration> _config;
    private SomeService _service;

    [OneTimeSetUp]
    public void GlobalPrepare()
    {
         var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false)
            .Build();

        _config = Options.Create(configuration.GetSection("someService").Get<SomeServiceConfiguration>());
    }

    [SetUp]
    public void PerTestPrepare()
    {
        _service = new SomeService(_config);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I feel like I'm missing something really obvious here. I have classes that require injecting of options using the .NET Core IOptions pattern(?). When I unit test that class, I want to mock various versions of the options to validate the functionality of the class. Does anyone know how to correctly mock/instantiate/populate IOptions<T> outside of the Startup class?

Here are some samples of the classes I'm working with:

Settings/Options Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OptionsSample.Models
{
    public class SampleOptions
    {
        public string FirstSetting { get; set; }
        public int SecondSetting { get; set; }
    }
}

Class to be tested which uses the Settings:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OptionsSample.Models
using System.Net.Http;
using Microsoft.Extensions.Options;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Dynamic;
using Microsoft.Extensions.Logging;

namespace OptionsSample.Repositories
{
    public class SampleRepo : ISampleRepo
    {
        private SampleOptions _options;
        private ILogger<AzureStorageQueuePassthru> _logger;

        public SampleRepo(IOptions<SampleOptions> options)
        {
            _options = options.Value;
        }

        public async Task Get()
        {
        }
    }
}

Unit test in a different assembly from the other classes:

using OptionsSample.Repositories;
using OptionsSample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace OptionsSample.Repositories.Tests
{
    public class SampleRepoTests
    {
        private IOptions<SampleOptions> _options;
        private SampleRepo _sampleRepo;

        public SampleRepoTests()
        {
            //Not sure how to populate IOptions<SampleOptions> here
            _options = options;

            _sampleRepo = new SampleRepo(_options);
        }
    }
}

Body:
You can avoid using MOQ at all.
Use in your tests .json configuration file. One file for many test class files. It will be fine to use ConfigurationBuilder in this case.

Example of appsetting.json

{
    "someService" {
        "someProp": "someValue
    }
}

Example of settings mapping class:

public class SomeServiceConfiguration
{
     public string SomeProp { get; set; }
}

Example of service which is needed to test:

public class SomeService
{
    public SomeService(IOptions<SomeServiceConfiguration> config)
    {
        _config = config ?? throw new ArgumentNullException(nameof(_config));
    }
}

NUnit test class:

[TestFixture]
public class SomeServiceTests
{

    private IOptions<SomeServiceConfiguration> _config;
    private SomeService _service;

    [OneTimeSetUp]
    public void GlobalPrepare()
    {
         var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false)
            .Build();

        _config = Options.Create(configuration.GetSection("someService").Get<SomeServiceConfiguration>());
    }

    [SetUp]
    public void PerTestPrepare()
    {
        _service = new SomeService(_config);
    }
}