问:
XML to JSON Conversion with Conditions
Wanted to covert an xml String to Json and I am doing it as below.

XML which has to be converted

```<code><Item>
    <Property name="Description" value="Description 1"/>
    <Property name="EffDate" value="01/05/2017"/>
    <Property name="ExpDate" value="12/31/9999"/>
    <Property name="Status" value="Launched"/>
</Item>
</code>```

I have created a Class for the xml as below.

```<code>public class Context {
    @XmlElement(name = "Item")
    private List<Item> offer;
}

public class Item {
    @XmlElement(name = "Property")
    private List<Property> properties;
}

public class Property {
    @XmlAttribute
    private String name;

    @XmlAttribute
    private String value;
}
</code>```

I am using Gson libraries to convert this Java object to Json - g.toJson.

Comverted JSON -

```<code>   "offer": [{
   "properties": [{
                "name": "Description",
                "value": "Description 1"
            },
            {
                "name": "EffDate",
                "value": "01/05/2017"
            },
            {
                "name": "ExpDate",
                "value": "12/31/9999"
            },
            {
                "name": "Status",
                "value": "Launched"
            }]
         }]
</code>```

But we wanted to convert the JSON as below -

```<code>"offer": [{
     "Description" : "Description 1",
     "EffDate":"01/05/2017",
     "ExpDate": "12/31/9999",
     "Status": "Launched"
    }]
</code>```

Is there a way to convert the properties name and value as Item class properties.?

答:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

```<code>import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("/")
        .attribute("offer", parsing.arr("/Item")
            .attribute("Description", "Property[@name='Description']/@value")
            .attribute("EffDate", "Property[@name='EffDate']/@value")
            .attribute("ExpDate", "Property[@name='ExpDate']/@value")
            .attribute("Status", "Property[@name='Status']/@value")
        )
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}
</code>```

It will return a Jackson ObjectNode, with the following json:

```<code>{
  "offer": [
    {
      "Status": "Launched",
      "Description": "Description 1",
      "ExpDate": "12/31/9999",
      "EffDate": "01/05/2017"
    }
  ]
}
</code>```

Title: XML to JSON Conversion with Conditions

Body:
Wanted to covert an xml String to Json and I am doing it as below.

XML which has to be converted

<Item>
    <Property name="Description" value="Description 1"/>
    <Property name="EffDate" value="01/05/2017"/>
    <Property name="ExpDate" value="12/31/9999"/>
    <Property name="Status" value="Launched"/>
</Item>

I have created a Class for the xml as below.

public class Context {
    @XmlElement(name = "Item")
    private List<Item> offer;
}

public class Item {
    @XmlElement(name = "Property")
    private List<Property> properties;
}

public class Property {
    @XmlAttribute
    private String name;

    @XmlAttribute
    private String value;
}

I am using Gson libraries to convert this Java object to Json - g.toJson.

Comverted JSON -

   "offer": [{
   "properties": [{
                "name": "Description",
                "value": "Description 1"
            },
            {
                "name": "EffDate",
                "value": "01/05/2017"
            },
            {
                "name": "ExpDate",
                "value": "12/31/9999"
            },
            {
                "name": "Status",
                "value": "Launched"
            }]
         }]

But we wanted to convert the JSON as below -

"offer": [{
     "Description" : "Description 1",
     "EffDate":"01/05/2017",
     "ExpDate": "12/31/9999",
     "Status": "Launched"
    }]

Is there a way to convert the properties name and value as Item class properties.?

Body:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("/")
        .attribute("offer", parsing.arr("/Item")
            .attribute("Description", "Property[@name='Description']/@value")
            .attribute("EffDate", "Property[@name='EffDate']/@value")
            .attribute("ExpDate", "Property[@name='ExpDate']/@value")
            .attribute("Status", "Property[@name='Status']/@value")
        )
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}

It will return a Jackson ObjectNode, with the following json:

{
  "offer": [
    {
      "Status": "Launched",
      "Description": "Description 1",
      "ExpDate": "12/31/9999",
      "EffDate": "01/05/2017"
    }
  ]
}


来源: stackexchange

问:
Delete a listview item from activity on button click from another activity
I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted  to create a button that should delete the listview item that was clicked on. Here is the code I came with.

MainActivity

```<code>package news;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> newslist_adapter;
    ArrayList<String> new_subject = new ArrayList<>();
    ArrayList<String> new_post = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView post_view = findViewById(R.id.news_feed);

        FloatingActionButton add_post_button = findViewById(R.id.post_btn);

        //create click event and pass values of arrays
        post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
                intent.putExtra("Subject", new_subject);
                intent.putExtra("Post", new_post);
                intent.putExtra("position", id);
//                getApplicationContext().startActivity(intent);
                startActivityForResult(intent, 2);
            }
        });

        //create button connection and create keylistener
        add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                startActivityForResult(intent, 1);

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final ListView post_view = findViewById(R.id.news_feed);
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                //get subject and post from second activity
                String new_subject_value = data.getStringExtra("newSubject");
                String new_post_value = data.getStringExtra("newPost");
                new_subject.add(new_subject_value);
                new_post.add(new_post_value);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);

            }
        }
        if (requestCode == 2) {
            if(resultCode == Activity.RESULT_OK){
                String item2delete = data.getStringExtra("id");
                new_subject.remove(item2delete);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);
            }
        }
    }
}
</code>```

SecondActivity

```<code>package news;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;

public class full_post_activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.full_post_activity);

        final int id = getIntent().getExtras().getInt("id");

        //create view reference
        final TextView subject_edit = findViewById(R.id.subject_input);
        final TextView post_edit = findViewById(R.id.post_input);

        //create button reference
        Button delete_button = findViewById(R.id.full_post_delete_btn);

        //create click event
        delete_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", id);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
        ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");

        String subject_string = subject_array.get(0);
        String post_string = post_array.get(0);

        //set textview text
        subject_edit.setText(subject_string);
        post_edit.setText(post_string);
    }
}
</code>```

My problem now is that the delete button doesn't do anything besides returning to the MainActivity. What am I doing wrong?

答:
If you want to stay in the activity where the delete button is I would suggest creating a getter and a setter for the list behind your ListView(Easily generate them with ALT+INSERT).

You can then make an instance of your MainActivity inside the delete_buttons OnClick methode and get said List with the getter.
Remove the Item you need to remove and update the list with your setter, again using your MainActivity instance.

Edit: here are some code samples

Getter and Setter:

```<code>public ArrayList<String> getNewPost() {
    return this.new_post;
}

public void setNewPost(ArrayList<String> np) {
    this.new_post = np;
}
</code>```

delete_button OnClick methode:

```<code>delete_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MainActivity main=new MainActivity();
            ListView<String> np=main.getNewPost();
            np.remove("StringToRemove");
            main.setNewPost(np);
        }
    });
</code>```

I would also suggest you to make a back_button to check if the list was updated, you can use your old delete_button onclick for that.

ContentLicense: CC BY-SA 3.0

Body:
I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted  to create a button that should delete the listview item that was clicked on. Here is the code I came with.

MainActivity

package news;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> newslist_adapter;
    ArrayList<String> new_subject = new ArrayList<>();
    ArrayList<String> new_post = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView post_view = findViewById(R.id.news_feed);

        FloatingActionButton add_post_button = findViewById(R.id.post_btn);

        //create click event and pass values of arrays
        post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
                intent.putExtra("Subject", new_subject);
                intent.putExtra("Post", new_post);
                intent.putExtra("position", id);
//                getApplicationContext().startActivity(intent);
                startActivityForResult(intent, 2);
            }
        });

        //create button connection and create keylistener
        add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                startActivityForResult(intent, 1);

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final ListView post_view = findViewById(R.id.news_feed);
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                //get subject and post from second activity
                String new_subject_value = data.getStringExtra("newSubject");
                String new_post_value = data.getStringExtra("newPost");
                new_subject.add(new_subject_value);
                new_post.add(new_post_value);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);

            }
        }
        if (requestCode == 2) {
            if(resultCode == Activity.RESULT_OK){
                String item2delete = data.getStringExtra("id");
                new_subject.remove(item2delete);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);
            }
        }
    }
}

SecondActivity

package news;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;

public class full_post_activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.full_post_activity);

        final int id = getIntent().getExtras().getInt("id");

        //create view reference
        final TextView subject_edit = findViewById(R.id.subject_input);
        final TextView post_edit = findViewById(R.id.post_input);

        //create button reference
        Button delete_button = findViewById(R.id.full_post_delete_btn);

        //create click event
        delete_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", id);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
        ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");

        String subject_string = subject_array.get(0);
        String post_string = post_array.get(0);

        //set textview text
        subject_edit.setText(subject_string);
        post_edit.setText(post_string);
    }
}

My problem now is that the delete button doesn't do anything besides returning to the MainActivity. What am I doing wrong?

Body:
If you want to stay in the activity where the delete button is I would suggest creating a getter and a setter for the list behind your ListView(Easily generate them with ALT+INSERT).

You can then make an instance of your MainActivity inside the delete_buttons OnClick methode and get said List with the getter.
Remove the Item you need to remove and update the list with your setter, again using your MainActivity instance.

Edit: here are some code samples

Getter and Setter:

public ArrayList<String> getNewPost() {
    return this.new_post;
}

public void setNewPost(ArrayList<String> np) {
    this.new_post = np;
}

delete_button OnClick methode:

delete_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MainActivity main=new MainActivity();
            ListView<String> np=main.getNewPost();
            np.remove("StringToRemove");
            main.setNewPost(np);
        }
    });

I would also suggest you to make a back_button to check if the list was updated, you can use your old delete_button onclick for that.


问:
Converting {integer} to f32 in Rust
I want to convert a value from {integer} to f32:

```<code>struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}
</code>```

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

```<code>for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}
</code>```

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

```<code>for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}
</code>```

But with my usecase this turns into:

```<code>for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}
</code>```

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

答:
Since everyone else is answering, I'll chime in with an iterator-flavored solution. This uses Itertools::cartesian_product instead of the for loops:

```<code>extern crate itertools;

use itertools::Itertools;

fn main() {
    fn conv(x: i32) -> f32 { x as f32 }

    let xx = (-5..5).map(conv);
    let yy = xx.clone();
    let zz = xx.clone();

    let coords = xx.cartesian_product(yy.clone().cartesian_product(zz));
    let vectors = coords.map(|(x, (y, z))| Vector3 { x, y, z });
}
</code>```

Unfortunately, closures don't yet implement Clone, so I used a small function to perform the mapping. These do implement Clone.

If you wanted a helper method:

```<code>extern crate itertools;

use itertools::Itertools;
use std::ops::Range;

fn f32_range(r: Range<i32>) -> std::iter::Map<Range<i32>, fn(i32) -> f32> {
    fn c(x: i32) -> f32 { x as _ }
    r.map(c)
}

fn main() {
    let xx = f32_range(-5..5);
    let yy = f32_range(-5..5);
    let zz = f32_range(-5..5);

    let coords = xx.cartesian_product(yy.cartesian_product(zz));
    let vectors = coords.map(|(x, (y, z))| Vector3 { x, y, z });
}
</code>```

Title: Converting {integer} to f32 in Rust

Body:
I want to convert a value from {integer} to f32:

struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}

But with my usecase this turns into:

for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

Body:
Since everyone else is answering, I'll chime in with an iterator-flavored solution. This uses Itertools::cartesian_product instead of the for loops:

extern crate itertools;

use itertools::Itertools;

fn main() {
    fn conv(x: i32) -> f32 { x as f32 }

    let xx = (-5..5).map(conv);
    let yy = xx.clone();
    let zz = xx.clone();

    let coords = xx.cartesian_product(yy.clone().cartesian_product(zz));
    let vectors = coords.map(|(x, (y, z))| Vector3 { x, y, z });
}

Unfortunately, closures don't yet implement Clone, so I used a small function to perform the mapping. These do implement Clone.

If you wanted a helper method:

extern crate itertools;

use itertools::Itertools;
use std::ops::Range;

fn f32_range(r: Range<i32>) -> std::iter::Map<Range<i32>, fn(i32) -> f32> {
    fn c(x: i32) -> f32 { x as _ }
    r.map(c)
}

fn main() {
    let xx = f32_range(-5..5);
    let yy = f32_range(-5..5);
    let zz = f32_range(-5..5);

    let coords = xx.cartesian_product(yy.cartesian_product(zz));
    let vectors = coords.map(|(x, (y, z))| Vector3 { x, y, z });
}


问:
Matlab calculating radians from -pi to pi instead of 0 to 2pi
I am working on a problem where the pressure profile is supposed to be smooth. For this the angle should be from 0 to 2pi. But when I take the logarithm of certain complex numbers, MATLAB maps the angle to the pi to negative pi range (clockwise direction).

For example :

```<code>var_z = [20.0 + 0.6i,  20.0 - 0.6i];
za2 = -2.5000 + 0.5000i;
A = log (-(var_z-za2))
</code>```

yields A = [3.11 - 3.13i, 3.11 + 3.091i], but if the angle was only in the counterclockwise direction (i.e. [0, 2pi]) we'd get [3.11 + 3.14i,  3.11 + 3.09i] instead.

The latter result makes more sense in my situation as it prevents the pressure profiles from rapidly jumping up. Is there any way to force MATLAB to use 0 to 2pi for the radians?

答:
According to the documentation of log, for complex numbers the performed computation is this:

```<code>log(abs(z)) + 1i*angle(z)
</code>```

It appears we can just "redefine" this slightly by adding a 2π-modulus, then explicitly applying the above set of operations instead of the log function:

```<code>log(abs(z)) + 1i*mod(angle(z),2*pi)
</code>```

Thus if we define a function handle and compare the results:

```<code>l = @(z)log(abs(z)) + 1i*mod(angle(z),2*pi);
</code>```

```<code>>> log(-([20.0 + 0.6i,  20.0 - 0.6i]-(-2.5000 + 0.5000i)))

ans =

   3.1135 - 3.1371i   3.1147 + 3.0927i

>> l(-([20.0 + 0.6i,  20.0 - 0.6i]-(-2.5000 + 0.5000i)))

ans =

   3.1135 + 3.1460i   3.1147 + 3.0927i
</code>```

... we see that the desired result is achieved.

Body:
I am working on a problem where the pressure profile is supposed to be smooth. For this the angle should be from 0 to 2pi. But when I take the logarithm of certain complex numbers, MATLAB maps the angle to the pi to negative pi range (clockwise direction).

For example :

var_z = [20.0 + 0.6i,  20.0 - 0.6i];
za2 = -2.5000 + 0.5000i;
A = log (-(var_z-za2))

yields A = [3.11 - 3.13i, 3.11 + 3.091i], but if the angle was only in the counterclockwise direction (i.e. [0, 2pi]) we'd get [3.11 + 3.14i,  3.11 + 3.09i] instead.

The latter result makes more sense in my situation as it prevents the pressure profiles from rapidly jumping up. Is there any way to force MATLAB to use 0 to 2pi for the radians?

Body:
According to the documentation of log, for complex numbers the performed computation is this:

log(abs(z)) + 1i*angle(z)

It appears we can just "redefine" this slightly by adding a 2π-modulus, then explicitly applying the above set of operations instead of the log function:

log(abs(z)) + 1i*mod(angle(z),2*pi)

Thus if we define a function handle and compare the results:

l = @(z)log(abs(z)) + 1i*mod(angle(z),2*pi);

>> log(-([20.0 + 0.6i,  20.0 - 0.6i]-(-2.5000 + 0.5000i)))

ans =

   3.1135 - 3.1371i   3.1147 + 3.0927i

>> l(-([20.0 + 0.6i,  20.0 - 0.6i]-(-2.5000 + 0.5000i)))

ans =

   3.1135 + 3.1460i   3.1147 + 3.0927i

... we see that the desired result is achieved.


问:
Why am I not able to return a fragment?
I'm getting an error on the line containing return MyFragment.get(position); inside the MyViewPageAdapter class.

Upon hovering over the error, the error is telling me:

Incompatible types.
Required: android.support.v4.app.Fragment
Found:android.app.Fragment

How can I fix this?

Here's MainActivity.java:

```<code>import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TabLayout MyTabs;
    ViewPager MyPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyTabs = (TabLayout)findViewById(R.id.MyTabs);
        MyPage = (ViewPager) findViewById(R.id.MyPage);

        MyTabs.setupWithViewPager(MyPage);
        setUpViewPager(MyPage);

    }

    public void setUpViewPager(ViewPager viewpage) {
        MyViewPageAdapter Adapter = new MyViewPageAdapter(getSupportFragmentManager());
        Adapter.AddFragmentPage(new Page_1(), "Page 1");
        Adapter.AddFragmentPage(new Page_2(), "Page 2");
        Adapter.AddFragmentPage(new Page_3(), "Page 3");

        viewpage.setAdapter(Adapter);
    }

    public class MyViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> MyFragment = new ArrayList<>();
        private List<String> MyPageTitle = new ArrayList<>();

        public MyViewPageAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        public void AddFragmentPage(Fragment Frag, String Title) {
            MyFragment.add(Frag);
            MyPageTitle.add(Title);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return MyFragment.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return MyPageTitle.get(position);
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
Replace the very first line:

```<code>import android.app.Fragment;
</code>```

with this one:

```<code>import android.support.v4.app.Fragment;
</code>```

In the Android Sdk, there are two different Fragment classes. One added in API 11 and one added in API 22. The latter provides Fragment functionality for API level below 11.

Title: Why am I not able to return a fragment?

Body:
I'm getting an error on the line containing return MyFragment.get(position); inside the MyViewPageAdapter class.

Upon hovering over the error, the error is telling me:

Incompatible types.
Required: android.support.v4.app.Fragment
Found:android.app.Fragment

How can I fix this?

Here's MainActivity.java:

import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TabLayout MyTabs;
    ViewPager MyPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyTabs = (TabLayout)findViewById(R.id.MyTabs);
        MyPage = (ViewPager) findViewById(R.id.MyPage);

        MyTabs.setupWithViewPager(MyPage);
        setUpViewPager(MyPage);

    }

    public void setUpViewPager(ViewPager viewpage) {
        MyViewPageAdapter Adapter = new MyViewPageAdapter(getSupportFragmentManager());
        Adapter.AddFragmentPage(new Page_1(), "Page 1");
        Adapter.AddFragmentPage(new Page_2(), "Page 2");
        Adapter.AddFragmentPage(new Page_3(), "Page 3");

        viewpage.setAdapter(Adapter);
    }

    public class MyViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> MyFragment = new ArrayList<>();
        private List<String> MyPageTitle = new ArrayList<>();

        public MyViewPageAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        public void AddFragmentPage(Fragment Frag, String Title) {
            MyFragment.add(Frag);
            MyPageTitle.add(Title);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return MyFragment.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return MyPageTitle.get(position);
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Body:
Replace the very first line:

import android.app.Fragment;

with this one:

import android.support.v4.app.Fragment;

In the Android Sdk, there are two different Fragment classes. One added in API 11 and one added in API 22. The latter provides Fragment functionality for API level below 11.


问:
How to show hide a class?
On ajax success I have to hide a class and show the different class.
Suppose I have "foo" and "bar" two classes. Now it has "foo" class when my ajax returns success then I want to show the "bar" class.

```<code>$.ajax({
        type:'POST',
        url:"/test/",
        data:{"test_data": my_data},
        success:function(data) {

        },
        dataType:"json"
        // here I want to hide the "foo" class and show the "bar" class.
    });
</code>```

Actually "foo" and "bar" is a class of button. when i click button having "foo" class it should hide and button having "bar" class should be shown. and vice versa

答:
You didn't mentiond on which element you want to apply this. Anyway this will give you an idea:

```<code>$.ajax({
    type:'POST',
    url:"/test/",
    data:{"test_data": my_data},
    success:function(data) {

    },
    dataType:"json"
    complete: function(xhr) {
       // if you want to switch classes on a specific element
       $('element_you_want_to_switch_classes').toggleClass('foo bar');

       // if you want to show/hide different elements
       $('.foo').hide();
       $('.bar').show();
    }
});
</code>```

This will apply the changes after the ajax request has completed (regardless if it fails or not). If you just want to apply the changes on success just pack that lines into your success handler.

ContentLicense: CC BY-SA 2.5

Title: How to show hide a class?

Body:
On ajax success I have to hide a class and show the different class.
Suppose I have "foo" and "bar" two classes. Now it has "foo" class when my ajax returns success then I want to show the "bar" class.

$.ajax({
        type:'POST',
        url:"/test/",
        data:{"test_data": my_data},
        success:function(data) {

        },
        dataType:"json"
        // here I want to hide the "foo" class and show the "bar" class.
    });

Actually "foo" and "bar" is a class of button. when i click button having "foo" class it should hide and button having "bar" class should be shown. and vice versa

Body:
You didn't mentiond on which element you want to apply this. Anyway this will give you an idea:

$.ajax({
    type:'POST',
    url:"/test/",
    data:{"test_data": my_data},
    success:function(data) {

    },
    dataType:"json"
    complete: function(xhr) {
       // if you want to switch classes on a specific element
       $('element_you_want_to_switch_classes').toggleClass('foo bar');

       // if you want to show/hide different elements
       $('.foo').hide();
       $('.bar').show();
    }
});

This will apply the changes after the ajax request has completed (regardless if it fails or not). If you just want to apply the changes on success just pack that lines into your success handler.


问:
Paste to virtual terminal
In a Ubuntu host system I have installed qemu and created a virtual machine with CentOS. The CentOS installation does not have an X server, just a virtual terminal. I would like to be able to copy strings from the host system to the virtual terminal of the virtual machine.

What I found so far is the suggestion to install spice-vdagent. If I understand correctly however, spice-vdagent requires an X server, which I don't have installed.

So, how can I paste strings to the virtual terminal (if possible at all)?

答:
Run your Vm and run next command:</p>

```<code># yum install spice-vdagent
# chkconfig --add spice-vdagentd
# service spice-vdagentd start
</code>```

Title: Paste to virtual terminal

Body:
Run your Vm and run next command:

# yum install spice-vdagent
# chkconfig --add spice-vdagentd
# service spice-vdagentd start


问:
Cross compiling problems
I have installed the cross compile tools in the ubuntu 16.04.And when I type arm-linux-gnueabihf-gcc -vin the command line.The command line shows that the cross compiler can work as follows:

```<code>Using built-in specs.
COLLECT_GCC=arm-linux-gnueabihf-gcc
COLLECT_LTO_WRAPPER=/home/nju/ti-processor-linux-sdk/linux-devkit/sysroots/x86_64-arago-linux/usr/bin/../libexec/gcc/arm-linux-gnueabihf/6.2.1/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: /home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/snapshots/gcc-linaro-6.2-2016.11/configure SHELL=/bin/bash --with-mpc=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-mpfr=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gmp=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gnu-as --with-gnu-ld --disable-libstdcxx-pch --disable-libmudflap --with-cloog=no --with-ppl=no --with-isl=no --disable-nls --enable-c99 --enable-gnu-indirect-function --disable-multilib --with-tune=cortex-a9 --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --enable-multiarch --with-build-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/sysroots/arm-linux-gnueabihf --enable-lto --enable-linker-build-id --enable-long-long --enable-shared --with-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu/arm-linux-gnueabihf/libc --enable-languages=c,c++,fortran,lto --enable-checking=release --disable-bootstrap --build=x86_64-unknown-linux-gnu --host=x86_64-unknown-linux-gnu --target=arm-linux-gnueabihf --prefix=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu
Thread model: posix
gcc version 6.2.1 20161016 (Linaro GCC 6.2-2016.11)
</code>```

But when I execute ./configure --host=arm-linux-gnueabihf,the system cannot detect the arm-linux-gnueabihf tools.

```<code>configure: WARNING: If you wanted to set the --build type, don't use --host.
If a cross compiler is detected then cross compile mode will be used.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for arm-linux-gnueabihf-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking for arm-linux-gnueabihf-g++... no
checking for arm-linux-gnueabihf-c++... no
checking for arm-linux-gnueabihf-gpp... no
checking for arm-linux-gnueabihf-aCC... no
checking for arm-linux-gnueabihf-CC... no
checking for arm-linux-gnueabihf-cxx... no
checking for arm-linux-gnueabihf-cc++... no
checking for arm-linux-gnueabihf-cl.exe... no
checking for arm-linux-gnueabihf-FCC... no
checking for arm-linux-gnueabihf-KCC... no
checking for arm-linux-gnueabihf-RCC... no
checking for arm-linux-gnueabihf-xlC_r... no
checking for arm-linux-gnueabihf-xlC... no
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking for style of include used by make... GNU
checking dependency style of g++... gcc3
checking for arm-linux-gnueabihf-gcc... no
checking for gcc... gcc
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking dependency style of gcc... gcc3
checking for pthread_rwlock_init in -lpthread... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking sys/ioctl.h usability... yes
checking sys/ioctl.h presence... yes
checking for sys/ioctl.h... yes
checking for unistd.h... (cached) yes
checking gtk/gtk.h usability... no
checking gtk/gtk.h presence... no
checking for gtk/gtk.h... no
checking pthread.h usability... yes
checking pthread.h presence... yes
checking for pthread.h... yes
checking for stdlib.h... (cached) yes
checking for GNU libc compatible malloc... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
config.status: config.h is unchanged
config.status: executing depfiles commands
</code>```

WHich reason could cause this problem? How can I solve it?
Thanks

答:
Have you exported your toolchain path? You need to do that. In order to work.

How to know you exported or not?

type echo $PATH in your terminal it will show the path.

Solution to your problem: export your toolchain path.

Below is example toolchain path. You need to give the right path of your toolchain.

Example:

```<code>export PATH=/opt/your_toolchains/path/arm-unknown-linux-gnu/bin/:$PATH
</code>```

Title: Cross compiling problems

Body:
I have installed the cross compile tools in the ubuntu 16.04.And when I type arm-linux-gnueabihf-gcc -vin the command line.The command line shows that the cross compiler can work as follows:

Using built-in specs.
COLLECT_GCC=arm-linux-gnueabihf-gcc
COLLECT_LTO_WRAPPER=/home/nju/ti-processor-linux-sdk/linux-devkit/sysroots/x86_64-arago-linux/usr/bin/../libexec/gcc/arm-linux-gnueabihf/6.2.1/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: /home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/snapshots/gcc-linaro-6.2-2016.11/configure SHELL=/bin/bash --with-mpc=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-mpfr=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gmp=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gnu-as --with-gnu-ld --disable-libstdcxx-pch --disable-libmudflap --with-cloog=no --with-ppl=no --with-isl=no --disable-nls --enable-c99 --enable-gnu-indirect-function --disable-multilib --with-tune=cortex-a9 --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --enable-multiarch --with-build-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/sysroots/arm-linux-gnueabihf --enable-lto --enable-linker-build-id --enable-long-long --enable-shared --with-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu/arm-linux-gnueabihf/libc --enable-languages=c,c++,fortran,lto --enable-checking=release --disable-bootstrap --build=x86_64-unknown-linux-gnu --host=x86_64-unknown-linux-gnu --target=arm-linux-gnueabihf --prefix=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu
Thread model: posix
gcc version 6.2.1 20161016 (Linaro GCC 6.2-2016.11)

But when I execute ./configure --host=arm-linux-gnueabihf,the system cannot detect the arm-linux-gnueabihf tools.

configure: WARNING: If you wanted to set the --build type, don't use --host.
If a cross compiler is detected then cross compile mode will be used.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for arm-linux-gnueabihf-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking for arm-linux-gnueabihf-g++... no
checking for arm-linux-gnueabihf-c++... no
checking for arm-linux-gnueabihf-gpp... no
checking for arm-linux-gnueabihf-aCC... no
checking for arm-linux-gnueabihf-CC... no
checking for arm-linux-gnueabihf-cxx... no
checking for arm-linux-gnueabihf-cc++... no
checking for arm-linux-gnueabihf-cl.exe... no
checking for arm-linux-gnueabihf-FCC... no
checking for arm-linux-gnueabihf-KCC... no
checking for arm-linux-gnueabihf-RCC... no
checking for arm-linux-gnueabihf-xlC_r... no
checking for arm-linux-gnueabihf-xlC... no
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking for style of include used by make... GNU
checking dependency style of g++... gcc3
checking for arm-linux-gnueabihf-gcc... no
checking for gcc... gcc
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking dependency style of gcc... gcc3
checking for pthread_rwlock_init in -lpthread... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking sys/ioctl.h usability... yes
checking sys/ioctl.h presence... yes
checking for sys/ioctl.h... yes
checking for unistd.h... (cached) yes
checking gtk/gtk.h usability... no
checking gtk/gtk.h presence... no
checking for gtk/gtk.h... no
checking pthread.h usability... yes
checking pthread.h presence... yes
checking for pthread.h... yes
checking for stdlib.h... (cached) yes
checking for GNU libc compatible malloc... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
config.status: config.h is unchanged
config.status: executing depfiles commands

WHich reason could cause this problem? How can I solve it?
Thanks

Body:
Have you exported your toolchain path? You need to do that. In order to work.

How to know you exported or not?

type echo $PATH in your terminal it will show the path.

Solution to your problem: export your toolchain path.

Below is example toolchain path. You need to give the right path of your toolchain.

Example:

export PATH=/opt/your_toolchains/path/arm-unknown-linux-gnu/bin/:$PATH


问:
How to configure grunt-protractor-runner / protractor / selenium-webdriver to configure firefox 56 to accept all SSL certs
I have an angular webapp which is becoming a PWA. So, it has a ServiceWorker. And, so, it requires a valid https session (or an exception on the certificate presenter by the server).

It also has automatic E2E tests, with protractor.

I do not find how to get them running with firefox (chrome is ok), with a server running on localhost and listening on port 8447.

I am failing to convince the instance of firefox launched by protractor through selenium-webdriver to accept all SSL certs, or even only the cert used by this test server.

I am using firefox driver in "directConnect" mode.

I am using grunt because I have to launch a few things before and after the E2E tests.

In my Gruntfile.js, my protractor / firefox session is :

```<code>grunt.initConfig({
    protractor: {
        firefox: {
            options: {
                keepAlive: true,
                configFile: "test/conf.firefox.js"
            },
            run: {}
        },
        ...
    },...
});
</code>```

In test/conf.firefox.js, I have :

```<code>exports.config = {
    framework: 'jasmine',
    directConnect: true,
    specs: ['delegations.js'],
    useAllAngular2AppRoots: true,
    capabilities: {
        'browserName': 'firefox',
        'acceptSSlCerts': true
    },
    webDriverProxy: null,
    verbose: true,
    jasmineNodeOpts: {
        isVerbose: true,
        showColors: true,
        defaultTimeoutInterval: 120000
    },
    allScriptsTimeout: 120000,
    maxSessions: 1,
    params: {
            url: 'https://localhost:8447/mywebapp'
    }
}
</code>```

I tried accepSslCerts along with a lot of other options, with no success.
Does someone have a clue ? I was all ok before with firefox 53 and protractor 4.x.

I am using :

grunt-protractor-runner 5.0.0

protractor 5.0.0

selenium-webdriver 3.6.0

firefox 56

答:
The capability was renamed in Selenium 3 to acceptInsecureCerts:

exports.config = {
    framework: 'jasmine',
    directConnect: true,
    specs: ['delegations.js'],
    useAllAngular2AppRoots: true,
    capabilities: {
        'browserName': 'firefox',
        'acceptInsecureCerts': true
    },
```

Body:
I have an angular webapp which is becoming a PWA. So, it has a ServiceWorker. And, so, it requires a valid https session (or an exception on the certificate presenter by the server).

It also has automatic E2E tests, with protractor.

I do not find how to get them running with firefox (chrome is ok), with a server running on localhost and listening on port 8447.

I am failing to convince the instance of firefox launched by protractor through selenium-webdriver to accept all SSL certs, or even only the cert used by this test server.

I am using firefox driver in "directConnect" mode.

I am using grunt because I have to launch a few things before and after the E2E tests.

In my Gruntfile.js, my protractor / firefox session is :

grunt.initConfig({
    protractor: {
        firefox: {
            options: {
                keepAlive: true,
                configFile: "test/conf.firefox.js"
            },
            run: {}
        },
        ...
    },...
});

In test/conf.firefox.js, I have :

exports.config = {
    framework: 'jasmine',
    directConnect: true,
    specs: ['delegations.js'],
    useAllAngular2AppRoots: true,
    capabilities: {
        'browserName': 'firefox',
        'acceptSSlCerts': true
    },
    webDriverProxy: null,
    verbose: true,
    jasmineNodeOpts: {
        isVerbose: true,
        showColors: true,
        defaultTimeoutInterval: 120000
    },
    allScriptsTimeout: 120000,
    maxSessions: 1,
    params: {
            url: 'https://localhost:8447/mywebapp'
    }
}

I tried accepSslCerts along with a lot of other options, with no success.
Does someone have a clue ? I was all ok before with firefox 53 and protractor 4.x.

I am using :

grunt-protractor-runner 5.0.0

protractor 5.0.0

selenium-webdriver 3.6.0

firefox 56


问:
Pass data to custom npm package module
I'm new to building custom npm packages and I'm getting lost configuring it with data coming from the application it is using it.

EDIT: This is just an example but the app will have more methods and those fake a and b will be used from many of those methods.

Basically on App I'm requiring my package in this way:

```<code>var a = 'a';
var b = 'b';
var module = require('module')(a, b);
module.test();
</code>```

My module in his index file has:

```<code>var a;
var b;

function test() {
  return {
    a: a,
    b: b
  };
}

module.exports = function(_a, _b) {
  a = _a;
  b = _b;

  return {
    test: test
  }
};
</code>```

As you can guess it is not working as I was expecting... How can I pass my custom data to my npm package and be able using that data along my methods?

答:
shouldnt you use it something like this

```<code>var a = 'a';
var b = 'b';
var module = require('module');
module.init(a,b);

// do some other code....

module.test();
</code>```

and in your module like this:

```<code>var _a = null;
var _b = null;
var test = function() {
    return {
        a: _a,
        b: _b
    }
}

var init = function(a, b) {
    _a = a;
    _b = b;
}

module.exports = {
    init,
    test
};
</code>```

Title: Pass data to custom npm package module

Body:
I'm new to building custom npm packages and I'm getting lost configuring it with data coming from the application it is using it.

EDIT: This is just an example but the app will have more methods and those fake a and b will be used from many of those methods.

Basically on App I'm requiring my package in this way:

var a = 'a';
var b = 'b';
var module = require('module')(a, b);
module.test();

My module in his index file has:

var a;
var b;

function test() {
  return {
    a: a,
    b: b
  };
}

module.exports = function(_a, _b) {
  a = _a;
  b = _b;

  return {
    test: test
  }
};

As you can guess it is not working as I was expecting... How can I pass my custom data to my npm package and be able using that data along my methods?

Body:
shouldnt you use it something like this

var a = 'a';
var b = 'b';
var module = require('module');
module.init(a,b);

// do some other code....

module.test();

and in your module like this:

var _a = null;
var _b = null;
var test = function() {
    return {
        a: _a,
        b: _b
    }
}

var init = function(a, b) {
    _a = a;
    _b = b;
}

module.exports = {
    init,
    test
};


问:
How to ensure maximum compatibility/portability of my code?
With newer versions of MATLAB newer features have been introduced such as the string class that allows creating string arrays and the possibility to define strings using double quotes "" (see answer), among other features.

This is great news because this kind of features make life easier. However, this also brings a problem to the table.

I share code with colleagues frequently and they may not necessarily have the latest version of MATLAB installed. If they run my code written using the newer syntax it will crash in their machines.

What techniques/measures can I put in practice to ensure maximum compatibility/portability of my code?

This post suggests refraining from using the newer features, but then what's in it for me by using the newest version if I have to force myself to use the older syntax?

Is using the older syntax and checking for the MATLAB version the only options I have?

答:
I would do the following:

Decide what versions of MATLAB you want to support. This could be either a specific version of MATLAB (the one you use to develop the code), or it could be a range of versions. This may have an upper bound as well as a lower bound.

Your decision here might be based on the range of versions that you know your colleagues require you to support; or it might be based on practical considerations. For example, I doubt you'd want to support really old versions of MATLAB like v5, otherwise you wouldn't be able to use logical variables, cell arrays, or arrays with dimension greater than two. Or you might really want to use the new string arrays, in which case you'll restrict it to R2017a and above, and your colleagues will have to upgrade.

In terms of recent versions, the really big boundaries are R2008a (which introduced the new object-oriented code) and R2014b (which introduced Handle Graphics 2). But your specific needs may dictate other boundaries too.

Right at the start of your code, test the version of MATLAB using ver or verLessThan, and error if it's not in that range, with a message like 'Unsupported MATLAB version'.

Within that version range, you can either limit yourself to the lowest-common denominator of functionality that is present across all versions, or you can occasionally use a test on ver or verLessThan to switch between behaviours depending on the version.

At the end of the day, if you're producing a product for others (rather than code to be used by just yourself), you need to do some research on what platforms your potential customers have (or can be persuaded to install), find a range of platforms that is big enough to satisfy most of your customers but small enough to be practical for you, and support those platforms.


问:
how to stretch image
i want to strech image by using Graphics but unable here is my code it shows image in size that i want but not strach the image</p>

```<code>void imageload () {
    FileDialog fd = new FileDialog(MainFram.this,"Open", FileDialog.LOAD);
    fd.show();
    if(fd.getFile() == null){
        //Label1.setText("You have not chosen any image files yet");
    }else{
        String d = (fd.getDirectory() + fd.getFile());
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image1 = toolkit.getImage(d);
        saveImage = d;//if user want to save Image
        ImageIcon icon=new ImageIcon(Image1);
        lblImage.setIcon(icon);
        lblImage.setMinimumSize(new Dimension(50, 70));
        lblImage.repaint();
    }
}
</code>```

答:
Call getScaledInstance() to scale the image to the size you want before you create the ImageIcon. You don't need to call setMinimumSize on the label.

```<code>Image image = toolkit.getImage("pic.jpg");
Image scaledImage = image.getScaledInstance(50, 70, Image.SCALE_DEFAULT);
ImageIcon icon=new ImageIcon(scaledImage);
</code>```

Title: how to stretch image

Body:
i want to strech image by using Graphics but unable here is my code it shows image in size that i want but not strach the image

void imageload () {
    FileDialog fd = new FileDialog(MainFram.this,"Open", FileDialog.LOAD);
    fd.show();
    if(fd.getFile() == null){
        //Label1.setText("You have not chosen any image files yet");
    }else{
        String d = (fd.getDirectory() + fd.getFile());
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image1 = toolkit.getImage(d);
        saveImage = d;//if user want to save Image
        ImageIcon icon=new ImageIcon(Image1);
        lblImage.setIcon(icon);
        lblImage.setMinimumSize(new Dimension(50, 70));
        lblImage.repaint();
    }
}

Body:
Call getScaledInstance() to scale the image to the size you want before you create the ImageIcon. You don't need to call setMinimumSize on the label.

Image image = toolkit.getImage("pic.jpg");
Image scaledImage = image.getScaledInstance(50, 70, Image.SCALE_DEFAULT);
ImageIcon icon=new ImageIcon(scaledImage);


问:
Finding specific instance of class?
I've just started learning java and I'm trying to create an application to register students.

Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.

```<code>    public class RegStudent {

    ArrayList<Student> studentList = new ArrayList<>();

    Scanner input = new Scanner(System.in);

    public void reggaStudent(int start) {

        while (start != 0) {
            String programNamn, studNamn;
            int totalPoint, antalKurser;

            System.out.println("Vad heter programmet?");
            programNamn = input.nextLine();
            System.out.println("Vad heter studenten");
            studNamn = input.nextLine();
            System.out.println("Hur många poäng har studenten?");
            totalPoint = input.nextInt();
            System.out.println("Hur många kurser är studenten registrerad på?");
            antalKurser = input.nextInt();

            // Add student to list of students
            studentList.add(new Student(totalPoint, antalKurser,
                                        programNamn, studNamn));
            System.out.println("Vill du registrera in en fler studenter? "
                                + "Skriv 1 för ja och 0 för nej");
            start = input.nextInt();
            input.nextLine();
        } // End of whileloop

    }
}
</code>```

The class is:

```<code>public class Student {
    private int totalPoint;
    private int antalKurser;
    private String programNamn;
    private String studNamn;
    private static int counter;

    public Student(int totalPoint, int antalKurser, String program, String studNamn) {

        this.totalPoint = totalPoint;
        this.antalKurser = antalKurser;
        this.programNamn = program;
        this.studNamn = studNamn;
        counter++;
    }

    public int getTotalPoint() {
        return totalPoint;
    }

    public void setTotalPoint(int totalPoint) {
        this.totalPoint = totalPoint;
    }

    public int getAntalKurser() {
        return antalKurser;
    }

    public void setAntalKurser(int antalKurser) {
        this.antalKurser = antalKurser;
    }

    public String getProgramNamn() {
        return programNamn;
    }

    public void setProgramNamn(String programNamn) {
        this.programNamn = programNamn;
    }

    public String getStudNamn() {
        return studNamn;
    }

    public void setStudNamn(String studNamn) {
        this.studNamn = studNamn;
    }
    public static int getCount(){

        return counter;
    }
    @Override
    public String toString() {

        return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
        + "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
    }

}
</code>```

How do I go about to get and set the instance variables in specific instance? I.e find the instances.

I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.

I've added a counter just to see I actually created some instances of the class.

答:
You simply query objects for certain properties, like:

```<code>for (Student student : studentList) {
  if (student.getProgramName().equals("whatever")) {
    some match, now you know that this is the student you are looking for
</code>```

In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.

Alternatively, you could "externalize" a property, and start putting objects into maps for example.

Title: Finding specific instance of class?

Body:
I've just started learning java and I'm trying to create an application to register students.

Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.

    public class RegStudent {

    ArrayList<Student> studentList = new ArrayList<>();

    Scanner input = new Scanner(System.in);

    public void reggaStudent(int start) {

        while (start != 0) {
            String programNamn, studNamn;
            int totalPoint, antalKurser;

            System.out.println("Vad heter programmet?");
            programNamn = input.nextLine();
            System.out.println("Vad heter studenten");
            studNamn = input.nextLine();
            System.out.println("Hur många poäng har studenten?");
            totalPoint = input.nextInt();
            System.out.println("Hur många kurser är studenten registrerad på?");
            antalKurser = input.nextInt();

            // Add student to list of students
            studentList.add(new Student(totalPoint, antalKurser,
                                        programNamn, studNamn));
            System.out.println("Vill du registrera in en fler studenter? "
                                + "Skriv 1 för ja och 0 för nej");
            start = input.nextInt();
            input.nextLine();
        } // End of whileloop

    }
}

The class is:

public class Student {
    private int totalPoint;
    private int antalKurser;
    private String programNamn;
    private String studNamn;
    private static int counter;

    public Student(int totalPoint, int antalKurser, String program, String studNamn) {

        this.totalPoint = totalPoint;
        this.antalKurser = antalKurser;
        this.programNamn = program;
        this.studNamn = studNamn;
        counter++;
    }

    public int getTotalPoint() {
        return totalPoint;
    }

    public void setTotalPoint(int totalPoint) {
        this.totalPoint = totalPoint;
    }

    public int getAntalKurser() {
        return antalKurser;
    }

    public void setAntalKurser(int antalKurser) {
        this.antalKurser = antalKurser;
    }

    public String getProgramNamn() {
        return programNamn;
    }

    public void setProgramNamn(String programNamn) {
        this.programNamn = programNamn;
    }

    public String getStudNamn() {
        return studNamn;
    }

    public void setStudNamn(String studNamn) {
        this.studNamn = studNamn;
    }
    public static int getCount(){

        return counter;
    }
    @Override
    public String toString() {

        return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
        + "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
    }

}

How do I go about to get and set the instance variables in specific instance? I.e find the instances.

I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.

I've added a counter just to see I actually created some instances of the class.

Body:
You simply query objects for certain properties, like:

for (Student student : studentList) {
  if (student.getProgramName().equals("whatever")) {
    some match, now you know that this is the student you are looking for

In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.

Alternatively, you could "externalize" a property, and start putting objects into maps for example.


问:
how to select User to Select based on country using mvc?
I have two tables one is country table another one is doctor table both contains  country fields.if i select any country name from country based on the country name i want to display doctors name from the doctor table.

```<code><div class="col-lg-4">
                            <fieldset class="form-group">
                                <label class="form-label" for="exampleInputEmail1">Country</label>
                                @Html.DropDownList("CountryID", null, "--- Select Country ---", new { @class = "select2-arrow" })
                                @Html.ValidationMessageFor(model => Model.CountryID, null, new { @style = "color: red" })
                            </fieldset>
                        </div>
                        <div class="col-lg-4">
                            <fieldset class="form-group">
                                <label class="form-label" for="exampleInput">Doctor Name</label>
                                <select id="UserRefID" class="select2-arrow"></select>
                                @Html.ValidationMessageFor(model => Model.UserRefID, null, new { @style = "color: red" })
                            </fieldset>
                        </div>
</code>```

Country bind Code:

```<code>#region Country
        public void Country_Bind()
        {
            userType type = new userType();
            DataSet ds = type.Get_Country();
            List<SelectListItem> coutrylist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                coutrylist.Add(new SelectListItem { Text = dr["CountryName"].ToString(), Value = dr["CountryID"].ToString() });
            }
            ViewBag.CountryID = coutrylist;
        }
        #endregion
</code>```

DAL :

```<code>public DataSet Get_Country()
        {
            SqlCommand cmd = new SqlCommand("Select * From Country", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
</code>```

Doctor Bind based one country ID

#region Doctor Bind

```<code>    public JsonResult Company_Bind(string CountryID)
    {
        userType type = new userType();
        DataSet ds = type.Get_Doctor(CountryID);
        List<SelectListItem> Doctorlist = new List<SelectListItem>();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            Doctorlist.Add(new SelectListItem { Text = dr["Tittle"].ToString() + " " + dr["DoctorName"].ToString(), Value = dr["DoctorID"].ToString() });
        }
        return Json(Doctorlist, JsonRequestBehavior.AllowGet);
    }
    #endregion

public DataSet Get_Doctor(string CountryID)
        {
            SqlCommand com = new SqlCommand("Select * from DoctorRegistration where Country=@Country", con);
            com.Parameters.AddWithValue("@Country", CountryID);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

<script>
        $(document).ready(function () {
            $("#CountryID").change(function () {
                var id = $(this).val();
                $("#UserRefID").empty();
                $.get("Company_Bind", { CountryID: id }, function (data) {
                    var v = "<option>--- Select State ---</option>";
                    $.each(data, function (i, v1) {
                        v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
                    });
                    $("#UserRefID").html(v);
                });
            });

        });
    </script>
</code>```

If i use [Authorize] i cann't use ajax function

```<code> //[Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            UserType_Bind();
            Country_Bind();
            //Doctor_Bind();
            return View();
        }
</code>```

if i don't use [Authorize] working fine

答:
You are passing the string Company_Bind as the url for the ajax call. So it will be appended to the current pages url and a call will be made to that.

For example, if your currrent page is yourBaseUrl/Home/Index, the call will be made to yourBaseUrl/Home/index/Company_Bind?CountryID=4

If your current page is yourBaseUrl/Doctors/List, the call will be made to yourBaseUrl/Doctors/List/Company_Bind?CountryID=4

This will give you 404 response as that is invalid url to your action method.

You should consider using the Url.Action helper method to generate the correct relative path to the action  method, irrespective of your current page.

So if your javascript code was inside a razor view,you can directly use it like

```<code>$.get("@Url.Action("Company_Bind")", { CountryID: id }, function (data) {

});
</code>```

Or use the Url.Action overload which accepts the action method name and controller name.

```<code>$.get("@Url.Action("Company_Bind","Doctors")", { CountryID: id }, function (data) {

});
</code>```

If it is in an external js file, you can still use the Url.Action helper in the razor view to generate the url and pass it to the external js file as explained in this post.

Body:
I have two tables one is country table another one is doctor table both contains  country fields.if i select any country name from country based on the country name i want to display doctors name from the doctor table.

                            <fieldset class="form-group">
                                Country
                                @Html.DropDownList("CountryID", null, "--- Select Country ---", new { @class = "select2-arrow" })
                                @Html.ValidationMessageFor(model => Model.CountryID, null, new { @style = "color: red" })
                            </fieldset>

                            <fieldset class="form-group">
                                Doctor Name
                                <select id="UserRefID" class="select2-arrow"></select>
                                @Html.ValidationMessageFor(model => Model.UserRefID, null, new { @style = "color: red" })
                            </fieldset>

Country bind Code:

#region Country
        public void Country_Bind()
        {
            userType type = new userType();
            DataSet ds = type.Get_Country();
            List<SelectListItem> coutrylist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                coutrylist.Add(new SelectListItem { Text = dr["CountryName"].ToString(), Value = dr["CountryID"].ToString() });
            }
            ViewBag.CountryID = coutrylist;
        }
        #endregion

DAL :

public DataSet Get_Country()
        {
            SqlCommand cmd = new SqlCommand("Select * From Country", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

Doctor Bind based one country ID

#region Doctor Bind

    public JsonResult Company_Bind(string CountryID)
    {
        userType type = new userType();
        DataSet ds = type.Get_Doctor(CountryID);
        List<SelectListItem> Doctorlist = new List<SelectListItem>();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            Doctorlist.Add(new SelectListItem { Text = dr["Tittle"].ToString() + " " + dr["DoctorName"].ToString(), Value = dr["DoctorID"].ToString() });
        }
        return Json(Doctorlist, JsonRequestBehavior.AllowGet);
    }
    #endregion

public DataSet Get_Doctor(string CountryID)
        {
            SqlCommand com = new SqlCommand("Select * from DoctorRegistration where Country=@Country", con);
            com.Parameters.AddWithValue("@Country", CountryID);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

If i use [Authorize] i cann't use ajax function

 //[Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            UserType_Bind();
            Country_Bind();
            //Doctor_Bind();
            return View();
        }

if i don't use [Authorize] working fine

Body:
You are passing the string Company_Bind as the url for the ajax call. So it will be appended to the current pages url and a call will be made to that.

For example, if your currrent page is yourBaseUrl/Home/Index, the call will be made to yourBaseUrl/Home/index/Company_Bind?CountryID=4

If your current page is yourBaseUrl/Doctors/List, the call will be made to yourBaseUrl/Doctors/List/Company_Bind?CountryID=4

This will give you 404 response as that is invalid url to your action method.

You should consider using the Url.Action helper method to generate the correct relative path to the action  method, irrespective of your current page.

So if your javascript code was inside a razor view,you can directly use it like

$.get("@Url.Action("Company_Bind")", { CountryID: id }, function (data) {

});

Or use the Url.Action overload which accepts the action method name and controller name.

$.get("@Url.Action("Company_Bind","Doctors")", { CountryID: id }, function (data) {

});

If it is in an external js file, you can still use the Url.Action helper in the razor view to generate the url and pass it to the external js file as explained in this post.


答:
On way to go with is to create your own bin first:</p>

```<code>library(dplyr)
library(ggplot)
data %>%
  count(Onset) %>%
  mutate_at("Onset", factor) %>%
  ggplot(aes(Onset, n)) +
  geom_bar(stat = "identity") +
  labs (x= "Date of Onset of Senescence (Julian)", y="# of Trees")
</code>```

Title: Adding additional bin labels on x axis ggplot

Body:
I am seeking to create a plot. Here's what I've got so far:

I want to make it so each of my bins has it's own label.

I tried:

  p1<-ggplot(data, aes(x=Onset)) +
  geom_histogram(binwidth= 1)+
  labs (x= "Date of Onset of Senescence (Julian)", y="# of Trees")

p1 + scale_y_continuous(breaks=c(270, 272, 274, 276, 278, 280,282,284,286,288,290, 292,294,296,298,300))

But that wasn't working for me. Please find my data attached:

> dput(data)
structure(list(ï..Tree = structure(c(1L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 11L, 2L, 3L, 12L, 15L, 16L, 17L, 18L, 19L, 20L, 21L,
22L, 13L, 14L, 23L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 24L,
25L), .Label = c("A1", "A10", "A11", "A2", "A3", "A4", "A5",
"A6", "A7", "A8", "A9", "B1", "B10", "B11", "B2", "B3", "B4",
"B5", "B6", "B7", "B8", "B9", "C1", "C10", "C11", "C2", "C3",
"C4", "C5", "C6", "C7", "C8", "C9"), class = "factor"), SourceLocation = structure(c(3L,
3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 7L,
7L, 7L, 6L, 6L, 6L, 2L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 6L, 6L
), .Label = c("Brooke Township", "Delaware Township", "Dunwich Township",
"Mosa Township", "Pelee Island", "Sombra Township", "Yarmouth Township"
), class = "factor"), Onset = c(279L, 279L, 285L, 283L, 283L,
275L, 277L, 287L, 287L, 295L, 285L, 271L, 283L, 269L, 275L, 285L,
285L, 285L, 285L, 285L, 287L, 283L, 279L, 293L, 283L, 285L, 285L,
283L, 279L, 279L, 279L, 277L, 279L), Completion = c(289L, 287L,
299L, 299L, 295L, 287L, 287L, 299L, NA, NA, NA, 285L, 299L, 285L,
287L, NA, NA, NA, NA, 295L, NA, 299L, 295L, NA, 295L, 299L, 299L,
293L, 297L, 299L, 295L, 295L, 299L), Duration = c(10L, 8L, 14L,
16L, 12L, 12L, 10L, 12L, NA, NA, NA, 14L, 16L, 16L, 12L, NA,
NA, NA, NA, 10L, NA, 16L, 16L, NA, 14L, 14L, 14L, 10L, 18L, 20L,
16L, 18L, 20L)), .Names = c("ï..Tree", "SourceLocation", "Onset",
"Completion", "Duration"), row.names = c(NA, 33L), class = "data.frame")

Body:
On way to go with is to create your own bin first:

library(dplyr)
library(ggplot)
data %>%
  count(Onset) %>%
  mutate_at("Onset", factor) %>%
  ggplot(aes(Onset, n)) +
  geom_bar(stat = "identity") +
  labs (x= "Date of Onset of Senescence (Julian)", y="# of Trees")


问:
How to post form data from reactjs to controller in mvc asp.net
I am new to React. I am trying to create a form in asp.net with react. when posting form data from reactjs to controller in mvc asp.net, the data is not getting passed. I have shared my code below. Please let me know what changes I have to make to make it work.

controller:

```<code>[Route("InputEmployee")]

        public void InputEmployee([FromBody]EmployeeTable Employee)
        {
            db.EmployeeTables.Add(Employee);
                   db.SaveChanges();
        }
</code>```

Reactjs code:

```<code>class InputValues extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(e) {
        e.preventDefault();
        const data = new FormData();
        data.append = this.firstName.value;
        data.append = this.lastName.value;
        data.append = this.gender.value;
        data.append = this.designation.value;
        data.append = this.salary.value;
        data.append = this.city.value;
        data.append = this.country.value;
        var xhr = new XMLHttpRequest();
        xhr.open('post', this.props.url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                // Do something on success
            }
        }
        xhr.send(data);
    }

    render() {
        return(
          <div>
              <form onSubmit={this.handleSubmit}>
          <label htmlFor="FirstName">First Name </label><br/>
          <input id="FirstName" type="text"  placeholder="Enter First Name" ref={(firstName) => this.firstName = firstName} />
          <br/><br/>
          <label htmlFor="LastName">Last Name: </label><br/>
          <input id="LastName" type="text"  placeholder="Enter Last Name"  ref={(lastName) => this.lastName = lastName} />
          <br/><br/>
          <label htmlFor="Gender">Gender: </label><br/>
          <input id="Gender" type="text"  placeholder="Gender"  ref={(gender) => this.gender = gender} />
          <br/><br/>
          <label htmlFor="Designation">Designation: </label><br/>
          <input id="Designation" type="text"  placeholder="Enter Designation" ref={(designation) => this.designation = designation} />
          <br/><br/>
          <label htmlFor="Salary">Salary: </label><br/>
          <input id="Salary" type="number"  placeholder="Enter Salary" ref={(salary) => this.salary = salary} />
          <br/><br/>
          <label htmlFor="City">City: </label><br/>
          <input id="City" type="text"  placeholder="Enter City" ref={(city) => this.city = city} />
          <br/><br/>
          <label htmlFor="Country">Country: </label><br/>
          <input id="Country" type="text"  placeholder="Enter Country" ref={(country) => this.country = country} />
          <p>
            <button type="submit">Submit</button>
          </p>
        </form>
      </div>
    );
          }
};

ReactDOM.render(<InputValues url="api/Employee/InputEmployee" />,
          document.getElementById('grid1'))
</code>```

values not getting passed:

after making changes in append:

答:
You're not building your FormData object correctly, append is a function so you need to use it as such:

```<code>data.append = ...; // wrong, overwrites the append function
data.append('key', 'value'); // correct, calls the function
</code>```

Also, I'd recommend using the native Fetch API for sending web requests as it's a lot neater than working with raw XHR requests. It's not 100% cross-browser yet but there are various libraries you can use as a polyfill e.g. whatwg-fetch

Body:
I am new to React. I am trying to create a form in asp.net with react. when posting form data from reactjs to controller in mvc asp.net, the data is not getting passed. I have shared my code below. Please let me know what changes I have to make to make it work.

controller:

[Route("InputEmployee")]

        public void InputEmployee([FromBody]EmployeeTable Employee)
        {
            db.EmployeeTables.Add(Employee);
                   db.SaveChanges();
        }

Reactjs code:

class InputValues extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(e) {
        e.preventDefault();
        const data = new FormData();
        data.append = this.firstName.value;
        data.append = this.lastName.value;
        data.append = this.gender.value;
        data.append = this.designation.value;
        data.append = this.salary.value;
        data.append = this.city.value;
        data.append = this.country.value;
        var xhr = new XMLHttpRequest();
        xhr.open('post', this.props.url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                // Do something on success
            }
        }
        xhr.send(data);
    }

    render() {
        return(

              <form onSubmit={this.handleSubmit}>
          First Name

          <input id="FirstName" type="text"  placeholder="Enter First Name" ref={(firstName) => this.firstName = firstName} />

          Last Name:

          <input id="LastName" type="text"  placeholder="Enter Last Name"  ref={(lastName) => this.lastName = lastName} />

          Gender:

          <input id="Gender" type="text"  placeholder="Gender"  ref={(gender) => this.gender = gender} />

          Designation:

          <input id="Designation" type="text"  placeholder="Enter Designation" ref={(designation) => this.designation = designation} />

          Salary:

          <input id="Salary" type="number"  placeholder="Enter Salary" ref={(salary) => this.salary = salary} />

          City:

          <input id="City" type="text"  placeholder="Enter City" ref={(city) => this.city = city} />

          Country:

          <input id="Country" type="text"  placeholder="Enter Country" ref={(country) => this.country = country} />

            <button type="submit">Submit</button>

        </form>

    );
          }
};

ReactDOM.render(<InputValues url="api/Employee/InputEmployee" />,
          document.getElementById('grid1'))

values not getting passed:

after making changes in append:

Body:
You're not building your FormData object correctly, append is a function so you need to use it as such:

data.append = ...; // wrong, overwrites the append function
data.append('key', 'value'); // correct, calls the function

Also, I'd recommend using the native Fetch API for sending web requests as it's a lot neater than working with raw XHR requests. It's not 100% cross-browser yet but there are various libraries you can use as a polyfill e.g. whatwg-fetch


问:
Pip, pip3, and conflicting python distributions
I am having trouble installing the python packages PyTransit and ktransit to Anaconda 3 (on Linux). It seems like lots of others have had similar errors, but none of their solutions have worked for me. There's a bunch of stuff going on:

pip install ktransit gives:

```<code>/usr/bin/ld: /home/name/anaconda3/lib/libgfortran.a(pause.o): relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object; recompile with -fPIC

/home/name/anaconda3/lib/libgfortran.a: error adding symbols: Bad value
    collect2: error: ld returned 1 exit status
</code>```

I would try to use ./configure with --enable-shared, but there's no config file. I tried adding extra_compile_args = ["-fPIC"], extra_link_args=["-fPIC"] to setup.py (as in https://github.com/h5py/h5py/issues/851), but that did nothing.

pip install pytransit gives different errors:

```<code> #warning "Using deprecated NumPy API, disable it by " \

Warning: src/gimenez.f90:35: Illegal preprocessor directive
    Warning: src/gimenez.f90:36: Illegal preprocessor directive
    Warning: src/gimenez.f90:37: Illegal preprocessor directive
    src/gimenez.f90:271.33:

        real(8), dimension(CHUNK_SIZE, npol) :: d
                                     1
    Error: Symbol 'chunk_size' at (1) has no IMPLICIT type
</code>```

Here's where it gets interesting.  Using pip3 (or sudo pip) allows ktransit to install successfully, but does nothing for pytransit. Pip and pip3 seem to be tied to different places:

```<code>which pip
/home/name/anaconda3/bin/pip

 which pip3
/usr/local/bin/pip3

which python
/home/name/anaconda3/bin/python
</code>```

Lastly, When I try to import ktransit in a jupyter notebook through anaconda, it fails, but when I import ktransit in the Jupyter QtConsole, it succeeds, but seems to contain itself and not provide actual functionality. What I mean is that I can't reference anything within the module, and:

```<code>Help on package ktransit:

NAME
    ktransit

PACKAGE CONTENTS
    ktransit (package)
    setup

FILE
    (built-in)
</code>```

I'm thinking that whatever version of python is associated with /usr/bin is somehow messing with me...or maybe there's something wrong with my gcc or libgfortran? I have gcc versions 4.8.5 and 6 (gcc --version gives 4.8.5, but -update-alternatives says there's only one version, 6).

Thanks for taking the time to read this far. I would be very grateful for any suggestions or ideas!

答: Figured it out -- I uninstalled Anaconda, made sure my python was pointing in the right direction, and then used sudo python -m pip install. Thank you to Nagev for pushing me to get rid of Anaconda!</p>

Body:
I am having trouble installing the python packages PyTransit and ktransit to Anaconda 3 (on Linux). It seems like lots of others have had similar errors, but none of their solutions have worked for me. There's a bunch of stuff going on:

pip install ktransit gives:

/usr/bin/ld: /home/name/anaconda3/lib/libgfortran.a(pause.o): relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object; recompile with -fPIC

/home/name/anaconda3/lib/libgfortran.a: error adding symbols: Bad value
    collect2: error: ld returned 1 exit status

I would try to use ./configure with --enable-shared, but there's no config file. I tried adding extra_compile_args = ["-fPIC"], extra_link_args=["-fPIC"] to setup.py (as in https://github.com/h5py/h5py/issues/851), but that did nothing.

pip install pytransit gives different errors:

 #warning "Using deprecated NumPy API, disable it by " \

Warning: src/gimenez.f90:35: Illegal preprocessor directive
    Warning: src/gimenez.f90:36: Illegal preprocessor directive
    Warning: src/gimenez.f90:37: Illegal preprocessor directive
    src/gimenez.f90:271.33:

        real(8), dimension(CHUNK_SIZE, npol) :: d
                                     1
    Error: Symbol 'chunk_size' at (1) has no IMPLICIT type

Here's where it gets interesting.  Using pip3 (or sudo pip) allows ktransit to install successfully, but does nothing for pytransit. Pip and pip3 seem to be tied to different places:

which pip
/home/name/anaconda3/bin/pip

 which pip3
/usr/local/bin/pip3

which python
/home/name/anaconda3/bin/python

Lastly, When I try to import ktransit in a jupyter notebook through anaconda, it fails, but when I import ktransit in the Jupyter QtConsole, it succeeds, but seems to contain itself and not provide actual functionality. What I mean is that I can't reference anything within the module, and:

Help on package ktransit:

NAME
    ktransit

PACKAGE CONTENTS
    ktransit (package)
    setup

FILE
    (built-in)

I'm thinking that whatever version of python is associated with /usr/bin is somehow messing with me...or maybe there's something wrong with my gcc or libgfortran? I have gcc versions 4.8.5 and 6 (gcc --version gives 4.8.5, but -update-alternatives says there's only one version, 6).

Thanks for taking the time to read this far. I would be very grateful for any suggestions or ideas!