问:
Ask location permissions inside service
I am getting the location data using a service, this service is started when my app runs on a activity, and i need that activity to ask for the permissions.

So basicly this is my service (it works fine)

```<code>public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0;
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 0;
    private static final float LOCATION_DISTANCE = 0f;
    private int updatePriority;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;

    private final IBinder mBinder = new LocalBinder();
    private Intent intent;
    private String provider;
    Context context;

    Location mLastLocation;

    public class LocalBinder extends Binder {
        public GoogleLocation getServerInstance() {
            return GoogleLocation.this;
        }
    }

    public Location getLocation() {
        Log.d("IMHERE", "HELLO");
        return mLastLocation;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        context = getApplicationContext();
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        initializeLocationManager();

        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        } else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
        } else {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        }

        this.buildGoogleApiClient();
        this.createLocationRequest();
        this.googleApiClient.connect();

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        // Request location updates
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        Log.d("localizacao",mLastLocation.toString());
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();

        this.googleApiClient.unregisterConnectionCallbacks(this);
        this.googleApiClient.unregisterConnectionFailedListener(this);
        this.googleApiClient.disconnect();
        this.mLastLocation = null;
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

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

    private void createLocationRequest() {
        this.locationRequest = new LocationRequest();
        this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        this.locationRequest.setPriority(updatePriority);

    }
</code>```

here is where i start it

```<code>package com.example.afcosta.inesctec.pt.android;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.afcosta.inesctec.pt.android.services.GoogleLocation;

public class LocationPermission extends AppCompatActivity {

    public static final int REQ_PERMISSION = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        askPermission();
        Intent i = new Intent(this,Login.class);
        startActivity(i);
    }

    // PEDIDO DE PERMISSÃO
    private void askPermission() {
        checkLocationPermission();
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission. ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission. ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Partilhar localização")
                        .setMessage("Permitir a partilha de dados sobre a sua localização?")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(LocationPermission.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission. ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            startService(new Intent(this, GoogleLocation.class));
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission. ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        startService(new Intent(this, GoogleLocation.class));
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }
}
</code>```

the thing is, i need to ask for permissions when he runs the app for the first time, or he has the location disabled. And that never happens.

I should just start the service when the user has give the permission.

Any help with this?

Thanks

答:
```<code>@Override
  protected Boolean processInBackground(Void... params) {
      PermissionResponse response = PermissionEverywhere.getPermission(getApplicationContext(),
      new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
              REQ_CODE,
              "Notification title",
              "This app need external permisison",
              R.launcher)
              .call();

      boolean isGranted = response.isGranted();

      if(isGrante){

        // here do your stuff
      }
  }
</code>```

Title: Ask location permissions inside service

Body:
I am getting the location data using a service, this service is started when my app runs on a activity, and i need that activity to ask for the permissions.

So basicly this is my service (it works fine)

public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0;
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 0;
    private static final float LOCATION_DISTANCE = 0f;
    private int updatePriority;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;

    private final IBinder mBinder = new LocalBinder();
    private Intent intent;
    private String provider;
    Context context;

    Location mLastLocation;

    public class LocalBinder extends Binder {
        public GoogleLocation getServerInstance() {
            return GoogleLocation.this;
        }
    }

    public Location getLocation() {
        Log.d("IMHERE", "HELLO");
        return mLastLocation;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        context = getApplicationContext();
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        initializeLocationManager();

        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        } else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
        } else {
            this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        }

        this.buildGoogleApiClient();
        this.createLocationRequest();
        this.googleApiClient.connect();

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        // Request location updates
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        Log.d("localizacao",mLastLocation.toString());
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();

        this.googleApiClient.unregisterConnectionCallbacks(this);
        this.googleApiClient.unregisterConnectionFailedListener(this);
        this.googleApiClient.disconnect();
        this.mLastLocation = null;
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

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

    private void createLocationRequest() {
        this.locationRequest = new LocationRequest();
        this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        this.locationRequest.setPriority(updatePriority);

    }

here is where i start it

package com.example.afcosta.inesctec.pt.android;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.afcosta.inesctec.pt.android.services.GoogleLocation;

public class LocationPermission extends AppCompatActivity {

    public static final int REQ_PERMISSION = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        askPermission();
        Intent i = new Intent(this,Login.class);
        startActivity(i);
    }

    // PEDIDO DE PERMISSÃO
    private void askPermission() {
        checkLocationPermission();
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission. ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission. ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Partilhar localização")
                        .setMessage("Permitir a partilha de dados sobre a sua localização?")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(LocationPermission.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission. ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            startService(new Intent(this, GoogleLocation.class));
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission. ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        startService(new Intent(this, GoogleLocation.class));
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }
}

the thing is, i need to ask for permissions when he runs the app for the first time, or he has the location disabled. And that never happens.

I should just start the service when the user has give the permission.

Any help with this?

Thanks


来源: stackexchange

问:
:focus styling on custom radio input
I have a custom radio input style that is implemented more or less like this:

```<code><input type="radio" id="testradio" class="visuallyhidden custom-radio">
<label for="testradio">...</label>

.custom-radio + label:before {
  content: ""
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
]
</code>```

This works great except for one nagging detail: the focus style for keyboard navigation. I can tab-select the group of radio buttons and use the arrow keys to change the selected one, but the default :focus outline doesn't appear because the input tag is hidden.

I tried adding my own focus style as above, but this ends up behaving differently than the default browser styling. By default, Chrome (and other browsers I assume) will draw an outline only when you are keyboard-selecting the radio inputs, not when you click them. However, the CSS :focus style seems to apply when clicking the radio input as well (or in this case, clicking the label), which looks really bad.

Basically my question is this: how do I apply a :focus style to a radio input that fully simulates the default browser behavior, i.e. does not appear from a mouse click focus? Or is there another way I can customize this radio input that will help me preserve the default behavior?

Edit: Here's a JSFiddle demonstrating what I'm talking about. On the first row, you can click a radio button and then navigate with the arrow keys - the outline only appears when you use the keyboard. On the second row, clicking the radio button immediately triggers the focus style.

http://jsfiddle.net/7Ltcks3n/1/

答:
The issue is that apparently Blink browsers maintain focus on radio elements after they are clicked, but Firefox and Safari don't.

As a workaround, you could add a class to the document on mousedown and touchstart that hides your added ring, and remove it on keydown.

Working example:

var className = 'focus-radio-hide-ring';
var add = function() {
    document.documentElement.classList.add(className);
};
var remove = function() {
    document.documentElement.classList.remove(className);
};
window.addEventListener('mousedown', add, true);
window.addEventListener('touchstart', add, true);
window.addEventListener('keydown', remove, true);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-radio {
 position: absolute;
 opacity: 0;
}
.custom-radio + label {
 cursor: pointer;
}
.custom-radio + label:before {
 content: "";
 display: inline-block;
 vertical-align: middle;
 width: 0.75em;
 height: 0.75em;
 margin-right: 0.25em;
 background: #EEEEEE;
 border: 1px solid #AAAAAA;
 border-radius: 50%;
}
.custom-radio:checked + label:before {
 background: #6666FF;
}

/* Add styles here: */
.custom-radio:focus + label:before {
 box-shadow: 0 0 4px 1px rgba(0, 0, 0, 1);
}
/* Add disable them again here: */
.focus-radio-hide-ring .custom-radio:focus + label:before {
 box-shadow: none;
}</code>```

<input placeholder="Tab from here">

<input id="testradio" type="radio" class="custom-radio">
Example```

ContentLicense: CC BY-SA 3.0

Title: :focus styling on custom radio input

Body:
I have a custom radio input style that is implemented more or less like this:

<input type="radio" id="testradio" class="visuallyhidden custom-radio">
...

.custom-radio + label:before {
  content: ""
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
]

This works great except for one nagging detail: the focus style for keyboard navigation. I can tab-select the group of radio buttons and use the arrow keys to change the selected one, but the default :focus outline doesn't appear because the input tag is hidden.

I tried adding my own focus style as above, but this ends up behaving differently than the default browser styling. By default, Chrome (and other browsers I assume) will draw an outline only when you are keyboard-selecting the radio inputs, not when you click them. However, the CSS :focus style seems to apply when clicking the radio input as well (or in this case, clicking the label), which looks really bad.

Basically my question is this: how do I apply a :focus style to a radio input that fully simulates the default browser behavior, i.e. does not appear from a mouse click focus? Or is there another way I can customize this radio input that will help me preserve the default behavior?

Edit: Here's a JSFiddle demonstrating what I'm talking about. On the first row, you can click a radio button and then navigate with the arrow keys - the outline only appears when you use the keyboard. On the second row, clicking the radio button immediately triggers the focus style.

http://jsfiddle.net/7Ltcks3n/1/

Body:
The issue is that apparently Blink browsers maintain focus on radio elements after they are clicked, but Firefox and Safari don't.

As a workaround, you could add a class to the document on mousedown and touchstart that hides your added ring, and remove it on keydown.

Working example:

var className = 'focus-radio-hide-ring';
var add = function() {
    document.documentElement.classList.add(className);
};
var remove = function() {
    document.documentElement.classList.remove(className);
};
window.addEventListener('mousedown', add, true);
window.addEventListener('touchstart', add, true);
window.addEventListener('keydown', remove, true);

.custom-radio {
 position: absolute;
 opacity: 0;
}
.custom-radio + label {
 cursor: pointer;
}
.custom-radio + label:before {
 content: "";
 display: inline-block;
 vertical-align: middle;
 width: 0.75em;
 height: 0.75em;
 margin-right: 0.25em;
 background: #EEEEEE;
 border: 1px solid #AAAAAA;
 border-radius: 50%;
}
.custom-radio:checked + label:before {
 background: #6666FF;
}

/* Add styles here: */
.custom-radio:focus + label:before {
 box-shadow: 0 0 4px 1px rgba(0, 0, 0, 1);
}
/* Add disable them again here: */
.focus-radio-hide-ring .custom-radio:focus + label:before {
 box-shadow: none;
}

<p><input placeholder="Tab from here"></p>

<input id="testradio" type="radio" class="custom-radio">
<label for="testradio">Example</label>


问:
Can't use git: "git fatal: unknown error occurred while reading the configuration files"
I can't use any git commands, they all result in the following error:

```<code>fatal: unknown error occurred while reading the configuration files
</code>```

Git was working fine up until I replaced my hard drive. I created a windows 10 system image and restored it on my new hard drive, and then combined the un-allocated disc space into my main partition.

I've tried re-installing and installing git, restarting my computer, and removing .gitconfig files, and pretty much every combination of those actions.

答: What finally fixed it was setting the HOME environment variable to point to something reasonable. Once this was done, git started behaving properly again</p>

Body:
I can't use any git commands, they all result in the following error:

fatal: unknown error occurred while reading the configuration files

Git was working fine up until I replaced my hard drive. I created a windows 10 system image and restored it on my new hard drive, and then combined the un-allocated disc space into my main partition.

I've tried re-installing and installing git, restarting my computer, and removing .gitconfig files, and pretty much every combination of those actions.


问:
Cookie not being saved
I am currently working on my API which is in charge of authentication and all the API endpoints being consumed on my SPA. The API is running on api.domain.com and the SPA is running on www.domain.com. All on the same SSL certificate (wildcard type).

Unfortunately when i return Set-cookie in the header from api.domain.com it is not saved, but i can see it in Chromes debugger.

My session is as following:

'Set-cookie':'__Secure-ID=38afes7a8-38afes7a8-38afes7a8-38afes7a8; Expires=Mon, 11-Sep-2017 23:03:13 GMT; Secure; HttpOnly; Domain=.domain.com'

Theres no problems retrieving it and reviewing it in the browser, but it won't stay and does not obey the Expire, it simply disappears when i navigate into other endpoints of api.domain.com or even www.domain.com.

What is the problem?

答: Your Expires field isn't using the proper format. You should change the Expires field to Mon, 11 Sep 2017 23:03:13 GMT.

Title: Cookie not being saved


问:
MomentJS: how to parse dates in MM/DD/YYYY & DD/MM/YYYY
How can i use moment.js in both: Australia & USA time formats?

For example:

07/08/2017 - is good for both time formats, but!

30/08/2017 - is invalid for moment.js, but i can have such dateTime

You can check it here:

http://jsfiddle.net/rLjQx/2135/

答:
In your fiddle you are using a very old version of moment (2.2.1), I suggest to upgrade it to lastest one (2.18.1).

Using a newer version, you will have a Deprecation Warning in your console:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

Following the link (and moment(String) docs) you will discover that you have to specify format to parse you string correctly.

As Billy Reilly suggested you can use moment(String, String[]) parsing function. Please remeber that:

Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:

Prefer formats resulting in valid dates over invalid ones.

Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.

Prefer formats earlier in the array than later.

So the way 07/08/2017 will be interpreted depends on the order of the format in array of formats parameter.

Here a snippet with some examples:

var now = moment('30/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now2 = moment('08/30/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now3 = moment('07/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);

console.log(now.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now2.format('MMM DD h:mm A'));// Aug 30 12:00 AM
console.log(now3.format('MMM DD h:mm A'));// Jul 08 12:00 AM

var now4 = moment('30/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now5 = moment('08/30/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now6 = moment('07/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);

console.log(now4.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now5.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now6.format('MMM DD h:mm A')); // Aug 07 12:00 AM```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
In your fiddle you are using a very old version of moment (2.2.1), I suggest to upgrade it to lastest one (2.18.1).

Using a newer version, you will have a Deprecation Warning in your console:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

Following the link (and moment(String) docs) you will discover that you have to specify format to parse you string correctly.

As Billy Reilly suggested you can use moment(String, String[]) parsing function. Please remeber that:

Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:

Prefer formats resulting in valid dates over invalid ones.

Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.

Prefer formats earlier in the array than later.

So the way 07/08/2017 will be interpreted depends on the order of the format in array of formats parameter.

Here a snippet with some examples:

var now = moment('30/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now2 = moment('08/30/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now3 = moment('07/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);

console.log(now.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now2.format('MMM DD h:mm A'));// Aug 30 12:00 AM
console.log(now3.format('MMM DD h:mm A'));// Jul 08 12:00 AM

var now4 = moment('30/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now5 = moment('08/30/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now6 = moment('07/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);

console.log(now4.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now5.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now6.format('MMM DD h:mm A')); // Aug 07 12:00 AM

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
Parse Server REST API - Group by and Sum
Is it possible to group by and sum values using the Parse Server REST API.

e.g. https://parseapi.back4app.com/classes/myclass?groupby=name&sum=score

If i have a table of 100k rows i would not like to let the client download all the result in order to perform a sum of the values.

Example Source:

```<code>name    | score
frank   | 50
frank   | 20
ben     | 30
</code>```

Result:

```<code>name    | score
frank   | 70
ben     | 30
</code>```

答: Migrate to PostgREST where you have PostgreSQL, a database that is capable of such trivial things :)</p>

Body:
Is it possible to group by and sum values using the Parse Server REST API.

e.g. https://parseapi.back4app.com/classes/myclass?groupby=name&sum=score

If i have a table of 100k rows i would not like to let the client download all the result in order to perform a sum of the values.

Example Source:

name    | score
frank   | 50
frank   | 20
ben     | 30

Result:

name    | score
frank   | 70
ben     | 30


问:
How to calculate the CPU usage of a process by PID in Linux from C?
I want to programmatically [in C] calculate CPU usage % for a given process ID in Linux.

How can we get the realtime CPU usage % for a given process?

To make it further clear:

I should be able to determine the CPU usage for the provided processid or process.

The process need not be the child process.

I want the solution in 'C' language.

答:
This is my solution...

```<code>/*
this program is looking for CPU,Memory,Procs also u can look glibtop header there was a lot of usefull function have fun..
systeminfo.c
*/
#include <stdio.h>
#include <glibtop.h>
#include <glibtop/cpu.h>
#include <glibtop/mem.h>
#include <glibtop/proclist.h>

int main(){

glibtop_init();

glibtop_cpu cpu;
glibtop_mem memory;
glibtop_proclist proclist;

glibtop_get_cpu (&cpu);
glibtop_get_mem(&memory);

printf("CPU TYPE INFORMATIONS \n\n"
"Cpu Total : %ld \n"
"Cpu User : %ld \n"
"Cpu Nice : %ld \n"
"Cpu Sys : %ld \n"
"Cpu Idle : %ld \n"
"Cpu Frequences : %ld \n",
(unsigned long)cpu.total,
(unsigned long)cpu.user,
(unsigned long)cpu.nice,
(unsigned long)cpu.sys,
(unsigned long)cpu.idle,
(unsigned long)cpu.frequency);

printf("\nMEMORY USING\n\n"
"Memory Total : %ld MB\n"
"Memory Used : %ld MB\n"
"Memory Free : %ld MB\n"
"Memory Buffered : %ld MB\n"
"Memory Cached : %ld MB\n"
"Memory user : %ld MB\n"
"Memory Locked : %ld MB\n",
(unsigned long)memory.total/(1024*1024),
(unsigned long)memory.used/(1024*1024),
(unsigned long)memory.free/(1024*1024),
(unsigned long)memory.shared/(1024*1024),
(unsigned long)memory.buffer/(1024*1024),
(unsigned long)memory.cached/(1024*1024),
(unsigned long)memory.user/(1024*1024),
(unsigned long)memory.locked/(1024*1024));

int which,arg;
glibtop_get_proclist(&proclist,which,arg);
printf("%ld\n%ld\n%ld\n",
(unsigned long)proclist.number,
(unsigned long)proclist.total,
(unsigned long)proclist.size);
return 0;
}

makefile is
CC=gcc
CFLAGS=-Wall -g
CLIBS=-lgtop-2.0 -lgtop_sysdeps-2.0 -lgtop_common-2.0

cpuinfo:cpu.c
$(CC) $(CFLAGS) systeminfo.c -o systeminfo $(CLIBS)
clean:
rm -f systeminfo
</code>```

Body:
This is my solution...

/*
this program is looking for CPU,Memory,Procs also u can look glibtop header there was a lot of usefull function have fun..
systeminfo.c
*/
#include <stdio.h>
#include <glibtop.h>
#include <glibtop/cpu.h>
#include <glibtop/mem.h>
#include <glibtop/proclist.h>

int main(){

glibtop_init();

glibtop_cpu cpu;
glibtop_mem memory;
glibtop_proclist proclist;

glibtop_get_cpu (&cpu);
glibtop_get_mem(&memory);

printf("CPU TYPE INFORMATIONS \n\n"
"Cpu Total : %ld \n"
"Cpu User : %ld \n"
"Cpu Nice : %ld \n"
"Cpu Sys : %ld \n"
"Cpu Idle : %ld \n"
"Cpu Frequences : %ld \n",
(unsigned long)cpu.total,
(unsigned long)cpu.user,
(unsigned long)cpu.nice,
(unsigned long)cpu.sys,
(unsigned long)cpu.idle,
(unsigned long)cpu.frequency);

printf("\nMEMORY USING\n\n"
"Memory Total : %ld MB\n"
"Memory Used : %ld MB\n"
"Memory Free : %ld MB\n"
"Memory Buffered : %ld MB\n"
"Memory Cached : %ld MB\n"
"Memory user : %ld MB\n"
"Memory Locked : %ld MB\n",
(unsigned long)memory.total/(1024*1024),
(unsigned long)memory.used/(1024*1024),
(unsigned long)memory.free/(1024*1024),
(unsigned long)memory.shared/(1024*1024),
(unsigned long)memory.buffer/(1024*1024),
(unsigned long)memory.cached/(1024*1024),
(unsigned long)memory.user/(1024*1024),
(unsigned long)memory.locked/(1024*1024));

int which,arg;
glibtop_get_proclist(&proclist,which,arg);
printf("%ld\n%ld\n%ld\n",
(unsigned long)proclist.number,
(unsigned long)proclist.total,
(unsigned long)proclist.size);
return 0;
}

makefile is
CC=gcc
CFLAGS=-Wall -g
CLIBS=-lgtop-2.0 -lgtop_sysdeps-2.0 -lgtop_common-2.0

cpuinfo:cpu.c
$(CC) $(CFLAGS) systeminfo.c -o systeminfo $(CLIBS)
clean:
rm -f systeminfo

ContentLicense: CC BY-SA 2.5


问:
Not sure why I'm getting "An object reference is required for the non-static field"
My code is below. Any help would be appreciated. I apologize in advance if it's a simple mistake - I'm still a beginner at C# (and object oriented in general).

```<code>public class Game1 : Microsoft.Xna.Framework.Game
{
    public void Update()
    {
        Levels level = new Levels();
        Game1 mainGame = Game1;
        Levels.AliensSetUp(1, 2, 50, 0, 0, 0, mainGame);
    }
}

class Levels
{
    public void AliensSetUp(int numberRows, int numberColumns, int spaceBetween, int XStart, int YStart, int AlienType, Game1 mainGame)
}
</code>```

The error is on the "mainGame" in "Levels.AliensSetUp(1, 2, 50, 0, 0, 0, mainGame)". I've also tried replacing "mainGame" with just "game1" but I get an error for that too. Thank you for any help you can give me.

答:
Levels is not static.  You have "new" up the Levels class and then call its AliensSetUp() method.  Ex:</p>

```<code>var levels = new Levels();
levels.AliensSetup(...)
</code>```

Body:
My code is below. Any help would be appreciated. I apologize in advance if it's a simple mistake - I'm still a beginner at C# (and object oriented in general).

public class Game1 : Microsoft.Xna.Framework.Game
{
    public void Update()
    {
        Levels level = new Levels();
        Game1 mainGame = Game1;
        Levels.AliensSetUp(1, 2, 50, 0, 0, 0, mainGame);
    }
}

class Levels
{
    public void AliensSetUp(int numberRows, int numberColumns, int spaceBetween, int XStart, int YStart, int AlienType, Game1 mainGame)
}

The error is on the "mainGame" in "Levels.AliensSetUp(1, 2, 50, 0, 0, 0, mainGame)". I've also tried replacing "mainGame" with just "game1" but I get an error for that too. Thank you for any help you can give me.

Body:
Levels is not static.  You have "new" up the Levels class and then call its AliensSetUp() method.  Ex:

var levels = new Levels();
levels.AliensSetup(...)


问:
Problems connecting a combobox signal to a std::function in Qt
I am creating a QWizard. For some of the QWizardPages, I give them a callback method in their constructors such the QWizardPage can set some properties on the QWizard.

Like so:

```<code>BWizard::BWizard(QWidget *parent, t::WindowFlags ): QWizard(parent, f), modelCheckedOut(false), selectedB(0){
  // Setup UI and add pages to wizard.
  ui.setupUi(this);
  // Make callbacks to set data onto Wizard instead of pages.
  auto makeLastPage = [this]()
  {
    int pageId = this->pageIds().last();
    this->removePage(pageId);
    this->modelCheckedOut = true;
  };
  auto setB = [this](int b)
  {
    this->selectedB = b;
  };
  addPage(new BWizardPage1(setB, this));
  addPage(new BWizardPage2(makeLastPage, this));
  addPage(new BWizardPage3(this));
}
</code>```

On BWizardPage1 I use setB function when Enter is pressed on a QLineEdit. I bind this in the constructor for BWizardPage1. This works fine:

```<code>QObject::connect(ui.searchField, &QLineEdit::returnPressed, this, [&]() {
  setB(5);
}
</code>```

On BWizardPage2 I use makeLastPage function when a combobox is changed. I bind this in the constructor for BWizardPage2. Once the combobox is changed, makeLastPage appears to be empty (or null).

```<code> QObject::connect(ui.comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [&](int index) {
    makeLastPage();
}
</code>```

Can anyone tell me what I am doing wrong? I pass the function as std::function<void(void)> makeLastPage and std::function<void(int)> setB

答:
```<code>QObject::connect(ui.comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [&](int index) {
    makeLastPage();
}
</code>```

By capturing makeLastPage by reference, you are capturing a reference to a function parameter. This will go out of scope after the function returns, leaving a dangling reference. Simply capture makeLastPage by value instead:

```<code>QObject::connect(ui.comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int index) {
    makeLastPage();
}
</code>```

Body:
I am creating a QWizard. For some of the QWizardPages, I give them a callback method in their constructors such the QWizardPage can set some properties on the QWizard.

Like so:

BWizard::BWizard(QWidget *parent, t::WindowFlags ): QWizard(parent, f), modelCheckedOut(false), selectedB(0){
  // Setup UI and add pages to wizard.
  ui.setupUi(this);
  // Make callbacks to set data onto Wizard instead of pages.
  auto makeLastPage = [this]()
  {
    int pageId = this->pageIds().last();
    this->removePage(pageId);
    this->modelCheckedOut = true;
  };
  auto setB = [this](int b)
  {
    this->selectedB = b;
  };
  addPage(new BWizardPage1(setB, this));
  addPage(new BWizardPage2(makeLastPage, this));
  addPage(new BWizardPage3(this));
}

On BWizardPage1 I use setB function when Enter is pressed on a QLineEdit. I bind this in the constructor for BWizardPage1. This works fine:

QObject::connect(ui.searchField, &QLineEdit::returnPressed, this, [&]() {
  setB(5);
}

On BWizardPage2 I use makeLastPage function when a combobox is changed. I bind this in the constructor for BWizardPage2. Once the combobox is changed, makeLastPage appears to be empty (or null).

 QObject::connect(ui.comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [&](int index) {
    makeLastPage();
}

Can anyone tell me what I am doing wrong? I pass the function as std::function<void(void)> makeLastPage and std::function<void(int)> setB

Body:
QObject::connect(ui.comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [&](int index) {
    makeLastPage();
}

By capturing makeLastPage by reference, you are capturing a reference to a function parameter. This will go out of scope after the function returns, leaving a dangling reference. Simply capture makeLastPage by value instead:

QObject::connect(ui.comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int index) {
    makeLastPage();
}


问:
outputting pdf files using C++ file I/O
I was trying to output a string to a file using File I/O of C++, but I decided to change the extension of the output file to .pdf, .docx and so on.

None of them seem to open up.

So are there any more internal translations required in order to make that file a proper(file which opens) pdf or docx??

```<code>void convert(char *file){

    ifstream in(file);
    ofstream out("out.pdf",ios::out);

    char str;

    while(in && out){
        in.get(str);
        out.put(str);
    }

    in.close();
    out.close();
    cout<<"Done!!!";
}
</code>```

答:
To write a pdf, docx, etc. you need to setup a file header, and format the data correctly. Changing the extension does not really do much if anything at all.

You will have to use an outside an outside library or format the code yourself. Below are a couple of examples of extensions you can use:

PDF
docx

Title: outputting pdf files using C++ file I/O

Body:
I was trying to output a string to a file using File I/O of C++, but I decided to change the extension of the output file to .pdf, .docx and so on.

None of them seem to open up.

So are there any more internal translations required in order to make that file a proper(file which opens) pdf or docx??

void convert(char *file){

    ifstream in(file);
    ofstream out("out.pdf",ios::out);

    char str;

    while(in && out){
        in.get(str);
        out.put(str);
    }

    in.close();
    out.close();
    cout<<"Done!!!";
}


问:
which tag executed at first?<tiles:insert or <tiles:put

</p>

<p>in the above codings which one executed at first

答: Since tiles:put works under tiles:insert, it is logical that tiles:put executes first and then tiles:insert. You will find more detail on this on Apache struts URL.


问:
Monads with Java 8
In the interests of helping to understand what a monad is, can someone provide an example using java ? Are they possible ?

Lambda expressions are possible using java if you download the pre-release lambda compatible JDK8   from here http://jdk8.java.net/lambda/

An example of a lambda using this JDK is shown below, can someone provide a comparably simple monad ?

```<code>public interface TransformService {
        int[] transform(List<Integer> inputs);
    }
    public static void main(String ars[]) {
        TransformService transformService = (inputs) -> {
            int[] ints = new int[inputs.size()];
            int i = 0;
            for (Integer element : inputs) {
                ints[i] = element;
            }
            return ints;
        };

        List<Integer> inputs = new ArrayList<Integer>(5) {{
            add(10);
            add(10);
        }};
        int[] results = transformService.transform(inputs);
    }
</code>```

答:
I like to think of monads in slighlty more mathematical (but still informal) fashion. After that I will explain the relationship to one of Java 8's monads CompletableFuture.

First of all, a monad M is a functor. That is, it transforms a type into another type: If X is a type (e.g. String) then we have another type M<X> (e.g. List<String>). Moreover, if we have a transformation/function X -> Y of types, we should get a function M<X> -> M<Y>.

But there is more data to such a monad. We have a so-called unit which is a function X -> M<X> for each type X. In other words, each object of X can be wrapped in a natural way into the monad.

The most characteristic data of a monad, however, is it's product: a function M<M<X>> -> M<X> for each type X.

All of these data should satisfy some axioms like functoriality, associativity, unit laws, but I won't go into detail here and it also doesn't matter for practical usage.

We can now deduce another operation for monads, which is often used as an equivalent definition for monads, the binding operation: A value/object in M<X> can be bound with a function X -> M<Y> to yield another value in M<Y>. How do we achieve this? Well, first we apply functoriality to the function to obtain a function M<X> -> M<M<Y>>. Next we apply the monadic product to the target to obtain a function M<X> -> M<Y>. Now we can plug in the value of M<X> to obtain a value in M<Y> as desired. This binding operation is used to chain several monadic operations together.

Now lets come to the CompletableFuture example, i.e. CompletableFuture = M. Think of an object of CompletableFuture<MyData> as some computation that's performed asynchronously and which yields an object of MyData as a result some time in the future. What are the monadic operations here?

functoriality is realized with the method thenApply: first the computation is performed and as soon as the result is available, the function which is given to thenApply is applied to transform the result into another type

the monadic unit is realized with the method completedFuture: as the documentation tells, the resulting computation is already finished and yields the given value at once

the monadic product is not realized by a function, but the binding operation below is equivalent to it (together with functoriality) and its semantic meaning is simply the following: given a computation of type CompletableFuture<CompletableFuture<MyData>> that computation asynchronously yields another computation in CompletableFuture<MyData> which in turn yields some value in MyData later on, so performing both computations on after the other yields one computation in total

the resulting binding operation is realized by the method thenCompose

As you see, computations can now be wrapped up in a special context, namely asynchronicity. The general monadic structures enable us to chain such computations in the given context. CompletableFuture is for example used in the Lagom framework to easily construct highly asynchronous request handlers which are transparently backed up by efficient thread pools (instead of handling each request by a dedicated thread).

Title: Monads with Java 8

Body:
In the interests of helping to understand what a monad is, can someone provide an example using java ? Are they possible ?

Lambda expressions are possible using java if you download the pre-release lambda compatible JDK8   from here http://jdk8.java.net/lambda/

An example of a lambda using this JDK is shown below, can someone provide a comparably simple monad ?

public interface TransformService {
        int[] transform(List<Integer> inputs);
    }
    public static void main(String ars[]) {
        TransformService transformService = (inputs) -> {
            int[] ints = new int[inputs.size()];
            int i = 0;
            for (Integer element : inputs) {
                ints[i] = element;
            }
            return ints;
        };

        List<Integer> inputs = new ArrayList<Integer>(5) {{
            add(10);
            add(10);
        }};
        int[] results = transformService.transform(inputs);
    }


问:
Using tmux through Cygwin: "open terminal failed: not a terminal"
I'm trying to use tmux on a Windows Computer.  I successfully installed tmux using

```<code>apt-cyg install tmux
</code>```

I can confirm successful installation because I get the following:

```<code>$ tmux -V
tmux 2.3
</code>```

However, when I try to type "tmux" in the console, I get the following error:

open terminal failed: not a terminal

Any thoughts?

答:
It sounds like the terminal you're using doesn't support full tty emulation. Clients like mintty (comes with Cygwin---or should, anyway), putty, rxvt for Windows, &c. will handle that. CMD, ConEmu, and Cmder won't.

There's not much to be done here without a huge ordeal (See second comment: https://news.ycombinator.com/item?id=8577817). Unsatisfying though it may be, the best answer is to make sure you're running mintty. CYGWIN.bat should run it out of the box, so if that's not working, try running it directly from Explorer instead of from CMD. Otherwise, you might need to poke around in the batch file and make sure C:\Cygwin64\bin\mintty (or what have you) is being called.

Body:
I'm trying to use tmux on a Windows Computer.  I successfully installed tmux using

apt-cyg install tmux

I can confirm successful installation because I get the following:

$ tmux -V
tmux 2.3

However, when I try to type "tmux" in the console, I get the following error:

open terminal failed: not a terminal

Any thoughts?


问:
Auto Merge Facebook and Internal Users
In our system, users can have multiple email addresses, and set one as their primary.  They can login with their primary email address and password.

We are looking at adding in a Facebook login.

My question is:

When a fb user 'signs in' and we see that the email for this fb user matches an email address for a user in our internal user database, is it safe to go ahead and 'merge' these accounts so that the fb user can see the data for the internal user?  Or is it better practice to give the user some hints that he/she can link their accounts and then guide them through a process of authenticating with the internal account before merging?

The question would also be for the opposite case, where a person first signed up with us using facebook, but now is creating an account using their email address, which matches the email for one of our facebook users.  Should we then go ahead and auto merge the users or walk them through an auth process?

I guess I'm a unclear of the oddities that could take place between emails that we manage and ones that facebook manages and I'm concerned about what may be the impacts if one of these oddities hoses some accounts.

Any insights are appreciated.

答:
From Facebook login flow documentation:

'After a successful login using Facebook, you will have the person's email address, Facebook ID, and access token. Your app should search for an existing account that has been created with that same email address. If one exists, you should merge the two accounts and add the Facebook info to the existing account - as recommended above.'

To me, this sounds like we should auto merge with matching emails.  Feels like there's room for error here... correct me if I'm wrong.

-- EDIT --

We decided against auto merges.  Just too much room for error.  We decided this a while ago... just now getting around to updating this.

Title: Auto Merge Facebook and Internal Users


问:
Program doesn't find file (EmguCV)
I downloaded Example for EmguCV.

I try to change image from default to my image

On default  it was like this

```<code> static void Run()
  {
     var image = new Mat("lena.jpg", LoadImageType.Color); //Read the files as an 8-bit Bgr image
     long detectionTime;
     List<Rectangle> faces = new List<Rectangle>();
     List<Rectangle> eyes = new List<Rectangle>();

     //The cuda cascade classifier doesn't seem to be able to load "haarcascade_frontalface_default.xml" file in this release
     //disabling CUDA module for now
     bool tryUseCuda = false;

     DetectFace.Detect(
       image, "haarcascade_frontalface_default.xml", "haarcascade_eye.xml",
       faces, eyes,
       tryUseCuda,
       out detectionTime);

     foreach (Rectangle face in faces)
        CvInvoke.Rectangle(image, face, new Bgr(Color.Green).MCvScalar, 2);
     foreach (Rectangle eye in eyes)
        CvInvoke.Rectangle(image, eye, new Bgr(Color.Aquamarine).MCvScalar, 2);

     //display the image
     ImageViewer.Show(image, String.Format(
        "Completed face and eye detection using {0} in {1} milliseconds",
        (tryUseCuda && CudaInvoke.HasCuda) ? "GPU"
        : CvInvoke.UseOpenCL ? "OpenCL"
        : "CPU",
        detectionTime));
  }
</code>```

}
}

I added change "lena.jpg" to my image - "oleg.jpg".

I added this image to project folder

Via Add Existing File - oleg.jpg.

But when I run my program it says that 'File oleg.jpg do not exist'

Where is problem?

Thank's for help

答:
It works placing your image file on Bin carpet.

Regards.

Title: Program doesn't find file (EmguCV)

Body:
I downloaded Example for EmguCV.

I try to change image from default to my image

On default  it was like this

 static void Run()
  {
     var image = new Mat("lena.jpg", LoadImageType.Color); //Read the files as an 8-bit Bgr image
     long detectionTime;
     List<Rectangle> faces = new List<Rectangle>();
     List<Rectangle> eyes = new List<Rectangle>();

     //The cuda cascade classifier doesn't seem to be able to load "haarcascade_frontalface_default.xml" file in this release
     //disabling CUDA module for now
     bool tryUseCuda = false;

     DetectFace.Detect(
       image, "haarcascade_frontalface_default.xml", "haarcascade_eye.xml",
       faces, eyes,
       tryUseCuda,
       out detectionTime);

     foreach (Rectangle face in faces)
        CvInvoke.Rectangle(image, face, new Bgr(Color.Green).MCvScalar, 2);
     foreach (Rectangle eye in eyes)
        CvInvoke.Rectangle(image, eye, new Bgr(Color.Aquamarine).MCvScalar, 2);

     //display the image
     ImageViewer.Show(image, String.Format(
        "Completed face and eye detection using {0} in {1} milliseconds",
        (tryUseCuda && CudaInvoke.HasCuda) ? "GPU"
        : CvInvoke.UseOpenCL ? "OpenCL"
        : "CPU",
        detectionTime));
  }

}
}

I added change "lena.jpg" to my image - "oleg.jpg".

I added this image to project folder

Via Add Existing File - oleg.jpg.

But when I run my program it says that 'File oleg.jpg do not exist'

Where is problem?

Thank's for help


问:
MYSQL query error #1452
I was trying to upload my Localhost website to the live server. In order to that i was uploading the .sql file for the database but my import was not successful instead it was showing the #1452 MySQL error.

I have tried

SET FOREIGN_KEY_CHECKS=0;

uploaded .SQL file again for new database

SET FOREIGN_KEY_CHECKS=1;

I don't know whether this solved my problem or not. Please help me to solve this error.

Thank you in advance

答:
Try this:
SET GLOBAL FOREIGN_KEY_CHECKS=0;</p>

Title: MYSQL query error #1452


问:
Edit my signature in PDF file in my iPad application
In my iPad application I want to add signature in my pdf file.

I already do perform following steps:

Open pdf in UIView (zooming is not implemented yet).

Add one transparent subview (UIImageView) and draw signature on that.

Save all screen using UIGraphicsGetImageFromCurrentImageContext() as a image.

Convert and save the image as a pdf.

This is works fine but pdf quality is very poor.

But now I want to add a signature/image as a pdf metadata. Same as a markup and commenting features of PDF.

Is there any help or sample code is available for the same?

答:
It should be possible to improve the quality of the output by skipping the image/pdf conversion, but afaik there's no lib that will help you editing the metadata of a pdf on the iPad (at least, none that's freely available).
Depending on what exactly you want to do, you may have to write a parser from scratch to know what exactly you have to append to your document to see the wanted effect:
It is very easy to append data to a pdf, but it has to be "registered" in the right locations so that a reader can use this information.</p>


问:
Reading a huge file into a C++ vector in Ubuntu (linux OS)
In my C++ program running in linux (Ubuntu 14.4), I need to read a 90 GB file completely buffered in a C++ vector, and I have only 125 GB memory.

When I read the file chunk by chunk, it continuously results in increase in cached mem usage in linux, which turns out to be more than 50% of the 128 GB mem, then the free memory easily becomes under 50 GB.

```<code>              total        used        free      shared  buff/cache   available
Mem:            125          60         0           0          65         65
</code>```

Swap:           255           0         255

So I found that the free memory then becomes zero, and the file reading process almost got stopped, and I have to manually run:

```<code>echo 3 | sudo tee /proc/sys/vm/drop_caches
</code>```

to clear cached mem, so that the file reading process resumes. I understand cached mem is to speed up reading a file again. My question is how could I avoid manually running the drop cache command to ensure the file reading process would successfully complete?

答:
Since you are simply streaming the data and never rereading it, the page cache does you no good whatsoever.  In fact, given the amount of data you're pushing through the page cache, and the memory pressure from your application, otherwise useful data is likely evicted from the page cache and your system performance suffers because of that.

So don't use the cache when reading your data.  Use direct IO.  Per the Linux open() man page:

O_DIRECT (since Linux 2.4.10)

Try to minimize cache effects of the I/O to and from this
                file.  In general this will degrade performance, but it is
                useful in special situations, such as when applications do
                their own caching.  File I/O is done directly to/from user-
                space buffers.  The O_DIRECT flag on its own makes an effort
                to transfer data synchronously, but does not give the
                guarantees of the O_SYNC flag that data and necessary metadata
                are transferred.  To guarantee synchronous I/O, O_SYNC must be
                used in addition to O_DIRECT.  See NOTES below for further
                discussion.

...

NOTES

...

O_DIRECT

The O_DIRECT flag may impose alignment restrictions on the length and
         address of user-space buffers and the file offset of I/Os.  In Linux
         alignment restrictions vary by filesystem and kernel version and
         might be absent entirely.  However there is currently no
         filesystem-independent interface for an application to discover these
         restrictions for a given file or filesystem.  Some filesystems
         provide their own interfaces for doing so, for example the
         XFS_IOC_DIOINFO operation in xfsctl(3).

Under Linux 2.4, transfer sizes, and the alignment of the user buffer
         and the file offset must all be multiples of the logical block size
         of the filesystem.  Since Linux 2.6.0, alignment to the logical block
         size of the underlying storage (typically 512 bytes) suffices.  The
         logical block size can be determined using the ioctl(2) BLKSSZGET
         operation or from the shell using the command:

```<code>      blockdev --getss
</code>```

...

Since you are not reading the data over and over, direct IO is likely to improve performance somewhat, as the data will go directly from disk into your application's memory instead of from disk, to the page cache, and then into your application's memory.

Use low-level, C-style I/O with open()/read()/close(), and open the file with the O_DIRECT flag:

```<code>int fd = ::open( filename, O_RDONLY | O_DIRECT );
</code>```

This will result in the data being read directly into the application's memory, without being cached in the system's page cache.

You'll have to read() using aligned memory, so you'll need something like this to actually read the data:

```<code>char *buffer;
size_t pageSize = sysconf( _SC_PAGESIZE );
size_t bufferSize = 32UL * pageSize;

int rc = ::posix_memalign( ( void ** ) &buffer, pageSize, bufferSize );
</code>```

posix_memalign() is a POSIX-standard function that returns a pointer to memory aligned as requested.  Page-aligned buffers are usually more than sufficient, but aligning to hugepage size (2MiB on x86-64) will hint the kernel that you want transparent hugepages for that allocation, making access to your buffer more efficient when you read it later.

```<code>ssize_t bytesRead = ::read( fd, buffer, bufferSize );
</code>```

Without your code, I can't say how to get the data from buffer into your std::vector, but it shouldn't be hard.  There are likely ways to wrap the C-style low-level file descriptor with a C++ stream of some type, and to configure that stream to use memory properly aligned for direct IO.

If you want to see the difference, try this:

```<code>echo 3 | sudo tee /proc/sys/vm/drop_caches
dd if=/your/big/data/file of=/dev/null bs=32k
</code>```

Time that.  Then look at the amount of data in the page cache.

Then do this:

```<code>echo 3 | sudo tee /proc/sys/vm/drop_caches
dd if=/your/big/data/file iflag=direct of=/dev/null bs=32k
</code>```

Check the amount of data in the page cache after that...

You can experiment with different block sizes to see what works best on your hardware and filesystem.

Note well, though, that direct IO is very implementation-dependent.  Requirements to perform direct IO can vary significantly between different filesystems, and performance can vary drastically depending on your IO pattern and your specific hardware.  Most of the time it's not worth those dependencies, but the one simple use where it usually is worthwhile is streaming a huge file without rereading/rewriting any part of the data.

Body:
In my C++ program running in linux (Ubuntu 14.4), I need to read a 90 GB file completely buffered in a C++ vector, and I have only 125 GB memory.

When I read the file chunk by chunk, it continuously results in increase in cached mem usage in linux, which turns out to be more than 50% of the 128 GB mem, then the free memory easily becomes under 50 GB.

              total        used        free      shared  buff/cache   available
Mem:            125          60         0           0          65         65

Swap:           255           0         255

So I found that the free memory then becomes zero, and the file reading process almost got stopped, and I have to manually run:

echo 3 | sudo tee /proc/sys/vm/drop_caches

to clear cached mem, so that the file reading process resumes. I understand cached mem is to speed up reading a file again. My question is how could I avoid manually running the drop cache command to ensure the file reading process would successfully complete?

Body:
Since you are simply streaming the data and never rereading it, the page cache does you no good whatsoever.  In fact, given the amount of data you're pushing through the page cache, and the memory pressure from your application, otherwise useful data is likely evicted from the page cache and your system performance suffers because of that.

So don't use the cache when reading your data.  Use direct IO.  Per the Linux open() man page:

O_DIRECT (since Linux 2.4.10)

Try to minimize cache effects of the I/O to and from this
                file.  In general this will degrade performance, but it is
                useful in special situations, such as when applications do
                their own caching.  File I/O is done directly to/from user-
                space buffers.  The O_DIRECT flag on its own makes an effort
                to transfer data synchronously, but does not give the
                guarantees of the O_SYNC flag that data and necessary metadata
                are transferred.  To guarantee synchronous I/O, O_SYNC must be
                used in addition to O_DIRECT.  See NOTES below for further
                discussion.

...

NOTES

...

O_DIRECT

The O_DIRECT flag may impose alignment restrictions on the length and
         address of user-space buffers and the file offset of I/Os.  In Linux
         alignment restrictions vary by filesystem and kernel version and
         might be absent entirely.  However there is currently no
         filesystem-independent interface for an application to discover these
         restrictions for a given file or filesystem.  Some filesystems
         provide their own interfaces for doing so, for example the
         XFS_IOC_DIOINFO operation in xfsctl(3).

Under Linux 2.4, transfer sizes, and the alignment of the user buffer
         and the file offset must all be multiples of the logical block size
         of the filesystem.  Since Linux 2.6.0, alignment to the logical block
         size of the underlying storage (typically 512 bytes) suffices.  The
         logical block size can be determined using the ioctl(2) BLKSSZGET
         operation or from the shell using the command:

      blockdev --getss

...

Since you are not reading the data over and over, direct IO is likely to improve performance somewhat, as the data will go directly from disk into your application's memory instead of from disk, to the page cache, and then into your application's memory.

Use low-level, C-style I/O with open()/read()/close(), and open the file with the O_DIRECT flag:

int fd = ::open( filename, O_RDONLY | O_DIRECT );

This will result in the data being read directly into the application's memory, without being cached in the system's page cache.

You'll have to read() using aligned memory, so you'll need something like this to actually read the data:

char *buffer;
size_t pageSize = sysconf( _SC_PAGESIZE );
size_t bufferSize = 32UL * pageSize;

int rc = ::posix_memalign( ( void ** ) &buffer, pageSize, bufferSize );

posix_memalign() is a POSIX-standard function that returns a pointer to memory aligned as requested.  Page-aligned buffers are usually more than sufficient, but aligning to hugepage size (2MiB on x86-64) will hint the kernel that you want transparent hugepages for that allocation, making access to your buffer more efficient when you read it later.

ssize_t bytesRead = ::read( fd, buffer, bufferSize );

Without your code, I can't say how to get the data from buffer into your std::vector, but it shouldn't be hard.  There are likely ways to wrap the C-style low-level file descriptor with a C++ stream of some type, and to configure that stream to use memory properly aligned for direct IO.

If you want to see the difference, try this:

echo 3 | sudo tee /proc/sys/vm/drop_caches
dd if=/your/big/data/file of=/dev/null bs=32k

Time that.  Then look at the amount of data in the page cache.

Then do this:

echo 3 | sudo tee /proc/sys/vm/drop_caches
dd if=/your/big/data/file iflag=direct of=/dev/null bs=32k

Check the amount of data in the page cache after that...

You can experiment with different block sizes to see what works best on your hardware and filesystem.

Note well, though, that direct IO is very implementation-dependent.  Requirements to perform direct IO can vary significantly between different filesystems, and performance can vary drastically depending on your IO pattern and your specific hardware.  Most of the time it's not worth those dependencies, but the one simple use where it usually is worthwhile is streaming a huge file without rereading/rewriting any part of the data.


问:
Foursquare Trending API Not giving result
I have checked in to few Nearby places from Foursquare app.
Now if I am hitting the foursquare trending api it does not give me the list of checked in venues. Can any one help.
This is the api I have used:<br>
https://api.foursquare.com/v2/venues/trending?ll=23.03,72.58&oauth_token=FMT04M2BJ1.............&v=201....
I have tried this also :
https://api.foursquare.com/v2/venues/trending?near=Ahmedabad&oauth_token=ONPEHQ.....&v=201...
I am Getting such response. </p>

```<code>{"meta":{"code":200,"requestId":"5925253df594df26def6707a"},"notifications":[{"type":"notificationTray","item":{"unreadCount":0}}],"response":{"venues":[]}}
</code>```

答: You may contact the enterprise team at https://enterprise.foursquare.com</p>

Body:
I have checked in to few Nearby places from Foursquare app.
Now if I am hitting the foursquare trending api it does not give me the list of checked in venues. Can any one help.
This is the api I have used:

https://api.foursquare.com/v2/venues/trending?ll=23.03,72.58&oauth_token=FMT04M2BJ1.............&v=201....
I have tried this also :
https://api.foursquare.com/v2/venues/trending?near=Ahmedabad&oauth_token=ONPEHQ.....&v=201...
I am Getting such response.

{"meta":{"code":200,"requestId":"5925253df594df26def6707a"},"notifications":[{"type":"notificationTray","item":{"unreadCount":0}}],"response":{"venues":[]}}


问:
Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git
I'm not sure why I'm unable to checkout a branch that I had worked on earlier. See the commands below (note: co is an alias for checkout):

```<code>ramon@ramon-desktop:~/source/unstilted$ git branch -a
* develop
  feature/datts_right
  feature/user_controlled_menu
  feature/user_controlled_site_layouts
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/develop
  remotes/origin/feature/datts_right
  remotes/origin/master
ramon@ramon-desktop:~/source/unstilted$ git co feature/user_controlled_site_layouts
error: pathspec 'feature/user_controlled_site_layouts' did not match any file(s) known to git.
</code>```

I'm not sure what it means, and I can't seem to find anything I can understand on Google.

How do I checkout that branch, and what may I have done to break this?

UPDATE:

I found this post, and running git show-ref gives me:

```<code>97e2cb33914e763ff92bbe38531d3fd02408da46 refs/heads/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/heads/feature/datts_right
11a90dae8897ceed318700b9af3019f4b4dceb1e refs/heads/feature/user_controlled_menu
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/heads/master
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/HEAD
e7c17eb40610505eea4e6687e4572191216ad4c6 refs/remotes/origin/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/remotes/origin/feature/datts_right
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/master
23768aa5425cbf29d10ff24274adad42d90d15cc refs/stash
e572cf91e95da03f04a5e51820f58a7306ce01de refs/tags/menu_shows_published_only
429ebaa895d9d41d835a34da72676caa75902e3d refs/tags/slow_dev
</code>```

UPDATE on .git directory (user_controlled_site_layouts is in the refs/heads/feature folder):

```<code>$ ls .git/refs/heads/feature/
datts_right  user_controlled_menu  user_controlled_site_layouts
$ cat .git/refs/heads/feature/user_controlled_site_layouts
3af84fcf1508c44013844dcd0998a14e61455034
</code>```

UPDATE on git show 3af84fcf1508c44013844dcd0998a14e61455034

```<code>$ git show 3af84fcf1508c44013844dcd0998a14e61455034
commit 3af84fcf1508c44013844dcd0998a14e61455034
Author: Ramon Tayag <xxx@xxxxx.xxx>
Date:   Thu May 12 19:00:03 2011 +0800

    Removed site layouts migration

diff --git a/db/schema.rb b/db/schema.rb
index 1218fc8..2040b9f 100755
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
 #
 # It's strongly recommended to check this file into your version control system.

-ActiveRecord::Schema.define(:version => 20110511012647) do
+ActiveRecord::Schema.define(:version => 20110503040056) do

   create_table "attachments", :force => true do |t|
     t.string   "name"
@@ -205,15 +205,6 @@ ActiveRecord::Schema.define(:version => 20110511012647) do
     t.integer  "old_id"
   end

-  create_table "site_layouts", :force => true do |t|
-    t.string   "name"
-    t.text     "description"
-    t.text     "content"
-    t.integer  "site_id"
-    t.datetime "created_at"
-    t.datetime "updated_at"
-  end
-
   create_table "site_styles", :force => true do |t|
     t.text     "published"
     t.datetime "created_at"
</code>```

答:
If you're on Windows you just probably change filename to lower/upper case like File.txt - file.txt

So check what file you have in git and rename it to what you want:

```<code>git status
</code>```

Then I need file.txt -> but git status gaves me File.txt so just rename it

```<code>git mv File.txt file.txt
</code>```

And problem is solved.

Body:
I'm not sure why I'm unable to checkout a branch that I had worked on earlier. See the commands below (note: co is an alias for checkout):

ramon@ramon-desktop:~/source/unstilted$ git branch -a
* develop
  feature/datts_right
  feature/user_controlled_menu
  feature/user_controlled_site_layouts
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/develop
  remotes/origin/feature/datts_right
  remotes/origin/master
ramon@ramon-desktop:~/source/unstilted$ git co feature/user_controlled_site_layouts
error: pathspec 'feature/user_controlled_site_layouts' did not match any file(s) known to git.

I'm not sure what it means, and I can't seem to find anything I can understand on Google.

How do I checkout that branch, and what may I have done to break this?

UPDATE:

I found this post, and running git show-ref gives me:

97e2cb33914e763ff92bbe38531d3fd02408da46 refs/heads/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/heads/feature/datts_right
11a90dae8897ceed318700b9af3019f4b4dceb1e refs/heads/feature/user_controlled_menu
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/heads/master
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/HEAD
e7c17eb40610505eea4e6687e4572191216ad4c6 refs/remotes/origin/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/remotes/origin/feature/datts_right
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/master
23768aa5425cbf29d10ff24274adad42d90d15cc refs/stash
e572cf91e95da03f04a5e51820f58a7306ce01de refs/tags/menu_shows_published_only
429ebaa895d9d41d835a34da72676caa75902e3d refs/tags/slow_dev

UPDATE on .git directory (user_controlled_site_layouts is in the refs/heads/feature folder):

$ ls .git/refs/heads/feature/
datts_right  user_controlled_menu  user_controlled_site_layouts
$ cat .git/refs/heads/feature/user_controlled_site_layouts
3af84fcf1508c44013844dcd0998a14e61455034

UPDATE on git show 3af84fcf1508c44013844dcd0998a14e61455034

$ git show 3af84fcf1508c44013844dcd0998a14e61455034
commit 3af84fcf1508c44013844dcd0998a14e61455034
Author: Ramon Tayag <xxx@xxxxx.xxx>
Date:   Thu May 12 19:00:03 2011 +0800

    Removed site layouts migration

diff --git a/db/schema.rb b/db/schema.rb
index 1218fc8..2040b9f 100755
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
 #
 # It's strongly recommended to check this file into your version control system.

-ActiveRecord::Schema.define(:version => 20110511012647) do
+ActiveRecord::Schema.define(:version => 20110503040056) do

   create_table "attachments", :force => true do |t|
     t.string   "name"
@@ -205,15 +205,6 @@ ActiveRecord::Schema.define(:version => 20110511012647) do
     t.integer  "old_id"
   end

-  create_table "site_layouts", :force => true do |t|
-    t.string   "name"
-    t.text     "description"
-    t.text     "content"
-    t.integer  "site_id"
-    t.datetime "created_at"
-    t.datetime "updated_at"
-  end
-
   create_table "site_styles", :force => true do |t|
     t.text     "published"
     t.datetime "created_at"

Body:
If you're on Windows you just probably change filename to lower/upper case like File.txt - file.txt

So check what file you have in git and rename it to what you want:

git status

Then I need file.txt -> but git status gaves me File.txt so just rename it

git mv File.txt file.txt

And problem is solved.


问:
Nested tables must have collapsed borders
I have Googled and read a few articles on SO. Unfortunately explicitly setting borders on nested tables is not an option - I am positive I have done this before using border-collapse: collapse

Maybe I imagined the whole thing. I have the following CSS:

```<code>    .table-grid {
        width: 100%;

    }

    .table-grid > thead > tr > th,
    .table-grid > tbody > tr > th,
    .table-grid > tfoot > tr > th,
    .table-grid > thead > tr > td,
    .table-grid > tbody > tr > td,
    .table-grid > tfoot > tr > td {
        border: 1px solid red;
        border-collapse: collapse;
    }
</code>```

Red borders still doubling up, tripling up, etc...what am I missing? Or misunderstanding?

This is for the UI of rather complicated scheduling tool for CNC machines - so DIV's are not required - I need it done using tables.

Anyway ideas?

EDIT | Markup below

```<code><table class="table-grid" style="background-color: #fff">
    <tr>
        <th>Month
            <table class="table-grid">
                <th>Jan</th>
                <th>Feb</th>
                <th>Mar</th>
                <th>Apr</th>
            </table>
        </th>
    </tr>
</code>```

This is somewhat trivialized - otherwise id' just keep the the Month as a colspan"7" - the actual scope is far more complicated - so colspan techniques won't suffice

答:
border-collapse: collapse; must be applied to the table for it to take effect, rather than the table cells. However, border-collapse only works on table cells ( or ) that share a common parent
. This means that you cannot merge cells of nested tables, nor can you merge elements that aren't  or  elements.

In your example this becomes a bit tricky being that all tables, including the nested ones, share the same single class.

With a little creative CSS, we can hide the bottom and left borders from all our nested cells. Additionally, we'll have to remove the right border of the last cell in a row.

Using a combination of the nested selector .table-grid .table-grid, as well as :last-child for altering the final cell of a nested row, you can come up with an infinitely "nestable" example that looks something like this:

.table-grid {
  width: 100%;
  border-collapse: collapse;
}

.table-grid>tbody>tr>th {
  padding: 0;
}

.table-grid>thead>tr>th,
.table-grid>tbody>tr>th,
.table-grid>tfoot>tr>th,
.table-grid>thead>tr>td,
.table-grid>tbody>tr>td,
.table-grid>tfoot>tr>td {
  border: 1px solid red;
}

.table-grid .table-grid td,
.table-grid .table-grid th {
  border-top: 1px solid red;
  border-right: 1px solid red;
  border-bottom: 0;
  border-left: 0;
}

.table-grid .table-grid td:last-child,
.table-grid .table-grid th:last-child {
  border-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table-grid" style="background-color: #fff">
  <tr>
    <th>Month
      <table class="table-grid">
        <tr>
          <th>Jan</th>
          <th>Feb</th>
          <th>Mar</th>
          <th>Apr</th>
        </tr>
      </table>
    </th>
  </tr>
</table></code>```

Body:
I have Googled and read a few articles on SO. Unfortunately explicitly setting borders on nested tables is not an option - I am positive I have done this before using border-collapse: collapse

Maybe I imagined the whole thing. I have the following CSS:

    .table-grid {
        width: 100%;

    }

    .table-grid > thead > tr > th,
    .table-grid > tbody > tr > th,
    .table-grid > tfoot > tr > th,
    .table-grid > thead > tr > td,
    .table-grid > tbody > tr > td,
    .table-grid > tfoot > tr > td {
        border: 1px solid red;
        border-collapse: collapse;
    }

Red borders still doubling up, tripling up, etc...what am I missing? Or misunderstanding?

This is for the UI of rather complicated scheduling tool for CNC machines - so DIV's are not required - I need it done using tables.

Anyway ideas?

EDIT | Markup below

        Month

                Jan
                Feb
                Mar
                Apr

This is somewhat trivialized - otherwise id' just keep the the Month as a colspan"7" - the actual scope is far more complicated - so colspan techniques won't suffice

Body:
border-collapse: collapse; must be applied to the table for it to take effect, rather than the table cells. However, border-collapse only works on table cells (<td> or <th>) that share a common parent <table>. This means that you cannot merge cells of nested tables, nor can you merge elements that aren't <td> or <th> elements.

In your example this becomes a bit tricky being that all tables, including the nested ones, share the same single class.

With a little creative CSS, we can hide the bottom and left borders from all our nested cells. Additionally, we'll have to remove the right border of the last cell in a row.

Using a combination of the nested selector .table-grid .table-grid, as well as :last-child for altering the final cell of a nested row, you can come up with an infinitely "nestable" example that looks something like this:

.table-grid {
  width: 100%;
  border-collapse: collapse;
}

.table-grid>tbody>tr>th {
  padding: 0;
}

.table-grid>thead>tr>th,
.table-grid>tbody>tr>th,
.table-grid>tfoot>tr>th,
.table-grid>thead>tr>td,
.table-grid>tbody>tr>td,
.table-grid>tfoot>tr>td {
  border: 1px solid red;
}

.table-grid .table-grid td,
.table-grid .table-grid th {
  border-top: 1px solid red;
  border-right: 1px solid red;
  border-bottom: 0;
  border-left: 0;
}

.table-grid .table-grid td:last-child,
.table-grid .table-grid th:last-child {
  border-right: 0;
}

<table class="table-grid" style="background-color: #fff">
  <tr>
    <th>Month
      <table class="table-grid">
        <tr>
          <th>Jan</th>
          <th>Feb</th>
          <th>Mar</th>
          <th>Apr</th>
        </tr>
      </table>
    </th>
  </tr>
</table>


问:
pushViewport -> layout.pos.col possible with doubles?
I am wondering if it is possible to specify grid viewports with double like this:

```<code>pushViewport(viewport(layout.pos.row=1, layout.pos.col=1.5))
popViewport()
</code>```

When I'm trying this I get row 1 and col 1.

But I want to have half of col 1 and half of col 2.

Has anyone a hint for me?

答:
PROBABLY you cannot do it by layout.pos.row and layout.pos.col.
Simple workaround is to specify position and size:

```<code>grid.newpage()
pushViewport(viewport(layout=grid.layout(2, 2)))
grid.rect(gp=gpar(fill=1),vp=viewport(layout.pos.col=1,layout.pos.row=1))
grid.rect(gp=gpar(fill=2),vp=viewport(layout.pos.col=1,layout.pos.row=2))
grid.rect(gp=gpar(fill=3),vp=viewport(layout.pos.col=2,layout.pos.row=1))
grid.rect(gp=gpar(fill=4),vp=viewport(layout.pos.col=2,layout.pos.row=2))

pushViewport(viewport(x=unit(0.5, "npc"), width=unit(0.5, "npc"),
  y=unit(0.75, "npc"), height=unit(0.5, "npc")))
grid.rect(gp=gpar(fill="white"))
</code>```

also, I think you can write a wrapper function to do this by specifying pos.col and pos.row in double, like this:

```<code>vpvp <- function(pos.col, pos.row){
  cvp <- current.viewport()
  nrow <- cvp$layout$nrow
  ncol <- cvp$layout$ncol
  w <- unit(1/ncol, "npc")
  h <- unit(1/nrow, "npc")
  x <- unit((pos.col-0.5)/ncol, "npc")
  y <- unit(1-(pos.row-0.5)/nrow, "npc")
  viewport(x=x, y=y, width=w, height=h)
}

grid.newpage()
pushViewport(viewport(layout=grid.layout(2, 3)))
grid.rect(gp=gpar(fill=1),vp=viewport(layout.pos.col=1,layout.pos.row=1))
grid.rect(gp=gpar(fill=2),vp=viewport(layout.pos.col=1,layout.pos.row=2))
grid.rect(gp=gpar(fill=3),vp=viewport(layout.pos.col=2,layout.pos.row=1))
grid.rect(gp=gpar(fill=4),vp=viewport(layout.pos.col=2,layout.pos.row=2))
grid.rect(gp=gpar(fill=5),vp=viewport(layout.pos.col=3,layout.pos.row=1))
grid.rect(gp=gpar(fill=6),vp=viewport(layout.pos.col=3,layout.pos.row=2))

pushViewport(vpvp(pos.col=2.5, pos.row=1.5))
grid.rect(gp=gpar(fill="white"))
</code>```

Body:
I am wondering if it is possible to specify grid viewports with double like this:

pushViewport(viewport(layout.pos.row=1, layout.pos.col=1.5))
popViewport()

When I'm trying this I get row 1 and col 1.

But I want to have half of col 1 and half of col 2.

Has anyone a hint for me?

Body:
PROBABLY you cannot do it by layout.pos.row and layout.pos.col.
Simple workaround is to specify position and size:

grid.newpage()
pushViewport(viewport(layout=grid.layout(2, 2)))
grid.rect(gp=gpar(fill=1),vp=viewport(layout.pos.col=1,layout.pos.row=1))
grid.rect(gp=gpar(fill=2),vp=viewport(layout.pos.col=1,layout.pos.row=2))
grid.rect(gp=gpar(fill=3),vp=viewport(layout.pos.col=2,layout.pos.row=1))
grid.rect(gp=gpar(fill=4),vp=viewport(layout.pos.col=2,layout.pos.row=2))

pushViewport(viewport(x=unit(0.5, "npc"), width=unit(0.5, "npc"),
  y=unit(0.75, "npc"), height=unit(0.5, "npc")))
grid.rect(gp=gpar(fill="white"))

also, I think you can write a wrapper function to do this by specifying pos.col and pos.row in double, like this:

vpvp <- function(pos.col, pos.row){
  cvp <- current.viewport()
  nrow <- cvp$layout$nrow
  ncol <- cvp$layout$ncol
  w <- unit(1/ncol, "npc")
  h <- unit(1/nrow, "npc")
  x <- unit((pos.col-0.5)/ncol, "npc")
  y <- unit(1-(pos.row-0.5)/nrow, "npc")
  viewport(x=x, y=y, width=w, height=h)
}

grid.newpage()
pushViewport(viewport(layout=grid.layout(2, 3)))
grid.rect(gp=gpar(fill=1),vp=viewport(layout.pos.col=1,layout.pos.row=1))
grid.rect(gp=gpar(fill=2),vp=viewport(layout.pos.col=1,layout.pos.row=2))
grid.rect(gp=gpar(fill=3),vp=viewport(layout.pos.col=2,layout.pos.row=1))
grid.rect(gp=gpar(fill=4),vp=viewport(layout.pos.col=2,layout.pos.row=2))
grid.rect(gp=gpar(fill=5),vp=viewport(layout.pos.col=3,layout.pos.row=1))
grid.rect(gp=gpar(fill=6),vp=viewport(layout.pos.col=3,layout.pos.row=2))

pushViewport(vpvp(pos.col=2.5, pos.row=1.5))
grid.rect(gp=gpar(fill="white"))


问:
Passing dynamic variables to function using setInterval
I am trying to pass "dynamic" (data is changed frequently by keypress event) body and direction.

I am calling function to like this:

```<code>snakeGame.createInterval(snakeGame.move, grid, body, direction, interval);

  createInterval: function(f, grid, body, direction, interval) {
    setInterval(function() { f(grid, body, direction); }, interval);
  },
</code>```

Problem is that both body and direction always keep same data when function was called.

Let's say that direction was 'right' when calling it first time and before second occurence happens, direction was changed to 'up', but this function still reads it as old 'right'.

How do I make sure that passed parameters are always up-to-date?

(Let me know if you need further clarification)

答:
To see changes to values, you need references to those values, and make sure that both the code that changes values and the code that read the values use a reference to the same value.

There are several ways to do this, but it will involve an object with several object properties which will have the targetted values. But you will pass the object, not the individual values.

From the little you have provided, it looks like you have a snakeGame object. You could use that object to store some of the properties, for instance, it could have a property grid. But you could also introduce another object, for storing things you'd rather not have in your snakeGame object. This could be the case for body and/or direction.

For instance:

```<code>// Use object properties instead of separate variables:
var snake = {
    body: 'xxxx',
    direction: 'L'
}

var snakeGame = {
    // You can also add properties to your existing object:
    grid: [[0,0,0],[0,0,0],[0,0,0]],
    createInterval: function(f, snake, interval) {
        // Pass `this` and snake objects:
        setInterval(f.bind(this, snake), interval);
    },
    move: function(snake) {
        // use this.grid, snake.body and snake.direction:
        //....
    }
    // etc
};

// Call with objects only (except for the constant interval)
snakeGame.createInterval(snakeGame.move, snake, interval);

// When you change direction:
$('#up').keydown(function () {
    // ... do not assign to snake, but to snake.direction:
    snake.direction = 'U';
    // ...
    // Same principle with snake.body.
});
</code>```

I just chose to define grid as a property of snakeGame, and direction and body as properties of a newly introduced object. But you may want to do it differently. This is just an example. The essence is that you pass along objects, not primitive values, but that you assign to properties of those objects, never redefining the objects themselves.

Body:
I am trying to pass "dynamic" (data is changed frequently by keypress event) body and direction.

I am calling function to like this:

snakeGame.createInterval(snakeGame.move, grid, body, direction, interval);

  createInterval: function(f, grid, body, direction, interval) {
    setInterval(function() { f(grid, body, direction); }, interval);
  },

Problem is that both body and direction always keep same data when function was called.

Let's say that direction was 'right' when calling it first time and before second occurence happens, direction was changed to 'up', but this function still reads it as old 'right'.

How do I make sure that passed parameters are always up-to-date?

(Let me know if you need further clarification)

Body:
To see changes to values, you need references to those values, and make sure that both the code that changes values and the code that read the values use a reference to the same value.

There are several ways to do this, but it will involve an object with several object properties which will have the targetted values. But you will pass the object, not the individual values.

From the little you have provided, it looks like you have a snakeGame object. You could use that object to store some of the properties, for instance, it could have a property grid. But you could also introduce another object, for storing things you'd rather not have in your snakeGame object. This could be the case for body and/or direction.

For instance:

// Use object properties instead of separate variables:
var snake = {
    body: 'xxxx',
    direction: 'L'
}

var snakeGame = {
    // You can also add properties to your existing object:
    grid: [[0,0,0],[0,0,0],[0,0,0]],
    createInterval: function(f, snake, interval) {
        // Pass `this` and snake objects:
        setInterval(f.bind(this, snake), interval);
    },
    move: function(snake) {
        // use this.grid, snake.body and snake.direction:
        //....
    }
    // etc
};

// Call with objects only (except for the constant interval)
snakeGame.createInterval(snakeGame.move, snake, interval);

// When you change direction:
$('#up').keydown(function () {
    // ... do not assign to snake, but to snake.direction:
    snake.direction = 'U';
    // ...
    // Same principle with snake.body.
});

I just chose to define grid as a property of snakeGame, and direction and body as properties of a newly introduced object. But you may want to do it differently. This is just an example. The essence is that you pass along objects, not primitive values, but that you assign to properties of those objects, never redefining the objects themselves.


问:
Problems while trying to remove a set of tuples from a list?
Just a quick question guys, I have a long list of tuples like this:

```<code>a_lis = [('[', '1O--'), ("'", '1B--'),('hi', 'SDFD29384'), ('there','2398SDFDSF'),("'", '1B--'), (']', '1C--')]
</code>```

How can I remove all this tuples (*): ('[', '1O--'), ("'", '1B--'),("'", '1B--'), (']', '1C--') from a_lis?

I tried to:

```<code>flat_list = filter(flat_list, lambda x: x[0] == '[' && x[1] == "'")
</code>```

However, I got a non iterable error, which is a better way of removing such tuples (*) from my list, in order to get?:

```<code>a_lis = [('hi', 'SDFD29384'), ('there','2398SDFDSF')]
</code>```

答:
Here's one way:

```<code>>>> a_list = [('[', '1O--'), ("'", '1B--'),('hi', 'SDFD29384'), ('there','2398SDFDSF'),("'", '1B--'), (']', '1C--')]
>>> b_list = [('[', '1O--'), ("'", '1B--'),("'", '1B--'), (']', '1C--')]
>>> list(set(a_list) - set(b_list))
[('hi', 'SDFD29384'), ('there', '2398SDFDSF')]
</code>```

Another way would be:

```<code>>>> [ x for x in a_list if x not in b_list ]
[('hi', 'SDFD29384'), ('there', '2398SDFDSF')]
</code>```

Another couple possibilities:

```<code>>>> for x in b_list:
        try:
            a_list.remove(x)
        except ValueError:
            pass
</code>```

That one actually modifies a_list, so may not be desirable depending on context. There's an analogous method involving set.remove() or even set.discard() (which wouldn't require the try block).

Note that any set based methods require all objects in the lists to be hashable - in the example given, they're all tuples, so this is fine. Another caveat in the set methods is that the surviving items in the result may not be in the same order they were in the original. Using an OrderedSet would work around that, but involves a bit more overhead, as that's not a core package/datatype.

Body:
Just a quick question guys, I have a long list of tuples like this:

a_lis = [('[', '1O--'), ("'", '1B--'),('hi', 'SDFD29384'), ('there','2398SDFDSF'),("'", '1B--'), (']', '1C--')]

How can I remove all this tuples (*): ('[', '1O--'), ("'", '1B--'),("'", '1B--'), (']', '1C--') from a_lis?

I tried to:

flat_list = filter(flat_list, lambda x: x[0] == '[' && x[1] == "'")

However, I got a non iterable error, which is a better way of removing such tuples (*) from my list, in order to get?:

a_lis = [('hi', 'SDFD29384'), ('there','2398SDFDSF')]

Body:
Here's one way:

>>> a_list = [('[', '1O--'), ("'", '1B--'),('hi', 'SDFD29384'), ('there','2398SDFDSF'),("'", '1B--'), (']', '1C--')]
>>> b_list = [('[', '1O--'), ("'", '1B--'),("'", '1B--'), (']', '1C--')]
>>> list(set(a_list) - set(b_list))
[('hi', 'SDFD29384'), ('there', '2398SDFDSF')]

Another way would be:

>>> [ x for x in a_list if x not in b_list ]
[('hi', 'SDFD29384'), ('there', '2398SDFDSF')]

Another couple possibilities:

>>> for x in b_list:
        try:
            a_list.remove(x)
        except ValueError:
            pass

That one actually modifies a_list, so may not be desirable depending on context. There's an analogous method involving set.remove() or even set.discard() (which wouldn't require the try block).

Note that any set based methods require all objects in the lists to be hashable - in the example given, they're all tuples, so this is fine. Another caveat in the set methods is that the surviving items in the result may not be in the same order they were in the original. Using an OrderedSet would work around that, but involves a bit more overhead, as that's not a core package/datatype.