问:
Node JS synchronous events
I am writing a node js program to read content from a file , I am executing this program multiple times in a short time. Sometimes I can see file content and sometimes I do not (PFA screenshot) , can anyone please explain why this is happening ? Is this because I am not using promises ?

```<code>var fs= require('fs');
fs.readFile('myData.json', (err, data) => {
  if(err)
    console.log('Error Found',err.code);
  else {
    console.log('inside else');
    fs.open('myData.json', 'wx', (err, fd) => {
      console.log('inside open file');
      fs.writeFile('myData.json','test data',(err)=>{
        if(err) console.log('error writing data');
      });
      fs.readFile('myData.json','utf8',(err, data) => {
        console.log('read file'+data);
      });
    });
  }
});
</code>```

Screen Shot :

答:
Can you try after fixing following code

```<code>fs.writeFile('myData.json','test data',(err)=>{
  if(err) console.log('error writing data');
  fs.readFile('myData.json','utf8',(err, data) => {
    console.log('read file'+data);
  });
});
</code>```

You have placed read file in async with write file. You need to read file after writing it.

Title: Node JS synchronous events

Body:
I am writing a node js program to read content from a file , I am executing this program multiple times in a short time. Sometimes I can see file content and sometimes I do not (PFA screenshot) , can anyone please explain why this is happening ? Is this because I am not using promises ?

var fs= require('fs');
fs.readFile('myData.json', (err, data) => {
  if(err)
    console.log('Error Found',err.code);
  else {
    console.log('inside else');
    fs.open('myData.json', 'wx', (err, fd) => {
      console.log('inside open file');
      fs.writeFile('myData.json','test data',(err)=>{
        if(err) console.log('error writing data');
      });
      fs.readFile('myData.json','utf8',(err, data) => {
        console.log('read file'+data);
      });
    });
  }
});

Screen Shot :

Body:
Can you try after fixing following code

fs.writeFile('myData.json','test data',(err)=>{
  if(err) console.log('error writing data');
  fs.readFile('myData.json','utf8',(err, data) => {
    console.log('read file'+data);
  });
});

You have placed read file in async with write file. You need to read file after writing it.


来源: stackexchange

问:
Angular - Copy array to modeled array
I need to make a custom array from an array receiving from an API Rest. I receive this model :

```<code>export interface AreaEstadistica {
  id_area_estadistica: String;
  nombre: String;
  id_distrito: String;
  calculos_estadisticos_pt: Array<CalculoEstadistico>;
}

export interface CalculoEstadistico {
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}
</code>```

And i want to make an array with the same fields, because in the object CalculoEstadistico I can receive so much information, and i need the 'header' for any register in CalculoEstadistico, something like this:

```<code>export interface AreaEstadistica2 {
  id_area_estadistica: String; //Header from this
  nombre: String;
  id_distrito: String;// To this
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}
</code>```

The service in Angular 5 :

```<code>getAreasEstadisticas(): Observable<AreaEstadistica[]> {
    let url: string = this.urlEstadisticas;
    console.log('URL' + url);
    return this._http.get<AreaEstadistica[]>(url);
  }
</code>```

I tried it by using a map in the component:

```<code>    areas: AreaEstadistica[] = [];
    areas2: AreaEstadistica2[] = [];
//...

getAreas() {
    this._EstadisticasService
      .getAreasEstadisticas()
      .subscribe(
        res => {
          this.areas = res;
          this.transformArray();
        },
        err => {
          console.log(err);
          alert('error');
        }
      );
  }
transformArray(){
    this.areas.map(item => {
            return {
               id_area_estadistica: item.id_area_estadistica,
               nombre: item.nombre,
               id_distrito: item.id_distrito,
               aa_ponencia_total: item.aa_ponencia_total,
               uso: item.calculos_estadisticos_pt[i].uso,
               valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
               valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
            };
        }).forEach(item => this.areas2.push(item));
}
</code>```

But this code don't work. One of the errors:

src/app/estadisticas/estadisticas.component.ts(129,57): error TS2304:
  Cannot find name 'i'.

Any ideas? I don't know how to access to the fields in the object CalculoEstadistico to map them:

```<code>uso: item.calculos_estadisticos_pt[i].uso,
valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
</code>```

Is there a way to copy a nested model array to another model array? Thanks!

答:
It looks like you want to add fields of a nested array in the main array.
e.g

```<code>arry1 = {
  name: 'suhel',
  id: 1,
  contact : {
    email: 'email',
    number: '123'
  }
}
</code>```

Now iterate the nested array like this

```<code>for(let key of Object.keys(arry1.contact)) {
  arry1[key] = arry1.contact[key];
}
</code>```

Now delete the contact field if you want

```<code>delete arry1["contact"];
</code>```

Then final result will be like this

```<code>arry1 = {
  email: "email"
  id: 1
  name: "suhel"
  number: "123"
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Angular - Copy array to modeled array

Body:
I need to make a custom array from an array receiving from an API Rest. I receive this model :

export interface AreaEstadistica {
  id_area_estadistica: String;
  nombre: String;
  id_distrito: String;
  calculos_estadisticos_pt: Array<CalculoEstadistico>;
}

export interface CalculoEstadistico {
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}

And i want to make an array with the same fields, because in the object CalculoEstadistico I can receive so much information, and i need the 'header' for any register in CalculoEstadistico, something like this:

export interface AreaEstadistica2 {
  id_area_estadistica: String; //Header from this
  nombre: String;
  id_distrito: String;// To this
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}

The service in Angular 5 :

getAreasEstadisticas(): Observable<AreaEstadistica[]> {
    let url: string = this.urlEstadisticas;
    console.log('URL' + url);
    return this._http.get<AreaEstadistica[]>(url);
  }

I tried it by using a map in the component:

    areas: AreaEstadistica[] = [];
    areas2: AreaEstadistica2[] = [];
//...

getAreas() {
    this._EstadisticasService
      .getAreasEstadisticas()
      .subscribe(
        res => {
          this.areas = res;
          this.transformArray();
        },
        err => {
          console.log(err);
          alert('error');
        }
      );
  }
transformArray(){
    this.areas.map(item => {
            return {
               id_area_estadistica: item.id_area_estadistica,
               nombre: item.nombre,
               id_distrito: item.id_distrito,
               aa_ponencia_total: item.aa_ponencia_total,
               uso: item.calculos_estadisticos_pt[i].uso,
               valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
               valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
            };
        }).forEach(item => this.areas2.push(item));
}

But this code don't work. One of the errors:

src/app/estadisticas/estadisticas.component.ts(129,57): error TS2304:
  Cannot find name 'i'.

Any ideas? I don't know how to access to the fields in the object CalculoEstadistico to map them:

uso: item.calculos_estadisticos_pt[i].uso,
valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo

Is there a way to copy a nested model array to another model array? Thanks!

Body:
It looks like you want to add fields of a nested array in the main array.
e.g

arry1 = {
  name: 'suhel',
  id: 1,
  contact : {
    email: 'email',
    number: '123'
  }
}

Now iterate the nested array like this

for(let key of Object.keys(arry1.contact)) {
  arry1[key] = arry1.contact[key];
}

Now delete the contact field if you want

delete arry1["contact"];

Then final result will be like this

arry1 = {
  email: "email"
  id: 1
  name: "suhel"
  number: "123"
}


问:
Changing whisker definition in geom_boxplot
I'm trying to use ggplot2 / geom_boxplot to produce a boxplot where the whiskers are defined as the 5 and 95th percentile instead of 0.25 - 1.5 IQR / 0.75 + IQR and outliers from those new whiskers are plotted as usual.  I can see that the geom_boxplot aesthetics include ymax / ymin, but it's not clear to me how I put values in here.  It seems like:

```<code>stat_quantile(quantiles = c(0.05, 0.25, 0.5, 0.75, 0.95))
</code>```

should be able to help, but I don't know how to relate the results of this stat to set the appropriate geom_boxplot() aesthetics:

```<code>geom_boxplot(aes(ymin, lower, middle, upper, ymax))
</code>```

I've seen other posts where people mention essentially building a boxplot-like object manually, but I'd rather keep the whole boxplot gestalt intact, just revising the meaning of two of the variables being drawn.

答:
geom_boxplot with stat_summary can do it:</p>

```<code># define the summary function
f <- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

# sample data
d <- data.frame(x=gl(2,50), y=rnorm(100))

# do it
ggplot(d, aes(x, y)) + stat_summary(fun.data = f, geom="boxplot")

# example with outliers
# define outlier as you want
o <- function(x) {
  subset(x, x < quantile(x)[2] | quantile(x)[4] < x)
}

# do it
ggplot(d, aes(x, y)) +
  stat_summary(fun.data=f, geom="boxplot") +
  stat_summary(fun.y = o, geom="point")
</code>```

Body:
I'm trying to use ggplot2 / geom_boxplot to produce a boxplot where the whiskers are defined as the 5 and 95th percentile instead of 0.25 - 1.5 IQR / 0.75 + IQR and outliers from those new whiskers are plotted as usual.  I can see that the geom_boxplot aesthetics include ymax / ymin, but it's not clear to me how I put values in here.  It seems like:

stat_quantile(quantiles = c(0.05, 0.25, 0.5, 0.75, 0.95))

should be able to help, but I don't know how to relate the results of this stat to set the appropriate geom_boxplot() aesthetics:

geom_boxplot(aes(ymin, lower, middle, upper, ymax))

I've seen other posts where people mention essentially building a boxplot-like object manually, but I'd rather keep the whole boxplot gestalt intact, just revising the meaning of two of the variables being drawn.

Body:
geom_boxplot with stat_summary can do it:

# define the summary function
f <- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

# sample data
d <- data.frame(x=gl(2,50), y=rnorm(100))

# do it
ggplot(d, aes(x, y)) + stat_summary(fun.data = f, geom="boxplot")

# example with outliers
# define outlier as you want
o <- function(x) {
  subset(x, x < quantile(x)[2] | quantile(x)[4] < x)
}

# do it
ggplot(d, aes(x, y)) +
  stat_summary(fun.data=f, geom="boxplot") +
  stat_summary(fun.y = o, geom="point")

ContentLicense: CC BY-SA 2.5


问:
AutoCompleteTextView on MapActivity is not working
I'm new to the Android Development and I'm trying to accomplish a Android application, Where I can Search the Places using Auto-Complete and mark that place on a Google Map.

Here's my activity_city_maps.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout_map_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CityMapsActivity">

    <AutoCompleteTextView
        android:id="@+id/editText_source"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="Select Source"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toStartOf="@+id/button_source_update"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_source_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:text="Set Source"
        app:layout_constraintBaseline_toBaselineOf="@+id/editText_source"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/editText_source" />

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_source_update"
        tools:context=".CityMapsActivity" />

</android.support.constraint.ConstraintLayout>
</code>```

And here my CityMapsActivity.java file

```<code>package com.softvision.gotogether.app;

//Imports hidden

public class CityMapsActivity extends FragmentActivity implements
        GoogleMap.OnMyLocationButtonClickListener,
        GoogleMap.OnMyLocationClickListener,
        OnMapReadyCallback,
        OnRequestPermissionsResultCallback,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleApiClient.ConnectionCallbacks{

    /* AUTO-COMPLETE PROPERTIES
    * ----------------------------------------------------------------------------------------------*/
    private static final String LOG_TAG = "CityMapsActivity";
    private GoogleApiClient client;
    private static final int GOOGLE_API_CLIENT_ID = 0;
    private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
            new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
    private PlaceArrayAdapter mPlaceArrayAdapter;
    private AutoCompleteTextView editTextSource;

    /* MAP PROPERTIES
    * ----------------------------------------------------------------------------------------------*/
    private GoogleMap mMap;
    private ArrayList<LatLng> markerPoints = new ArrayList<>();
    //Request code for location permission request.
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    //Flag indicating whether a requested permission has been denied after returning in
    private boolean mPermissionDenied = false;

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

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

        // Location Auto complete
        client = new GoogleApiClient.Builder(CityMapsActivity.this)
                .addApi(Places.GEO_DATA_API)
                .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                .addConnectionCallbacks(this)
                .build();

        editTextSource = (AutoCompleteTextView) findViewById(R.id.editText_source);
        editTextSource.setThreshold(3);

        editTextSource.setOnItemClickListener(autoCompleteClickListener);
        mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1,BOUNDS_MOUNTAIN_VIEW, null);
        editTextSource.setAdapter(mPlaceArrayAdapter);
    }

    /* ----------------------------------------------------------------------------------------------------
    BEGIN: LOCATION AUTO COMPLETE SECTION
    ------------------------------------------------------------------------------------------------------*/
    private AdapterView.OnItemClickListener autoCompleteClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final PlaceArrayAdapter.PlaceAutocomplete item = mPlaceArrayAdapter.getItem(position);
            final String placeId = String.valueOf(item.placeId);
            Log.i(LOG_TAG, "Selected: " + item.description);
            PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(client, placeId);
            placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
            Log.i(LOG_TAG, "Fetching details for ID: " + item.placeId);
        }
    };

    private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
            = new ResultCallback<PlaceBuffer>() {
        @Override
        public void onResult(PlaceBuffer places) {
            if (!places.getStatus().isSuccess()) {
                Log.e(LOG_TAG, "Place query did not complete. Error: " +
                        places.getStatus().toString());
                return;
            }
            // Selecting the first object buffer.
            final Place place = places.get(0);
            /*
            CharSequence attributions = places.getAttributions();
            mNameTextView.setText(Html.fromHtml(place.getName() + ""));
            mAddressTextView.setText(Html.fromHtml(place.getAddress() + ""));
            mIdTextView.setText(Html.fromHtml(place.getId() + ""));
            mPhoneTextView.setText(Html.fromHtml(place.getPhoneNumber() + ""));
            mWebTextView.setText(place.getWebsiteUri() + "");
            if (attributions != null) {
                mAttTextView.setText(Html.fromHtml(attributions.toString()));
            }*/
        }
    };

    /* ----------------------------------------------------------------------------------------------------
    END: LOCATION AUTO COMPLETE SECTION
    ------------------------------------------------------------------------------------------------------*/

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Enable my location option for map.
        enableMyLocation();

        mMap.setOnMyLocationButtonClickListener(this);
        mMap.setOnMyLocationClickListener(this);

        // Creating Markers by clicking on map
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                MarkerOptions options = new MarkerOptions();

                if(markerPoints.size()>1){
                    markerPoints.clear();
                    mMap.clear();
                }

                // Add new Point
                markerPoints.add(latLng);
                options.position(latLng);

                if(markerPoints.size()==1){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                    options.title("Source");
                    editTextSource.setText(getCompleteAddressString(latLng.latitude, latLng.longitude));
                }else if(markerPoints.size()==2){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    options.title("Destination");
                }
                mMap.addMarker(options);

                if(markerPoints.size() >= 2){
                    LatLng origin = markerPoints.get(0);
                    LatLng dest = markerPoints.get(1);

                    String url = getDirectionsUrl(origin, dest);
                    DownloadTask downloadTask = new DownloadTask();
                    downloadTask.execute(url);
                }
            }
        });

        mMap.setOnMarkerClickListener((new GoogleMap.OnMarkerClickListener(){
            @Override
            public boolean onMarkerClick(Marker marker) {
                if(marker.isInfoWindowShown()) {
                    marker.hideInfoWindow();
                } else {
                    marker.showInfoWindow();
                }
                //.setText(myMarker.getTitle());    //Change TextView text here like this
                return true;
            }
        }));

        // Add a marker in Sydney and move the camera
        /*
        LatLng destination = new LatLng(12.354509, 76.603085);
        mMap.addMarker(new MarkerOptions().position(destination).title("Softvision, LLC (DBA Software Paradigms Infotech Pvt Ltd)"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(destination));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(destination.latitude, destination.longitude), 12.0f));
        */
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }

    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Permission to access the location is missing.
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            // Access to the location has been granted to the app.
            mMap.setMyLocationEnabled(true);
        }
    }
    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "Searching for location...", Toast.LENGTH_SHORT).show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }
        if (PermissionUtils.isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            // Display the missing permission error dialog when the fragments resume.
            mPermissionDenied = true;
        }
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            // Permission was not granted, display error dialog.
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }

    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog.newInstance(true).show(getSupportFragmentManager(), "dialog");
    }

    /* -------------------------------------------------------------------------------------------------------------
    BEGIN [GoogleApiClient] :Overrides for :
        GoogleApiClient.OnConnectionFailedListener,
        GoogleApiClient.ConnectionCallback
    ---------------------------------------------------------------------------------------------------------------*/
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mPlaceArrayAdapter.setGoogleApiClient(client);
        Log.i(LOG_TAG, "Google Places API connected.");
    }

    @Override
    public void onConnectionSuspended(int i) {
        mPlaceArrayAdapter.setGoogleApiClient(null);
        Log.e(LOG_TAG, "Google Places API connection suspended.");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(LOG_TAG, "Google Places API connection failed with error code: "
                + connectionResult.getErrorCode());

        Toast.makeText(this,
                "Google Places API connection failed with error code:" + connectionResult.getErrorCode(), Toast.LENGTH_LONG)
                .show();
    }
    /* -------------------------------------------------------------------------------------------------------------
    END [GoogleApiClient]
    ---------------------------------------------------------------------------------------------------------------*/

    /*-------------------------------------------------------------------------------------------------------------*/
    /* Map Utility Section */
    /*-------------------------------------------------------------------------------------------------------------*/
    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(LATITUDE,LONGITUDE, 1);
            if (addresses != null) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");
                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append(",");
                }
                strAdd = strReturnedAddress.toString();
            } else {
                strAdd = "No Address returned!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            strAdd = e.getMessage();
        }
        return strAdd;
    }

    private String getDirectionsUrl(LatLng origin,LatLng dest){
        // Origin of route
        String str_origin = String.format("origin=%s,%s", origin.latitude, origin.longitude);
        // Destination of route
        String str_dest = "destination="+dest.latitude+","+dest.longitude;
        // Sensor enabled
        String sensor = "sensor=false";
        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor;
        // Output format
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
        return url;
    }

    @SuppressLint("LongLogTag")
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            // Connecting to url
            urlConnection.connect();
            // Reading data from url
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }

            data = sb.toString();
            br.close();
        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, String> {

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {
            // For storing data from web service
            String data = "";
            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            ParserTask parserTask = new ParserTask();
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>>> {
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try{
                jObject = new JSONObject(jsonData[0]);
                GmapUtility parser = new GmapUtility();
                // Starts parsing data
                routes = parser.parseJson(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            // Traversing through all the routes
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points)
                        .width(12)
                        .color(Color.parseColor("#05b1fb"))//Google maps blue color
                        .geodesic(true);
            }

            // Drawing polyline in the Google Map for the i-th route
            mMap.addPolyline(lineOptions);
        }
    }
}
</code>```

And here is my PlaceArrayAdapter.java file

```<code>package com.softvision.gotogether.app;

/*imports hidden*/

public class PlaceArrayAdapter
        extends ArrayAdapter<PlaceArrayAdapter.PlaceAutocomplete> implements Filterable {
    private static final String TAG = "PlaceArrayAdapter";
    private GoogleApiClient mGoogleApiClient;
    private AutocompleteFilter mPlaceFilter;
    private LatLngBounds mBounds;
    private ArrayList<PlaceAutocomplete> mResultList;

    /**
     * Constructor
     *
     * @param context  Context
     * @param resource Layout resource
     * @param bounds   Used to specify the search bounds
     * @param filter   Used to specify place types
     */
    public PlaceArrayAdapter(Context context, int resource, LatLngBounds bounds,AutocompleteFilter filter) {
        super(context, resource);
        mBounds = bounds;
        mPlaceFilter = filter;
    }

    public void setGoogleApiClient(GoogleApiClient googleApiClient) {
        if (googleApiClient == null || !googleApiClient.isConnected()) {
            mGoogleApiClient = null;
        } else {
            mGoogleApiClient = googleApiClient;
        }
    }

    @Override
    public int getCount() {
        return mResultList.size();
    }

    @Override
    public PlaceAutocomplete getItem(int position) {
        return mResultList.get(position);
    }

    private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) {
        if (mGoogleApiClient != null) {
            Log.i(TAG, "Executing autocomplete query for: " + constraint);
            PendingResult<AutocompletePredictionBuffer> results =
                    Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),mBounds, mPlaceFilter);
            // Wait for predictions, set the timeout.
            AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);
            final Status status = autocompletePredictions.getStatus();
            if (!status.isSuccess()) {
                Toast.makeText(getContext(), "Error: " + status.toString(),Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Error getting place predictions: " + status.toString());
                autocompletePredictions.release();
                return null;
            }

            Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                    + " predictions.");
            Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
            ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
            while (iterator.hasNext()) {
                AutocompletePrediction prediction = iterator.next();
                resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getFullText(null)));
            }
            // Buffer release
            autocompletePredictions.release();
            return resultList;
        }
        Log.e(TAG, "Google API client is not connected.");
        return null;
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint != null) {
                    // Query the autocomplete API for the entered constraint
                    mResultList = getPredictions(constraint);
                    if (mResultList != null) {
                        // Results
                        results.values = mResultList;
                        results.count = mResultList.size();
                    }
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    // The API returned at least one result, update the data.
                    notifyDataSetChanged();
                } else {
                    // The API did not return any results, invalidate the data set.
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }

    class PlaceAutocomplete {
        public CharSequence placeId;
        public CharSequence description;

        PlaceAutocomplete(CharSequence placeId, CharSequence description) {
            this.placeId = placeId;
            this.description = description;
        }

        @Override
        public String toString() {
            return description.toString();
        }
    }
}
</code>```

Here, when I build the application, I'm getting the following build warnings on Gradle Console and Build was successful:

```<code>:app:compileDebugJavaWithJavac
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\PlaceArrayAdapter.java:88: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
                resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getFullText(null)));
                              ^
  where E is a type-variable:
    E extends Object declared in class ArrayList
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\PlaceArrayAdapter.java:92: warning: [unchecked] unchecked conversion
            return resultList;
                   ^
  required: ArrayList<PlaceArrayAdapter.PlaceAutocomplete>
  found:    ArrayList
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\GmapUtility.java:47: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
                            path.add(hm);
                                    ^
  where E is a type-variable:
    E extends Object declared in interface List
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\GmapUtility.java:50: warning: [unchecked] unchecked method invocation: method add in interface List is applied to given types
                    routes.add(path);
                              ^
  required: E
  found: List
  where E is a type-variable:
    E extends Object declared in interface List
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\GmapUtility.java:50: warning: [unchecked] unchecked conversion
                    routes.add(path);
                               ^
  required: E
  found:    List
  where E is a type-variable:
    E extends Object declared in interface List
5 warnings
</code>```

And when I run the application on my device, It's crashing. Errors on Run Console as below:

```<code>    Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
V/BoostFramework: BoostFramework() : mPerf = null
D/ViewRootImpl@27d899d[CityMapsActivity]: ViewPostImeInputStage processPointer 1
D/InputMethodManager: ISS - flag : 0Pid : 21012 view : com.softvision.gotogether.app
D/ViewRootImpl@27d899d[CityMapsActivity]: MSG_RESIZED: ci=Rect(0, 42 - 0, 0) vi=Rect(0, 42 - 0, 494) or=1
I/PlaceArrayAdapter: Executing autocomplete query for: usa
E/PlaceArrayAdapter: Error getting place predictions: Status{statusCode=ERROR, resolution=null}
</code>```

Please help me on this.

答:
Try setting multiDexEnabled true in your app Gradle file, inside android {defaultConfig{}}.

And I would suggest using the default ArrayAdapter instead of a custom adapter for the AutoCompleteTextView.

EDIT:

The standard way of using an ArrayAdapter is:

```<code>// The sample String array, you can use either this or List<String>
String[] countries = getResources().getStringArray(R.array.list_of_countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
editTextSource.setAdapter(adapter);
</code>```

Android documentation for AutoCompleteTextView: https://developer.android.com/reference/android/widget/AutoCompleteTextView.html

Useful tutorial: https://www.tutorialspoint.com/android/android_auto_complete.htm

Body:
I'm new to the Android Development and I'm trying to accomplish a Android application, Where I can Search the Places using Auto-Complete and mark that place on a Google Map.

Here's my activity_city_maps.xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout_map_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CityMapsActivity">

    <AutoCompleteTextView
        android:id="@+id/editText_source"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="Select Source"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toStartOf="@+id/button_source_update"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_source_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:text="Set Source"
        app:layout_constraintBaseline_toBaselineOf="@+id/editText_source"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/editText_source" />

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_source_update"
        tools:context=".CityMapsActivity" />

</android.support.constraint.ConstraintLayout>

And here my CityMapsActivity.java file

package com.softvision.gotogether.app;

//Imports hidden

public class CityMapsActivity extends FragmentActivity implements
        GoogleMap.OnMyLocationButtonClickListener,
        GoogleMap.OnMyLocationClickListener,
        OnMapReadyCallback,
        OnRequestPermissionsResultCallback,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleApiClient.ConnectionCallbacks{

    /* AUTO-COMPLETE PROPERTIES
    * ----------------------------------------------------------------------------------------------*/
    private static final String LOG_TAG = "CityMapsActivity";
    private GoogleApiClient client;
    private static final int GOOGLE_API_CLIENT_ID = 0;
    private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
            new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
    private PlaceArrayAdapter mPlaceArrayAdapter;
    private AutoCompleteTextView editTextSource;

    /* MAP PROPERTIES
    * ----------------------------------------------------------------------------------------------*/
    private GoogleMap mMap;
    private ArrayList<LatLng> markerPoints = new ArrayList<>();
    //Request code for location permission request.
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    //Flag indicating whether a requested permission has been denied after returning in
    private boolean mPermissionDenied = false;

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

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

        // Location Auto complete
        client = new GoogleApiClient.Builder(CityMapsActivity.this)
                .addApi(Places.GEO_DATA_API)
                .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                .addConnectionCallbacks(this)
                .build();

        editTextSource = (AutoCompleteTextView) findViewById(R.id.editText_source);
        editTextSource.setThreshold(3);

        editTextSource.setOnItemClickListener(autoCompleteClickListener);
        mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1,BOUNDS_MOUNTAIN_VIEW, null);
        editTextSource.setAdapter(mPlaceArrayAdapter);
    }

    /* ----------------------------------------------------------------------------------------------------
    BEGIN: LOCATION AUTO COMPLETE SECTION
    ------------------------------------------------------------------------------------------------------*/
    private AdapterView.OnItemClickListener autoCompleteClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final PlaceArrayAdapter.PlaceAutocomplete item = mPlaceArrayAdapter.getItem(position);
            final String placeId = String.valueOf(item.placeId);
            Log.i(LOG_TAG, "Selected: " + item.description);
            PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(client, placeId);
            placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
            Log.i(LOG_TAG, "Fetching details for ID: " + item.placeId);
        }
    };

    private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
            = new ResultCallback<PlaceBuffer>() {
        @Override
        public void onResult(PlaceBuffer places) {
            if (!places.getStatus().isSuccess()) {
                Log.e(LOG_TAG, "Place query did not complete. Error: " +
                        places.getStatus().toString());
                return;
            }
            // Selecting the first object buffer.
            final Place place = places.get(0);
            /*
            CharSequence attributions = places.getAttributions();
            mNameTextView.setText(Html.fromHtml(place.getName() + ""));
            mAddressTextView.setText(Html.fromHtml(place.getAddress() + ""));
            mIdTextView.setText(Html.fromHtml(place.getId() + ""));
            mPhoneTextView.setText(Html.fromHtml(place.getPhoneNumber() + ""));
            mWebTextView.setText(place.getWebsiteUri() + "");
            if (attributions != null) {
                mAttTextView.setText(Html.fromHtml(attributions.toString()));
            }*/
        }
    };

    /* ----------------------------------------------------------------------------------------------------
    END: LOCATION AUTO COMPLETE SECTION
    ------------------------------------------------------------------------------------------------------*/

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Enable my location option for map.
        enableMyLocation();

        mMap.setOnMyLocationButtonClickListener(this);
        mMap.setOnMyLocationClickListener(this);

        // Creating Markers by clicking on map
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                MarkerOptions options = new MarkerOptions();

                if(markerPoints.size()>1){
                    markerPoints.clear();
                    mMap.clear();
                }

                // Add new Point
                markerPoints.add(latLng);
                options.position(latLng);

                if(markerPoints.size()==1){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                    options.title("Source");
                    editTextSource.setText(getCompleteAddressString(latLng.latitude, latLng.longitude));
                }else if(markerPoints.size()==2){
                    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    options.title("Destination");
                }
                mMap.addMarker(options);

                if(markerPoints.size() >= 2){
                    LatLng origin = markerPoints.get(0);
                    LatLng dest = markerPoints.get(1);

                    String url = getDirectionsUrl(origin, dest);
                    DownloadTask downloadTask = new DownloadTask();
                    downloadTask.execute(url);
                }
            }
        });

        mMap.setOnMarkerClickListener((new GoogleMap.OnMarkerClickListener(){
            @Override
            public boolean onMarkerClick(Marker marker) {
                if(marker.isInfoWindowShown()) {
                    marker.hideInfoWindow();
                } else {
                    marker.showInfoWindow();
                }
                //.setText(myMarker.getTitle());    //Change TextView text here like this
                return true;
            }
        }));

        // Add a marker in Sydney and move the camera
        /*
        LatLng destination = new LatLng(12.354509, 76.603085);
        mMap.addMarker(new MarkerOptions().position(destination).title("Softvision, LLC (DBA Software Paradigms Infotech Pvt Ltd)"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(destination));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(destination.latitude, destination.longitude), 12.0f));
        */
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }

    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Permission to access the location is missing.
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, true);
        } else if (mMap != null) {
            // Access to the location has been granted to the app.
            mMap.setMyLocationEnabled(true);
        }
    }
    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "Searching for location...", Toast.LENGTH_SHORT).show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            return;
        }
        if (PermissionUtils.isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            // Display the missing permission error dialog when the fragments resume.
            mPermissionDenied = true;
        }
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            // Permission was not granted, display error dialog.
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }

    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog.newInstance(true).show(getSupportFragmentManager(), "dialog");
    }

    /* -------------------------------------------------------------------------------------------------------------
    BEGIN [GoogleApiClient] :Overrides for :
        GoogleApiClient.OnConnectionFailedListener,
        GoogleApiClient.ConnectionCallback
    ---------------------------------------------------------------------------------------------------------------*/
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mPlaceArrayAdapter.setGoogleApiClient(client);
        Log.i(LOG_TAG, "Google Places API connected.");
    }

    @Override
    public void onConnectionSuspended(int i) {
        mPlaceArrayAdapter.setGoogleApiClient(null);
        Log.e(LOG_TAG, "Google Places API connection suspended.");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(LOG_TAG, "Google Places API connection failed with error code: "
                + connectionResult.getErrorCode());

        Toast.makeText(this,
                "Google Places API connection failed with error code:" + connectionResult.getErrorCode(), Toast.LENGTH_LONG)
                .show();
    }
    /* -------------------------------------------------------------------------------------------------------------
    END [GoogleApiClient]
    ---------------------------------------------------------------------------------------------------------------*/

    /*-------------------------------------------------------------------------------------------------------------*/
    /* Map Utility Section */
    /*-------------------------------------------------------------------------------------------------------------*/
    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(LATITUDE,LONGITUDE, 1);
            if (addresses != null) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");
                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append(",");
                }
                strAdd = strReturnedAddress.toString();
            } else {
                strAdd = "No Address returned!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            strAdd = e.getMessage();
        }
        return strAdd;
    }

    private String getDirectionsUrl(LatLng origin,LatLng dest){
        // Origin of route
        String str_origin = String.format("origin=%s,%s", origin.latitude, origin.longitude);
        // Destination of route
        String str_dest = "destination="+dest.latitude+","+dest.longitude;
        // Sensor enabled
        String sensor = "sensor=false";
        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor;
        // Output format
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
        return url;
    }

    @SuppressLint("LongLogTag")
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            // Connecting to url
            urlConnection.connect();
            // Reading data from url
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }

            data = sb.toString();
            br.close();
        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, String> {

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {
            // For storing data from web service
            String data = "";
            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            ParserTask parserTask = new ParserTask();
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>>> {
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try{
                jObject = new JSONObject(jsonData[0]);
                GmapUtility parser = new GmapUtility();
                // Starts parsing data
                routes = parser.parseJson(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            // Traversing through all the routes
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points)
                        .width(12)
                        .color(Color.parseColor("#05b1fb"))//Google maps blue color
                        .geodesic(true);
            }

            // Drawing polyline in the Google Map for the i-th route
            mMap.addPolyline(lineOptions);
        }
    }
}

And here is my PlaceArrayAdapter.java file

package com.softvision.gotogether.app;

/*imports hidden*/

public class PlaceArrayAdapter
        extends ArrayAdapter<PlaceArrayAdapter.PlaceAutocomplete> implements Filterable {
    private static final String TAG = "PlaceArrayAdapter";
    private GoogleApiClient mGoogleApiClient;
    private AutocompleteFilter mPlaceFilter;
    private LatLngBounds mBounds;
    private ArrayList<PlaceAutocomplete> mResultList;

    /**
     * Constructor
     *
     * @param context  Context
     * @param resource Layout resource
     * @param bounds   Used to specify the search bounds
     * @param filter   Used to specify place types
     */
    public PlaceArrayAdapter(Context context, int resource, LatLngBounds bounds,AutocompleteFilter filter) {
        super(context, resource);
        mBounds = bounds;
        mPlaceFilter = filter;
    }

    public void setGoogleApiClient(GoogleApiClient googleApiClient) {
        if (googleApiClient == null || !googleApiClient.isConnected()) {
            mGoogleApiClient = null;
        } else {
            mGoogleApiClient = googleApiClient;
        }
    }

    @Override
    public int getCount() {
        return mResultList.size();
    }

    @Override
    public PlaceAutocomplete getItem(int position) {
        return mResultList.get(position);
    }

    private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) {
        if (mGoogleApiClient != null) {
            Log.i(TAG, "Executing autocomplete query for: " + constraint);
            PendingResult<AutocompletePredictionBuffer> results =
                    Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),mBounds, mPlaceFilter);
            // Wait for predictions, set the timeout.
            AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);
            final Status status = autocompletePredictions.getStatus();
            if (!status.isSuccess()) {
                Toast.makeText(getContext(), "Error: " + status.toString(),Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Error getting place predictions: " + status.toString());
                autocompletePredictions.release();
                return null;
            }

            Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                    + " predictions.");
            Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
            ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
            while (iterator.hasNext()) {
                AutocompletePrediction prediction = iterator.next();
                resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getFullText(null)));
            }
            // Buffer release
            autocompletePredictions.release();
            return resultList;
        }
        Log.e(TAG, "Google API client is not connected.");
        return null;
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint != null) {
                    // Query the autocomplete API for the entered constraint
                    mResultList = getPredictions(constraint);
                    if (mResultList != null) {
                        // Results
                        results.values = mResultList;
                        results.count = mResultList.size();
                    }
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    // The API returned at least one result, update the data.
                    notifyDataSetChanged();
                } else {
                    // The API did not return any results, invalidate the data set.
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }

    class PlaceAutocomplete {
        public CharSequence placeId;
        public CharSequence description;

        PlaceAutocomplete(CharSequence placeId, CharSequence description) {
            this.placeId = placeId;
            this.description = description;
        }

        @Override
        public String toString() {
            return description.toString();
        }
    }
}

Here, when I build the application, I'm getting the following build warnings on Gradle Console and Build was successful:

:app:compileDebugJavaWithJavac
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\PlaceArrayAdapter.java:88: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
                resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getFullText(null)));
                              ^
  where E is a type-variable:
    E extends Object declared in class ArrayList
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\PlaceArrayAdapter.java:92: warning: [unchecked] unchecked conversion
            return resultList;
                   ^
  required: ArrayList<PlaceArrayAdapter.PlaceAutocomplete>
  found:    ArrayList
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\GmapUtility.java:47: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
                            path.add(hm);
                                    ^
  where E is a type-variable:
    E extends Object declared in interface List
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\GmapUtility.java:50: warning: [unchecked] unchecked method invocation: method add in interface List is applied to given types
                    routes.add(path);
                              ^
  required: E
  found: List
  where E is a type-variable:
    E extends Object declared in interface List
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\GmapUtility.java:50: warning: [unchecked] unchecked conversion
                    routes.add(path);
                               ^
  required: E
  found:    List
  where E is a type-variable:
    E extends Object declared in interface List
5 warnings

And when I run the application on my device, It's crashing. Errors on Run Console as below:

    Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
V/BoostFramework: BoostFramework() : mPerf = null
D/ViewRootImpl@27d899d[CityMapsActivity]: ViewPostImeInputStage processPointer 1
D/InputMethodManager: ISS - flag : 0Pid : 21012 view : com.softvision.gotogether.app
D/ViewRootImpl@27d899d[CityMapsActivity]: MSG_RESIZED: ci=Rect(0, 42 - 0, 0) vi=Rect(0, 42 - 0, 494) or=1
I/PlaceArrayAdapter: Executing autocomplete query for: usa
E/PlaceArrayAdapter: Error getting place predictions: Status{statusCode=ERROR, resolution=null}

Please help me on this.

Body:
Try setting multiDexEnabled true in your app Gradle file, inside android {defaultConfig{}}.

And I would suggest using the default ArrayAdapter instead of a custom adapter for the AutoCompleteTextView.

EDIT:

The standard way of using an ArrayAdapter is:

// The sample String array, you can use either this or List<String>
String[] countries = getResources().getStringArray(R.array.list_of_countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
editTextSource.setAdapter(adapter);

Android documentation for AutoCompleteTextView: https://developer.android.com/reference/android/widget/AutoCompleteTextView.html

Useful tutorial: https://www.tutorialspoint.com/android/android_auto_complete.htm


问:
How do I remove the bootstrap input box border using scss?
I am trying to remove the border of the input box. My current code is:

input{
  background-color: #31363A;
  outline: 0;
  box-shadow: none;
  border:none;

}
 ```

How do I remove the annoying white border?
Many Thanks

答: Using scss border: 1px solid [color of the background]

Body:
I am trying to remove the border of the input box. My current code is:

input{
  background-color: #31363A;
  outline: 0;
  box-shadow: none;
  border:none;

}

How do I remove the annoying white border?
Many Thanks


问:
How to handle accessibility in custom view when it is not designed for handling clicks?
I've written a chessboard component in android, by subclassing view. It only process drag and drop from user. But Android Studio complains about the fact that performClick is not handled for this view, so that accessibility is not handled correctly.

But as I manage Dnd and not a simple click, how to resolve this problem ?
In fact, I am just overriding onTouchEvent, managing ACTION_DOWN, ACTION_MOVE and ACTION_UP. But I can't see how to adapt the code for onPerformClick.

答:
I see two options here:

1, Add suppress lint warning annotation for onTouchEvent

```<code>@SuppressLint("ClickableViewAccessibility")
</code>```

2, override performClick:

```<code>override fun performClick(): Boolean {
    return super.performClick()
}
</code>```

Your choice ;-)

Body:
I see two options here:

1, Add suppress lint warning annotation for onTouchEvent

@SuppressLint("ClickableViewAccessibility")

2, override performClick:

override fun performClick(): Boolean {
    return super.performClick()
}

Your choice ;-)


问:
PhantomJs rendering
Is there any limit to the number of characters for the file name to get it render from phantomJs?

```<code>var page = require('webpage').create();
page.open('http://github.com/', function() {
      window.setTimeout(function(){
      var filename = encodeURI('The code shown here is also available in various examples included with PhantomJS. You are also recommended to explore the use of PhantomJS for page automation, network monitoring, screen capture, and headless testing The code shown here is also available in various examples included with PhantomJS. You are also recommended to explore the use of PhantomJS for page automation, network monitoring, screen capture, and headless testing');
      console.log('filename: ' + filename);
      page.render(filename + ".png");
      phantom.exit();}, 100);
});
</code>```

This  file is not getting render through phantomJs.

Can someone please help here?

答:
I don't think it has anything to do with PhantomJS, but basically with your OS. There is a size limit for the file path name in every OS.

According to the naming convention in Windos OS -

In the Windows API (with some exceptions discussed in the following
  paragraphs), the maximum length for a path is MAX_PATH, which is
  defined as 260 characters. A local path is structured in the following
  order: drive letter, colon, backslash, name components separated by
  backslashes, and a terminating null character. For example, the
  maximum path on drive D is "D:\some 256-character path string"
  where "" represents the invisible terminating null character for
  the current system codepage. (The characters < > are used here for
  visual clarity and cannot be part of a valid path string.)

Title: PhantomJs rendering

Body:
Is there any limit to the number of characters for the file name to get it render from phantomJs?

var page = require('webpage').create();
page.open('http://github.com/', function() {
      window.setTimeout(function(){
      var filename = encodeURI('The code shown here is also available in various examples included with PhantomJS. You are also recommended to explore the use of PhantomJS for page automation, network monitoring, screen capture, and headless testing The code shown here is also available in various examples included with PhantomJS. You are also recommended to explore the use of PhantomJS for page automation, network monitoring, screen capture, and headless testing');
      console.log('filename: ' + filename);
      page.render(filename + ".png");
      phantom.exit();}, 100);
});

This  file is not getting render through phantomJs.

Can someone please help here?


问:
Generating more than one output file from a template
Hi
I am writing a custom template generator for my xml file. I was wondering if you guys can tell me a way I can generate more than one output file from the template under the same template.

The no of file should depend on the no of xml files I input

If I want to generate the c# class for a.xml I am doing something like this

```<code><#= XmlToCsGenerator.Xml(this.Host.ResolvePath("a.xml")) #>
</code>```

where my  function XmlToCsGenerator.Xml(string path) returns the string to be written into the file.

Thanks in advance

答:
Damien Guard's approach detailed here:
http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited
is a good one too.  This is very close to the approach used in the Entity Framework's use of T4 in the .Net 4.0 product.</p>

Body:
Hi
I am writing a custom template generator for my xml file. I was wondering if you guys can tell me a way I can generate more than one output file from the template under the same template.

The no of file should depend on the no of xml files I input

If I want to generate the c# class for a.xml I am doing something like this

<#= XmlToCsGenerator.Xml(this.Host.ResolvePath("a.xml")) #>

where my  function XmlToCsGenerator.Xml(string path) returns the string to be written into the file.

Thanks in advance


答:
fs.readFile and fs.writeFile are asynchronous. You start the readFile immediately after calling writeFile. This means writeFile may or may not (probably not) have time to finish before readFile executes.

Try putting the readFile within the writeFile callback. The callback is called after the asynchronous function completes, so it allows you to handle code in a synchronous manner.

I'm not sure the readFile -> open -> writeFile -> readFile logic makes a lot of sense, though.

Title: Node JS synchronous events


问:
How to save and restore multiple different sessions in Vim?
Depending on my task in Vim I have several tabs open.

How can I save different sessions for later use?

答:
Since this is the first hit on Google for me (and probably others) for how to work with sessions in Vim I've decided to add a little to @mathielo's answer on how to make this automatic.

I like his code, but the addition of the "only if without args" solution seemed to be a bit lacking. This is my modified version:

```<code>function! MakeSession(overwrite)
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  if (filewritable(b:sessiondir) != 2)
    exe 'silent !mkdir -p ' b:sessiondir
    redraw!
  endif
  let b:filename = b:sessiondir . '/session.vim'
  if a:overwrite == 0 && !empty(glob(b:filename))
    return
  endif
  exe "mksession! " . b:filename
endfunction

function! LoadSession()
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  let b:sessionfile = b:sessiondir . "/session.vim"
  if (filereadable(b:sessionfile))
    exe 'source ' b:sessionfile
  else
    echo "No session loaded."
  endif
endfunction

" Adding automatons for when entering or leaving Vim
if(argc() == 0)
  au VimEnter * nested :call LoadSession()
  au VimLeave * :call MakeSession(1)
else
  au VimLeave * :call MakeSession(0)
endif
</code>```

The notable change here is the optional override. If you open Vim without options it will open any existing session and overwrite changes made when you leave. If Vim is opened with options it will only create a new session if none exist, this means that you can open single files in a directory that has a session without overwriting it. Then you can open Vim without options to run the session instead. If there doesn't exist a session then it creates a new one.

Body:
Since this is the first hit on Google for me (and probably others) for how to work with sessions in Vim I've decided to add a little to @mathielo's answer on how to make this automatic.

I like his code, but the addition of the "only if without args" solution seemed to be a bit lacking. This is my modified version:

function! MakeSession(overwrite)
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  if (filewritable(b:sessiondir) != 2)
    exe 'silent !mkdir -p ' b:sessiondir
    redraw!
  endif
  let b:filename = b:sessiondir . '/session.vim'
  if a:overwrite == 0 && !empty(glob(b:filename))
    return
  endif
  exe "mksession! " . b:filename
endfunction

function! LoadSession()
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  let b:sessionfile = b:sessiondir . "/session.vim"
  if (filereadable(b:sessionfile))
    exe 'source ' b:sessionfile
  else
    echo "No session loaded."
  endif
endfunction

" Adding automatons for when entering or leaving Vim
if(argc() == 0)
  au VimEnter * nested :call LoadSession()
  au VimLeave * :call MakeSession(1)
else
  au VimLeave * :call MakeSession(0)
endif

The notable change here is the optional override. If you open Vim without options it will open any existing session and overwrite changes made when you leave. If Vim is opened with options it will only create a new session if none exist, this means that you can open single files in a directory that has a session without overwriting it. Then you can open Vim without options to run the session instead. If there doesn't exist a session then it creates a new one.


问:
My image doesnt scale to its right pixel
Gonna ask for help coz this is making me crazy now.
The background image doesn't seem to fit in my window size. Can't see what i'm missing in my code. I've tried changing some x and y and other parameters, tried searching too but it still doesn't work. Thanks!

```<code>import Tkinter as tk
from Tkinter import *
import ttk
from PIL import Image, ImageTk

def callback():
    mainmenu.deiconify

def genkeymenu():

    mainmenu.withdraw()
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = ttk.Label(generatemenu, image=bg1)
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    background_label.image = bg1

    keynamelabel = ttk.Label(generatemenu, text="Enter your key name")

    keynameEntry = ttk.Entry(generatemenu)

    keynameButton = ttk.Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    background_label.pack()

    keynamelabel.pack()
    keynameEntry.pack()
    keynameButton.pack()

    check1024.pack()
    check2048.pack()
    check4096.pack()

    generatemenu.title("Generate Key")
    ttk.eval('tk::PlaceWindow %s center' % generatemenu.winfo_pathname(generatemenu.winfo_id()))
    generatemenu.mainloop()

class Buttons:
    def __init__(self, buttons):
        self.buttons = buttons
        self.genkeybutton = Button(buttons, text= "Generate Key Pair", fg="black", command=genkeymenu)
        self.id = buttons.create_window(50, 100, width=0, height=0,window=self.genkeybutton)

mainmenu = tk.Tk()
mainmenu.minsize(width=600, height=400)

imgpath = "key.jpg"
img=Image.open(imgpath)
img=img.resize((600,400), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)

buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=photo)
Buttons(buttons)

mainmenu.title("RSA ENCRYPTION")
#mainmenu.wm_attributes('-type', 'splash')
#mainmenu.eval('tk::PlaceWindow %s center' %
mainmenu.winfo_pathname(mainmenu.winfo_id()))
mainmenu.mainloop()
</code>```

This is the part of the code that i have problem with:

```<code>class Buttons:
    def __init__(self, buttons):
        self.buttons = buttons
        self.genkeybutton = Button(buttons, text= "Generate Key Pair", fg="black", command=genkeymenu)
        self.id = buttons.create_window(50, 100, width=0, height=0,window=self.genkeybutton)

mainmenu = tk.Tk()
mainmenu.minsize(width=600, height=400)

imgpath = "key.jpg"
img=Image.open(imgpath)
img=img.resize((600,400), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)

buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=photo)
Buttons(buttons)

mainmenu.title("RSA ENCRYPTION")
#mainmenu.wm_attributes('-type', 'splash')
#mainmenu.eval('tk::PlaceWindow %s center' %
mainmenu.winfo_pathname(mainmenu.winfo_id()))
mainmenu.mainloop()
</code>```

Here is the screenshot of the problem:

答:
In place of this:

```<code>imgpath = "key2.jpg"
img=Image.open(imgpath)
img=img.resize((600,400), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)
</code>```

do this :

```<code>imgpath = PhotoImage(file="key2.jpg")
img = Label(mainmenu, image=imgpath)
img.place(x=0, y=0, relwidth=1, relheight=1)
</code>```

it will cover the background.Then comment this to see what am talking about #buttons.create_image(0, 0, image=img)

better still do for image in the canvas

```<code>buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=imgpath)
Buttons(buttons)
</code>```

Full code below

```<code>import Tkinter as tk
from Tkinter import *
import ttk
from PIL import Image, ImageTk

def callback():
    mainmenu.deiconify

def genkeymenu():

    mainmenu.withdraw()
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = ttk.Label(generatemenu, image=bg1)
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    background_label.image = bg1

    keynamelabel = ttk.Label(generatemenu, text="Enter your key name")

    keynameEntry = ttk.Entry(generatemenu)

    keynameButton = ttk.Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    background_label.pack()

    keynamelabel.pack()
    keynameEntry.pack()
    keynameButton.pack()

    check1024.pack()
    check2048.pack()
    check4096.pack()

    generatemenu.title("Generate Key")
    ttk.eval('tk::PlaceWindow %s center' %
    generatemenu.winfo_pathname(generatemenu.winfo_id()))
   generatemenu.mainloop()

class Buttons:
    def __init__(self, buttons):
        self.buttons = buttons
        self.genkeybutton = Button(buttons, text= "Generate Key Pair", fg="black", command=genkeymenu)
        self.id = buttons.create_window(50, 100, width=0, height=0,window=self.genkeybutton)

mainmenu = tk.Tk()
mainmenu.minsize(width=600, height=400)

imgpath = PhotoImage(file="key2.jpg")
img = Label(mainmenu, image=imgpath)
img.place(x=0, y=0, relwidth=1, relheight=1)

buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=imgpath)
Buttons(buttons)

mainmenu.title("RSA ENCRYPTION")
#mainmenu.wm_attributes('-type', 'splash')
#mainmenu.eval('tk::PlaceWindow %s center' %
mainmenu.winfo_pathname(mainmenu.winfo_id())
mainmenu.mainloop()
</code>```

Body:
Gonna ask for help coz this is making me crazy now.
The background image doesn't seem to fit in my window size. Can't see what i'm missing in my code. I've tried changing some x and y and other parameters, tried searching too but it still doesn't work. Thanks!

import Tkinter as tk
from Tkinter import *
import ttk
from PIL import Image, ImageTk

def callback():
    mainmenu.deiconify

def genkeymenu():

    mainmenu.withdraw()
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = ttk.Label(generatemenu, image=bg1)
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    background_label.image = bg1

    keynamelabel = ttk.Label(generatemenu, text="Enter your key name")

    keynameEntry = ttk.Entry(generatemenu)

    keynameButton = ttk.Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    background_label.pack()

    keynamelabel.pack()
    keynameEntry.pack()
    keynameButton.pack()

    check1024.pack()
    check2048.pack()
    check4096.pack()

    generatemenu.title("Generate Key")
    ttk.eval('tk::PlaceWindow %s center' % generatemenu.winfo_pathname(generatemenu.winfo_id()))
    generatemenu.mainloop()

class Buttons:
    def __init__(self, buttons):
        self.buttons = buttons
        self.genkeybutton = Button(buttons, text= "Generate Key Pair", fg="black", command=genkeymenu)
        self.id = buttons.create_window(50, 100, width=0, height=0,window=self.genkeybutton)

mainmenu = tk.Tk()
mainmenu.minsize(width=600, height=400)

imgpath = "key.jpg"
img=Image.open(imgpath)
img=img.resize((600,400), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)

buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=photo)
Buttons(buttons)

mainmenu.title("RSA ENCRYPTION")
#mainmenu.wm_attributes('-type', 'splash')
#mainmenu.eval('tk::PlaceWindow %s center' %
mainmenu.winfo_pathname(mainmenu.winfo_id()))
mainmenu.mainloop()

This is the part of the code that i have problem with:

class Buttons:
    def __init__(self, buttons):
        self.buttons = buttons
        self.genkeybutton = Button(buttons, text= "Generate Key Pair", fg="black", command=genkeymenu)
        self.id = buttons.create_window(50, 100, width=0, height=0,window=self.genkeybutton)

mainmenu = tk.Tk()
mainmenu.minsize(width=600, height=400)

imgpath = "key.jpg"
img=Image.open(imgpath)
img=img.resize((600,400), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)

buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=photo)
Buttons(buttons)

mainmenu.title("RSA ENCRYPTION")
#mainmenu.wm_attributes('-type', 'splash')
#mainmenu.eval('tk::PlaceWindow %s center' %
mainmenu.winfo_pathname(mainmenu.winfo_id()))
mainmenu.mainloop()

Here is the screenshot of the problem:

Body:
In place of this:

imgpath = "key2.jpg"
img=Image.open(imgpath)
img=img.resize((600,400), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)

do this :

imgpath = PhotoImage(file="key2.jpg")
img = Label(mainmenu, image=imgpath)
img.place(x=0, y=0, relwidth=1, relheight=1)

it will cover the background.Then comment this to see what am talking about #buttons.create_image(0, 0, image=img)

better still do for image in the canvas

buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=imgpath)
Buttons(buttons)

Full code below

import Tkinter as tk
from Tkinter import *
import ttk
from PIL import Image, ImageTk

def callback():
    mainmenu.deiconify

def genkeymenu():

    mainmenu.withdraw()
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = ttk.Label(generatemenu, image=bg1)
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    background_label.image = bg1

    keynamelabel = ttk.Label(generatemenu, text="Enter your key name")

    keynameEntry = ttk.Entry(generatemenu)

    keynameButton = ttk.Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    background_label.pack()

    keynamelabel.pack()
    keynameEntry.pack()
    keynameButton.pack()

    check1024.pack()
    check2048.pack()
    check4096.pack()

    generatemenu.title("Generate Key")
    ttk.eval('tk::PlaceWindow %s center' %
    generatemenu.winfo_pathname(generatemenu.winfo_id()))
   generatemenu.mainloop()

class Buttons:
    def __init__(self, buttons):
        self.buttons = buttons
        self.genkeybutton = Button(buttons, text= "Generate Key Pair", fg="black", command=genkeymenu)
        self.id = buttons.create_window(50, 100, width=0, height=0,window=self.genkeybutton)

mainmenu = tk.Tk()
mainmenu.minsize(width=600, height=400)

imgpath = PhotoImage(file="key2.jpg")
img = Label(mainmenu, image=imgpath)
img.place(x=0, y=0, relwidth=1, relheight=1)

buttons = tk.Canvas(mainmenu)
buttons.pack()
buttons.create_image(0, 0, image=imgpath)
Buttons(buttons)

mainmenu.title("RSA ENCRYPTION")
#mainmenu.wm_attributes('-type', 'splash')
#mainmenu.eval('tk::PlaceWindow %s center' %
mainmenu.winfo_pathname(mainmenu.winfo_id())
mainmenu.mainloop()


问:
ASP.NET Javascript Services Server Side Render Specific Routes
With Microsoft's ASP.NET Javascript Services is it possible to pick and choose which routes get rendered server side?

I need marketing pages like the home page to get rendered on the server for SEO, but the web app pages to only be rendered on the client.

I am using react, react router and asp net core 2.0.

答:
Use asp-prerender-* in a view, as described here

https://github.com/aspnet/JavaScriptServices/tree/dev/src/Microsoft.AspNetCore.SpaServices#server-side-prerendering

For example, in your cshtml:

```<code><div id="my-spa" asp-prerender-module="ClientApp/boot-server"
             asp-prerender-data="new {
                IsGoldUser = true,
                Cookies = ViewContext.HttpContext.Request.Cookies
             }"></div>
</code>```

Body:
Use asp-prerender-* in a view, as described here

https://github.com/aspnet/JavaScriptServices/tree/dev/src/Microsoft.AspNetCore.SpaServices#server-side-prerendering

For example, in your cshtml:

<div id="my-spa" asp-prerender-module="ClientApp/boot-server"
             asp-prerender-data="new {
                IsGoldUser = true,
                Cookies = ViewContext.HttpContext.Request.Cookies
             }"></div>


答:
Using latest Node.js v9.2.0 Documentation

fs.writeFile(file, data[, options], callback)

...

Asynchronously writes data to a file, replacing the file if it already
  exists. data can be a string or a buffer.

Since you wanna writeFile synchronous you should use

fs.writeFileSync(file, data[, options])

...

The synchronous version of fs.writeFile(). Returns undefined.

Title: Node JS synchronous events


问:
How to open desired figure by dialogue box in MATLAB
Is there any possible way to open the desired figures from a lot of plotted figures in MATLAB?

If it is possible with dialogue box then it will be perfect.

I have like 75 figures plotted after my code but I have closed the figures at end of loops as they are too much.

Is it possible to open just one figure by just entering values necessary for plotting figure in MATLAB at end of program?

答:
One way to do this is the following:
1) You save the figures as .fig in a dedicated folder using the saveas command, e.g.:

```<code>saveas(gcf,['FileName_',num2str(idx),'.fig']);
</code>```

where idx is the index associated with the figure number (so in 75 in the example you mentioned). For simplicity, I would save all of them in one folder.

2) You use inputdlg to create an input dialog box, where you type in the index you want. Then, you run uiopen(['FileName_',idxFromInput,'.fig']), which will display the figure. Note that the output from inputdlg is normally a string, so you don't need num2str here.

Body:
One way to do this is the following:
1) You save the figures as .fig in a dedicated folder using the saveas command, e.g.:

saveas(gcf,['FileName_',num2str(idx),'.fig']);

where idx is the index associated with the figure number (so in 75 in the example you mentioned). For simplicity, I would save all of them in one folder.

2) You use inputdlg to create an input dialog box, where you type in the index you want. Then, you run uiopen(['FileName_',idxFromInput,'.fig']), which will display the figure. Note that the output from inputdlg is normally a string, so you don't need num2str here.


问:
Hide UISearchBar clear text button
I would like to know how to hide or not display the UISearchBar cross that appears in the textField fo the UISearchBar

I have tried using this

```<code>filterSearchBar.showsCancelButton = NO;
</code>```

However this is an actual cancel button not the small grey cross, so I would like to know if there is an equivalent for the small grey button that shows in the UISearchBar.

答:
You can remove the clear text button for all UISearchBar instances:</p>

```<code>[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].clearButtonMode = UITextFieldViewModeNever;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Hide UISearchBar clear text button

Body:
I would like to know how to hide or not display the UISearchBar cross that appears in the textField fo the UISearchBar

I have tried using this

filterSearchBar.showsCancelButton = NO;

However this is an actual cancel button not the small grey cross, so I would like to know if there is an equivalent for the small grey button that shows in the UISearchBar.

Body:
You can remove the clear text button for all UISearchBar instances:

[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].clearButtonMode = UITextFieldViewModeNever;


问:
Add a more button to gwt Suggest Box
I have a gwt suggest box that does an RPC call to get some data from the server and display it.  In some cases there are up to 2000 results.  Whilst this works fine in chrome when the javascript runs in firefox it freezes the window for 5 seconds and sometime brings up script not responding warnings.

What I wanted to do was something like show 20 results and have a more button that can just append the next 20 without having to call back to the server every time it is clicked.  I am fairly new to this, I have tried extending suggestBox and overriding showSuggestions() but it is protected so I can't.

Any suggestions/ ideas would be great.

Cheers,
Rob

答: See this question for pointers on how to extend the GWT's SuggestBox - basically, you want to provide your own SuggestOracle (it's used for fetching the suggestions), maybe your textbox (see the links in the question I mentioned earlier) and most likely a custom SuggestBox.SuggestionDisplay. Those three are passed via the constructor to SuggestBox. See the existing default implementations (MultiWordSuggestOracle, SuggestBox.DefaultSuggestionDisplay) for some ideas :)

Title: Add a more button to gwt Suggest Box


问:
Integrate Mpesa API with google forms
I want to integrate Mpesa API to a google form.
Users using the form to pay, let us say for registration Fee </p>

答:
You now use M-Pesa RESTful APIs accessible through Safaricom's developer portal. The documentation has sample codes in the major programming languages - Python, JavaScript/NodeJS, Java, Ruby.

You can now consume the M-Pesa RESTful APIs with Google Apps Script like you would any other RESTful APIs.

Title: Integrate Mpesa API with google forms


问:
How to fix ssh permission in home dir
I have trouble with my ssh config, I have directory /homa/ivan/.ssh but after my manipulation I have access denied for that derictory. At that moment I have
drwx------    2 root root   4096 Dec  5 14:20 .ssh

after change owner I have

Bad owner or permissions on /home/ivan/.ssh/config

but I vae owner ivan

```<code>drwx------  2 ivan ivan 4096 Дек  5 14:55 .
drwxr-xr-x 32 ivan ivan 4096 Дек  5 14:03 ..
-rwxrwxrwx  1 ivan ivan  106 Ноя 26 22:48 config
-rwxrwxrwx  1 ivan ivan 1675 Дек  5 14:20 id_rsa
-rwxrwxrwx  1 ivan ivan  394 Дек  5 14:20 id_rsa.pub
-rwxrwxrwx  1 ivan ivan 3982 Ноя 28 19:04 known_hosts
</code>```

how to correct tune permission for ssh config and key ?

答:
I solved it </p>

```<code>chmod 600 ~/.ssh/config
</code>```

Title: How to fix ssh permission in home dir

Body:
I have trouble with my ssh config, I have directory /homa/ivan/.ssh but after my manipulation I have access denied for that derictory. At that moment I have
drwx------    2 root root   4096 Dec  5 14:20 .ssh

after change owner I have

Bad owner or permissions on /home/ivan/.ssh/config

but I vae owner ivan

drwx------  2 ivan ivan 4096 Дек  5 14:55 .
drwxr-xr-x 32 ivan ivan 4096 Дек  5 14:03 ..
-rwxrwxrwx  1 ivan ivan  106 Ноя 26 22:48 config
-rwxrwxrwx  1 ivan ivan 1675 Дек  5 14:20 id_rsa
-rwxrwxrwx  1 ivan ivan  394 Дек  5 14:20 id_rsa.pub
-rwxrwxrwx  1 ivan ivan 3982 Ноя 28 19:04 known_hosts

how to correct tune permission for ssh config and key ?

Body:
I solved it

chmod 600 ~/.ssh/config