问:
Binary XML file line #0: Binary XML file line #0: Error inflating class fragment

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: co.antariksh.antarikshbin, PID: 15765
                                                                             android.view.InflateException:

```*********This is a TabActivity****************
package co.antariksh.antarikshbin;

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

public class OneActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                       OneActivity.this.finish();
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }

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

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

        //noinspection SimplifiableIfStatement

        return super.onOptionsItemSelected(item);
    }

    //placehlder deleted

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    CameraActivity cameraActivity = new CameraActivity();
                    return cameraActivity;
                case 1:
                    MaterialActivity materialActivity = new MaterialActivity();
                    return materialActivity;
                case 2:
                    DetailActivity detailActivity =  new DetailActivity();
                    return detailActivity;
                case 3:
                    MoreDetailsActivity moreDetailsActivity = new MoreDetailsActivity();
                    return moreDetailsActivity;
                case 4:
                    MapPointActivity mapPointActivity = new MapPointActivity();

                    return mapPointActivity;
                case 5:
                    AddRecordActivity addRecordActivity = new AddRecordActivity();
                    return addRecordActivity;
                default:
                    return null;
            }

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 6;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:

                    return "Take Picture";
                case 1:

                    return  "Material";
                case 2:

                    return  "Info";
                case 3:

                    return  "Details";
                case 4:

                    return  "Map";
                case 5:

                    return  "Publish";

            }
            return null;
        }
    }
}

*******This is a Fragment for the above activity**************
package co.antariksh.antarikshbin;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.os.ResultReceiver;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

public class MapPointActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private static String TAG = "MAP LOCATION";
    Context mContext;
    TextView mLocationMarkerText;
    private LatLng mCenterLatLong;
    private AddressResultReceiver mResultReceiver;
    protected String mAddressOutput;
    protected String mAreaOutput;
    protected String mCityOutput;
    protected String mStateOutput;
    EditText mLocationAddress;
    TextView mLocationText;
    private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
    Toolbar mToolbar;
    SupportMapFragment mapFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_map_point, container, false);

        mContext = getContext();
        if (mapFragment == null) {
            mapFragment = SupportMapFragment.newInstance();
            mapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                   mapReady(googleMap);
                }
            });
        }

             // R.id.map is a FrameLayout, not a Fragment
        getChildFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();

          // Obtain the SupportMapFragment and get notified when the map is ready to be used.
         // SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
        //        .findFragmentById(R.id.map);

        mLocationMarkerText = (TextView)rootView.findViewById(R.id.locationMarkertext);
        mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);

      //  mapFragment.getMapAsync(this);
        mResultReceiver = new AddressResultReceiver(new Handler());

        if (checkPlayServices()) {
            // If this check succeeds, proceed with normal processing.
            // Otherwise, prompt user to get valid Play Services APK.
            if (!AppUtils.isLocationEnabled(mContext)) {
                // notify user
                AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
                dialog.setMessage("Location not enabled!");
                dialog.setPositiveButton("Open location settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    }
                });
                dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        // TODO Auto-generated method stub

                    }
                });
                dialog.show();
            }
            buildGoogleApiClient();
        } else {
            Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
        }

        return rootView;
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    public void mapReady(GoogleMap googleMap){
        Log.d(TAG, "OnMapReady");
        mMap = googleMap;

        mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                Log.d("Camera postion change" + "", cameraPosition + "");
                mCenterLatLong = cameraPosition.target;

                mMap.clear();

                try {

                    Location mLocation = new Location("");
                    mLocation.setLatitude(mCenterLatLong.latitude);
                    mLocation.setLongitude(mCenterLatLong.longitude);

                    startIntentService(mLocation);
                    mLocationMarkerText.setText("Lat : " + mCenterLatLong.latitude + "," + "Long : " + mCenterLatLong.longitude);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
//        mMap.setMyLocationEnabled(true);
//        mMap.getUiSettings().setMyLocationButtonEnabled(true);
//
//        // Add a marker in Sydney and move the camera
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            changeMap(mLastLocation);
            Log.d(TAG, "ON connected");

        } else
            try {
                LocationServices.FusedLocationApi.removeLocationUpdates(
                        mGoogleApiClient, this);

            } catch (Exception e) {
                e.printStackTrace();
            }
        try {
            LocationRequest mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(10000);
            mLocationRequest.setFastestInterval(5000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);

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

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        try {
            if (location != null)
                changeMap(location);
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);

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

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

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

    @Override
    public void onStart() {
        super.onStart();
        try {
            mGoogleApiClient.connect();

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

    @Override
    public void onStop() {
        super.onStop();
        try {

        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                //finish();
            }
            return false;
        }
        return true;
    }

    private void changeMap(Location location) {

        Log.d(TAG, "Reaching map" + mMap);

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        // check if map is created successfully or not
        if (mMap != null) {
            mMap.getUiSettings().setZoomControlsEnabled(false);
            LatLng latLong;

            latLong = new LatLng(location.getLatitude(), location.getLongitude());

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLong).zoom(19f).tilt(70).build();

            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
            mMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
            startIntentService(location);

        } else {
            Toast.makeText(getActivity().getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

    }

    /**
     * Receiver for data sent from FetchAddressIntentService.
     */
    class AddressResultReceiver extends ResultReceiver {
        public AddressResultReceiver(Handler handler) {
            super(handler);
        }

        /**
         * Receives data sent from FetchAddressIntentService and updates the UI in MainActivity.
         */
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            // Display the address string or an error message sent from the intent service.
            mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);

            mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);

            mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
            mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);

            displayAddressOutput();

            // Show a toast message if an address was found.
            if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
                //  showToast(getString(R.string.address_found));

            }

        }

    }

    /**
     * Updates the address in the UI.
     */
    protected void displayAddressOutput() {
        //  mLocationAddressTextView.setText(mAddressOutput);
        try {
            if (mAreaOutput != null)
                // mLocationText.setText(mAreaOutput+ "");

                mLocationAddress.setText(mAddressOutput);
            //mLocationText.setText(mAreaOutput);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates an intent, adds location data to it as an extra, and starts the intent service for
     * fetching an address.
     */
    protected void startIntentService(Location mLocation) {
        // Create an intent for passing to the intent service responsible for fetching the address.
        Intent intent = new Intent(getContext(), FetchAddressIntentService.class);

        // Pass the result receiver as an extra to the service.
        intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);

        // Pass the location data as an extra to the service.
        intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);

        // Start the service. If the service isn't already running, it is instantiated and started
        // (creating a process for it if needed); if it is running then it remains running. The
        // service kills itself automatically once all intents are processed.
        getActivity().startService(intent);
    }

    private void openAutocompleteActivity() {
        try {
            // The autocomplete activity requires Google Play Services to be available. The intent
            // builder checks this and throws an exception if it is not the case.
            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                    .build(getActivity());
            startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
        } catch (GooglePlayServicesRepairableException e) {
            // Indicates that Google Play Services is either not installed or not up to date. Prompt
            // the user to correct the issue.
            GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(),
                    0 /* requestCode */).show();
        } catch (GooglePlayServicesNotAvailableException e) {
            // Indicates that Google Play Services is not available and the problem is not easily
            // resolvable.
            String message = "Google Play Services is not available: " +
                    GoogleApiAvailability.getInstance().getErrorString(e.errorCode);

            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Called after the autocomplete activity has finished to return its result.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Check that the result was from the autocomplete widget.
        if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
            if (resultCode == RESULT_OK) {
                // Get the user's selected place from the Intent.
                Place place = PlaceAutocomplete.getPlace(mContext, data);

                // TODO call location based filter

                LatLng latLong;

                latLong = place.getLatLng();

                //mLocationText.setText(place.getName() + "");

                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(latLong).zoom(19f).tilt(70).build();

                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                mMap.setMyLocationEnabled(true);
                mMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

            }

        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(mContext, data);
        } else if (resultCode == RESULT_CANCELED) {
            // Indicates that the activity closed before a selection was made. For example if
            // the user pressed the back button.
        }
    }

}
```

Here is the error:

Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class fragment
  Caused by: java.lang.IllegalStateException: Fragment com.google.android.gms.maps.SupportMapFragment did not create a view.

答:
Change this line:

```<code>mContext = getContext();
</code>```

To this:

```<code>mContext = getActivity();
</code>```

Reason:

The method View.getContext() runs only when a view has already been inflated so for this you have used it inside onCreateView while the View has not been made yet, until the line return rootView; is reached. (Though you could use your way in other lifecycle methods like onResume() after onCreateView).

So instead use the activity since the Fragment has already been attached up to this point and the Context is the Activity for this Fragment. If you still face Context issues comment below and I will edit the answer!

In addition to that Please use Class names that resemble the situation for example this part

```<code>public class MapPointActivity extends Fragment ....
</code>```

It was good if you would call it MapPointFragment since it extends Fragment not Activity,(its a good design) especially for Future reference of the code.

Body:
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: co.antariksh.antarikshbin, PID: 15765
                                                                             android.view.InflateException:

*********This is a TabActivity****************
package co.antariksh.antarikshbin;

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

public class OneActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                       OneActivity.this.finish();
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }

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

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

        //noinspection SimplifiableIfStatement

        return super.onOptionsItemSelected(item);
    }

    //placehlder deleted

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    CameraActivity cameraActivity = new CameraActivity();
                    return cameraActivity;
                case 1:
                    MaterialActivity materialActivity = new MaterialActivity();
                    return materialActivity;
                case 2:
                    DetailActivity detailActivity =  new DetailActivity();
                    return detailActivity;
                case 3:
                    MoreDetailsActivity moreDetailsActivity = new MoreDetailsActivity();
                    return moreDetailsActivity;
                case 4:
                    MapPointActivity mapPointActivity = new MapPointActivity();

                    return mapPointActivity;
                case 5:
                    AddRecordActivity addRecordActivity = new AddRecordActivity();
                    return addRecordActivity;
                default:
                    return null;
            }

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 6;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:

                    return "Take Picture";
                case 1:

                    return  "Material";
                case 2:

                    return  "Info";
                case 3:

                    return  "Details";
                case 4:

                    return  "Map";
                case 5:

                    return  "Publish";

            }
            return null;
        }
    }
}

*******This is a Fragment for the above activity**************
package co.antariksh.antarikshbin;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.os.ResultReceiver;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

public class MapPointActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private static String TAG = "MAP LOCATION";
    Context mContext;
    TextView mLocationMarkerText;
    private LatLng mCenterLatLong;
    private AddressResultReceiver mResultReceiver;
    protected String mAddressOutput;
    protected String mAreaOutput;
    protected String mCityOutput;
    protected String mStateOutput;
    EditText mLocationAddress;
    TextView mLocationText;
    private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
    Toolbar mToolbar;
    SupportMapFragment mapFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_map_point, container, false);

        mContext = getContext();
        if (mapFragment == null) {
            mapFragment = SupportMapFragment.newInstance();
            mapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                   mapReady(googleMap);
                }
            });
        }

             // R.id.map is a FrameLayout, not a Fragment
        getChildFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();

          // Obtain the SupportMapFragment and get notified when the map is ready to be used.
         // SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
        //        .findFragmentById(R.id.map);

        mLocationMarkerText = (TextView)rootView.findViewById(R.id.locationMarkertext);
        mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);

      //  mapFragment.getMapAsync(this);
        mResultReceiver = new AddressResultReceiver(new Handler());

        if (checkPlayServices()) {
            // If this check succeeds, proceed with normal processing.
            // Otherwise, prompt user to get valid Play Services APK.
            if (!AppUtils.isLocationEnabled(mContext)) {
                // notify user
                AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
                dialog.setMessage("Location not enabled!");
                dialog.setPositiveButton("Open location settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    }
                });
                dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        // TODO Auto-generated method stub

                    }
                });
                dialog.show();
            }
            buildGoogleApiClient();
        } else {
            Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
        }

        return rootView;
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    public void mapReady(GoogleMap googleMap){
        Log.d(TAG, "OnMapReady");
        mMap = googleMap;

        mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                Log.d("Camera postion change" + "", cameraPosition + "");
                mCenterLatLong = cameraPosition.target;

                mMap.clear();

                try {

                    Location mLocation = new Location("");
                    mLocation.setLatitude(mCenterLatLong.latitude);
                    mLocation.setLongitude(mCenterLatLong.longitude);

                    startIntentService(mLocation);
                    mLocationMarkerText.setText("Lat : " + mCenterLatLong.latitude + "," + "Long : " + mCenterLatLong.longitude);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
//        mMap.setMyLocationEnabled(true);
//        mMap.getUiSettings().setMyLocationButtonEnabled(true);
//
//        // Add a marker in Sydney and move the camera
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            changeMap(mLastLocation);
            Log.d(TAG, "ON connected");

        } else
            try {
                LocationServices.FusedLocationApi.removeLocationUpdates(
                        mGoogleApiClient, this);

            } catch (Exception e) {
                e.printStackTrace();
            }
        try {
            LocationRequest mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(10000);
            mLocationRequest.setFastestInterval(5000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);

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

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        try {
            if (location != null)
                changeMap(location);
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);

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

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

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

    @Override
    public void onStart() {
        super.onStart();
        try {
            mGoogleApiClient.connect();

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

    @Override
    public void onStop() {
        super.onStop();
        try {

        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                //finish();
            }
            return false;
        }
        return true;
    }

    private void changeMap(Location location) {

        Log.d(TAG, "Reaching map" + mMap);

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        // check if map is created successfully or not
        if (mMap != null) {
            mMap.getUiSettings().setZoomControlsEnabled(false);
            LatLng latLong;

            latLong = new LatLng(location.getLatitude(), location.getLongitude());

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLong).zoom(19f).tilt(70).build();

            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
            mMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
            startIntentService(location);

        } else {
            Toast.makeText(getActivity().getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

    }

    /**
     * Receiver for data sent from FetchAddressIntentService.
     */
    class AddressResultReceiver extends ResultReceiver {
        public AddressResultReceiver(Handler handler) {
            super(handler);
        }

        /**
         * Receives data sent from FetchAddressIntentService and updates the UI in MainActivity.
         */
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            // Display the address string or an error message sent from the intent service.
            mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);

            mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);

            mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
            mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);

            displayAddressOutput();

            // Show a toast message if an address was found.
            if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
                //  showToast(getString(R.string.address_found));

            }

        }

    }

    /**
     * Updates the address in the UI.
     */
    protected void displayAddressOutput() {
        //  mLocationAddressTextView.setText(mAddressOutput);
        try {
            if (mAreaOutput != null)
                // mLocationText.setText(mAreaOutput+ "");

                mLocationAddress.setText(mAddressOutput);
            //mLocationText.setText(mAreaOutput);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates an intent, adds location data to it as an extra, and starts the intent service for
     * fetching an address.
     */
    protected void startIntentService(Location mLocation) {
        // Create an intent for passing to the intent service responsible for fetching the address.
        Intent intent = new Intent(getContext(), FetchAddressIntentService.class);

        // Pass the result receiver as an extra to the service.
        intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);

        // Pass the location data as an extra to the service.
        intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);

        // Start the service. If the service isn't already running, it is instantiated and started
        // (creating a process for it if needed); if it is running then it remains running. The
        // service kills itself automatically once all intents are processed.
        getActivity().startService(intent);
    }

    private void openAutocompleteActivity() {
        try {
            // The autocomplete activity requires Google Play Services to be available. The intent
            // builder checks this and throws an exception if it is not the case.
            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                    .build(getActivity());
            startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
        } catch (GooglePlayServicesRepairableException e) {
            // Indicates that Google Play Services is either not installed or not up to date. Prompt
            // the user to correct the issue.
            GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(),
                    0 /* requestCode */).show();
        } catch (GooglePlayServicesNotAvailableException e) {
            // Indicates that Google Play Services is not available and the problem is not easily
            // resolvable.
            String message = "Google Play Services is not available: " +
                    GoogleApiAvailability.getInstance().getErrorString(e.errorCode);

            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Called after the autocomplete activity has finished to return its result.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Check that the result was from the autocomplete widget.
        if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
            if (resultCode == RESULT_OK) {
                // Get the user's selected place from the Intent.
                Place place = PlaceAutocomplete.getPlace(mContext, data);

                // TODO call location based filter

                LatLng latLong;

                latLong = place.getLatLng();

                //mLocationText.setText(place.getName() + "");

                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(latLong).zoom(19f).tilt(70).build();

                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                mMap.setMyLocationEnabled(true);
                mMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

            }

        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(mContext, data);
        } else if (resultCode == RESULT_CANCELED) {
            // Indicates that the activity closed before a selection was made. For example if
            // the user pressed the back button.
        }
    }

}

Here is the error:

Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class fragment
  Caused by: java.lang.IllegalStateException: Fragment com.google.android.gms.maps.SupportMapFragment did not create a view.

Body:
Change this line:

mContext = getContext();

To this:

mContext = getActivity();

Reason:

The method View.getContext() runs only when a view has already been inflated so for this you have used it inside onCreateView while the View has not been made yet, until the line return rootView; is reached. (Though you could use your way in other lifecycle methods like onResume() after onCreateView).

So instead use the activity since the Fragment has already been attached up to this point and the Context is the Activity for this Fragment. If you still face Context issues comment below and I will edit the answer!

In addition to that Please use Class names that resemble the situation for example this part

public class MapPointActivity extends Fragment ....

It was good if you would call it MapPointFragment since it extends Fragment not Activity,(its a good design) especially for Future reference of the code.


来源: stackexchange

问:
Calculating CPU Utiliization for Round Robin Algorithm
I have been stuck on this for the past day. Im not sure how to calculate cpu utilization percentage for processes using round robin algorithm.

Let say we have these datas with time quantum of 1. Job Letter followed by arrival and burst time. How would i go about calculating the cpu utilization? I believe the formula is

total burst time / (total burst time + idle time). I know idle time means when the cpu are not busy but not sure how to really calculate it the processes. If anyone can walk me through it, it is greatly appreciated

```<code>A 2 6
B 3 1
C 5 9
D 6 7
E 7 10
</code>```

答:
Well,The formula is correct but in order to know the total-time you need to know the idle-time of CPU and you know when your CPU becomes idle? During the context-swtich it becomes idlt and it depends on short-term-scheduler how much time it take to assign the next proccess to CPU.

In 10-100 milliseconds of time quantua , context swtich time is arround 10 microseconds which is very small factor , now you can guess the context-switch time with time quantum of 1 millisecond. It will be ignoreable but it also results in too many context-switches.

ContentLicense: CC BY-SA 3.0

Body:
I have been stuck on this for the past day. Im not sure how to calculate cpu utilization percentage for processes using round robin algorithm.

Let say we have these datas with time quantum of 1. Job Letter followed by arrival and burst time. How would i go about calculating the cpu utilization? I believe the formula is

total burst time / (total burst time + idle time). I know idle time means when the cpu are not busy but not sure how to really calculate it the processes. If anyone can walk me through it, it is greatly appreciated

A 2 6
B 3 1
C 5 9
D 6 7
E 7 10


问:
How to enter values from inputbox in excel and store them in newline using vbscript every time
I am trying to add values from an InputBox to Excel worksheet cells which I have  created using VBScript.

I am able to store values in worksheet cells whenever I am entering the values in InputBox but my issue is that I have hardcoded the cell values and by using that I have assigned values to my InputBox that where to put the InputBox data in worksheet cells so whenever I am running my vbs file it is replacing the old values stored in those particular cells but instead I want to make it like every time I run my VBScript it will store the InputBox data in a new line and will also keep the old entries in worksheet cells saved but I am not sure how to do that.

Below is my code for your reference:

```<code>sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

  objExcel.Cells(1,1).Value= sInput
  objExcel.Cells(1,2).Value= sInput1

objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
</code>```

答:
Something like this does what you are after.  You can adapt your code accordingly

```<code>Sub Test()

Dim rg As Range, lr As Long

Set rg = Sheet1.Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = "Me"
    .Offset(lr, 1).Value = "You"
End With
End Sub
</code>```

In reference to your code:

```<code>Dim ws as worksheet
set ws = objWorkbook.Worksheets("Your Sheet Name")

dim rg as range
set rg = ws.range("A1")

Dim lr as Long
lr = rg.CurrentRegion.Rows.Count

With rg
  .Offset(lr, 0).Value = sInput
  .Offset(lr, 1).Value = sInput1
End With
</code>```

Body:
I am trying to add values from an InputBox to Excel worksheet cells which I have  created using VBScript.

I am able to store values in worksheet cells whenever I am entering the values in InputBox but my issue is that I have hardcoded the cell values and by using that I have assigned values to my InputBox that where to put the InputBox data in worksheet cells so whenever I am running my vbs file it is replacing the old values stored in those particular cells but instead I want to make it like every time I run my VBScript it will store the InputBox data in a new line and will also keep the old entries in worksheet cells saved but I am not sure how to do that.

Below is my code for your reference:

sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

  objExcel.Cells(1,1).Value= sInput
  objExcel.Cells(1,2).Value= sInput1

objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

Body:
Something like this does what you are after.  You can adapt your code accordingly

Sub Test()

Dim rg As Range, lr As Long

Set rg = Sheet1.Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = "Me"
    .Offset(lr, 1).Value = "You"
End With
End Sub

In reference to your code:

Dim ws as worksheet
set ws = objWorkbook.Worksheets("Your Sheet Name")

dim rg as range
set rg = ws.range("A1")

Dim lr as Long
lr = rg.CurrentRegion.Rows.Count

With rg
  .Offset(lr, 0).Value = sInput
  .Offset(lr, 1).Value = sInput1
End With


问:
Using comma-formatted numbers for DecimalField in Wagtail page admin
I have a request from a client to have page admin fields that they can add/read numbers into  with commas such as 1,000,000.

The Django model field to store the value would be a django.db.models.fields.DecimalField instance.

From looking at the Django docs, this is something that’s supported by the django.forms.fields.DecimalField localized property, but I can’t find a way of enforcing it in the Wagtail admin, even when subclassing the Wagtail BaseFieldPanel __init__ function with self.bound_field.field.localize = True.

答:
You can override the fields that Wagtail FieldPanel uses by customising generated forms documented here:

http://docs.wagtail.io/en/v1.13/advanced_topics/customisation/page_editing_interface.html#wagtail.wagtailadmin.forms.WagtailAdminPageForm

Basic example below - myapp/models.py

```<code>from django import forms
from django.db import models

from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.forms import WagtailAdminPageForm
from wagtail.wagtailcore.models import Page

class MyCustomPageForm(WagtailAdminPageForm):
    # fields here are django.forms fields
    # when set to localize, renders as a TextInput widget
    total_amount = forms.DecimalField(localize=True)

    # when left with defaults, renders as a NumberInput widget
    # total_amount = forms.DecimalField()

    # can also set any kind of widget here
    # total_amount = forms.DecimalField(widget=MyCustomDecimalWidget)

class MyCustomPage(Page):
    # fields here are django.db.models fields
    total_amount = models.DecimalField()
    content_panels = Page.content_panels + [
        FieldPanel('total_amount'),
    ]
    base_form_class = MyCustomPageForm # important: must set this
</code>```

When you set the form field to localize=True it appears to follow the intended behaviour as per the Django Docs which is to render a TextInput widget.

You could also set your own widget for any field in your page's form class if you want to do some more complicated functionality.

Body:
You can override the fields that Wagtail FieldPanel uses by customising generated forms documented here:

http://docs.wagtail.io/en/v1.13/advanced_topics/customisation/page_editing_interface.html#wagtail.wagtailadmin.forms.WagtailAdminPageForm

Basic example below - myapp/models.py

from django import forms
from django.db import models

from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.forms import WagtailAdminPageForm
from wagtail.wagtailcore.models import Page

class MyCustomPageForm(WagtailAdminPageForm):
    # fields here are django.forms fields
    # when set to localize, renders as a TextInput widget
    total_amount = forms.DecimalField(localize=True)

    # when left with defaults, renders as a NumberInput widget
    # total_amount = forms.DecimalField()

    # can also set any kind of widget here
    # total_amount = forms.DecimalField(widget=MyCustomDecimalWidget)

class MyCustomPage(Page):
    # fields here are django.db.models fields
    total_amount = models.DecimalField()
    content_panels = Page.content_panels + [
        FieldPanel('total_amount'),
    ]
    base_form_class = MyCustomPageForm # important: must set this

When you set the form field to localize=True it appears to follow the intended behaviour as per the Django Docs which is to render a TextInput widget.

You could also set your own widget for any field in your page's form class if you want to do some more complicated functionality.


答:
Use the below lines of codes

```<code>    var firstArray = NSMutableArray()
    var secondArray = NSMutableArray()

    for i in 0 ..< data.count{
        if (data.object(at: i) as AnyObject).value(forKey: "status") as? Int != nil {
            if (data.object(at: i) as AnyObject).value(forKey: "status") as! Int == 1 {
                let dummyDict = data.object(at: i) as! NSMutableDictionary
                firstArray.add(dummyDict)
            } else if (data.object(at: i) as AnyObject).value(forKey: "status") as! Int == 2 {
                let dummyDict = data.object(at: i) as! NSMutableDictionary
                secondArray.add(dummyDict)
            }
        }
    }
</code>```

Hope that will help you :)

Title: How to find value from dictionary

Body:
I have following simple dictionary and I want latitude array when status 1 it is store one array and status 2 it store second array
Please help me out

 data =     (
            {
        created = "2017-11-13 09:04:18";
        "end_date" = "2017-11-13 11:49:08";
        id = 878;
        latitude = "23.032190322875977000";
        longitude = "72.565238952636720000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 11:49:08";
        "end_date" = "2017-11-13 13:13:15";
        id = 888;
        latitude = "23.032133102416992000";
        longitude = "72.565208435058600000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:13:15";
        "end_date" = "2017-11-13 13:26:26";
        id = 891;
        latitude = "23.032199859619140000";
        longitude = "72.565269470214840000";
        status = 2;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:26:26";
        "end_date" = "2017-11-13 16:54:20";
        id = 892;
        latitude = "23.032056808471680000";
        longitude = "72.565223693847660000";
        status = 2;
        "user_id" = 21;
    }

)

Body:
Use the below lines of codes

    var firstArray = NSMutableArray()
    var secondArray = NSMutableArray()

    for i in 0 ..< data.count{
        if (data.object(at: i) as AnyObject).value(forKey: "status") as? Int != nil {
            if (data.object(at: i) as AnyObject).value(forKey: "status") as! Int == 1 {
                let dummyDict = data.object(at: i) as! NSMutableDictionary
                firstArray.add(dummyDict)
            } else if (data.object(at: i) as AnyObject).value(forKey: "status") as! Int == 2 {
                let dummyDict = data.object(at: i) as! NSMutableDictionary
                secondArray.add(dummyDict)
            }
        }
    }

Hope that will help you :)


问:
What does synchronous vs asynchronous loading mean?
Reading from this site, I understand that using commonjs means that when the browser finishes downloading your files, it will have to load them up 1 by 1 as they depend on each other. But with AMD, it can load multiple ones at the same time so that even if file a depends on file b, it part of file a can be executed before file b is finished?

CommonJS Modules: The dominant implementation of this standard is in
  Node.js (Node.js modules have a few features that go beyond CommonJS).
  Characteristics: Compact syntax Designed for synchronous loading and
  servers

Asynchronous Module Definition (AMD): The most popular
  implementation of this standard is RequireJS. Characteristics:
  Slightly more complicated syntax, enabling AMD to work without eval()
  (or a compilation step) Designed for asynchronous loading and browsers

答:
The syntax with CommonJS in loading modules is as such:

```<code>var MyModule = require("MyModule");
</code>```

As you can see, this will block the thread until the module is downloaded, from either your filesystem or the web. This is called synchronous loading. This is impossible to achieve in a normal web browser environment without affecting user experience, since we cannot block the thread as the browser uses the thread to update the graphics.

With RequireJS, it's done as such:

```<code>// In your module
define(["dependencies", ...], function(){
    return MyModule;
})

// In your web page
require(["dependencies", ...], function(MyModules, ...){
    // do stuff here
});
</code>```

With this model, our web page does not depend on the timing of when the module should be loaded. We can load our scripts in parallel while the page is still being loaded. This is called asynchronous loading. Once the scripts are loaded, they will call define which notifies RequireJS that the scripts are indeed loaded and executed. RequireJS will then call your main function and pass in the initialized modules.

Body:
The syntax with CommonJS in loading modules is as such:

var MyModule = require("MyModule");

As you can see, this will block the thread until the module is downloaded, from either your filesystem or the web. This is called synchronous loading. This is impossible to achieve in a normal web browser environment without affecting user experience, since we cannot block the thread as the browser uses the thread to update the graphics.

With RequireJS, it's done as such:

// In your module
define(["dependencies", ...], function(){
    return MyModule;
})

// In your web page
require(["dependencies", ...], function(MyModules, ...){
    // do stuff here
});

With this model, our web page does not depend on the timing of when the module should be loaded. We can load our scripts in parallel while the page is still being loaded. This is called asynchronous loading. Once the scripts are loaded, they will call define which notifies RequireJS that the scripts are indeed loaded and executed. RequireJS will then call your main function and pass in the initialized modules.


问:
Angular 4 change provider behavior
I have a Tournament class like:

```<code>class Tournament{
  id: number;
  name: string;
  ...
  state: string;
}
</code>```

I have three components like:

hidden-tournament

playing-tournament

finished-tournament

They all have same template and some shared methods like changeName() or delete(), but also have differences like addTeam(team: Team) just on hidden-tournament or finish() on playing-tournament.

I want to change that to a unique tournament with all shared and particular methods, and delegate the behavior to a service, but I don't know how to tell the service to act differently for each state of the tournament.

答:
Instead of making three components, you could make one component and name it 'TournamentComponent'.

```<code>  //TournamentComponent.ts

  import { Component,OnInit } from '@angular/core';
  import {  ActivatedRoute } from '@angular/router';

 @Component({
  selector: 'tournament-component',
  template: `
        <div *ngIf="hiddenTournament"> Hidden Tournament HTML </div>
        <div *ngIf="playingTournament"> Playing Tournament HTML </div>
        <div *ngIf="finishedTournament"> Finished Tournament HTM</div>

         `
  })

  export class TournamentComponent implements OnInit {
  finishedTournament:  boolean = false;
  playingTournament: boolean = false;
  hiddenTournament: boolean = false;

  constructor(private route: ActivatedRoute) {}
  ngOnInit() {

  this.route.data.subscribe(v => {
  if(v['type'] === 'finished') {
   this.finishedTournament = true;
   //make others false

   } else if(v['type'] === 'hidden'){
   this.hiddenTournament = true;
   //make others false

  }
  else {
   this.playingTournament = true;
   //make others false
   }

  }
</code>```

Respectively, you can make these changes in routes.

```<code>  //Routes.ts
  {path: 'tournament/finish',
         component: TournamentComponent,
         data: {type: 'finished'}
   },

   {path: 'tournament/hidden',
         component: TournamentComponent,
         data: {type: 'hidden'}
   },

   {path: 'tournament/playing',
         component: TournamentComponent,
         data: {type: 'playing'}
   }
</code>```

If you have long html, you could use a separate child component for each of them and emit the events respectively to the parent component TournamentComponent. You can achieve such as a sample given below.

```<code>       //hidden Tournament Component
        <hidden-tournament (onChangeName)="changeName()"
           *ngIf="hiddenTournament">

           </hidden-tournament>

        //Hidden  Tournament Component
        @Component({
        selector: 'hidden-tournament',
        template: `
                 hidden html content
                 <button (click)="saveName("testName")"></button>
                 `
        })

        export class HiddenTournamentComponent {
          @Ouput() onChangeName: EventEmitter<any>;

          saveName(name){
          this.onChangeName(name);
          }

         }
</code>```

Title: Angular 4 change provider behavior

Body:
I have a Tournament class like:

class Tournament{
  id: number;
  name: string;
  ...
  state: string;
}

I have three components like:

hidden-tournament

playing-tournament

finished-tournament

They all have same template and some shared methods like changeName() or delete(), but also have differences like addTeam(team: Team) just on hidden-tournament or finish() on playing-tournament.

I want to change that to a unique tournament with all shared and particular methods, and delegate the behavior to a service, but I don't know how to tell the service to act differently for each state of the tournament.

Body:
Instead of making three components, you could make one component and name it 'TournamentComponent'.

  //TournamentComponent.ts

  import { Component,OnInit } from '@angular/core';
  import {  ActivatedRoute } from '@angular/router';

 @Component({
  selector: 'tournament-component',
  template: `
        <div *ngIf="hiddenTournament"> Hidden Tournament HTML </div>
        <div *ngIf="playingTournament"> Playing Tournament HTML </div>
        <div *ngIf="finishedTournament"> Finished Tournament HTM</div>

         `
  })

  export class TournamentComponent implements OnInit {
  finishedTournament:  boolean = false;
  playingTournament: boolean = false;
  hiddenTournament: boolean = false;

  constructor(private route: ActivatedRoute) {}
  ngOnInit() {

  this.route.data.subscribe(v => {
  if(v['type'] === 'finished') {
   this.finishedTournament = true;
   //make others false

   } else if(v['type'] === 'hidden'){
   this.hiddenTournament = true;
   //make others false

  }
  else {
   this.playingTournament = true;
   //make others false
   }

  }

Respectively, you can make these changes in routes.

  //Routes.ts
  {path: 'tournament/finish',
         component: TournamentComponent,
         data: {type: 'finished'}
   },

   {path: 'tournament/hidden',
         component: TournamentComponent,
         data: {type: 'hidden'}
   },

   {path: 'tournament/playing',
         component: TournamentComponent,
         data: {type: 'playing'}
   }

If you have long html, you could use a separate child component for each of them and emit the events respectively to the parent component TournamentComponent. You can achieve such as a sample given below.

       //hidden Tournament Component
        <hidden-tournament (onChangeName)="changeName()"
           *ngIf="hiddenTournament">

           </hidden-tournament>

        //Hidden  Tournament Component
        @Component({
        selector: 'hidden-tournament',
        template: `
                 hidden html content
                 <button (click)="saveName("testName")"></button>
                 `
        })

        export class HiddenTournamentComponent {
          @Ouput() onChangeName: EventEmitter<any>;

          saveName(name){
          this.onChangeName(name);
          }

         }


问:
What does it mean to recycle the dynamic memory?
I learned about ‘free’ which is used after malloc not to make garbage memory in C. What’s recycle? I looked up for it but could not find any code. All I got is the explanation about free.. Are they the same?

To add, in my book about data structure (general linear lists) says that “Recycle is a pseudocode command to return a node’s space to dynamic memory.

Thanks a lot.

I will discard the picture if there is any problem with the license.

答: I had a look at the phrase you mentioned in google books. What they have meant is that they assume that they have already defined a function or pseudocode, void recycle(node *ploc), where ploc is the node we no longer need in the linked list. And yes, it is similar to doing free or delete on ploc. We can either directly do it in the current function or do it in a separate function like recycle.</p>


问:
How can I replace a the pattern ",," with <RETURN> in awk?
I am doing a ldapsearch query which returns the results as follow

```<code>John Joe jjoe@company.com +1 916 662-4727  Ann Tylor Atylor@company.com (987) 654-3210  Steve Harvey sharvey@company.com 4567893210  (321) 956-3344  ...
</code>```

As you can see between each personal record output there is a blank space and the phone numbers might start with +1 or not and might have blank between the numbers or parenthesis and finally between personal records there are two blank spaces. For example:

I would like to transform these entries to the following format:

```<code>John,Joe,jjoe@company.com,(916) 662-4727
Ann,Tylor,Atylor@company.com,(987) 654-3210
Steve,Harvey,sharvey@company.com,(456) 789-3210,(321) 956-3344
...
</code>```

So basically replace the one blanks with one comma "," and two blanks with , so that at the end I have one personal record (comma separated) per line. Example:

I am trying awk and have managed to replace  with "," which makes

```<code><blank><blank> to double comma ",,".
But can't figure out how to turn ",," to <RETURN>
</code>```

11/22/2017      ----******  UPDATE   ******---------           11/22/2017

I made this track too crowded. I will post a fresh questions with more details.

Body:
I am doing a ldapsearch query which returns the results as follow

John Joe jjoe@company.com +1 916 662-4727  Ann Tylor Atylor@company.com (987) 654-3210  Steve Harvey sharvey@company.com 4567893210  (321) 956-3344  ...

As you can see between each personal record output there is a blank space and the phone numbers might start with +1 or not and might have blank between the numbers or parenthesis and finally between personal records there are two blank spaces. For example:

I would like to transform these entries to the following format:

John,Joe,jjoe@company.com,(916) 662-4727
Ann,Tylor,Atylor@company.com,(987) 654-3210
Steve,Harvey,sharvey@company.com,(456) 789-3210,(321) 956-3344
...

So basically replace the one blanks with one comma "," and two blanks with , so that at the end I have one personal record (comma separated) per line. Example:

I am trying awk and have managed to replace  with "," which makes

<blank><blank> to double comma ",,".
But can't figure out how to turn ",," to <RETURN>

11/22/2017      ----******  UPDATE   ******---------           11/22/2017

I made this track too crowded. I will post a fresh questions with more details.

Body:
Just for your interest, you could say with Perl:

perl -e '
while (<>) {
    s/  /\n/g;
    s/ /,/g;
    s/(\+1,)?\(?(\d{3})\)?[-,]?(\d{3})[-,]?(\d{4})/($2) $3-$4/g;
    print;
}' file


问:
Bash script to automate Git pull
I want to automatically pull from Git. For some reasons it is not possible to automate the password thing in the server I am using. So it needs to be done by a Bash file. Now my Bash coding is not that good. Then it is possible to enter the passphrase for the SSH key. But I have really no clue what to do...

#!/bin/bash
cd . public_html/auto_deploy/foldername && git fetch --all && git checkout --force "origin/master"

The above is not working... And then it needs to enter the passphrase, and I have no idea what to do then... How can I do this?

答:
If you want to do Git pull from a shell script, you need to use it like this:</p>

```<code>git pull https://username:password@git_hostname.com/my/repository
</code>```

ContentLicense: CC BY-SA 4.0

Title: Bash script to automate Git pull

Body:
If you want to do Git pull from a shell script, you need to use it like this:

git pull https://username:password@git_hostname.com/my/repository


问:
How to pick top value from tie-break group using Unix sort
I have the following text file:

```<code>$ cat myfile.txt
foo,a,10
bar,c,33
foo,b,50
bar,a,9
foo,a,20
bar,b,20
</code>```

What I want to do is to sort by 2nd column and 3rd (numeric descending) and finally pick the top of each 2nd column group, resulting in

```<code>foo,a,20
foo,b,50
bar,c,33
</code>```

I'm stuck with this:

```<code>$ sort -t"," -k2 -k3r   test.txt
foo,a,10
foo,a,20
bar,a,9
bar,b,20
foo,b,50
bar,c,33
</code>```

Whats the right way to do it?

答:
Here's pure awk method to do that,

```<code> awk -F, '{split(a[$2],b,",");if(b[3]<$3)a[$2]=$0}END{for(i in a)print [i]}' myfile.txt
</code>```

Brief explanation,

split(a[$2],b,","): split each record separated by ',', and save each field to array b.

if(b[3]<$3)a[$2]=$0: compare b[3] and $3 to determine if a[$2] needs to be updated

Print all content in array a in the last.

Body:
I have the following text file:

$ cat myfile.txt
foo,a,10
bar,c,33
foo,b,50
bar,a,9
foo,a,20
bar,b,20

What I want to do is to sort by 2nd column and 3rd (numeric descending) and finally pick the top of each 2nd column group, resulting in

foo,a,20
foo,b,50
bar,c,33

I'm stuck with this:

$ sort -t"," -k2 -k3r   test.txt
foo,a,10
foo,a,20
bar,a,9
bar,b,20
foo,b,50
bar,c,33

Whats the right way to do it?

Body:
Here's pure awk method to do that,

 awk -F, '{split(a[$2],b,",");if(b[3]<$3)a[$2]=$0}END{for(i in a)print [i]}' myfile.txt

Brief explanation,

split(a[$2],b,","): split each record separated by ',', and save each field to array b.

if(b[3]<$3)a[$2]=$0: compare b[3] and $3 to determine if a[$2] needs to be updated

Print all content in array a in the last.


问:
Unsupported element in Slideshow (Facebook Instant Articles)
I have an issue with Facebook Instant Articles validation. For one of my articles this error message pops up:

Slideshow Contains Unsupported Elements: Only image elements can appear in a slideshow. Ensure that slideshow (at /html/body/article/figure[3]) only contains supported elements. Refer to Slideshows under Format Reference in Instant Articles documentation for more information.

Here's the code:

```<code><figure class="op-slideshow">
    <figure>
        <img src="https://www.example.com/image1.jpg">
        <figcaption>Caption1</figcaption>
    </figure>
    <figure>
        <img src="https://www.example.com/image2.jpg">
        <figcaption>Caption2</figcaption>
    </figure>
</figure>
</code>```

It was generated by the official PHP SDK, and in the example they are using very similar structure. (http://take.ms/nookv) Is this a bug?

答:
you can't add a figcaption for each slide, only images can be enclosed within the inner  tags.
Correct format would be:</p>

```<code><figure class="op-slideshow">
  <figure>
    <img src="http://example.com/path/to/img1.jpg" />
  </figure>
  <figure>
    <img src="http://example.com/path/to/img2.jpg" />
  </figure>
  <figure>
    <img src="http://example.com/path/to/img3.jpg" />
  </figure>
  <figcaption>This slideshow is amazing.</figcaption>
</figure>
</code>```

Body:
I have an issue with Facebook Instant Articles validation. For one of my articles this error message pops up:

Slideshow Contains Unsupported Elements: Only image elements can appear in a slideshow. Ensure that slideshow (at /html/body/article/figure[3]) only contains supported elements. Refer to Slideshows under Format Reference in Instant Articles documentation for more information.

Here's the code:

Caption1

Caption2

It was generated by the official PHP SDK, and in the example they are using very similar structure. (http://take.ms/nookv) Is this a bug?

Body:
you can't add a figcaption for each slide, only images can be enclosed within the inner  tags.
Correct format would be:

<figure class="op-slideshow">
  <figure>
    <img src="http://example.com/path/to/img1.jpg" />
  </figure>
  <figure>
    <img src="http://example.com/path/to/img2.jpg" />
  </figure>
  <figure>
    <img src="http://example.com/path/to/img3.jpg" />
  </figure>
  <figcaption>This slideshow is amazing.</figcaption>
</figure>


问:
Question about TCP states for a webserver process - Why is it always on LISTENING state?
I'm learning in-depth TCP now and I didn't understand the TCP lifecycle of a server process.
Supposed I'm running a web server on port 80, when I use netstat to view the connection, I see it listens on port 80, as it should be.
When new clients connects to my server, a new socket is created between the client and the server and the this socket is moving through the normal lifecycle (as described on the TCP RFC, or here http://www.sdsusa.com/connections/ ). this is perfectly understood considering TCP's demultiplexing abilities.

My question is: is the TCP connection that listens on port 80 follows the same lifecycle? I tried monitoring it but it stuck on LISTENING.

答:
The listening socket always stays in "listening" state. When a new connection arrives, the listening socket is cloned, and the clone is put into "established" state and returned from the accept() call (or equivalent thereof). The original is left in listening state so that the application can poll it again for new connections.

Strictly speaking, the listening socket doesn't correspond to a "TCP connection" at all- it represents a potential TCP connection. Only the sockets returned from accept() represent real connections.

ContentLicense: CC BY-SA 2.5


问:
Why we use null in sqlite methods?
Why we use null in sqlite database methods like:

```<code>db.insert("table1", null, cv);
</code>```

Is it necessary use it in methods?
Without null we have error.

答:
Read insert

```<code>long insert (String table,
                String nullColumnHack,
                ContentValues values)
</code>```

String nullColumnHack : optional; may be null. SQL doesn't allow inserting a
  completely empty row without naming at least one column name. If your
  provided values is empty, no column names are known and an empty row
  can't be inserted. If not set to null, the nullColumnHack parameter
  provides the name of nullable column name to explicitly insert a NULL
  into in the case where your values is empty.

Title: Why we use null in sqlite methods?

Body:
Why we use null in sqlite database methods like:

db.insert("table1", null, cv);

Is it necessary use it in methods?
Without null we have error.

Body:
Read insert

long insert (String table,
                String nullColumnHack,
                ContentValues values)

String nullColumnHack : optional; may be null. SQL doesn't allow inserting a
  completely empty row without naming at least one column name. If your
  provided values is empty, no column names are known and an empty row
  can't be inserted. If not set to null, the nullColumnHack parameter
  provides the name of nullable column name to explicitly insert a NULL
  into in the case where your values is empty.


问:
How can I get google+ user profile details, given the access token and refresh token
Using google API

function googleLogin(req, res, next) {

    var google = require('googleapis');
    var plus = google.plus('v1');
    SCOPES = 'https://mail.google.com';
    var OAuth2 = google.auth.OAuth2;
    var oauth2Client = new OAuth2(
        '215995260545-6rp2pg69olionsiugudcl4fni3o36ap9.apps.googleusercontent.com',
        'xxxxxxxxxxxxxxxxxxxxxxxx',
        'https://developers.google.com/oauthplayground'
    );

    oauth2Client.setCredentials({
        access_token: req.query.ac_token,
        refresh_token: req.query.rf_token
    });
    plus.people.get({
        userId: 'me',
        auth: oauth2Client
    }, function(err, response) {
        if (err) console.log(err);
        console.log(response);
    });
}```
</div>
</div>
</p>

<p>When I run this code, I am getting the error like <code>**insufficient permission**</code>. Am I wrong anywhere??</p>

``` "code": 403,
    "errors": [
        {
            "domain": "global",
            "reason": "insufficientPermissions",
            "message": "Insufficient Permission"
        }
    ]
```

How can I solve this problem?? I have also referred the Gmail API scopes.

答:
The main part of your problem is that you are using the wrong endpoint https://developers.google.com/oauthplayground is not something you can use to my knowlage

How you should be doing it

try adding the following scope

profile - View your basic profile info

You also shouldnt have to go though the google+ api you may be able to request the info from the userinfo endpoint but it depends on what info you are after

https://www.googleapis.com/oauth2/v3/userinfo?access_token=XXX

UserInfo Response

```<code>{
  "family_name": "Lawton",
  "name": "Linda Lawton",
  "picture": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg",
  "locale": "en",
  "gender": "female",
  "link": "https://plus.google.com/+LindaLawton",
  "given_name": "Linda",
  "id": "117200475532672775346"
}
</code>```

People api request

```<code>https://www.googleapis.com/plus/v1/people/me
</code>```

Response

```<code>{
  "braggingRights": "Extreme Beekeeper first to recorded an Hive inspection using Google Glass with out a veil on.",
  "image": {
    "url": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg?sz=50",
    "isDefault": false
  },
  "id": "117200475532672775346",
  "objectType": "person",
  "verified": false,
  "tagline": "Google Developer Expert 2014 - 2017",
  "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/0gZZ-LRb-PWLjbw12lr-IOAearE\"",
  "circledByCount": 2514,
  "occupation": "Google Developer Expert, BIA Developer at Targit",
  .....  Lots of stuff here ...
  }
</code>```

You should try testing using the Oauth playground

Body:
Using google API

function googleLogin(req, res, next) {

    var google = require('googleapis');
    var plus = google.plus('v1');
    SCOPES = 'https://mail.google.com';
    var OAuth2 = google.auth.OAuth2;
    var oauth2Client = new OAuth2(
        '215995260545-6rp2pg69olionsiugudcl4fni3o36ap9.apps.googleusercontent.com',
        'xxxxxxxxxxxxxxxxxxxxxxxx',
        'https://developers.google.com/oauthplayground'
    );

    oauth2Client.setCredentials({
        access_token: req.query.ac_token,
        refresh_token: req.query.rf_token
    });
    plus.people.get({
        userId: 'me',
        auth: oauth2Client
    }, function(err, response) {
        if (err) console.log(err);
        console.log(response);
    });
}

When I run this code, I am getting the error like **insufficient permission**. Am I wrong anywhere??

 "code": 403,
    "errors": [
        {
            "domain": "global",
            "reason": "insufficientPermissions",
            "message": "Insufficient Permission"
        }
    ]

How can I solve this problem?? I have also referred the Gmail API scopes.

Body:
The main part of your problem is that you are using the wrong endpoint https://developers.google.com/oauthplayground is not something you can use to my knowlage

How you should be doing it

try adding the following scope

profile - View your basic profile info

You also shouldnt have to go though the google+ api you may be able to request the info from the userinfo endpoint but it depends on what info you are after

https://www.googleapis.com/oauth2/v3/userinfo?access_token=XXX

UserInfo Response

{
  "family_name": "Lawton",
  "name": "Linda Lawton",
  "picture": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg",
  "locale": "en",
  "gender": "female",
  "link": "https://plus.google.com/+LindaLawton",
  "given_name": "Linda",
  "id": "117200475532672775346"
}

People api request

https://www.googleapis.com/plus/v1/people/me

Response

{
  "braggingRights": "Extreme Beekeeper first to recorded an Hive inspection using Google Glass with out a veil on.",
  "image": {
    "url": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg?sz=50",
    "isDefault": false
  },
  "id": "117200475532672775346",
  "objectType": "person",
  "verified": false,
  "tagline": "Google Developer Expert 2014 - 2017",
  "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/0gZZ-LRb-PWLjbw12lr-IOAearE\"",
  "circledByCount": 2514,
  "occupation": "Google Developer Expert, BIA Developer at Targit",
  .....  Lots of stuff here ...
  }

You should try testing using the Oauth playground


问:
(Python3.6 using cx_Freeze) Exe does not run pandas, numpy application
I wrote a .py script called Expiration_Report.py using the following libraries: pandas, numpy. This code runs perfectly fine when executed in Spyder(python 3.6).

(Using Anaconda for everything)

I then created another .py file called 'setup.py' with the following code in order to convert Expiration_Report.py to Expiration_Report.exe:

```<code>    import sys
    from cx_Freeze import setup, Executable

    # Dependencies are automatically detected, but it might need fine tuning.
      build_exe_options = {"packages": ["os"],
                 "excludes": ["tkinter"]}

    # GUI applications require a different base on Windows (the default is for a
    # console application).
    base = None
    if sys.platform == "win32":
        base = "console"

    setup(  name = "my prog",
        version = "1.0",
        description = "My application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("Expiration_Report.py", base = base)])
</code>```

Then in the command prompt I write:

```<code>    python setup.py build
</code>```

It builds without any errors. And the build folder is available with the .exe file as well. However, when I run the .exe file from the build folder: nothing happens.

Here is the code from the Expiration_Report.py script:

```<code>    import pandas as pd
    import numpy as np

    df = pd.read_excel('C:/Users/Salman/Desktop/WIP Board - 007.xlsx',                         index_col=None, na_values=['NA'])

    df.columns = df.iloc[12]
    df.columns

    df.shape

    df = df.dropna(axis=1, how = 'all')
    df

    df.columns

    df1 = df.copy()
    df1 = df1.iloc[13:]
    df1

    df1 = df1.dropna(axis=1, how = 'all')
    df1.shape

    from datetime import datetime
    print(str(datetime.now()))

    df2 = df1.copy()
    df2["Now_Time"] = pd.Series([datetime.now()] * (13+len(df1)))

    df2["Now_Time"]

    df2

    df2.fillna(value='NaN')

    df2 = df2.dropna(how='any')

    df2.shape

    df3 = df2.copy()
    df3 = df3[df3.Size>0]
    df3['Lot Expiration Date'] = pd.to_datetime(df3['Lot Expiration Date'])

    df3['Days_Countdown'] = df3[['Lot Expiration Date']].sub(df3['Now_Time'], axis = 0 )

    df3.dtypes

    df3['Hours_Countdown'] = df3['Days_Countdown'] / np.timedelta64(1, 'h')

    df3 = df3.sort_values('Hours_Countdown')

    df_expiration = df3[df3.Hours_Countdown<12]

    df_expiration['Hours_Countdown'].astype(int)
    df_expiration

    df_expiration.to_excel('C:/Users/Salman/Desktop/WIP Board - 000.xlsx', sheet_name = 'Sheet1')
</code>```

The method for creating an exe file from cs_Freeze is correct. Because I converted a simple script HelloWorld.py to exe and it worked fine. It is not importing the pandas library and just exits the exe.

答:
Maybe you need to add pandas and numpy to the packages list. cx_freeze can be a bit dodgy when it comes to finding all the necessary packages.</p>

```<code>build_exe_options = {"packages": ["os", "numpy", "pandas"],
             "excludes": ["tkinter"]}
</code>```

Body:
I wrote a .py script called Expiration_Report.py using the following libraries: pandas, numpy. This code runs perfectly fine when executed in Spyder(python 3.6).

(Using Anaconda for everything)

I then created another .py file called 'setup.py' with the following code in order to convert Expiration_Report.py to Expiration_Report.exe:

    import sys
    from cx_Freeze import setup, Executable

    # Dependencies are automatically detected, but it might need fine tuning.
      build_exe_options = {"packages": ["os"],
                 "excludes": ["tkinter"]}

    # GUI applications require a different base on Windows (the default is for a
    # console application).
    base = None
    if sys.platform == "win32":
        base = "console"

    setup(  name = "my prog",
        version = "1.0",
        description = "My application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("Expiration_Report.py", base = base)])

Then in the command prompt I write:

    python setup.py build

It builds without any errors. And the build folder is available with the .exe file as well. However, when I run the .exe file from the build folder: nothing happens.

Here is the code from the Expiration_Report.py script:

    import pandas as pd
    import numpy as np

    df = pd.read_excel('C:/Users/Salman/Desktop/WIP Board - 007.xlsx',                         index_col=None, na_values=['NA'])

    df.columns = df.iloc[12]
    df.columns

    df.shape

    df = df.dropna(axis=1, how = 'all')
    df

    df.columns

    df1 = df.copy()
    df1 = df1.iloc[13:]
    df1

    df1 = df1.dropna(axis=1, how = 'all')
    df1.shape

    from datetime import datetime
    print(str(datetime.now()))

    df2 = df1.copy()
    df2["Now_Time"] = pd.Series([datetime.now()] * (13+len(df1)))

    df2["Now_Time"]

    df2

    df2.fillna(value='NaN')

    df2 = df2.dropna(how='any')

    df2.shape

    df3 = df2.copy()
    df3 = df3[df3.Size>0]
    df3['Lot Expiration Date'] = pd.to_datetime(df3['Lot Expiration Date'])

    df3['Days_Countdown'] = df3[['Lot Expiration Date']].sub(df3['Now_Time'], axis = 0 )

    df3.dtypes

    df3['Hours_Countdown'] = df3['Days_Countdown'] / np.timedelta64(1, 'h')

    df3 = df3.sort_values('Hours_Countdown')

    df_expiration = df3[df3.Hours_Countdown<12]

    df_expiration['Hours_Countdown'].astype(int)
    df_expiration

    df_expiration.to_excel('C:/Users/Salman/Desktop/WIP Board - 000.xlsx', sheet_name = 'Sheet1')

The method for creating an exe file from cs_Freeze is correct. Because I converted a simple script HelloWorld.py to exe and it worked fine. It is not importing the pandas library and just exits the exe.

Body:
Maybe you need to add pandas and numpy to the packages list. cx_freeze can be a bit dodgy when it comes to finding all the necessary packages.

build_exe_options = {"packages": ["os", "numpy", "pandas"],
             "excludes": ["tkinter"]}