问:
Android studio 3.0 shows Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
I am using android studio 3.0 on that when i run App it crashes when i run it on the real device once i click buttonGo . in the code it shows me in yellow line Response.body.toString is reduntant and App crashes and Logcat is indicating me to refer the line when it shows it is reduntant . My logcat is below

```<code> Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                             at com.clone.uber.uberclone.Welcome$4.onResponse(Welcome.java:240)
                                                                             at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                                                                             at android.os.Handler.handleCallback(Handler.java:739)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:135)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5912)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                             at com.android.internal.os.ZygoteInit.main
</code>```

My Java code

```    package com.clone.uber.uberclone;

import android.*;
import android.Manifest;
import android.animation.ValueAnimator;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.clone.uber.uberclone.Common.Common;
import com.clone.uber.uberclone.Remote.IGoogleAPI;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.JointType;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.model.SquareCap;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Welcome extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener
{

    private GoogleMap mMap;

    //play services
    private static final int MY_PERMISSION_REQUEST_CODE= 7000;
    private static final int PLAY_SERVICE_RES_REQUEST=7001;

    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;

    private static int UPDATE_INTERVAL= 5000;
    private static int FASTEST_INTERVAL=3000;
    private static int DISPLACEMENT= 10;

    DatabaseReference drivers;
    GeoFire geoFire;
    Marker mCurrent;
    MaterialAnimatedSwitch location_switch;
    SupportMapFragment mapFragment;

    //car animation

    private List<LatLng> polyLineList;
    private Marker carMarker;
    private float v;
    private double lat,lng;
    private Handler handler;
    private LatLng startPosition,endPosition,currentPosition;
    private int index,next;
    private Button btnGo;
    private EditText edtPlace;
    private String destination;
    private PolylineOptions polylineOptions, blackPolylineOptions;
    private Polyline blackPolyline,greyPolyline;
    private IGoogleAPI mService;

    Runnable drawPathRunnable = new Runnable() {
        @Override
        public void run() {
            if (index<polyLineList.size()-1)
            {
                index++;
                next= index+1;
            }
            if (index<polyLineList.size()-1)
            {
                startPosition = polyLineList.get(index);
                endPosition= polyLineList.get(next);
            }

            ValueAnimator valueAnimator= ValueAnimator.ofFloat(0,1);
            valueAnimator.setDuration(3000);
            valueAnimator.setInterpolator(new LinearInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    v =valueAnimator.getAnimatedFraction();
                    lng = v*endPosition.longitude+(1-v)*startPosition.longitude;
                    lat = v*endPosition.latitude+(1-v)*startPosition.latitude;
                    LatLng newPos= new LatLng(lat,lng);
                    carMarker.setPosition(newPos);
                    carMarker.setAnchor(0.5f,0.5f);
                    carMarker.setRotation(getBearing(startPosition,newPos));
                    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(
                            new CameraPosition.Builder()
                            .target(newPos)
                            .zoom(15.5f)
                            .build()
                    ));
                }
            });
            valueAnimator.start();
            handler.postDelayed(this,3000);
        }
    };

    private float getBearing(LatLng startPosition, LatLng endPosition) {
        double lat = Math.abs(startPosition.latitude - endPosition.latitude);
        double lng = Math.abs(startPosition.longitude - endPosition.longitude);

        if (startPosition.latitude < endPosition.latitude && startPosition.longitude < endPosition.longitude)
            return (float) (Math.toDegrees(Math.atan(lng/lat)));
        else  if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude)
            return (float) ((90-Math.toDegrees(Math.atan(lng/lat)))+90);
        else  if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
            return (float) (Math.toDegrees(Math.atan(lng/lat))+180);
        else  if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude)
            return (float) ((90-Math.toDegrees(Math.atan(lng/lat)))+270);
        return -1;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
         mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //init view
        location_switch =(MaterialAnimatedSwitch)findViewById(R.id.location_switch);
        location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(boolean isOnline) {
                if (isOnline)
                {
                    startLocationUpdates();
                    displayLocation();
                    Snackbar.make(mapFragment.getView(),"you are Online",Snackbar.LENGTH_SHORT).show();
                }
                else
                {
                    stopLocationUpdates();
                    mCurrent.remove();
                    mMap.clear();
                    handler.removeCallbacks(drawPathRunnable);
                    Snackbar.make(mapFragment.getView(),"you are Offline",Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        polyLineList =new ArrayList<>();
        btnGo=(Button)findViewById(R.id.btnGo);
        edtPlace=(EditText)findViewById(R.id.edtPlace);

        btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                destination= edtPlace.getText().toString();
                destination = destination.replace(" ","+"); //replsce space with + for fetch data
                Log.d("WAHDAT",destination);

                getDirection();
            }
        });
        //geo fire
        drivers = FirebaseDatabase.getInstance().getReference("Drivers");
        geoFire=new GeoFire(drivers);
        setUpLocation();
        mService= Common.getGoogleAPI();
    }

    private void getDirection() {
        currentPosition=new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
        String requestApi =null;
        try{

            requestApi="https://maps.googleapis.com/maps/api/direction/json?"+
                    "mode=driving&"+
                    "transit_routing_preference=less_driving&"+
                    "origin="+currentPosition.latitude+","+currentPosition.longitude+"&"+
                    "destination="+destination+"&"+
                    "key="+getResources().getString(R.string.google_direction_api);

            Log.d("WAHDAT",requestApi); //print url for debug
            mService.getPath(requestApi)
                    .enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            try {
                                JSONObject jsonObject=new JSONObject(response.body().toString());
                                JSONArray jsonArray=jsonObject.getJSONArray("routes");
                                for (int i=0;i<jsonArray.length();i++)
                                {
                                    JSONObject route=jsonArray.getJSONObject(i);
                                    JSONObject poly =route.getJSONObject("overview_polyline");
                                    String polyline=poly.getString("points");
                                    polyLineList=decodePoly(polyline);

                                }
                                //adjusting bounds
                                LatLngBounds.Builder builder=new LatLngBounds.Builder();
                                for (LatLng latLng:polyLineList)
                                    builder.include(latLng);
                                LatLngBounds bounds=builder.build();
                                CameraUpdate mCameraUpdate =CameraUpdateFactory.newLatLngBounds(bounds,2);
                                mMap.animateCamera(mCameraUpdate);

                                polylineOptions = new PolylineOptions();
                                polylineOptions.color(Color.GRAY);
                                polylineOptions.width(5);
                                polylineOptions.startCap(new SquareCap());
                                polylineOptions.endCap(new SquareCap());
                                polylineOptions.jointType(JointType.ROUND);
                                polylineOptions.addAll(polyLineList);
                                greyPolyline = mMap.addPolyline(polylineOptions);

                                blackPolylineOptions = new PolylineOptions();
                                blackPolylineOptions.color(Color.GRAY);
                                blackPolylineOptions.width(5);
                                blackPolylineOptions.startCap(new SquareCap());
                                blackPolylineOptions.endCap(new SquareCap());
                                blackPolylineOptions.jointType(JointType.ROUND);
                                blackPolyline = mMap.addPolyline(blackPolylineOptions);

                                mMap.addMarker(new MarkerOptions().position(polyLineList.get(polyLineList.size()-1))
                                .title("PickUp location"));

                                //Animation
                                ValueAnimator polyLineAnimator =ValueAnimator.ofInt(0,100);
                                polyLineAnimator.setDuration(2000);
                                polyLineAnimator.setInterpolator(new LinearInterpolator());
                                polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                    @Override
                                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                        List<LatLng> points = greyPolyline.getPoints();
                                        int percentValue=(int)valueAnimator.getAnimatedValue();
                                        int size=points.size();
                                        int newPoints = (int)(size * (percentValue/100.0f));
                                        List<LatLng> p=points.subList(0,newPoints);
                                        blackPolyline.setPoints(p);
                                    }
                                });
                                polyLineAnimator.start();

                                carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
                                .flat(true)
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));

                                handler = new Handler();
                                index=-1;
                                next=1;
                                handler.postDelayed(drawPathRunnable,3000);

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

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                      Toast.makeText(Welcome.this,""+t.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    });

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

    }

    private List decodePoly(String encoded) {

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

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

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

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

        return poly;
    }

    //we request runtime permission, we need override onrequestpermissionresult method

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode)
        {
            case MY_PERMISSION_REQUEST_CODE:
                if (grantResults.length >0 && grantResults[0] ==PackageManager.PERMISSION_GRANTED)
                {
                    if (checkPlayServices())
                    {
                        buildGoogleApiClient();
                        createLocationRequest();
                        if (location_switch.isChecked())
                            displayLocation();
                    }
                }
        }
    }

    private void setUpLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
          //request runtime permission
            ActivityCompat.requestPermissions(this,new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
                    },MY_PERMISSION_REQUEST_CODE);
        }
        else
        {
            if (checkPlayServices())
            {
                buildGoogleApiClient();
                createLocationRequest();
                if (location_switch.isChecked())
                    displayLocation();
            }
        }
    }

    private void createLocationRequest() {
        mLocationRequest =new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);

    }

    private void buildGoogleApiClient() {
        mGoogleApiClient =new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICE_RES_REQUEST).show();
            else {
                Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
                finish();
            }
            return false;
        }
        return true;
    }

    private void stopLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
    }

    private void displayLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        mLastLocation= LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation !=null)
        {
            if (location_switch.isChecked())
            {
                final double latitude= mLastLocation.getLatitude();
                final double longitude=mLastLocation.getLongitude();
                //update to firebase
                geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
                    @Override
                    public void onComplete(String key, DatabaseError error) {
                        //add marker
                        if (mCurrent !=null)
                           mCurrent.remove();//remove marker already

                       mCurrent = mMap.addMarker(new MarkerOptions()

                                                    .position(new LatLng(latitude,longitude))
                                                               .title("Your Location"));
//
//                        //move camera to this position
                        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));

//

                    }
                });
            }
        }
        else
        {
            Log.d("ERROR","Cannot get your Location");

        }
    }

    private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
        final Handler handler=new Handler();
        final long start= SystemClock.uptimeMillis();
        final float startRotation = mCurrent.getRotation();
        final long duration = 1500;
        final Interpolator interpolator=new LinearInterpolator();

        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed=SystemClock.uptimeMillis() - start;
                float t= interpolator.getInterpolation((float)elapsed/duration);
                float rot= t*i+(1-t)*startRotation;
                mCurrent.setRotation(-rot >180?rot/2:rot);
                if (t<1.0)
                {
                    handler.postDelayed(this,16);
                }
            }
        });
    }

    private void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setTrafficEnabled(false);
        mMap.setIndoorEnabled(false);
        mMap.setBuildingsEnabled(false);
        mMap.getUiSettings().setZoomControlsEnabled(true);

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
    mLastLocation= location;
    displayLocation();
    }
}
```

答:
Retrofit response.body() can be null if there was an HTTP error.
Perform null check before accessing to it.
Also check response.errorBody()

If your response type is Response, then response.body return type will be String. That makes toString() redundant.

if(response.body() != null) {
    ... your code...
} else {
    ...your error handling code...
}

Body:
I am using android studio 3.0 on that when i run App it crashes when i run it on the real device once i click buttonGo . in the code it shows me in yellow line Response.body.toString is reduntant and App crashes and Logcat is indicating me to refer the line when it shows it is reduntant . My logcat is below

 Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                             at com.clone.uber.uberclone.Welcome$4.onResponse(Welcome.java:240)
                                                                             at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                                                                             at android.os.Handler.handleCallback(Handler.java:739)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:135)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5912)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                             at com.android.internal.os.ZygoteInit.main

My Java code

    package com.clone.uber.uberclone;

import android.*;
import android.Manifest;
import android.animation.ValueAnimator;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.clone.uber.uberclone.Common.Common;
import com.clone.uber.uberclone.Remote.IGoogleAPI;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.JointType;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.model.SquareCap;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Welcome extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener
{

    private GoogleMap mMap;

    //play services
    private static final int MY_PERMISSION_REQUEST_CODE= 7000;
    private static final int PLAY_SERVICE_RES_REQUEST=7001;

    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;

    private static int UPDATE_INTERVAL= 5000;
    private static int FASTEST_INTERVAL=3000;
    private static int DISPLACEMENT= 10;

    DatabaseReference drivers;
    GeoFire geoFire;
    Marker mCurrent;
    MaterialAnimatedSwitch location_switch;
    SupportMapFragment mapFragment;

    //car animation

    private List<LatLng> polyLineList;
    private Marker carMarker;
    private float v;
    private double lat,lng;
    private Handler handler;
    private LatLng startPosition,endPosition,currentPosition;
    private int index,next;
    private Button btnGo;
    private EditText edtPlace;
    private String destination;
    private PolylineOptions polylineOptions, blackPolylineOptions;
    private Polyline blackPolyline,greyPolyline;
    private IGoogleAPI mService;

    Runnable drawPathRunnable = new Runnable() {
        @Override
        public void run() {
            if (index<polyLineList.size()-1)
            {
                index++;
                next= index+1;
            }
            if (index<polyLineList.size()-1)
            {
                startPosition = polyLineList.get(index);
                endPosition= polyLineList.get(next);
            }

            ValueAnimator valueAnimator= ValueAnimator.ofFloat(0,1);
            valueAnimator.setDuration(3000);
            valueAnimator.setInterpolator(new LinearInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    v =valueAnimator.getAnimatedFraction();
                    lng = v*endPosition.longitude+(1-v)*startPosition.longitude;
                    lat = v*endPosition.latitude+(1-v)*startPosition.latitude;
                    LatLng newPos= new LatLng(lat,lng);
                    carMarker.setPosition(newPos);
                    carMarker.setAnchor(0.5f,0.5f);
                    carMarker.setRotation(getBearing(startPosition,newPos));
                    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(
                            new CameraPosition.Builder()
                            .target(newPos)
                            .zoom(15.5f)
                            .build()
                    ));
                }
            });
            valueAnimator.start();
            handler.postDelayed(this,3000);
        }
    };

    private float getBearing(LatLng startPosition, LatLng endPosition) {
        double lat = Math.abs(startPosition.latitude - endPosition.latitude);
        double lng = Math.abs(startPosition.longitude - endPosition.longitude);

        if (startPosition.latitude < endPosition.latitude && startPosition.longitude < endPosition.longitude)
            return (float) (Math.toDegrees(Math.atan(lng/lat)));
        else  if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude)
            return (float) ((90-Math.toDegrees(Math.atan(lng/lat)))+90);
        else  if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
            return (float) (Math.toDegrees(Math.atan(lng/lat))+180);
        else  if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude)
            return (float) ((90-Math.toDegrees(Math.atan(lng/lat)))+270);
        return -1;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
         mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //init view
        location_switch =(MaterialAnimatedSwitch)findViewById(R.id.location_switch);
        location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(boolean isOnline) {
                if (isOnline)
                {
                    startLocationUpdates();
                    displayLocation();
                    Snackbar.make(mapFragment.getView(),"you are Online",Snackbar.LENGTH_SHORT).show();
                }
                else
                {
                    stopLocationUpdates();
                    mCurrent.remove();
                    mMap.clear();
                    handler.removeCallbacks(drawPathRunnable);
                    Snackbar.make(mapFragment.getView(),"you are Offline",Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        polyLineList =new ArrayList<>();
        btnGo=(Button)findViewById(R.id.btnGo);
        edtPlace=(EditText)findViewById(R.id.edtPlace);

        btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                destination= edtPlace.getText().toString();
                destination = destination.replace(" ","+"); //replsce space with + for fetch data
                Log.d("WAHDAT",destination);

                getDirection();
            }
        });
        //geo fire
        drivers = FirebaseDatabase.getInstance().getReference("Drivers");
        geoFire=new GeoFire(drivers);
        setUpLocation();
        mService= Common.getGoogleAPI();
    }

    private void getDirection() {
        currentPosition=new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
        String requestApi =null;
        try{

            requestApi="https://maps.googleapis.com/maps/api/direction/json?"+
                    "mode=driving&"+
                    "transit_routing_preference=less_driving&"+
                    "origin="+currentPosition.latitude+","+currentPosition.longitude+"&"+
                    "destination="+destination+"&"+
                    "key="+getResources().getString(R.string.google_direction_api);

            Log.d("WAHDAT",requestApi); //print url for debug
            mService.getPath(requestApi)
                    .enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            try {
                                JSONObject jsonObject=new JSONObject(response.body().toString());
                                JSONArray jsonArray=jsonObject.getJSONArray("routes");
                                for (int i=0;i<jsonArray.length();i++)
                                {
                                    JSONObject route=jsonArray.getJSONObject(i);
                                    JSONObject poly =route.getJSONObject("overview_polyline");
                                    String polyline=poly.getString("points");
                                    polyLineList=decodePoly(polyline);

                                }
                                //adjusting bounds
                                LatLngBounds.Builder builder=new LatLngBounds.Builder();
                                for (LatLng latLng:polyLineList)
                                    builder.include(latLng);
                                LatLngBounds bounds=builder.build();
                                CameraUpdate mCameraUpdate =CameraUpdateFactory.newLatLngBounds(bounds,2);
                                mMap.animateCamera(mCameraUpdate);

                                polylineOptions = new PolylineOptions();
                                polylineOptions.color(Color.GRAY);
                                polylineOptions.width(5);
                                polylineOptions.startCap(new SquareCap());
                                polylineOptions.endCap(new SquareCap());
                                polylineOptions.jointType(JointType.ROUND);
                                polylineOptions.addAll(polyLineList);
                                greyPolyline = mMap.addPolyline(polylineOptions);

                                blackPolylineOptions = new PolylineOptions();
                                blackPolylineOptions.color(Color.GRAY);
                                blackPolylineOptions.width(5);
                                blackPolylineOptions.startCap(new SquareCap());
                                blackPolylineOptions.endCap(new SquareCap());
                                blackPolylineOptions.jointType(JointType.ROUND);
                                blackPolyline = mMap.addPolyline(blackPolylineOptions);

                                mMap.addMarker(new MarkerOptions().position(polyLineList.get(polyLineList.size()-1))
                                .title("PickUp location"));

                                //Animation
                                ValueAnimator polyLineAnimator =ValueAnimator.ofInt(0,100);
                                polyLineAnimator.setDuration(2000);
                                polyLineAnimator.setInterpolator(new LinearInterpolator());
                                polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                    @Override
                                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                        List<LatLng> points = greyPolyline.getPoints();
                                        int percentValue=(int)valueAnimator.getAnimatedValue();
                                        int size=points.size();
                                        int newPoints = (int)(size * (percentValue/100.0f));
                                        List<LatLng> p=points.subList(0,newPoints);
                                        blackPolyline.setPoints(p);
                                    }
                                });
                                polyLineAnimator.start();

                                carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
                                .flat(true)
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));

                                handler = new Handler();
                                index=-1;
                                next=1;
                                handler.postDelayed(drawPathRunnable,3000);

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

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                      Toast.makeText(Welcome.this,""+t.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    });

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

    }

    private List decodePoly(String encoded) {

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

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

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

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

        return poly;
    }

    //we request runtime permission, we need override onrequestpermissionresult method

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode)
        {
            case MY_PERMISSION_REQUEST_CODE:
                if (grantResults.length >0 && grantResults[0] ==PackageManager.PERMISSION_GRANTED)
                {
                    if (checkPlayServices())
                    {
                        buildGoogleApiClient();
                        createLocationRequest();
                        if (location_switch.isChecked())
                            displayLocation();
                    }
                }
        }
    }

    private void setUpLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
          //request runtime permission
            ActivityCompat.requestPermissions(this,new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
                    },MY_PERMISSION_REQUEST_CODE);
        }
        else
        {
            if (checkPlayServices())
            {
                buildGoogleApiClient();
                createLocationRequest();
                if (location_switch.isChecked())
                    displayLocation();
            }
        }
    }

    private void createLocationRequest() {
        mLocationRequest =new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);

    }

    private void buildGoogleApiClient() {
        mGoogleApiClient =new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICE_RES_REQUEST).show();
            else {
                Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
                finish();
            }
            return false;
        }
        return true;
    }

    private void stopLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
    }

    private void displayLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        mLastLocation= LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation !=null)
        {
            if (location_switch.isChecked())
            {
                final double latitude= mLastLocation.getLatitude();
                final double longitude=mLastLocation.getLongitude();
                //update to firebase
                geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
                    @Override
                    public void onComplete(String key, DatabaseError error) {
                        //add marker
                        if (mCurrent !=null)
                           mCurrent.remove();//remove marker already

                       mCurrent = mMap.addMarker(new MarkerOptions()

                                                    .position(new LatLng(latitude,longitude))
                                                               .title("Your Location"));
//
//                        //move camera to this position
                        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));

//

                    }
                });
            }
        }
        else
        {
            Log.d("ERROR","Cannot get your Location");

        }
    }

    private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
        final Handler handler=new Handler();
        final long start= SystemClock.uptimeMillis();
        final float startRotation = mCurrent.getRotation();
        final long duration = 1500;
        final Interpolator interpolator=new LinearInterpolator();

        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed=SystemClock.uptimeMillis() - start;
                float t= interpolator.getInterpolation((float)elapsed/duration);
                float rot= t*i+(1-t)*startRotation;
                mCurrent.setRotation(-rot >180?rot/2:rot);
                if (t<1.0)
                {
                    handler.postDelayed(this,16);
                }
            }
        });
    }

    private void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setTrafficEnabled(false);
        mMap.setIndoorEnabled(false);
        mMap.setBuildingsEnabled(false);
        mMap.getUiSettings().setZoomControlsEnabled(true);

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
    mLastLocation= location;
    displayLocation();
    }
}


来源: stackexchange

问:
ORA-01748: only simple column names allowed here in Oracle
What I am trying to do ?

I am trying to create two tables and at the same time i am trying to link them together using foreign and primary keys. However I successfully create my parent table ( Student with primary key ) but failed to create child table ( Attendence with foreign key ).

What is the problem ?

I get the following error while creating Attendence table:

ERROR at line 5: ORA-01748: only simple column names allowed here

My code:

Student table:

```<code>create table Student (

            ST_ROLLNO  NUMBER(6) constraint s_pk primary key,
            ST_NAME    VARCHAR(30) not null,
            ST_ADDRESS  varchar(35) not null
);
</code>```

Attendence table:

```<code>create table Attendence (

            ST_ROLLNO  NUMBER(6),
            ST_DATE    VARCHAR(30) not null,
            ST_PRESENT_ABSENT  varchar(1) not null,
            constraint f_pk Attendence.ST_ROLLNO foreign key references Student(ST_ROLLNO)
);
</code>```

答:
According to oracle documentation,

ORA ERR

ORA-01748 only simple column names allowed here

The following is the cause of this error:

This SQL statement does not allow a qualified column name, such as
  username.table.column or table.column.

Action you can take to resolve this issue: Remove the qualifications
  from the column and retry the operation.

In your case, you are trying to refer to the table name while defining a constraint -

Attendence.ST_ROLLNO - WRONG.

It must contain a simple name without the table name or schema name.

ContentLicense: CC BY-SA 3.0

Body:
What I am trying to do ?

I am trying to create two tables and at the same time i am trying to link them together using foreign and primary keys. However I successfully create my parent table ( Student with primary key ) but failed to create child table ( Attendence with foreign key ).

What is the problem ?

I get the following error while creating Attendence table:

ERROR at line 5: ORA-01748: only simple column names allowed here

My code:

Student table:

create table Student (

            ST_ROLLNO  NUMBER(6) constraint s_pk primary key,
            ST_NAME    VARCHAR(30) not null,
            ST_ADDRESS  varchar(35) not null
);

Attendence table:

create table Attendence (

            ST_ROLLNO  NUMBER(6),
            ST_DATE    VARCHAR(30) not null,
            ST_PRESENT_ABSENT  varchar(1) not null,
            constraint f_pk Attendence.ST_ROLLNO foreign key references Student(ST_ROLLNO)
);


问:
Eclipse android error
Everytime I start the emulator from eclipse, I get the following error in my console.

[2010-09-13 17:04:51 - DeviceMonitor]Sending jdwp tracking request failed!
[2010-09-13 17:18:49 - DeviceMonitor]Sending jdwp tracking request failed!

The application works fine, but I am concerned as to why I see this error. Please help

答: As Koby said this message comes if you close the emulator after running an application. First of all between successive application running on emulator you don't need to close the emulator. First before running the application you start the emulator by clicking window-->Android SDK and AVD Manager and click on the emulator you want to launch and click on 'start' button and then click on 'Launch' to launch the emulator. After the emulator launches unlock the emulator and keep that emulator minimized. And if you want to run an application go for 'run as android app' and you can see that on the emulator when maximized. After running that application if you want to make some changes in the application you don't need to close the emulator. you press the home button after running the application and keep the emulator minimized. Make the changes on the code and again go for running the application. Thus you can avoid that error message and save time for launching the emulator. if you got that error message then also the application will work properly but you cannot see the messages like uploading app-->installing .apk-->and the success messages. But these will be happening on the background. One way to overcome this is to restart the eclipse.</p>

ContentLicense: CC BY-SA 2.5

Title: Eclipse android error


问:
Increase a http get request connection Timeout in Angular2 http module
I use Angular2 on the client side and Node in the backend. I am trying to keep the https connection open until it timesout in 4 hours.

In the backend I tried, calling this but it still timesout at default 2 minutes

request.timeout(1000 * 60 * 60 * 4, function(){})

Since I use Angular2 http module. I tried using timeout method in http request as follows, this timesout at default of 2 minutes:

return this.http.get(this.URL, {search : params, withCredentials: true})
      .map(res => res.json())
      .timeout(1000 * 60 * 60 * 4)
      .catch(this.handleError);

Any other suggestions to increase https request connection from default 2 minutes to 4 hours

答:
Following are some of the suggestions:

It is not a good design to wait for 4 hours for the response.Try changing the back-end for quicker responses

Adding requestTimeout to the web.config file of the project fixed the issue for me

```<code><system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore requestTimeout="00:10:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</code>```

Body:
Following are some of the suggestions:

It is not a good design to wait for 4 hours for the response.Try changing the back-end for quicker responses

Adding requestTimeout to the web.config file of the project fixed the issue for me

<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore requestTimeout="00:10:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>


问:
If a cells are selected (from more than one sheet) then show message box
For starters, I am self taught and still learning (I learn a great deal from this website). That being said, please do not assume something is obvious. I will need help altering the code if your solution is too complex.

What I want to accomplish is; if you select cell A10 on "Sheet3", "Sheet4", and "Sheet5" then I want a message box to appear with the information from Sheets("Sheet6").Range("A1").

```<code>Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A10")) Is Nothing Then ' this range is where you click to get the msgbox
                Dim rng As Range, s As String, x As String
                Set rng = Sheets("Sheet6").Range("A1") ' this defines x
                 s = "Define: " ' s is what appears first
                 x = s & rng.Value ' x is what appears after s

                 MsgBox x
        End If
    End If
End Sub
</code>```

What I would like to happen; if you are in "Sheet3", "Sheet4", and "Sheet5" and select A10 in any of those three sheets, it will appear with the message box that is defined in the code.

What is working; currently this is a private sub that is directly in "Sheet5". When it is here, if cell A10 (in "Sheet5") is selected the information from "Sheet6" A1 appears in the message box as I want.

What is not working; because this is a private sub and is inside "Sheet5" I am struggling to get it to work with A10 from "Sheet3" and "Sheet4".

I attempted to alter the code by moving it and declaring it a public sub to work for all sheets but so far am unsuccessful.

答:
Sounds like a fun project! To expand a little more on the answer, when you use the Worksheet_SelectionChange event, this is an event that happens to a specific object. That's why it only works for the one sheet that has the code behind it. To have this work in multiple sheets, you could take one of the three following approaches.

Option 1: Copy the code to each worksheet object. This is the simplest approach, in one sense, but it can be messy to maintain copies of the same code in multiple locations.

Option 2: Put your code in a public function in a standard module. This way you can maintain your code routine in one location, and use the minimal necessary code to call this from each worksheet.

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    MySpecialFunction Target
End Sub
</code>```

For most cases, you will probably find this to be the most efficient way to handle the need.

Option 3: Another more advanced way to do this is to use a wrapper class object. This allows you to dynamically apply your function to any active sheet, without having to add the (option 2) code to each worksheet. While this is more complex, it allows you to apply your event-driven code to any worksheet, even new ones created by your users.

To do this, create a Class Module in your project, and name it clsMyClass. Then paste in the following code:

```<code>Option Explicit

Public WithEvents MySheet As Worksheet

Private Sub MySheet_SelectionChange(ByVal Target As Range)
    ' Do neat stuff here...
End Sub
</code>```

The key thing here is that WithEvents declaration. This is what allows you to tap into an event from an object variable. (But you can only do this from a class object, not a standard module.)

Then in your Workbook_Open() event, or somewhere else in your project, you can add the function that adds all current worksheets to a collection, allowing you to harness the SelectionChange event for all of these worksheets without needing to add code to each one.

```<code>Option Explicit

Private mcolSheets As Collection

Public Sub ActivateCodeForAllWorksheets()

    Dim wks As Worksheet
    Dim cSheet As clsMyClass

    ' Initialize module-level collection
    Set mcolSheets = New Collection

    For Each wks In ActiveWorkbook.Worksheets
        ' Create new instance of class
        Set cSheet = New clsMyClass
        ' Set to the current worksheet in our loop,
        ' and add to the collection so the sheet object
        ' reference perists after this sub finishes.
        Set cSheet.MySheet = wks
        mcolSheets.Add cSheet
    Next wks

End Sub
</code>```

In real life this can be very useful for things like applying special formatting to a text box when it has the focus, and having this behavior consistent across a large number of objects without needing hundreds of lines of repeated code.

I hope this is helpful!

Body:
For starters, I am self taught and still learning (I learn a great deal from this website). That being said, please do not assume something is obvious. I will need help altering the code if your solution is too complex.

What I want to accomplish is; if you select cell A10 on "Sheet3", "Sheet4", and "Sheet5" then I want a message box to appear with the information from Sheets("Sheet6").Range("A1").

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A10")) Is Nothing Then ' this range is where you click to get the msgbox
                Dim rng As Range, s As String, x As String
                Set rng = Sheets("Sheet6").Range("A1") ' this defines x
                 s = "Define: " ' s is what appears first
                 x = s & rng.Value ' x is what appears after s

                 MsgBox x
        End If
    End If
End Sub

What I would like to happen; if you are in "Sheet3", "Sheet4", and "Sheet5" and select A10 in any of those three sheets, it will appear with the message box that is defined in the code.

What is working; currently this is a private sub that is directly in "Sheet5". When it is here, if cell A10 (in "Sheet5") is selected the information from "Sheet6" A1 appears in the message box as I want.

What is not working; because this is a private sub and is inside "Sheet5" I am struggling to get it to work with A10 from "Sheet3" and "Sheet4".

I attempted to alter the code by moving it and declaring it a public sub to work for all sheets but so far am unsuccessful.

Body:
Sounds like a fun project! To expand a little more on the answer, when you use the Worksheet_SelectionChange event, this is an event that happens to a specific object. That's why it only works for the one sheet that has the code behind it. To have this work in multiple sheets, you could take one of the three following approaches.

Option 1: Copy the code to each worksheet object. This is the simplest approach, in one sense, but it can be messy to maintain copies of the same code in multiple locations.

Option 2: Put your code in a public function in a standard module. This way you can maintain your code routine in one location, and use the minimal necessary code to call this from each worksheet.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    MySpecialFunction Target
End Sub

For most cases, you will probably find this to be the most efficient way to handle the need.

Option 3: Another more advanced way to do this is to use a wrapper class object. This allows you to dynamically apply your function to any active sheet, without having to add the (option 2) code to each worksheet. While this is more complex, it allows you to apply your event-driven code to any worksheet, even new ones created by your users.

To do this, create a Class Module in your project, and name it clsMyClass. Then paste in the following code:

Option Explicit

Public WithEvents MySheet As Worksheet

Private Sub MySheet_SelectionChange(ByVal Target As Range)
    ' Do neat stuff here...
End Sub

The key thing here is that WithEvents declaration. This is what allows you to tap into an event from an object variable. (But you can only do this from a class object, not a standard module.)

Then in your Workbook_Open() event, or somewhere else in your project, you can add the function that adds all current worksheets to a collection, allowing you to harness the SelectionChange event for all of these worksheets without needing to add code to each one.

Option Explicit

Private mcolSheets As Collection

Public Sub ActivateCodeForAllWorksheets()

    Dim wks As Worksheet
    Dim cSheet As clsMyClass

    ' Initialize module-level collection
    Set mcolSheets = New Collection

    For Each wks In ActiveWorkbook.Worksheets
        ' Create new instance of class
        Set cSheet = New clsMyClass
        ' Set to the current worksheet in our loop,
        ' and add to the collection so the sheet object
        ' reference perists after this sub finishes.
        Set cSheet.MySheet = wks
        mcolSheets.Add cSheet
    Next wks

End Sub

In real life this can be very useful for things like applying special formatting to a text box when it has the focus, and having this behavior consistent across a large number of objects without needing hundreds of lines of repeated code.

I hope this is helpful!


问:
Why does requests return an error when running through a function?
There's an endpoint called getbalance on the Bittrex Api which takes in a currency as a string and returns your current balance for that currency. When doing the request in a function,

```<code>balance = get_balance('BTC')
</code>```

the request returns:

{'message': 'INVALID_SIGNATURE',

  'result': None,

  'success': False}

Function:

```<code>def get_balance(currency):
    endpoint = '/account/getbalance'
    params = {
        'currency' : currency
    }
    return call_endpoint(endpoint, False, params)
</code>```

call_endpoint:

```<code>def call_endpoint(endpoint, isPublic, params = None):
    base_url = 'https://bittrex.com/api/v1.1'
    url = (base_url + endpoint +
       '?apikey=' + API_KEY +
       '&nonce=' + str(time.time())).encode('utf-8')
    signature = hmac.new(SECRET_KEY, url, hashlib.sha512).hexdigest()
    headers = {'apisign' : signature}
    r = requests.get(url, headers = headers, params=params)
    return r
</code>```

However, if I were to request it outside of a function:

```<code>url = ('https://bittrex.com/api/v1.1/account/getbalance' +
    '?apikey=' + API_KEY +
    '&nonce=' + str(time.time()) +
    '&currency=BTC').encode('utf-8')
signature = hmac.new(SECRET_KEY, url, hashlib.sha512).hexdigest()
headers = {'apisign' : signature}
r = requests.get(url, headers = headers)
</code>```

it works.

{'message': '',

  'result': {'Available':

  ...,

  'success': True}

These two approaches have the same code, so is there something about python functions or the requests library that causes this error?

答:
These two approaches do not do the same thing.

Your call_endpoint function computes a signature for the headers on an input of the url WITHOUT a currency param, then has requests add in the currency param.

Your other snippet computes the signature on a url that contains the currency param.

Body:
There's an endpoint called getbalance on the Bittrex Api which takes in a currency as a string and returns your current balance for that currency. When doing the request in a function,

balance = get_balance('BTC')

the request returns:

{'message': 'INVALID_SIGNATURE',

  'result': None,

  'success': False}

Function:

def get_balance(currency):
    endpoint = '/account/getbalance'
    params = {
        'currency' : currency
    }
    return call_endpoint(endpoint, False, params)

call_endpoint:

def call_endpoint(endpoint, isPublic, params = None):
    base_url = 'https://bittrex.com/api/v1.1'
    url = (base_url + endpoint +
       '?apikey=' + API_KEY +
       '&nonce=' + str(time.time())).encode('utf-8')
    signature = hmac.new(SECRET_KEY, url, hashlib.sha512).hexdigest()
    headers = {'apisign' : signature}
    r = requests.get(url, headers = headers, params=params)
    return r

However, if I were to request it outside of a function:

url = ('https://bittrex.com/api/v1.1/account/getbalance' +
    '?apikey=' + API_KEY +
    '&nonce=' + str(time.time()) +
    '&currency=BTC').encode('utf-8')
signature = hmac.new(SECRET_KEY, url, hashlib.sha512).hexdigest()
headers = {'apisign' : signature}
r = requests.get(url, headers = headers)

it works.

{'message': '',

  'result': {'Available':

  ...,

  'success': True}

These two approaches have the same code, so is there something about python functions or the requests library that causes this error?


问:
C++ - structs... function parameter issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

It has the following code:

```<code>// Declare a DateStruct variable
DateStruct sToday;

// Initialize it manually
sToday.nMonth = 10;
sToday.nDay = 14;
sToday.nYear = 2020;

// Here is a function to initialize a date
void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
{
    sDate.nMonth = nMonth;
    sDate.nDay = nDay;
    sDate.nYear = nYear;
}

// Init our date to the same date using the function
SetDate(sToday, 10, 14, 2020);
</code>```

What is the purpose of the

DateStruct &sDate

parameter in the function signature, especially that I cannot see a use of it in the function body?

Thanks.

答:
The aforementioned, highlighted code is called a reference. You might think of references as aliases for variables.

During function call sDate becomes an alias to sToday - which has been given as a parameter. Thus it makes it possible to modify sToday from within the function!

The reason is that it makes possible to give complex structures that might be filled up with data, modified, etc. inside of called functions.

In your case the SetDate function takes separate year, month and day - and packs it inside sDate (== sToday) structure.

Just compare the first way of initialization (you need to mention all struct members yourself) to calling SetDate function.

eg.:

```<code>DateStruct janFirst;
DateStruct decLast;

SetDate(janFirst, 1, 1, 2011);
SetDate(decLast, 12, 31, 2011);
</code>```

Compare this to how much code would have been written if you had to fill all those janFirst, decLast structures by hand!

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

It has the following code:

// Declare a DateStruct variable
DateStruct sToday;

// Initialize it manually
sToday.nMonth = 10;
sToday.nDay = 14;
sToday.nYear = 2020;

// Here is a function to initialize a date
void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
{
    sDate.nMonth = nMonth;
    sDate.nDay = nDay;
    sDate.nYear = nYear;
}

// Init our date to the same date using the function
SetDate(sToday, 10, 14, 2020);

What is the purpose of the

DateStruct &sDate

parameter in the function signature, especially that I cannot see a use of it in the function body?

Thanks.

Body:
The aforementioned, highlighted code is called a reference. You might think of references as aliases for variables.

During function call sDate becomes an alias to sToday - which has been given as a parameter. Thus it makes it possible to modify sToday from within the function!

The reason is that it makes possible to give complex structures that might be filled up with data, modified, etc. inside of called functions.

In your case the SetDate function takes separate year, month and day - and packs it inside sDate (== sToday) structure.

Just compare the first way of initialization (you need to mention all struct members yourself) to calling SetDate function.

eg.:

DateStruct janFirst;
DateStruct decLast;

SetDate(janFirst, 1, 1, 2011);
SetDate(decLast, 12, 31, 2011);

Compare this to how much code would have been written if you had to fill all those janFirst, decLast structures by hand!


答:
You can use plotly to achieve your desired result.

Install the plotly package

```<code>sudo pip install plotly
</code>```

And then import and use as needed

```<code>import plotly.plotly as py
import plotly.graph_objs as go

data = [go.Bar( x=['jan', 'feb', 'mar'], y=[20, 14, 23] )]
py.iplot(data, filename='basic-bar')
</code>```

In your case pass the month column from data frame to x and values to y as input.

Plotly documentation

Bar charts in plotly

Title: plotting bar graph in python

Body:
Someone Please tell me how to plot a bar graph or line graph in python.
I want to plot a bar graph with x-axis as month and y-axis with the mean values of different columns.

A Sample of my dataset:

Month   Bedroom Outlets Cellar Outlets  Bedroom Lights  DisposalDishwasher  DuctHeaterHRV   FridgeRange FurnaceHRV  KitchenLights   MasterLights    MasterOutlets   WashingMachine
Jan-16  0.008704    0.074089    0.006081    0.000116    0.000058    0.001162    0.176832    0.000024    0.014887    0.009617    0.000378
Feb-16  0.008187    0.075153    0.005993    0.000102    0.000059    0.001905    0.172289    0.000023    0.01448 0.007724    0.000367
Mar-16  0.007725    0.072855    0.005536    0.000073    0.000048    0.001469    0.1261  0.000015    0.014242    0.005848    0.00024
Apr-16  0.007678    0.074465    0.005729    0.000061    0.000042    0.001129    0.093861    0.000014    0.014267    0.005899    0.000152
May-16  0.007864    0.075408    0.005823    0.000096    0.000102    0.001691    0.116811    0.000029    0.014387    0.007111    0.000406
Jun-16  0.006876    0.07829 0.005587    0.000143    0.000134    0.000937    0.176654    0.000046    0.014229    0.005706    0.000654
Jul-16  0.006032    0.093383    0.006214    0.000193    0.000236    0.000831    0.228637    0.000082    0.014352    0.005174    0.001004

For example I want that my values on y-axis and jan 2016 on x- axis and there is a bar graph on it showing the usage of different attribute of that particular month.

Body:
You can use plotly to achieve your desired result.

Install the plotly package

sudo pip install plotly

And then import and use as needed

import plotly.plotly as py
import plotly.graph_objs as go

data = [go.Bar( x=['jan', 'feb', 'mar'], y=[20, 14, 23] )]
py.iplot(data, filename='basic-bar')

In your case pass the month column from data frame to x and values to y as input.

Plotly documentation

Bar charts in plotly


问:
How to track progress of a student in a Learning Management System
I'm working on an LMS for a client. The top level table is Certificates. The next level down is Courses and below that is Activities. An Activity may be a video, a slide, or a quiz.

Storing those relations is easy and not an issue.

If a student/user signs up for a certificate, I need to track that student's progress through the certificate. So I need to have a unique version of the Certificate and all it's children so I can know what their progress is for each Activity, Course and Certificate. One other consideration is that the student can complete the certificate multiple times.

I tried a Progress table with user_id, certificate_id, course_id, activity_id and completed but it doesn't handle signing up for the certificate multiple times. In that same table I tried referring to the certificates_users_id to attempt to establish a unique top level reference for that user & certificate but I'm having trouble joining it together.

I want to be able to grab that user's In Progress Certificates and know exactly which activities & courses in it have been completed by that user.

答:
If you just add a new field say attempt_number in your progress table, the keys: user_id, certificate_id, attempt_number together can make a primary key and this way you can handle the scenario in which a user completes a certificate multiple times. You can start with attempt_number as 1 and increment it the next time user does the same certification.

It also tracks the history of each time the certification is completed, say a new Activity got added in a course after the user completes the certification, that can be tracked easily.


问:
Having trouble finding the start of a sentence inside string array
I have a text file from which I read the text in lines. Also from all that text I need to find the longest sentence and find in which line it begins. I have no trouble finding the longest sentence but the problem arises when I need to find where it begins.

The contents of the text file is:

V. M. Putinas

  Margi sakalai

  Lydėdami gęstančią žarą vėlai

  Pakilo į dangų;;, margi sakalai.

  Paniekinę žemės vylingus sapnus,

  Padangėje ištiesė,,; savo sparnus.

  Ir tarė margieji: negrįšim į žemę,

  Kol josios kalnai ir pakalnės aptemę.

My code:

```<code>static void Sakiniai (string fv, string skyrikliai)
{
    char[] skyrikliaiSak = { '.', '!', '?' };
    string naujas = "";
    string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));

    foreach (string line in lines)
    {
        // Add lines into a string so I can separate them into sentences
        naujas += line;
    }

    // Separating into sentences
    string[] sakiniai = naujas.Split(skyrikliaiSak);

    // This method finds the longest sentence
    string ilgiausiasSak = RastiIlgiausiaSakini(sakiniai);
}
</code>```

From the text file the longest sentence is: "Margi sakalai Lydėdami gęstančią žarą vėlai Pakilo į dangų;;, margi sakalai"

How can I find the exact line where the sentence begins?

答:
Build an index that solves your problem.

We can make a straightforward modification of your existing code:

```<code>var lineOffsets = new List<int>();
lineOffsets.Add(0);
foreach (string line in lines)
{
    // Add lines into a string so I can separate them into sentences
    naujas += line;
    lineOffsets.Add(naujas.Length);
}
</code>```

All right; now you have a list of the character offset in your final string corresponding to each line.

You have a substring of the big string. You can use IndexOf to find the offset of the substring in the big string.  Then you can search through the list to find the list index of the last element that is smaller or equal than the offset. That's the line number.

If the list is large, you can binary search it.

Body:
I have a text file from which I read the text in lines. Also from all that text I need to find the longest sentence and find in which line it begins. I have no trouble finding the longest sentence but the problem arises when I need to find where it begins.

The contents of the text file is:

V. M. Putinas

  Margi sakalai

  Lydėdami gęstančią žarą vėlai

  Pakilo į dangų;;, margi sakalai.

  Paniekinę žemės vylingus sapnus,

  Padangėje ištiesė,,; savo sparnus.

  Ir tarė margieji: negrįšim į žemę,

  Kol josios kalnai ir pakalnės aptemę.

My code:

static void Sakiniai (string fv, string skyrikliai)
{
    char[] skyrikliaiSak = { '.', '!', '?' };
    string naujas = "";
    string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));

    foreach (string line in lines)
    {
        // Add lines into a string so I can separate them into sentences
        naujas += line;
    }

    // Separating into sentences
    string[] sakiniai = naujas.Split(skyrikliaiSak);

    // This method finds the longest sentence
    string ilgiausiasSak = RastiIlgiausiaSakini(sakiniai);
}

From the text file the longest sentence is: "Margi sakalai Lydėdami gęstančią žarą vėlai Pakilo į dangų;;, margi sakalai"

How can I find the exact line where the sentence begins?

Body:
Build an index that solves your problem.

We can make a straightforward modification of your existing code:

var lineOffsets = new List<int>();
lineOffsets.Add(0);
foreach (string line in lines)
{
    // Add lines into a string so I can separate them into sentences
    naujas += line;
    lineOffsets.Add(naujas.Length);
}

All right; now you have a list of the character offset in your final string corresponding to each line.

You have a substring of the big string. You can use IndexOf to find the offset of the substring in the big string.  Then you can search through the list to find the list index of the last element that is smaller or equal than the offset. That's the line number.

If the list is large, you can binary search it.


问:
Plugin execution not covered by lifecycle configuration for org.jacoco:jacoco-maven-plugin
I'm encountering the following error:

Plugin execution not covered by lifecycle configuration: org.jacoco:jacoco-maven-plugin:0.7.4.201502262128:prepare-agent (execution: jacoco-initialize, phase: initialize)

I tried searching the internet but didn't get any sufficient responses and ideas to it

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
          <groupId>org.jacoco</groupId>
                       <artifactId>jacoco-maven-plugin</artifactId>
                       <version>0.7.4.201502262128</version>
        <configuration>
            <destFile>${basedir}/../../target/coverage-reports/jacoco_domain-rest-service.exec</destFile>
            <dataFile>${basedir}/../../target/coverage-reports/jacoco_domain-rest-service.exec</dataFile>
        </configuration>
        <executions>
            <execution>
                <id>jacoco-initialize</id>
                 <goals>
                  <goal>prepare-agent</goal>
                 </goals>
            </execution>
            <execution>
                <id>jacoco-site</id>
                <phase>package</phase>
                <goals>
                  <goal>report</goal>
                </goals>
            </execution>
        </executions>
      </plugin>
    </plugins>
</build>
</code>```

Any help and suggestions much appreciated!

Thank you!

答:
smart987 says:

Replace the jacoco version part in pom.xml with the following it will work. I too faced the same issue and resolved with this and is working fine now.

```<code><groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
</code>```

So delete the content in between version tags and replace that with .7.5.201505241946. It will work

Body:
I'm encountering the following error:

Plugin execution not covered by lifecycle configuration: org.jacoco:jacoco-maven-plugin:0.7.4.201502262128:prepare-agent (execution: jacoco-initialize, phase: initialize)

I tried searching the internet but didn't get any sufficient responses and ideas to it

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
          <groupId>org.jacoco</groupId>
                       <artifactId>jacoco-maven-plugin</artifactId>
                       <version>0.7.4.201502262128</version>
        <configuration>
            <destFile>${basedir}/../../target/coverage-reports/jacoco_domain-rest-service.exec</destFile>
            <dataFile>${basedir}/../../target/coverage-reports/jacoco_domain-rest-service.exec</dataFile>
        </configuration>
        <executions>
            <execution>
                <id>jacoco-initialize</id>
                 <goals>
                  <goal>prepare-agent</goal>
                 </goals>
            </execution>
            <execution>
                <id>jacoco-site</id>
                <phase>package</phase>
                <goals>
                  <goal>report</goal>
                </goals>
            </execution>
        </executions>
      </plugin>
    </plugins>
</build>

Any help and suggestions much appreciated!

Thank you!

Body:
smart987 says:

Replace the jacoco version part in pom.xml with the following it will work. I too faced the same issue and resolved with this and is working fine now.

<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>

So delete the content in between version tags and replace that with .7.5.201505241946. It will work