text:
Q: Find distance between two points on map using Google Map API V2 I am using google map api v2 in my android application, I am able to show the map and put markers on it, but now I am stuck with the  problem in which I need to find out the distance between two markers or points placed on map, I have already gone through the  docs but didn't find anything helpful in this case.
If anyone knows how to solve this then please help me.
Thanks

A: In Google Map API V2 You have LatLng objects so you can't use distanceTo (yet).
You can then use the following code considering oldPosition and newPosition are LatLng objects :
// The computed distance is stored in results[0].
//If results has length 2 or greater, the initial bearing is stored in results[1].
//If results has length 3 or greater, the final bearing is stored in results[2].
float[] results = new float[1];
Location.distanceBetween(oldPosition.latitude, oldPosition.longitude,
                newPosition.latitude, newPosition.longitude, results);

For more informations about the Location class see this link

A: You can use the following method that will give you accurate result
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
        int Radius = 6371;// radius of earth in Km
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult = Radius * c;
        double km = valueResult / 1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec = Integer.valueOf(newFormat.format(km));
        double meter = valueResult % 1000;
        int meterInDec = Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
                + " Meter   " + meterInDec);

        return Radius * c;
    }

A: You should use the android Location
You can do:
location1.distanceTo(location2);

And also:
float[] results = new float[1];
Location.distanceBetween(latLongA.latitude, latLongA.longitude,
                         latLongB.latitude, latLongB.longitude,
                         results);

And you will get the distance in meters between location1 and location2 in meters.
And beetween latLongA ant latLongB.
Using location.

A: simple util function to calculate distance between two geopoints:
public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {

    double l1 = toRadians(lat1);
    double l2 = toRadians(lat2);
    double g1 = toRadians(lng1);
    double g2 = toRadians(lng2);

    double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
    if(dist < 0) {
        dist = dist + Math.PI;
    }

    return Math.round(dist * 6378100);
}

A: try this
double distance;
Location locationA = new Location("");
locationA.setLatitude(main_Latitude);
locationA.setLongitude(main_Longitude);
Location locationB = new Location("");
locationB.setLatitude(sub_Latitude);
locationB.setLongitude(sub_Longitude);
distance = locationA.distanceTo(locationB)/1000;
kmeter.setText(String.valueOf(distance));
Toast.makeText(getApplicationContext(), ""+distance, Toast.LENGTH_LONG).show();double distance;

A: public class GoogleDirection {

    public final static String MODE_DRIVING = "driving";
    public final static String MODE_WALKING = "walking";
    public final static String MODE_BICYCLING = "bicycling";

    public final static String STATUS_OK = "OK";
    public final static String STATUS_NOT_FOUND = "NOT_FOUND";
    public final static String STATUS_ZERO_RESULTS = "ZERO_RESULTS";
    public final static String STATUS_MAX_WAYPOINTS_EXCEEDED = "MAX_WAYPOINTS_EXCEEDED";
    public final static String STATUS_INVALID_REQUEST = "INVALID_REQUEST";
    public final static String STATUS_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT";
    public final static String STATUS_REQUEST_DENIED = "REQUEST_DENIED";
    public final static String STATUS_UNKNOWN_ERROR = "UNKNOWN_ERROR";

    public final static int SPEED_VERY_FAST = 1;
    public final static int SPEED_FAST = 2;
    public final static int SPEED_NORMAL = 3;
    public final static int SPEED_SLOW = 4;
    public final static int SPEED_VERY_SLOW = 5;

    private OnDirectionResponseListener mDirectionListener = null;
    private OnAnimateListener mAnimateListener = null;

    private boolean isLogging = false;

    private LatLng animateMarkerPosition = null;
    private LatLng beginPosition = null;
    private LatLng endPosition = null;
    private ArrayList<LatLng> animatePositionList = null;
    private Marker animateMarker = null;
    private Polyline animateLine = null;
    private GoogleMap gm = null;
    private int step = -1;
    private int animateSpeed = -1;
    private int zoom = -1;
    private double animateDistance = -1;
    private double animateCamera = -1;
    private double totalAnimateDistance = 0;
    private boolean cameraLock = false;
    private boolean drawMarker = false;
    private boolean drawLine = false;
    private boolean flatMarker = false;
    private boolean isCameraTilt = false;
    private boolean isCameraZoom = false;
    private boolean isAnimated = false;

    private Context mContext = null;

    public GoogleDirection(Context context) {
        mContext = context;
    }

    public String request(LatLng start, LatLng end, String mode) {
        final String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                + "origin=" + start.latitude + "," + start.longitude
                + "&destination=" + end.latitude + "," + end.longitude
                + "&sensor=false&units=metric&mode=" + mode;

        if(isLogging)
            Log.i("GoogleDirection", "URL : " + url);
        new RequestTask().execute(new String[]{ url });
        return url;
    }

    private class RequestTask extends AsyncTask<String, Void, Document> {
        protected Document doInBackground(String... url) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url[0]);
                HttpResponse response = httpClient.execute(httpPost, localContext);
                InputStream in = response.getEntity().getContent();
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                return builder.parse(in);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Document doc) {
            super.onPostExecute(doc);
            if(mDirectionListener != null)
                mDirectionListener.onResponse(getStatus(doc), doc, GoogleDirection.this);
        }

        private String getStatus(Document doc) {
            NodeList nl1 = doc.getElementsByTagName("status");
            Node node1 = nl1.item(0);
            if(isLogging)
                Log.i("GoogleDirection", "Status : " + node1.getTextContent());
            return node1.getTextContent();
        }
    }

    public void setLogging(boolean state) {
        isLogging = state;
    }

    public String getStatus(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("status");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "Status : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String[] getDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        String[] arr_str = new String[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();
            if(isLogging)
                Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
        }
        return arr_str;
    }

    public int[] getDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        int[] arr_int = new int[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());
            if(isLogging)
                Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
        }
        return arr_int;
    }

    public String getTotalDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return node2.getTextContent();
    }

    public int getTotalDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String[] getDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        String[] arr_str = new String[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();
            if(isLogging)
                Log.i("GoogleDirection", "DurationText : " + node2.getTextContent());
        }
        return arr_str;
    }

    public int[] getDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        int[] arr_int = new int[nl1.getLength() - 1];
        for(int i = 0 ; i < nl1.getLength() - 1 ; i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());
            if(isLogging)
                Log.i("GoogleDirection", "Duration : " + node2.getTextContent());
        }
        return arr_int;
    }

    public String getTotalDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return node2.getTextContent();
    }

    public int getTotalDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        if(isLogging)
            Log.i("GoogleDirection", "TotalDuration : " + node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "StartAddress : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String getEndAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "StartAddress : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public String getCopyRights(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        if(isLogging)
            Log.i("GoogleDirection", "CopyRights : " + node1.getTextContent());
        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection(Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for(int j = 0 ; j < arr.size() ; j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude
                            , arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public ArrayList<LatLng> getSection(Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public PolylineOptions getPolyline(Document doc, int width, int color) {
        ArrayList<LatLng> arr_pos = getDirection(doc);
        PolylineOptions rectLine = new PolylineOptions().width(dpToPx(width)).color(color);
        for(int i = 0 ; i < arr_pos.size() ; i++)
            rectLine.add(arr_pos.get(i));
        return rectLine;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for(int i = 0 ; i < nl.getLength() ; i++) {
            if(nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        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 position = new LatLng((double)lat / 1E5, (double)lng / 1E5);
            poly.add(position);
        }
        return poly;
    }

    private int dpToPx(int dp) {
        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }

    public void setOnDirectionResponseListener(OnDirectionResponseListener listener) {
        mDirectionListener = listener;
    }

    public void setOnAnimateListener(OnAnimateListener listener) {
        mAnimateListener = listener;
    }

    public interface OnDirectionResponseListener {
        public void onResponse(String status, Document doc, GoogleDirection gd);
    }

    public interface OnAnimateListener {
        public void onFinish();
        public void onStart();
        public void onProgress(int progress, int total);
    }

    public void animateDirection(GoogleMap gm, ArrayList<LatLng> direction, int speed
            , boolean cameraLock, boolean isCameraTilt, boolean isCameraZoom
            , boolean drawMarker, MarkerOptions mo, boolean flatMarker
            , boolean drawLine, PolylineOptions po) {
        if(direction.size() > 1) {
            isAnimated = true;
            animatePositionList = direction;
            animateSpeed = speed;
            this.drawMarker = drawMarker;
            this.drawLine = drawLine;
            this.flatMarker = flatMarker;
            this.isCameraTilt = isCameraTilt;
            this.isCameraZoom = isCameraZoom;
            step = 0;
            this.cameraLock = cameraLock;
            this.gm = gm;

            setCameraUpdateSpeed(speed);

            beginPosition = animatePositionList.get(step);
            endPosition = animatePositionList.get(step + 1);
            animateMarkerPosition = beginPosition;

            if(mAnimateListener != null)
                mAnimateListener.onProgress(step, animatePositionList.size());

            if(cameraLock) {
                float bearing = getBearing(beginPosition, endPosition);
                CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                    .target(animateMarkerPosition).bearing(bearing);

                if(isCameraTilt)
                    cameraBuilder.tilt(90);
                else
                    cameraBuilder.tilt(gm.getCameraPosition().tilt);

                if(isCameraZoom)
                    cameraBuilder.zoom(zoom);
                else
                    cameraBuilder.zoom(gm.getCameraPosition().zoom);

                CameraPosition cameraPosition = cameraBuilder.build();
                gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }

            if(drawMarker) {
                if(mo != null)
                    animateMarker = gm.addMarker(mo.position(beginPosition));
                else
                    animateMarker = gm.addMarker(new MarkerOptions().position(beginPosition));

                if(flatMarker) {
                    animateMarker.setFlat(true);

                    float rotation = getBearing(animateMarkerPosition, endPosition) + 180;
                    animateMarker.setRotation(rotation);
                }
            }

            if(drawLine) {
                if(po != null)
                    animateLine = gm.addPolyline(po.add(beginPosition)
                            .add(beginPosition).add(endPosition)
                            .width(dpToPx((int)po.getWidth())));
                else
                    animateLine = gm.addPolyline(new PolylineOptions()
                            .width(dpToPx(5)));
            }

            new Handler().postDelayed(r, speed);
            if(mAnimateListener != null)
                mAnimateListener.onStart();
        }
    }

    public void cancelAnimated() {
        isAnimated = false;
    }

    public boolean isAnimated() {
        return isAnimated;
    }

    private Runnable r = new Runnable() {
        public void run() {

            animateMarkerPosition = getNewPosition(animateMarkerPosition, endPosition);

            if(drawMarker)
                animateMarker.setPosition(animateMarkerPosition);

            if(drawLine) {
                List<LatLng> points = animateLine.getPoints();
                points.add(animateMarkerPosition);
                animateLine.setPoints(points);
            }

            if((animateMarkerPosition.latitude == endPosition.latitude
                    && animateMarkerPosition.longitude == endPosition.longitude)) {
                if(step == animatePositionList.size() - 2) {
                    isAnimated = false;
                    totalAnimateDistance = 0;
                    if(mAnimateListener != null)
                        mAnimateListener.onFinish();
                } else {
                    step++;
                    beginPosition = animatePositionList.get(step);
                    endPosition = animatePositionList.get(step + 1);
                    animateMarkerPosition = beginPosition;

                    if(flatMarker && step + 3 < animatePositionList.size() - 1) {
                        float rotation = getBearing(animateMarkerPosition, animatePositionList.get(step + 3)) + 180;
                        animateMarker.setRotation(rotation);
                    }

                    if(mAnimateListener != null)
                        mAnimateListener.onProgress(step, animatePositionList.size());
                }
            }

            if(cameraLock && (totalAnimateDistance > animateCamera || !isAnimated)) {
                totalAnimateDistance = 0;
                float bearing = getBearing(beginPosition, endPosition);
                CameraPosition.Builder cameraBuilder = new CameraPosition.Builder()
                    .target(animateMarkerPosition).bearing(bearing);

                if(isCameraTilt)
                    cameraBuilder.tilt(90);
                else
                    cameraBuilder.tilt(gm.getCameraPosition().tilt);

                if(isCameraZoom)
                    cameraBuilder.zoom(zoom);
                else
                    cameraBuilder.zoom(gm.getCameraPosition().zoom);

                CameraPosition cameraPosition = cameraBuilder.build();
                gm.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            }

            if(isAnimated) {
                new Handler().postDelayed(r, animateSpeed);
            }
        }
    };

    public Marker getAnimateMarker() {
        return animateMarker;
    }

    public Polyline getAnimatePolyline() {
        return animateLine;
    }

    private LatLng getNewPosition(LatLng begin, LatLng end) {
        double lat = Math.abs(begin.latitude - end.latitude);
        double lng = Math.abs(begin.longitude - end.longitude);

        double dis = Math.sqrt(Math.pow(lat, 2) + Math.pow(lng, 2));
        if(dis >= animateDistance) {
            double angle = -1;

            if(begin.latitude <= end.latitude && begin.longitude <= end.longitude)
                angle = Math.toDegrees(Math.atan(lng / lat));
            else if(begin.latitude > end.latitude && begin.longitude <= end.longitude)
                angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 90;
            else if(begin.latitude > end.latitude && begin.longitude > end.longitude)
                angle = Math.toDegrees(Math.atan(lng / lat)) + 180;
            else if(begin.latitude <= end.latitude && begin.longitude > end.longitude)
                angle = (90 - Math.toDegrees(Math.atan(lng / lat))) + 270;

            double x = Math.cos(Math.toRadians(angle)) * animateDistance;
            double y = Math.sin(Math.toRadians(angle)) * animateDistance;
            totalAnimateDistance += animateDistance;
            double finalLat = begin.latitude + x;
            double finalLng = begin.longitude + y;

            return new LatLng(finalLat, finalLng);
        } else {
            return end;
        }
    }

    private float getBearing(LatLng begin, LatLng end) {
        double lat = Math.abs(begin.latitude - end.latitude);
        double lng = Math.abs(begin.longitude - end.longitude);
         if(begin.latitude < end.latitude && begin.longitude < end.longitude)
            return (float)(Math.toDegrees(Math.atan(lng / lat)));
        else if(begin.latitude >= end.latitude && begin.longitude < end.longitude)
            return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
        else if(begin.latitude >= end.latitude && begin.longitude >= end.longitude)
            return  (float)(Math.toDegrees(Math.atan(lng / lat)) + 180);
        else if(begin.latitude < end.latitude && begin.longitude >= end.longitude)
            return (float)((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
         return -1;
    }

    public void setCameraUpdateSpeed(int speed) {
        if(speed == SPEED_VERY_SLOW) {
            animateDistance = 0.000005;
            animateSpeed = 20;
            animateCamera = 0.0004;
            zoom = 19;
        } else if(speed == SPEED_SLOW) {
            animateDistance = 0.00001;
            animateSpeed = 20;
            animateCamera = 0.0008;
            zoom = 18;
        } else if(speed == SPEED_NORMAL) {
            animateDistance = 0.00005;
            animateSpeed = 20;
            animateCamera = 0.002;
            zoom = 16;
        } else if(speed == SPEED_FAST) {
            animateDistance = 0.0001;
            animateSpeed = 20;
            animateCamera = 0.004;
            zoom = 15;
        } else if(speed == SPEED_VERY_FAST) {
            animateDistance = 0.0005;
            animateSpeed = 20;
            animateCamera = 0.004;
            zoom = 13;
        } else {
            animateDistance = 0.00005;
            animateSpeed = 20;
            animateCamera = 0.002;
            zoom = 16;
        }
    }
}

//Main Activity
public class MapActivity extends ActionBarActivity {

    GoogleMap map = null;
    GoogleDirection gd;

    LatLng start,end;

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

        start = new LatLng(13.744246499553903, 100.53428772836924);
        end = new LatLng(13.751279688694071, 100.54316081106663);

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 15));

        gd = new GoogleDirection(this);
        gd.setOnDirectionResponseListener(new GoogleDirection.OnDirectionResponseListener() {
            public void onResponse(String status, Document doc, GoogleDirection gd) {
                Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();

                gd.animateDirection(map, gd.getDirection(doc), GoogleDirection.SPEED_FAST
                        , true, true, true, false, null, false, true, new PolylineOptions().width(8).color(Color.RED));

                map.addMarker(new MarkerOptions().position(start)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.markera)));

                map.addMarker(new MarkerOptions().position(end)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.markerb)));

                String TotalDistance = gd.getTotalDistanceText(doc);
                String TotalDuration = gd.getTotalDurationText(doc);
            }
        });

        gd.request(start, end, GoogleDirection.MODE_DRIVING);
    }
}

A: Coming rather late, but seeing that this is one of the top results on Google search for the topic I'll share another way:
Use a one-liner with Googles utility class SphericalUtil
SphericalUtil.computeDistanceBetween(latLngFrom, latLngTo)

You will need the utility classes.
You can simply include them in your project using gradle:
implementation 'com.google.maps.android:android-maps-utils:0.5+'

A: The distance between two geo-coordinates can be found by using Haversine formula . This formula is effective to calculate distance in a spherical body i.e earth in our case.

A: THIS IS THE EASY AND PERFECT CODE FOR DURATION AND DISTANCE FINDING

*

*Step 1;(add this and sync in your gradle)
 implementation 'com.android.volley:volley:1.0.0'

*Step 2:(write this in your trigger method)
 public void clicked(View view) throws JSONException {

      JSONObject locationJsonObject = new JSONObject();
             locationJsonObject.put("origin", "54.406505,18.67708");
             locationJsonObject.put("destination", "54.446251,18.570993");
             LatlngCalc(locationJsonObject);
 }

*Step 3:(Copy & Paste in your class)
 private void LatlngCalc(JSONObject locationJsonObject) throws JSONException {

     RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
     String url = "https://maps.googleapis.com/maps/api/distancematrix/" +
                 "json?origins=" + locationJsonObject.getString("origin") + "&destinations=" + locationJsonObject.getString("destination") + "&mode=driving&" +
                 "language=en-EN&sensor=false" + "&key=" + /*Insert Your API Key Here */;

     StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
             new Response.Listener<String>() {
                 @Override
                 public void onResponse(String response) {

                     mTextView.setText("Response is: " + response.substring(0, 500));
                 }
             }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
             mTextView.setText("That didn't work!");
         }
     });
     queue.add(stringRequest);
 }

A: to get distance between two points try this code..
public static float GetDistanceFromCurrentPosition(double lat1,double lng1, double lat2, double lng2)
 {
        double earthRadius = 3958.75;

        double dLat = Math.toRadians(lat2 - lat1);

        double dLng = Math.toRadians(lng2 - lng1);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
                * Math.sin(dLng / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double dist = earthRadius * c;

        int meterConversion = 1609;

        return new Float(dist * meterConversion).floatValue();

    }

A: you can use this function. I have used it in my project.
public String getDistance(LatLng my_latlong, LatLng frnd_latlong) {
    Location l1 = new Location("One");
    l1.setLatitude(my_latlong.latitude);
    l1.setLongitude(my_latlong.longitude);

    Location l2 = new Location("Two");
    l2.setLatitude(frnd_latlong.latitude);
    l2.setLongitude(frnd_latlong.longitude);

    float distance = l1.distanceTo(l2);
    String dist = distance + " M";

    if (distance > 1000.0f) {
        distance = distance / 1000.0f;
        dist = distance + " KM";
    }
    return dist;
}

A: This is an old question with old answers. I want to highlight an updated way of calculating distance between two points. By now we should be familiar with the utility class, "SphericalUtil". You can retrieve the distance using that.
double distance = SphericalUtil.computeDistanceBetween(origin, dest);

A: All this answers will give you the distance in a straight line. If you need to get the distance by road, you have to parse the JSON that Google sends you back after calling his service. You can use this method:
public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
    String parsedDistance;
    String response;
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
                    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("routes");
                    JSONObject routes = array.getJSONObject(0);
                    JSONArray legs = routes.getJSONArray("legs");
                    JSONObject steps = legs.getJSONObject(0);
                    JSONObject distance = steps.getJSONObject("distance");
                    parsedDistance=distance.getString("text");

                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return parsedDistance;
}

lat1 and lon1 are coordinates of origin, lat2 and lon2 are coordinates of destination.

A: @salman khan what Usman Kurd suggested is perfect. Only thing i found which can be corrected is that "For google maps v2 we use LatLng class. So below is the code of Usman Kurd that can be used for Google Maps v2. I checked it works perfect.
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
        int Radius=6371;//radius of earth in Km
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2-lat1);
        double dLon = Math.toRadians(lon2-lon1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult= Radius*c;
        double km=valueResult/1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec =  Integer.valueOf(newFormat.format(km));
        double meter=valueResult%1000;
        int  meterInDec= Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value",""+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);

        return Radius * c;
     }

A: Use Google directions Api
https://maps.googleapis.com/maps/api/directions/json?origin=00.00,00.004&destination=00.00,00.00&key=YOUR_MAP_KEY
Parse Api Response:
JSONArray jsonArrayRoutes = jObject.getJSONArray("routes");
            if (jsonArrayRoutes.length() > 0) {
                JSONObject jsonObjectRoutes = jsonArrayRoutes.getJSONObject(0);

                if (!jObject.isNull("bounds")) {
                    JSONObject jsonObjectBounds = jObject.getJSONObject("bounds");
                    if (!jsonObjectBounds.isNull("northeast")) {
                        JSONObject jsonObjectNorthEast = jsonObjectBounds.getJSONObject("northeast");
                        LatLng latLngNorthEast = new LatLng(Double.parseDouble(jsonObjectNorthEast.getString("lat")), Double.parseDouble(jsonObjectNorthEast.getString("lng")));
                    }
                    if (!jsonObjectBounds.isNull("southwest")) {
                        JSONObject jsonObjectSouthWest = jsonObjectBounds.getJSONObject("southwest");
                        LatLng latLngSouthWest = new LatLng(Double.parseDouble(jsonObjectSouthWest.getString("lat")), Double.parseDouble(jsonObjectSouthWest.getString("lng")));
                    }
                }

                //Distance & Duration
                JSONArray jsonArrayLegs = jsonObjectRoutes.getJSONArray("legs");
                if (jsonArrayLegs.length() > 0) {
                    JSONObject jsonObjectLegs = jsonArrayLegs.getJSONObject(0);

                    JSONObject jsonObjectDistance = jsonObjectLegs.getJSONObject("distance");
                    String distKM = jsonObjectDistance.getString("text");
                    System.out.println("Distance in KM: " + distKM);
                    JSONObject jsonObjectDuration = jsonObjectLegs.getJSONObject("duration");
                    String durTime = jsonObjectDuration.getString("text");
                    System.out.println("Duration: " + durTime);
                }
            }

A: In android google maps application there is a very easy way to find distance between 2 locations, to do so follow the following easy steps:

*

*when you first open the app go to " your timeline " from the drop
menue on the top left.

*once the new windwo opens, chose from the settings on your top right menue and choose "add place".

*add your places and name them lilke point 1 , point 2 , or any easy name to remember.

*once your places are added and flagged go back to the main Window in your google app.

*click on the blue circle with the arrow in your bottom right.

*a new windwo will open and you can see on the top there are two text fields in which you can add your "from location" and "distance location".

*click on any text field and type in your saved location in point 3.

*click on the other text field and add your next saved location.

*By doing so, google maps will calculate the distance between the two locations and show you the blue path on map ..

Good luck


text:
Q: Capture ContentService return from Google Sheet with javascript on the page I have a web form that gathers some data from users, then sent the data to Google Sheet with doPost(). Now I need to capture the ContentService returned to my with javascript, so I could display some feedbacks on the same page with that web form. I have tried to set the "target" attribute of the form to some hidden iframe, and I keep getting "script.googleusercontent.com refused to connect".  So my question is, what is the best way to capture the content service object return by Google Sheet without directing my users to another page or reloading the current page?
Thank in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Move object relative to the direction it's facing I am trying to move an object upwards relative to the direction it's facing. I have a CubeGeometry with a certain height, and I want to put an object at the top of it, and rotate with the cube. I cannot just add the new object to the cube because I need to be able to access the rotation of this object (which will be rotated later) and the parent object. For example, if you were facing up, "up" would be sideways. I have tried to get the direction something is facing with .getWorldDirection() and rotating it using .applyAxisAngle(), but this does not work for some reason. My code right now:
tmpObj.position.set(cube.position.x, cube.position.y, cube.position.z); // put at the position of the cube
var gwd = cube.getWorldDirection().applyAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI*-0.5); // if you don't do the applyAxisAngle, it will be facing the wrong direction
gwd.multiplyScalar(2.5); // the height of the cube
tmpObj.position.add(gwd);

This makes the cube (tmpObj) go the wrong way when cube is rotated.
For reference, there is another tmpObj and cube (named differently) that will then point at each other in order to detect what side of each other they are on.

A: In three.js, an object is considered to be facing in the direction of its local, positive Z-axis. (The exception is a camera, which faces its local, negative Z-axis.)
By default, the local, positive Y-axis is "up" in the object's local coordinate system.
You can translate an object in the direction of its local, positive Y-axis like so:
object.translateY( distance );

three.js r.90


text:
Q: Why arent these PHP functions working? I think for some reason $con is not getting filled with a connection, or db_connection() is not returning $con properly, because i always end up with this notice:
Notice: Undefined variable: con in ...
And i also get this error:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ...
function db_connection(){

$username="username123";
$password="password1234";
$database="iptracker";

$con=mysqli_connect('localhost',$username,$password,$database);

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

return $con;
}

function add_ip_to_db($user_ip){

//mysqli_close($con);
db_connection();

$current_time = date ('Y-m-d h:m');
mysqli_query($con,"INSERT INTO ips (ip, submit_count, date_time)
VALUES ('". $user_ip ."', 1, $current_time)");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);

}

function add_count_to_db($user_ip){

//mysqli_close($con);
db_connection();

mysqli_query($con,"UPDATE ips ".
       "SET submit_count = submit_count+1 ".
       "WHERE ip = '". $user_ip ."'" );

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);
}

function check_ip($user_ip){

db_connection();

$result = mysqli_query($con,"SELECT * FROM ips WHERE ip='". $user_ip."' LIMIT 1");

    if(mysqli_fetch_array($result) !== false){
        //Adding record to database
        add_ip_to_db($user_ip);
    } else {
        //Update database and adding another count to 'submit_count'
        add_count_to_db($user_ip);
    }
}

check_ip($_SERVER['REMOTE_ADDR']);

A: You are not using the returned $con, do this in all your functions:
$con = db_connection();

A: You're calling the db_connection function which returns the $con handler, but you are not assigning it's returned value to a variable.
Try amending to:
$con = db_connection();

Additionally, this $con assignment is also within a function, which means the variable will only be available within the scope of that function.

A: That's because $con is empty. It is local to the function. As soon as the function ends it's nowhere to be found. Assign a variable to db_connection();
$con = db_connection();


text:
Q: Javascript - How to toggle an element in contenteditable as execCommand? I want to toggle B tag if selected:

Zeffer !

<button id="bold">Bold</button>

A: You can simply add a click event listener to the button, which executes the execCommand.
var bold = document.getElementById('bold');

bold.addEventListener('click', function () {
    document.execCommand('bold', false, null);
});

When selecting the text inside the contenteditable div and then clicking the button, it will toggle to either bold or non-bold; depending on its' current status.
See this fiddle for a live demo.


text:
Q: ProGuard is not obfuscating Android project? I try to include ProGuard in my Android project, because i want to my app be less "readable" after decompilation so i configured ProGuard and there is no difference between decompiled app (using apktool) with ProGuard and without.
This is my proguard.cfg file:
-optimizationpasses 5
-dontwarn org.apache.commons.codec.binary.Base64
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

Plus i added this line to project.properties:
proguard.config=proguard.cfg


text:
Q: Emit format in C# UWP So I created a nodejs server like this :
var io = socket(server);

io.on('connection', (socket) => {

console.log('made socket connection', socket.id);

// Handle chat event
socket.on('chat', function(data){
    console.log(data);
    io.sockets.emit('chat', data);
});

with nice UI and work out perfectly with this JavaScript function:
btn.addEventListener('click', function(){
socket.emit('chat', {
  message: message.value,
  handle: handle.value
 });
 });

and got the result like this
made socket connection eo96mhJ1_RwG9WYMAAAR
{ message: 'Hello', handle: 'From the Browser' }

Now I want my UWP application connect to server and emit the message just like the front-end on the server
I use "SocketIOClientDotNet" nuget
here is the code:
var socket = IO.Socket("ws://localhost:8888");
socket.Connect();
ReceivedText.Text = "Connect Completed";
socket.Emit("chat", "This is a message from UWP...");

and the console reply:
made socket connection 8rRfm0gOmJeg9orIAAAe
This is a message from UWP...

the problem here is: I want the emit message have the same exact same format as the front-end so It could display like this :
{ message: 'Hello', handle: 'From UWP' }

which is params object[] in C# have work like the JavaScript frontend in the socket.Emit but I don't know it's syntax

A: The response is JSON based, so you can use Json.NET for this.
First install Newtonsoft.Json from NuGet:
> Install-Package Newtonsoft.Json -Version 12.0.1

Create a class:
public class SocketMessage
{
   public string Message {get;set;}
   public string Handle {get;set;}
}

And now use Json.NET to serialize instance of this object:
var message = new SocketMessage()
{
   Message = "Hello",
   Handle = "From UWP"
};
socket.Emit("chat", JsonConvert.SerializeObject(message));


text:
Q: Understanding the prime notation for the derivative of a power function Let's say, hypothetically, that I got this question: y = x^2
I would take the derivative by multiplying both sides by " ' ", getting y'= x'^2'
My question is whether or not the " ' " carries to the ^2 as well.
Thank you for the help.

A: Welcome to MSE @quantum bontum,
I believe you have a misconception regarding the derivatives.
The notation,
$$f'(x)=\frac{d}{dx}f(x)$$
If $f(x)=x^{2}$ then it's derivative is represented as,
$$f'(x)=(x^{2})'=2x$$
Here are some videos of Khan academy on calculus which might help you to get some intuition regarding your question.


text:
Q: Implicit Euler scheme for the Navier-Stokes equation and the Schauder fixed-point theorem Let

*

*$d\in\left\{1,\ldots,4\right\}$

*$\Lambda\subseteq\mathbb R^d$ be a bounded Lipschitz domain

*$\mathcal V:=\left\{\phi\in C_c^\infty(\Lambda,\mathbb R^d):\nabla\cdot\phi=0\right\}$, $V:=\overline{\mathcal V}^{\left\|\;\cdot\;\right\|_{H^1(\Lambda,\:\mathbb R^d)}}$ and $H:=\overline{\mathcal V}^{\left\|\;\cdot\;\right\|_{L^2(\Lambda,\:\mathbb R^d)}}$

*$\mathfrak a(u,v):=\sum_{i=1}^d\langle\nabla u_i,\nabla v_i\rangle_{L^2}$ for $u,v\in V$

*$\mathfrak b(u,v,w):=\langle((u\cdot\nabla)v,w\rangle_{L^2}$ for $u,v,w\in V$

*$\nu>0$

*$f\in L^2(\Lambda,\mathbb R^d)$

*$u^0\in V$

*$h>0$

Now, let $$\eta_u(v):=\frac1h\langle u-u^0,v\rangle_H+\nu\mathfrak a(u,v)+\mathfrak b(u,u,v)-\langle f,v\rangle_{L^2(\Lambda,\:\mathbb R^d)}\;\;\;\text{for }v\in V$$ for $u\in V$. It's easy to see that $$\left|\mathfrak a(u,v)\right|\le C_1\left\|u\right\|_H\left\|v\right\|_H\;\;\;\text{for all }u,v\in V\tag1$$ and $$\left|\mathfrak b(u,u,v)\right|\le C_2\left\|u\right\|_V^2\left\|v\right\|_V\;\;\;\text{for all }u,v\in V\tag2$$ for some $C_1,C_2\ge 0$. Thus, $$\left|\eta_u(v)\right|\le\left(\left(\frac1h+\nu C_1\right)\left\|u\right\|_H+C_2\left\|u\right\|_V^2+\left\|f\right\|_{L^2(\Lambda,\:\mathbb R^d)}+\frac1h\left\|u_0\right\|_H\right)\left\|v\right\|_V\;\;\;\text{for all }v\in V\tag3\;,$$ i.e. $$\eta_u\in V'\;,\tag4$$ for all $u\in V$. By $(4)$ and Riesz' representation theorem, for all $u\in V$ there is a unique $\Phi(u)\in V$ with $$\langle\Phi(u),v\rangle_V=\eta_u(v)\;\;\;\text{for all }v\in V\tag5\;.$$

How can we show that $V\ni u\mapsto\Phi(u)$ is continuous?


text:
Q: How to change ID to Class in Javascript What do you do to change a javascript from a ID to a Class? I tried to do it on my own but with no luck, this is what I ended up with. The original code was to show or hide an element and remember the users selection.
HTML:

JAVASCRIPT:
function setCookie (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie (name) {

    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;

    if (cookie.length > 0) {
        offset = cookie.indexOf(search);

        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset);

            if (end == -1) {
                end = cookie.length;
            }

            setStr = unescape(cookie.substring(offset, end));
        }
    }

    if (setStr == 'false') {
        setStr = false;
    }

    if (setStr == 'true') {
        setStr = true;
    }

    if (setStr == 'null') {
        setStr = null;
    }

    return(setStr);
}

function hidePopup() {
    setCookie('popup_state', false);
    document.getElementsByClassName('popup').style.display = 'none';
}

function showPopup() {
    setCookie('popup_state', null);
    document.getElementsByClassName('popup').style.display = 'block';
}

function checkPopup() {
    if (getCookie('popup_state') == null) {
        // if popup was not closed
        document.getElementsByClassName('popup').style.display = 'block';
    }
}

A: document.getElementsByClassName gives you back a NodeList.  And a NodeList doesn't have a style property that's useful...all it has is length, and indexes for each node in the list.
In order to set the style of every popup that was found, you should iterate through the NodeList.  For example:
function showPopups() {
    setCookie('popup_state', null);
    var popups = document.getElementsByClassName('popup');
    for (var i = popups.length - 1; i >= 0; --i) {
        popups[i].style.display = '';
    }
}

Of course, to hide them, you'd set the display to none instead.
If you know you'll only have one element to change, (1) why aren't you using an ID? :)  but (2) you can just say document.getElementsByClassName('popup')[0] to access the one element.  Note, though...if you ever have more than one, you'll only change the first one that way.


text:
Q: how to handle navigation on map annotation bubble I trying to create an application which will show some location on map. When i click on bubble with location name, i want to navigate to different view which will some information regarding the selected location
Can anyone guide me how to do that..
Thanx

A: You can use MKMapView delegate method
- (void) mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view
calloutAccessoryControlTapped:(UIControl *)control {
        // navigate to view from here
}

A: @Umang why don't to you try adding a UIButton to the MKPinAnnotationView and give it a action that will be much easier. Navigate to diffetrent view by the action of UIButton......Please have a look on this tutorial and see how the UIImageView and UIButton is added to the MKPinAnnotationView
good Luck!


text:
Q: Resizing div's in an AngularJS directive? I'm trying to resize a div with a background image (left) and a variable height description (right), but can't get it to work. Here's the fiddle
. I tried several things with/without zepto/jQuery/document.getElementById ... nothing works.
.directive('resize', function () {
  return {
    restrict: 'A',
    scope: {},
    link: function(scope, elem, attrs) {
      elem.height(400);
    }
  };
})

A: You can use jQuery:
jQuery(elem).height(400);

Fiddle
Not too ideal though :(

A: If you don't use jQuery, AngularJS implements only a lite version of the framework, jqLite, which doesn't have a height() method. You can see the documentation for the list of the available functions in jqLite.
In your case, for instance, you can simply do:
element.css('height', '400px');

Fiddle
Notice that, as pointed out in the comment, your fiddle wasn't functional. I've corrected that problem.


text:
Q: cURL Response JSON RestAPI I need to delete some wrong data, inserted in a lot of processes, and I need to figure if this is possible with cURL and rest API, with a script in sh, batch or something like this:
curl -u admin:admin -i -H "Accept: application/json" -X GET "http://json_bpm.com/wle/v1/service/6112449?action=getData&fields=context"

First I just need the result map.
Output:
{"status":"200","data":{"result":"{\"context\":{\"name\":\"xxx\" (...)
"resultMap":{"context":{"name\":"xxx\" (...) }}}

Because I need to remove the userDelete array (see below) for thousands of processes, and set this again using curl. If you know how to remove arrays from JSON too, you're the man. :)
 {
    "context": {
        "name": "Change Process",
        "startUser": {
            "user": "0001"
        },
        "endUser": {
            "user": "0001"
        },
        "userDelete": {
            "user": "0002"
        },
        "origin": "GUI",
        "userAction": "Change Process"
    }
 }


text:
Q: How can you index python functions for use in a for loop? I'd like to figure out how to code the following pseudo-code:
# Base-case
u_0(x) = x^3

for i in [0,5):
    u_(i+1)(x) = u_(i)(x)^2

So that in the end I can call u_5(x), for example.
The difficulty I'm having with accomplishing the above is finding a way to index Python functions by i so that I can iteratively define each function.
I tried using recursion with two functions in place of indexing but I get "maximum recursion depth exceeded".
Here is a minimal working example:
import math
import sympy as sym

a,b = sym.symbols('x y')

def f1(x,y):
    return sym.sin(x) + sym.cos(y)*sym.tan(x*y)

for i in range(0,5):
    def f2(x,y):
    return sym.diff(f1(x,y),x) + sym.cos(sym.diff(f1(x,y),y,y))

    def f1(x,y):
        return f2(x,y)

print(f2(a,b))

A: Yes, the general idea would be to "index" the results in order to avoid recalculating them. The simplest way to achieve that is to "memoize", meaning telling a function to remember the result for values it has already calculated.
If f(i+1) is based on f(i) where i is a natural number, that can be especially effective.
In Python3, doing it for a 1 variable function is surprisingly simple, with a decorator:

import functools
@functools.lru_cache(maxsize=None)
def f(x):
    .....
    return ....

To know more about this, you can consult
What is memoization and how can I use it in Python?. (If you are using Python 2.7, there is also a way to do it with a prepackaged decorator.)
Your specific case (if my understanding of your pseudo-code is correct) relies on a two variables function, where i is an integer variable and x is a symbol (i.e. not supposed to be resolved here). So you would need to memoize along i.
To avoid blowing the stack up when you brutally ask for the image of 5 (not sure why, but no doubt there is more recursion than meets the eye), then use a for loop to calculate your images on the range from 0 to 5 (in that order: 0, 1, 2...).
I hope this helps.

A: The answer is actually pretty simple:
Pseudocode:
u_0(x) = x^3

for i in [0,5):
     u_(i+1)(x) = u_(i)(x)^2

Actual code:
import sympy as sym

u = [None]*6 #Creates an empty array of 6 entries, i.e., u[0], u[1], ..., u[5]

x=sym.symbols('x')

u[0] = lambda x: x**3

for i in range(0,5):
    u[i+1] = lambda x, i=i: (u[i](x))**2 #the i=i in the argument of the lambda function is
     #necessary in Python; for more about this, see this question.

#Now, the functions are stores in the array u.  However, to call them (e.g., evaluate them,
#plot them, print them, etc) requires that we "lambdify" them, i.e., replace sympy
#functions with numpy functions, which the following for loop accomplishes:

for i in range(0,6):
    ulambdified[i] = sym.lambdify(x,u[i](x),"numpy")

for i in range(0,6):
    print(ulambdified[i](x))


text:
Q: Equally spaced points on a sphere If you have an image on a plane,  you can represent it discreetly by sampling equally spaced points and putting the values in a matrix of some sort. (I'm not worried about the potential lost of information this may imply)
If you were to do the same for an image on a sphere, how could you pick the points to sample from. The Platonic Solids provide five examples of equally spaced points on a sphere. But are these the only five configurations possible? This would limit the maximum resolution of the image to 20 points of the vertices of the dodecaedro. (without resorting to imperfect configurations). This is a disappointingly low number of points. And my expectations say that this problem has less restrictions than the platonic solids do. So maybe it could have more solutions.
So, in one sentence, my question is:
For an arbitrarily large N, can you always find a configuration of n > N points that are even spaced within the surface of a sphere?
Maybe group-theory and the study of symmetries have something to say about this problem?
EDIT: After consulting some professors of mine, It turns out that this problem is closely related to the sphere packing problem.
One of my professors pointed to Sphere Codes:
http://neilsloane.com/packings/
The formal formulation of this problem is:  Place n points on a sphere in d dimensions so as to maximize the minimal distance (or equivalently the minimal angle) between them.

A: Since regular polygons include the equilateral triangle, square, and regular pentagon, which form the five Platonic solids, then since these solids can all be inscribed in a sphere, and Euclid shows that no other regular solids are possible (Elements, XIII, 18), then wouldn't the twenty vertices of the regular dodecahedron be the maximum number of points that can be equally spaced on the surface of a sphere? Each of the twenty points is separated from its three nearest neighbors by an arc whose chord is the edge of the regular pentagon which makes up the inscribed solid. If this is a good argument, then there would be no solution for an arbitrary number of points.

A: The best method I can think of is unfortunately complex.  If you construct a standing spherical wave super imposed on the earth you can adjust the parameters of the wave to produce the desired number of nodes required.  I believe this will allow you to pick an arbitrary number of points and evenly distribute them.  A visual example of this can be seen on page 440 of this pdf http://www.mr-fusion.hellblazer.com/pdfs/spherical_nonlinear_waves.pdf
Perhaps someone here with a better grasp of differential equations and linear algebra can comment on plausibility of this approach.


text:
Q: publishing a svelte 3 component: semantics for "main" and "svelte" fields of package.json? I took the Svelte tutorial and rewrote the keypad in the component bindings section with a state machine. That worked lovely.
Now I want to extract the Machine.svelte file into a npm package and I am not sure how to do that. I could not find any documentation about publishing. For what I saw from svelte-virtual-list, I probably have to configure either the main or svelte field of my package.json:
{
  "name": "@sveltejs/svelte-virtual-list",
  "version": "3.0.0",
  "description": "A <VirtualList> component for Svelte apps",
  "main": "VirtualList.svelte",
  "svelte": "VirtualList.svelte",
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -cw",
    "prepublishOnly": "npm test",
    "test": "node test/runner.js",
    "test:browser": "npm run build && serve test/public",
    "pretest": "npm run build",
    "lint": "eslint src/VirtualList.svelte"
  },
  "devDependencies": {
    "eslint": "^5.12.1",
    "eslint-plugin-svelte3": "git+https://github.com/sveltejs/eslint-plugin-svelte3.git",
    "port-authority": "^1.0.5",
    "puppeteer": "^1.9.0",
    "rollup": "^1.1.2",
    "rollup-plugin-commonjs": "^9.2.0",
    "rollup-plugin-node-resolve": "^4.0.0",
    "rollup-plugin-svelte": "^5.0.1",
    "sirv": "^0.2.2",
    "svelte": "^3.0.0-beta.2",
    "tap-diff": "^0.1.1",
    "tap-dot": "^2.0.0",
    "tape-modern": "^1.1.1"
  },
  "repository": "https://github.com/sveltejs/svelte-virtual-list",
  "author": "Rich Harris",
  "license": "LIL",
  "keywords": [
    "svelte"
  ],
  "files": [
    "src",
    "index.mjs",
    "index.js"
  ]
}

Is that a correct assumption? Additionally I am perplexed by the fact that in the package.json.files the VirtualList.svelte is not present? How would you go about publishing a svelte component??
EDIT: final gist correctly importing the Machine Svelte component

A: The svelte field is used by rollup-plugin-svelte and (if properly configured) svelte-loader to locate the source file, so that your third party components get compiled at the same time as the rest of your app (and import from the same internal library).
In a case like svelte-virtual-list, where you can't really use it programmatically from JavaScript (i.e. it has to be inside another component), there's really no point having a main field as well; that's something left over from a previous version I think.
But in some cases you do want non-Svelte-users to be able to use your component as a standalone class, and that's when main is useful, as long as it points to a precompiled JavaScript file. This could be generated with rollup-plugin-svelte during a prepublish script (though we could do a better job of generating some standard workflows around this). For maximum compatibility, a component — or package of components — intended to be used in this way should have a pkg.main (usually index.js which is a CommonJS or UMD file), and a pkg.module (usually index.mjs which is a JavaScript module).

Additionally I am perplexed by the fact that in the package.json.files the VirtualList.svelte is not present?

Regardless of what's in pkg.files, pkg.main will always be included. Since there's an erroneous pkg.main in svelte-virtual-list, the VirtualList.svelte file is included in the package even though I forgot to add it to pkg.files.


text:
Q: CORS Ajax POST variables empty in live server but work in local server After days (and a bit of spamming here and there), I did get CORS to work for my CodeIgniter applications. However, POST variables are empty in the PHP side in live server. the whole $_POST array is empty for some reason. Here is my ajax code:
 var postForm = {'e':'sammy'}; //data to process
$.ajax({
            type: "POST",
            url: "http://www.abc.ca/types/add",

            data: postForm,
            dataType : "json",

            cache: "false",
            contentType: "application/json",
            success: function (result) {

                //result here is blank
                alert(result);
            },
            fail: function (result){
            alert(result);
            }

        });

and the called php function (without the whole controller class):
        function add() {
     //Add new a biz type
      file_put_contents('trial.txt',implode(" | ",$_POST));
      echo $this->input->post('e');
        }

Am I missing something? the response from server are ok. but still the file created contains no data and echo prints empty. Any tips please? I have already tried method:'POST' instead of type:'POST'. Get variables pass away successfully.
Is this CI issue or Ajax because it is constant across ff,chrome and Opera

A: Try This Ajax :
 $.ajax({
        type: "POST",
        url: "http://www.abc.ca/types/add",
        data: postForm,
        cache: "false",
        success: function (result) {
            //result here is blank
            alert(result);
        },
        fail: function (result){
        alert(result);
        }
    });


text:
Q: JavaFX bulk edit images I'm trying to edit five images I have in a folder at once (using javafx motion blur), rather than select them one after the other. This is my code, I'm not exactly sure what I'm doing wrong but when I run it, only the last image in the folder gets edited. The others remain as they are.
public class IterateThrough extends Application {

    private Desktop desktop = Desktop.getDesktop();

@Override
public void start(Stage primaryStage) throws IOException {

    File dir = new File("filepath");
    File [] directoryListing = dir.listFiles();

    if (directoryListing != null) {

        for (File file : directoryListing) {
            if(file.getName().toLowerCase().endsWith(".jpeg")){

                //desktop.open(file);

                Image image = new Image(new FileInputStream(file));

                 //Setting the image view
                 ImageView imageView = new ImageView(image);

                 //setting the fit height and width of the image view
                 imageView.setFitHeight(600);
                 imageView.setFitWidth(500);

                 //Setting the preserve ratio of the image view
                 imageView.setPreserveRatio(true);

                 // instantiate Motion Blur class
                 MotionBlur motionBlur = new MotionBlur();

                 // set blur radius and blur angle
                 motionBlur.setRadius(15.0);
                 motionBlur.setAngle(110.0);

                 //set imageView effect
                 imageView.setEffect(motionBlur);

                 //Creating a Group object
                 Group root = new Group(imageView);

                 //Creating a scene object
                 Scene scene = new Scene(root, 600, 500);

                 //Setting title to the Stage
                 primaryStage.setTitle("Loading an image");

                 //Adding scene to the stage
                 primaryStage.setScene(scene);

                 //Displaying the contents of the stage
                 primaryStage.show();
            }
        }
     }
}

public static void main(String[] args) {
    launch(args);
}

}

A: first, you shouldn't just let the primaryStage show() in the for-each loop, because when the primaryStage first show(), the fx thread pause on that instruction, the remaining pictures will not be read and when you close the window, the loop won't continue to go on for remaining, it represents the end of the application.
so it's better to let the primaryStage show() outside the each-loop after all image has been read.
second, you shouldn't use the "Group" container to contains all images, better use VBox/HBox/FlowPane, make sure above image won't covers below's.
here's modified code for reference.
public class IterateThrough2 extends Application{
  private Desktop desktop = Desktop.getDesktop();
  @Override
  public void start(Stage primaryStage) throws IOException{
    File dir = new File("filepath");
    File[] directoryListing = dir.listFiles();

    FlowPane root = new FlowPane();

    if(directoryListing != null){
      for(File file : directoryListing){
        if(file.getName().toLowerCase().endsWith(".jpeg")){
          Image image = new Image(new FileInputStream(file));
          ImageView imageView = new ImageView(image);
          imageView.setFitHeight(600);
          imageView.setFitWidth(500);
          imageView.setPreserveRatio(true);
          MotionBlur motionBlur = new MotionBlur();
          motionBlur.setRadius(15.0);
          motionBlur.setAngle(110.0);
          imageView.setEffect(motionBlur);
          root.getChildren().add(imageView);
        }
      }
    }

    Scene scene = new Scene(root, 600, 500);
    primaryStage.setTitle("Loading an image");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

  public static void main(String[] args){
    launch(args);
  }
}


text:
Q: Magento: How to query (SQL) top selling products? Im seeking for a SQL query to directly get a list of our top selling products (ordered by quantity or by amount - doesn´t really matter). This seems to be more difficult than I thought...
Searching with google only finds solutions for PHP-modules and so on - but I want SQL.
I have picked up a small query from a different site and modified it a bit:
SELECT
SUM(order_items.qty_ordered) AS ordered_qty, order_items.name AS order_items_name, order_items.product_id AS entity_id,
e.entity_type_id, e.attribute_set_id, e.type_id, e.sku, e.has_options, e.required_options, e.created_at,
e.updated_at FROM sales_flat_order_item AS order_items
INNER JOIN sales_flat_order AS `order` ON `order`.entity_id = order_items.order_id AND `order`.state <> 'canceled'
LEFT JOIN catalog_product_entity AS e
ON
-- (e.type_id NOT IN ('grouped', 'configurable', 'bundle'))
-- AND
e.entity_id = order_items.product_id AND e.entity_type_id = 4
--AND state = "complete"

WHERE (parent_item_id IS NULL)

GROUP BY order_items.product_id
HAVING (SUM(order_items.qty_ordered) > 0)

ORDER BY ORDERED_QTY DESC

It more or less seems to give a reasonable output - but the numbers differ from the admin-start screen (where only the top 5 are displayed).
Has anybody done smth. similar to that already?

A: Have a solution (query) now
select
        year_ordered,
        product_type,
        sku,
        name,
        sum(qty_ordered) as qty,
        sum(row_total) as total
from (

SELECT
    YEAR(so.created_at) AS year_ordered,
    -- order_id,
    product_type, sku, name, qty_ordered, price, row_total

   FROM `sales_flat_order` AS so
   INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
        AND (so.state != "canceled" )
 ORDER BY so.created_at desc

) stat

group by stat.year_ordered, stat.product_type, stat.sku, stat.name
order by year_ordered desc, total desc

I´m using a subquery to be able to control that counting the products is correct.
 SELECT
        YEAR(so.created_at) AS year_ordered,
        -- order_id,
        product_type, sku, name, qty_ordered, price, row_total

   FROM `sales_flat_order` AS so
   INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
        AND (so.state != "canceled" )
 ORDER BY so.created_at desc

Result is a list of the ordered products per year. If you want to see a best seller list over all years a slight modification is sufficient (here ordered by total).
select
        product_type,
        sku,
        name,
        sum(qty_ordered) as qty,
        sum(row_total) as total
from (

SELECT
    YEAR(so.created_at) AS year_ordered,
    -- order_id,
    product_type, sku, name, qty_ordered, price, row_total

   FROM `sales_flat_order` AS so
   INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
        AND (so.state != "canceled" )
 ORDER BY so.created_at desc

) stat

group by stat.product_type, stat.sku, stat.name
order by total desc


text:
Q: TypeScript either or return type is not detecting properties type MyReturnType = Promise<boolean> | void

interface TestInterface {
    testFunction(): MyReturnType;
}

class TestClass implements TestInterface {
    testFunction() {
    }
}

const testObject = new TestClass();
testObject.testFunction()
    .then(() => { });

Why does it through the following error?
Property 'then' does not exist on type 'void'.

Am I missing something?

A: When you use the Union Type (denoted by the pipe character, '|'), you cannot assume the testFunction will return one type or another.
First you must check what type the testFunction returns after it has been called.
const result = testObject.testFunction()
if (result instanceof Promise) {
    result.then(() => {});
}


text:
Q: How would I write this in a MS Access query? Here's how I would write it in C.
if(x < 50 && x < 0.125y)
    {
    return 0;
    }
else if(x < 50 && x >= 0.125y)
    {
    if(z >= 2a)
        {
        return 50;
        }
    }
else return b;

Here's my attempt, it's just a bunch of nested ifs...
IIf(([Est_Order_Qty]<50) And ([Est_Order_Qty]<0.125*[Quantity On Hand]),"0",IIf(([Est_Order_Qty]<50) And ([Est_Order_Qty]>=0.125*[Quantity On Hand]),IIf([Est_Order_Qty]<2*[Qty],"50",[Rounded_To_50])))

A: IIF((x < 50) AND (x < 0.125 * y), 0,
    IIF((x < 50) AND (x >= 0.125 * y) AND (z >= 2 * a), 50,
       b)

or with your attempt
IIf(([Est_Order_Qty] < 50) And
    ([Est_Order_Qty] < 0.125 * [Quantity On Hand]), "0",
    IIf(([Est_Order_Qty] < 50) And
        ([Est_Order_Qty] >= 0.125 * [Quantity On Hand]),
        IIf([Est_Order_Qty] < 2 * [Qty], "50", [Rounded_To_50]),
        [Rounded_To_50])
)

A: Try Switch
SWITCH(
x < 50 AND x < 0.125y, 0,
x < 50 AND x >= 0.125y AND z >= 2a, 50,
TRUE, b)

A: If I understood your if statement correctly, then my answer came out to:
    iif(x < 50 And x > 0.125y, "0", iif(x < 50 And x >= 0.125y, iif(2 >= 2a, 50, ""), b))

I believe this is it. Let me know.


text:
Q: I am using django for a project and i got this error I am doing a project in Django and i got this error.How is this occurs?
NoReverseMatch at /
Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']
urls.py
from django.urls import path
from accounts import views
urlpatterns = [
path('',views.home, name="home"),
path('product/',views.products, name="product"),
path('customer/<str:pkid>/',views.customer, name="customer"),

path('create_order/<str:pk>/',views.createOrder, name="create_order"),
path('update_order/<str:pk>/',views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/',views.deleteOrder, name="delete_order"),

]
views.py
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
    form = OrderForm(request.POST)
    if form.is_valid:
        form.save()
        return redirect('/')
context =  {'form':form}
return render(request, 'accounts/order_form.html', context)

order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<form action="" method="POST">

    {% csrf_token %}

    {{ form }}

    <input type="submit" name="Submit">
</form>

{% endblock %}
customer.html`
{% extends 'accounts/main.html' %}

{% block content %}

Customer:{{customer.name}}

            Update Customer
            Place Order

Contact Information

Email: {{customer.email}}

Phone: {{customer.phone}}

Total Orders

{{total_orders}}

            <form method="get">

                <button class="btn btn-primary" type="submit">Search</button>
            </form>

                    Product
                    Category
                    Date Ordered
                    Status
                    Update
                    Remove

                {% for order in orders %}

                    {{order.product.name}}
                    {{order.product.category}}
                    {{order.date_created}}
                    {{order.status}}
                    Update
                    Remove

                {% endfor %}

{% endblock %}

A: The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
In your HTML write action=" {%url 'create_order' order.id%}"


text:
Q: jCIFS can't seem to authenticate I was starting to benchmark how much performance we'd lose by using jCIFS instead of requiring our users to map drives manually themselves, but then I found that I couldn't even pass the first basic test of reading data from a file using jCIFS.
I boiled down my issue to a test problem:
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.google.common.io.ByteStreams;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;

public class TestCifs
{
    public static void main(String[] args) throws Exception
    {
        OutputStream output = ByteStreams.nullOutputStream();

        String domain = ""; // have tried the actual name too
        String user = "<your_user_here>";
        String pass = "<your_pass_here>";

        String relativePath = "path/to/100MiB";

        // Read via UNC path (Windows doing the SMB work.)
        Path uncFile = Paths.get("\\\\192.168.1.66\\Shared", relativePath);
        Files.copy(uncFile, output);

        // Read via jCIFS
        //TODO: Figure out if this is a real URL in which case we'd have to escape stuff.
        SmbFile smbFile = new SmbFile("smb://192.168.1.66/Shared/" + relativePath,
                                      new NtlmPasswordAuthentication(domain, user, pass));
        ByteStreams.copy(smbFile.getInputStream(), output);
    }
}

If I run this, it runs past the direct copy and then the jCIFS copy fails with:
Exception in thread "main" jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
    at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:546)
    at jcifs.smb.SmbTransport.send(SmbTransport.java:663)
    at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:390)
    at jcifs.smb.SmbSession.send(SmbSession.java:218)
    at jcifs.smb.SmbTree.treeConnect(SmbTree.java:176)
    at jcifs.smb.SmbFile.doConnect(SmbFile.java:911)
    at jcifs.smb.SmbFile.connect(SmbFile.java:954)
    at jcifs.smb.SmbFile.connect0(SmbFile.java:880)
    at jcifs.smb.SmbFile.open0(SmbFile.java:972)
    at jcifs.smb.SmbFile.open(SmbFile.java:1006)
    at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:73)
    at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:65)
    at jcifs.smb.SmbFile.getInputStream(SmbFile.java:2844)
    at TestCifs.main(TestCifs.java:33)

The username and password I provided in user/pass are the same ones I used when authenticating with the server to mount its directory via Windows. I also tried using the name of the server as the domain to no effect. I'm really at a loss with this one and am about to look at something like Wireshark to figure out what is actually going wrong but maybe I'm doing something obviously wrong and someone here can point that out.
This is probably the relevant bit from jCIFS' own diagnostics for the failed login:
treeConnect: unc=\\192.168.1.66\SHARED,service=?????
sessionSetup: accountName=TESTER,primaryDomain=
NtlmContext[auth=TESTER,ntlmsspFlags=0x20080004,workstation=JCIFS1_183_42,isEstablished=false,state=1,serverChallenge=null,signingKey=null]
Type1Message[suppliedDomain=,suppliedWorkstation=JCIFS1_183_42,flags=0x20080205]
00000: 4E 54 4C 4D 53 53 50 00 01 00 00 00 05 22 08 20  |NTLMSSP......". |
00010: 00 00 00 00 00 00 00 00 0D 00 0D 00 20 00 00 00  |............ ...|
00020: 4A 43 49 46 53 31 5F 31 38 33 5F 34 32           |JCIFS1_183_42   |

SmbComSessionSetupAndX[command=SMB_COM_SESSION_SETUP_ANDX,received=false,errorCode=0,flags=0x0018,flags2=0xC803,signSeq=0,tid=0,pid=21886,uid=0,mid=2,wordCount=12,byteCount=77,andxCommand=0xFF,andxOffset=0,snd_buf_size=16644,maxMpxCount=10,VC_NUMBER=1,sessionKey=0,lmHash.length=0,ntHash.length=0,capabilities=-2147483564,accountName=null,primaryDomain=null,NATIVE_OS=Windows 8,NATIVE_LANMAN=jCIFS]
00000: FF 53 4D 42 73 00 00 00 00 18 03 C8 00 00 00 00  |ÿSMBs......È....|
00010: 00 00 00 00 00 00 00 00 00 00 7E 55 00 00 02 00  |..........~U....|
00020: 0C FF 00 DE DE 04 41 0A 00 01 00 00 00 00 00 2D  |.ÿ.ÞÞ.A........-|
00030: 00 00 00 00 00 54 00 00 80 4D 00 4E 54 4C 4D 53  |.....T...M.NTLMS|
00040: 53 50 00 01 00 00 00 05 22 08 20 00 00 00 00 00  |SP......". .....|
00050: 00 00 00 0D 00 0D 00 20 00 00 00 4A 43 49 46 53  |....... ...JCIFS|
00060: 31 5F 31 38 33 5F 34 32 57 00 69 00 6E 00 64 00  |1_183_42W.i.n.d.|
00070: 6F 00 77 00 73 00 20 00 38 00 00 00 6A 00 43 00  |o.w.s. .8...j.C.|
00080: 49 00 46 00 53 00 00 00                          |I.F.S...        |

New data read: Transport1[0.0.0.0<00>/192.168.1.66:445]
00000: FF 53 4D 42 73 6D 00 00 C0 80 41 C8 00 00 00 00  |ÿSMBsm..À.AÈ....|
00010: 00 00 00 00 00 00 00 00 00 00 7E 55 00 00 02 00  |..........~U....|

SmbComSessionSetupAndXResponse[command=SMB_COM_SESSION_SETUP_ANDX,received=false,errorCode=Logon failure: unknown user name or bad password.,flags=0x0080,flags2=0xC841,signSeq=0,tid=0,pid=21886,uid=0,mid=2,wordCount=0,byteCount=0,andxCommand=0xFF,andxOffset=0,isLoggedInAsGuest=false,nativeOs=,nativeLanMan=,primaryDomain=]
00000: FF 53 4D 42 73 6D 00 00 C0 80 41 C8 00 00 00 00  |ÿSMBsm..À.AÈ....|
00010: 00 00 00 00 00 00 00 00 00 00 7E 55 00 00 02 00  |..........~U....|
00020: 00 00 00                                         |...             |

It seems like it isn't putting the username into the message at all, so maybe I'm looking at a bug, but if it's really doing this, surely it would have been noticed by someone else before...
Workarounds already attempted:

*

*Putting authentication info into the URL instead of the auth object.

*Calling SmbSession.logon before trying to access the SmbFile. In this situation, you just get the error from logon instead.

*Setting a default authenticator using NtlmAuthenticator.setDefault(). In this situation, you see it call the authenticator to get the auth details but then seemingly throw away the info and make the request with no username.

A: I fought with this for over an hour but was finally able to get it working using the full URL string as opposed to the NtlmPasswordAuthentication object. I can't say why this is the case, but potentially it's doing some weird stuff to the username and/or password before passing it into the connection string.
In case anyone needs it, here is the URL format I used, which included the domain:
smb://domain;username:password@server/share/path


text:
Q: Javascript: pass variable to arrow function instead of setting harcoded value How to replace value 1 by the variable x when setting an onclick function to a td like below:
var sounds = [1, 3, 8, 12];
var x = 123;
mytd.onclick = () => play(sounds[1].toString());

A: Perhaps you want "currying"?
var sounds = [1, 3, 8, 12];
const playSound = (snd) => () => play(sounds[snd].toString());

var x = 123;
mytd.onclick = playSound(x)


text:
Q: How do I pass plain text as my request body using NestJS? One of the controller methods in my NestJS application is supposed to take plain text as its body but whenever I try to make a request, the parameter is received as an empty object. Is this even possible or am I going to have to create some sort of DTO to pass that single string?
Example:
@Post()
  myFunction(@Body() id: string) {
    // do something here
  }

A: I see that this question is pretty old, but it is listed in google among first, so I want to add answer here.
If you don't want to add body-parser middleware (for example, you want plain text only in single controller method), you can use raw-body (which is already exists in your node_modules), something like this:
import * as rawbody from 'raw-body';
import { Controller, Post, Body, Req } from '@nestjs/common';

@Controller('/')
export class IndexController {

  @Post()
  async index(@Body() data, @Req() req) {

    // we have to check req.readable because of raw-body issue #57
    // https://github.com/stream-utils/raw-body/issues/57
    if (req.readable) {
      // body is ignored by NestJS -> get raw body from request
      const raw = await rawbody(req);
      const text = raw.toString().trim();
      console.log('body:', text);

    } else {
      // body is parsed by NestJS
      console.log('data:', data);
    }

    // ...
  }

}

you could also create new parameter decorator
import * as rawbody from 'raw-body';
import { createParamDecorator, HttpException, HttpStatus } from '@nestjs/common';

export const PlainBody = createParamDecorator(async (data, req) => {
  if (req.readable) {
    return (await rawbody(req)).toString().trim();
  }
  throw new HttpException('Body aint text/plain', HttpStatus.INTERNAL_SERVER_ERROR);
});

and use it like
@Post()
async index(@PlainBody() text: string) {
  // ...

(I didn't check decorator code, wrote it right here in comment)

A: Adding on @yumaa's post above
Here's the working decorator with NestJS v7.0.8:
import { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common';
import * as rawBody from "raw-body";

export const PlainBody = createParamDecorator(async (_, context: ExecutionContext) => {
    const req = context.switchToHttp().getRequest<import("express").Request>();
    if (!req.readable) { throw new BadRequestException("Invalid body"); }

    const body = (await rawBody(req)).toString("utf8").trim();
    return body;
})

A: The semantics of a post request are determined by the header that indicates the content type.  Try making sure the request header has the type 'text/plain' and see of this helps.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

A: Nest is not compatible with plain/text and you must pass a bodyparser to your express app instead.  Try something like this:
import * as bodyParser from 'body-parser';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(bodyparser({ ...options })) // for plain/text bodies
  await app.listen(3000)
}
bootstrap();

where options is created from https://www.npmjs.com/package/body-parser

A: Old question but none of the above worked for me but the following did:
The above decorator or controller-method approaches did not work for me as the request body buffer had always already been read.
I was able to get it working using the following middleware. (Note in my case I needed to validate a Xero webhook so the example is geared towards that)
cache-raw-body-on-request.ts:
import { json } from 'body-parser';
import * as cloneBuffer from 'clone-buffer';

export const cachedRawBodyRequestKey = 'rawBodyBuffer';

/**
 * Clones the request buffer and stores it on the request object for reading later
 */
export const cacheRawBodyOnRequest = json({
  verify: (req: any, res, buf, encoding) => {

    // only clone the buffer if we're receiving a Xero webhook request
    if (req.headers['x-xero-signature'] && Buffer.isBuffer(buf)) {
      req[cachedRawBodyRequestKey] = cloneBuffer(buf);
    }
    return true;
  },
});

main.ts:
app.use(cacheRawBodyOnRequest);

controller:
const textBody = req[cachedRawBodyRequestKey].toString('utf-8');

A: This is my take on getting the raw(text)body in NestJS's hander:

*

*configure the app with preserveRawBodyInRequest as shown in JSDoc example

*use RawBody decorator in handler to retrieve the raw(text)body

raw-request.decorator.ts:
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { NestExpressApplication } from "@nestjs/platform-express";

import { json, urlencoded } from "express";
import type { Request } from "express";
import type http from "http";

export const HTTP_REQUEST_RAW_BODY = "rawBody";

/**
 * make sure you configure the nest app with preserveRawBodyInRequest
 * @example
 * webhook(@RawBody() rawBody: string): Record<string, unknown> {
 *   return { received: true };
 * }
 * @see preserveRawBodyInRequest
 */
export const RawBody = createParamDecorator(
  async (data: unknown, context: ExecutionContext) => {
    const request = context
      .switchToHttp()
      .getRequest<Request>()
    ;

    if (!(HTTP_REQUEST_RAW_BODY in request)) {
      throw new Error(
        `RawBody not preserved for request in handler: ${context.getClass().name}::${context.getHandler().name}`,
      );
    }

    const rawBody = request[HTTP_REQUEST_RAW_BODY];

    return rawBody;
  },
);

/**
 * @example
 * const app = await NestFactory.create<NestExpressApplication>(
 *   AppModule,
 *   {
 *     bodyParser: false, // it is prerequisite to disable nest's default body parser
 *   },
 * );
 * preserveRawBodyInRequest(
 *   app,
 *   "signature-header",
 * );
 * @param app
 * @param ifRequestContainsHeader
 */
export function preserveRawBodyInRequest(
  app: NestExpressApplication,
  ...ifRequestContainsHeader: string[]
): void {
  const rawBodyBuffer = (
    req: http.IncomingMessage,
    res: http.ServerResponse,
    buf: Buffer,
  ): void => {
    if (
      buf?.length
      && (ifRequestContainsHeader.length === 0
        || ifRequestContainsHeader.some(filterHeader => req.headers[filterHeader])
      )
    ) {
      req[HTTP_REQUEST_RAW_BODY] = buf.toString("utf8");
    }
  };

  app.use(
    urlencoded(
      {
        verify: rawBodyBuffer,
        extended: true,
      },
    ),
  );
  app.use(
    json(
      {
        verify: rawBodyBuffer,
      },
    ),
  );
}

A: If you'd prefer to avoid extra 3rd party dependencies, you could also get use of the built-in nodejs approach here:
function readPost(req: IncomingMessage) {
  return new Promise<string>((resolve, reject) => {
    let body = '';
    req.on('data', (data: string) => (body += data));
    req.on('error', (error: unknown) => reject(error));
    req.on('end', () => resolve(body));
  });
}

Usage:
import { Post, Req } from '@nestjs/common';
import { IncomingMessage } from 'http';
...
@Post()
myFunction(@Req() req: IncomingMessage) {
  const bodyStr = await readPost(req);
  console.log('request body:', bodyStr);
}


text:
Q: Multi-dimensional data clustering I am a data-mining newbie and need some help with a high dimensional data-set (subset is shown below). It actually has 30 dimensions and several thousand rows.
The task is to see how they are clustered and if any similarity metrics can be calculated from this data. I have looked at SOMs and Cosine similarity approaches, however unsure how to approach this problem.
p.s. I am not versed at all with R or similar stats packages, would appreciate some pointers in C#/.NET based libraries.
"ROW"   "CPG"   "FSD"   "FR"    "CV"    "BI22"  "MI99"  "ME"    "HC"    "L1"    "L2"    "TL"
1   298 840 3.80    5.16    169.17  69  25.0    0.82    125 453 792
2   863 676 4.09    4.28    97.22   63  18.5    0.85    172 448 571
3   915 942 7.04    5.33    33.01   72  35.1    0.86    134 450 574

A: I think what you are looking for is known as a multidimensional scaling plot (MDS), its pretty straightforward to do, but you will need a library that can do some linear algebra/optimization stuff.
Step one is to calculate a distance matrix, this is a matrix of pairwise Euclidean distance between all of the data points.
Step two is to find N vectors or features (usually 2 for a 2d plot) which form the closest distance matrix to the one calculated in step 1. This is equivalent to getting the eigenvectors with the N largest eigenvalues from the square distance matrix. You may be able to find some linear algebra libraries that can do this in your language of choice. I have always used the R function cmdscale()for this though:
 http://stat.ethz.ch/R-manual/R-patched/library/stats/html/cmdscale.html


text:
Q: How to rotate original image without resizing(not expand width or height) the image I have rotate the image using UIRotationGestureRecognizer and it's working fine. But the image width & height increased.
Original Image Size: x = 85.000000, y = 83.000000, width = 150.000000, height = 150.000000
After rotating image size : x = 54.476551, y = 52.476551, width = 211.046906, height = 211.046906
How to handle this problem? I am trying like this:
recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
recognizer.rotation = 0;

A: CGAffineTransform transform = self.view.transform;
            if (UIDeviceOrientationLandscapeLeft == deviceOrientation) {
                transform = CGAffineTransformRotate(transform, -(M_PI / 2.0));
            } else {
                transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            }
            self.view.transform = transform;

I hope it helps


text:
Q: How to mask password exist in json string? I am working on .net core c# logging project for my API response.
The output is JSON format with the response contains sensitive info (eg. password)
I am stuck when the response output contains more complex Json structure with an array, whose items are complex objects, each with an "id" property and the keyword denoting the sensitive field, appears as value of that "id" field (see example below).
For the below output, How do I to replace the password value to 'XXXX' using RegEx if the  value of the "id" contains the word 'password' . eg...there are value required to be masked below...

{
    "type": "CatalogResourceRequest",
    "description": null,
    "reasons": null,
    "data": {
        "customProperties": [
            {

                "data": {
                    "id": "CloneFrom",
                    "is_hidden": false,
                    "value": "TMPLABC"
                }
            },
            {

                "data": {
                    "id": "Debug",
                    "is_hidden": false,
                    "value": false
                }
            },
            {
                "data": {
                    "id": "abc_password",
                    "is_hidden": false,
                    "value": "This_Is_Password_To_Be_Masked"
            },

                "data": {
                    "id": "password_of_user1",
                    "is_hidden": false,
                    "value": "This_Is_Password_To_Be_Masked_Also"
                        }
        }
    ]
    }
}

A: Here is a working demo by using Json.Net:
[HttpGet]
public IActionResult Index()
{
    var data = System.IO.File.ReadAllText("test.json");
    var json = ToObject(data);

    return Ok(json);
}
public object ToObject(string json)
{
    if (string.IsNullOrEmpty(json))
        return null;
    return ToObject(JToken.Parse(json));
}

public object ToObject(JToken token)
{
    switch (token.Type)
    {
        case JTokenType.Object:
            return token.Children<JProperty>()
                        .ToDictionary(prop => prop.Name,
                                        prop => ToObject(prop.Value),
                                        StringComparer.OrdinalIgnoreCase);
        case JTokenType.Array:
            return token.Select(ToObject).ToList();
        case JTokenType.Null:
            return null;
        default:
            if(((JValue)token).Value.ToString().Contains("password"))
            {
                ViewBag.Id = true;
                return ((JValue)token).Value;
            }
            if(((JProperty)token.Parent).Name== "value" && ViewBag.Id!=null)
            {
                if(ViewBag.Id)
                {
                    ViewBag.Id = false;
                    return "XXXXX";
                }
                return ((JValue)token).Value;
            }
            return ((JValue)token).Value;
    }
}

BTW,your provided json is not correct,it should be like below:
{
  "type": "CatalogResourceRequest",
  "description": null,
  "reasons": null,
  "data": {
    "customProperties": [
      {

        "data": {
          "id": "CloneFrom",
          "is_hidden": false,
          "value": "TMPLABC"
        }
      },
      {

        "data": {
          "id": "Debug",
          "is_hidden": false,
          "value": false
        }
      },
      {
        "data": {
          "id": "abc_password",
          "is_hidden": false,
          "value": "This_Is_Password_To_Be_Masked"
        }
      },
      {
        "data": {
          "id": "password_of_user1",
          "is_hidden": false,
          "value": "This_Is_Password_To_Be_Masked_Also"
        }
      }
    ]
  }
}


text:
Q: How to get rid of rEFInd? I wanted to try to install Ubuntu, but since I didn't have an available USB I searched how to do it without USB or CD in  this post.
I have a UEFI device so decided to follow through, After making the partition and all that I encountered I couldn't change the partition size, so I decided to copy the content from that one into an unused partition that had 8 GB of memory. Well I had to reboot and I encountered the issue.
rEFInd appears as my boot and I have no OS to choose from, ended up having to use a USB device to solve the issue by booting into Windows installation program and using the repair system option.
Now I wanted to get rid of rEFInd, but I don't know how to do it, and I'm also scared of removing that S: partition because the boot is located there. I figured out I could use this command:"bcdedit /set '{bootmgr}' path \Windows\Boot\EFI\bootmgr.efi", but it gives me an error saying:

element's data type not recognised or it doesn't apply to the specified entry

Execute "bcdedit /?" to obtain help  with the command line :

Element not found
  (I manually translated this so maybe some words aren't the usual ones in English)

So if anyone knows how to do this I'd be very grateful. It isn't a matter of life or death, since I can finally boot to Windows with no issue, but I'd like to get rid of this.

A: There are a couple of posts on our site which could help here.
The post
Reconstructing Windows EFI files in /boot partition
has this answer
which lets you assign the EFI partition a drive letter and restore the Windows boot
environment.
If this is not enough, you could now access the EFI partition via this drive letter
and delete rEFInd as described in
this answer.