问:
How can I show file sizes with commas when getting a directory listing with 'ls -l'?
You can do 'ls -l' to get a detailed directory listing like this:

```<code>-rw-rw-rw-  1 alice themonkeys 1159995999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob         244251992 2008-08-20 05:30 bar.txt
</code>```

But notice how you have to slide your finger along the screen to figure out the order of magnitude of those file sizes.

What's a good way to add commas to the file sizes in the directory listing, like this:

```<code>-rw-rw-rw-  1 alice themonkeys 1,159,995,999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob          244,251,992 2008-08-20 05:30 bar.txt
</code>```

答:
Actually, I was looking for a test for a young trainee and this seemed ideal.  Here's what he came up with:

```<code>for i in $(ls -1)
do
    sz=$(expr $(ls -ld $i | awk '{print $5}' | wc -c) - 1)
    printf "%10d %s\n" $sz $i
done
</code>```

It gives the order of magnitude for the size in a horribly inefficient way. I'll make this community wiki since we're both interested how you rate his code, but I don't want my rep suffering.

Feel free to leave comments (be gentle, he's a newbie, though you wouldn't guess it by his shell scripting :-).

OwnerDisplayName: dreeves

Body:
You can do 'ls -l' to get a detailed directory listing like this:

-rw-rw-rw-  1 alice themonkeys 1159995999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob         244251992 2008-08-20 05:30 bar.txt

But notice how you have to slide your finger along the screen to figure out the order of magnitude of those file sizes.

What's a good way to add commas to the file sizes in the directory listing, like this:

-rw-rw-rw-  1 alice themonkeys 1,159,995,999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob          244,251,992 2008-08-20 05:30 bar.txt

Body:
Actually, I was looking for a test for a young trainee and this seemed ideal.  Here's what he came up with:

for i in $(ls -1)
do
    sz=$(expr $(ls -ld $i | awk '{print $5}' | wc -c) - 1)
    printf "%10d %s\n" $sz $i
done

It gives the order of magnitude for the size in a horribly inefficient way. I'll make this community wiki since we're both interested how you rate his code, but I don't want my rep suffering.

Feel free to leave comments (be gentle, he's a newbie, though you wouldn't guess it by his shell scripting :-).

OwnerDisplayName: Pax


来源: stackexchange

问:
How do I guarantee node order for an XPath 'OR' query
I have a snippet of XML that looks like

```<code><body>
   Some text....
   <nodeA>....</nodeA>
   more text
   <someOtherNode>
      <nodeA>.......</nodeA>
   </someOtherNode>
   <nodeB>.......</nodeB>
   etc.....
</body>
</code>```

I'm selecting all nodeA and NodeB nodes inside  using an XPATH query similar to
//nodeA|//nodeB

As I understand it, .NET supports XPath 1.0 which does not guarantee node order.

How can I guarantee selected nodes are returned in document order in my OR query : that's to say:

```<code>nodeA, nodeA, nodeB
</code>```

答:
You have to sort the nodes outside of XPath. So iterate through the nodes in the node-set and add them to a collection, which you then sort using XPathNavigator.ComparePosition for comparisons.

Either that or use an XPath 2.0 implementation for .NET

ContentLicense: CC BY-SA 2.5

Body:
I have a snippet of XML that looks like

   Some text....
   <nodeA>....</nodeA>
   more text
   <someOtherNode>
      <nodeA>.......</nodeA>
   </someOtherNode>
   <nodeB>.......</nodeB>
   etc.....

I'm selecting all nodeA and NodeB nodes inside  using an XPATH query similar to
//nodeA|//nodeB

As I understand it, .NET supports XPath 1.0 which does not guarantee node order.

How can I guarantee selected nodes are returned in document order in my OR query : that's to say:

nodeA, nodeA, nodeB


问:
Can't get GPS coordinates in android application
I use this code to get the current location's coordinates. When I start this activity, nothing happens. When I use this exact code in another application it worked. The only difference that I use this location-getter in a different class, not in MainActivity. When I open that app a service comes up and starts searching the coordinates. In this case (GetLocationPS) nothing happens.

What could be the problem?

build.gradle:

```<code>compile 'com.google.android.gms:play-services:11.0.2'
</code>```

GetLocationPS.java:

```<code>import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class GetLocationPS extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

private static final String TAG = "MainActivity";
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;

private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */

private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_location_ps);

    mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
    mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

    checkLocation(); //check whether location service is enable or not in your  phone
}

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

    startLocationUpdates();

    mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if(mLocation == null){
        startLocationUpdates();
    }
    if (mLocation != null) {

        // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
        //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
    } else {
        Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
    }
}

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

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}

@Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

protected void startLocationUpdates() {
    // Create the location request
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    // Request location updates
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
            mLocationRequest, this);
    Log.d("reque", "--->>>>");
}

@Override
public void onLocationChanged(Location location) {

    String msg = "Updated Location: " +
            Double.toString(location.getLatitude()) + "," +
            Double.toString(location.getLongitude());
    mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
    mLongitudeTextView.setText(String.valueOf(location.getLongitude() ));
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    // You can now create a LatLng Object for use with maps
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}

private boolean checkLocation() {
    if(!isLocationEnabled())
        showAlert();
    return isLocationEnabled();
}

private void showAlert() {
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Enable Location")
            .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                    "use this app")
            .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                }
            });
    dialog.show();
}

private boolean isLocationEnabled() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
}
</code>```

答:
Hope this might help

Edit:

```<code>public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100;

    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
    mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));

        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        if (!checkPermissions()) requestPermissions();
    }

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

    @Override
    public void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(checkPermissions()) stopLocationUpdates();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(checkPermissions() && mGoogleApiClient.isConnected()) startLocationUpdates();
    }

    private void startLocationUpdates() {
        //noinspection MissingPermission
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    private void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    private boolean checkPermissions() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermissions() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
        }
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if(checkPermissions() && mGoogleApiClient.isConnected()) startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }

    @Override
    public void onLocationChanged(Location location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
        mLongitudeTextView.setText(String.valueOf(location.getLongitude()));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_ACCESS_FINE_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startLocationUpdates();
                } else {

                }
            }
        }
    }
}
</code>```

In onLocationChanged() you get location which you can use to get latitude and longitude. Also, this code does not give continuous location updates. For that you have to set UPDATE INTERVAL & FASTEST UPDATE INTERVAL in method createLocationRequest().

ContentLicense: CC BY-SA 3.0

Body:
I use this code to get the current location's coordinates. When I start this activity, nothing happens. When I use this exact code in another application it worked. The only difference that I use this location-getter in a different class, not in MainActivity. When I open that app a service comes up and starts searching the coordinates. In this case (GetLocationPS) nothing happens.

What could be the problem?

build.gradle:

compile 'com.google.android.gms:play-services:11.0.2'

GetLocationPS.java:

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class GetLocationPS extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

private static final String TAG = "MainActivity";
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;

private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */

private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_location_ps);

    mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
    mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

    checkLocation(); //check whether location service is enable or not in your  phone
}

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

    startLocationUpdates();

    mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if(mLocation == null){
        startLocationUpdates();
    }
    if (mLocation != null) {

        // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
        //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
    } else {
        Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
    }
}

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

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}

@Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

protected void startLocationUpdates() {
    // Create the location request
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    // Request location updates
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
            mLocationRequest, this);
    Log.d("reque", "--->>>>");
}

@Override
public void onLocationChanged(Location location) {

    String msg = "Updated Location: " +
            Double.toString(location.getLatitude()) + "," +
            Double.toString(location.getLongitude());
    mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
    mLongitudeTextView.setText(String.valueOf(location.getLongitude() ));
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    // You can now create a LatLng Object for use with maps
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}

private boolean checkLocation() {
    if(!isLocationEnabled())
        showAlert();
    return isLocationEnabled();
}

private void showAlert() {
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Enable Location")
            .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                    "use this app")
            .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                }
            });
    dialog.show();
}

private boolean isLocationEnabled() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
}

Body:
Hope this might help

Edit:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100;

    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
    mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));

        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        if (!checkPermissions()) requestPermissions();
    }

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

    @Override
    public void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(checkPermissions()) stopLocationUpdates();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(checkPermissions() && mGoogleApiClient.isConnected()) startLocationUpdates();
    }

    private void startLocationUpdates() {
        //noinspection MissingPermission
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    private void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    private boolean checkPermissions() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermissions() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
        }
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if(checkPermissions() && mGoogleApiClient.isConnected()) startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }

    @Override
    public void onLocationChanged(Location location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
        mLongitudeTextView.setText(String.valueOf(location.getLongitude()));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_ACCESS_FINE_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startLocationUpdates();
                } else {

                }
            }
        }
    }
}

In onLocationChanged() you get location which you can use to get latitude and longitude. Also, this code does not give continuous location updates. For that you have to set UPDATE INTERVAL & FASTEST UPDATE INTERVAL in method createLocationRequest().


问:
ReactJS: Uncaught ReferenceError: [function] not defined, July 2017
Attempting to turn a JSON file into an array, then randomly selecting 5 items from it.

I think the issue is my render/return statement at the bottom of ImageContainer.js, but I'm a ReactJS n00b, so it could be anything.

Any help or advice is greatly appreciated.

Console Error

```<code>compiled.js:31562 Uncaught ReferenceError: selectImages is not defined
  at ImageContainer.render (compiled.js:31562)
  at compiled.js:20195
  at measureLifeCyclePerf (compiled.js:19475)
  at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (compiled.js:20194)
  at ReactCompositeComponentWrapper._renderValidatedComponent (compiled.js:20221)
  at ReactCompositeComponentWrapper.performInitialMount (compiled.js:19761)
  at ReactCompositeComponentWrapper.mountComponent (compiled.js:19657)
  at Object.mountComponent (compiled.js:4009)
  at ReactDOMComponent.mountChildren (compiled.js:24150)
  at ReactDOMComponent._createInitialChildren (compiled.js:21126)
</code>```

ImageContainer.js - pulls img info from a .JSON file, randomly selects 5 to render

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
  constructor(props) {
    super(props);

    this.numImages = 5;

    this.state = {
      data: []
    };
  }

  componentDidMount() {
    $.ajax({
      url: '../app/data/namegame-data.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  shuffleArray(array) {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  selectImages({ data }) {
    const shuffledImages = shuffleArray(images);
    return (
      shuffledImages.map((data, idx) => {
        for (let i = 0; i < this.numImages; i++) {
            if (this.state.data.length > 0) {
                return <Image key={idx} name={data.name} src={data.src} />;
            }
        }
      })
    );
  }

  render() {
    return {selectImages};
  }
}
</code>```

Image.js - just the image HTML

```<code>import React from 'react';

export class Image extends React.Component {
    render() {
        const key = this.props.id;
        const name = this.props.name;
        const src = this.props.src;
        return (
            <picture>
                <img id="pic-template" className="pic" src="{src}" name="{name}" key="id" />
            </picture>
        );
    }
}
</code>```

[Main].js - most of the HTML is here, just including the import bits

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { ImageContainer } from './ImageContainer';

export default class NameGame extends React.Component {
  render () {
    return (
      ...
      <div id="images-wrap">
          <ImageContainer />
      </div>
      ...
    );
  }
}
</code>```

Dependencies

```<code>{
  ...
  "dependencies": {
    "json-loader": "^0.5.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.5.0"
  }
}
</code>```

答:
i think "this" is where it goes wrong ;):

selectImages is part of the ImageContainer class,
meaning the function is scoped within this Class, so it should be this.selectImages

In the render you call selectimages

```<code>render() {
    return {this.selectImages()}; <-- its a function so u should call it as a function
}
</code>```

Remember selectimage should return a react component, but if it will return a array of items that
react will render you should wrap it, you cannot pas multiple react elements to render

so you should something like

```<code>render() {
    return (
        <div> <-- give render 1 react component wrapping the multiple components
            {this.selectImages()}; <-- its a function so u should call it as a function
        </div>
    )
}
</code>```

selectImages({ data }) <-- where is it getting data from ? i don't think data is needed , only if u gonna pass { data: 'whatever' } to the function

```<code>shuffledImages.map((data, idx) => {
 data will be the items from the shuffledImages array
})

const shuffledImages = shuffleArray(images); should be ->
const shuffledImages = this.shuffleArray(images);
</code>```

about your other question

```<code>shuffleArray() {
  (array) <-- u are mutating the data from the state, when u passed it to the function, u should only change state with setState.

     use another shuffle function where u dont mutate the data ,use concat or es6 spread operator [ ...data ] etc .
</code>```

read: "Correct modification of state arrays in ReactJS"

}

```<code>    selectImages() {
      const shuffledImages = this.shuffleArray(this.state.data); <-- u dont have to pass this.state.data, to the function ,it is accessable within shufflarray -> const shuffledImages = this.shuffleArray();

      return (
          shuffledImages.map((data, idx) => {
            for (let i = 0; i < this.numImages; i++) {
                return <Image key={idx} name={this.state.data.name} src={this.state.data.src} />;
            }
          })
      );
    }
</code>```

if ur ajax call fails array is undefined. and u cannot call length on undefined. (thats what the error says)- about ur call

u need to tell ur ajax call what to do, is it a post or get?
add a 'type' (it should be type: 'get', )

or use the shorthand (i see u are using jquery)

```<code>$.getJSON('whateverjson file.json').done(function(response) {
    console.log("Success");
}).fail(function() {
    console.log("Error");
});
</code>```

About the data ->

```<code>u should parse the json setstate({ data: JSON.parse(data) }) or setstate({ data: $.parseJSON(data) });
</code>```

I must say using jquery, in combination with react, is not something i should recommend, jquery is mostly used for dom manipulation, react uses its virtual dom, and to include the whole jquery library for only the ajax requests is a waste.

try 'fetch' <==

PS look into https://facebook.github.io/react/docs/react-api.html (react docs)

Its also best to pass results of api calls to the component as props, but u will figure that out once u dive into the docs! i hope this helps u, good luck m8

Body:
Attempting to turn a JSON file into an array, then randomly selecting 5 items from it.

I think the issue is my render/return statement at the bottom of ImageContainer.js, but I'm a ReactJS n00b, so it could be anything.

Any help or advice is greatly appreciated.

Console Error

compiled.js:31562 Uncaught ReferenceError: selectImages is not defined
  at ImageContainer.render (compiled.js:31562)
  at compiled.js:20195
  at measureLifeCyclePerf (compiled.js:19475)
  at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (compiled.js:20194)
  at ReactCompositeComponentWrapper._renderValidatedComponent (compiled.js:20221)
  at ReactCompositeComponentWrapper.performInitialMount (compiled.js:19761)
  at ReactCompositeComponentWrapper.mountComponent (compiled.js:19657)
  at Object.mountComponent (compiled.js:4009)
  at ReactDOMComponent.mountChildren (compiled.js:24150)
  at ReactDOMComponent._createInitialChildren (compiled.js:21126)

ImageContainer.js - pulls img info from a .JSON file, randomly selects 5 to render

import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
  constructor(props) {
    super(props);

    this.numImages = 5;

    this.state = {
      data: []
    };
  }

  componentDidMount() {
    $.ajax({
      url: '../app/data/namegame-data.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  shuffleArray(array) {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  selectImages({ data }) {
    const shuffledImages = shuffleArray(images);
    return (
      shuffledImages.map((data, idx) => {
        for (let i = 0; i < this.numImages; i++) {
            if (this.state.data.length > 0) {
                return <Image key={idx} name={data.name} src={data.src} />;
            }
        }
      })
    );
  }

  render() {
    return {selectImages};
  }
}

Image.js - just the image HTML

import React from 'react';

export class Image extends React.Component {
    render() {
        const key = this.props.id;
        const name = this.props.name;
        const src = this.props.src;
        return (
            <picture>

            </picture>
        );
    }
}

[Main].js - most of the HTML is here, just including the import bits

import React from 'react';
import ReactDOM from 'react-dom';
import { ImageContainer } from './ImageContainer';

export default class NameGame extends React.Component {
  render () {
    return (
      ...

          <ImageContainer />

      ...
    );
  }
}

Dependencies

{
  ...
  "dependencies": {
    "json-loader": "^0.5.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.5.0"
  }
}

Body:
i think "this" is where it goes wrong ;):

selectImages is part of the ImageContainer class,
meaning the function is scoped within this Class, so it should be this.selectImages

In the render you call selectimages

render() {
    return {this.selectImages()}; <-- its a function so u should call it as a function
}

Remember selectimage should return a react component, but if it will return a array of items that
react will render you should wrap it, you cannot pas multiple react elements to render

so you should something like

render() {
    return (
        <div> <-- give render 1 react component wrapping the multiple components
            {this.selectImages()}; <-- its a function so u should call it as a function
        </div>
    )
}

selectImages({ data }) <-- where is it getting data from ? i don't think data is needed , only if u gonna pass { data: 'whatever' } to the function

shuffledImages.map((data, idx) => {
 data will be the items from the shuffledImages array
})

const shuffledImages = shuffleArray(images); should be ->
const shuffledImages = this.shuffleArray(images);

about your other question

shuffleArray() {
  (array) <-- u are mutating the data from the state, when u passed it to the function, u should only change state with setState.

     use another shuffle function where u dont mutate the data ,use concat or es6 spread operator [ ...data ] etc .

read: "Correct modification of state arrays in ReactJS"

}

    selectImages() {
      const shuffledImages = this.shuffleArray(this.state.data); <-- u dont have to pass this.state.data, to the function ,it is accessable within shufflarray -> const shuffledImages = this.shuffleArray();

      return (
          shuffledImages.map((data, idx) => {
            for (let i = 0; i < this.numImages; i++) {
                return <Image key={idx} name={this.state.data.name} src={this.state.data.src} />;
            }
          })
      );
    }

if ur ajax call fails array is undefined. and u cannot call length on undefined. (thats what the error says)- about ur call

u need to tell ur ajax call what to do, is it a post or get?
add a 'type' (it should be type: 'get', )

or use the shorthand (i see u are using jquery)

$.getJSON('whateverjson file.json').done(function(response) {
    console.log("Success");
}).fail(function() {
    console.log("Error");
});

About the data ->

u should parse the json setstate({ data: JSON.parse(data) }) or setstate({ data: $.parseJSON(data) });

I must say using jquery, in combination with react, is not something i should recommend, jquery is mostly used for dom manipulation, react uses its virtual dom, and to include the whole jquery library for only the ajax requests is a waste.

try 'fetch' <==

PS look into https://facebook.github.io/react/docs/react-api.html (react docs)

Its also best to pass results of api calls to the component as props, but u will figure that out once u dive into the docs! i hope this helps u, good luck m8


问:
Time date format, Converting no of hours into ISO8601 format
I have a time  in "no of hours", where '0' refers to 12am, '1 refers to 1pm' and so on until 23 hours. Is there any way to convert these number of hours into  "ISO8601" format.    P.S: I have date in proper format</p>

答:
Use the following:

```<code>import time
time.strftime("%H:%M:%S", time.gmtime(3600 * x))
</code>```

X could your value from 0 to 12.

Body:
Use the following:

import time
time.strftime("%H:%M:%S", time.gmtime(3600 * x))

X could your value from 0 to 12.


问:
How can I display two lists with each li element vertically under each other?
I have two separate lists (however I'm open for an example on how to just have one). The first list is information (such as 'title', 'length' 'release date') and the second list is the answers to the information (such as '50 Shades of Grey', '50 minutes' and '2015').

Here is my desired output and as you can see, the answers to the information is vertically centered under the information:

(Note there could be more information such as members of the cast, the budget e.g)

I have tried using Flex however the two lists are displayed separately on top of each other:

ul {
   white-space:nowrap;
}

li {
   display: flex;
   justify-content: center;
   flex-direction: column;
   text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Title</li>
<li>Length</li>
<li>Release Date</li>
</ul>
<ul>
<li>50 Shades of Grey</li>
<li>50 minutes</li>
<li>2015</li>
</ul></code>```

答:
Here's one method, using a single ul and flexbox:

ul {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  flex: 1;
  text-align: center;
}

h2, p {
  white-space: nowrap; /* optional */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    <h2>Title</h2>
    <p>50 Shades of Grey</p>
    <p>another title</p>
    <p>another title</p>
    <p>another title</p>
  </li>
  <li>
    <h2>Length</h2>
    <p>50 minutes</p>
    <p>another length</p>
    <p>another length</p>
    <p>another length</p>
  </li>
  <li>
    <h2>Release Date</h2>
    <p>2015</p>
    <p>another year</p>
    <p>another year</p>
    <p>another year</p>
  </li>
</ul></code>```

If you want to go hard-core semantic, you could nest the content of each li in another list, since they are also lists.

Body:
I have two separate lists (however I'm open for an example on how to just have one). The first list is information (such as 'title', 'length' 'release date') and the second list is the answers to the information (such as '50 Shades of Grey', '50 minutes' and '2015').

Here is my desired output and as you can see, the answers to the information is vertically centered under the information:

(Note there could be more information such as members of the cast, the budget e.g)

I have tried using Flex however the two lists are displayed separately on top of each other:

ul {
   white-space:nowrap;
}

li {
   display: flex;
   justify-content: center;
   flex-direction: column;
   text-align: center;
}

Title

Length

Release Date

50 Shades of Grey

50 minutes

2015

Body:
Here's one method, using a single ul and flexbox:

ul {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  flex: 1;
  text-align: center;
}

h2, p {
  white-space: nowrap; /* optional */
}

<ul>
  <li>
    <h2>Title</h2>
    <p>50 Shades of Grey</p>
    <p>another title</p>
    <p>another title</p>
    <p>another title</p>
  </li>
  <li>
    <h2>Length</h2>
    <p>50 minutes</p>
    <p>another length</p>
    <p>another length</p>
    <p>another length</p>
  </li>
  <li>
    <h2>Release Date</h2>
    <p>2015</p>
    <p>another year</p>
    <p>another year</p>
    <p>another year</p>
  </li>
</ul>

If you want to go hard-core semantic, you could nest the content of each li in another list, since they are also lists.


问:
Full Json match with RestAssured
I'm using REST-Assured to test some API. My API clearly respond with a JSON and according to the doc if this is the response:

```<code>{
    "id": "390",
    "data": {
        "leagueId": 35,
        "homeTeam": "Norway",
        "visitingTeam": "England",
    },
    "odds": [{
        "price": "1.30",
        "name": "1"
    },
    {
        "price": "5.25",
        "name": "X"
    }]
}
</code>```

I could test like this:

```<code>@Test
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
   get("/events?id=390")
      .then()
         .statusCode(200)
         .assertThat()
            .body("data.leagueId", equalTo(35));
}
</code>```

Surely this is readable but I would a full comparison of the JSON (i.e.: this is the JSON response; this is a canned JSON - a resource file would be perfect - are those JSON equals?). Does REST-Assured offer something like that or I need to make it manually.

答: REST Assured does not support JSON comparison, only schema and parts of the body as you have in your question. What you can do is using Hamcrest's JSON comparitorSameJSONAs in Hamcrest JSON SameJSONAs</p>

Title: Full Json match with RestAssured

Body:
I'm using REST-Assured to test some API. My API clearly respond with a JSON and according to the doc if this is the response:

{
    "id": "390",
    "data": {
        "leagueId": 35,
        "homeTeam": "Norway",
        "visitingTeam": "England",
    },
    "odds": [{
        "price": "1.30",
        "name": "1"
    },
    {
        "price": "5.25",
        "name": "X"
    }]
}

I could test like this:

@Test
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
   get("/events?id=390")
      .then()
         .statusCode(200)
         .assertThat()
            .body("data.leagueId", equalTo(35));
}

Surely this is readable but I would a full comparison of the JSON (i.e.: this is the JSON response; this is a canned JSON - a resource file would be perfect - are those JSON equals?). Does REST-Assured offer something like that or I need to make it manually.


问:
rxJs & angular 4 & restangular: stack errorInterceptors
In my angular 4 app I'm using ngx-restangular to handle all server calls. It returns observable as result, and this module has hooks to handle errors (like 401 etc).

But from documentation, i can handle 403 (401) so:

```<code>  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {

      refreshAccesstoken()
      .switchMap(refreshAccesstokenResponse => {
        //If you want to change request or make with it some actions and give the request to the repeatRequest func.
        //Or you can live it empty and request will be the same.

        // update Authorization header
        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

        return response.repeatRequest(response.request);
      })
      .subscribe(
        res => responseHandler(res),
        err => subject.error(err)
      );

      return false; // error handled
    }
    return true; // error not handled
  });
</code>```

and this is good for one request, which has broken with 403 error.
how can i stack this calls using rxJs? Becouse now, for example, i have 3 requests, which have 403 and for each this broken request I'm refreshing token - this is not so good, i have to update my token and then repeat all my broken requests. How can I achive this using Observables?

In angular 1 it was pretty easy:

```<code>Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
  if (response.status == 403) {
    // send only one request if multiple errors exist
    if (!refreshingIsInProgress) {
      refreshingIsInProgress = AppApi.refreshAccessToken(); // Returns promise
    }

    $q.when(refreshingIsInProgress, function () {
      refreshingIsInProgress = null;

      setHeaders(response.config.headers);

      // repeat request with error
      $http(response.config).then(responseHandler, deferred);
    }, function () {
      refreshingIsInProgress = null;

      $state.go('auth');
    });

    return false; // stop the promise chain
  }

  return true;
});
</code>```

And all was working like a charm. But I'm new to rxJs & angular 4 and I don't have any idea how to achive this with observables and angular 4. Maybe somebody have an idea?

upd!
here is my refreshAccesstoken method

```<code>const refreshAccesstoken = function () {
  const refreshToken = http.post(environment.apiURL + `/token/refresh`,
    {refreshToken: 'someToken'});
  return refreshToken;
};
</code>```

答:
RxJs is not silver bullet, and in cases like this it can complicate things even more.

While it may be possible to combine several operators and have if-blocks, retry-blocks within single observable stream, in the end solution will be too complicated, difficult to support, understand and refactor. This is particularly true for http handling.

Body:
In my angular 4 app I'm using ngx-restangular to handle all server calls. It returns observable as result, and this module has hooks to handle errors (like 401 etc).

But from documentation, i can handle 403 (401) so:

  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {

      refreshAccesstoken()
      .switchMap(refreshAccesstokenResponse => {
        //If you want to change request or make with it some actions and give the request to the repeatRequest func.
        //Or you can live it empty and request will be the same.

        // update Authorization header
        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

        return response.repeatRequest(response.request);
      })
      .subscribe(
        res => responseHandler(res),
        err => subject.error(err)
      );

      return false; // error handled
    }
    return true; // error not handled
  });

and this is good for one request, which has broken with 403 error.
how can i stack this calls using rxJs? Becouse now, for example, i have 3 requests, which have 403 and for each this broken request I'm refreshing token - this is not so good, i have to update my token and then repeat all my broken requests. How can I achive this using Observables?

In angular 1 it was pretty easy:

Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
  if (response.status == 403) {
    // send only one request if multiple errors exist
    if (!refreshingIsInProgress) {
      refreshingIsInProgress = AppApi.refreshAccessToken(); // Returns promise
    }

    $q.when(refreshingIsInProgress, function () {
      refreshingIsInProgress = null;

      setHeaders(response.config.headers);

      // repeat request with error
      $http(response.config).then(responseHandler, deferred);
    }, function () {
      refreshingIsInProgress = null;

      $state.go('auth');
    });

    return false; // stop the promise chain
  }

  return true;
});

And all was working like a charm. But I'm new to rxJs & angular 4 and I don't have any idea how to achive this with observables and angular 4. Maybe somebody have an idea?

upd!
here is my refreshAccesstoken method

const refreshAccesstoken = function () {
  const refreshToken = http.post(environment.apiURL + `/token/refresh`,
    {refreshToken: 'someToken'});
  return refreshToken;
};


问:
MVVM framework AND Prism 4?
I just read this question. It has some nice answers, but they are over 1-year-old, and a lot have changed in this space over the last year. Some of the most popular frameworks have come out in a new mayor release such as Prism and MVVM Light Toolkit.

My question is somehow the same, but with one twist, I'm already using Prism 4.0 because of the region and module features.

Prism 4.0 embraces MVVM, but I feel there are some things which are "not lightweight", for instance interaction requests.
So I'm thinking would it better to use another MVVM framework either as a substitute or a supplement for Prism 4.0?

答: There's nothing to stop you using an MVVM framework in addition to Prism.  We're using Caliburn.Micro and Prism - there is some crossover in functionality provided, and many differences too.  Use whatever tool is most appropriate for the problem you're solving.</p>

Title: MVVM framework AND Prism 4?


问:
Android Drawing Separator/Divider Line in Layout?
I would like to draw a line right in the middle of a layout and use it as a separator of other items like TextView. Is there a good widget for this.  I don't really want to use an image as it would be hard to match the other components to it.  And I want it to be relatively positioned as well.  Thanks</p>

答:
```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<item
    android:bottom="0dp"
    android:left="-2dp"
    android:right="-2dp"
    android:top="-2dp">
    <shape android:shape="rectangle">
        <stroke
            android:width="1dp"
            android:color="@color/divider" />
    </shape>
</item>
</code>```


问:
Select element in collection satisfying max in Clojure
The following expression

```<code>(reduce (fn [[c x y] [s k d]] (if (< c s) [s k d] [c x y])) [0 0 0] colls)
</code>```

Is for the element [e, x, y] in colls such that e is the maximum among all in the tuples in colls.

Is there already an idiomatic expression in Clojure for that? I guess that with macro, it should be possible to express it with brevity.

I feel that Python/numpy/panda has some good example.

答:
You can use max-key:

```<code>(apply max-key first colls)
</code>```

Body:
The following expression

(reduce (fn [[c x y] [s k d]] (if (< c s) [s k d] [c x y])) [0 0 0] colls)

Is for the element [e, x, y] in colls such that e is the maximum among all in the tuples in colls.

Is there already an idiomatic expression in Clojure for that? I guess that with macro, it should be possible to express it with brevity.

I feel that Python/numpy/panda has some good example.

Body:
You can use max-key:

(apply max-key first colls)


问:
How to match 2 columns in excel?
I have an excel sheet, sheet1 which has 2 cols, A and B. Col A has some values and has corresponding mapping in col B(not all values in A have a mapping in B, some are empty). The sorting is done from Z-A and w.r.to Col A. I have another excel sheet, sheet2 which has similar Col A and Col B. Now, i want to find out whether any match is there between Col A of sheet1 and Col A of sheet2. If matches are found, those values should be copied onto a new column.</p>

Title: How to match 2 columns in excel?


问:
HTML5 live streaming
For school I need to set up an HTML5 live stream site. They have a flash stream-player they've been using but now they want it to use HTML5 instead. How can I do this? I tried using the video tag but I can't get it working. Below is the code I have. Could someone point me in the correct direction?</p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Deltion Live Streaming</title>
    <script language="javascript" type="text/javascript" src="../swfobject.js"></script>
</head>

<body>

    <video id="movie" width="460" height="306" preload autoplay>
        <source src="rtmp://fl2.sz.xlcdn.com:80/sz=Deltion_College=lb1"  type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
            <!-- HERE THE CODE FOR THE ALTERNATIVE PLAYER (FLASH) WILL BE! -->
    </video>
</body>
</html>
</code>```

答:
Firstly you need to setup a media streaming server. You can use Wowza, red5 or nginx-rtmp-module. Read their documentation and setup on OS you want.
All the engine are support HLS (Http Live Stream protocol that was developed by Apple). You should read documentation for config.
Example with nginx-rtmp-module:

```<code>rtmp {
    server {
        listen 1935; # Listen on standard RTMP port
        chunk_size 4000;

        application show {
            live on;
            # Turn on HLS
            hls on;
            hls_path /mnt/hls/;
            hls_fragment 3;
            hls_playlist_length 60;
            # disable consuming the stream from nginx as rtmp
            deny play all;
        }
    }
}

server {
    listen 8080;

    location /hls {
        # Disable cache
        add_header Cache-Control no-cache;

        # CORS setup
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        add_header 'Access-Control-Allow-Headers' 'Range';

        # allow CORS preflight requests
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Headers' 'Range';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }

        root /mnt/;
    }
}
</code>```

After server was setup and configuration successful. you must use some rtmp encoder software (OBS, wirecast ...) for start streaming like youtube or twitchtv.

In client side (browser in your case) you can use Videojs or JWplayer to play video for end user. You can do something like below for Videojs:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Live Streaming</title>
    <link href="//vjs.zencdn.net/5.8/video-js.min.css" rel="stylesheet">
    <script src="//vjs.zencdn.net/5.8/video.min.js"></script>
</head>
<body>
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls preload="none">
    <source src="http://localhost:8080/hls/stream.m3u8" type="application/x-mpegURL" />
</video>
<script>
    var player = videojs('#player');
</script>
</body>
</html>
</code>```

You don't need to add others plugin like flash (because we use HLS not rtmp). This player can work well cross browser with out flash.

Title: HTML5 live streaming

Body:
For school I need to set up an HTML5 live stream site. They have a flash stream-player they've been using but now they want it to use HTML5 instead. How can I do this? I tried using the video tag but I can't get it working. Below is the code I have. Could someone point me in the correct direction?

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Deltion Live Streaming</title>

    <video id="movie" width="460" height="306" preload autoplay>
        <source src="rtmp://fl2.sz.xlcdn.com:80/sz=Deltion_College=lb1"  type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>

    </video>

Body:
Firstly you need to setup a media streaming server. You can use Wowza, red5 or nginx-rtmp-module. Read their documentation and setup on OS you want.
All the engine are support HLS (Http Live Stream protocol that was developed by Apple). You should read documentation for config.
Example with nginx-rtmp-module:

rtmp {
    server {
        listen 1935; # Listen on standard RTMP port
        chunk_size 4000;

        application show {
            live on;
            # Turn on HLS
            hls on;
            hls_path /mnt/hls/;
            hls_fragment 3;
            hls_playlist_length 60;
            # disable consuming the stream from nginx as rtmp
            deny play all;
        }
    }
}

server {
    listen 8080;

    location /hls {
        # Disable cache
        add_header Cache-Control no-cache;

        # CORS setup
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        add_header 'Access-Control-Allow-Headers' 'Range';

        # allow CORS preflight requests
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Headers' 'Range';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }

        root /mnt/;
    }
}

After server was setup and configuration successful. you must use some rtmp encoder software (OBS, wirecast ...) for start streaming like youtube or twitchtv.

In client side (browser in your case) you can use Videojs or JWplayer to play video for end user. You can do something like below for Videojs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Live Streaming</title>
    <link href="//vjs.zencdn.net/5.8/video-js.min.css" rel="stylesheet">
    <script src="//vjs.zencdn.net/5.8/video.min.js"></script>
</head>
<body>
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls preload="none">
    <source src="http://localhost:8080/hls/stream.m3u8" type="application/x-mpegURL" />
</video>
<script>
    var player = videojs('#player');
</script>
</body>
</html>

You don't need to add others plugin like flash (because we use HLS not rtmp). This player can work well cross browser with out flash.


问:
Progress bar c++
I'm creating a simple server console application. This server works on Windows.

I'd like to make a progress bar and print it while server is sending files to the client. But I don't know how to implement it using winapi.

Could someone explain ?

答:
You can write on the same line of the console using the carriage return (\r). With this technique you can basically override the old progress an print the new one, which results in a "moving" progressbar. This works independent of any api, just with c++ and it worked on the windows console.

```<code>int barLength = 30;
int pos = progress * barLength;

std::cout << "[";
for(int i=0; i != barLength; ++i)
{
    if(i < pos)
        std::cout << "#";
    else
        std::cout << " ";
}
std::cout << "]\r";
</code>```

You get the concept and can adapt the look to your needs.
Just pass the progress value as double to this (100% = 1.0).
It might be useful to write a part, if the progress is 1.0, so that a complete bar is printed with a \n or std::endl at the end.

Title: Progress bar c++

Body:
You can write on the same line of the console using the carriage return (\r). With this technique you can basically override the old progress an print the new one, which results in a "moving" progressbar. This works independent of any api, just with c++ and it worked on the windows console.

int barLength = 30;
int pos = progress * barLength;

std::cout << "[";
for(int i=0; i != barLength; ++i)
{
    if(i < pos)
        std::cout << "#";
    else
        std::cout << " ";
}
std::cout << "]\r";

You get the concept and can adapt the look to your needs.
Just pass the progress value as double to this (100% = 1.0).
It might be useful to write a part, if the progress is 1.0, so that a complete bar is printed with a \n or std::endl at the end.


问:
Python Logging. Messages are with the same date
I get log messages with the same date when I print them to the console (or logfile). But the time-out between messages is two seconds.  Here is my code

```<code>folder = "logs"
log_name = {}.log
file_name = os.path.join(folder, log_name)

date_format = "%Y-%m-%d_%H:%M:%S"
name_format = "[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)s] - %(message)s"

log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter(name_format, datetime.now().strftime(date_format))

console_handler = logging.StreamHandler(sys.stderr)
file_handler = handlers.RotatingFileHandler(filename=datetime.now().strftime(file_name.format(date_format)),
                                            maxBytes=(1048576*5),
                                            backupCount=7)
console_handler.setFormatter(format)
file_handler.setFormatter(format)

log.addHandler(console_handler)
log.addHandler(file_handler)

from time import sleep
log.info("1")
sleep(2)
log.info("2")
sleep(2)
log.info("3")
</code>```

Here is output:

```<code>[2017-07-08_17:20:51] [INFO] [logs.py:112] - 1
[2017-07-08_17:20:51] [INFO] [logs.py:114] - 2
[2017-07-08_17:20:51] [INFO] [logs.py:116] - 3
</code>```

答:
have a look at the documentation of logging.Formatter(fmt=None, datefmt=None, style='%'). the second argument you need to pass is a datefmt ("%Y-%m-%d_%H:%M:%S" in your case). the logger will do the fmt.strftime(...) for you.

you are passing a string that represents datetime.now() in this format. as this is a str (e.g. '2017-07-08_17:20:51') the formatter does not complain but always prints this exact date: '2017-07-08_17:20:51'.strftime(...) will result in '2017-07-08_17:20:51' - there are no format specifiers to fill in.

what you should do is this:

```<code>fmt = logging.Formatter(name_format, date_format)
# instead of
# format = logging.Formatter(name_format, datetime.now().strftime(date_format))
</code>```

(btw: format is a built-in; renamed your formatter to fmt such that the built-in is not overwritten).

Body:
I get log messages with the same date when I print them to the console (or logfile). But the time-out between messages is two seconds.  Here is my code

folder = "logs"
log_name = {}.log
file_name = os.path.join(folder, log_name)

date_format = "%Y-%m-%d_%H:%M:%S"
name_format = "[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)s] - %(message)s"

log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter(name_format, datetime.now().strftime(date_format))

console_handler = logging.StreamHandler(sys.stderr)
file_handler = handlers.RotatingFileHandler(filename=datetime.now().strftime(file_name.format(date_format)),
                                            maxBytes=(1048576*5),
                                            backupCount=7)
console_handler.setFormatter(format)
file_handler.setFormatter(format)

log.addHandler(console_handler)
log.addHandler(file_handler)

from time import sleep
log.info("1")
sleep(2)
log.info("2")
sleep(2)
log.info("3")

Here is output:

[2017-07-08_17:20:51] [INFO] [logs.py:112] - 1
[2017-07-08_17:20:51] [INFO] [logs.py:114] - 2
[2017-07-08_17:20:51] [INFO] [logs.py:116] - 3

Body:
have a look at the documentation of logging.Formatter(fmt=None, datefmt=None, style='%'). the second argument you need to pass is a datefmt ("%Y-%m-%d_%H:%M:%S" in your case). the logger will do the fmt.strftime(...) for you.

you are passing a string that represents datetime.now() in this format. as this is a str (e.g. '2017-07-08_17:20:51') the formatter does not complain but always prints this exact date: '2017-07-08_17:20:51'.strftime(...) will result in '2017-07-08_17:20:51' - there are no format specifiers to fill in.

what you should do is this:

fmt = logging.Formatter(name_format, date_format)
# instead of
# format = logging.Formatter(name_format, datetime.now().strftime(date_format))

(btw: format is a built-in; renamed your formatter to fmt such that the built-in is not overwritten).


问:
input textbox larger than input-lg
I am trying to increase the size of my search textbox to something larger than input-lg (using Bootstrap 3). Is that possible? Couldn't find much in Bootstrap 3 docs or SO posts.

答:
I ended up doing the following. Thanks to @gianni's comment.

HTML

```<code><input class="form-control input-lg searchbox" name="query" type="text"  autocomplete="off">
</code>```

CSS

```<code>.searchbox {
  font-size: 23px;
  height: 60px;
  padding: 1px 7px;
  text-transform: capitalize; /* Capitalises first letter of each word only 'visually', value sent is as-typed */
}
</code>```

Title: input textbox larger than input-lg

Body:
I ended up doing the following. Thanks to @gianni's comment.

HTML

<input class="form-control input-lg searchbox" name="query" type="text"  autocomplete="off">

CSS

.searchbox {
  font-size: 23px;
  height: 60px;
  padding: 1px 7px;
  text-transform: capitalize; /* Capitalises first letter of each word only 'visually', value sent is as-typed */
}


问:
How do you get the Ruby on Rails generated id of a form element for reference in JavaScript?
When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the <input /> element that it outputs. How can I generate the same id for later inclusion into JavaScript generated later?

```<code><%= form_for @user do |f| %>
  <%= f.text_field :username %>
<% end %>
</code>```

Then later in the page:

```<code><%= javascript_tag do %>
  $('<%= id of the :username field %>').doSomethingReallyCool();
<% end %>
</code>```

答:
I assume that there are multiple form_for in the page and each has it's own submit button. I think this is how I would do this:

Have a hidden field in the the form_for and set it's value to the id of the input field. Here I've chosen input_#{n} as the id of the input field. Of course I'll define the id for each input.

```<code><%= form_for @user do |f| %>
  <%= f.text_field :username, id: "input_#{n}" %>
  <%= hidden_field_tag 'user[input_id]', value: "input_#{n}" %>
  <%= f.submit %>
<% end %>
</code>```

Then on submit I can get the id the form input in my params params[:user][:input_id] which I can pass to the js.erb using the locals.

Hope this helps :)

Body:
When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the <input /> element that it outputs. How can I generate the same id for later inclusion into JavaScript generated later?

<%= form_for @user do |f| %>
  <%= f.text_field :username %>
<% end %>

Then later in the page:

<%= javascript_tag do %>
  $('<%= id of the :username field %>').doSomethingReallyCool();
<% end %>

Body:
I assume that there are multiple form_for in the page and each has it's own submit button. I think this is how I would do this:

Have a hidden field in the the form_for and set it's value to the id of the input field. Here I've chosen input_#{n} as the id of the input field. Of course I'll define the id for each input.

<%= form_for @user do |f| %>
  <%= f.text_field :username, id: "input_#{n}" %>
  <%= hidden_field_tag 'user[input_id]', value: "input_#{n}" %>
  <%= f.submit %>
<% end %>

Then on submit I can get the id the form input in my params params[:user][:input_id] which I can pass to the js.erb using the locals.

Hope this helps :)


问:
Using mustache templates as partial views in Rails 4?
I'm trying to use mustache views in Rails 4 instead of some old partial views that hosted some HTML templates I am sharing with a javascript application.

Added config/initializers/mustache.rb

```<code># Tell Rails how to render mustache templates
module MustacheTemplateHandler
  def self.call(template)
    #assigns contains all the instance_variables defined on the controller's view method
    "Mustache.render(#{template.source.inspect}, assigns).html_safe"
  end
end

# Register a mustache handler in the Rails template engine
ActionView::Template.register_template_handler(:mustache, MustacheTemplateHandler)
</code>```

I named my template _template.mustache and put it the template in views/sales/_template.mustache and I can render it just fine from normal .html.erb with render partial: 'template'

Where do I put the Template.rb file for it to work with the mustache?

```<code>class Template < Mustache

  def something
    # return something
    "WOW"
  end

end
</code>```

答: So, you can write this variables directly to yours controller. </p>

Body:
I'm trying to use mustache views in Rails 4 instead of some old partial views that hosted some HTML templates I am sharing with a javascript application.

Added config/initializers/mustache.rb

# Tell Rails how to render mustache templates
module MustacheTemplateHandler
  def self.call(template)
    #assigns contains all the instance_variables defined on the controller's view method
    "Mustache.render(#{template.source.inspect}, assigns).html_safe"
  end
end

# Register a mustache handler in the Rails template engine
ActionView::Template.register_template_handler(:mustache, MustacheTemplateHandler)

I named my template _template.mustache and put it the template in views/sales/_template.mustache and I can render it just fine from normal .html.erb with render partial: 'template'

Where do I put the Template.rb file for it to work with the mustache?

class Template < Mustache

  def something
    # return something
    "WOW"
  end

end