问:
How to call controller function from javascript
Creating a web app using mvc and codeigniter. In the view, on the click of a button it calls a javascript method. This method should take the source of 3 images as parameters, and pass them to a controller method. The controller method then turns them into a single $record and passes it to a function in the model, which will then insert the record contents into a database.

View button:

```<code><input type="submit" class="btn btn-primary" value="Assemble bot" onclick="insertAssembled()"></input>
</code>```

Javascript function:

```<code>function assemble(var head, var body, var legs) {
    var head = document.getElementById("HeadImage".src);
    var body = document.getElementById("BodyImage".src);
    var legs = document.getElementById("FeetImage".src);
    // call controller function here, passing head body and legs
}
</code>```

Controller method:

```<code>    public function insertAssembled($head, $body, $legs) {
        //Build record and send to saveBot
        $record['id'] = 1;
        $record['head'] = $head;
        $record['body'] = $body;
        $record['legs'] = $legs;
        $this->Robotsdata->saveBot($record);
   }
</code>```

Model method (very rough, help not needed just trying to pass parameters):

```<code>public function saveBot($record) {
    $con = mysql_connect("localhost","root@localhost","");
    mysql_select_db("factory", $con);
    $bot_id = $_POST['id'];
    $bot_head = $_POST['head'];
    $bot_body = $_POST['body'];
    $bot_legs = $_POST['legs'];
    $query = "INSERT INTO `factory`.`assembledbots` ('id', 'head', 'body', 'legs') "
            . "VALUES ('$bot_id', '$bot_head', '$bot_body', '$bot_legs');";
    mysql_query($query);
    mysql_close($con);
}
</code>```

答:
You can achieve this by using ajax. Also, in your model, try using CI's Query Builder Class (Active Record) so your queries are safe and to avoid SQL injections.

javascript

```<code>function assemble(var head, var body, var legs) {
   var head = document.getElementById("HeadImage".src);
   var body = document.getElementById("BodyImage".src);
   var legs = document.getElementById("FeetImage".src);

   //ajax
   //you post variables
   var fields = {
      head  : head,
      body  : body,
      legs  : legs,
      submit_a: true
   };

   $.ajax({
     url: 'domain/controller/insertAssembled',
     type: 'POST',
     data: fields,
     dataType:'JSON',
     success: function(result){
        console.log(result);
     }
   });
}
</code>```

controller

```<code>public function insertAssembled()
{

  if ($this->input->is_ajax_request()) { // just additional, to make sure request is from ajax
    if ($this->input->post('submit_a')) {
        $record['id'] = 1;
        $record['head'] = $this->input->post('head');
        $record['body'] = $this->input->post('body');
        $record['legs'] = $this->input->post('legs');

        // to model
        $this->Robotsdata->saveBot($record);

        // return to view
        echo json_encode(array("error"=>false));
        return false;
    }
  }
}
</code>```

model

```<code>public function saveBot($record)
{
  if ($record) {

    $save_fields = array(
        'id'   => $record['id'],
        'head' => $record['head'],
        'body' => $record['body'],
        'legs' => $record['legs']
    );
    $this->db->insert('table_name', $save_fields);

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

Body:
Creating a web app using mvc and codeigniter. In the view, on the click of a button it calls a javascript method. This method should take the source of 3 images as parameters, and pass them to a controller method. The controller method then turns them into a single $record and passes it to a function in the model, which will then insert the record contents into a database.

View button:

<input type="submit" class="btn btn-primary" value="Assemble bot" onclick="insertAssembled()"></input>

Javascript function:

function assemble(var head, var body, var legs) {
    var head = document.getElementById("HeadImage".src);
    var body = document.getElementById("BodyImage".src);
    var legs = document.getElementById("FeetImage".src);
    // call controller function here, passing head body and legs
}

Controller method:

    public function insertAssembled($head, $body, $legs) {
        //Build record and send to saveBot
        $record['id'] = 1;
        $record['head'] = $head;
        $record['body'] = $body;
        $record['legs'] = $legs;
        $this->Robotsdata->saveBot($record);
   }

Model method (very rough, help not needed just trying to pass parameters):

public function saveBot($record) {
    $con = mysql_connect("localhost","root@localhost","");
    mysql_select_db("factory", $con);
    $bot_id = $_POST['id'];
    $bot_head = $_POST['head'];
    $bot_body = $_POST['body'];
    $bot_legs = $_POST['legs'];
    $query = "INSERT INTO `factory`.`assembledbots` ('id', 'head', 'body', 'legs') "
            . "VALUES ('$bot_id', '$bot_head', '$bot_body', '$bot_legs');";
    mysql_query($query);
    mysql_close($con);
}

Body:
You can achieve this by using ajax. Also, in your model, try using CI's Query Builder Class (Active Record) so your queries are safe and to avoid SQL injections.

javascript

function assemble(var head, var body, var legs) {
   var head = document.getElementById("HeadImage".src);
   var body = document.getElementById("BodyImage".src);
   var legs = document.getElementById("FeetImage".src);

   //ajax
   //you post variables
   var fields = {
      head  : head,
      body  : body,
      legs  : legs,
      submit_a: true
   };

   $.ajax({
     url: 'domain/controller/insertAssembled',
     type: 'POST',
     data: fields,
     dataType:'JSON',
     success: function(result){
        console.log(result);
     }
   });
}

controller

public function insertAssembled()
{

  if ($this->input->is_ajax_request()) { // just additional, to make sure request is from ajax
    if ($this->input->post('submit_a')) {
        $record['id'] = 1;
        $record['head'] = $this->input->post('head');
        $record['body'] = $this->input->post('body');
        $record['legs'] = $this->input->post('legs');

        // to model
        $this->Robotsdata->saveBot($record);

        // return to view
        echo json_encode(array("error"=>false));
        return false;
    }
  }
}

model

public function saveBot($record)
{
  if ($record) {

    $save_fields = array(
        'id'   => $record['id'],
        'head' => $record['head'],
        'body' => $record['body'],
        'legs' => $record['legs']
    );
    $this->db->insert('table_name', $save_fields);

    return true;
  }
  return false;
}


来源: stackexchange

问:
Using a running total for calculator
I made a calculator on android. I get results for only two numbers (1+1), but I would like to be able to do more then one calculation at a time instead of hitting enter every time I need a new answer (1+1-2).

Something like this: 2 + 2 (new operator pressed) 4 + 3 (equals is pressed) 7

But I'm not sure how to implement this on my code.

This is the button code for every operator:

```<code>btnPlus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            perform();
            operation = "+";
        }
    }); // end btnPlus
</code>```

This is my calculation method:

```<code>private void calculate() {

    if (operation == null) {
        numberInput.setText(null);

    } else if (operation.equals("+")){
        numResult = (secondNum + firstNum);
        numberInput.setText(String.valueOf(numResult));

    } else if (operation.equals("-")) {
        numResult = (secondNum - firstNum);
        numberInput.setText(String.valueOf(numResult));

    } else if (operation.equals("/")) {
        numResult = (secondNum / firstNum);
        numberInput.setText(String.valueOf(numResult));

    } else if (operation.equals("*")) {
        numResult = (secondNum * firstNum);
        numberInput.setText(String.valueOf(numResult));
    } // end if statement

}
</code>```

Also, perform if needed:

```<code>private void perform() {
    str = "";
    secondNum = firstNum;
}
</code>```

答:
A quick way to solve your problem given your current code is to use textChangeListener/TextWatcher(assuming you have an EditText or TextView) to detect every time an operator is entered then call the operate function. It would look something like this.

```<code>myEditText.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {}

    public void beforeTextChanged(CharSequence s, int start,
       int count, int after) {
    }

    public void onTextChanged(CharSequence s, int start,
      int before, int count) {
      // if 2nd operator is detected
      // call calculate
      // append 2nd operator
    }
</code>```

});

ContentLicense: CC BY-SA 3.0

Title: Using a running total for calculator

Body:
I made a calculator on android. I get results for only two numbers (1+1), but I would like to be able to do more then one calculation at a time instead of hitting enter every time I need a new answer (1+1-2).

Something like this: 2 + 2 (new operator pressed) 4 + 3 (equals is pressed) 7

But I'm not sure how to implement this on my code.

This is the button code for every operator:

btnPlus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            perform();
            operation = "+";
        }
    }); // end btnPlus

This is my calculation method:

private void calculate() {

    if (operation == null) {
        numberInput.setText(null);

    } else if (operation.equals("+")){
        numResult = (secondNum + firstNum);
        numberInput.setText(String.valueOf(numResult));

    } else if (operation.equals("-")) {
        numResult = (secondNum - firstNum);
        numberInput.setText(String.valueOf(numResult));

    } else if (operation.equals("/")) {
        numResult = (secondNum / firstNum);
        numberInput.setText(String.valueOf(numResult));

    } else if (operation.equals("*")) {
        numResult = (secondNum * firstNum);
        numberInput.setText(String.valueOf(numResult));
    } // end if statement

}

Also, perform if needed:

private void perform() {
    str = "";
    secondNum = firstNum;
}

Body:
A quick way to solve your problem given your current code is to use textChangeListener/TextWatcher(assuming you have an EditText or TextView) to detect every time an operator is entered then call the operate function. It would look something like this.

myEditText.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {}

    public void beforeTextChanged(CharSequence s, int start,
       int count, int after) {
    }

    public void onTextChanged(CharSequence s, int start,
      int before, int count) {
      // if 2nd operator is detected
      // call calculate
      // append 2nd operator
    }

});


问:
Running Product based on another column
I need to create a "running product" column in Excel. However, the running product is based on another column, a "group". Consider the example below.

Here, Column A is my group, and each group has multiple items in it (column B). Column C is what I need a running product on, and Column D is the output column. Cell D2 is 0.2 because it is the first item in group 0. Cell D3 is 0.02 since it is the product of item 0 and item 1 in group 0. This continues until we get to group 1, which is when the running product "resets" and starts applying the running product only to group 1, so on and so forth.

I'd like to do this with an formula, and not VBA if possible.

答:
Use the following IF function:

=IF(B2=0,C2,D1*C2)

Title: Running Product based on another column


问:
Would the size or number of installed packages affect server performance
As I'm learning, I'm seeing many developers use a large variety of packages in an app. I'm sure much of the functionality of these packages aren't needed in the app.

Would too many packages slow server performance in a similar way that multiple javascript libraries would on the client side? Is this a smaller or non-issue since the packages aren't being downloaded on each new visit?

答:
Just because a module is installed on the file system in node_modules doesn't mean that any of the code from the entry point of your application actually require/imports it.

The modules get loaded in as they are imported, which is usually pretty much all of them at the beginning, although you can make some modules load dynamically in only certain circumstances if you want.

No, of course the packages aren't being reloaded on each request.  The Node server stays running until it crashes or you stop it.  Each request is handled by the same running server, with the same set of modules already loaded unless a request causes it to load a new module, which is unusual.  What would affect the performance of the server would usually not be the amount of modules or size on disk, but the actual activities that those modules are performing.  For many applications, most of the modules do nothing until they are used while serving a request, so having 100 modules loaded into memory or 10, they are still doing nothing if there is no request.

More modules will use more memory at runtime.  If you have many loaded, this could theoretically use up the memory on a very small server, which would kill the performance.  But it would have to be a server with very little resources.

If you create an application where even 1 module is busy doing some CPU intensive processing, or 1 module is doing a synchronous IO task, or one module is thrashing memory by causing lots of garbage collection, then that will block the application from processing requests efficiently since its single threaded.  But this is an issue you will have if you have even one module misbehaving like that, and isn't about having lots of modules being used/loaded by your application.  The vast majority of modules provide small bits of functionality that isn't synchronous or CPU-intensive, so having lots of them doesn't really increase your chances of having a misbehaving module.

It can take a few minutes to install lots of dependency modules, however.  But this usually isn't a problem if you use newer versions of npm and stay away from underpowered servers like AWS's 'free' tiny EC2 instances.


问:
Creating an Asana Task using a POST http request
I'm trying to use the asana-api to create a Task using a POST http request but I keep getting a 400 bad request as a response.

I managed to get data from the Asana-api using ( a GET request ), but I'm having trouble sending data to Asana with ( a POST request )

I'm using the 'request' module to do the api call

here's the error message :

```<code>`{"errors":[{
      "message":"Could not parse request data,invalid JSON",
      "help":"For more information on API status codes and how to handle them,
      read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}
 ]}`
</code>```

Here's my code:

```<code>testTask(){
   var taskName = "Test Name for a Test Task"
   var workspaceID = "123456789"
   var projectID = "123456789"
   var assigneeID = "123456789"
   var parentID = null
   this.createTask(taskName, workspaceID, projectID, assigneeID, parentID)
}

createTask(taskName, workspaceID, projectID, assigneeID, parentID){
    var token = "0/1234abcd5678efgh9102ijk"
    var bearerToken = "Bearer " + token
    var task = {
       data: {
         assignee: "me",
         notes: "test test test test",
         workspace: workspaceID,
         name: taskName,
         projects: [projectID],
         parent: parentID
       }
     }
     var options = {
       "method" : "POST",
       "headers" : {"Authorization": bearerToken},
       "contentType": "application/json",
       "payload" : JSON.stringify(task)
     }
     try {
       var url = "https://app.asana.com/api/1.0/tasks";
       request.post(url, options, function optionalCallback(err, httpResponse, body) {
       if (err) {
          return console.error('upload failed:', err);
       }
          console.log('Upload successful!  Server responded with:', body);
       });
     }
     catch (e) {
          console.log(e);
     }

}
</code>```

I also tried a different implementation :

```<code>  createTask(){
    var token = "0/1234abcd5678efgh9102ijk"
    var bearerToken = "Bearer " + token

     var options = {
       "method" : "POST",
       "headers" : {"Authorization": bearerToken},
     }
     try {
       request.post("https://app.asana.com/api/1.0/tasks?workspace=1234567&projects=765534432&parent=null&name=taskName&assignee=me", options, function optionalCallback(err, httpResponse, body) {
       if (err) {
          return console.error('upload failed:', err);
       }
          console.log('Upload successful!  Server responded with:', body);
       });
     }
     catch (e) {
          console.log(e);
     }

}
</code>```

答: Based on the examples provided by the request module, it appears that your options object uses payload as a key, but it should be body.

Body:
I'm trying to use the asana-api to create a Task using a POST http request but I keep getting a 400 bad request as a response.

I managed to get data from the Asana-api using ( a GET request ), but I'm having trouble sending data to Asana with ( a POST request )

I'm using the 'request' module to do the api call

here's the error message :

`{"errors":[{
      "message":"Could not parse request data,invalid JSON",
      "help":"For more information on API status codes and how to handle them,
      read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}
 ]}`

Here's my code:

testTask(){
   var taskName = "Test Name for a Test Task"
   var workspaceID = "123456789"
   var projectID = "123456789"
   var assigneeID = "123456789"
   var parentID = null
   this.createTask(taskName, workspaceID, projectID, assigneeID, parentID)
}

createTask(taskName, workspaceID, projectID, assigneeID, parentID){
    var token = "0/1234abcd5678efgh9102ijk"
    var bearerToken = "Bearer " + token
    var task = {
       data: {
         assignee: "me",
         notes: "test test test test",
         workspace: workspaceID,
         name: taskName,
         projects: [projectID],
         parent: parentID
       }
     }
     var options = {
       "method" : "POST",
       "headers" : {"Authorization": bearerToken},
       "contentType": "application/json",
       "payload" : JSON.stringify(task)
     }
     try {
       var url = "https://app.asana.com/api/1.0/tasks";
       request.post(url, options, function optionalCallback(err, httpResponse, body) {
       if (err) {
          return console.error('upload failed:', err);
       }
          console.log('Upload successful!  Server responded with:', body);
       });
     }
     catch (e) {
          console.log(e);
     }

}

I also tried a different implementation :

  createTask(){
    var token = "0/1234abcd5678efgh9102ijk"
    var bearerToken = "Bearer " + token

     var options = {
       "method" : "POST",
       "headers" : {"Authorization": bearerToken},
     }
     try {
       request.post("https://app.asana.com/api/1.0/tasks?workspace=1234567&projects=765534432&parent=null&name=taskName&assignee=me", options, function optionalCallback(err, httpResponse, body) {
       if (err) {
          return console.error('upload failed:', err);
       }
          console.log('Upload successful!  Server responded with:', body);
       });
     }
     catch (e) {
          console.log(e);
     }

}


问:
Code will only return 0.0, 0.0 GPS coordinate while throwing NullPointerException
This is my n-th try with the Android Location API, and I just can't seem to get it to work properly. This tutorial seems like the most promising, but I can only seem to get this code to return a GPS coordinate of 0.0, 0.0 which isn't very useful...

There seems to be a clue in that getLocation() returns a java.lang.NullPointerException error, but I'm not sure where I should even start looking for it.

Here's the error:

```<code> W/System.err: java.lang.NullPointerException
 W/System.err:     at android.content.ContextWrapper.checkPermission(ContextWrapper.java:557)
</code>```

I tried making a new permissions block, pasted at the bottom, but it just gave the same error.

Can anyone please point me in the right direction here?

The code is split over two class-files: MainActivity.java and GPSTracker.java.

GPSTracker.java

```<code>    package com.tutorial.android.location.api;

// http://www.androidhive.xyz/2016/07/android-gps-location-manager-tutorial.html
// with some modifications, especially for new permissions

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {
    private String TAG = "¤¤";
    private final Context mContext;

    public GPSTracker(Context mContext) {
        this.mContext = mContext;
        this.getLocation();
    }

    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    Location location;
    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10; // 10 meters
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 30 sec

    protected LocationManager locationManager;

    public Location getLocation() {
        try {

            if(locationManager == null) {
                locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            }
            if(isGPSEnabled != true) {
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            }
            if(isNetworkEnabled != true) {
                isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            }

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no provider enabled :p
                Log.e(TAG, "getLocation() no provider :(");
            } else {
                this.canGetLocation = true;
                // get network location
                if (isNetworkEnabled) {
                    // permission block:
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        // return TODO;
                    } else {
                        Log.e(TAG, "getLocation() permission DENIED");
                    }
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                    if(locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if(location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // get GPS location
                if(isGPSEnabled) {
                    if(location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                        Log.d(TAG, "getLocation() GPS Enabled");
                        if(locationManager != null){
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if(location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getLocation() ERROR...: " + e);
            e.printStackTrace();
        }
        return location;
    }

    public double getLatitude() {
        if(location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }

    public double getLongitude() {
        if(location != null) {
            longitude = location.getLongitude();
        }
        return longitude;
    }

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

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        // GPS is ON
        Log.d(TAG, "GPS is ON");
    }

    @Override
    public void onProviderDisabled(String provider) {
        // GPS is OFF
        Log.d(TAG, "GPS is OFF");
    }

    // GPS dialog
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    // don't really need this when testing
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        alertDialog.setTitle(R.string.gps_settings_title);

        alertDialog.setMessage(R.string.gps_settings_msg);
        alertDialog.setPositiveButton(R.string.gps_settings_word, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivities(new Intent[]{intent}); // hm...
            }
        });
        alertDialog.show();
    }

    public void stopUsingGPS() {
        if(locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
}
</code>```

Rewritten but still not working permissions block in GPSTracker.java:

```<code>int permissionCheck = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if(!(permissionCheck == PackageManager.PERMISSION_GRANTED)) {
    if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, Manifest.permission.ACCESS_FINE_LOCATION)) {
        // explanation :p
        Log.i(TAG, "NOpe...");
    } else {
        // request permission
        Log.d(TAG, "Requestion new permission");
        ActivityCompat.requestPermissions((Activity) mContext, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }
}
</code>```

MainActivity.java

```<code>package com.tutorial.android.location.api;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    String TAG = "¤";

    GPSTracker gps;

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

        gps = new GPSTracker(this);

        if(gps.canGetLocation()) {
            Log.i(TAG, "onCreate() GPS is ON");
            Log.i(TAG, "onCreate() " + gps.getLatitude()+ ", " + gps.getLongitude());
        } else {
            Log.d(TAG, "onCreate() GPS is OFF");
        }

    }
}
</code>```

答:
This tutorial seems like the most promising

It is truly awful code.

I can only seem to get this code to return a GPS coordinate of 0.0, 0.0 which isn't very useful

That is because it will only ever have a location if getLastKnownLocation() happens to return one. It is unlikely to do so.

Rewritten but still not working permissions block in GPSTracker.java:

There are two problems here:

You cannot request permissions from a service.

This is not a real service. The author of this code elected to create a class that extends Service without actually implementing or using the service properly. This is what is causing your NullPointerException, as this is not a properly initialized Context.

Can anyone please point me in the right direction here?

Throw all of this out.

FWIW, here is my sample app for using the LocationManager API.

The recipe is fairly simple:

Step #1: Get a LocationManager by calling getSystemService(Context.LOCATION_SERVICE) on some Context. I happen to do that in a fragment:

```<code>  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    template=getActivity().getString(R.string.url);
    mgr=(LocationManager)getActivity()
      .getSystemService(Context.LOCATION_SERVICE);
  }
</code>```

Step #2: Call requestUpdates(), passing in something that implements LocationListener. In my case, that happens to be the fragment itself:

```<code>  @Override
  @SuppressWarnings({"MissingPermission"})
  public void onStart() {
    super.onStart();

    mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3600000,
      1000, this);
  }
</code>```

Step #3: In onLocationChanged() of your LocationListener, do something with the Location that you get, which in my case is to execute an AsyncTask to get a weather forecast:

```<code>  @Override
  public void onLocationChanged(Location location) {
    new FetchForecastTask().execute(location);
  }
</code>```

Step #4: Call removeUpdates() when you are done:

```<code>  @Override
  @SuppressWarnings({"MissingPermission"})
  public void onStop() {
    mgr.removeUpdates(this);

    super.onStop();
  }
</code>```

And that's it (other than runtime permission stuff, which I abstract out into an AbstractPermissionsActivity).

If you want, use getLastKnownLocation() as an optimization, but do not rely upon it.

Body:
This is my n-th try with the Android Location API, and I just can't seem to get it to work properly. This tutorial seems like the most promising, but I can only seem to get this code to return a GPS coordinate of 0.0, 0.0 which isn't very useful...

There seems to be a clue in that getLocation() returns a java.lang.NullPointerException error, but I'm not sure where I should even start looking for it.

Here's the error:

 W/System.err: java.lang.NullPointerException
 W/System.err:     at android.content.ContextWrapper.checkPermission(ContextWrapper.java:557)

I tried making a new permissions block, pasted at the bottom, but it just gave the same error.

Can anyone please point me in the right direction here?

The code is split over two class-files: MainActivity.java and GPSTracker.java.

GPSTracker.java

    package com.tutorial.android.location.api;

// http://www.androidhive.xyz/2016/07/android-gps-location-manager-tutorial.html
// with some modifications, especially for new permissions

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {
    private String TAG = "¤¤";
    private final Context mContext;

    public GPSTracker(Context mContext) {
        this.mContext = mContext;
        this.getLocation();
    }

    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    Location location;
    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10; // 10 meters
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 30 sec

    protected LocationManager locationManager;

    public Location getLocation() {
        try {

            if(locationManager == null) {
                locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            }
            if(isGPSEnabled != true) {
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            }
            if(isNetworkEnabled != true) {
                isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            }

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no provider enabled :p
                Log.e(TAG, "getLocation() no provider :(");
            } else {
                this.canGetLocation = true;
                // get network location
                if (isNetworkEnabled) {
                    // permission block:
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        // return TODO;
                    } else {
                        Log.e(TAG, "getLocation() permission DENIED");
                    }
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                    if(locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if(location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // get GPS location
                if(isGPSEnabled) {
                    if(location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                        Log.d(TAG, "getLocation() GPS Enabled");
                        if(locationManager != null){
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if(location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getLocation() ERROR...: " + e);
            e.printStackTrace();
        }
        return location;
    }

    public double getLatitude() {
        if(location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }

    public double getLongitude() {
        if(location != null) {
            longitude = location.getLongitude();
        }
        return longitude;
    }

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

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        // GPS is ON
        Log.d(TAG, "GPS is ON");
    }

    @Override
    public void onProviderDisabled(String provider) {
        // GPS is OFF
        Log.d(TAG, "GPS is OFF");
    }

    // GPS dialog
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    // don't really need this when testing
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        alertDialog.setTitle(R.string.gps_settings_title);

        alertDialog.setMessage(R.string.gps_settings_msg);
        alertDialog.setPositiveButton(R.string.gps_settings_word, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivities(new Intent[]{intent}); // hm...
            }
        });
        alertDialog.show();
    }

    public void stopUsingGPS() {
        if(locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
}

Rewritten but still not working permissions block in GPSTracker.java:

int permissionCheck = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if(!(permissionCheck == PackageManager.PERMISSION_GRANTED)) {
    if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, Manifest.permission.ACCESS_FINE_LOCATION)) {
        // explanation :p
        Log.i(TAG, "NOpe...");
    } else {
        // request permission
        Log.d(TAG, "Requestion new permission");
        ActivityCompat.requestPermissions((Activity) mContext, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }
}

MainActivity.java

package com.tutorial.android.location.api;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    String TAG = "¤";

    GPSTracker gps;

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

        gps = new GPSTracker(this);

        if(gps.canGetLocation()) {
            Log.i(TAG, "onCreate() GPS is ON");
            Log.i(TAG, "onCreate() " + gps.getLatitude()+ ", " + gps.getLongitude());
        } else {
            Log.d(TAG, "onCreate() GPS is OFF");
        }

    }
}

Body:
This tutorial seems like the most promising

It is truly awful code.

I can only seem to get this code to return a GPS coordinate of 0.0, 0.0 which isn't very useful

That is because it will only ever have a location if getLastKnownLocation() happens to return one. It is unlikely to do so.

Rewritten but still not working permissions block in GPSTracker.java:

There are two problems here:

You cannot request permissions from a service.

This is not a real service. The author of this code elected to create a class that extends Service without actually implementing or using the service properly. This is what is causing your NullPointerException, as this is not a properly initialized Context.

Can anyone please point me in the right direction here?

Throw all of this out.

FWIW, here is my sample app for using the LocationManager API.

The recipe is fairly simple:

Step #1: Get a LocationManager by calling getSystemService(Context.LOCATION_SERVICE) on some Context. I happen to do that in a fragment:

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    template=getActivity().getString(R.string.url);
    mgr=(LocationManager)getActivity()
      .getSystemService(Context.LOCATION_SERVICE);
  }

Step #2: Call requestUpdates(), passing in something that implements LocationListener. In my case, that happens to be the fragment itself:

  @Override
  @SuppressWarnings({"MissingPermission"})
  public void onStart() {
    super.onStart();

    mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3600000,
      1000, this);
  }

Step #3: In onLocationChanged() of your LocationListener, do something with the Location that you get, which in my case is to execute an AsyncTask to get a weather forecast:

  @Override
  public void onLocationChanged(Location location) {
    new FetchForecastTask().execute(location);
  }

Step #4: Call removeUpdates() when you are done:

  @Override
  @SuppressWarnings({"MissingPermission"})
  public void onStop() {
    mgr.removeUpdates(this);

    super.onStop();
  }

And that's it (other than runtime permission stuff, which I abstract out into an AbstractPermissionsActivity).

If you want, use getLastKnownLocation() as an optimization, but do not rely upon it.


问:
lttng: Unable to list kernel events: Kernel tracer not available
Currently running a CENTOS 7 machine trying to install lttng-tools and lttng-modules.

I am going through the steps required to get lttng setup on my machine located at http://lttng.org/docs/v2.9/ and am experiencing issues with just about every step along the way. My issue right now is getting lttng-modules installed. I tried running the set of commands provided to install lttng-modules:

```<code>cd $(mktemp -d) &&
wget http://lttng.org/files/lttng-modules/lttng-modules-latest2.9.tar.bz2 &&
tar -xf lttng-modules-latest-2.9.tar.bz2 &&
cd lttng-modules-2.9.* &&
make &&
sudo make modules_install &&
sudo depmod -a
</code>```

To which I received errors "Can't read private key" followed by INSTALL /probe/path/name/probe_name.ko for an entire list of probes. I read through the readme and made sure that the OS config variable dependencies were properly set. From here, I am completely unsure and any help would be appreciated.

A snippet of the terminal output is as follows:

```<code>Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/probes/lttng-probe-x86-exceptions.ko
Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/probes/lttng-probe-x86-irq-vectors.ko
Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/tests/lttng-clock-plugin-test.ko
Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/tests/lttng-test.ko
Can't read private key
  DEPMOD  3.10.0-327.el7.x86_64
make[1]: Leaving directory `/usr/src/kernels/3.10.0-327.el7.x86_64'
</code>```

答:
This sounds like enabled Linux Module signing (Documented at http://lxr.free-electrons.com/source/Documentation/module-signing.txt?v=4.8), which usually is turned on on modern UEFI Secureboot-enabled systems. Your bootloader (shim-signed or other) is signed with some UEFI-preinstalled (trusted) OEM/KEK key, shim have some OS vendor keys preinstalled, and the vendor's kernel and modules are signed with OS vendor key (more at https://wiki.ubuntu.com/SecurityTeam/SecureBoot). Your kernel probably has CONFIG_MODULE_SIG_FORCE enabled (as it was done in ubuntu https://askubuntu.com/questions/755238), and will not load unsigned module (or module signed with non-trusted key).

If you are not author of your OS distribution, you have no OS vendor private key to sign modules. And the message says that you have no any key to sign module with.

You have several variants:

Try to find the needed module in your OS (prebuild and signed by your OS vendor). If there is no required module, try asking OS vendor to include it (or pay them money for signing your module with their key). (RedHat with help of EfficiOS did some lttng for RHEL7 in 2015: https://developers.redhat.com/blog/2015/07/09/lttng-packages-available-for-rhel-7/ "LTTng Packages now Available for Red Hat Enterprise Linux 7" - probably still posted on packages.efficios.com portal and probably compatible with CentOS)

Make your own key hierarchy. You can't add any key into the kernel binary signed by vendor, but kernel will allow you to use your MOK key to sign modules. So you need to create your key, install it into shim with mokutil, (it will be added to kernel as trusted if recorded in hardware store - UEFI key database), sign new modules with it (original kernel and OS modules will work with OS vendor key).

UNSAFE: disable secure boot and use (custom compiled?) kernel with module signing required and with your own key registered as trusted (it should be listed in cat /proc/keys or keyctl list %:.system_keyring), and sign all modules of the kernel

UNSAFE, not recommended and only can be used as temporary solution on testing PC: disable secure boot and use (custom compiled or from OS vendor if it has such version) kernel with module signing disabled (disable CONFIG_MODULE_SIG_FORCE).

There are some manuals from OS vendors about module signing:

https://docs.fedoraproject.org/en-US/Fedora/23/html/System_Administrators_Guide/sect-signing-kernel-modules-for-secure-boot.html "The Fedora distribution includes signed boot loaders, signed kernels, and signed kernel modules. In addition, the signed first-stage boot loader and the signed kernel include embedded Fedora public keys...These sections also provide an overview of available options for getting your public key onto the target system where you want to deploy your kernel module."

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sect-signing-kernel-modules-for-secure-boot.html "When Secure Boot is enabled, the EFI operating system boot loaders, the Red Hat Enterprise Linux kernel, and all kernel modules must be signed with a private key and authenticated with the corresponding public key. The Red Hat Enterprise Linux 7 distribution includes signed boot loaders, signed kernels, and signed kernel modules. In addition, the signed first-stage boot loader and the signed kernel include embedded Red Hat public keys. ..  These sections also provide an overview of available options for getting your public key onto the target system where you want to deploy your kernel module."

Body:
Currently running a CENTOS 7 machine trying to install lttng-tools and lttng-modules.

I am going through the steps required to get lttng setup on my machine located at http://lttng.org/docs/v2.9/ and am experiencing issues with just about every step along the way. My issue right now is getting lttng-modules installed. I tried running the set of commands provided to install lttng-modules:

cd $(mktemp -d) &&
wget http://lttng.org/files/lttng-modules/lttng-modules-latest2.9.tar.bz2 &&
tar -xf lttng-modules-latest-2.9.tar.bz2 &&
cd lttng-modules-2.9.* &&
make &&
sudo make modules_install &&
sudo depmod -a

To which I received errors "Can't read private key" followed by INSTALL /probe/path/name/probe_name.ko for an entire list of probes. I read through the readme and made sure that the OS config variable dependencies were properly set. From here, I am completely unsure and any help would be appreciated.

A snippet of the terminal output is as follows:

Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/probes/lttng-probe-x86-exceptions.ko
Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/probes/lttng-probe-x86-irq-vectors.ko
Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/tests/lttng-clock-plugin-test.ko
Can't read private key
  INSTALL /tmp/tmp.frbWYvVaL8/lttng-modules-2.9.1/tests/lttng-test.ko
Can't read private key
  DEPMOD  3.10.0-327.el7.x86_64
make[1]: Leaving directory `/usr/src/kernels/3.10.0-327.el7.x86_64'


问:
Porting an old DOS TUI to ncurses
I would like to have some advice about how to port an old C++ program written for MS-DOS in the early 90s.

This program implements a quite complex text-user interface. The interface code is well separated from the logic, and I don't think it would be too difficult to make it use ncurses.

Being a complete novice, I have a few questions:

The DOS program intercepts interrupt 0x33 to handle mouse events. The interrupt handler store events in a FIFO, which the main program pools periodically. (Every element in the FIFO is a C structure containing information about the nature of the event, the position of the mouse and the state of its buttons.) To keep the logic of the code unchanged, I was thinking of firing a thread which calls getch() asynchronously within an infinite loop and fills the FIFO in the same way the old program did. My idea is that this thread, and only this thread, should access stdin, while the main thread would only have the responsibility to access stdout (through add_wch() and similar). Is ncurses safe to use in this way, or do stdin/stdout accesses need to be always done within the same thread?

The way colors are set in this app is quite byzantine, as it uses the concept of "inherited palettes". Basically, a window usually specifies the background and foreground colors, and every widget within that window sets the foreground only (but a few widgets redefine both fg/bg). I understand that ncurses' attr() always wants to specify colors using pairs, which must be initialized using initp(), and this doesn't play nicely with the logic of this program. I am therefore thinking of using tiparm() to directly send setaf/setbf sequences when the program wants to change the fg/bg color, respectively. (I would lose the ability to run the code on terminals which do not support setaf/setbf, but this would not be a huge loss.) Is it safe to send setaf/setbf control sequences and then call functions like add_wch(), or should the latter be used only in association with attr()?

I could write a few test scripts to check that my ideas work, but I would not be sure that this approach is supposed to work always.

Thanks for any help!

答:
There's a lot of possibilities - but the approach described sounds like terminfo (low-level) rather than curses, except for the mention of add_wch.  Rather than tiparm, a curses application would use wattr_set, init_pair, start_color, etc.

ncurses I/O has to be in one thread; while ncurses can be compiled to help (by using mutexes in some places), packagers have generally ignored that (and even with that configuration, application developers still would have work to do).

Further reading:

curses color manipulation routines

curses character and window attribute control routines

curses thread support

Title: Porting an old DOS TUI to ncurses


问:
Developing a Counter for Outputting Data Info into a specific range of excel rows & columns?
I am a beginner in Python with just basic fundamentals under my belt, ie. loops and modules.  I have some data that I want to automate by exporting it as text into specific Microsoft excel cells.

Specifically, I have 3 folders each with image files in them, a total of 10 image files.  My goal is to make a code that opens up excel and outputs the name of the folder path in each descending row of Column A and the respective image file name in descending rows of column B.

So far, I have defined the folder and path, and have allowed my code to open up Excel and name the sheet and put a title in.  I encountered my problem when trying to individually iterate each folder/file into a new cell. I tried using the range function, but it doesn't work with strings and I feel like a simple counter variable would work, but again, excel column and row names are strings.

Here is my code so far:

```<code>import win32com.client

import sys, os, string, arcpy

data_folder = "F:\\School\\GEOG_390\\Week11\\data"

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()

print(xlApp.Worksheets("Sheet1").Name)
xlApp.Worksheets("Sheet1").Range("A1").Value= "Data Files:"

for root, folders, files, in os.walk(data_folder):
for folder in folders:
    workspace = os.path.join(root, folder)
    print( "Processing" + " " + workspace)

    arcpy.env.workspace = workspace

    rasters = arcpy.ListRasters("*", "IMG")

    for raster in rasters:
        arcpy.BuildPyramids_management(raster)
        arcpy.CalculateStatistics_management(raster)

        print(raster)

        sheet = xlApp.Worksheets("Sheet1")
        sheet.Range("A2").Value = "Folder:" + folder
        sheet.Range("B2").Value = "Raster:" + raster

        print(sheet.Range("A2").Value)
        print(sheet.Range("B2").Value)
</code>```

I need the code to put folder name 1 in cell A2 and the image file name in B2, and from there on, folder 2 in cell A3 and file 2 in cell B3, all the way until cells A11 and B11.

答:
If I understand the problem correctly, you are having trouble figuring out how to increment the names of the cells (for example, "A2" and "B2") each time you process a file.  My apologies if that is not the issue.

(1) Before the first for loop, declare a variable cell_row that will track the row number where the next pair of cells will be created.  It starts at 2.

```<code>cell_row = 2
</code>```

(2) Modify the end of your loop as follows:

```<code>    folder_cell = "A" + str(cell_row)
    raster_cell = "B" + str(cell_row)
    sheet = xlApp.Worksheets("Sheet1")
    sheet.Range(folder_cell).Value = "Folder:" + folder
    sheet.Range(raster_cell).Value = "Raster:" + raster

    print(sheet.Range(folder_cell).Value)
    print(sheet.Range(raster_cell).Value)

    cell_row += 1
</code>```

Body:
I am a beginner in Python with just basic fundamentals under my belt, ie. loops and modules.  I have some data that I want to automate by exporting it as text into specific Microsoft excel cells.

Specifically, I have 3 folders each with image files in them, a total of 10 image files.  My goal is to make a code that opens up excel and outputs the name of the folder path in each descending row of Column A and the respective image file name in descending rows of column B.

So far, I have defined the folder and path, and have allowed my code to open up Excel and name the sheet and put a title in.  I encountered my problem when trying to individually iterate each folder/file into a new cell. I tried using the range function, but it doesn't work with strings and I feel like a simple counter variable would work, but again, excel column and row names are strings.

Here is my code so far:

import win32com.client

import sys, os, string, arcpy

data_folder = "F:\\School\\GEOG_390\\Week11\\data"

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()

print(xlApp.Worksheets("Sheet1").Name)
xlApp.Worksheets("Sheet1").Range("A1").Value= "Data Files:"

for root, folders, files, in os.walk(data_folder):
for folder in folders:
    workspace = os.path.join(root, folder)
    print( "Processing" + " " + workspace)

    arcpy.env.workspace = workspace

    rasters = arcpy.ListRasters("*", "IMG")

    for raster in rasters:
        arcpy.BuildPyramids_management(raster)
        arcpy.CalculateStatistics_management(raster)

        print(raster)

        sheet = xlApp.Worksheets("Sheet1")
        sheet.Range("A2").Value = "Folder:" + folder
        sheet.Range("B2").Value = "Raster:" + raster

        print(sheet.Range("A2").Value)
        print(sheet.Range("B2").Value)

I need the code to put folder name 1 in cell A2 and the image file name in B2, and from there on, folder 2 in cell A3 and file 2 in cell B3, all the way until cells A11 and B11.

Body:
If I understand the problem correctly, you are having trouble figuring out how to increment the names of the cells (for example, "A2" and "B2") each time you process a file.  My apologies if that is not the issue.

(1) Before the first for loop, declare a variable cell_row that will track the row number where the next pair of cells will be created.  It starts at 2.

cell_row = 2

(2) Modify the end of your loop as follows:

    folder_cell = "A" + str(cell_row)
    raster_cell = "B" + str(cell_row)
    sheet = xlApp.Worksheets("Sheet1")
    sheet.Range(folder_cell).Value = "Folder:" + folder
    sheet.Range(raster_cell).Value = "Raster:" + raster

    print(sheet.Range(folder_cell).Value)
    print(sheet.Range(raster_cell).Value)

    cell_row += 1


问:
Mouse scroll not working in a scroll viewer with a wpf datagrid and additional UI elements
I am trying to figure out how to get the mouse scroll working on a wpf window with a scrollviewer and a datagrid within it. The WPF and C# code is below

```<code><ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">

            <Border Name="DataGridBorder" BorderThickness="2"  Margin="1" CornerRadius="4" BorderBrush="#FF080757">
                <dg:DataGrid AutoGenerateColumns="False" Name="ValuesDataGrid"
                         BorderThickness="0" CanUserResizeColumns="True" FontWeight="Bold" HorizontalScrollBarVisibility="Auto"
                         CanUserReorderColumns="False" IsReadOnly="True" IsTextSearchEnabled="True" AlternationCount="2"
                         SelectionMode="Extended" GridLinesVisibility="All"
                         HeadersVisibility="Column" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" CanUserSortColumns="False"
                         RowDetailsVisibilityMode="Collapsed"  SelectedIndex="0"
                         RowStyle="{StaticResource CognitiDataGridRowStyle}"
                         >

                    <dg:DataGrid.Columns>
                        <dg:DataGridTemplateColumn Header="Title" >
                            <dg:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal" >
                                        <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Text="{Binding Path=Name}" FontWeight="Normal"  />
                                    </StackPanel>
                                </DataTemplate>
                            </dg:DataGridTemplateColumn.CellTemplate>
                        </dg:DataGridTemplateColumn>
                    </dg:DataGrid.Columns>
                </dg:DataGrid>
            </Border>
        </Grid>
        <Button Grid.Row="1" Height="90" >hello world</Button>
    </Grid>
</ScrollViewer>
</code>```

and the C# code is as follows

```<code> public partial class Window1 : Window
  {
     public Window1()
     {
        InitializeComponent();
        initialize();
      }

    public void initialize()
    {
        ObservableCollection<MyObject> testList = new ObservableCollection<MyObject>();

        for (int i = 0; i < 20; i++)
        {
            MyObject my = new MyObject("jack " + i);
            testList.Add(my);
        }

        ValuesDataGrid.ItemsSource = testList;

    }
}

public class MyObject
{
    public string Name { get; set; }

    public MyObject(string name)
    {
        Name = name;
    }
   }
</code>```

The problem i am facing is that when using the mouse to scroll, it works fine when it is over the button but as soon as i move the mouse pointer over the grid and try to scroll, nothing happens. I am able to move the scrollbar of the scrollviewer directly though. I am still a wpf novice so any help on how to get the mouse scroll to work over the datagrid would be appreciated. I am guessing there should be a pretty easy solution for this but I havent been able to figure it out

答:
To enable touch support you might also want to set ScrollViewer.PanningMode to None on your DataGrid and set the same property to VerticalFirst or other value on your top level ScrollViewer

Example

```<code><ScrollViewer VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>
</code>```

Of course, also use the PreviewMouseWheel event as indicated by Don B's answers to fix the original mouse scrolling issue.

```<code>private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
{
    var scrollViewer = (ScrollViewer)sender;
    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
    e.Handled = true;
}
</code>```

Or, you can simply set the following Attached Property to your ScrollViewer

```<code>public class TopMouseScrollPriorityBehavior
{
    public static bool GetTopMouseScrollPriority(ScrollViewer obj)
    {
        return (bool)obj.GetValue(TopMouseScrollPriorityProperty);
    }

    public static void SetTopMouseScrollPriority(ScrollViewer obj, bool value)
    {
        obj.SetValue(TopMouseScrollPriorityProperty, value);
    }

    public static readonly DependencyProperty TopMouseScrollPriorityProperty =
        DependencyProperty.RegisterAttached("TopMouseScrollPriority", typeof(bool), typeof(TopMouseScrollPriorityBehavior), new PropertyMetadata(false, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var scrollViewer = d as ScrollViewer;
        if (scrollViewer == null)
            throw new InvalidOperationException($"{nameof(TopMouseScrollPriorityBehavior)}.{nameof(TopMouseScrollPriorityProperty)} can only be applied to controls of type {nameof(ScrollViewer)}");
        if (e.NewValue == e.OldValue)
            return;
        if ((bool)e.NewValue)
            scrollViewer.PreviewMouseWheel += ScrollViewer_PreviewMouseWheel;
        else
            scrollViewer.PreviewMouseWheel -= ScrollViewer_PreviewMouseWheel;
    }

    private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
    {
        var scrollViewer = (ScrollViewer)sender;
        scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
        e.Handled = true;
    }
}
</code>```

Usage

```<code><ScrollViewer b:TopMouseScrollPriorityBehavior.TopMouseScrollPriority="True" VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>
</code>```

Where b: is the namespace that contains this behavior

This way your no code-behind is needed and your app is purely MVVM

ContentLicense: CC BY-SA 2.5

Body:
I am trying to figure out how to get the mouse scroll working on a wpf window with a scrollviewer and a datagrid within it. The WPF and C# code is below

<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">

            <Border Name="DataGridBorder" BorderThickness="2"  Margin="1" CornerRadius="4" BorderBrush="#FF080757">
                <dg:DataGrid AutoGenerateColumns="False" Name="ValuesDataGrid"
                         BorderThickness="0" CanUserResizeColumns="True" FontWeight="Bold" HorizontalScrollBarVisibility="Auto"
                         CanUserReorderColumns="False" IsReadOnly="True" IsTextSearchEnabled="True" AlternationCount="2"
                         SelectionMode="Extended" GridLinesVisibility="All"
                         HeadersVisibility="Column" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" CanUserSortColumns="False"
                         RowDetailsVisibilityMode="Collapsed"  SelectedIndex="0"
                         RowStyle="{StaticResource CognitiDataGridRowStyle}"
                         >

                    <dg:DataGrid.Columns>
                        <dg:DataGridTemplateColumn Header="Title" >
                            <dg:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal" >
                                        <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Text="{Binding Path=Name}" FontWeight="Normal"  />
                                    </StackPanel>
                                </DataTemplate>
                            </dg:DataGridTemplateColumn.CellTemplate>
                        </dg:DataGridTemplateColumn>
                    </dg:DataGrid.Columns>
                </dg:DataGrid>
            </Border>
        </Grid>
        <Button Grid.Row="1" Height="90" >hello world</Button>
    </Grid>
</ScrollViewer>

and the C# code is as follows

 public partial class Window1 : Window
  {
     public Window1()
     {
        InitializeComponent();
        initialize();
      }

    public void initialize()
    {
        ObservableCollection<MyObject> testList = new ObservableCollection<MyObject>();

        for (int i = 0; i < 20; i++)
        {
            MyObject my = new MyObject("jack " + i);
            testList.Add(my);
        }

        ValuesDataGrid.ItemsSource = testList;

    }
}

public class MyObject
{
    public string Name { get; set; }

    public MyObject(string name)
    {
        Name = name;
    }
   }

The problem i am facing is that when using the mouse to scroll, it works fine when it is over the button but as soon as i move the mouse pointer over the grid and try to scroll, nothing happens. I am able to move the scrollbar of the scrollviewer directly though. I am still a wpf novice so any help on how to get the mouse scroll to work over the datagrid would be appreciated. I am guessing there should be a pretty easy solution for this but I havent been able to figure it out

Body:
To enable touch support you might also want to set ScrollViewer.PanningMode to None on your DataGrid and set the same property to VerticalFirst or other value on your top level ScrollViewer

Example

<ScrollViewer VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>

Of course, also use the PreviewMouseWheel event as indicated by Don B's answers to fix the original mouse scrolling issue.

private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
{
    var scrollViewer = (ScrollViewer)sender;
    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
    e.Handled = true;
}

Or, you can simply set the following Attached Property to your ScrollViewer

public class TopMouseScrollPriorityBehavior
{
    public static bool GetTopMouseScrollPriority(ScrollViewer obj)
    {
        return (bool)obj.GetValue(TopMouseScrollPriorityProperty);
    }

    public static void SetTopMouseScrollPriority(ScrollViewer obj, bool value)
    {
        obj.SetValue(TopMouseScrollPriorityProperty, value);
    }

    public static readonly DependencyProperty TopMouseScrollPriorityProperty =
        DependencyProperty.RegisterAttached("TopMouseScrollPriority", typeof(bool), typeof(TopMouseScrollPriorityBehavior), new PropertyMetadata(false, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var scrollViewer = d as ScrollViewer;
        if (scrollViewer == null)
            throw new InvalidOperationException($"{nameof(TopMouseScrollPriorityBehavior)}.{nameof(TopMouseScrollPriorityProperty)} can only be applied to controls of type {nameof(ScrollViewer)}");
        if (e.NewValue == e.OldValue)
            return;
        if ((bool)e.NewValue)
            scrollViewer.PreviewMouseWheel += ScrollViewer_PreviewMouseWheel;
        else
            scrollViewer.PreviewMouseWheel -= ScrollViewer_PreviewMouseWheel;
    }

    private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
    {
        var scrollViewer = (ScrollViewer)sender;
        scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
        e.Handled = true;
    }
}

Usage

<ScrollViewer b:TopMouseScrollPriorityBehavior.TopMouseScrollPriority="True" VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>

Where b: is the namespace that contains this behavior

This way your no code-behind is needed and your app is purely MVVM


答:
You could do as i suggested in the comment, and just make a list for every operation, and then calculate it every time the current data changes (there may be difffrent ways to "know" if some of the result is final depending on how you can delete from the app.

SOmething like this is what i would do, and then just everytime a button is pressed call the logic for adding the input, and then calculate it and write it out

```<code>public class Calc {

    private List<String> inputs = new ArrayList<>();

    public String calculate(List<String> input){
        String result = "";
        for(String current : input){
            switch (current) {
                case "(":
                    // do stuff
                case "+":
                    //do stuff
                default:
                    // do stuff
            }
        }
        return result;
    }

    btnPlus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // add to list, and call calculate
        }
    }); // end btnPlus
}
</code>```

Title: Using a running total for calculator

Body:
You could do as i suggested in the comment, and just make a list for every operation, and then calculate it every time the current data changes (there may be difffrent ways to "know" if some of the result is final depending on how you can delete from the app.

SOmething like this is what i would do, and then just everytime a button is pressed call the logic for adding the input, and then calculate it and write it out

public class Calc {

    private List<String> inputs = new ArrayList<>();

    public String calculate(List<String> input){
        String result = "";
        for(String current : input){
            switch (current) {
                case "(":
                    // do stuff
                case "+":
                    //do stuff
                default:
                    // do stuff
            }
        }
        return result;
    }

    btnPlus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // add to list, and call calculate
        }
    }); // end btnPlus
}


问:
Navigate in code with react-router-dom 4.0?
Looking at this video the react router seems easy to use, but I can't find how to navigate in my code since I want to link on clicking a div and not use <Link>.

I've search StackOverflow but haven't found any answers that work with 4.0.  Trying to import browserHistory gives undefined (before and after installing 'react-router' in addition to 'react-router-dom') from this question:

```<code>import { browserHistory } from 'react-router';
console.log('browserHistory:', browserHistory);
</code>```

I also saw somewhere that there is a 'context' you can get to, but this shows a value for 'match' but not 'context':

```<code><Route path="/" render={({ match, context}) => {
    console.log('match:', match);
    console.log('context:', context);
</code>```

Edit

In the dev tools I can see that "Router" has a history property, so when I add that I can get to it:

```<code><Route path="/" render={({ match, context, history}) => {
</code>```

Is there a way to get to this from outside a route?  For example a navbar component that will navigate to other components, but is not inside a Route itself...

答:
If I understand your question, this is how you make a link programaticaly.</p>

```<code>    class Test extends React.Component {

      handleClick() {
        console.log(this.context);
        this.context.router.history.push('/some/path');
      },

      render() {

        return (
          <div onClick={handleClick}>
            This is div.
          </div>
        )
      }
    }

    Test.contextTypes = {
      router: React.PropTypes.object.isRequired
    }

    ReactDOM.render(
      <Test />,
      document.getElementById("app")
    );
</code>```

Body:
Looking at this video the react router seems easy to use, but I can't find how to navigate in my code since I want to link on clicking a div and not use <Link>.

I've search StackOverflow but haven't found any answers that work with 4.0.  Trying to import browserHistory gives undefined (before and after installing 'react-router' in addition to 'react-router-dom') from this question:

import { browserHistory } from 'react-router';
console.log('browserHistory:', browserHistory);

I also saw somewhere that there is a 'context' you can get to, but this shows a value for 'match' but not 'context':

<Route path="/" render={({ match, context}) => {
    console.log('match:', match);
    console.log('context:', context);

Edit

In the dev tools I can see that "Router" has a history property, so when I add that I can get to it:

<Route path="/" render={({ match, context, history}) => {

Is there a way to get to this from outside a route?  For example a navbar component that will navigate to other components, but is not inside a Route itself...

Body:
If I understand your question, this is how you make a link programaticaly.

    class Test extends React.Component {

      handleClick() {
        console.log(this.context);
        this.context.router.history.push('/some/path');
      },

      render() {

        return (
          <div onClick={handleClick}>
            This is div.
          </div>
        )
      }
    }

    Test.contextTypes = {
      router: React.PropTypes.object.isRequired
    }

    ReactDOM.render(
      <Test />,
      document.getElementById("app")
    );


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答:
There are multiple ways to do this, depending on how much validation you want to do.

In the solution below first number is obtained using .nextInt().  Note that if it is not an integer we need to clear the stream input, so in catching of InputMismatchException we do call .next().  Otherwise the same exception would keep occurring since the input has not been cleared

The second number is obtained using .next() which returns a string and we cast that string to the integer.  Note that here we catch a different exception NumberFormatException to ensure that the input is still good.  (we do not call .next())

```<code> public static void main (String [] args) {
    try (Scanner keyboard = new Scanner(System.in)) {
        System.out.print("Type your first integer: ");
        int first;
        do {
            try {
                first = keyboard.nextInt();
                break;
            } catch (InputMismatchException e) {
                keyboard.next();
                System.out.print("Invalid first integer, try again: ");
            }
        } while (true);
        System.out.print("Type your seconds integer : ");
        int second;
        do {
            try {
                second = Integer.valueOf(keyboard.next());
                break;
            } catch (NumberFormatException e) {
                System.out.print("Invalid seconds integer, try again: ");
            }
        } while (true);
        System.out.print("The sum of your two integers are: " + (first + second));
    }
}
</code>```

One last thing I did was try on the resource, this way the input stream will be closed regardless if the program exits normally or throws an exception.

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.

Body:
There are multiple ways to do this, depending on how much validation you want to do.

In the solution below first number is obtained using .nextInt().  Note that if it is not an integer we need to clear the stream input, so in catching of InputMismatchException we do call .next().  Otherwise the same exception would keep occurring since the input has not been cleared

The second number is obtained using .next() which returns a string and we cast that string to the integer.  Note that here we catch a different exception NumberFormatException to ensure that the input is still good.  (we do not call .next())

 public static void main (String [] args) {
    try (Scanner keyboard = new Scanner(System.in)) {
        System.out.print("Type your first integer: ");
        int first;
        do {
            try {
                first = keyboard.nextInt();
                break;
            } catch (InputMismatchException e) {
                keyboard.next();
                System.out.print("Invalid first integer, try again: ");
            }
        } while (true);
        System.out.print("Type your seconds integer : ");
        int second;
        do {
            try {
                second = Integer.valueOf(keyboard.next());
                break;
            } catch (NumberFormatException e) {
                System.out.print("Invalid seconds integer, try again: ");
            }
        } while (true);
        System.out.print("The sum of your two integers are: " + (first + second));
    }
}

One last thing I did was try on the resource, this way the input stream will be closed regardless if the program exits normally or throws an exception.


问:
How to draw on top of an image in Java?
I used JFrame to import and display an image, and used mousemotionlistener to detect the mouse clicks, and I want to be able to draw on top of the image. I want to be able to, if the user makes a click, make that pixel a certain color while preserving the rest of the image, however, I couldn't find out how to use Graphics to do so without deleting the rest of the image or opening a new window. </p>

```<code>public class Simple extends JFrame{
  static ImageIcon icon;
  static JFrame myframe;
  static JLabel mylabel;
  static BufferedImage image = null;
  public static void main(String[] args) {
    try{
      image = ImageIO.read(new File("mypic.png"));
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    icon=new ImageIcon(image);
    myframe=new JFrame();
    myframe.setSize(200,200);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mylabel=new JLabel();
    mylabel.setIcon(icon);
    myframe.getContentPane().add(mylabel);
    myframe.pack();
    Container container = myframe.getContentPane();
    MouseMotionEvents3 mousemotion = new MouseMotionEvents3();
    container.add(mousemotion);
    myframe.setVisible(true);
    while(1 == 1) {
      if(mousemotion.signal == true) {
        System.out.println("second message");
        mousemotion.signal = false;
      }
    }
  }
}
  class MouseMotionEvents3 extends JPanel implements MouseListener,
    MouseMotionListener {
    public boolean signal;
    public MouseMotionEvents3() {
      addMouseListener(this);
      addMouseMotionListener(this);
      signal = false;
    }
    public void mouseClicked(MouseEvent me) {
     // System.out.println("i hate you");
    }

    public void mouseEntered(MouseEvent me) {
    }

    public void mouseExited(MouseEvent me) {
    }

    public void mousePressed(MouseEvent me) {
      signal = true;
      System.out.println("message");
    }

    public void mouseReleased(MouseEvent me) {
    }

    public void mouseDragged(MouseEvent me) {
    }

    public void mouseMoved(MouseEvent me) {
    }
  }
</code>```

答:
The simplest method would be to have a list of points that represent the pixels you wish to colour. Then override the paint method for the label to first call super.paint (to display the image) and then paint the pixels that have been clicked.

```<code>List<Point> points = new ArrayList<>();

myLabel = new JLabel() {
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        points.forEach(p -> g.fillRect(p.x, p.y, 1, 1));
    }
};
</code>```

In your mouse handling just add the current point to the list and repaint the label.

```<code>public void mouseClicked(MouseEvent me) {
    points.add(me.getPoint());
    myLabel.repaint();
}
</code>```

There are more sophisticated methods that involve buffered images but this is likely good enough to get you started.

Title: How to draw on top of an image in Java?

Body:
I used JFrame to import and display an image, and used mousemotionlistener to detect the mouse clicks, and I want to be able to draw on top of the image. I want to be able to, if the user makes a click, make that pixel a certain color while preserving the rest of the image, however, I couldn't find out how to use Graphics to do so without deleting the rest of the image or opening a new window.

public class Simple extends JFrame{
  static ImageIcon icon;
  static JFrame myframe;
  static JLabel mylabel;
  static BufferedImage image = null;
  public static void main(String[] args) {
    try{
      image = ImageIO.read(new File("mypic.png"));
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    icon=new ImageIcon(image);
    myframe=new JFrame();
    myframe.setSize(200,200);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mylabel=new JLabel();
    mylabel.setIcon(icon);
    myframe.getContentPane().add(mylabel);
    myframe.pack();
    Container container = myframe.getContentPane();
    MouseMotionEvents3 mousemotion = new MouseMotionEvents3();
    container.add(mousemotion);
    myframe.setVisible(true);
    while(1 == 1) {
      if(mousemotion.signal == true) {
        System.out.println("second message");
        mousemotion.signal = false;
      }
    }
  }
}
  class MouseMotionEvents3 extends JPanel implements MouseListener,
    MouseMotionListener {
    public boolean signal;
    public MouseMotionEvents3() {
      addMouseListener(this);
      addMouseMotionListener(this);
      signal = false;
    }
    public void mouseClicked(MouseEvent me) {
     // System.out.println("i hate you");
    }

    public void mouseEntered(MouseEvent me) {
    }

    public void mouseExited(MouseEvent me) {
    }

    public void mousePressed(MouseEvent me) {
      signal = true;
      System.out.println("message");
    }

    public void mouseReleased(MouseEvent me) {
    }

    public void mouseDragged(MouseEvent me) {
    }

    public void mouseMoved(MouseEvent me) {
    }
  }

Body:
The simplest method would be to have a list of points that represent the pixels you wish to colour. Then override the paint method for the label to first call super.paint (to display the image) and then paint the pixels that have been clicked.

List<Point> points = new ArrayList<>();

myLabel = new JLabel() {
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        points.forEach(p -> g.fillRect(p.x, p.y, 1, 1));
    }
};

In your mouse handling just add the current point to the list and repaint the label.

public void mouseClicked(MouseEvent me) {
    points.add(me.getPoint());
    myLabel.repaint();
}

There are more sophisticated methods that involve buffered images but this is likely good enough to get you started.


问:
.NET Core Entitiy Framework Get Mutiple Table
Sql Tables Here

```<code>public partial class Users
{
    public Users()
    {
        UsersRelationFollower = new HashSet<UsersRelation>();
        UsersRelationFollowing = new HashSet<UsersRelation>();
        Vote = new HashSet<Vote>();
        VoteRating = new HashSet<VoteRating>();
    }

    public string Id { get; set; }
    public string UserType { get; set; }
    public string UserName { get; set; }
    public string Mail { get; set; }
    public string ImageUrl { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime? ModifyDate { get; set; }
    public bool State { get; set; }

    public virtual UserPasswords UserPasswords { get; set; }
    public virtual CorporateProperty CorporateProperty { get; set; }
    public virtual UserProperty UserProperty { get; set; }
    public virtual ICollection<UsersRelation> UsersRelationFollower { get; set; }
    public virtual ICollection<UsersRelation> UsersRelationFollowing { get; set; }
    public virtual ICollection<Vote> Vote { get; set; }
    public virtual ICollection<VoteRating> VoteRating { get; set; }
}

public partial class UserProperty
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime BirthDay { get; set; }
    public string Gender { get; set; }
    public string Locale { get; set; }
    public string PhoneNumber { get; set; }
    public bool State { get; set; }

    public virtual Users IdNavigation { get; set; }
}

public partial class CorporateProperty
{
    public string Id { get; set; }
    public string OrganisationName { get; set; }
    public string Website { get; set; }
    public bool State { get; set; }

    public virtual Users IdNavigation { get; set; }
}
</code>```

UserControllerClass

```<code>// GET: api/Users/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetUsers([FromRoute] string id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);

        if (users == null)
        {
            return NotFound();
        }
        return Ok(users);
    }
</code>```

My problem is exactly this; User information is coming but the password and property table information is not coming.

How to modify the following line solves my problem?

```<code>var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);
</code>```

答:
based on your code this would also hydrate your CorporateProperty & UseProperty objects, etc.

```<code>var user = await _context.Users.Include(user => user.UserProperty).Include
(user => user.CorporateProperty).SingleOrDefaultAsync(user => user.Id == id);
</code>```

lazy loading doesn't exist yet so you have Eager Loading to play with for now.

Surprised you didn't roll with Identity since this all of this would have been taken care for you especially Passwords...  Hope you aren't rolling your own hash for that..

Just add in the custom class / collection objects you need.

you can also check out this link
https://learn.microsoft.com/en-us/ef/core/querying/related-data

Body:
Sql Tables Here

public partial class Users
{
    public Users()
    {
        UsersRelationFollower = new HashSet<UsersRelation>();
        UsersRelationFollowing = new HashSet<UsersRelation>();
        Vote = new HashSet<Vote>();
        VoteRating = new HashSet<VoteRating>();
    }

    public string Id { get; set; }
    public string UserType { get; set; }
    public string UserName { get; set; }
    public string Mail { get; set; }
    public string ImageUrl { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime? ModifyDate { get; set; }
    public bool State { get; set; }

    public virtual UserPasswords UserPasswords { get; set; }
    public virtual CorporateProperty CorporateProperty { get; set; }
    public virtual UserProperty UserProperty { get; set; }
    public virtual ICollection<UsersRelation> UsersRelationFollower { get; set; }
    public virtual ICollection<UsersRelation> UsersRelationFollowing { get; set; }
    public virtual ICollection<Vote> Vote { get; set; }
    public virtual ICollection<VoteRating> VoteRating { get; set; }
}

public partial class UserProperty
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime BirthDay { get; set; }
    public string Gender { get; set; }
    public string Locale { get; set; }
    public string PhoneNumber { get; set; }
    public bool State { get; set; }

    public virtual Users IdNavigation { get; set; }
}

public partial class CorporateProperty
{
    public string Id { get; set; }
    public string OrganisationName { get; set; }
    public string Website { get; set; }
    public bool State { get; set; }

    public virtual Users IdNavigation { get; set; }
}

UserControllerClass

// GET: api/Users/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetUsers([FromRoute] string id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);

        if (users == null)
        {
            return NotFound();
        }
        return Ok(users);
    }

My problem is exactly this; User information is coming but the password and property table information is not coming.

How to modify the following line solves my problem?

var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);

Body:
based on your code this would also hydrate your CorporateProperty & UseProperty objects, etc.

var user = await _context.Users.Include(user => user.UserProperty).Include
(user => user.CorporateProperty).SingleOrDefaultAsync(user => user.Id == id);

lazy loading doesn't exist yet so you have Eager Loading to play with for now.

Surprised you didn't roll with Identity since this all of this would have been taken care for you especially Passwords...  Hope you aren't rolling your own hash for that..

Just add in the custom class / collection objects you need.

you can also check out this link
https://learn.microsoft.com/en-us/ef/core/querying/related-data


问:
Escape catastrophic backtracking in HTML markup
Like I said in the title, my data set is markup and it looks somewhat like this

```<code><!DOCTYPE html>
<html>
<head>
    <title>page</title>
</head>
<body>
<main>

<div class="menu">
    <img src=mmayboy.jpg>
    <p> stackoverflow is good </p>
</div>

<div class="combine">
    <p> i have suffered <span>7</span></p>
</div>
</main>
</body>
</html>
</code>```

And my regex engine tries to match each of the following node blocks separately i.e I can attempt to match combine or menu. In one shot, this is what my regex engine looks like, although I dived into its internals just below it.

```<code>/(<div class="menu">(\s+.*)+<\/div>(?:(?=(\s+<div))))/
</code>```

It attempts to dive into that markup and grabs the desired node block. That is all. As for the internals, here we go

```<code>/
(
 <div class="menu"> // match text that begins with these literals
  (
   \s+.*
  )+ /* match any white space or character after previous. But the problem is that this matches up till the closing tag of other DIVs i.e greedy. */
  <\/div> // stop at the next closing DIV (this catches the last DIV)
  (?: // begin non-capturing group
   (?=
    (
     \s+<div
     ) /* I'm using the positive lookahead to make sure previous match is not followed by a space and a new DIV tag. This is where the catastrophic backtracking is raised. */
   )
  )
 )
/
</code>```

I've indented it with comments to aid anyone willing to help. I have also scouted for solution from blogs and the manual they say it's caused by an expression having too many possibilities and can be remedied by reducing the chances of outcomes i.e +? instead of * but as hard as I've tried, I'm unable to apply any of it to my current dilemma.

答:
```<code>(\s+.*)+
</code>```

can probably be simplified to just

```<code>[^]*?
</code>```

which should prevent catastrophic backtracking. Overall simplification:

```<code>/<div class="menu">[^]*?<\/div>/
</code>```

Have you considered using an HTML parser instead, though?

```<code>var parser = new DOMParser();
var doc = parser.parseFromString(data, 'text/html');
var menu = doc.getElementsByClassName('menu')[0];

console.log(menu.innerHTML);
</code>```

Body:
Like I said in the title, my data set is markup and it looks somewhat like this

<!DOCTYPE html>

    <title>page</title>

 stackoverflow is good

 i have suffered 7

And my regex engine tries to match each of the following node blocks separately i.e I can attempt to match combine or menu. In one shot, this is what my regex engine looks like, although I dived into its internals just below it.

/(
(\s+.*)+<\/div>(?:(?=(\s+<div))))/

It attempts to dive into that markup and grabs the desired node block. That is all. As for the internals, here we go

/
(

 // match text that begins with these literals
  (
   \s+.*
  )+ /* match any white space or character after previous. But the problem is that this matches up till the closing tag of other DIVs i.e greedy. */
  <\/div> // stop at the next closing DIV (this catches the last DIV)
  (?: // begin non-capturing group
   (?=
    (
     \s+<div
     ) /* I'm using the positive lookahead to make sure previous match is not followed by a space and a new DIV tag. This is where the catastrophic backtracking is raised. */
   )
  )
 )
/

I've indented it with comments to aid anyone willing to help. I have also scouted for solution from blogs and the manual they say it's caused by an expression having too many possibilities and can be remedied by reducing the chances of outcomes i.e +? instead of * but as hard as I've tried, I'm unable to apply any of it to my current dilemma.

Body:
(\s+.*)+

can probably be simplified to just

[^]*?

which should prevent catastrophic backtracking. Overall simplification:

/<div class="menu">[^]*?<\/div>/

Have you considered using an HTML parser instead, though?

var parser = new DOMParser();
var doc = parser.parseFromString(data, 'text/html');
var menu = doc.getElementsByClassName('menu')[0];

console.log(menu.innerHTML);


问:
Gray Box thumbnail icon Google Play Developer Console
i have a problem in the Google Play Developer Console.
After i had uploaded a new update of one of my apps, the thumbnail icon of this app in the "All Applications" page changed to this. I had set a different icon both on android manifest and "Store listing" page.</p>

答: The icon appeared in my console after I uploaded a new APKs with launch icons for high density screens</p>