问:
how to add two filters with or condition in ng-repeat Angular JS
i am using ng-repeate and in my filter i need to use one of the fields in upper bounded list that can not be refrenced by inner select filter , so i need to set filters in html block and not in js file .somthing like this:</p>

```<code><div ng-repeat="groupfield in gCtrl.groupingFields">
        <select ng-options="c.id as c.title for c in gCtrl.columnList | filter : {available:true } || {id:groupfield.fieldName}">
</select></div>
</code>```

答:
You can pass the filter a custom function. You cannot pass arguments to the actual filter function, so the trick is to create a function that returns the filter function, and pass groupfield to that.

```<code>function MyController() {
    this.customFilter = customFilter;

    function customFilter(groupfield) {
        return function(value, index, array) {
            return value.available || groupfield.fieldName === value.id;
        }
    }
}

<div ng-repeat="groupfield in gCtrl.groupingFields">
    <select required class="form-control" ng-model="groupfield.fieldName" ng-options="c.id as c.title for c in gCtrl.columnList | filter : groupCtrl.customFilter(groupfield)"></select>
</div>
</code>```

Body:
i am using ng-repeate and in my filter i need to use one of the fields in upper bounded list that can not be refrenced by inner select filter , so i need to set filters in html block and not in js file .somthing like this:

        <select ng-options="c.id as c.title for c in gCtrl.columnList | filter : {available:true } || {id:groupfield.fieldName}">
</select>

Body:
You can pass the filter a custom function. You cannot pass arguments to the actual filter function, so the trick is to create a function that returns the filter function, and pass groupfield to that.

function MyController() {
    this.customFilter = customFilter;

    function customFilter(groupfield) {
        return function(value, index, array) {
            return value.available || groupfield.fieldName === value.id;
        }
    }
}

<div ng-repeat="groupfield in gCtrl.groupingFields">
    <select required class="form-control" ng-model="groupfield.fieldName" ng-options="c.id as c.title for c in gCtrl.columnList | filter : groupCtrl.customFilter(groupfield)"></select>
</div>


来源: stackexchange

问:
All the nodes having an attribute
Is there some kind of xpath syntax I could use to get all the nodes(including child nodes) that have an identifierref present in the xml below? I've been trying something like XmlNodeList nodeList = xmlDoc.SelectNodes("//@identifierref"); but that doesn't return the child title node below the item nodes. Ideally I want to obtain a node list which has access to the item nodes that have identifierref present and the title nodes below them. Below is the xml I'm working with. Thanks in advance.

```<code><organization xmlns:adlcp="test1" xmlns="test2">
      <title>1.2 Tester</title>
      <item identifier="C2_LESSON1">
        <title>TestName1</title>
        <item identifier="I_SCO1" identifierref="SCO01">
          <title>Tester SCO 1</title>
        </item>
      </item>
      <item identifier="C2_LESSON2">
        <title>TestName2</title>
        <item identifier="I_SCO2" identifierref="SCO01">
          <title>Tester SCO 2</title>
        </item>
      </item>
      <item identifier="C2_LESSON3">
        <title>TestName3</title>
        <item identifier="I_SCO3" identifierref="SCO01">
          <title>Tester SCO 3</title>
        </item>
      </item>
    </organization>
</code>```

答:
I want to obtain a node list which has
  access to the item nodes that have
  identifierref present and the title
  nodes below them

```<code>//item[@identifier]
</code>```

The above selects all item elements in the document having an identifier attribute.

If you want to select also the title element child.

```<code>//item[@identifier]|//item[@identifier]/title
</code>```

But node set result order depends on host language (the most work with document order). Also there is no "grouping" feature: you can't iterate over each two because maybe some title is missing.

So, use first XPath expression first, and then iterate over those item getting the title with any DOM method or a relative XPath expression like:

```<code>title
</code>```

ContentLicense: CC BY-SA 2.5

Title: All the nodes having an attribute

Body:
Is there some kind of xpath syntax I could use to get all the nodes(including child nodes) that have an identifierref present in the xml below? I've been trying something like XmlNodeList nodeList = xmlDoc.SelectNodes("//@identifierref"); but that doesn't return the child title node below the item nodes. Ideally I want to obtain a node list which has access to the item nodes that have identifierref present and the title nodes below them. Below is the xml I'm working with. Thanks in advance.

<organization xmlns:adlcp="test1" xmlns="test2">
      <title>1.2 Tester</title>
      <item identifier="C2_LESSON1">
        <title>TestName1</title>
        <item identifier="I_SCO1" identifierref="SCO01">
          <title>Tester SCO 1</title>
        </item>
      </item>
      <item identifier="C2_LESSON2">
        <title>TestName2</title>
        <item identifier="I_SCO2" identifierref="SCO01">
          <title>Tester SCO 2</title>
        </item>
      </item>
      <item identifier="C2_LESSON3">
        <title>TestName3</title>
        <item identifier="I_SCO3" identifierref="SCO01">
          <title>Tester SCO 3</title>
        </item>
      </item>
    </organization>

Body:
I want to obtain a node list which has
  access to the item nodes that have
  identifierref present and the title
  nodes below them

//item[@identifier]

The above selects all item elements in the document having an identifier attribute.

If you want to select also the title element child.

//item[@identifier]|//item[@identifier]/title

But node set result order depends on host language (the most work with document order). Also there is no "grouping" feature: you can't iterate over each two because maybe some title is missing.

So, use first XPath expression first, and then iterate over those item getting the title with any DOM method or a relative XPath expression like:

title


问:
How to prevent user to enter specific key using Javascript
I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^).
Can any one tell me how to restrict uparrow(^) ?

```<code>function onlyAlphabet(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    var keychar = String.fromCharCode(key);
    var keycheck = /[a-zA-z\s]/;

    if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete  escape arrows
    {
        if (!keycheck.test(keychar)) {
            theEvent.returnValue = false;//for IE
            if (theEvent.preventDefault)
                theEvent.preventDefault();//Firefox
        }
    }
}
</code>```

html code

```<code><div class="form-group">
   <label class="form-text">Travels Name</label>
   <h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />
</div>
</code>```

答:
You can achieve that in a more simpler way like the following:

function onlyAlphabet(inputVal) {
  var patt=/^[a-zA-Z]+$/;
  if(patt.test(inputVal)){
    document.getElementById('txtTravel').value = inputVal;
  }
  else{
    var txt = inputVal.slice(0, -1);
    document.getElementById('txtTravel').value = txt;
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
    <label class="form-text">Travels Name</label>
    <input id="txtTravel" type="text" maxlength="50"
     oninput="onlyAlphabet(value)" />
 </div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^).
Can any one tell me how to restrict uparrow(^) ?

function onlyAlphabet(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    var keychar = String.fromCharCode(key);
    var keycheck = /[a-zA-z\s]/;

    if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete  escape arrows
    {
        if (!keycheck.test(keychar)) {
            theEvent.returnValue = false;//for IE
            if (theEvent.preventDefault)
                theEvent.preventDefault();//Firefox
        }
    }
}

html code

   Travels Name
   <h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />

Body:
You can achieve that in a more simpler way like the following:

function onlyAlphabet(inputVal) {
  var patt=/^[a-zA-Z]+$/;
  if(patt.test(inputVal)){
    document.getElementById('txtTravel').value = inputVal;
  }
  else{
    var txt = inputVal.slice(0, -1);
    document.getElementById('txtTravel').value = txt;
  }

}

<div class="form-group">
    <label class="form-text">Travels Name</label>
    <input id="txtTravel" type="text" maxlength="50"
     oninput="onlyAlphabet(value)" />
 </div>


问:
How to delete last character from a string using jQuery?
How to delete last character from a string for instance in 123-4- when I delete 4 it should display 123- using jQuery.

答:
You can do it with plain JavaScript:

```<code>alert('123-4-'.substr(0, 4)); // outputs "123-"
</code>```

This returns the first four characters of your string (adjust 4 to suit your needs).

Body:
You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).


问:
Google Maps Android V2 and Direction API
I'm developing an app where i need to know the path between the current user posistion and a point of interest.

I'm using android 2.3.3, google maps android v2 and direction api.
My problem is that all the code i have found is for the old version of the maps, and I also tried to adapt the code but i failed. I try to change GeoPoint (not supported in this new versione) in LatLng.
the problem is that i can't display the path, to do it i create a new polyline and i add it to the map.

i post my code:

Parser:

```<code>public interface Parser {
    public Route parse();
}
</code>```

XMLParser

```<code>public class XMLParser {
    // names of the XML tags
    protected static final String MARKERS = "markers";
    protected static final String MARKER = "marker";

    protected URL feedUrl;

    protected XMLParser(final String feedUrl) {
            try {
                    this.feedUrl = new URL(feedUrl);
            } catch (MalformedURLException e) {
                    Log.e(e.getMessage(), "XML parser - " + feedUrl);
            }
    }

    protected InputStream getInputStream() {
            try {
                    return feedUrl.openConnection().getInputStream();
            } catch (IOException e) {
                    Log.e(e.getMessage(), "XML parser - " + feedUrl);
                    return null;
            }
    }
}
</code>```

JsonParser (parse the google direction json)

```<code>public class JsonParser extends XMLParser implements Parser {
    /** Distance covered. **/
    private int distance;

    public JsonParser(String feedUrl) {
        super(feedUrl);
    }

    /**
     * Parses a url pointing to a Google JSON object to a Route object.
     * @return a Route object based on the JSON object.
     */

    public Route parse() {
        // turn the stream into a string
        final String result = convertStreamToString(this.getInputStream());
        //Create an empty route
        final Route route = new Route();
        //Create an empty segment
        final Segment segment = new Segment();
        try {
            //Tranform the string into a json object
            final JSONObject json = new JSONObject(result);
            //Get the route object
            final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
            //Get the leg, only one leg as we don't support waypoints
            final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
            //Get the steps for this leg
            final JSONArray steps = leg.getJSONArray("steps");
            //Number of steps for use in for loop
            final int numSteps = steps.length();
            //Set the name of this route using the start & end addresses
            route.setName(leg.getString("start_address") + " to " + leg.getString("end_address"));
            //Get google's copyright notice (tos requirement)
            route.setCopyright(jsonRoute.getString("copyrights"));
            //Get the total length of the route.
            route.setLength(leg.getJSONObject("distance").getInt("value"));
            //Get any warnings provided (tos requirement)
            if (!jsonRoute.getJSONArray("warnings").isNull(0)) {
                route.setWarning(jsonRoute.getJSONArray("warnings").getString(0));
            }
            /* Loop through the steps, creating a segment for each one and
             * decoding any polylines found as we go to add to the route object's
             * map array. Using an explicit for loop because it is faster!
             */
            for (int i = 0; i < numSteps; i++) {
                //Get the individual step
                final JSONObject step = steps.getJSONObject(i);
                //Get the start position for this step and set it on the segment
                final JSONObject start = step.getJSONObject("start_location");
                final LatLng position = new LatLng(start.getDouble("lat"), start.getDouble("lng"));
                segment.setPoint(position);
                //Set the length of this segment in metres
                final int length = step.getJSONObject("distance").getInt("value");
                distance += length;
                segment.setLength(length);
                segment.setDistance(distance/1000);
                //Strip html from google directions and set as turn instruction
                segment.setInstruction(step.getString("html_instructions").replaceAll("<(.*?)*>", ""));
                //Retrieve & decode this segment's polyline and add it to the route.
                route.addPoints(decodePolyLine(step.getJSONObject("polyline").getString("points")));
                //Push a copy of the segment to the route
                route.addSegment(segment.copy());
            }
        } catch (JSONException e) {
            Log.e(e.getMessage(), "Google JSON Parser - " + feedUrl);
        }
        return route;
    }

    /**
     * Convert an inputstream to a string.
     * @param input inputstream to convert.
     * @return a String of the inputstream.
     */

    private static String convertStreamToString(final InputStream input) {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        final StringBuilder sBuf = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sBuf.append(line);
            }
        } catch (IOException e) {
            Log.e(e.getMessage(), "Google parser, stream2string");
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(e.getMessage(), "Google parser, stream2string");
            }
        }
        return sBuf.toString();
    }

    /**
     * Decode a polyline string into a list of LatLng.
     * @param poly polyline encoded string to decode.
     * @return the list of GeoPoints represented by this polystring.
     */

    private List<LatLng> decodePolyLine(final String poly) {
        int len = poly.length();
        int index = 0;
        List<LatLng> decoded = new LinkedList<LatLng>();
        int lat = 0;
        int lng = 0;

        while (index < len) {
            int b;
            int shift = 0;
            int result = 0;
            do {
                b = poly.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = poly.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            decoded.add(new LatLng((lat / 1E5),(lng / 1E5)));
        }

        return decoded;
    }
}
</code>```

Route (to save json info)

```<code>public class Route {
    private String name;
    private final List<LatLng> points;
    private List<Segment> segments;
    private String copyright;
    private String warning;
    private String country;
    private int length;
    private String polyline;

    public Route() {
        points = new LinkedList<LatLng>();
        segments = new LinkedList<Segment>();
    }

    public void addPoint(final LatLng p) {
        points.add(p);
    }

    public void addPoints(final List<LatLng> points) {
        this.points.addAll(points);
    }

    public List<LatLng> getPoints() {
        return points;
    }

    public void addSegment(final Segment s) {
        segments.add(s);
    }

    public List<Segment> getSegments() {
        return segments;
    }

    /**
     * @param name the name to set
     */
     public void setName(final String name) {
        this.name = name;
    }

    /**
     * @return the name
     */
     public String getName() {
         return name;
     }

     /**
      * @param copyright the copyright to set
      */
     public void setCopyright(String copyright) {
         this.copyright = copyright;
     }

     /**
      * @return the copyright
      */
     public String getCopyright() {
         return copyright;
     }

     /**
      * @param warning the warning to set
      */
     public void setWarning(String warning) {
         this.warning = warning;
     }

     /**
      * @return the warning
      */
     public String getWarning() {
         return warning;
     }

     /**
      * @param country the country to set
      */
     public void setCountry(String country) {
         this.country = country;
     }

     /**
      * @return the country
      */
     public String getCountry() {
         return country;
     }

     /**
      * @param length the length to set
      */
     public void setLength(int length) {
         this.length = length;
     }

     /**
      * @return the length
      */
     public int getLength() {
         return length;
     }

     /**
      * @param polyline the polyline to set
      */
     public void setPolyline(String polyline) {
         this.polyline = polyline;
     }

     /**
      * @return the polyline
      */
     public String getPolyline() {
         return polyline;
     }

}
</code>```

Segment:

```<code>public class Segment {
    /** Points in this segment. **/
    private LatLng start;
    /** Turn instruction to reach next segment. **/
    private String instruction;
    /** Length of segment. **/
    private int length;
    /** Distance covered. **/
    private double distance;

    /**
     * Create an empty segment.
     */

    public Segment() {
    }

    /**
     * Set the turn instruction.
     * @param turn Turn instruction string.
     */

    public void setInstruction(final String turn) {
            this.instruction = turn;
    }

    /**
     * Get the turn instruction to reach next segment.
     * @return a String of the turn instruction.
     */

    public String getInstruction() {
            return instruction;
    }

    /**
     * Add a point to this segment.
     * @param point LatLng to add.
     */

    public void setPoint(LatLng point) {
            start = point;
    }

    /** Get the starting point of this
     * segment.
     * @return a LatLng
     */

    public LatLng startPoint() {
            return start;
    }

    /** Creates a segment which is a copy of this one.
     * @return a Segment that is a copy of this one.
     */

    public Segment copy() {
            final Segment copy = new Segment();
            copy.start = start;
            copy.instruction = instruction;
            copy.length = length;
            copy.distance = distance;
            return copy;
    }

    /**
     * @param length the length to set
     */
    public void setLength(final int length) {
            this.length = length;
    }

    /**
     * @return the length
     */
    public int getLength() {
            return length;
    }

    /**
     * @param distance the distance to set
     */
    public void setDistance(double distance) {
            this.distance = distance;
    }

    /**
     * @return the distance
     */
    public double getDistance() {
            return distance;
    }

}
</code>```

My MainActivity (there are 326 code line because of user localization, you can find it on google developer site, so we can just suppose to have two static point A and B and I want to go from A to B):

```<code>public class MainActivity extends FragmentActivity{
    private GoogleMap map;
    private Marker currentLocation;
    private PolylineOptions pathLine;
    private LatLng imhere = new LatLng(41.8549038,12.4618208);
        private LatLng poi = new LatLng(41.89000,12.49324);

    private LocationManager mLocationManager;
    private Handler mHandler;
    private boolean mUseBoth;
    private Context context;
    // Keys for maintaining UI states after rotation.
    private static final String KEY_BOTH = "use_both";
    // UI handler codes.
    private static final int UPDATE_LATLNG = 2;

    private static final int FIVE_SECONDS = 5000;
    private static final int THREE_METERS = 3;
    private static final int TWO_MINUTES = 1000 * 60 * 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        Marker colosseoMarker  = map.addMarker(new MarkerOptions()
        .position(colosseo)
        .title("Start")
        .snippet("poi")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));

                Marker current pos = map.addMarker(new MarkerOptions()
        .position(imhere)
        .title("i'm here")
        .snippet("here!")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));

        context =this ;
        map.setOnMarkerClickListener(new OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                final String[] options = {"Calcola il Percorso"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Ottieni Informazioni aggiuntive");
                builder.setPositiveButton("Calcola Percorso",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        LatLng start = new LatLng(imhere.latitude,imhere.longitude);
                        LatLng dest = new LatLng(poi.latitude, poi.longitude);
                        Route route = drawPath(start, dest);

                        List<LatLng> list= route.getPoints();

if(pathLine!= null) pathline =null;
pathLine = new PolylineOptions();

                        pathLine.addAll(list);
                        pathLine.color(Color.rgb(0,191,255));

                        map.addPolyline(pathLine);

                    }
                  });

                AlertDialog alert = builder.create();
                alert.show();
                Toast.makeText(MainActivity.this, marker.getSnippet(),Toast.LENGTH_SHORT).show();
                return true;
            }
        });

                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(imhere, 12));
                }
            }
        };
        // Get a reference to the LocationManager object.
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

     private Route drawPath(LatLng start, LatLng dest) {
            Parser parser;
            String jsonURL = "http://maps.google.com/maps/api/directions/json?";
            final StringBuffer sBuf = new StringBuffer(jsonURL);
            sBuf.append("origin=");
            sBuf.append(start.latitude);
            sBuf.append(',');
            sBuf.append(start.longitude);
            sBuf.append("&destination=");
            sBuf.append(dest.latitude);
            sBuf.append(',');
            sBuf.append(dest.longitude);
            sBuf.append("&sensor=true&mode=walking");
            parser = new JsonParser(sBuf.toString());
            Route r =  parser.parse();
            return r;
        }
}
</code>```

every suggestion is well accepted

答:
I am doing like the following. I think this will help you.

```<code> Marker interestedMarker;
    private void plot_direction(){
        if (currentSelectedPin !=null) {
            LatLng origin = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
            new GoogleMapDirection(getActivity(), origin, interestedMarker.getPosition(), new DirectionListener() {
                @Override
                public void onDirectionPointsReceived(ArrayList<RouteModel> routeList, String distance, String duration) {
                    PolylineOptions lineOptions = null;
                    for (RouteModel route : routeList) {
                        lineOptions = new PolylineOptions();
                        lineOptions.addAll(route.getSteps());
                        lineOptions.width(20);
                        lineOptions.color(ContextCompat.getColor(getContext(), R.color.map_route));
                    }

                    //For removing existing line
                    if (routeMap!=null){
                        routeMap.remove();
                    }
                    if(lineOptions != null) {
                        routeMap = mMap.addPolyline(lineOptions);
                    }
                }
            });
        }
    }
</code>```

GoogleMapDirection class is as follows

```<code>public class GoogleMapDirection {
    private DirectionListener listener;
    public GoogleMapDirection(final Activity activity, LatLng source, LatLng destination, DirectionListener listener){
        this.listener=listener;
        String url = null;
        try {
            url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ URLEncoder.encode(Double.toString(source.latitude) + "," + Double.toString(source.longitude), "UTF-8") + "&destination=" + URLEncoder.encode(Double.toString(destination.latitude) + "," + Double.toString(destination.longitude), "UTF-8") + "&mode=driving&sensor=false&key=" + Config.GOOGLE_API_BROWSER_KEY;
            Print.d(url);
        } catch (UnsupportedEncodingException e) {
            Print.exception(e);
        }

        JSONObject parameters = new JSONObject();
        VolleyJsonBodyRequest.execute(activity, url, parameters, new VolleyResponseListener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getString("status").equals("OK")) {
                        String distance = "NA";
                        String duration = "NA";
                        if (response.has("routes")){
                            JSONArray routesJArray = response.getJSONArray("routes");
                            if (routesJArray.length()>0){
                                if (routesJArray.getJSONObject(0).has("legs")){
                                    JSONArray legsJArray = routesJArray.getJSONObject(0).getJSONArray("legs");
                                    if (legsJArray.length()>0){
                                        JSONObject firstLegsJObj = legsJArray.getJSONObject(0);
                                        if (firstLegsJObj.has("distance")){
                                            distance = firstLegsJObj.getJSONObject("distance").getString("text");
                                        }
                                        if (firstLegsJObj.has("duration")){
                                            duration = firstLegsJObj.getJSONObject("duration").getString("text");
                                        }

                                    }
                                }
                            }
                        }
                        GoogleResponseParserTask task = new GoogleResponseParserTask(distance,duration);
                        task.execute(response);
                    }
                } catch (JSONException e) {
                    Print.exception(e);
                    DialogWindow.showOK(activity, Config.MESSAGE_INVALID_RESPONSE_FORMAT, new DialogListenerOK() {
                        @Override
                        public void onOK() {

                        }
                    });
                }
            }
            @Override
            public void onErrorResponse(VolleyResponseError error) {
                Print.e(error.getDetails());
                DialogWindow.showOK(activity, error.getMessage(), new DialogListenerOK() {
                    @Override
                    public void onOK() {

                    }
                });
            }
        });
    }

    /**
     * A class to parse the Google Places in JSON format
     */
    private class GoogleResponseParserTask extends AsyncTask<JSONObject, Integer, ArrayList<RouteModel>> {

        String distance;
        String duration;
        private GoogleResponseParserTask(String distance, String duration){
            this.distance=distance;
            this.duration=duration;

        }
        @Override
        protected ArrayList<RouteModel> doInBackground(JSONObject... jsonResponse) {
            ArrayList<RouteModel> routes = null;
            try {
                routes = parse(jsonResponse[0]);
            } catch (Exception e) {
                Print.exception(e);
            }
            return routes;
        }
        @Override
        protected void onPostExecute(ArrayList<RouteModel> result) {
            listener.onDirectionPointsReceived(result,distance,duration);
        }
    }

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public ArrayList<RouteModel> parse(JSONObject jObject){

        ArrayList<RouteModel> routeList = new ArrayList<>() ;
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                ArrayList<LatLng> pointList = new ArrayList<>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ((JSONObject)jLegs.get(j)).getJSONArray("steps");
                    JSONObject jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    JSONObject jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");

                    String distance = jDistance.getString("text");
                    String duration = jDuration.getString("text");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        ArrayList<LatLng> stepList = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<stepList.size();l++){
                            LatLng point = new LatLng((stepList.get(l)).latitude, (stepList.get(l)).longitude);
                            pointList.add(point);
                        }
                    }
                    RouteModel routeModel = new RouteModel();
                    routeModel.setSteps(pointList);
                    routeModel.setDistance(distance);
                    routeModel.setDuration(duration);
                    routeList.add(routeModel);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e){
        }

        return routeList;
    }

    /**
     * Method to decode polyline points
     * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
     * */
    private ArrayList<LatLng> decodePoly(String encoded) {

        ArrayList<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
</code>```

Body:
I'm developing an app where i need to know the path between the current user posistion and a point of interest.

I'm using android 2.3.3, google maps android v2 and direction api.
My problem is that all the code i have found is for the old version of the maps, and I also tried to adapt the code but i failed. I try to change GeoPoint (not supported in this new versione) in LatLng.
the problem is that i can't display the path, to do it i create a new polyline and i add it to the map.

i post my code:

Parser:

public interface Parser {
    public Route parse();
}

XMLParser

public class XMLParser {
    // names of the XML tags
    protected static final String MARKERS = "markers";
    protected static final String MARKER = "marker";

    protected URL feedUrl;

    protected XMLParser(final String feedUrl) {
            try {
                    this.feedUrl = new URL(feedUrl);
            } catch (MalformedURLException e) {
                    Log.e(e.getMessage(), "XML parser - " + feedUrl);
            }
    }

    protected InputStream getInputStream() {
            try {
                    return feedUrl.openConnection().getInputStream();
            } catch (IOException e) {
                    Log.e(e.getMessage(), "XML parser - " + feedUrl);
                    return null;
            }
    }
}

JsonParser (parse the google direction json)

public class JsonParser extends XMLParser implements Parser {
    /** Distance covered. **/
    private int distance;

    public JsonParser(String feedUrl) {
        super(feedUrl);
    }

    /**
     * Parses a url pointing to a Google JSON object to a Route object.
     * @return a Route object based on the JSON object.
     */

    public Route parse() {
        // turn the stream into a string
        final String result = convertStreamToString(this.getInputStream());
        //Create an empty route
        final Route route = new Route();
        //Create an empty segment
        final Segment segment = new Segment();
        try {
            //Tranform the string into a json object
            final JSONObject json = new JSONObject(result);
            //Get the route object
            final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
            //Get the leg, only one leg as we don't support waypoints
            final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
            //Get the steps for this leg
            final JSONArray steps = leg.getJSONArray("steps");
            //Number of steps for use in for loop
            final int numSteps = steps.length();
            //Set the name of this route using the start & end addresses
            route.setName(leg.getString("start_address") + " to " + leg.getString("end_address"));
            //Get google's copyright notice (tos requirement)
            route.setCopyright(jsonRoute.getString("copyrights"));
            //Get the total length of the route.
            route.setLength(leg.getJSONObject("distance").getInt("value"));
            //Get any warnings provided (tos requirement)
            if (!jsonRoute.getJSONArray("warnings").isNull(0)) {
                route.setWarning(jsonRoute.getJSONArray("warnings").getString(0));
            }
            /* Loop through the steps, creating a segment for each one and
             * decoding any polylines found as we go to add to the route object's
             * map array. Using an explicit for loop because it is faster!
             */
            for (int i = 0; i < numSteps; i++) {
                //Get the individual step
                final JSONObject step = steps.getJSONObject(i);
                //Get the start position for this step and set it on the segment
                final JSONObject start = step.getJSONObject("start_location");
                final LatLng position = new LatLng(start.getDouble("lat"), start.getDouble("lng"));
                segment.setPoint(position);
                //Set the length of this segment in metres
                final int length = step.getJSONObject("distance").getInt("value");
                distance += length;
                segment.setLength(length);
                segment.setDistance(distance/1000);
                //Strip html from google directions and set as turn instruction
                segment.setInstruction(step.getString("html_instructions").replaceAll("<(.*?)*>", ""));
                //Retrieve & decode this segment's polyline and add it to the route.
                route.addPoints(decodePolyLine(step.getJSONObject("polyline").getString("points")));
                //Push a copy of the segment to the route
                route.addSegment(segment.copy());
            }
        } catch (JSONException e) {
            Log.e(e.getMessage(), "Google JSON Parser - " + feedUrl);
        }
        return route;
    }

    /**
     * Convert an inputstream to a string.
     * @param input inputstream to convert.
     * @return a String of the inputstream.
     */

    private static String convertStreamToString(final InputStream input) {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        final StringBuilder sBuf = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sBuf.append(line);
            }
        } catch (IOException e) {
            Log.e(e.getMessage(), "Google parser, stream2string");
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(e.getMessage(), "Google parser, stream2string");
            }
        }
        return sBuf.toString();
    }

    /**
     * Decode a polyline string into a list of LatLng.
     * @param poly polyline encoded string to decode.
     * @return the list of GeoPoints represented by this polystring.
     */

    private List<LatLng> decodePolyLine(final String poly) {
        int len = poly.length();
        int index = 0;
        List<LatLng> decoded = new LinkedList<LatLng>();
        int lat = 0;
        int lng = 0;

        while (index < len) {
            int b;
            int shift = 0;
            int result = 0;
            do {
                b = poly.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = poly.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            decoded.add(new LatLng((lat / 1E5),(lng / 1E5)));
        }

        return decoded;
    }
}

Route (to save json info)

public class Route {
    private String name;
    private final List<LatLng> points;
    private List<Segment> segments;
    private String copyright;
    private String warning;
    private String country;
    private int length;
    private String polyline;

    public Route() {
        points = new LinkedList<LatLng>();
        segments = new LinkedList<Segment>();
    }

    public void addPoint(final LatLng p) {
        points.add(p);
    }

    public void addPoints(final List<LatLng> points) {
        this.points.addAll(points);
    }

    public List<LatLng> getPoints() {
        return points;
    }

    public void addSegment(final Segment s) {
        segments.add(s);
    }

    public List<Segment> getSegments() {
        return segments;
    }

    /**
     * @param name the name to set
     */
     public void setName(final String name) {
        this.name = name;
    }

    /**
     * @return the name
     */
     public String getName() {
         return name;
     }

     /**
      * @param copyright the copyright to set
      */
     public void setCopyright(String copyright) {
         this.copyright = copyright;
     }

     /**
      * @return the copyright
      */
     public String getCopyright() {
         return copyright;
     }

     /**
      * @param warning the warning to set
      */
     public void setWarning(String warning) {
         this.warning = warning;
     }

     /**
      * @return the warning
      */
     public String getWarning() {
         return warning;
     }

     /**
      * @param country the country to set
      */
     public void setCountry(String country) {
         this.country = country;
     }

     /**
      * @return the country
      */
     public String getCountry() {
         return country;
     }

     /**
      * @param length the length to set
      */
     public void setLength(int length) {
         this.length = length;
     }

     /**
      * @return the length
      */
     public int getLength() {
         return length;
     }

     /**
      * @param polyline the polyline to set
      */
     public void setPolyline(String polyline) {
         this.polyline = polyline;
     }

     /**
      * @return the polyline
      */
     public String getPolyline() {
         return polyline;
     }

}

Segment:

public class Segment {
    /** Points in this segment. **/
    private LatLng start;
    /** Turn instruction to reach next segment. **/
    private String instruction;
    /** Length of segment. **/
    private int length;
    /** Distance covered. **/
    private double distance;

    /**
     * Create an empty segment.
     */

    public Segment() {
    }

    /**
     * Set the turn instruction.
     * @param turn Turn instruction string.
     */

    public void setInstruction(final String turn) {
            this.instruction = turn;
    }

    /**
     * Get the turn instruction to reach next segment.
     * @return a String of the turn instruction.
     */

    public String getInstruction() {
            return instruction;
    }

    /**
     * Add a point to this segment.
     * @param point LatLng to add.
     */

    public void setPoint(LatLng point) {
            start = point;
    }

    /** Get the starting point of this
     * segment.
     * @return a LatLng
     */

    public LatLng startPoint() {
            return start;
    }

    /** Creates a segment which is a copy of this one.
     * @return a Segment that is a copy of this one.
     */

    public Segment copy() {
            final Segment copy = new Segment();
            copy.start = start;
            copy.instruction = instruction;
            copy.length = length;
            copy.distance = distance;
            return copy;
    }

    /**
     * @param length the length to set
     */
    public void setLength(final int length) {
            this.length = length;
    }

    /**
     * @return the length
     */
    public int getLength() {
            return length;
    }

    /**
     * @param distance the distance to set
     */
    public void setDistance(double distance) {
            this.distance = distance;
    }

    /**
     * @return the distance
     */
    public double getDistance() {
            return distance;
    }

}

My MainActivity (there are 326 code line because of user localization, you can find it on google developer site, so we can just suppose to have two static point A and B and I want to go from A to B):

public class MainActivity extends FragmentActivity{
    private GoogleMap map;
    private Marker currentLocation;
    private PolylineOptions pathLine;
    private LatLng imhere = new LatLng(41.8549038,12.4618208);
        private LatLng poi = new LatLng(41.89000,12.49324);

    private LocationManager mLocationManager;
    private Handler mHandler;
    private boolean mUseBoth;
    private Context context;
    // Keys for maintaining UI states after rotation.
    private static final String KEY_BOTH = "use_both";
    // UI handler codes.
    private static final int UPDATE_LATLNG = 2;

    private static final int FIVE_SECONDS = 5000;
    private static final int THREE_METERS = 3;
    private static final int TWO_MINUTES = 1000 * 60 * 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        Marker colosseoMarker  = map.addMarker(new MarkerOptions()
        .position(colosseo)
        .title("Start")
        .snippet("poi")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));

                Marker current pos = map.addMarker(new MarkerOptions()
        .position(imhere)
        .title("i'm here")
        .snippet("here!")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));

        context =this ;
        map.setOnMarkerClickListener(new OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                final String[] options = {"Calcola il Percorso"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Ottieni Informazioni aggiuntive");
                builder.setPositiveButton("Calcola Percorso",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        LatLng start = new LatLng(imhere.latitude,imhere.longitude);
                        LatLng dest = new LatLng(poi.latitude, poi.longitude);
                        Route route = drawPath(start, dest);

                        List<LatLng> list= route.getPoints();

if(pathLine!= null) pathline =null;
pathLine = new PolylineOptions();

                        pathLine.addAll(list);
                        pathLine.color(Color.rgb(0,191,255));

                        map.addPolyline(pathLine);

                    }
                  });

                AlertDialog alert = builder.create();
                alert.show();
                Toast.makeText(MainActivity.this, marker.getSnippet(),Toast.LENGTH_SHORT).show();
                return true;
            }
        });

                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(imhere, 12));
                }
            }
        };
        // Get a reference to the LocationManager object.
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

     private Route drawPath(LatLng start, LatLng dest) {
            Parser parser;
            String jsonURL = "http://maps.google.com/maps/api/directions/json?";
            final StringBuffer sBuf = new StringBuffer(jsonURL);
            sBuf.append("origin=");
            sBuf.append(start.latitude);
            sBuf.append(',');
            sBuf.append(start.longitude);
            sBuf.append("&destination=");
            sBuf.append(dest.latitude);
            sBuf.append(',');
            sBuf.append(dest.longitude);
            sBuf.append("&sensor=true&mode=walking");
            parser = new JsonParser(sBuf.toString());
            Route r =  parser.parse();
            return r;
        }
}

every suggestion is well accepted

Body:
I am doing like the following. I think this will help you.

 Marker interestedMarker;
    private void plot_direction(){
        if (currentSelectedPin !=null) {
            LatLng origin = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
            new GoogleMapDirection(getActivity(), origin, interestedMarker.getPosition(), new DirectionListener() {
                @Override
                public void onDirectionPointsReceived(ArrayList<RouteModel> routeList, String distance, String duration) {
                    PolylineOptions lineOptions = null;
                    for (RouteModel route : routeList) {
                        lineOptions = new PolylineOptions();
                        lineOptions.addAll(route.getSteps());
                        lineOptions.width(20);
                        lineOptions.color(ContextCompat.getColor(getContext(), R.color.map_route));
                    }

                    //For removing existing line
                    if (routeMap!=null){
                        routeMap.remove();
                    }
                    if(lineOptions != null) {
                        routeMap = mMap.addPolyline(lineOptions);
                    }
                }
            });
        }
    }

GoogleMapDirection class is as follows

public class GoogleMapDirection {
    private DirectionListener listener;
    public GoogleMapDirection(final Activity activity, LatLng source, LatLng destination, DirectionListener listener){
        this.listener=listener;
        String url = null;
        try {
            url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ URLEncoder.encode(Double.toString(source.latitude) + "," + Double.toString(source.longitude), "UTF-8") + "&destination=" + URLEncoder.encode(Double.toString(destination.latitude) + "," + Double.toString(destination.longitude), "UTF-8") + "&mode=driving&sensor=false&key=" + Config.GOOGLE_API_BROWSER_KEY;
            Print.d(url);
        } catch (UnsupportedEncodingException e) {
            Print.exception(e);
        }

        JSONObject parameters = new JSONObject();
        VolleyJsonBodyRequest.execute(activity, url, parameters, new VolleyResponseListener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getString("status").equals("OK")) {
                        String distance = "NA";
                        String duration = "NA";
                        if (response.has("routes")){
                            JSONArray routesJArray = response.getJSONArray("routes");
                            if (routesJArray.length()>0){
                                if (routesJArray.getJSONObject(0).has("legs")){
                                    JSONArray legsJArray = routesJArray.getJSONObject(0).getJSONArray("legs");
                                    if (legsJArray.length()>0){
                                        JSONObject firstLegsJObj = legsJArray.getJSONObject(0);
                                        if (firstLegsJObj.has("distance")){
                                            distance = firstLegsJObj.getJSONObject("distance").getString("text");
                                        }
                                        if (firstLegsJObj.has("duration")){
                                            duration = firstLegsJObj.getJSONObject("duration").getString("text");
                                        }

                                    }
                                }
                            }
                        }
                        GoogleResponseParserTask task = new GoogleResponseParserTask(distance,duration);
                        task.execute(response);
                    }
                } catch (JSONException e) {
                    Print.exception(e);
                    DialogWindow.showOK(activity, Config.MESSAGE_INVALID_RESPONSE_FORMAT, new DialogListenerOK() {
                        @Override
                        public void onOK() {

                        }
                    });
                }
            }
            @Override
            public void onErrorResponse(VolleyResponseError error) {
                Print.e(error.getDetails());
                DialogWindow.showOK(activity, error.getMessage(), new DialogListenerOK() {
                    @Override
                    public void onOK() {

                    }
                });
            }
        });
    }

    /**
     * A class to parse the Google Places in JSON format
     */
    private class GoogleResponseParserTask extends AsyncTask<JSONObject, Integer, ArrayList<RouteModel>> {

        String distance;
        String duration;
        private GoogleResponseParserTask(String distance, String duration){
            this.distance=distance;
            this.duration=duration;

        }
        @Override
        protected ArrayList<RouteModel> doInBackground(JSONObject... jsonResponse) {
            ArrayList<RouteModel> routes = null;
            try {
                routes = parse(jsonResponse[0]);
            } catch (Exception e) {
                Print.exception(e);
            }
            return routes;
        }
        @Override
        protected void onPostExecute(ArrayList<RouteModel> result) {
            listener.onDirectionPointsReceived(result,distance,duration);
        }
    }

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public ArrayList<RouteModel> parse(JSONObject jObject){

        ArrayList<RouteModel> routeList = new ArrayList<>() ;
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                ArrayList<LatLng> pointList = new ArrayList<>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ((JSONObject)jLegs.get(j)).getJSONArray("steps");
                    JSONObject jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    JSONObject jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");

                    String distance = jDistance.getString("text");
                    String duration = jDuration.getString("text");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        ArrayList<LatLng> stepList = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<stepList.size();l++){
                            LatLng point = new LatLng((stepList.get(l)).latitude, (stepList.get(l)).longitude);
                            pointList.add(point);
                        }
                    }
                    RouteModel routeModel = new RouteModel();
                    routeModel.setSteps(pointList);
                    routeModel.setDistance(distance);
                    routeModel.setDuration(duration);
                    routeList.add(routeModel);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e){
        }

        return routeList;
    }

    /**
     * Method to decode polyline points
     * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
     * */
    private ArrayList<LatLng> decodePoly(String encoded) {

        ArrayList<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }


问:
How to show the attributes of an object when clicking a button in Windows forms?
I want to show the attributes of an object when I click on a button in Windows Forms using c# and I don't know how to do it. Part of my code looks like this until now. I'm a beginner in c#.

```<code>class Pizza: ICloneable
    {
        private string nume;
        private int nrIngrediente;
        private string[] ingrediente;

        public Pizza()
        {
            nume = "Margherita";
            nrIngrediente = 2;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
            {
                ingrediente[0] = "Sos rosii";
                ingrediente[1] = "Mozzarella";
            }
        }

        public Pizza(string den, int nri, string[] ing)
        {
            nume = den;
            nrIngrediente = nri;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = ing[i];
        }

        public Pizza(Pizza p)
        {
            nume = p.nume;
            nrIngrediente = p.nrIngrediente;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = p.ingrediente[i];
        }

        public string PizzaName
        {
            get { return nume; }
            set { nume = value; }
        }

 public int PizzaNrIng
        {
            get { return nrIngrediente; }
            set { nrIngrediente = value; }

//also, i don't know how to write the getter and setter for this one
      public string PizzaIngredients
        //{
        //    get
        //    {
        //        for(int i=0;i<nrIngrediente;i++)
        //            return ingrediente[i];
        //    }
        //    set { ingrediente = value; }
        //}
</code>```

And now, the form code is the following(note that i designed it already):

```<code> public partial class ListaPizza : Form
    {

        public ListaPizza()
        {
            InitializeComponent();
        }

        private void Margherita_Click(object sender, EventArgs e)
        {

            string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
            Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

            //Show(Margherita);
//here i want the object created above to be shown in a messagebox when i click the button in the form but i don't know how

        }
    }
</code>```

Thank you!

答:
MessageBox.Show();

has to be a string value so any parts of your object that is not a string will need the .ToString() method

Or if you want to customize the view you could pass the object to a new form and create a whole nice layout for it with the designer.

Body:
I want to show the attributes of an object when I click on a button in Windows Forms using c# and I don't know how to do it. Part of my code looks like this until now. I'm a beginner in c#.

class Pizza: ICloneable
    {
        private string nume;
        private int nrIngrediente;
        private string[] ingrediente;

        public Pizza()
        {
            nume = "Margherita";
            nrIngrediente = 2;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
            {
                ingrediente[0] = "Sos rosii";
                ingrediente[1] = "Mozzarella";
            }
        }

        public Pizza(string den, int nri, string[] ing)
        {
            nume = den;
            nrIngrediente = nri;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = ing[i];
        }

        public Pizza(Pizza p)
        {
            nume = p.nume;
            nrIngrediente = p.nrIngrediente;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = p.ingrediente[i];
        }

        public string PizzaName
        {
            get { return nume; }
            set { nume = value; }
        }

 public int PizzaNrIng
        {
            get { return nrIngrediente; }
            set { nrIngrediente = value; }

//also, i don't know how to write the getter and setter for this one
      public string PizzaIngredients
        //{
        //    get
        //    {
        //        for(int i=0;i<nrIngrediente;i++)
        //            return ingrediente[i];
        //    }
        //    set { ingrediente = value; }
        //}

And now, the form code is the following(note that i designed it already):

 public partial class ListaPizza : Form
    {

        public ListaPizza()
        {
            InitializeComponent();
        }

        private void Margherita_Click(object sender, EventArgs e)
        {

            string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
            Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

            //Show(Margherita);
//here i want the object created above to be shown in a messagebox when i click the button in the form but i don't know how

        }
    }

Thank you!


问:
Subscribe to another subscription in Angular
I have a private method which i use for authentication. Then i have another method (public) that i call in my components called login to do the actual login. I want to be able to subscribe to the login method which in reality subscribe's to the private authentication method so that i can show loading and other messages while login in being performed differently for each view. Is it possible?

Authentication method:

```<code>private userAuthenticate( email: string, password: string ) {
    return this.httpPost(`${this.baseApiUrl}/auth?format=json&provider=login`, {userName: email, password: password}).subscribe(
        res     => this.saveJwt(res.bearerToken),
        err     => this.logError(err),
        ()      => console.log("Authentication done.")
    );
}
</code>```

Login method:

```<code>login( email: string, password: string ) {
    this.logout();
    return this.userAuthenticate(email, password);
}
</code>```

I want to subscribe to the login method so that i can control my loaders and error messages etc.
Please help.

答:
You can't subscribe to Subscription (returned by subscribe()). You can only subscribe to Observable.

To get an Observable use map() instead of subscribe(). Then the caller of login() can do the subscription.

```<code>private userAuthenticate( email: string, password: string ) {
    return this.httpPost(
             `${this.baseApiUrl}/auth?format=json&provider=login`,
             {userName: email, password: password}
           )
           .map(res => this.saveJwt(res.bearerToken));
}
</code>```

For the other callabacks, if your really need them, you can use the catch and finally operators.

Body:
I have a private method which i use for authentication. Then i have another method (public) that i call in my components called login to do the actual login. I want to be able to subscribe to the login method which in reality subscribe's to the private authentication method so that i can show loading and other messages while login in being performed differently for each view. Is it possible?

Authentication method:

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(`${this.baseApiUrl}/auth?format=json&provider=login`, {userName: email, password: password}).subscribe(
        res     => this.saveJwt(res.bearerToken),
        err     => this.logError(err),
        ()      => console.log("Authentication done.")
    );
}

Login method:

login( email: string, password: string ) {
    this.logout();
    return this.userAuthenticate(email, password);
}

I want to subscribe to the login method so that i can control my loaders and error messages etc.
Please help.

Body:
You can't subscribe to Subscription (returned by subscribe()). You can only subscribe to Observable.

To get an Observable use map() instead of subscribe(). Then the caller of login() can do the subscription.

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(
             `${this.baseApiUrl}/auth?format=json&provider=login`,
             {userName: email, password: password}
           )
           .map(res => this.saveJwt(res.bearerToken));
}

For the other callabacks, if your really need them, you can use the catch and finally operators.

ContentLicense: CC BY-SA 4.0


问:
Disable button until checkbox ticked
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

```<code><td>
    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
    <td>
    <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
    </td>
</td>
</tr>
<td class="label1"></td>
<td align="right">
    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</i></button>
</td>
</code>```

答:
Please check the answers:
In simple HTML just Add "disabled" Attribute to button.

With jQuery :

```<code>    $('#terms').attr('disabled',true);
</code>```

With Css

Title: Disable button until checkbox ticked

Body:
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />

 I agree to the Terms & Conditions

    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</button>

Body:
Please check the answers:
In simple HTML just Add "disabled" Attribute to button.

With jQuery :

    $('#terms').attr('disabled',true);

With Css


问:
How to store csv file into webjob
I have created a azure webjob with queue trigger with search parameters.
I want to process searching using these parameters and save records into a csv file.

I want a way to store csv file on azure, so that i can send download link for that to user?

答: You can store the CSV using Azure Blob Storage. By ensuring the container has the correct permissions, you can then obtain the link directly to the blob and send to the user. In addition you can use SASUrls to limit the duration of URL validity.</p>

Title: How to store csv file into webjob


问:
Bootstrap Carousel not working in Chrome
I've implemented carousel as a slider in my web page. It is working perfectly in firefox and mobile browsers (even chrome). But it is not showing up in chrome.
I can't figure what's wrong. My syntax are:

HTML:

```<code><div class="carousel fade-carousel slide" data-ride="carousel" data-interval="4000" id="bs-carousel">
  <!-- Overlay -->
  <div class="overlay"></div>

  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#bs-carousel" data-slide-to="0" class="active"></li>
    <li data-target="#bs-carousel" data-slide-to="1"></li>
    <li data-target="#bs-carousel" data-slide-to="2"></li>
  </ol>

  <!-- Wrapper for slides -->
  <div class="carousel-inner">
    <div class="item slides active">
      <div class="slide-1"></div>
      <div class="hero">
        <hgroup>
            <h1>Nepal's First</h1>
            <h3>Nepal's first portal to buy authentic and verified refurbished Auto-mobiles.</h3>
        </hgroup>

      </div>
    </div>
    <div class="item slides">
      <div class="slide-2"></div>
      <div class="hero">
        <hgroup>
            <h1>Trusted Sellers</h1>
            <h3>Buy from our authentic and verified recondition houses across the nation.</h3>
        </hgroup>

      </div>
    </div>
    <div class="item slides">
      <div class="slide-3"></div>
      <div class="hero">
        <hgroup>
            <h1>Tested</h1>
            <h3>All listed vehicles tested and in well condition.</h3>
        </hgroup>

      </div>
    </div>
  </div>
</div>
</code>```

CSS

```<code>/*
Fade content bs-carousel with hero headers
Code snippet by maridlcrmn (Follow me on Twitter @maridlcrmn) for Bootsnipp.com
Image credits: unsplash.com
*/

/********************************/
/*       Fade Bs-carousel       */
/********************************/
.fade-carousel {
    position: relative;
    height: 55vh;
}
.fade-carousel .carousel-inner .item {
    height: 55vh;
}
.fade-carousel .carousel-indicators > li {
    margin: 0 2px;
    background-color: #f39c12;
    border-color: #f39c12;
    opacity: .7;
}
.fade-carousel .carousel-indicators > li.active {
  width: 10px;
  height: 10px;
  opacity: 1;
}

/********************************/
/*          Hero Headers        */
/********************************/
.hero {
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 3;
    color: #fff;
    text-align: center;
    text-transform: uppercase;
    text-shadow: 1px 1px 0 rgba(0,0,0,.75);
      -webkit-transform: translate3d(-50%,-50%,0);
         -moz-transform: translate3d(-50%,-50%,0);
          -ms-transform: translate3d(-50%,-50%,0);
           -o-transform: translate3d(-50%,-50%,0);
              transform: translate3d(-50%,-50%,0);
}
.hero h1 {
    font-size: 6em;
    font-weight: bold;
color: #d3d3d3d3;
    margin: 0;
    padding: 0;
}
.hero h3{
color:#cccccccc;
}

.fade-carousel .carousel-inner .item .hero {
    opacity: 0;
    -webkit-transition: 2s all ease-in-out .1s;
       -moz-transition: 2s all ease-in-out .1s;
        -ms-transition: 2s all ease-in-out .1s;
         -o-transition: 2s all ease-in-out .1s;
            transition: 2s all ease-in-out .1s;
}
.fade-carousel .carousel-inner .item.active .hero {
    opacity: 1;
    -webkit-transition: 2s all ease-in-out .1s;
       -moz-transition: 2s all ease-in-out .1s;
        -ms-transition: 2s all ease-in-out .1s;
         -o-transition: 2s all ease-in-out .1s;
            transition: 2s all ease-in-out .1s;
}

/********************************/
/*            Overlay           */
/********************************/
.overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
    background-color: #080d15;
    opacity: .2;
}

/********************************/
/*          Custom Buttons      */
/********************************/
.btn.btn-lg {padding: 10px 40px;}
.btn.btn-hero,
.btn.btn-hero:hover,
.btn.btn-hero:focus {
    color: #f5f5f5;
    background-color: #1abc9c;
    border-color: #1abc9c;
    outline: none;
    margin: 20px auto;
}

/********************************/
/*       Slides backgrounds     */
/********************************/
.fade-carousel .slides .slide-1,
.fade-carousel .slides .slide-2,
.fade-carousel .slides .slide-3 {
  height: 55vh;
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
}
.fade-carousel .slides .slide-1 {
 background-image: url(../img/homepage-slider/nepalride-banner-1.jpg);;
}
.fade-carousel .slides .slide-2 {
  background-image: url(../img/homepage-slider/nepalride-banner-2.jpg);;
}
.fade-carousel .slides .slide-3 {
 background-image: url(../img/homepage-slider/nepalride-banner-3.jpg);;
}

/********************************/
/*          Media Queries       */
/********************************/
@media screen and (min-width: 980px){
    .hero { width: 980px; }
}
@media screen and (max-width: 640px){
    .hero h1 { font-size: 4em; }
}
</code>```

Can anyone tell me what to do? I have the following error in the console:

```<code>Uncaught TypeError: Cannot read property 'getContext' of null
    at frontend.js:30
</code>```

You can see details on nepalride.com

答:
In dom there is no element with the id cline. You can avoid the error with this if statement

```<code>if ($('#cline').length > 0) {
   var cline = document.getElementById("cline").getContext("2d");
   new Chart(cline).Line(lineChartData, {
      responsive: true
   });
}
</code>```

Good luck.
C

Body:
I've implemented carousel as a slider in my web page. It is working perfectly in firefox and mobile browsers (even chrome). But it is not showing up in chrome.
I can't figure what's wrong. My syntax are:

HTML:

        <hgroup>

Nepal's First

Nepal's first portal to buy authentic and verified refurbished Auto-mobiles.

        </hgroup>

        <hgroup>

Trusted Sellers

Buy from our authentic and verified recondition houses across the nation.

        </hgroup>

        <hgroup>

Tested

All listed vehicles tested and in well condition.

        </hgroup>

CSS

/*
Fade content bs-carousel with hero headers
Code snippet by maridlcrmn (Follow me on Twitter @maridlcrmn) for Bootsnipp.com
Image credits: unsplash.com
*/

/********************************/
/*       Fade Bs-carousel       */
/********************************/
.fade-carousel {
    position: relative;
    height: 55vh;
}
.fade-carousel .carousel-inner .item {
    height: 55vh;
}
.fade-carousel .carousel-indicators > li {
    margin: 0 2px;
    background-color: #f39c12;
    border-color: #f39c12;
    opacity: .7;
}
.fade-carousel .carousel-indicators > li.active {
  width: 10px;
  height: 10px;
  opacity: 1;
}

/********************************/
/*          Hero Headers        */
/********************************/
.hero {
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 3;
    color: #fff;
    text-align: center;
    text-transform: uppercase;
    text-shadow: 1px 1px 0 rgba(0,0,0,.75);
      -webkit-transform: translate3d(-50%,-50%,0);
         -moz-transform: translate3d(-50%,-50%,0);
          -ms-transform: translate3d(-50%,-50%,0);
           -o-transform: translate3d(-50%,-50%,0);
              transform: translate3d(-50%,-50%,0);
}
.hero h1 {
    font-size: 6em;
    font-weight: bold;
color: #d3d3d3d3;
    margin: 0;
    padding: 0;
}
.hero h3{
color:#cccccccc;
}

.fade-carousel .carousel-inner .item .hero {
    opacity: 0;
    -webkit-transition: 2s all ease-in-out .1s;
       -moz-transition: 2s all ease-in-out .1s;
        -ms-transition: 2s all ease-in-out .1s;
         -o-transition: 2s all ease-in-out .1s;
            transition: 2s all ease-in-out .1s;
}
.fade-carousel .carousel-inner .item.active .hero {
    opacity: 1;
    -webkit-transition: 2s all ease-in-out .1s;
       -moz-transition: 2s all ease-in-out .1s;
        -ms-transition: 2s all ease-in-out .1s;
         -o-transition: 2s all ease-in-out .1s;
            transition: 2s all ease-in-out .1s;
}

/********************************/
/*            Overlay           */
/********************************/
.overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
    background-color: #080d15;
    opacity: .2;
}

/********************************/
/*          Custom Buttons      */
/********************************/
.btn.btn-lg {padding: 10px 40px;}
.btn.btn-hero,
.btn.btn-hero:hover,
.btn.btn-hero:focus {
    color: #f5f5f5;
    background-color: #1abc9c;
    border-color: #1abc9c;
    outline: none;
    margin: 20px auto;
}

/********************************/
/*       Slides backgrounds     */
/********************************/
.fade-carousel .slides .slide-1,
.fade-carousel .slides .slide-2,
.fade-carousel .slides .slide-3 {
  height: 55vh;
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
}
.fade-carousel .slides .slide-1 {
 background-image: url(../img/homepage-slider/nepalride-banner-1.jpg);;
}
.fade-carousel .slides .slide-2 {
  background-image: url(../img/homepage-slider/nepalride-banner-2.jpg);;
}
.fade-carousel .slides .slide-3 {
 background-image: url(../img/homepage-slider/nepalride-banner-3.jpg);;
}

/********************************/
/*          Media Queries       */
/********************************/
@media screen and (min-width: 980px){
    .hero { width: 980px; }
}
@media screen and (max-width: 640px){
    .hero h1 { font-size: 4em; }
}

Can anyone tell me what to do? I have the following error in the console:

Uncaught TypeError: Cannot read property 'getContext' of null
    at frontend.js:30

You can see details on nepalride.com

Body:
In dom there is no element with the id cline. You can avoid the error with this if statement

if ($('#cline').length > 0) {
   var cline = document.getElementById("cline").getContext("2d");
   new Chart(cline).Line(lineChartData, {
      responsive: true
   });
}

Good luck.
C


问:
Search with SharePoint CSOM (portable) throws an exception
I am trying to use SharePoint client framework to execute a search, using the portable dll's from a Windows app.

Using Fiddler I can see that my search is executed, and returns a JSON collection of metadata and search results. This is identical to the result from the non-portable CSOM.

When CSOM tries to map the result to it's data objects I get the following exception:

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'Microsoft.SharePoint.Client.Search.Query.ResultTableCollection'.

This exception occurs inside CSOM (portable). Non-portable CSOM runs without exception, and returns the expected result.

The code I am running to get this exception is:

```<code>var query = new KeywordQuery(ctx);
query.QueryText = "something";
var executor = new SearchExecutor(ctx);
var results = executor.ExecuteQuery(query);
await ctx.ExecuteQueryAsync();
</code>```

In the above, ctx is a ClientContext that has already been authenticated. Other requests, such as getting a specific list, works as expected.

I am referencing the following dll's from c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI:

Microsoft.SharePoint.Client.Portable.dll

Microsoft.SharePoint.Client.Runtime.Portable.dll

Microsoft.SharePoint.Client.Runtime.WindowsStore.dll

Microsoft.SharePoint.Client.Search.Portable.dll

My question is.

How do I solve this, so that I can use CSOM to run search queries from a Windows Store app?

UPDATE:
I added the following after authenticating the ClientContext:

```<code>ctx.ExecutingWebRequest += (s, e) =>
    e.WebRequest.Headers["Accept-Encoding"] = "gzip, deflate";
</code>```

This solved the immediate problem, but introduced a new one. I am now getting a System.FormatException:

Not well formatted JSON stream.

Since the JSON from portable and non-portable CSOM is the same, there should not be a parsing error in one CSOM and not the other.

答:
Notice that the first post uses ctx.ExecuteQueryAsync but the "answer" uses ctx.ExecuteQuery.

The bug is in the portable class library (that the first post uses) but this works in the non-portable version (the second post).

Cheers,
Paul

Body:
I am trying to use SharePoint client framework to execute a search, using the portable dll's from a Windows app.

Using Fiddler I can see that my search is executed, and returns a JSON collection of metadata and search results. This is identical to the result from the non-portable CSOM.

When CSOM tries to map the result to it's data objects I get the following exception:

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'Microsoft.SharePoint.Client.Search.Query.ResultTableCollection'.

This exception occurs inside CSOM (portable). Non-portable CSOM runs without exception, and returns the expected result.

The code I am running to get this exception is:

var query = new KeywordQuery(ctx);
query.QueryText = "something";
var executor = new SearchExecutor(ctx);
var results = executor.ExecuteQuery(query);
await ctx.ExecuteQueryAsync();

In the above, ctx is a ClientContext that has already been authenticated. Other requests, such as getting a specific list, works as expected.

I am referencing the following dll's from c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI:

Microsoft.SharePoint.Client.Portable.dll

Microsoft.SharePoint.Client.Runtime.Portable.dll

Microsoft.SharePoint.Client.Runtime.WindowsStore.dll

Microsoft.SharePoint.Client.Search.Portable.dll

My question is.

How do I solve this, so that I can use CSOM to run search queries from a Windows Store app?

UPDATE:
I added the following after authenticating the ClientContext:

ctx.ExecutingWebRequest += (s, e) =>
    e.WebRequest.Headers["Accept-Encoding"] = "gzip, deflate";

This solved the immediate problem, but introduced a new one. I am now getting a System.FormatException:

Not well formatted JSON stream.

Since the JSON from portable and non-portable CSOM is the same, there should not be a parsing error in one CSOM and not the other.


问:
I have got some error when I install Laravel spark like this
PS C:\Win10\tests\spark-installer> cd .\sparkprojectname\
PS C:\Win10\tests\spark-installer\sparkprojectname> php artisan migrate

[Illuminate\Database\QueryException]
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'announcements' alrea
  dy exists (SQL: create table announcements (id varchar(255) not null, user_id
  int not null, body text not null, action_text varchar(255) null, action_url te
  xt null, created_at timestamp null, updated_at timestamp null) default character
   set utf8mb4 collate utf8mb4_unicode_ci)

[PDOException]   SQLSTATE[42S01]: Base table or view already exists:
  1050 Table 'announcements' already exists

答: The table announcements already exists in the Database. And hence when you run the migrate command then it triggers the error. If it is necessary to migrate, then delete the table from database.


问:
A cycle is detected in the object graph using JAXB
How to overcome this error please?

```<code>@XmlRootElement(name="schema")
@Entity
public class SchemaBase implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id_schema;
private String name_schema;
private String description_schema;
private String measuresCaption_schema;
private String defaultRole_schema;

@OneToMany (mappedBy="schema",cascade={CascadeType.MERGE,CascadeType.PERSIST})
private List<CubeBase> cubes;

 @XmlElementWrapper(name = "cube")
   @XmlElement(name = "cube")
public List<CubeBase> getCubes() {
    return cubes;
}

public void setCubes(List<CubeBase> cubes) {
    this.cubes = cubes;
}

public int getId_schema() {
    return id_schema;
}
public void setId_schema(int id_schema) {
    this.id_schema = id_schema;
}
public String getName_schema() {
    return name_schema;
}
@XmlAttribute(name="name")
public void setName_schema(String name_schema) {
    this.name_schema = name_schema;
}
public String getDescription_schema() {
    return description_schema;
}
@XmlAttribute(name="description")
public void setDescription_schema(String description_schema) {
    this.description_schema = description_schema;
}
public String getMeasuresCaption_schema() {
    return measuresCaption_schema;
}
@XmlAttribute(name="measuresCaption")
public void setMeasuresCaption_schema(String measuresCaption_schema) {
    this.measuresCaption_schema = measuresCaption_schema;
}
public String getDefaultRole_schema() {
    return defaultRole_schema;
}
@XmlAttribute(name="defaultRole")
public void setDefaultRole_schema(String defaultRole_schema) {
    this.defaultRole_schema = defaultRole_schema;
}
public void addCubeToShema(List<CubeBase> cubes){
   for(CubeBase cubeBase:cubes)
       cubeBase.setSchema(this);
   this.cubes=cubes;
}

}
</code>```

and the other class is like this:

```<code>@XmlRootElement(namespace ="esprit.olap.domain.SchemaBase")
@Entity
public class CubeBase implements Serializable{

/**
 * Private Attribute
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id_cube;
private String name_cube;
private String description_cube;
private String caption_cube;
private boolean visible;
private boolean cache;
private boolean enabled;

@ManyToOne
private SchemaBase schema;

public boolean isCache() {
    return cache;
}

public void setCache(boolean cache) {
    this.cache = cache;
}
public boolean isEnabled() {
    return enabled;
}

public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}
public boolean isVisible() {
    return visible;
}

public void setVisible(boolean visible) {
    this.visible = visible;
}

public SchemaBase getSchema() {
    return schema;
}

public void setSchema(SchemaBase schema) {
    this.schema = schema;
}
public int getId_cube() {
    return id_cube;
}

public void setId_cube(int id_cube) {
    this.id_cube = id_cube;
}
public String getName_cube() {
    return name_cube;
}

public void setName_cube(String name_cube) {
    this.name_cube = name_cube;
}
public String getDescription_cube() {
    return description_cube;
}

public void setDescription_cube(String description_cube) {
    this.description_cube = description_cube;
}
public String getCaption_cube() {
    return caption_cube;
}

public void setCaption_cube(String caption_cube) {
    this.caption_cube = caption_cube;
}

}
</code>```

答:
Add annotation @XmlTransient before setting  Lists ,
In this exemple you have to add @XmlTransient before addCubeToShema method.</p>

Body:
How to overcome this error please?

@XmlRootElement(name="schema")
@Entity
public class SchemaBase implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id_schema;
private String name_schema;
private String description_schema;
private String measuresCaption_schema;
private String defaultRole_schema;

@OneToMany (mappedBy="schema",cascade={CascadeType.MERGE,CascadeType.PERSIST})
private List<CubeBase> cubes;

 @XmlElementWrapper(name = "cube")
   @XmlElement(name = "cube")
public List<CubeBase> getCubes() {
    return cubes;
}

public void setCubes(List<CubeBase> cubes) {
    this.cubes = cubes;
}

public int getId_schema() {
    return id_schema;
}
public void setId_schema(int id_schema) {
    this.id_schema = id_schema;
}
public String getName_schema() {
    return name_schema;
}
@XmlAttribute(name="name")
public void setName_schema(String name_schema) {
    this.name_schema = name_schema;
}
public String getDescription_schema() {
    return description_schema;
}
@XmlAttribute(name="description")
public void setDescription_schema(String description_schema) {
    this.description_schema = description_schema;
}
public String getMeasuresCaption_schema() {
    return measuresCaption_schema;
}
@XmlAttribute(name="measuresCaption")
public void setMeasuresCaption_schema(String measuresCaption_schema) {
    this.measuresCaption_schema = measuresCaption_schema;
}
public String getDefaultRole_schema() {
    return defaultRole_schema;
}
@XmlAttribute(name="defaultRole")
public void setDefaultRole_schema(String defaultRole_schema) {
    this.defaultRole_schema = defaultRole_schema;
}
public void addCubeToShema(List<CubeBase> cubes){
   for(CubeBase cubeBase:cubes)
       cubeBase.setSchema(this);
   this.cubes=cubes;
}

}

and the other class is like this:

@XmlRootElement(namespace ="esprit.olap.domain.SchemaBase")
@Entity
public class CubeBase implements Serializable{

/**
 * Private Attribute
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id_cube;
private String name_cube;
private String description_cube;
private String caption_cube;
private boolean visible;
private boolean cache;
private boolean enabled;

@ManyToOne
private SchemaBase schema;

public boolean isCache() {
    return cache;
}

public void setCache(boolean cache) {
    this.cache = cache;
}
public boolean isEnabled() {
    return enabled;
}

public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}
public boolean isVisible() {
    return visible;
}

public void setVisible(boolean visible) {
    this.visible = visible;
}

public SchemaBase getSchema() {
    return schema;
}

public void setSchema(SchemaBase schema) {
    this.schema = schema;
}
public int getId_cube() {
    return id_cube;
}

public void setId_cube(int id_cube) {
    this.id_cube = id_cube;
}
public String getName_cube() {
    return name_cube;
}

public void setName_cube(String name_cube) {
    this.name_cube = name_cube;
}
public String getDescription_cube() {
    return description_cube;
}

public void setDescription_cube(String description_cube) {
    this.description_cube = description_cube;
}
public String getCaption_cube() {
    return caption_cube;
}

public void setCaption_cube(String caption_cube) {
    this.caption_cube = caption_cube;
}

}


问:
C++ member of class updated outside class
I have a question about pointers and references in C++. I am a programmer who normally programs in C# and PHP.

I have two classes (for now) which are the following.
The X/Y in Controller are continuously changing but i want them up to date in the Commands. I have multiple commands like Forward, Turn, Backward etc.

When i make the commands i give them the controller but the state (X, Y) of the controller are updating every second.

How can i fix that the controller attribute in the Commands are getting updated also every second?

```<code>class Forward : ICommand
{
    Controller ctrl;

    void Execute() {
        int CurrentX = ctrl.X;
        int CurrentY = ctrl.Y;
        //Check here for the current location and calculate where he has to go.
    }
}

class Controller
{
    int X;
    int Y;

    void ExecuteCommand(ICommand command) {
        command.Execute();
    }
}
</code>```

Main.cpp

```<code>Controller controller;

Forward cmd1 = new Forward(1, controller);
Turn cmd2 = new Turn(90, controller);
Forward cmd3 = new Forward(2, controller);

controller.Execute(cmd1);
controller.Execute(cmd2);
controller.Execute(cmd3);
</code>```

I have read something about pointers and references and i think i have to use this but don't know how to use it in this situation.

(code can have some syntax errors but that's because i typed over. Everything is working further except for the updating).

答:
If you use references rather than copy objects you can see changes.

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

class ICommand
{
public:
    virtual ~ICommand() = default;
    virtual void Execute() = 0;
};

class Controller
{
public:
    int X = 0;
    int Y = 0;

    void ExecuteCommand(ICommand & command) {
        //                       ^-------
        command.Execute();
    }
};//,--- semicolons required

class Forward : public ICommand //note public
{
    const int step;
    Controller ctrlCopy;
    Controller & ctrlReference;

public:
    Forward(int step, Controller & ctrl) :
        step(step),
        ctrlCopy(ctrl),      //this is a copy of an object
        ctrlReference(ctrl)  //this is a reference to an object
    {

    }

    void Execute() {
        std::cout << "copy: " << ctrlCopy.X << ", " << ctrlCopy.Y << '\n';
        std::cout << " ref: " << ctrlReference.X << ", " << ctrlReference.Y << '\n';
        //Check here for the current location and calculate where he has to go.
        ctrlCopy.X += 10;
        ctrlReference.X += 10;
    }
};//<--- semicolons required

int main() {
    Controller controller;

    Forward cmd1(1, controller);
    //Turn cmd2(90, controller); //Left for the OP to do
    Forward cmd3(2, controller);

    controller.ExecuteCommand(cmd1);
    //controller.ExecuteCommand(cmd2);
    controller.ExecuteCommand(cmd3);

    //Do it again to show the copy and reference difference
    std::cout << "Once more, with feeling\n";
    controller.ExecuteCommand(cmd1);
    controller.ExecuteCommand(cmd3);
}
</code>```

Giving

```<code>copy: 0, 0
 ref: 0, 0
copy: 0, 0  // [1]
 ref: 10, 0 // [2]
Once more, with feeling
copy: 10, 0
 ref: 20, 0
copy: 10, 0
 ref: 30, 0
</code>```

1 shows that the copy has X and Y of 0, while the reference shown in [2] has moved by the stated step (in controller.ExecuteCommand(cmd3))

Note, we don't need to use new to make this work (don't forget delete if you use new).

Also, void ExecuteCommand(ICommand command) now takes a reference instead otherwise the by-value copy does "slicing" (e.g. see here)

Body:
I have a question about pointers and references in C++. I am a programmer who normally programs in C# and PHP.

I have two classes (for now) which are the following.
The X/Y in Controller are continuously changing but i want them up to date in the Commands. I have multiple commands like Forward, Turn, Backward etc.

When i make the commands i give them the controller but the state (X, Y) of the controller are updating every second.

How can i fix that the controller attribute in the Commands are getting updated also every second?

class Forward : ICommand
{
    Controller ctrl;

    void Execute() {
        int CurrentX = ctrl.X;
        int CurrentY = ctrl.Y;
        //Check here for the current location and calculate where he has to go.
    }
}

class Controller
{
    int X;
    int Y;

    void ExecuteCommand(ICommand command) {
        command.Execute();
    }
}

Main.cpp

Controller controller;

Forward cmd1 = new Forward(1, controller);
Turn cmd2 = new Turn(90, controller);
Forward cmd3 = new Forward(2, controller);

controller.Execute(cmd1);
controller.Execute(cmd2);
controller.Execute(cmd3);

I have read something about pointers and references and i think i have to use this but don't know how to use it in this situation.

(code can have some syntax errors but that's because i typed over. Everything is working further except for the updating).

Body:
If you use references rather than copy objects you can see changes.

#include <iostream>
using namespace std;

class ICommand
{
public:
    virtual ~ICommand() = default;
    virtual void Execute() = 0;
};

class Controller
{
public:
    int X = 0;
    int Y = 0;

    void ExecuteCommand(ICommand & command) {
        //                       ^-------
        command.Execute();
    }
};//,--- semicolons required

class Forward : public ICommand //note public
{
    const int step;
    Controller ctrlCopy;
    Controller & ctrlReference;

public:
    Forward(int step, Controller & ctrl) :
        step(step),
        ctrlCopy(ctrl),      //this is a copy of an object
        ctrlReference(ctrl)  //this is a reference to an object
    {

    }

    void Execute() {
        std::cout << "copy: " << ctrlCopy.X << ", " << ctrlCopy.Y << '\n';
        std::cout << " ref: " << ctrlReference.X << ", " << ctrlReference.Y << '\n';
        //Check here for the current location and calculate where he has to go.
        ctrlCopy.X += 10;
        ctrlReference.X += 10;
    }
};//<--- semicolons required

int main() {
    Controller controller;

    Forward cmd1(1, controller);
    //Turn cmd2(90, controller); //Left for the OP to do
    Forward cmd3(2, controller);

    controller.ExecuteCommand(cmd1);
    //controller.ExecuteCommand(cmd2);
    controller.ExecuteCommand(cmd3);

    //Do it again to show the copy and reference difference
    std::cout << "Once more, with feeling\n";
    controller.ExecuteCommand(cmd1);
    controller.ExecuteCommand(cmd3);
}

Giving

copy: 0, 0
 ref: 0, 0
copy: 0, 0  // [1]
 ref: 10, 0 // [2]
Once more, with feeling
copy: 10, 0
 ref: 20, 0
copy: 10, 0
 ref: 30, 0

1 shows that the copy has X and Y of 0, while the reference shown in [2] has moved by the stated step (in controller.ExecuteCommand(cmd3))

Note, we don't need to use new to make this work (don't forget delete if you use new).

Also, void ExecuteCommand(ICommand command) now takes a reference instead otherwise the by-value copy does "slicing" (e.g. see here)