问:
How To create an expiration date based off the next effective date
So I can not use a temp table to accomplish this. Basically I need to create an experation date based off the next effective date available.

So for one proc code i have 10 fee schedules with only effective dates. I tried writing this but its not working because it is giving for some records the same expiration date. I know an order by is needed but i placed it in various places and it still gives me the same issue. Any help is greatly appreciated

```<code>SELECT a.*,
       ( CASE
           WHEN (SELECT TOP 1 b.effectivedate - 1
                 FROM   ietl_profileprocedure b
                 WHERE  b.effectivedate > a.effectivedate
                   AND  a.profilesid = b.profilesid) IS NULL THEN (SELECT
           Dateadd(mm, Datediff(mm, 0, Getdate()) + 1, -1))
           ELSE (SELECT TOP 1 b.effectivedate - 1
                 FROM   ietl_profileprocedure b
                 WHERE  b.effectivedate > a.effectivedate
                   AND  a.profilesid = b.profilesid)
         END ) AS 'ExpDate'
FROM   ietl_profileprocedure a
WHERE  profilesid = '4197'
  AND  procedurecode = '90685'
</code>```

答:
Thank you Juan I looked up lead and lag and was able to come up with the code below to suit my needs! now i can have a date something was posted and find the amount that should have pertained to the ProcedureCode at that time more easily</p>

```<code>SELECT s.ProfileSID,s.ProcedureCode,s.Amount,cast(s.EffectiveDate as date)     as EffectiveDate ,
cast(isnull(dateadd(day,-1,LEAD(EffectiveDate) OVER (ORDER BY     ProfileSID,ProcedureCode,EffectiveDate
)),getdate())as date) ExpDate
FROM iETL_ProfileProcedure s
WHERE ProfileSID IN ('4197')and ProcedureCode = '90685'
</code>```

Body:
So I can not use a temp table to accomplish this. Basically I need to create an experation date based off the next effective date available.

So for one proc code i have 10 fee schedules with only effective dates. I tried writing this but its not working because it is giving for some records the same expiration date. I know an order by is needed but i placed it in various places and it still gives me the same issue. Any help is greatly appreciated

SELECT a.*,
       ( CASE
           WHEN (SELECT TOP 1 b.effectivedate - 1
                 FROM   ietl_profileprocedure b
                 WHERE  b.effectivedate > a.effectivedate
                   AND  a.profilesid = b.profilesid) IS NULL THEN (SELECT
           Dateadd(mm, Datediff(mm, 0, Getdate()) + 1, -1))
           ELSE (SELECT TOP 1 b.effectivedate - 1
                 FROM   ietl_profileprocedure b
                 WHERE  b.effectivedate > a.effectivedate
                   AND  a.profilesid = b.profilesid)
         END ) AS 'ExpDate'
FROM   ietl_profileprocedure a
WHERE  profilesid = '4197'
  AND  procedurecode = '90685'

Body:
Thank you Juan I looked up lead and lag and was able to come up with the code below to suit my needs! now i can have a date something was posted and find the amount that should have pertained to the ProcedureCode at that time more easily

SELECT s.ProfileSID,s.ProcedureCode,s.Amount,cast(s.EffectiveDate as date)     as EffectiveDate ,
cast(isnull(dateadd(day,-1,LEAD(EffectiveDate) OVER (ORDER BY     ProfileSID,ProcedureCode,EffectiveDate
)),getdate())as date) ExpDate
FROM iETL_ProfileProcedure s
WHERE ProfileSID IN ('4197')and ProcedureCode = '90685'


来源: stackexchange

问:
File size limit for SQLite on 32bit system
I'm using sqlite as temporary storage to calculate statistic about moderately large data set.
I'm wondering what will happen if my database exceed 2GB on 32 bit system. (I can't currently change the system to 64 bit)

Does it use memory mapped files and break if size of file exceed addressable memory? (like mongodb)

答:
According sqlite documentation, maximum size of database file is ~140 terabytes and is practically limited by os/file system.

You can read more here (note the Pages section): http://www.sqlite.org/fileformat2.html

ContentLicense: CC BY-SA 2.5


问:
FileInputStream & FileOutputStream
I am trying to save objects from a Java application to a file for later use after the application is closed.  I understand that you use FileInputStream/ObjectInputStream to read objects from a file and use FileOutputStream/ObjectOutputStream to write objects to a file.  So far I am able to successfully save the objects to a file and reload them back into the application when I reopen the app. However my problem is that this only works once.

I start the application, input data and close the application.  The data is written to the specified file and when I reopen the application the data is properly reloaded into the application, but if I add any new data it does not get written to the specified file when the app is closed.  Then when I reopen the application a second time no data is read into the app leaving the app completely blank.

Here is my code for my object writing:

```<code>static class quit_Action implements ActionListener
{
    @Override
    public void actionPerformed (ActionEvent e)
    {
        try
        {
            FileOutputStream savedData = new FileOutputStream("groupData.txt", false);
            ObjectOutputStream save = new ObjectOutputStream(savedData);
            save.writeObject(existingGroups);
            save.writeObject(groupCombo);
            save.writeObject(groupList);
            System.out.println("Data Saved");
            save.close();
            System.out.println("savedData Closed");

        }
        catch(IOException ioe)
        {
        }
        System.exit(0);
    }
}
</code>```

The first time this is run the system outputs "Data Saved" and "savedData Closed", but the second time this is run neither print statement is printed.  Through troubleshooting I've determined all the code up to

```<code>ObjectOutputStream save = new ObjectOutputStream(savedData);
</code>```

runs, but any lines after that do not occur except for the system exit.

Here is the code for my object reading:

```<code>try
    {
        FileInputStream loadedData = new FileInputStream("groupData.txt");
        ObjectInputStream load = new ObjectInputStream(loadedData);
        existingGroups = (ArrayList<NewGroup>) load.readObject();
        groupCombo = (DefaultComboBoxModel) load.readObject();
        groupList = (DefaultListModel) load.readObject();
        System.out.println("Data Loaded");
        loadedData.close();
        System.out.println("loadedData Closed");
    }
    catch(IOException ioe2)
    {
    }
</code>```

This has the same problem as the writing part in that "Data Loaded" and "loadedData Closed" are printed the first time but not the second time. The code up to

```<code>ObjectInputStream load = new ObjectInputStream(loadedData);
</code>```

runs, but nothing after it inside the try statement.

If I delete the file groupData.txt and reopen the application I am able to read and write again, but only once.  I have tried deleting the file in the application using the File.delete() method, but even if the application makes it past this line of code the file doesn't delete itself.  My thought here was that I could delete the file then create a new one of the same name directly afterwards then writing the objects to the new file before closing the program. This has not worked.  I have also tried creating a new file every time I create a FileOutPutStream using

```<code>FileOutputStream out = new FileOutputStream(new File(groupData.txt), false);
</code>```

But this has not worked either.

I thought maybe I could come up with a way to create a file with a different name every time the application is opened and use that to create my streams, but I am not sure how I would do this and it would also clutter whatever directory the files are being created in with a bunch of useless files.

This is how my objects are initialized

```<code>static DefaultListModel groupList = new DefaultListModel();
static DefaultComboBoxModel groupCombo = new DefaultComboBoxModel();
static ArrayList<NewGroup> existingGroups = new ArrayList<NewGroup>();
</code>```

I looked online, but am mostly only able to find tutorials of how to write/read objects to and from an application, which I have figured out how to do(though only once), which is why I figured I would ask for help. If this has already been asked I apologize, I looked through a dozen or so questions and they didn't pertain to this specific problem.

答: Instead of FileOutputStream savedData = new FileOutputStream("groupData.txt", ***false***);, use FileOutputStream savedData = new FileOutputStream("groupData.txt", ***true***);. The second parameter, when set to true, indicates that you want to add data to your file. As you chose 'false', existing data is erased before the new data is saved.

ContentLicense: CC BY-SA 3.0

Title: FileInputStream & FileOutputStream

Body:
I am trying to save objects from a Java application to a file for later use after the application is closed.  I understand that you use FileInputStream/ObjectInputStream to read objects from a file and use FileOutputStream/ObjectOutputStream to write objects to a file.  So far I am able to successfully save the objects to a file and reload them back into the application when I reopen the app. However my problem is that this only works once.

I start the application, input data and close the application.  The data is written to the specified file and when I reopen the application the data is properly reloaded into the application, but if I add any new data it does not get written to the specified file when the app is closed.  Then when I reopen the application a second time no data is read into the app leaving the app completely blank.

Here is my code for my object writing:

static class quit_Action implements ActionListener
{
    @Override
    public void actionPerformed (ActionEvent e)
    {
        try
        {
            FileOutputStream savedData = new FileOutputStream("groupData.txt", false);
            ObjectOutputStream save = new ObjectOutputStream(savedData);
            save.writeObject(existingGroups);
            save.writeObject(groupCombo);
            save.writeObject(groupList);
            System.out.println("Data Saved");
            save.close();
            System.out.println("savedData Closed");

        }
        catch(IOException ioe)
        {
        }
        System.exit(0);
    }
}

The first time this is run the system outputs "Data Saved" and "savedData Closed", but the second time this is run neither print statement is printed.  Through troubleshooting I've determined all the code up to

ObjectOutputStream save = new ObjectOutputStream(savedData);

runs, but any lines after that do not occur except for the system exit.

Here is the code for my object reading:

try
    {
        FileInputStream loadedData = new FileInputStream("groupData.txt");
        ObjectInputStream load = new ObjectInputStream(loadedData);
        existingGroups = (ArrayList<NewGroup>) load.readObject();
        groupCombo = (DefaultComboBoxModel) load.readObject();
        groupList = (DefaultListModel) load.readObject();
        System.out.println("Data Loaded");
        loadedData.close();
        System.out.println("loadedData Closed");
    }
    catch(IOException ioe2)
    {
    }

This has the same problem as the writing part in that "Data Loaded" and "loadedData Closed" are printed the first time but not the second time. The code up to

ObjectInputStream load = new ObjectInputStream(loadedData);

runs, but nothing after it inside the try statement.

If I delete the file groupData.txt and reopen the application I am able to read and write again, but only once.  I have tried deleting the file in the application using the File.delete() method, but even if the application makes it past this line of code the file doesn't delete itself.  My thought here was that I could delete the file then create a new one of the same name directly afterwards then writing the objects to the new file before closing the program. This has not worked.  I have also tried creating a new file every time I create a FileOutPutStream using

FileOutputStream out = new FileOutputStream(new File(groupData.txt), false);

But this has not worked either.

I thought maybe I could come up with a way to create a file with a different name every time the application is opened and use that to create my streams, but I am not sure how I would do this and it would also clutter whatever directory the files are being created in with a bunch of useless files.

This is how my objects are initialized

static DefaultListModel groupList = new DefaultListModel();
static DefaultComboBoxModel groupCombo = new DefaultComboBoxModel();
static ArrayList<NewGroup> existingGroups = new ArrayList<NewGroup>();

I looked online, but am mostly only able to find tutorials of how to write/read objects to and from an application, which I have figured out how to do(though only once), which is why I figured I would ask for help. If this has already been asked I apologize, I looked through a dozen or so questions and they didn't pertain to this specific problem.


问:
App is not updating my textview for google maps api when location is changed
I have an app that displays the latitude, longitude, speed, and distance, in a textview above of the map. The first location is displayed but when I move to another location the textview does not update the information. I also don't know if I am calculating the distance correctly. I am not sure if onLocationChanged is called. My code is below.

---EDIT---

As of now I am no longer working on this project anymore. I believe I was able to fix the issues I had, but I not longer have the code for this project anymore. As this post has been down voted 2 times, I don't believe that it has been very helpful to the community and so I would like to close and delete this post if possible, but there needs to be more votes to close and then delete it. Unless there is any other reason for why this post should stay open?

```<code>public class MainActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    private ArrayList<Location> locations = new ArrayList<Location>();

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

        getSupportActionBar().setTitle("Map");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

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

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        double speed = location.getSpeed();
        double distance = 0;
        locations.add(location);
        for(int i = 0; i < locations.size()-1; i++) {
            distance += locations.get(i).distanceTo(locations.get(i +1));
        }

        StringBuilder stBuilder = new StringBuilder();
        stBuilder.append(" Latitude: ");
        stBuilder.append(latitude);
        stBuilder.append("\n");
        stBuilder.append(" Logitude: ");
        stBuilder.append(longitude);
        stBuilder.append("\n");
        stBuilder.append(" Speed: ");
        stBuilder.append(speed + "                           ");

        stBuilder.append("Distance: ");
        stBuilder.append(distance);
        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(stBuilder);

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

        //optionally, stop location updates if only current location is needed
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void 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("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MainActivity.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 );
            }
        }
    }

    @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) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}
</code>```

答:
In your onLocationChanged() method there is no need to stop the location Service:

Remove this:

```<code> if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
</code>```

calling this immediately will stop the location service and so your onLocationChnage() will not be called.

Besides you are adding it in onPause().

```<code> @Override
public void onPause() {
    super.onPause();

    //stop location updates when Activity is no longer active
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an app that displays the latitude, longitude, speed, and distance, in a textview above of the map. The first location is displayed but when I move to another location the textview does not update the information. I also don't know if I am calculating the distance correctly. I am not sure if onLocationChanged is called. My code is below.

---EDIT---

As of now I am no longer working on this project anymore. I believe I was able to fix the issues I had, but I not longer have the code for this project anymore. As this post has been down voted 2 times, I don't believe that it has been very helpful to the community and so I would like to close and delete this post if possible, but there needs to be more votes to close and then delete it. Unless there is any other reason for why this post should stay open?

public class MainActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    private ArrayList<Location> locations = new ArrayList<Location>();

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

        getSupportActionBar().setTitle("Map");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

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

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        double speed = location.getSpeed();
        double distance = 0;
        locations.add(location);
        for(int i = 0; i < locations.size()-1; i++) {
            distance += locations.get(i).distanceTo(locations.get(i +1));
        }

        StringBuilder stBuilder = new StringBuilder();
        stBuilder.append(" Latitude: ");
        stBuilder.append(latitude);
        stBuilder.append("\n");
        stBuilder.append(" Logitude: ");
        stBuilder.append(longitude);
        stBuilder.append("\n");
        stBuilder.append(" Speed: ");
        stBuilder.append(speed + "                           ");

        stBuilder.append("Distance: ");
        stBuilder.append(distance);
        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(stBuilder);

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

        //optionally, stop location updates if only current location is needed
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void 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("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MainActivity.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 );
            }
        }
    }

    @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) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

Body:
In your onLocationChanged() method there is no need to stop the location Service:

Remove this:

 if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

calling this immediately will stop the location service and so your onLocationChnage() will not be called.

Besides you are adding it in onPause().

 @Override
public void onPause() {
    super.onPause();

    //stop location updates when Activity is no longer active
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
}


问:
Very slow delete on mysql base with subquery
This mysql query is running for around 10 hours and has not finished. Something is horribly wrong.

Two tables (text and spam) are here. Spam stores the ids of spam entrys in text that I want to delete.

```<code>DELETE FROM tname.text WHERE old_id IN (SELECT textid FROM spam);
</code>```

spam has just 2 columns, both are ints. 800K entries has a file size of several Mbs. Both ints are primary keys.

text has 3 columns. id (prim key), text, flags. around 1200K entries, and around 2.1 gigabyte size (most spam).

The server is a xeon quad, 2 gigabyte ram (don't ask me why). Only apache (why?) and mysqld is running. Its an old free bsd and mysql 4.1.2 (don't ask me why)

Threads: 6  Questions: 188805  Slow queries: 318  Opens: 810  Flush tables: 1  Open tables: 157  Queries per second avg: 7.532

Mysql my.cnf:

```<code>[mysqld]
datadir=/usr/local/mysql
log-error=/usr/local/mysql/mysqld.err
pid-file=/usr/local/mysql/mysqld.pid
tmpdir=/var/tmp
innodb_data_home_dir =
innodb_log_files_in_group = 2
join_buffer_size=2M
key_buffer_size=32M
max_allowed_packet=1M
max_connections=800
myisam_sort_buffer_size=32M
query_cache_size=8M
read_buffer_size=2M
sort_buffer_size=2M
table_cache=256
skip-bdb
log-slow-queries = slow.log
long_query_time = 1

#skip-innodb
#default-table-type=innodb
innodb_data_file_path = /usr/local/mysql/ibdata1:10M:autoextend
innodb_log_group_home_dir = /usr/local/mysql/
innodb_buffer_pool_size = 128M
innodb_log_file_size = 16M
innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit=1
#innodb_additional_mem_pool_size=1M
#innodb_lock_wait_timeout=50

log-bin
server-id=201

[isamchk]
key_buffer_size=128M
read_buffer_size=128M
write_buffer_size=128M
sort_buffer_size=128M

[myisamchk]
key_buffer_size=128M[server:~] dmesg | grep memory
real memory  = 2146828288 (2047 MB)
avail memory = 2095534080 (1998 MB)

read_buffer_size=128M
write_buffer_size=128M
sort_buffer_size=128M
tmpdir=/var/tmp
</code>```

The query is using just one cpu, top says 25% cpu time (so 1 of 4).

```<code>real memory  = 2146828288 (2047 MB)
avail memory = 2095534080 (1998 MB)

62 processes:  2 running, 60 sleeping
CPU states: 25.2% user,  0.0% nice,  1.6% system,  0.0% interrupt, 73.2% idle
Mem: 244M Active, 1430M Inact, 221M Wired, 75M Cache, 112M Buf, 31M Free
Swap: 4096M Total, 1996K Used, 4094M Free

  PID USERNAME     THR PRI NICE   SIZE    RES STATE  C   TIME   WCPU COMMAND
11536 mysql         27  20    0   239M   224M kserel 3 441:16 94.29% mysqld
</code>```

Any idea how to fix it?

答:
of corse it will take a lot of time because it execute the subquery for every record but by using INNER JOIN directly this query is executed only one time
lets think that the query will take

```<code>10 ms for 50000 rec  full time = 50000 * 10 ms ---> 8.333 minutes !! at least don't forget the condition and deleting time .....
</code>```

but using join the query will be executed only one time :

```<code>DELETE t FROM tname.text t INNER JOIN (SELECT textid FROM spam) sq on t.old_id = sq.textid ;
</code>```

Body:
This mysql query is running for around 10 hours and has not finished. Something is horribly wrong.

Two tables (text and spam) are here. Spam stores the ids of spam entrys in text that I want to delete.

DELETE FROM tname.text WHERE old_id IN (SELECT textid FROM spam);

spam has just 2 columns, both are ints. 800K entries has a file size of several Mbs. Both ints are primary keys.

text has 3 columns. id (prim key), text, flags. around 1200K entries, and around 2.1 gigabyte size (most spam).

The server is a xeon quad, 2 gigabyte ram (don't ask me why). Only apache (why?) and mysqld is running. Its an old free bsd and mysql 4.1.2 (don't ask me why)

Threads: 6  Questions: 188805  Slow queries: 318  Opens: 810  Flush tables: 1  Open tables: 157  Queries per second avg: 7.532

Mysql my.cnf:

[mysqld]
datadir=/usr/local/mysql
log-error=/usr/local/mysql/mysqld.err
pid-file=/usr/local/mysql/mysqld.pid
tmpdir=/var/tmp
innodb_data_home_dir =
innodb_log_files_in_group = 2
join_buffer_size=2M
key_buffer_size=32M
max_allowed_packet=1M
max_connections=800
myisam_sort_buffer_size=32M
query_cache_size=8M
read_buffer_size=2M
sort_buffer_size=2M
table_cache=256
skip-bdb
log-slow-queries = slow.log
long_query_time = 1

#skip-innodb
#default-table-type=innodb
innodb_data_file_path = /usr/local/mysql/ibdata1:10M:autoextend
innodb_log_group_home_dir = /usr/local/mysql/
innodb_buffer_pool_size = 128M
innodb_log_file_size = 16M
innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit=1
#innodb_additional_mem_pool_size=1M
#innodb_lock_wait_timeout=50

log-bin
server-id=201

[isamchk]
key_buffer_size=128M
read_buffer_size=128M
write_buffer_size=128M
sort_buffer_size=128M

[myisamchk]
key_buffer_size=128M[server:~] dmesg | grep memory
real memory  = 2146828288 (2047 MB)
avail memory = 2095534080 (1998 MB)

read_buffer_size=128M
write_buffer_size=128M
sort_buffer_size=128M
tmpdir=/var/tmp

The query is using just one cpu, top says 25% cpu time (so 1 of 4).

real memory  = 2146828288 (2047 MB)
avail memory = 2095534080 (1998 MB)

62 processes:  2 running, 60 sleeping
CPU states: 25.2% user,  0.0% nice,  1.6% system,  0.0% interrupt, 73.2% idle
Mem: 244M Active, 1430M Inact, 221M Wired, 75M Cache, 112M Buf, 31M Free
Swap: 4096M Total, 1996K Used, 4094M Free

  PID USERNAME     THR PRI NICE   SIZE    RES STATE  C   TIME   WCPU COMMAND
11536 mysql         27  20    0   239M   224M kserel 3 441:16 94.29% mysqld

Any idea how to fix it?

Body:
of corse it will take a lot of time because it execute the subquery for every record but by using INNER JOIN directly this query is executed only one time
lets think that the query will take

10 ms for 50000 rec  full time = 50000 * 10 ms ---> 8.333 minutes !! at least don't forget the condition and deleting time .....

but using join the query will be executed only one time :

DELETE t FROM tname.text t INNER JOIN (SELECT textid FROM spam) sq on t.old_id = sq.textid ;


问:
Turn off themeing of menus in Qt?
I've inherited a Qt project that had themed right-click menus (which look really weird on macOS). I removed the setStyleSheet() call from the QMenu, yet it still highlights only the text instead of the item's background and uses weird font sizes.

Is there any other place in a Qt app where someone could have set colors that the menu would somehow inherit?

The menu is shown via exec(), and the QMenu and QActions are created with a QWidget as their parent, in case that helps.

答:
Probably it has been set globally; look for a call to QApplication::setStyleSheet, and for a QMenu selector inside that global stylesheet. It may also be set into a stylesheet of a parent widget.

In general, if I were you I'd grep the project for stylesheets that contain a QMenu selector.

Title: Turn off themeing of menus in Qt?


问:
Merging a dataframe in a dict with another dataframe in Python
I have a dict that currently looks like this:

```<code>raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
import pandas as pd
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
dict = {}
dict = {'Check':df1}
print dict
</code>```

I am trying to append the appended df to the df element of this dict such as:

```<code>appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
import pandas as pd
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print appended

adfs = {k:df.merge(appended[appended.Desc==df.Desc],on=['Series_Date'],how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}
</code>```

However, on running this merge statement, I get the following error: ValueError: Can only compare identically-labeled Series objects

Tried reading on thie error but not sure how it's applicable here, any thoughts what could be done to get over this error or alternatively, another approach to do

答:
using 'pd.concat' can do the job here.

```<code>import pandas as pd
raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
print 'df1:\n', df1

appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print 'appended\n:',appended

df_concat =pd.concat([appended,df1],axis=0)
print 'concat\n:',df_concat
</code>```

Will results with:

```df1:
  Series_Date  Value Type      Desc
0  2017-03-10      1   SP  Check SP
1  2017-03-10      1   1M  Check 1M
2  2017-03-10      1   3M  Check 3M
3  2017-03-13      1   SP  Check SP
4  2017-03-13      1   1M  Check 1M
5  2017-03-13      1   3M  Check 3M
appended
:   Series_Date  Value Type      Desc
0  2017-03-13      1   SP  Check SP
1  2017-03-13      1   1M  Check 1M
2  2017-03-13      1   3M  Check 3M
concat
:   Series_Date  Value Type      Desc
0  2017-03-13      1   SP  Check SP
1  2017-03-13      1   1M  Check 1M
2  2017-03-13      1   3M  Check 3M
0  2017-03-10      1   SP  Check SP
1  2017-03-10      1   1M  Check 1M
2  2017-03-10      1   3M  Check 3M
3  2017-03-13      1   SP  Check SP
4  2017-03-13      1   1M  Check 1M
5  2017-03-13      1   3M  Check 3M
```

Body:
I have a dict that currently looks like this:

raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
import pandas as pd
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
dict = {}
dict = {'Check':df1}
print dict

I am trying to append the appended df to the df element of this dict such as:

appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
import pandas as pd
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print appended

adfs = {k:df.merge(appended[appended.Desc==df.Desc],on=['Series_Date'],how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}

However, on running this merge statement, I get the following error: ValueError: Can only compare identically-labeled Series objects

Tried reading on thie error but not sure how it's applicable here, any thoughts what could be done to get over this error or alternatively, another approach to do

Body:
using 'pd.concat' can do the job here.

import pandas as pd
raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
print 'df1:\n', df1

appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print 'appended\n:',appended

df_concat =pd.concat([appended,df1],axis=0)
print 'concat\n:',df_concat

Will results with:

df1:
  Series_Date  Value Type      Desc
0  2017-03-10      1   SP  Check SP
1  2017-03-10      1   1M  Check 1M
2  2017-03-10      1   3M  Check 3M
3  2017-03-13      1   SP  Check SP
4  2017-03-13      1   1M  Check 1M
5  2017-03-13      1   3M  Check 3M
appended
:   Series_Date  Value Type      Desc
0  2017-03-13      1   SP  Check SP
1  2017-03-13      1   1M  Check 1M
2  2017-03-13      1   3M  Check 3M
concat
:   Series_Date  Value Type      Desc
0  2017-03-13      1   SP  Check SP
1  2017-03-13      1   1M  Check 1M
2  2017-03-13      1   3M  Check 3M
0  2017-03-10      1   SP  Check SP
1  2017-03-10      1   1M  Check 1M
2  2017-03-10      1   3M  Check 3M
3  2017-03-13      1   SP  Check SP
4  2017-03-13      1   1M  Check 1M
5  2017-03-13      1   3M  Check 3M


问:
Filtering JSON data in jQuery or vanilla JavaScript
I want to filter my JSON-object in jQuery or vanilla JavaScript. I prefer vanilla JavaScript but don't know how to solve this. I have created pseudo-code in order to explain what I want to achieve. Any ideas?

I basically want to only allow records that don't contain values from the lists. The first list only contains mfs values that should be excluded from expJSON. Second list contains pn values that should be excluded from expJSON, and so on...

Pseude-code

```<code>var results = $(jsonData).filter(function (i, n) {
        return if list1 is not empty: (n.psn.indexOf(item1 from list1) === -1 || n.psn.indexOf(item2 from list1) === -1 || n.psn.indexOf(item3 from list1) === -1 ... ) &&
        if list2 is not empty: (n.pn.indexOf(item1 from list2) === -1 || n.pn.indexOf(item2 from list2) === -1 || n.pn.indexOf(item3 from list2) === -1 ... ) &&
        if list3 is not empty: (n.mft.indexOf(item1 from list3) === -1 || n.mft.indexOf(item2 from list3) === -1 || n.mft.indexOf(item3 from list3) === -1 ... ) &&
        if list4 is not empty: (n.sl.indexOf(item1 from list4) === -1 || n.sl.indexOf(item2 from list4) === -1 || n.sl.indexOf(item3 from list4) === -1 ... ) &&
        if list5 is not empty: (n.vtv.indexOf(item1 from list5) === -1 || n.vtv.indexOf(item2 from list5) === -1 || n.vtv.indexOf(item3 from list5) === -1 ... )
    })
</code>```

jsonData

```<code>[{"mft": "asjfasdf", "pn": "234awefwa", "vtv": "No", "psn": "234fasdfa", "sl": "asf8sf"}, {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"}, {"mft": "fbsdf8df", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"}, {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"} ...]
</code>```

list1, list2, list3, list4, list5

```<code>              item1     item2    item3
list1/mft = ["word1", "word2", "word3", ...]
list2/pn = ["word1", "word2", "word3", ...]
list3/vtv = ["word1", "word2", "word3", ...]
list4/psn = ["word1", "word2", "word3", ...]
list5/sl = ["word1", "word2", "word3", ...]
</code>```

答:
If I understand the question correctly, this should solve it for you.</p>

```<code>// this is based on the jsonData provided
// but I deleted some values cause you said it might not always have a value
var jsonData = [
    {"mft": "asjfasdf", "pn": "234awefwa", "vtv": "", "psn": "234fasdfa", "sl": "asf8sf"},
    {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"},
    {"mft": "", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"},
    {"mft": "sdf7688sdf76f", "pn": "", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"},
    {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": ""}]

var keys = ['mft', 'pn', 'vtv', 'psn', 'sl']
var mftList = []
var pnList = []
var vtvList = []
var psnList = []
var slList = []

jsonData.forEach(function(data) {
    keys.forEach(function(key){
       var value = data[key];
       if(!value) {return;}

       switch (key) {
           case 'mft': {
                mftList.push(value)
                break;
           }
           case 'pn': {
                pnList.push(value)
                break;
           }
           case 'vtv': {
                vtvList.push(value)
                break;
           }
           case 'psn': {
                psnList.push(value)
                break;
           }
           case 'sl': {
                slList.push(value)
                break;
           }
        }
    });
});
</code>```

Body:
I want to filter my JSON-object in jQuery or vanilla JavaScript. I prefer vanilla JavaScript but don't know how to solve this. I have created pseudo-code in order to explain what I want to achieve. Any ideas?

I basically want to only allow records that don't contain values from the lists. The first list only contains mfs values that should be excluded from expJSON. Second list contains pn values that should be excluded from expJSON, and so on...

Pseude-code

var results = $(jsonData).filter(function (i, n) {
        return if list1 is not empty: (n.psn.indexOf(item1 from list1) === -1 || n.psn.indexOf(item2 from list1) === -1 || n.psn.indexOf(item3 from list1) === -1 ... ) &&
        if list2 is not empty: (n.pn.indexOf(item1 from list2) === -1 || n.pn.indexOf(item2 from list2) === -1 || n.pn.indexOf(item3 from list2) === -1 ... ) &&
        if list3 is not empty: (n.mft.indexOf(item1 from list3) === -1 || n.mft.indexOf(item2 from list3) === -1 || n.mft.indexOf(item3 from list3) === -1 ... ) &&
        if list4 is not empty: (n.sl.indexOf(item1 from list4) === -1 || n.sl.indexOf(item2 from list4) === -1 || n.sl.indexOf(item3 from list4) === -1 ... ) &&
        if list5 is not empty: (n.vtv.indexOf(item1 from list5) === -1 || n.vtv.indexOf(item2 from list5) === -1 || n.vtv.indexOf(item3 from list5) === -1 ... )
    })

jsonData

[{"mft": "asjfasdf", "pn": "234awefwa", "vtv": "No", "psn": "234fasdfa", "sl": "asf8sf"}, {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"}, {"mft": "fbsdf8df", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"}, {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"} ...]

list1, list2, list3, list4, list5

              item1     item2    item3
list1/mft = ["word1", "word2", "word3", ...]
list2/pn = ["word1", "word2", "word3", ...]
list3/vtv = ["word1", "word2", "word3", ...]
list4/psn = ["word1", "word2", "word3", ...]
list5/sl = ["word1", "word2", "word3", ...]

Body:
If I understand the question correctly, this should solve it for you.

// this is based on the jsonData provided
// but I deleted some values cause you said it might not always have a value
var jsonData = [
    {"mft": "asjfasdf", "pn": "234awefwa", "vtv": "", "psn": "234fasdfa", "sl": "asf8sf"},
    {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"},
    {"mft": "", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"},
    {"mft": "sdf7688sdf76f", "pn": "", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"},
    {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": ""}]

var keys = ['mft', 'pn', 'vtv', 'psn', 'sl']
var mftList = []
var pnList = []
var vtvList = []
var psnList = []
var slList = []

jsonData.forEach(function(data) {
    keys.forEach(function(key){
       var value = data[key];
       if(!value) {return;}

       switch (key) {
           case 'mft': {
                mftList.push(value)
                break;
           }
           case 'pn': {
                pnList.push(value)
                break;
           }
           case 'vtv': {
                vtvList.push(value)
                break;
           }
           case 'psn': {
                psnList.push(value)
                break;
           }
           case 'sl': {
                slList.push(value)
                break;
           }
        }
    });
});


问:
JavaScript Nesting For Loops
I have the following code where I fail to understand some parts:

```<code>var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
 for (var j=0; j < arr[i].length; j++) {
  console.log(arr[i][j]);
  }
}
</code>```

What does arr[i] mean? I have been told that arr[i] itself is an array. How is that? And What is happening in the arr[i][j] part?

答:
Tried to add comments and rewrite to explain what's happening a little better. Play with the code until you understand what's happening!

// A 2-dimension array (or "array of arrays").
// You can think of this as a matrix by row and column.
var arr = [
//      col 0    col 1
       [    1,       2], // row 0
       [    3,       4], // row 1
       [    5,       6], // row 2
];

// Loop over rows.
for (var r = 0; r < arr.length; r++) {
 // The "row" is the array at index r.
 var row = arr[r];
 // Loop over columns.
 for (var c = 0; c < row.length; c++) {
  // Print the value at row "r" and column "c".
  console.log(`row ${r}, column ${c} = ${row[c]}`);
  }
}```

Title: JavaScript Nesting For Loops

Body:
I have the following code where I fail to understand some parts:

var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
 for (var j=0; j < arr[i].length; j++) {
  console.log(arr[i][j]);
  }
}

What does arr[i] mean? I have been told that arr[i] itself is an array. How is that? And What is happening in the arr[i][j] part?


问:
Get number before a specified string
Given the string

```<code>RAM Statistics: 5954 / 8174 743=InUse 746=Peak
</code>```

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"
</code>```

But that's returning nothing.

UPDATE:
Per Joshua I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"
</code>```

And both $matches[0] and [1] return everything before the =Peak. So

```<code>Statistics:     5954 /     8174       743=InUse      746!
</code>```

Title: Get number before a specified string

Body:
Given the string

RAM Statistics: 5954 / 8174 743=InUse 746=Peak

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"

But that's returning nothing.

UPDATE:
Per Joshua I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"

And both $matches[0] and [1] return everything before the =Peak. So

Statistics:     5954 /     8174       743=InUse      746!

Body:
$Pattern = '(\d+) *\/ *(\d+) +(\d+)=[^0-9]*(\d+)'
$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
if ($string -match $Pattern){$Matches[0..4]}

5954 /     8174       743=InUse      746
5954
8174
743
746


问:
VBA Copying Excel Range to Different Workbook
I am trying to find a way to copy a range in one workbook, in this case A6:J21,to another workbook. I thought it would be something like the following...

```<code>currentWorksheet = xlWorkBook.Sheets.Item("Command Group")
excelRange = currentWorksheet.Range("A6:J21")
excelDestination = newXlSheet.Range("A6:J21")
excelRange.Copy(excelDestination)
</code>```

But it gives me an error on excelRange.Copy(excelDestination).

The below code runs as expected, so I'm not sure where i'm going wrong here..

```<code>Dim xRng As Excel.Range = CType(currentWorksheet.Cells(7, 7), Excel.Range)
Console.WriteLine(xRng.ToString)
Dim val As Object = xRng.Value()
testString = val.ToString
Console.WriteLine(testString)
newXlSheet.Cells(1, 1) = testString
</code>```

答:
This should do it, let me know if you have trouble with it:

```<code>Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub
</code>```

Alternatively, you could just:

```<code>Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1")

'Close x:
x.Close

End Sub
</code>```

Copy from one workbook and paste into another

Body:
I am trying to find a way to copy a range in one workbook, in this case A6:J21,to another workbook. I thought it would be something like the following...

currentWorksheet = xlWorkBook.Sheets.Item("Command Group")
excelRange = currentWorksheet.Range("A6:J21")
excelDestination = newXlSheet.Range("A6:J21")
excelRange.Copy(excelDestination)

But it gives me an error on excelRange.Copy(excelDestination).

The below code runs as expected, so I'm not sure where i'm going wrong here..

Dim xRng As Excel.Range = CType(currentWorksheet.Cells(7, 7), Excel.Range)
Console.WriteLine(xRng.ToString)
Dim val As Object = xRng.Value()
testString = val.ToString
Console.WriteLine(testString)
newXlSheet.Cells(1, 1) = testString

Body:
This should do it, let me know if you have trouble with it:

Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub

Alternatively, you could just:

Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1")

'Close x:
x.Close

End Sub

Copy from one workbook and paste into another


问:
ExcelNewbie: Matching cell information across worksheets
Please forgive me if this is simple...I am not an Excel expert and this is causing my nose to bleed(!)

Firstly I am using Excel 365.

I am working on a Bonus Calculator Sheet and the system is VERY complex, but I have reduced it to a two column table.

Column A is the company success "number" and column B is the % bonus it draws. This is all on worksheet B.
Worksheet A contains salary stuff and the company success number sits at the top and is not changed. What I need to do in pseudocode is:

Take value from Sheet A Cell A1
Find match in Sheet B Column A.
Return value next to it in Column B to Sheet A somewhere.

My life is mainly spent in the world of Python and this looks SO simple - but any help you experts could offer would just make my day rosier...if anyone can help I will give my two dogs a biscuit to show the love(!)

Thanks.

答:
You could also try using index match formula

```<code>=INDEX(SheetB!B:B,MATCH(A1,SheetB!A:A,0))
</code>```

Where A1 is the value that you want to lookup in SheetB in range A:A.

Body:
You could also try using index match formula

=INDEX(SheetB!B:B,MATCH(A1,SheetB!A:A,0))

Where A1 is the value that you want to lookup in SheetB in range A:A.


问:
Overlaying an image only on currently clicked Div - Javascript
I'm trying to overlay a small checkmark (an image) over whatever image/div is currently clicked. I would prefer to use just javascript if possible, since the rest of my program is written in that.

```<code>$('#checked').click(function(){
  if ( $('.selected').css('visibility') == 'hidden' )
     $('.selected').css('visibility','visible').siblings('visibility','hidden');
  else
     $('.selected').css('visibility','hidden');
});

<div id="checked">
   <div id="axisFrame">
      <img name="msImg" id='axisSofa' src="img.jpg" />
   </div>

<div id="checked">
    <div id="fionaFrame">
       <img name="msImg" id='fionaSofa' src="img.jpg" />
    </div>

.selected {
   width: 46px;
   height: 46px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin: -23px auto 0 -23px;
   background-image: url(images/msSelected.png);
   z-index: 10;
   visibility:"hidden";
}
</code>```

I want the msSelected image to overlay on the div that is most recently clicked and then disappear when another element is clicked (basically a selector).

Any help is much appreciated!!

答:
There are a few problems with this - right now nothing sets selected items as selected, and visibility:hidden will hide the whole div tag, including the background image.

One solution would be to have the div background always a checkbox and hide the img tag when clicked:

```<code>$('#msImg').click(function(){
  if ( $(this).css('visibility') == 'hidden' )
     $(this).css('visibility','visible');
  else
     $(this).css('visibility','hidden');
});

<div class="checked">
   <div id="axisFrame">
      <img name="msImg" id='axisSofa' src="img.jpg" />
   </div>

<div class="checked">
    <div id="fionaFrame">
       <img name="msImg" id='fionaSofa' src="img.jpg" />
    </div>

.checked {
   width: 46px;
   height: 46px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin: -23px auto 0 -23px;
   background-image: url(images/msSelected.png);
   z-index: 10;
}
</code>```

Body:
I'm trying to overlay a small checkmark (an image) over whatever image/div is currently clicked. I would prefer to use just javascript if possible, since the rest of my program is written in that.

$('#checked').click(function(){
  if ( $('.selected').css('visibility') == 'hidden' )
     $('.selected').css('visibility','visible').siblings('visibility','hidden');
  else
     $('.selected').css('visibility','hidden');
});

.selected {
   width: 46px;
   height: 46px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin: -23px auto 0 -23px;
   background-image: url(images/msSelected.png);
   z-index: 10;
   visibility:"hidden";
}

I want the msSelected image to overlay on the div that is most recently clicked and then disappear when another element is clicked (basically a selector).

Any help is much appreciated!!

Body:
There are a few problems with this - right now nothing sets selected items as selected, and visibility:hidden will hide the whole div tag, including the background image.

One solution would be to have the div background always a checkbox and hide the img tag when clicked:

$('#msImg').click(function(){
  if ( $(this).css('visibility') == 'hidden' )
     $(this).css('visibility','visible');
  else
     $(this).css('visibility','hidden');
});

<div class="checked">
   <div id="axisFrame">
      <img name="msImg" id='axisSofa' src="img.jpg" />
   </div>

<div class="checked">
    <div id="fionaFrame">
       <img name="msImg" id='fionaSofa' src="img.jpg" />
    </div>

.checked {
   width: 46px;
   height: 46px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin: -23px auto 0 -23px;
   background-image: url(images/msSelected.png);
   z-index: 10;
}


问:
Dplyr: filter last entry for date in a series
I want to filter only the last date entry in a time series for every occurrence where there was more than one for a given month.

As an example in a table like this:

```<code>obs <- c("A", "B", "A", "B", "A", "B", "A", "B")
date <- c("2017-01-01", "2017-01-01", "2017-02-01", "2017-02-01", "2017-03-01", "2017-03-01", "2017-03-02","2017-03-02")
num <- c(1000, 1800, 2000, 2900, 3000, 3400, 3500, 3400)
dat <- data.frame(obs, date, num)

    obs       date  num
1   A 2017-01-01 1000
2   B 2017-01-01 1800
3   A 2017-02-01 2000
4   B 2017-02-01 2900
5   A 2017-03-01 3000
6   B 2017-03-01 3400
7   A 2017-03-02 3500
8   B 2017-03-02 3400
</code>```

A simple selection for "A" would be:

```<code>x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date))

  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
3   A 2017-03-01 3000
4   A 2017-03-02 3500
</code>```

So, there are now two entries for the third month and I would like to keep only the most recent entry for that month. I thought it would be a straightforward thing to do so I did:

```<code>x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date)) %>%
  arrange(date) %>%
  slice(which.max(date))
</code>```

But I get just the last entry instead with the other ones removed. What am I missing? The output should be:

```<code>  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
4   A 2017-03-02 3500
</code>```

答:
You need to group by month(date) and then filter for the last date:

```<code>dat %>% filter(obs=="A") %>%
        mutate(date = ymd(date)) %>%
        group_by(obs, m = month(date)) %>%
        filter(date == max(date))
#     obs       date   num     m
#1      A 2017-01-01  1000     1
#2      A 2017-02-01  2000     2
#3      A 2017-03-02  3500     3
</code>```

Body:
I want to filter only the last date entry in a time series for every occurrence where there was more than one for a given month.

As an example in a table like this:

obs <- c("A", "B", "A", "B", "A", "B", "A", "B")
date <- c("2017-01-01", "2017-01-01", "2017-02-01", "2017-02-01", "2017-03-01", "2017-03-01", "2017-03-02","2017-03-02")
num <- c(1000, 1800, 2000, 2900, 3000, 3400, 3500, 3400)
dat <- data.frame(obs, date, num)

    obs       date  num
1   A 2017-01-01 1000
2   B 2017-01-01 1800
3   A 2017-02-01 2000
4   B 2017-02-01 2900
5   A 2017-03-01 3000
6   B 2017-03-01 3400
7   A 2017-03-02 3500
8   B 2017-03-02 3400

A simple selection for "A" would be:

x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date))

  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
3   A 2017-03-01 3000
4   A 2017-03-02 3500

So, there are now two entries for the third month and I would like to keep only the most recent entry for that month. I thought it would be a straightforward thing to do so I did:

x <- dat %>%
  filter(obs=="A") %>%
  select(obs, date, num) %>%
  mutate(date = ymd(date)) %>%
  arrange(date) %>%
  slice(which.max(date))

But I get just the last entry instead with the other ones removed. What am I missing? The output should be:

  obs       date  num
1   A 2017-01-01 1000
2   A 2017-02-01 2000
4   A 2017-03-02 3500

Body:
You need to group by month(date) and then filter for the last date:

dat %>% filter(obs=="A") %>%
        mutate(date = ymd(date)) %>%
        group_by(obs, m = month(date)) %>%
        filter(date == max(date))
#     obs       date   num     m
#1      A 2017-01-01  1000     1
#2      A 2017-02-01  2000     2
#3      A 2017-03-02  3500     3


问:
How to block a specific user agent in nginx config
How do I block a user agent using nginx.
so far I have something like this:

```<code>if ($http_user_agent = "Mozilla/5.0 (Linux; Android 4.2.2; SGH-M919 Build/JDQ39) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.169 Mobile Safari/537.22") {
return 403;}
</code>```

this is from a similar thread on this stack overflow.

I run nginx as a reverse proxy for cherrypy server. I intend to filter a certain user agent using nginx alone but the above code doesn't work on my server.

is that the correct way to do this?
It wasn't included in any block in the nginx config. Should I add it to the "http" block or the "server" block

答:
If's are evil - use the map directive.

Directive if has problems when used in location context, in some cases
it doesn’t do what you expect but something completely different
instead. In some cases it even segfaults. It’s generally a good idea
to avoid it if possible.

Nginx Ultimate Bad Bot Blocker makes blocking bots easy with support for Debian / Centos / Alpine Linux / FreeBSD.

Body:
How do I block a user agent using nginx.
so far I have something like this:

if ($http_user_agent = "Mozilla/5.0 (Linux; Android 4.2.2; SGH-M919 Build/JDQ39) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.169 Mobile Safari/537.22") {
return 403;}

this is from a similar thread on this stack overflow.

I run nginx as a reverse proxy for cherrypy server. I intend to filter a certain user agent using nginx alone but the above code doesn't work on my server.

is that the correct way to do this?
It wasn't included in any block in the nginx config. Should I add it to the "http" block or the "server" block


问:
Any faster, simpler alternative to php preg_match
I am using cakephp 1.3 and I have textarea where users submit articles. On submit, I want to look into the article for certain key words and and add respective tags to the article.

I was thinking of preg_match, But preg_match pattern has to be string. So I would have to loop through an array(big).

Is there a easier way to plug in the keywords array for the pattern.

I appreciate all your help.

Thanks.

答: Add tags manually? Just like we add tags here at SO.</p>


答:
The styles are inheritable. There can be a global stylesheet, or a stylesheet on any of the widgets that are parents of the menu being shown. You'll need to inspect them all and remove menu styles.

You could limit the applicability of the menu styles by using a dynamic property to describe whether the style should apply or not:

```<code>QMenu[styled="true"] { ... }
</code>```

Then, on the platforms where the menus are styled, apply the property:

```<code>void styleMenu(QMenu * menu) {
  #ifndef Q_OS_MACOS
  menu->setProperty("styled", true);
  #endif
}

...
styleMenu(menu); // no-op on OS X
</code>```

Title: Turn off themeing of menus in Qt?

Body:
I've inherited a Qt project that had themed right-click menus (which look really weird on macOS). I removed the setStyleSheet() call from the QMenu, yet it still highlights only the text instead of the item's background and uses weird font sizes.

Is there any other place in a Qt app where someone could have set colors that the menu would somehow inherit?

The menu is shown via exec(), and the QMenu and QActions are created with a QWidget as their parent, in case that helps.

Body:
The styles are inheritable. There can be a global stylesheet, or a stylesheet on any of the widgets that are parents of the menu being shown. You'll need to inspect them all and remove menu styles.

You could limit the applicability of the menu styles by using a dynamic property to describe whether the style should apply or not:

QMenu[styled="true"] { ... }

Then, on the platforms where the menus are styled, apply the property:

void styleMenu(QMenu * menu) {
  #ifndef Q_OS_MACOS
  menu->setProperty("styled", true);
  #endif
}

...
styleMenu(menu); // no-op on OS X


答:
So here's some very basic and not well thought out unoptimized code that should do what you want:

```<code>function getLists(data){
  var output={}
  var keys = ['mft', 'pn', 'vtv', 'psn', 'sl'];
  for(var i = 0; i < keys.length; i++){
    var current = keys[i];
    output[current] = [];
    for(var j = 0; j < data.length; j++){
      if(data[j][current){
        output[current].push(data[j][current])
      }
    }
  }
  return output;
}
</code>```

This function should output something like
{mft: ['word1', 'word2' ...], pn: ['word1', 'word2' ...] ... }

Title: Filtering JSON data in jQuery or vanilla JavaScript

Body:
So here's some very basic and not well thought out unoptimized code that should do what you want:

function getLists(data){
  var output={}
  var keys = ['mft', 'pn', 'vtv', 'psn', 'sl'];
  for(var i = 0; i < keys.length; i++){
    var current = keys[i];
    output[current] = [];
    for(var j = 0; j < data.length; j++){
      if(data[j][current){
        output[current].push(data[j][current])
      }
    }
  }
  return output;
}

This function should output something like
{mft: ['word1', 'word2' ...], pn: ['word1', 'word2' ...] ... }


问:
How to specify 'exp' without 'ttl'?
Our security policy requires that users must relogin at 00:00:00, so we can't hardcode some ttl for token in the config. What is the preferable way to create token with specified expiry date like '2017-03-08 00:00:00'?</p>

答: You should have a look at writing and using your own encoder service, computing your token lifetime dynamically.</p>

Title: How to specify 'exp' without 'ttl'?


问:
Why this constructor is called twice?
I have this code:

```<code>// Example program
#include <iostream>
#include <string>

class Hello{
    public:
    Hello(){std::cout<<"Hello world!"<<std::endl;}
};

class Base{
    public:
    Base(const Hello &hello){ this->hello = hello;}
    private:
    Hello hello;
};

class Derived : public Base{
    public:
    Derived(const Hello &hello) : Base(hello) {}
};

int main()
{
    Hello hello;
    Derived d(hello);
    return 0;
}
</code>```

The resulting print is:

```<code>Hello world!
Hello world!
</code>```

Why this happens?

答:
It is called when default-constructing the hello member of Base (before the this->hello = hello; assignment).

Use a member initializer list to avoid this (i.e. to copy-construct the hello member directly from the parameter hello):

```<code>Base(const Hello &hello) : hello(hello) { }
</code>```

Title: Why this constructor is called twice?

Body:
I have this code:

// Example program
#include <iostream>
#include <string>

class Hello{
    public:
    Hello(){std::cout<<"Hello world!"<<std::endl;}
};

class Base{
    public:
    Base(const Hello &hello){ this->hello = hello;}
    private:
    Hello hello;
};

class Derived : public Base{
    public:
    Derived(const Hello &hello) : Base(hello) {}
};

int main()
{
    Hello hello;
    Derived d(hello);
    return 0;
}

The resulting print is:

Hello world!
Hello world!

Why this happens?

Body:
It is called when default-constructing the hello member of Base (before the this->hello = hello; assignment).

Use a member initializer list to avoid this (i.e. to copy-construct the hello member directly from the parameter hello):

Base(const Hello &hello) : hello(hello) { }


问:
batch file to copy newest file, then delete the original file
I'm trying to create a batch file that finds the newest file in a directory, copies it to a new directory, then deletes the original. Everything works except for the delete portion. Here's what I have. Any help would be greatly appreciated. </p>

```<code>@echo off
set source="C:\BLEND2\Results\LCBlend"
set target="z:\Blenders"
set NewestFile=

FOR /F "delims=" %%I IN ('DIR %source%\*.* /A:-D /O:-D /B')
DO set NewestFile=%%I
COPY %source%\"%NewestFile%" %target%
del %source%\%NewestFile%
</code>```

答:
Your DO needs to be on the same line as your closing parenthesis, also your code will retrieve the oldest file not the newest.

Try this altered version which uses Move instead of Copy followed by Delete:

@Echo Off
Set "source=C:\BLEND2\Results\LCBlend"
Set "target=Z:\Blenders"

For /F "Delims=" %%A In ('Dir/B/A-D/OD "%source%"') Do Set "NewestFile=%%A"
Move "%source%\%NewestFile%" "%target%"
```

Body:
I'm trying to create a batch file that finds the newest file in a directory, copies it to a new directory, then deletes the original. Everything works except for the delete portion. Here's what I have. Any help would be greatly appreciated.

@echo off
set source="C:\BLEND2\Results\LCBlend"
set target="z:\Blenders"
set NewestFile=

FOR /F "delims=" %%I IN ('DIR %source%\*.* /A:-D /O:-D /B')
DO set NewestFile=%%I
COPY %source%\"%NewestFile%" %target%
del %source%\%NewestFile%


问:
C++ code refusing to run script
I am running the following code based on this answer: C: read only last line of a file. No loops

```<code> #include <arpa/inet.h>

 #include <netdb.h>
 #include <netinet/in.h>
 #include <unistd.h>
 #include <iostream>
 #include <cstring>
 #include <stdlib.h>
 #include <stdio.h>

 main(){
 string answer= "Nothing, actually"
 FILE* fd;
 if ((fd = fopen("result.txt", "r")) != NULL);
 static const long max_len = 55 + 1;
 char buf[max_len + 1];
 fseek(fd, -max_len, SEEK_END);
 ssize_t len = fread(fd, buf, max_len);
 buf[len] = '\0';
 char *last_newline = strrchr(buf, '\n');
 char *last_line = last_newline+1;
 answer= last_line;}
</code>```

When I compile it via my makefile I get back:

tcp-server.cc:111:42: error: invalid conversion from ‘char*’ to ‘size_t {aka long unsigned int}’ [-fpermissive]
        ssize_t len = fread(fd, buf, max_len);
                                            ^
  tcp-server.cc:111:42: error: too few arguments to function ‘size_t fread(void*, size_t, size_t, FILE*)’

I just want it to read the last line of a file. Have no idea why this is difficult or why I am getting the error. Edited to show update made after a comment that did fix one error, but not the current two.

答:
You have numerous bugs. Here are a few/the first ones I've noticed:

"if ((fd = fopen("result.txt", "r")) != NULL);" makes no sense; you probably wanted to do something in case the condition was true/false, not just end the statement with ; there.

"static const long max_len = 55 + 1;" there's absolutely no reason for that static.

main always returns int - you can't have main with no return value.

std::fread takes 4 arguments but you are only passing it 3 (which btw is actually the error you mention in your question).

" string answer= ..." should be "std::string answer= ...".

Btw: this all looks like (pretty bad) C. Why are you tagging it as C++ (except for the use of string this has nothing to do with modern idiomatic C++)?

The best advice I can give you is: 1) turn on all compiler warnings and take them seriously. 2) buy and read a good C++ book.

Title: C++ code refusing to run script

Body:
I am running the following code based on this answer: C: read only last line of a file. No loops

 #include <arpa/inet.h>

 #include <netdb.h>
 #include <netinet/in.h>
 #include <unistd.h>
 #include <iostream>
 #include <cstring>
 #include <stdlib.h>
 #include <stdio.h>

 main(){
 string answer= "Nothing, actually"
 FILE* fd;
 if ((fd = fopen("result.txt", "r")) != NULL);
 static const long max_len = 55 + 1;
 char buf[max_len + 1];
 fseek(fd, -max_len, SEEK_END);
 ssize_t len = fread(fd, buf, max_len);
 buf[len] = '\0';
 char *last_newline = strrchr(buf, '\n');
 char *last_line = last_newline+1;
 answer= last_line;}

When I compile it via my makefile I get back:

tcp-server.cc:111:42: error: invalid conversion from ‘char*’ to ‘size_t {aka long unsigned int}’ [-fpermissive]
        ssize_t len = fread(fd, buf, max_len);
                                            ^
  tcp-server.cc:111:42: error: too few arguments to function ‘size_t fread(void*, size_t, size_t, FILE*)’

I just want it to read the last line of a file. Have no idea why this is difficult or why I am getting the error. Edited to show update made after a comment that did fix one error, but not the current two.


问:
C++ - Splitting Filename and File Extension
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

```<code>void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}
</code>```

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.

答: There is no way of doing what you want that does not involve a database of extensions for your purpose. There's nothing magical about extensions, they are just part of a filename (if you gunzip foo.tar.gz you'll likely get a foo.tar, so for this application .gz actually is "the extension"). So, in order to do what you want, build a database of extensions that you want to look for and fall back on "last dot" if you don't find one.

Body:
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.


问:
Swift 3.0 Passing data among view controller
I'm using Xcode Swift 3.0, I have 5 view controllers, each controller have several textField. Once the information finish filled, press nextButton to next view controller. For example, finish fill in all textField in view controller 1, click nextButton and I will segue it to view controller 2, and so on.....

I want to get view controller 1,2,3,4 entered textField information only from view controller 5.

How am I gonna to do that without using Segue to pass data from vc1 to vc2, and from vc2 to vc3 and so on?

Please advice.

答:
How am I gonna to do that without using Segue to pass data from vc1 to vc2, and from vc2 to vc3 and so on?

No matter whether you're using Swift or Objective-C, the right solution here is to use a data model. Each view controller gets a reference to a common data model from the object that creates it, and the view controller uses the model to populate its views. The view controller updates the model as the user makes changes. Since the other view controllers also refer to the same model, they all automatically get the user's changes.


问:
Get a word broken into syllables and separated by hyphens, without displaying it as
I would like to get a string, of a word broken into one or more syllables, and if more than one, with hyphens, in-between, too.

For example: I would like to get Floccinaucinihilipil-ification out of Floccinaucinihilipilification.

Current browsers are able to break them by hyphens already, grammatical correct.

The reason: I would like to show a term like it would have been shown in a dictionary. Therefor the easiest thing would be to get access to how the browser would break it, but show it in one single line.

In other words: Is there any way to get access to a word as it would be shown to an user agent if there is enough space to show at least the narrowest syllables?

答:
It's possible, if a bit tedious, to determine where the word wraps are located in the document. But you're also depending on the browser having a hyphenation dictionary, which can depend on the platform and possibly the user's language.

Here's one approach, which works in Firefox. I couldn't get Chrome or WebKit to reliably hyphenate the word at every possible spot, and it simply gave up hyphenating below a certain width.

testbed.innerHTML = testbed.innerHTML.replace(/./g, '$&');
outer = testbed.getBoundingClientRect();
match = [...testbed.querySelectorAll('span:not(:first-child)')].filter(e => e.getBoundingClientRect().x == outer.x);
match.forEach(e => e.classList.toggle('match', true));
output = [...testbed.children].map(e => (e.classList.contains('match') ? '-' : '') + e.textContent).join('');
console.log(output);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div#testbed {
  width: 0;
  hyphens: auto;
}
span.match {
  background: magenta;
}</code>```

Floccinaucinihilipilification
```

Body:
It's possible, if a bit tedious, to determine where the word wraps are located in the document. But you're also depending on the browser having a hyphenation dictionary, which can depend on the platform and possibly the user's language.

Here's one approach, which works in Firefox. I couldn't get Chrome or WebKit to reliably hyphenate the word at every possible spot, and it simply gave up hyphenating below a certain width.

testbed.innerHTML = testbed.innerHTML.replace(/./g, '<span>$&</span>');
outer = testbed.getBoundingClientRect();
match = [...testbed.querySelectorAll('span:not(:first-child)')].filter(e => e.getBoundingClientRect().x == outer.x);
match.forEach(e => e.classList.toggle('match', true));
output = [...testbed.children].map(e => (e.classList.contains('match') ? '-' : '') + e.textContent).join('');
console.log(output);

div#testbed {
  width: 0;
  hyphens: auto;
}
span.match {
  background: magenta;
}

<div id=testbed lang=en>Floccinaucinihilipilification</div>


问:
How to assign client-id to a particular Kafka Producer or Topic?
I know that quotas are based on client-id. Basically I want to run the kafka-producer-perf-test with a particular client id to test whether the quotas work properly.

How can I assign a client-id for a particular producer (or) partition?

答:
You can use ProducerRecord to specify which partition you want to send message. Say partition 0. Create KafkaConsumer and assign consumer to specific partition (in this case partition 0). This will ensure, producer and consumer (with given client-id) both are working on same partition id of topic.

ProducerRecord(java.lang.String topic, ava.lang.Integer partition, K key, V value)
```
<p>Produce message to partition 0</p>
<pre class="lang-java prettyprint-override"><code>ProducerRecord<byte[],byte[]> record = new ProducerRecord<byte[],byte[]>("PerftestTopic", 0, key, value)
producer.send(record);
</code>```

Consumer to read from specific partition

TopicPartition partition0 = new TopicPartition("PerftestTopic", 0);
consumer.assign(Arrays.asList(partition0));
```

Body:
You can use ProducerRecord to specify which partition you want to send message. Say partition 0. Create KafkaConsumer and assign consumer to specific partition (in this case partition 0). This will ensure, producer and consumer (with given client-id) both are working on same partition id of topic.

ProducerRecord(java.lang.String topic, ava.lang.Integer partition, K key, V value)

Produce message to partition 0

ProducerRecord<byte[],byte[]> record = new ProducerRecord<byte[],byte[]>("PerftestTopic", 0, key, value)
producer.send(record);

Consumer to read from specific partition

TopicPartition partition0 = new TopicPartition("PerftestTopic", 0);
consumer.assign(Arrays.asList(partition0));


问:
Filtering JSON data in jQuery or vanilla JavaScript
I want to filter my JSON-object in jQuery or vanilla JavaScript. I prefer vanilla JavaScript but don't know how to solve this. I have created pseudo-code in order to explain what I want to achieve. Any ideas?

I basically want to only allow records that don't contain values from the lists. The first list only contains mfs values that should be excluded from expJSON. Second list contains pn values that should be excluded from expJSON, and so on...

Pseude-code

```<code>var results = $(jsonData).filter(function (i, n) {
        return if list1 is not empty: (n.psn.indexOf(item1 from list1) === -1 || n.psn.indexOf(item2 from list1) === -1 || n.psn.indexOf(item3 from list1) === -1 ... ) &&
        if list2 is not empty: (n.pn.indexOf(item1 from list2) === -1 || n.pn.indexOf(item2 from list2) === -1 || n.pn.indexOf(item3 from list2) === -1 ... ) &&
        if list3 is not empty: (n.mft.indexOf(item1 from list3) === -1 || n.mft.indexOf(item2 from list3) === -1 || n.mft.indexOf(item3 from list3) === -1 ... ) &&
        if list4 is not empty: (n.sl.indexOf(item1 from list4) === -1 || n.sl.indexOf(item2 from list4) === -1 || n.sl.indexOf(item3 from list4) === -1 ... ) &&
        if list5 is not empty: (n.vtv.indexOf(item1 from list5) === -1 || n.vtv.indexOf(item2 from list5) === -1 || n.vtv.indexOf(item3 from list5) === -1 ... )
    })
</code>```

jsonData

```<code>[{"mft": "asjfasdf", "pn": "234awefwa", "vtv": "No", "psn": "234fasdfa", "sl": "asf8sf"}, {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"}, {"mft": "fbsdf8df", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"}, {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"} ...]
</code>```

list1, list2, list3, list4, list5

```<code>              item1     item2    item3
list1/mft = ["word1", "word2", "word3", ...]
list2/pn = ["word1", "word2", "word3", ...]
list3/vtv = ["word1", "word2", "word3", ...]
list4/psn = ["word1", "word2", "word3", ...]
list5/sl = ["word1", "word2", "word3", ...]
</code>```

答:
I'm guessing you mean something like the following?

I just simply used Array.filter to file through each Object in the JSON Object. Then a simple switch statement within a for loop for each item in the object in order to "filter" them into the proper list.

Update! After further review of your question and what you asked in comments, I believe what you're seeking is something more like the following. I changed the loop to instead only allow objects to return where said sub items cannot be found in given list. Hope this is what you're seeking! Good Luck!

var expJSON = [{"mft": "asjfasdf", "pn": "234awefwa", "vtv": "No", "psn": "234fasdfa", "sl": "asf8sf"}, {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"}, {"mft": "fbsdf8df", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"}, {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"}];
function filterOutOfMainList(obj, ind, $this) {
  for (var x in obj) switch(x) {
    case 'mft':
      if (list1.indexOf(obj[x]) > -1) return;
      break;
    case 'pn':
      if (list2.indexOf(obj[x]) > -1) return;
      break;
    case 'vtv':
      if (list3.indexOf(obj[x]) > -1) return;
      break;
    case 'psn':
      if (list4.indexOf(obj[x]) > -1) return;
      break;
    case 'sl':
      if (list5.indexOf(obj[x]) > -1) return;
      break;
  }
  return obj;
}
var list1 = ["example->", "fsjldfd98sf9d"], //  mft
  list2 = ["word1", "word2", "etc"], //  pn
  list3 = ["Yes"], //  vtv
  list4 = ["word1", "word2", "etc"], //  psn
  list5 = ["word1", "word2", "etc"]; //  sl
console.log(expJSON.filter(filterOutOfMainList));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Using your JSON as example. Vanilla!</h1></code>```

Body:
I want to filter my JSON-object in jQuery or vanilla JavaScript. I prefer vanilla JavaScript but don't know how to solve this. I have created pseudo-code in order to explain what I want to achieve. Any ideas?

I basically want to only allow records that don't contain values from the lists. The first list only contains mfs values that should be excluded from expJSON. Second list contains pn values that should be excluded from expJSON, and so on...

Pseude-code

var results = $(jsonData).filter(function (i, n) {
        return if list1 is not empty: (n.psn.indexOf(item1 from list1) === -1 || n.psn.indexOf(item2 from list1) === -1 || n.psn.indexOf(item3 from list1) === -1 ... ) &&
        if list2 is not empty: (n.pn.indexOf(item1 from list2) === -1 || n.pn.indexOf(item2 from list2) === -1 || n.pn.indexOf(item3 from list2) === -1 ... ) &&
        if list3 is not empty: (n.mft.indexOf(item1 from list3) === -1 || n.mft.indexOf(item2 from list3) === -1 || n.mft.indexOf(item3 from list3) === -1 ... ) &&
        if list4 is not empty: (n.sl.indexOf(item1 from list4) === -1 || n.sl.indexOf(item2 from list4) === -1 || n.sl.indexOf(item3 from list4) === -1 ... ) &&
        if list5 is not empty: (n.vtv.indexOf(item1 from list5) === -1 || n.vtv.indexOf(item2 from list5) === -1 || n.vtv.indexOf(item3 from list5) === -1 ... )
    })

jsonData

[{"mft": "asjfasdf", "pn": "234awefwa", "vtv": "No", "psn": "234fasdfa", "sl": "asf8sf"}, {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"}, {"mft": "fbsdf8df", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"}, {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"} ...]

list1, list2, list3, list4, list5

              item1     item2    item3
list1/mft = ["word1", "word2", "word3", ...]
list2/pn = ["word1", "word2", "word3", ...]
list3/vtv = ["word1", "word2", "word3", ...]
list4/psn = ["word1", "word2", "word3", ...]
list5/sl = ["word1", "word2", "word3", ...]

Body:
I'm guessing you mean something like the following?

I just simply used Array.filter to file through each Object in the JSON Object. Then a simple switch statement within a for loop for each item in the object in order to "filter" them into the proper list.

Update! After further review of your question and what you asked in comments, I believe what you're seeking is something more like the following. I changed the loop to instead only allow objects to return where said sub items cannot be found in given list. Hope this is what you're seeking! Good Luck!

var expJSON = [{"mft": "asjfasdf", "pn": "234awefwa", "vtv": "No", "psn": "234fasdfa", "sl": "asf8sf"}, {"mft": "fsjldfd98sf9d", "pn": "skfjsdf7df", "vtv": "Yes", "psn": "tfs76fdfd", "sl": "basd7f"}, {"mft": "fbsdf8df", "pn": "898723923", "vtv": "No", "psn": "fs7daf6sd", "sl": "f7s6df"}, {"mft": "sdf7688sdf76f", "pn": "131d21", "vtv": "Yes", "psn": "t23yt342y23", "sl": "bfldk34"}];
function filterOutOfMainList(obj, ind, $this) {
  for (var x in obj) switch(x) {
    case 'mft':
      if (list1.indexOf(obj[x]) > -1) return;
      break;
    case 'pn':
      if (list2.indexOf(obj[x]) > -1) return;
      break;
    case 'vtv':
      if (list3.indexOf(obj[x]) > -1) return;
      break;
    case 'psn':
      if (list4.indexOf(obj[x]) > -1) return;
      break;
    case 'sl':
      if (list5.indexOf(obj[x]) > -1) return;
      break;
  }
  return obj;
}
var list1 = ["example->", "fsjldfd98sf9d"], //  mft
  list2 = ["word1", "word2", "etc"], //  pn
  list3 = ["Yes"], //  vtv
  list4 = ["word1", "word2", "etc"], //  psn
  list5 = ["word1", "word2", "etc"]; //  sl
console.log(expJSON.filter(filterOutOfMainList));

<h1>Using your JSON as example. Vanilla!</h1>


问:
jQuery filter to select first two and then next two
I have the following list:

```<code><li class="list one" data-number="2"></li>
<li class="list one" data-number="2"></li>
<li class="list two" data-number="3"></li>
<li class="list two" data-number="7"></li>
</code>```

And I need to pass each value from data-number attribute to a variable based on the list class.

I have these functions for that:

```<code>var list_one = 0;
var list_two = 0;

$(".one").each(function (i, val) {
  var number = $(this).data('number')
  list_one = list_one + parseInt(number); // Gives 4
});

$(".two").each(function (i, val) {
  var number = $(this).data('number')
  list_two = list_two + parseInt(number); // Gives 10
});
</code>```

But as the list grows, this becomes a long and messy code. What's the best way to get the values from the first two li, and then the two next, etc and pass the sum to the variable?

The list will always have this structure, so I don't need to concider that the number of lis with each class will vary.

答:
You can obtain an object of summed values:

var result = {};

$('.list').each(function(idx, ele) {
    var key = ele.classList.toString().replace(/ /g,  '_');
    result[key] = (+result[key] || 0) +  +ele.dataset["number"];
});

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
    <li class="list one" data-number="2">one</li>
    <li class="list one" data-number="2">one</li>
    <li class="list two" data-number="3">two</li>
    <li class="list two" data-number="7">tow</li>
</ul></code>```

Body:
I have the following list:

And I need to pass each value from data-number attribute to a variable based on the list class.

I have these functions for that:

var list_one = 0;
var list_two = 0;

$(".one").each(function (i, val) {
  var number = $(this).data('number')
  list_one = list_one + parseInt(number); // Gives 4
});

$(".two").each(function (i, val) {
  var number = $(this).data('number')
  list_two = list_two + parseInt(number); // Gives 10
});

But as the list grows, this becomes a long and messy code. What's the best way to get the values from the first two li, and then the two next, etc and pass the sum to the variable?

The list will always have this structure, so I don't need to concider that the number of lis with each class will vary.

Body:
You can obtain an object of summed values:

var result = {};

$('.list').each(function(idx, ele) {
    var key = ele.classList.toString().replace(/ /g,  '_');
    result[key] = (+result[key] || 0) +  +ele.dataset["number"];
});

console.log(result);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
    <li class="list one" data-number="2">one</li>
    <li class="list one" data-number="2">one</li>
    <li class="list two" data-number="3">two</li>
    <li class="list two" data-number="7">tow</li>
</ul>