问:
R- current column minus sum of next x other columns till condition is met
I try to get the sum column done with R but it does not work.
Its actually simple to illustrate:
sum = points of current row - sum(bonus rows up till the first participation equals to 0) I would prefer a crisp and short code if it is possible.

```<code>Pupil   participation   bonus   points
  2           55          6       10
  2           33          3       10
  2           88          9       10
  2           44          8       10
  2           44          0       10
  2           66          7       10
  2            0          0       10
  1           22          11      10
  1           33          12      10
  1           33          13      10
  1            3          13      10
  1           44          1       10
  1            0          3       10
  1            0          0       10
</code>```

to

```<code>Pupil   participation   bonus   points   sum
  2           55          6       10      10-(6+3+9+8+0+7)
  2           33          3       10      10-(3+9+8+0+7)
  2           88          9       10      10-(9+8+0+7)
  2           44          8       10      10-(8+0+7)
  2           44          0       10      10-(0+7)
  2           66          7       10      10-(7)
  2            0          0       0        0
  1           22          11      10      10-(11+12+13+13+1)
  1           33          12      10      10-(12+13+13+1)
  1           33          13      10      10-(13+13+1)
  1            3          13      10      10-(13+1
  1           44          1       10      10-(1)
  1            0          3       10       0
  1            0          0       0        0
</code>```

Thanks

Body:
I try to get the sum column done with R but it does not work.
Its actually simple to illustrate:
sum = points of current row - sum(bonus rows up till the first participation equals to 0) I would prefer a crisp and short code if it is possible.

Pupil   participation   bonus   points
  2           55          6       10
  2           33          3       10
  2           88          9       10
  2           44          8       10
  2           44          0       10
  2           66          7       10
  2            0          0       10
  1           22          11      10
  1           33          12      10
  1           33          13      10
  1            3          13      10
  1           44          1       10
  1            0          3       10
  1            0          0       10

to

Pupil   participation   bonus   points   sum
  2           55          6       10      10-(6+3+9+8+0+7)
  2           33          3       10      10-(3+9+8+0+7)
  2           88          9       10      10-(9+8+0+7)
  2           44          8       10      10-(8+0+7)
  2           44          0       10      10-(0+7)
  2           66          7       10      10-(7)
  2            0          0       0        0
  1           22          11      10      10-(11+12+13+13+1)
  1           33          12      10      10-(12+13+13+1)
  1           33          13      10      10-(13+13+1)
  1            3          13      10      10-(13+1
  1           44          1       10      10-(1)
  1            0          3       10       0
  1            0          0       0        0

Thanks

Body:
Here's a base R split-apply-combine approach:

unsplit(lapply(split(df, df$Pupil), function(x) {
  idx <- rev(seq_len(max(which(cumsum(x$participation == 0) == 0))))
  x[idx, 'sum'] <- x[idx, 'points'] - cumsum(x[idx, 'bonus'])
  x[is.na(x$sum), 'sum'] <- 0
  x
}), df$Pupil)

   Pupil participation bonus points sum
1      2            55     6     10 -23
2      2            33     3     10 -17
3      2            88     9     10 -14
4      2            44     8     10  -5
5      2            44     0     10   3
6      2            66     7     10   3
7      2             0    11     10   0
8      1            22    12     10 -40
9      1            33    13     10 -28
10     1            33    13     10 -15
11     1             3    11     10  -2
12     1            44     1     10   9
13     1             0     3     10   0
14     1             0     0     10   0


来源: stackexchange

问:
JavaFx: is it possible to check if an item has a specific style class?
Im making buttons that need to switch between two colors every time they are pressed. I wanted to do that by comparing the style class to see if it matches either the "green" or "red" css class. Like so.

```<code>if(clickedBtn.getStyleClass() == "green") {
            clickedBtn.getStyleClass().add("red");
        } else {
        clickedBtn.getStyleClass().add("green");
        }
</code>```

This doesn't work as it doesn't recognize "green" as anything. Is there a simpler way of doing this? I just need a graphic display with selectable seats. Thanks

答:
.getStyleClass() retruns a ObservableList containing the style classes. This will never be the same object as a string literal, so the == check always yields false. The proper way of checking, if a node has a style class would be invoking the contains method of the list:

```<code>if (clickedBtn.getStyleClass().contains("green")) {
</code>```

Since you probably want red and green to be mutual exclusive. you should also remove the style classes:

```<code>if(clickedBtn.getStyleClass().remove("green")) {
    clickedBtn.getStyleClass().add("red");
} else {
    clickedBtn.getStyleClass().remove("red");
    clickedBtn.getStyleClass().add("green");
}
</code>```

Using pseudo classes would probably be a bit more convenient however:

```<code>private final static PseudoClass GREEN = PseudoClass.getPseudoClass("green");
private final static PseudoClass RED = PseudoClass.getPseudoClass("red");

...

boolean isGreen = clickedBtn.getPseudoClassStates().contains(GREEN);
clickedBtn.pseudoClassStateChanged(GREEN, !isGreen);
clickedBtn.pseudoClassStateChanged(RED, isGreen);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im making buttons that need to switch between two colors every time they are pressed. I wanted to do that by comparing the style class to see if it matches either the "green" or "red" css class. Like so.

if(clickedBtn.getStyleClass() == "green") {
            clickedBtn.getStyleClass().add("red");
        } else {
        clickedBtn.getStyleClass().add("green");
        }

This doesn't work as it doesn't recognize "green" as anything. Is there a simpler way of doing this? I just need a graphic display with selectable seats. Thanks

Body:
.getStyleClass() retruns a ObservableList containing the style classes. This will never be the same object as a string literal, so the == check always yields false. The proper way of checking, if a node has a style class would be invoking the contains method of the list:

if (clickedBtn.getStyleClass().contains("green")) {

Since you probably want red and green to be mutual exclusive. you should also remove the style classes:

if(clickedBtn.getStyleClass().remove("green")) {
    clickedBtn.getStyleClass().add("red");
} else {
    clickedBtn.getStyleClass().remove("red");
    clickedBtn.getStyleClass().add("green");
}

Using pseudo classes would probably be a bit more convenient however:

private final static PseudoClass GREEN = PseudoClass.getPseudoClass("green");
private final static PseudoClass RED = PseudoClass.getPseudoClass("red");

...

boolean isGreen = clickedBtn.getPseudoClassStates().contains(GREEN);
clickedBtn.pseudoClassStateChanged(GREEN, !isGreen);
clickedBtn.pseudoClassStateChanged(RED, isGreen);


问:
After converting byte array image not displaying core.net
In my detail view, to show more information about (in my case a Task), I will display an Image. Currently the image will not show in the view. What's wrong?

Here is my code:

My ActionResult in the controller:

```<code>public ActionResult ShowImage(int id)
{
    var task = _context.Task.SingleOrDefault(m => m.ID == id);
    Image image = byteArrayToImage(task.Image);
    return View(image);
}
</code>```

The converter method:

```<code>private Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}
</code>```

And my View:

```<code><img src="@Url.Action("ShowImage", new { id = Model.ID } )" class="img-responsive"/>
</code>```

Here is a print screen of the return. See the image for the output, it looks fine.

答:
You should use a FileContentResult to return a file from your action. Your action then becomes as simple as:

```<code>public IActionResult ShowImage(int id)
{
    var task = _context.Task.SingleOrDefault(m => m.ID == id);

    return File(task.Image, "image/jpeg");    //TODO: Set Content-Type appropriately
}
</code>```

Note:

You should set the contentType parameter appropriately in the above (I have guessed).

In the above code, I am using the ControllerBase.File Method to return a FileContentResult. If your controller does not inherit from Controller or ControllerBase you will need to return a FileContentResult directly.

Body:
In my detail view, to show more information about (in my case a Task), I will display an Image. Currently the image will not show in the view. What's wrong?

Here is my code:

My ActionResult in the controller:

public ActionResult ShowImage(int id)
{
    var task = _context.Task.SingleOrDefault(m => m.ID == id);
    Image image = byteArrayToImage(task.Image);
    return View(image);
}

The converter method:

private Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

And my View:

Here is a print screen of the return. See the image for the output, it looks fine.

Body:
You should use a FileContentResult to return a file from your action. Your action then becomes as simple as:

public IActionResult ShowImage(int id)
{
    var task = _context.Task.SingleOrDefault(m => m.ID == id);

    return File(task.Image, "image/jpeg");    //TODO: Set Content-Type appropriately
}

Note:

You should set the contentType parameter appropriately in the above (I have guessed).

In the above code, I am using the ControllerBase.File Method to return a FileContentResult. If your controller does not inherit from Controller or ControllerBase you will need to return a FileContentResult directly.


问:
Pass required argument to optional
Trying to make a board, which must be a square if there as only one argument (and a rectangle if there are two of them).

Code sample:

```<code>class Game:
    def __init__(self,h,w=h): # lookie-lookie
       self.board = [[0 for i in range(w)] for j in range(h)]
</code>```

What I expect:

```<code>b = Game(2)
b.board
#should return [[0,0],[0,0]]
b = Game(2,1)
b.board
#should return [[0],[0]]
</code>```

What i got:

```<code>NameError: name 'h' is not defined
</code>```

How should I fix it?

答:
At function definition, the value passed to optional arguments is evaluated, however, in that instant, h is not defined. You can instead use a sentinel value as a placeholder for the optional argument:

```<code>class Game(object):
    def __init__(self,h,w=None):
        if w is None:
           w = h
</code>```

If you're on Python 2, remember to subclass object.

Title: Pass required argument to optional

Body:
Trying to make a board, which must be a square if there as only one argument (and a rectangle if there are two of them).

Code sample:

class Game:
    def __init__(self,h,w=h): # lookie-lookie
       self.board = [[0 for i in range(w)] for j in range(h)]

What I expect:

b = Game(2)
b.board
#should return [[0,0],[0,0]]
b = Game(2,1)
b.board
#should return [[0],[0]]

What i got:

NameError: name 'h' is not defined

How should I fix it?

Body:
At function definition, the value passed to optional arguments is evaluated, however, in that instant, h is not defined. You can instead use a sentinel value as a placeholder for the optional argument:

class Game(object):
    def __init__(self,h,w=None):
        if w is None:
           w = h

If you're on Python 2, remember to subclass object.


问:
Trace.WriteLine in ASP.NET Azure
when I use

```<code>Diagnostics.Trace.WriteLine("message", "Information");
</code>```

in my azure-asp.net this does not show up in my  azure compute emulator,
but if I do the same from my worker-role it works, any idea why?

Thanks!

答:
Add a TraceListener of the type :

```<code>Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime.DevelopmentFabricTraceListener,
    Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime,
    Version=1.0.0.0,
    Culture=neutral,
    PublicKeyToken=31bf3856ad364e35
</code>```

The reason is due to not having this TraceListener in the AppDomain of the ASP.NET application - which is different to where WebRole.cs runs. All changed in v1.3 with the introduction of full IIS.

http://blog.bareweb.eu/2011/01/tracing-to-azure-compute-emulator-sdk-v1-3/

ContentLicense: CC BY-SA 2.5

Title: Trace.WriteLine in ASP.NET Azure

Body:
when I use

Diagnostics.Trace.WriteLine("message", "Information");

in my azure-asp.net this does not show up in my  azure compute emulator,
but if I do the same from my worker-role it works, any idea why?

Thanks!

Body:
Add a TraceListener of the type :

Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime.DevelopmentFabricTraceListener,
    Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime,
    Version=1.0.0.0,
    Culture=neutral,
    PublicKeyToken=31bf3856ad364e35

The reason is due to not having this TraceListener in the AppDomain of the ASP.NET application - which is different to where WebRole.cs runs. All changed in v1.3 with the introduction of full IIS.

http://blog.bareweb.eu/2011/01/tracing-to-azure-compute-emulator-sdk-v1-3/


问:
Array won't fill in while loop
I am currently working on schedule list for one company and I am really desperate after few hours of trying to figure out what the duck is messing up.

```<code>$schedule = [];

$result = mysql_query("SELECT *
   FROM schedule s
   INNER JOIN workers w
   ON s.worker_id = w.id BETWEEN [date1] AND [date2]");
while ($row = mysql_fetch_array($result)) {
  if(($row['s.time'] >= '8:00') && ($row['s.time'] < '20:00')) {
    if($schedule[$row['s.date']]['info']['name'] == '') {
      $schedule[$row['s.date']]['info']['name']
           = $row['w.name']; // Just one worker
    } else {
       $schedule[$row['s.date']]['info']['name'] .= ',' . $row['name'];
           // IF there is one or more workers, "join" them together by comma
    }
  }
</code>```

NO

This is not the actual code, I just rewrote the while loop with if conditions

I am unable to modify the table

YES

It only returns one worker

I tried yelling at it

I tried many conditions (empty,isset etc.)

I am not quite sure but I think I need to initialize the $schedule['Wed']['info'] first, but it will be pain in the butt.

答:
Try this way:

```<code>if(($row['s.time'] >= '8:00') && ($row['s.time'] < '20:00')) {
    if(in_array($row['w.name'], $schedule)) {  // Checking if the value already exists in array.
      $schedule[][$row['s.date']]['info']['name']
           = $row['w.name']; // Just one worker
    } else {
       $schedule[][$row['s.date']]['info']['name'] .= ',' . $row['name'];
           // IF there is one or more workers, "join" them together by comma
    }
}
</code>```

then print_r($schedule);die;  and check. You should get all the data in the array.

Title: Array won't fill in while loop

Body:
I am currently working on schedule list for one company and I am really desperate after few hours of trying to figure out what the duck is messing up.

$schedule = [];

$result = mysql_query("SELECT *
   FROM schedule s
   INNER JOIN workers w
   ON s.worker_id = w.id BETWEEN [date1] AND [date2]");
while ($row = mysql_fetch_array($result)) {
  if(($row['s.time'] >= '8:00') && ($row['s.time'] < '20:00')) {
    if($schedule[$row['s.date']]['info']['name'] == '') {
      $schedule[$row['s.date']]['info']['name']
           = $row['w.name']; // Just one worker
    } else {
       $schedule[$row['s.date']]['info']['name'] .= ',' . $row['name'];
           // IF there is one or more workers, "join" them together by comma
    }
  }

NO

This is not the actual code, I just rewrote the while loop with if conditions

I am unable to modify the table

YES

It only returns one worker

I tried yelling at it

I tried many conditions (empty,isset etc.)

I am not quite sure but I think I need to initialize the $schedule['Wed']['info'] first, but it will be pain in the butt.

Body:
Try this way:

if(($row['s.time'] >= '8:00') && ($row['s.time'] < '20:00')) {
    if(in_array($row['w.name'], $schedule)) {  // Checking if the value already exists in array.
      $schedule[][$row['s.date']]['info']['name']
           = $row['w.name']; // Just one worker
    } else {
       $schedule[][$row['s.date']]['info']['name'] .= ',' . $row['name'];
           // IF there is one or more workers, "join" them together by comma
    }
}

then print_r($schedule);die;  and check. You should get all the data in the array.


问:
PHP probleme while remove columns in csv
I use the php script below to remove some columns from a csv, order them new and save it as new file.
And it works for the file i made it for.
Now i need to do the same with another csv but i don't know whats wrong. I always get a comma befor the data in the first column.

This is what i have, but it doesn't really work.

```<code><?php
$input = 'http://***/original.csv';
$output = 'new.csv';

if (false !== ($ih = fopen($input, 'r'))) {
$oh = fopen($output, 'w');

while (false !== ($data = fgetcsv($ih))) {
    // this is where you build your new row
    $outputData = array($data[4], $data[0]);
    fputcsv($oh, $outputData);
}

fclose($ih);
fclose($oh);
}
</code>```

The original.csv looks that:

```<code>subproduct_number   barcode        stock    week_number qty_estimate    productid   variantid
05096470000         4024144513543   J                   3               6           35016
ae214               848518017215    N       23          0               7           35015
05097280000         4024144513727   J                   1               32          34990
</code>```

The seperator is ';'. The same seperator is used in the file that is working

But here it will be go wrong because my saved new.csv looks like this:

```<code>subproduct_number   barcode        stock    week_number qty_estimate    productid   variantid
,05096470000        4024144513543   J                   3               6           35016
,ae214              848518017215    N       23          0               7           35015
,05097280000        4024144513727   J                   1               32          34990
</code>```

But what i need is a new csv that looks like this:

```<code>  qty_estimate  subproduct_number
  3             05096470000
  0             ae214
  1             05097280000
</code>```

As you can see, i need only the 5. column ($data[4]) as first and the first column ($data[0]) as the second one.

I hope someone can point me in the reight direction.
Thanks

答:
You can do so:</p>

```<code>while (false !== ($data = fgetcsv($ih))) {
    $data = explode(';', $data[0]);
    $outputData = array($data[4], $data[0]);
    fputcsv($oh, $outputData, ';');
}
</code>```

Body:
I use the php script below to remove some columns from a csv, order them new and save it as new file.
And it works for the file i made it for.
Now i need to do the same with another csv but i don't know whats wrong. I always get a comma befor the data in the first column.

This is what i have, but it doesn't really work.

<?php
$input = 'http://***/original.csv';
$output = 'new.csv';

if (false !== ($ih = fopen($input, 'r'))) {
$oh = fopen($output, 'w');

while (false !== ($data = fgetcsv($ih))) {
    // this is where you build your new row
    $outputData = array($data[4], $data[0]);
    fputcsv($oh, $outputData);
}

fclose($ih);
fclose($oh);
}

The original.csv looks that:

subproduct_number   barcode        stock    week_number qty_estimate    productid   variantid
05096470000         4024144513543   J                   3               6           35016
ae214               848518017215    N       23          0               7           35015
05097280000         4024144513727   J                   1               32          34990

The seperator is ';'. The same seperator is used in the file that is working

But here it will be go wrong because my saved new.csv looks like this:

subproduct_number   barcode        stock    week_number qty_estimate    productid   variantid
,05096470000        4024144513543   J                   3               6           35016
,ae214              848518017215    N       23          0               7           35015
,05097280000        4024144513727   J                   1               32          34990

But what i need is a new csv that looks like this:

  qty_estimate  subproduct_number
  3             05096470000
  0             ae214
  1             05097280000

As you can see, i need only the 5. column ($data[4]) as first and the first column ($data[0]) as the second one.

I hope someone can point me in the reight direction.
Thanks

Body:
You can do so:

while (false !== ($data = fgetcsv($ih))) {
    $data = explode(';', $data[0]);
    $outputData = array($data[4], $data[0]);
    fputcsv($oh, $outputData, ';');
}


问:
Signing VSTO Code with EV Certificate on Visual Studio 2017
I have a VSTO program in Visual Studio 2017. In order to make the install process run more smoothly when I publish via ClickOnce and host the files on the web, I bought an EV Certificate from DigiCert.

This is what I bought - https://www.digicert.com/code-signing/ev-code-signing/

So I waited a couple days, got my USB token, set everything up and now when I sign the app with my fancy new certificate... the install flat-out fails.

The error the user gets is:
Customized Functionality in this application will not work because the certificate used to sign the deployment manifest for AppName or its location is not trusted. Contact your administrator for further assistance.

I contacted DigiCert for tech support and they basically said that this is an error with Visual Studio 2017 and the Operating System.

I then called Entrust to see if they could confirm since they also have the EV Certificates:
https://www.entrust.com/code-signing-certificates/#ev-code-signing-certificates

Turns out I guess until you buy one, they can't answer the question. They just kindof say "buy it and try it and if it doesn't work we'll give you your money back."

How is it possible that nobody knows how to sign an install from Visual Studio?

I would love to be able to sign this install and get it to work.

答:
After a lot of time spent on the phone with support at DigiCert, we finally figured out a process that works.

What is not immediately obvious in this case is that you end up doing a LOT of signing of code.

So when you build a VSTO application, you sign the code with the EV certificate. Then, when you want to publish (using ClickOnce) you will have to sign again.

But even after that, you have to then re-sign the setup file TWO MORE TIMES to get this all to work!

After spending a ton of time on this, I now have a batch file that does the final steps, including syncing the setup files up to Amazon S3 for deployment.

So here's how I do it:

Once you have the USB dongle installed, you setup the "Signing"
section of your app in Visual Studio to reference the correct
certificate.

Right-click your project and click Build (or Rebuild to be
safe) and you will have to sign using the dongle.

Now, right-click the project and pick Properties

Inside Properties go to Signing and confirm you have the
correct certificate selected. If you skip this step, the app won't
install.

Still inside Properties go to Publish and make sure to set
your publishing location and installation folders. I use Amazon S3
for the installation folder.

Click Publish Now. It will ask you to sign again.

Now, you would think at this point you'd be done... but you aren't.

So what you need next is a .p12 certificate. I contacted
DigiCert support and they were able to give me one for free (prob
just for a year) since I was having so many problems. This is
different than the EV certificate.

After you have the .p12 certificate AND the EV, I run the following batch
routine, which signs the setup.exe file TWICE (once with .p12 and then
again with the EV) and also pushes up to Amazon S3.

Here's my SignDeploy.bat file:

```<code>echo off
cls
echo Signing setup.exe with .p12 Certificate File
"C:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe" sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /f [LOCATION OF P12 FILE] /p [PASSWORD] [LOCATION OF SETUP.EXE]
pause
echo Signing setup.exe with EV Certificate from Store
"C:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe" sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /sha1 [EV HASH FROM DIGICERT] [LOCATION OF SETUP.EXE]
pause
echo Dry run on syncing files up to S3
aws s3 sync [LOCAL DEPLOYMENT FOLDER] [S3 BUCKET AND FOLDER LOCATION] --acl public-read --dryrun
echo
echo If that worked, it's time to send them up for real.
echo Control-C to stop now, or...
pause
aws s3 sync [LOCAL DEPLOYMENT FOLDER] [S3 BUCKET AND FOLDER LOCATION] --acl public-read
pause
</code>```

After all this (I think you end up typing your EV certificate password 3 times total) a user who downloads setup.exe from the specified location (must be the same as indicated in your app) will be able to install and run your VSTO application.

There are other problems we have run into along the way with the installation process on the client side, but using the above process solves the issue with signing.

I won't pretend to understand why this needs signed so many times, nor does it make sense that this doesn't all work smoothly from inside Visual Studio. DigiCert tried to have me use Build Events to do this, but it doesn't work b/c those processes run on either side of the BUILD not the PUBLISH. What we'd need are Publish Events which I don't think exist.

I have explored the idea of a longer more involved command-line process using MsBuild.exe, but it's difficult to do the Automatically increment revision with each release part that way.

Maybe someone here has an idea how to set that up. My process is still a bit manual, but it seems to work reliably at this point so I'm not inclined to mess with it too much.

Body:
After a lot of time spent on the phone with support at DigiCert, we finally figured out a process that works.

What is not immediately obvious in this case is that you end up doing a LOT of signing of code.

So when you build a VSTO application, you sign the code with the EV certificate. Then, when you want to publish (using ClickOnce) you will have to sign again.

But even after that, you have to then re-sign the setup file TWO MORE TIMES to get this all to work!

After spending a ton of time on this, I now have a batch file that does the final steps, including syncing the setup files up to Amazon S3 for deployment.

So here's how I do it:

Once you have the USB dongle installed, you setup the "Signing"
section of your app in Visual Studio to reference the correct
certificate.

Right-click your project and click Build (or Rebuild to be
safe) and you will have to sign using the dongle.

Now, right-click the project and pick Properties

Inside Properties go to Signing and confirm you have the
correct certificate selected. If you skip this step, the app won't
install.

Still inside Properties go to Publish and make sure to set
your publishing location and installation folders. I use Amazon S3
for the installation folder.

Click Publish Now. It will ask you to sign again.

Now, you would think at this point you'd be done... but you aren't.

So what you need next is a .p12 certificate. I contacted
DigiCert support and they were able to give me one for free (prob
just for a year) since I was having so many problems. This is
different than the EV certificate.

After you have the .p12 certificate AND the EV, I run the following batch
routine, which signs the setup.exe file TWICE (once with .p12 and then
again with the EV) and also pushes up to Amazon S3.

Here's my SignDeploy.bat file:

echo off
cls
echo Signing setup.exe with .p12 Certificate File
"C:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe" sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /f [LOCATION OF P12 FILE] /p [PASSWORD] [LOCATION OF SETUP.EXE]
pause
echo Signing setup.exe with EV Certificate from Store
"C:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe" sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /sha1 [EV HASH FROM DIGICERT] [LOCATION OF SETUP.EXE]
pause
echo Dry run on syncing files up to S3
aws s3 sync [LOCAL DEPLOYMENT FOLDER] [S3 BUCKET AND FOLDER LOCATION] --acl public-read --dryrun
echo
echo If that worked, it's time to send them up for real.
echo Control-C to stop now, or...
pause
aws s3 sync [LOCAL DEPLOYMENT FOLDER] [S3 BUCKET AND FOLDER LOCATION] --acl public-read
pause

After all this (I think you end up typing your EV certificate password 3 times total) a user who downloads setup.exe from the specified location (must be the same as indicated in your app) will be able to install and run your VSTO application.

There are other problems we have run into along the way with the installation process on the client side, but using the above process solves the issue with signing.

I won't pretend to understand why this needs signed so many times, nor does it make sense that this doesn't all work smoothly from inside Visual Studio. DigiCert tried to have me use Build Events to do this, but it doesn't work b/c those processes run on either side of the BUILD not the PUBLISH. What we'd need are Publish Events which I don't think exist.

I have explored the idea of a longer more involved command-line process using MsBuild.exe, but it's difficult to do the Automatically increment revision with each release part that way.

Maybe someone here has an idea how to set that up. My process is still a bit manual, but it seems to work reliably at this point so I'm not inclined to mess with it too much.


问:
Visual Studio 2017 class or method comment shortcut (formerly ///)
In previous versions of Visual Studio, when writing a class or method the user could type /// to have the IDE provide a structured comment block. This isn't strictly a 'keyboard shortcut', nor is it a snippet.

This doesn't work in Visual Studio 2017. Is there now a new key sequence to generate that comment block? Or is it deprecated?

答: I had the same issue. Yet the cause was that I did not note that there was a [httppsot] attribute above the place where I was trying to write the function summary. So be sure that you type /// before all function attributes.</p>


问:
Using whereRaw() and orWhereRaw() with Join in laravel 5.2
I am writing a code like this:-

```<code>$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details', function($query) use ($rating,$keyword) {
            $query->on('users.id', '=', 'homechef_details.user_id');
            $query->where('users.status','=',1);
            if(isset($rating) && !empty($rating))
            {
                if(count($rating)==1)
                    $query->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                    $query->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
        })->get();
</code>```

I need to check the floor value of the column value in the where clause. I am getting this error:-

```<code>Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw()
</code>```

How can I fix this error?

答:
Inside closure, $query is instance of JoinClause and it does not have whereRaw() methods.

As alternative to madalinivascu's answer, you can use DB::raw() to construct raw SQL inside closure.

Body:
I am writing a code like this:-

$results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating')
        ->join('homechef_details', function($query) use ($rating,$keyword) {
            $query->on('users.id', '=', 'homechef_details.user_id');
            $query->where('users.status','=',1);
            if(isset($rating) && !empty($rating))
            {
                if(count($rating)==1)
                    $query->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                else if(count($rating)>1)
                {
                    $query->where(function($q) use($rating)
                    {
                        $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]);
                        for($r = 1; $r < count($rating); $r++)
                        {
                           $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]);
                        }
                    });
                }
            }
        })->get();

I need to check the floor value of the column value in the where clause. I am getting this error:-

Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw()

How can I fix this error?


问:
Creating UI framework more like Visual studio
I want to develop the application UI much like as VS2010 or any similar UI models. My requirements are as below:

Opening new project will create empty canavs.

When I will do add data sheet it will add new tab page in that.

Remaining few things I will do on that added tab page like showing charts, different types of controls etc.

When I will press 'Save' it will persist whatever there on UI like added tab pages and every controls on it on disk.

When I will open any saved project, It will recreate everything what was there on UI at the time of saving the project.

I will have recently open project list.

Any idea for creating how to create such UI?

Thanks,
Omky

答: Maybe develop your solution over Visual Studio SDK? A good sample is AddonStudio for World of Warcraft which is customized dev. environment for World of Warcraft addon development based on Visual Studio.


问:
cordova not installing on windows
I wanted to installed ionic3 so I completely uninstalled nodejs and reinstalled it, then installed ionic,

```<code>C:\Windows\system32>ionic -v
3.19.0

C:\Windows\system32>npm -v
5.5.1

C:\Windows\system32>node -v
v8.9.1
</code>```

now I am trying to install cordova and it is not installing.

```<code>C:\Windows\system32>npm install -g cordova
npm ERR! Unexpected end of JSON input while parsing near '....1.4","ripemd160":"
^2'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\DELL 5521\AppData\Roaming\npm-cache\_logs\2017-12-05T20_46
_55_094Z-debug.log
</code>```

here are contents of log file

// 2017-12-05T20_46_55_094Z-debug.log
https://pastebin.com/7mVNRkC8

答:
try following steps
Ionic CLI and Cordova
To create Ionic projects, you’ll need to install the latest version of the CLI and Cordova. Before you do that, you’ll need a recent version of Node.js. Node Download

next you need to open cmd and run $ npm install -g ionic cordova
learn more details https://ionicframework.com/docs/intro/installation/

Title: cordova not installing on windows

Body:
I wanted to installed ionic3 so I completely uninstalled nodejs and reinstalled it, then installed ionic,

C:\Windows\system32>ionic -v
3.19.0

C:\Windows\system32>npm -v
5.5.1

C:\Windows\system32>node -v
v8.9.1

now I am trying to install cordova and it is not installing.

C:\Windows\system32>npm install -g cordova
npm ERR! Unexpected end of JSON input while parsing near '....1.4","ripemd160":"
^2'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\DELL 5521\AppData\Roaming\npm-cache\_logs\2017-12-05T20_46
_55_094Z-debug.log

here are contents of log file

// 2017-12-05T20_46_55_094Z-debug.log
https://pastebin.com/7mVNRkC8


问:
Clear old data in Grafana
I'm using Prometheus and Grafana  for monitoring the servers.
Grafana data were stored in /home/user/data folder.

This folder occupied the majority of the file system .

Need to remove the old data in Grafana data folder ( Data which is older than a month )

答:
Grafana does not save data from Prometheus. It queries Prometheus and displays UI. In this case, you would have to look at purging Prometheus data.

Prometheus by default has a 15 day retention period. But this could be adjusted by the -storage.local.retention flag to suit your needs.

Title: Clear old data in Grafana

ContentLicense: CC BY-SA 4.0


问:
regex for finding a particular file
I want to match a file name as "abc (1).xyz" or "abc (2).xyz" or "abc (3).xyz" and so on, in which abc and xyz (extension) is fixed. Besides, the space+(number)  part is optional, i.e. the abc.xyz is also valid.

I have tried the below code, but it didn't returns the success response:

```<code>String regex = "abc\\s([0-9])\\.xyz";
        Pattern mather = Pattern.compile(regex);

        if (mather.matcher(fileName).matches()) {
            return true;
        } else {
            return false;
        }
</code>```

Please suggest any solution for the same. Thanks in advance.

答:
You may use

```<code>String regex = "abc(?:\\s+\\([0-9]+\\))?\\.xyz";
</code>```

It will match:

abc - abc

(?:\\s+\\([0-9]+\\))? - an optional sequence of:

\\s+ - 1+ whitespace chars

\\( - a (

[0-9]+  - 1+ digits

\\) - a )

\\.xyz - a .xyz substring.

Since you are using Matcher#matches() method, the whole string match is required (as if the whole pattern was enclosed with ^ and $ anchors, "^abc(?:\\s+\\([0-9]+\\))?\\.xyz$").

Title: regex for finding a particular file

Body:
I want to match a file name as "abc (1).xyz" or "abc (2).xyz" or "abc (3).xyz" and so on, in which abc and xyz (extension) is fixed. Besides, the space+(number)  part is optional, i.e. the abc.xyz is also valid.

I have tried the below code, but it didn't returns the success response:

String regex = "abc\\s([0-9])\\.xyz";
        Pattern mather = Pattern.compile(regex);

        if (mather.matcher(fileName).matches()) {
            return true;
        } else {
            return false;
        }

Please suggest any solution for the same. Thanks in advance.

Body:
You may use

String regex = "abc(?:\\s+\\([0-9]+\\))?\\.xyz";

It will match:

abc - abc

(?:\\s+\\([0-9]+\\))? - an optional sequence of:

\\s+ - 1+ whitespace chars

\\( - a (

[0-9]+  - 1+ digits

\\) - a )

\\.xyz - a .xyz substring.

Since you are using Matcher#matches() method, the whole string match is required (as if the whole pattern was enclosed with ^ and $ anchors, "^abc(?:\\s+\\([0-9]+\\))?\\.xyz$").


问:
Check if mousedown() event happened on certain element
I'm using this function to detect mousedown() and initialize content drag:

```<code>        var mouseDown = false;
        var prevCoords = { x: 0, y: 0 };

        $("#mainDiv").mousedown(function() {
            mouseDown = true;
        }).mousemove(function(e) {
            var currentScrollX = $('#mainDiv').scrollLeft();
            var currentScrollY = $('#mainDiv').scrollTop();
            if(mouseDown) {
                $('#mainDiv').scrollLeft(currentScrollX + prevCoords.x - e.clientX)
                $('#mainDiv').scrollTop(currentScrollY + prevCoords.y - e.clientY)
            };
            prevCoords.x = e.clientX;
            prevCoords.y = e.clientY;
        }).mouseup(function() {
            mouseDown = false;
        });
</code>```

But #mainDiv contains .foo tables which are draggable itself. How do I check, if mousedown() happened on .foo table? In this case mouseDown should become false to cancel content drag. I have tried this but it did not work:

```<code>        $("#mainDiv").mousedown(function() {
            if($('.foo').mousedown()){
                mouseDown = false;
            }
            else{
                mouseDown = true;
            }
</code>```

答:
To check which element caused the event that bubbled up to #mainDiv you can check the target of the event. You can also make the logic a little tidier:

```<code>$("#mainDiv").mousedown(function(e) {
  mousedown = !$(e.target).closest('.foo').length;
});
</code>```

Body:
I'm using this function to detect mousedown() and initialize content drag:

        var mouseDown = false;
        var prevCoords = { x: 0, y: 0 };

        $("#mainDiv").mousedown(function() {
            mouseDown = true;
        }).mousemove(function(e) {
            var currentScrollX = $('#mainDiv').scrollLeft();
            var currentScrollY = $('#mainDiv').scrollTop();
            if(mouseDown) {
                $('#mainDiv').scrollLeft(currentScrollX + prevCoords.x - e.clientX)
                $('#mainDiv').scrollTop(currentScrollY + prevCoords.y - e.clientY)
            };
            prevCoords.x = e.clientX;
            prevCoords.y = e.clientY;
        }).mouseup(function() {
            mouseDown = false;
        });

But #mainDiv contains .foo tables which are draggable itself. How do I check, if mousedown() happened on .foo table? In this case mouseDown should become false to cancel content drag. I have tried this but it did not work:

        $("#mainDiv").mousedown(function() {
            if($('.foo').mousedown()){
                mouseDown = false;
            }
            else{
                mouseDown = true;
            }

Body:
To check which element caused the event that bubbled up to #mainDiv you can check the target of the event. You can also make the logic a little tidier:

$("#mainDiv").mousedown(function(e) {
  mousedown = !$(e.target).closest('.foo').length;
});


问:
jQuery mobile - close panel on history back
I have a jQuery mobile panel which slides in from the side, it works great.
But lets say you have a login page, that redirects to a main page with a panel. Now if the user opens the panel, and then clicks the back button, he expects the panel to close. But instead the browser navigates back to the login page.

I´ve tried adding something to the url:

```<code>window.location.hash = "panelOpen";
</code>```

But that just messes up the jQuery mobile history state pattern. I´ve also tried to listen to the navigate event, and prevent it if a panel is open:

```<code>$(window).on('navigate', function (e, hans) {
     var panels = $('[data-role="panel"].ui-panel-open');
     if (panels&&panels.length>0) {
         e.preventDefault();
         e.stopPropagation();
         $('#' + panels[0].id).panel('close');
           return false;
         }
});
</code>```

This kind of works, except that the url is changed, and I cannot grab the event that changes the url. Furthermore, it also messes up the jQuery mobile history pattern.

So how does people achieve this expected 'app-like' behaviour with a jQuery mobile panel; open panel > history back > close panel. And thats it.

Thanks alot!

答:
I am a little bit late on the party, but i had recently the same requirements and i would like to share how i did it. So, i extended the requirement in the original question to Panels, Popups and Pages:

...an expected 'app-like' behaviour, history back > close
  whaterver is open. And thats it.

In .on("panelopen"), .on("popupafteropen") and .on("pagecontainershow") i simply add another entry to the window history, by using the HTML5 API (https://developer.mozilla.org/en-US/docs/Web/API/History_API) (I believe there is no need to use the JQM navigate browser quirks for that):

```<code>window.history.pushState({}, window.document.title, window.location.href);
</code>```

After that, i'm using more or less Omar's function to intercept the popstate event:

```<code>$(window).on("popstate", function (e) {
  var pageId = $(":mobile-pagecontainer").pagecontainer("getActivePage").prop("id");
  var pageOpen = (pageId != "page-home");
  var panelOpen = $(".ui-panel-open").length > 0;
  var popupOpen = $(".ui-popup-active").length > 0;

  if(pageOpen) {
    $.mobile.pageContainer.pagecontainer("change", "#page-home", {reverse: true});
    return false;
  }
  if(panelOpen) {
    $(".ui-panel-open").panel("close");
    return false;
  }
  if(popupOpen) {
    $(".ui-popup-active .ui-popup").popup("close")
    return false;
  }
});
</code>```

As you see, the is just only one level to the home-page, but this can be easily extended by using JQM history implementation to get the previous page:

```<code>var activeId = $.mobile.navigate.history.activeIndex;
var jqmHistory = $.mobile.navigate.history.stack; // array of pages
</code>```

and use pagecontainer to change to the active entry - 1.

As last note, this works well also by completely disabling the built-in JQM Ajax navigation system:

```<code>/* Completely disable navigation for mobile app */
$.mobile.ajaxEnabled = false;
$.mobile.loadingMessage = false;
$.mobile.pushStateEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
$.mobile.popup.prototype.options.history = false;
</code>```

(Tested in Browser, on real Android and iOS devices)

Body:
I have a jQuery mobile panel which slides in from the side, it works great.
But lets say you have a login page, that redirects to a main page with a panel. Now if the user opens the panel, and then clicks the back button, he expects the panel to close. But instead the browser navigates back to the login page.

I´ve tried adding something to the url:

window.location.hash = "panelOpen";

But that just messes up the jQuery mobile history state pattern. I´ve also tried to listen to the navigate event, and prevent it if a panel is open:

$(window).on('navigate', function (e, hans) {
     var panels = $('[data-role="panel"].ui-panel-open');
     if (panels&&panels.length>0) {
         e.preventDefault();
         e.stopPropagation();
         $('#' + panels[0].id).panel('close');
           return false;
         }
});

This kind of works, except that the url is changed, and I cannot grab the event that changes the url. Furthermore, it also messes up the jQuery mobile history pattern.

So how does people achieve this expected 'app-like' behaviour with a jQuery mobile panel; open panel > history back > close panel. And thats it.

Thanks alot!

Body:
I am a little bit late on the party, but i had recently the same requirements and i would like to share how i did it. So, i extended the requirement in the original question to Panels, Popups and Pages:

...an expected 'app-like' behaviour, history back > close
  whaterver is open. And thats it.

In .on("panelopen"), .on("popupafteropen") and .on("pagecontainershow") i simply add another entry to the window history, by using the HTML5 API (https://developer.mozilla.org/en-US/docs/Web/API/History_API) (I believe there is no need to use the JQM navigate browser quirks for that):

window.history.pushState({}, window.document.title, window.location.href);

After that, i'm using more or less Omar's function to intercept the popstate event:

$(window).on("popstate", function (e) {
  var pageId = $(":mobile-pagecontainer").pagecontainer("getActivePage").prop("id");
  var pageOpen = (pageId != "page-home");
  var panelOpen = $(".ui-panel-open").length > 0;
  var popupOpen = $(".ui-popup-active").length > 0;

  if(pageOpen) {
    $.mobile.pageContainer.pagecontainer("change", "#page-home", {reverse: true});
    return false;
  }
  if(panelOpen) {
    $(".ui-panel-open").panel("close");
    return false;
  }
  if(popupOpen) {
    $(".ui-popup-active .ui-popup").popup("close")
    return false;
  }
});

As you see, the is just only one level to the home-page, but this can be easily extended by using JQM history implementation to get the previous page:

var activeId = $.mobile.navigate.history.activeIndex;
var jqmHistory = $.mobile.navigate.history.stack; // array of pages

and use pagecontainer to change to the active entry - 1.

As last note, this works well also by completely disabling the built-in JQM Ajax navigation system:

/* Completely disable navigation for mobile app */
$.mobile.ajaxEnabled = false;
$.mobile.loadingMessage = false;
$.mobile.pushStateEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
$.mobile.popup.prototype.options.history = false;

(Tested in Browser, on real Android and iOS devices)


问:
Can I use the DetailsView control without binding?
I wanna use the DetailsView control without binding it with a datasource (just in insert mode) but the problem is when I try to get the values of the fields throught ItemInserting event handler I found the e.Values property empty however there are some fields.

Note: I wanna use it (The DetailsView control) [instead of allign the fields manually] because there're already a theme for it in whole the system and I don't want to do that again from scratch for custom template.

Any Idea !!

答:
Ah yes, I wrote a blog post on this topic. http://weblogs.asp.net/davidfowler/archive/2008/12/12/getting-your-data-out-of-the-data-controls.aspx.

BTW in .NET 4.0 e.Values won't be empty :).


问:
java program : calculate the average?
I'm creating a java program, which allows me to calculate the average number of votes entered by me, and when I finally enter a negative number the program stops. The program works fine but there is a section of the program that is not shown.

Here is the program :

```<code> public static void main (String[] args) {

    System.out.println("This program calculate the average of your votes");
    Scanner keyboard = new Scanner(System.in);
    String answer;

    do {
        int sum = 0, myVotes=0;
        System.out.println("Enter your votes and at the end a negative number");
        boolean average = true;

        while(average ) {
            int votes = keyboard.nextInt();
            if (votes >0) {
                sum = sum + votes;
                myVotes++;
            } else if (myVotes>0){
                System.out.println("The average is :" + (sum/myVotes));
            } else  if (votes<0){
                average = false;
            }
        }
        System.out.println("Do you want to calculate another average : yes or no");
        answer = keyboard.next();
    }while(answer.equalsIgnoreCase("yes"));
}
</code>```

This is the section which is not show by the program :

Do you want to calculate another average : yes or no;
exc ..

Thank you all for the helping.

答:
Problem is in your if-else logic. Remove if (myVotes>0) and put System.out.println("The average is :" + (sum/myVotes)); line out of while(average ) loop:

Following is corrected code snippet:

```<code>do {

    int sum = 0, myVotes=0;

    System.out.println("Enter your votes and at the end a negative number");

    boolean average = true;

    while(average ) {

        int votes = keyboard.nextInt();
        if (votes >0) {
            sum = sum + votes;
            myVotes++;
        } else  if (votes<0){
            average = false;
        }
    }

    if (myVotes != 0){//To handle divide by 0 exception
            System.out.println("The average is :" + (sum/myVotes));
    }
    System.out.println("Do you want to calculate another average : yes or no");

    answer = keyboard.next();

}while(answer.equalsIgnoreCase("yes"));
</code>```

Title: java program : calculate the average?

Body:
I'm creating a java program, which allows me to calculate the average number of votes entered by me, and when I finally enter a negative number the program stops. The program works fine but there is a section of the program that is not shown.

Here is the program :

 public static void main (String[] args) {

    System.out.println("This program calculate the average of your votes");
    Scanner keyboard = new Scanner(System.in);
    String answer;

    do {
        int sum = 0, myVotes=0;
        System.out.println("Enter your votes and at the end a negative number");
        boolean average = true;

        while(average ) {
            int votes = keyboard.nextInt();
            if (votes >0) {
                sum = sum + votes;
                myVotes++;
            } else if (myVotes>0){
                System.out.println("The average is :" + (sum/myVotes));
            } else  if (votes<0){
                average = false;
            }
        }
        System.out.println("Do you want to calculate another average : yes or no");
        answer = keyboard.next();
    }while(answer.equalsIgnoreCase("yes"));
}

This is the section which is not show by the program :

Do you want to calculate another average : yes or no;
exc ..

Thank you all for the helping.

Body:
Problem is in your if-else logic. Remove if (myVotes>0) and put System.out.println("The average is :" + (sum/myVotes)); line out of while(average ) loop:

Following is corrected code snippet:

do {

    int sum = 0, myVotes=0;

    System.out.println("Enter your votes and at the end a negative number");

    boolean average = true;

    while(average ) {

        int votes = keyboard.nextInt();
        if (votes >0) {
            sum = sum + votes;
            myVotes++;
        } else  if (votes<0){
            average = false;
        }
    }

    if (myVotes != 0){//To handle divide by 0 exception
            System.out.println("The average is :" + (sum/myVotes));
    }
    System.out.println("Do you want to calculate another average : yes or no");

    answer = keyboard.next();

}while(answer.equalsIgnoreCase("yes"));


问:
R- current column minus sum of next x other columns till condition is met
I try to get the sum column done with R but it does not work.
Its actually simple to illustrate:
sum = points of current row - sum(bonus rows up till the first participation equals to 0) I would prefer a crisp and short code if it is possible.

```<code>Pupil   participation   bonus   points
  2           55          6       10
  2           33          3       10
  2           88          9       10
  2           44          8       10
  2           44          0       10
  2           66          7       10
  2            0          0       10
  1           22          11      10
  1           33          12      10
  1           33          13      10
  1            3          13      10
  1           44          1       10
  1            0          3       10
  1            0          0       10
</code>```

to

```<code>Pupil   participation   bonus   points   sum
  2           55          6       10      10-(6+3+9+8+0+7)
  2           33          3       10      10-(3+9+8+0+7)
  2           88          9       10      10-(9+8+0+7)
  2           44          8       10      10-(8+0+7)
  2           44          0       10      10-(0+7)
  2           66          7       10      10-(7)
  2            0          0       0        0
  1           22          11      10      10-(11+12+13+13+1)
  1           33          12      10      10-(12+13+13+1)
  1           33          13      10      10-(13+13+1)
  1            3          13      10      10-(13+1
  1           44          1       10      10-(1)
  1            0          3       10       0
  1            0          0       0        0
</code>```

Thanks

Body:
I try to get the sum column done with R but it does not work.
Its actually simple to illustrate:
sum = points of current row - sum(bonus rows up till the first participation equals to 0) I would prefer a crisp and short code if it is possible.

Pupil   participation   bonus   points
  2           55          6       10
  2           33          3       10
  2           88          9       10
  2           44          8       10
  2           44          0       10
  2           66          7       10
  2            0          0       10
  1           22          11      10
  1           33          12      10
  1           33          13      10
  1            3          13      10
  1           44          1       10
  1            0          3       10
  1            0          0       10

to

Pupil   participation   bonus   points   sum
  2           55          6       10      10-(6+3+9+8+0+7)
  2           33          3       10      10-(3+9+8+0+7)
  2           88          9       10      10-(9+8+0+7)
  2           44          8       10      10-(8+0+7)
  2           44          0       10      10-(0+7)
  2           66          7       10      10-(7)
  2            0          0       0        0
  1           22          11      10      10-(11+12+13+13+1)
  1           33          12      10      10-(12+13+13+1)
  1           33          13      10      10-(13+13+1)
  1            3          13      10      10-(13+1
  1           44          1       10      10-(1)
  1            0          3       10       0
  1            0          0       0        0

Thanks

Body:
An alternative solution.

df  =read.table(text="Pupil   participation   bonus   points
  2           55          6       10
  2           33          3       10
  2           88          9       10
  2           44          8       10
  2           44          0       10
  2           66          7       10
  2            0          0       10
  1           22          11      10
  1           33          12      10
  1           33          13      10
  1            3          13      10
  1           44          1       10
  1            0          3       10
  1            0          0       10",header=T)

library(data.table)
df = rbindlist(lapply(split(df,with(rle(df$participation==0),
                 rep(seq(length(values)),lengths))),
                 function(x) {x$sum2=x$points-rev(cumsum(rev(x$bonus))); x}))
df$sum2[df$participation==0]=0

Output:

    Pupil participation bonus points                sum sum2
 1:     2            55     6     10   10-(6+3+9+8+0+7)  -23
 2:     2            33     3     10     10-(3+9+8+0+7)  -17
 3:     2            88     9     10       10-(9+8+0+7)  -14
 4:     2            44     8     10         10-(8+0+7)   -5
 5:     2            44     0     10           10-(0+7)    3
 6:     2            66     7     10             10-(7)    3
 7:     2             0     0      0                  0    0
 8:     1            22    11     10 10-(11+12+13+13+1)  -40
 9:     1            33    12     10    10-(12+13+13+1)  -29
10:     1            33    13     10       10-(13+13+1)  -17
11:     1             3    13     10           10-(13+1   -4
12:     1            44     1     10             10-(1)    9
13:     1             0     3     10                  0    0
14:     1             0     0      0                  0    0


问:
Updating data on destroy with pygtk
I'm using glade and pygtk and I have a window with a treeview with a button that opens a dialog that creates a new entry for the treeview.  I want to update the treeview in the main window when the dialog is destroyed but I can't see a simple way to do this.

--Edit--

Found the answer, I just needed to connect the windows destroy signal

```<code>(dialog).window.connect('destroy', self.foo)
</code>```

答:
The correct approach is to handle the response of the dialog in the main window:

```<code>def on_menu_item_activated(self, widget, data=None):
    dialog = FunkyDialog()
    response = dialog.run()

    if response == gtk.RESPONSE_OK:
        // update treeview
</code>```

Perhaps a better way of doing this would be to use the Observer design pattern. When the user presses Ok, you save your data. This notifies the treeview that a change has been made, which causes it to reload.

Title: Updating data on destroy with pygtk

Body:
I'm using glade and pygtk and I have a window with a treeview with a button that opens a dialog that creates a new entry for the treeview.  I want to update the treeview in the main window when the dialog is destroyed but I can't see a simple way to do this.

--Edit--

Found the answer, I just needed to connect the windows destroy signal

(dialog).window.connect('destroy', self.foo)

Body:
The correct approach is to handle the response of the dialog in the main window:

def on_menu_item_activated(self, widget, data=None):
    dialog = FunkyDialog()
    response = dialog.run()

    if response == gtk.RESPONSE_OK:
        // update treeview

Perhaps a better way of doing this would be to use the Observer design pattern. When the user presses Ok, you save your data. This notifies the treeview that a change has been made, which causes it to reload.


问:
How can I find a range in an array using user input?
```<code>package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}
</code>```

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

```<code>Arrays.asList(a).indexOf(index1)
</code>```

but that will give me -1 every time
And I don't know how to make it wors in the other method

答:
You can do this using simple for loop, use start and stop like:

```<code>double sum=0;
for(int i=start; i<stop; i++)
sum+=array[i];
</code>```

Body:
package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

Arrays.asList(a).indexOf(index1)

but that will give me -1 every time
And I don't know how to make it wors in the other method

Body:
You can do this using simple for loop, use start and stop like:

double sum=0;
for(int i=start; i<stop; i++)
sum+=array[i];


问:
Spring Data JPA NativeQuery like search
I have tried this query:

```<code>@Query(value = "SELECT distinct `id`,`customer name`,`customer number` FROM My_Data WHERE `customer number` like '%"
        + ":customerNumber" + "%'", nativeQuery = true)
public List<MyData> findDistinctByCustomerNumberContainingIgnoreCase(
        @Param("customerNumber") String customerNumber);
</code>```

When I run this,
I get:

java.lang.IllegalArgumentException: Parameter with that position [1]
  did not exist exception.

I want a native query due to some restrictions I have with my table.

答:
You have put the placeholder within parentheses and the engine treats it like a plain string.

If you surround it simply with %, the engine will know to parse that adding the parentherses in the resolved query:

```<code>@Query(value = "SELECT distinct `id`,`customer name`,`customer number` FROM My_Data
       WHERE `customer number` like %:customerNumber%", nativeQuery = true)
</code>```

Title: Spring Data JPA NativeQuery like search

Body:
I have tried this query:

@Query(value = "SELECT distinct `id`,`customer name`,`customer number` FROM My_Data WHERE `customer number` like '%"
        + ":customerNumber" + "%'", nativeQuery = true)
public List<MyData> findDistinctByCustomerNumberContainingIgnoreCase(
        @Param("customerNumber") String customerNumber);

When I run this,
I get:

java.lang.IllegalArgumentException: Parameter with that position [1]
  did not exist exception.

I want a native query due to some restrictions I have with my table.

Body:
You have put the placeholder within parentheses and the engine treats it like a plain string.

If you surround it simply with %, the engine will know to parse that adding the parentherses in the resolved query:

@Query(value = "SELECT distinct `id`,`customer name`,`customer number` FROM My_Data
       WHERE `customer number` like %:customerNumber%", nativeQuery = true)