问:
RCPTT running Java code from the script
I am looking for some way to run some Java code directly from the test script I am writing for our RCP application.

I need to set up a multi-cast socket in the test before clicking a particular button in the application. Something like this:

```<code>MulticastSocket socket = new MulticastSocket();
socket.setNetworkInterface(interfaceTarget);

InetAddress group = InetAddress.getByName("220.2.2.2");
socket.joinGroup(group);
</code>```

I was unable to find any way to do this just wondering if this is possible?

答:
You cannot execute arbitrary Java Code directly (i.e., by writing or referring to Java code in your script), because the AUT runs in a separate process and you only can communicate from the outside.

In other words, the script executes in your RCPTT IDE or test runner process. The actual application under test (AUT) just includes the RCPTT runtime which effectively opens a telnet socket by which it receives commands and sends results via a textual language. Therefore, everything must stick to that protocol and you cannot do anything not specified by the protocol out of the box.

That said, you can call existing Java classes and methods in your AUT via the invoke and invoke-static script commands.

Precondition for invoke is that you are able to retrieve an object reference via the scripting language.
E.g., you can use

```<code><get-something-from-somewhere> | get-object | invoke methodName arg0 arg1 ...
</code>```

Precondition to call a static method via invoke-static is that the method you want to call is accessible from within the AUT. To achieve this (and if your desired method is not part of the AUT already), you can add a test support bundle into your AUT which declares the static method. This way you could implement the code snippet given in your question.

Finally, as the third and most advanced option, you can add your own ECL commands. This is done by implementing an extension point defined by the AUT runtime and including the implementation as bundle in your AUT (similar to the invoke-static approach, but much more flexible, because you can build command chains.

For all three cases, this link serves as a starting point to executing any kind of custom code in the AUT...

Title: RCPTT running Java code from the script

Body:
I am looking for some way to run some Java code directly from the test script I am writing for our RCP application.

I need to set up a multi-cast socket in the test before clicking a particular button in the application. Something like this:

MulticastSocket socket = new MulticastSocket();
socket.setNetworkInterface(interfaceTarget);

InetAddress group = InetAddress.getByName("220.2.2.2");
socket.joinGroup(group);

I was unable to find any way to do this just wondering if this is possible?

Body:
You cannot execute arbitrary Java Code directly (i.e., by writing or referring to Java code in your script), because the AUT runs in a separate process and you only can communicate from the outside.

In other words, the script executes in your RCPTT IDE or test runner process. The actual application under test (AUT) just includes the RCPTT runtime which effectively opens a telnet socket by which it receives commands and sends results via a textual language. Therefore, everything must stick to that protocol and you cannot do anything not specified by the protocol out of the box.

That said, you can call existing Java classes and methods in your AUT via the invoke and invoke-static script commands.

Precondition for invoke is that you are able to retrieve an object reference via the scripting language.
E.g., you can use

<get-something-from-somewhere> | get-object | invoke methodName arg0 arg1 ...

Precondition to call a static method via invoke-static is that the method you want to call is accessible from within the AUT. To achieve this (and if your desired method is not part of the AUT already), you can add a test support bundle into your AUT which declares the static method. This way you could implement the code snippet given in your question.

Finally, as the third and most advanced option, you can add your own ECL commands. This is done by implementing an extension point defined by the AUT runtime and including the implementation as bundle in your AUT (similar to the invoke-static approach, but much more flexible, because you can build command chains.

For all three cases, this link serves as a starting point to executing any kind of custom code in the AUT...


来源: stackexchange

问:
import two external libraries in JniLibs folder( android - NDK )
I'm making a app which needs two library (opencv, dlib)

I have .so file(armeabi-v7a version)

But, I have a problem of importing two libraries in JniLibs folder.

when I import both of them like below, my app doesn't work

JniLibs

------opencv

-------------- armeabi-v7a .so

------dlib

-------------- armeabi-v7a .so

what should I do to use both of libraries?
Thank you in advance.

答: libraries for armeabi-v7a should be put into jniLibs/armeabi-v7a folder directly

ContentLicense: CC BY-SA 3.0


问:
How to inject language OR reference in intellij 15
In intellij 14 i had to use JSON directly added into my string. But have not seen something with intellij 15. Can someone tell me what is a shortcut for that?

Attached reference video from java zone (see video of time 26.20):
http://2015.javazone.no/details.html?talk=0802cb9274ebf62bddf5f8563d99a9a95daf0b5c8c2c39548971855882364ac8

答:
Ctrl+Alt+S

Editor/Intentions

click enable the checkbox "Inject language or reference"

After that you will see "Inject language or reference" options in editor.


问:
Understanding geocoding in Javascript
OK, I have Google maps setup in a jQuery app. (V3).  I can geocode maps all day long.

So, I thought I'd be smart and move the actual geocode function into, well, a function.

Here is the function I am using:

```

    function geocode(address) {
        var self = this;
        geocoder.geocode( { 'address': address }, function(results, status) {
            console.log(status);
            if (status == google.maps.GeocoderStatus.OK) {
                return results[0].geometry.location;
            } else { return null; }
        });
        return "WTF?";
    }
```

The "WTF" is a joke that you will see in a moment.

Now, later on in my code, I try to call the function like so:

```
var start_latlng;
start_latlng = geocode(start_address);

console.log(start_latlng);
```

What I get in the console is:

```
WTF?
OK
```

Notice the "WTF" is BEFORE the "OK" even though I print the "OK" within the function.  (the console.log(status) )

My guess is because the geocoding needs a little time to return and the function continues on before returning the first geocoded value.

Does anyone have any suggestions on how to improve this so that my "start_latlng" contains the expected values?

Thanks for any pointers.

* EDIT **

Here is what I ended up doing.

I call the function like so:

```
        geocode(start_address, function(data) {
            start_latlng = data;
            console.log(start_latlng);
        });
```

And here is the new function (not finished but you get the idea)

```
    function geocode(address, callback) {
        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback(results[0].geometry.location);
            }
            else {
                callback("Error");
            }
        });
    }
```

Works like a charm.  :-)

Thanks for the tips and helping me think better.

答:
What geocode() expects is a callback function as its argument. This means that the result of its call will be passed on to the function you specify when it's ready, asynchronously, and not as a return value.

```<code>function geocode(address) {
    geocoder.geocode( { 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            /* do whatever you need to do with the results here */
        }
        else {
            /* handle the error */
        }
    });
}
</code>```

Title: Understanding geocoding in Javascript

Body:
OK, I have Google maps setup in a jQuery app. (V3).  I can geocode maps all day long.

So, I thought I'd be smart and move the actual geocode function into, well, a function.

Here is the function I am using:

    function geocode(address) {
        var self = this;
        geocoder.geocode( { 'address': address }, function(results, status) {
            console.log(status);
            if (status == google.maps.GeocoderStatus.OK) {
                return results[0].geometry.location;
            } else { return null; }
        });
        return "WTF?";
    }

The "WTF" is a joke that you will see in a moment.

Now, later on in my code, I try to call the function like so:

var start_latlng;
start_latlng = geocode(start_address);

console.log(start_latlng);

What I get in the console is:

WTF?
OK

Notice the "WTF" is BEFORE the "OK" even though I print the "OK" within the function.  (the console.log(status) )

My guess is because the geocoding needs a little time to return and the function continues on before returning the first geocoded value.

Does anyone have any suggestions on how to improve this so that my "start_latlng" contains the expected values?

Thanks for any pointers.

* EDIT **

Here is what I ended up doing.

I call the function like so:

        geocode(start_address, function(data) {
            start_latlng = data;
            console.log(start_latlng);
        });

And here is the new function (not finished but you get the idea)

    function geocode(address, callback) {
        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback(results[0].geometry.location);
            }
            else {
                callback("Error");
            }
        });
    }

Works like a charm.  :-)

Thanks for the tips and helping me think better.

Body:
What geocode() expects is a callback function as its argument. This means that the result of its call will be passed on to the function you specify when it's ready, asynchronously, and not as a return value.

function geocode(address) {
    geocoder.geocode( { 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            /* do whatever you need to do with the results here */
        }
        else {
            /* handle the error */
        }
    });
}

ContentLicense: CC BY-SA 2.5


问:
Store the output of a loop inside a function into a vector or data.frame
I have a data frame df that looks like the following:

```<code>structure(list(sequence = c("CSPPPPSPSPHPRPP", "GEGSPTSPTSPKQPG",
"EAGAPAGSGAPPPAD", "PAPPKPKESKEPENA", "AKPKQQDEDPDGAAE", "GDRGGGTGNEDDDYE"
), group = c("BP", "BP", "BP", "BP", "BP", "BP")), .Names = c("sequence",
"group"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

For all the character variables underdf$sequence I want to get all the possible sub-sets of 7 characters, shifting one character to the right after each iteration.
For that, I created a function called scan_core_OLpeptides. If I apply the following function:

```<code>scan_core_OLpeptides <- function(x) {
  for(i in seq_len(nchar(x)-7+1)){
    print(str_sub(string = x, start = i, end = i+6))
}}
</code>```

I get the following output:

```<code>[1] "CSPPPPS" "GEGSPTS" "EAGAPAG" "PAPPKPK" "AKPKQQD" "GDRGGGT"
[1] "SPPPPSP" "EGSPTSP" "AGAPAGS" "APPKPKE" "KPKQQDE" "DRGGGTG"
[1] "PPPPSPS" "GSPTSPT" "GAPAGSG" "PPKPKES" "PKQQDED" "RGGGTGN"
[1] "PPPSPSP" "SPTSPTS" "APAGSGA" "PKPKESK" "KQQDEDP" "GGGTGNE"
[1] "PPSPSPH" "PTSPTSP" "PAGSGAP" "KPKESKE" "QQDEDPD" "GGTGNED"
[1] "PSPSPHP" "TSPTSPK" "AGSGAPP" "PKESKEP" "QDEDPDG" "GTGNEDD"
[1] "SPSPHPR" "SPTSPKQ" "GSGAPPP" "KESKEPE" "DEDPDGA" "TGNEDDD"
[1] "PSPHPRP" "PTSPKQP" "SGAPPPA" "ESKEPEN" "EDPDGAA" "GNEDDDY"
[1] "SPHPRPP" "TSPKQPG" "GAPPPAD" "SKEPENA" "DPDGAAE" "NEDDDYE"
</code>```

Which is exactly what I want. However, I wanted to store this output into an object, preferably into a vector or into a data.frame.
I thought about storing into a list but it did not work.

答:
We can modify the function to create a list to store the output that comes from each 'i'

```<code>scan_core_OLpeptides <- function(x) {
  x1 <-  vector("list", nrow(df))
  for(i in seq(nchar(x) - 7 +1) ){
   x1[[i]] <- str_sub(string = x, start = i, end = i+6)

  }
   x1
}

scan_core_OLpeptides(df$sequence)
#[[1]]
#[1] "CSPPPPS" "GEGSPTS" "EAGAPAG" "PAPPKPK" "AKPKQQD" "GDRGGGT"

#[[2]]
#[1] "SPPPPSP" "EGSPTSP" "AGAPAGS" "APPKPKE" "KPKQQDE" "DRGGGTG"

#[[3]]
#[1] "PPPPSPS" "GSPTSPT" "GAPAGSG" "PPKPKES" "PKQQDED" "RGGGTGN"

#[[4]]
#[1] "PPPSPSP" "SPTSPTS" "APAGSGA" "PKPKESK" "KQQDEDP" "GGGTGNE"

#[[5]]
#[1] "PPSPSPH" "PTSPTSP" "PAGSGAP" "KPKESKE" "QQDEDPD" "GGTGNED"

#[[6]]
#[1] "PSPSPHP" "TSPTSPK" "AGSGAPP" "PKESKEP" "QDEDPDG" "GTGNEDD"
</code>```

Body:
I have a data frame df that looks like the following:

structure(list(sequence = c("CSPPPPSPSPHPRPP", "GEGSPTSPTSPKQPG",
"EAGAPAGSGAPPPAD", "PAPPKPKESKEPENA", "AKPKQQDEDPDGAAE", "GDRGGGTGNEDDDYE"
), group = c("BP", "BP", "BP", "BP", "BP", "BP")), .Names = c("sequence",
"group"), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))

For all the character variables underdf$sequence I want to get all the possible sub-sets of 7 characters, shifting one character to the right after each iteration.
For that, I created a function called scan_core_OLpeptides. If I apply the following function:

scan_core_OLpeptides <- function(x) {
  for(i in seq_len(nchar(x)-7+1)){
    print(str_sub(string = x, start = i, end = i+6))
}}

I get the following output:

[1] "CSPPPPS" "GEGSPTS" "EAGAPAG" "PAPPKPK" "AKPKQQD" "GDRGGGT"
[1] "SPPPPSP" "EGSPTSP" "AGAPAGS" "APPKPKE" "KPKQQDE" "DRGGGTG"
[1] "PPPPSPS" "GSPTSPT" "GAPAGSG" "PPKPKES" "PKQQDED" "RGGGTGN"
[1] "PPPSPSP" "SPTSPTS" "APAGSGA" "PKPKESK" "KQQDEDP" "GGGTGNE"
[1] "PPSPSPH" "PTSPTSP" "PAGSGAP" "KPKESKE" "QQDEDPD" "GGTGNED"
[1] "PSPSPHP" "TSPTSPK" "AGSGAPP" "PKESKEP" "QDEDPDG" "GTGNEDD"
[1] "SPSPHPR" "SPTSPKQ" "GSGAPPP" "KESKEPE" "DEDPDGA" "TGNEDDD"
[1] "PSPHPRP" "PTSPKQP" "SGAPPPA" "ESKEPEN" "EDPDGAA" "GNEDDDY"
[1] "SPHPRPP" "TSPKQPG" "GAPPPAD" "SKEPENA" "DPDGAAE" "NEDDDYE"

Which is exactly what I want. However, I wanted to store this output into an object, preferably into a vector or into a data.frame.
I thought about storing into a list but it did not work.

Body:
We can modify the function to create a list to store the output that comes from each 'i'

scan_core_OLpeptides <- function(x) {
  x1 <-  vector("list", nrow(df))
  for(i in seq(nchar(x) - 7 +1) ){
   x1[[i]] <- str_sub(string = x, start = i, end = i+6)

  }
   x1
}

scan_core_OLpeptides(df$sequence)
#[[1]]
#[1] "CSPPPPS" "GEGSPTS" "EAGAPAG" "PAPPKPK" "AKPKQQD" "GDRGGGT"

#[[2]]
#[1] "SPPPPSP" "EGSPTSP" "AGAPAGS" "APPKPKE" "KPKQQDE" "DRGGGTG"

#[[3]]
#[1] "PPPPSPS" "GSPTSPT" "GAPAGSG" "PPKPKES" "PKQQDED" "RGGGTGN"

#[[4]]
#[1] "PPPSPSP" "SPTSPTS" "APAGSGA" "PKPKESK" "KQQDEDP" "GGGTGNE"

#[[5]]
#[1] "PPSPSPH" "PTSPTSP" "PAGSGAP" "KPKESKE" "QQDEDPD" "GGTGNED"

#[[6]]
#[1] "PSPSPHP" "TSPTSPK" "AGSGAPP" "PKESKEP" "QDEDPDG" "GTGNEDD"


问:
AngularJS is not seeing my js in the Scripts folder
Good morning people.
I'm studying AngularJS and found a situation that I can not solve.
I use Visual Studio 2013 and am creating an empty project, and including the step-by-step codes.

When you rotate the application, the angle is not working properly.

Fig1

Folder

Please help me.

答:
This error in the figure occurs because success was deprecated since angular version 1.4. instead of success use then to catch the response

```<code>$http.get('url')
.then(function(response){
   console.log(response.data) // result
})
</code>```

Body:
This error in the figure occurs because success was deprecated since angular version 1.4. instead of success use then to catch the response

$http.get('url')
.then(function(response){
   console.log(response.data) // result
})


问:
How to save drag/drop coordinates back to angular model?
My code allows for dragging and dropping of form fields overlaying an page image.  I'm using Kendo-ui for the drag/drop but that's not critical to the answer, I don't think, and the demo is overly simplified and doesn't contain the image.  I need to be able to change the angular model's coordinates to reflect the dropped location so I can save it.  The meat of my question is HOW to update the model.  What's the most efficient way of doing this since I can possibly have hundreds of fields?  Is it possible to bind to the left/bottom CSS coordinates?  Should I update the CSS manually using jQuery and then update the model?

Here's the plunker with my code

INDEX.HTML

```<code><!DOCTYPE html>
<html ng-app="app">

  <head>
    <title></title>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.common-bootstrap.min.css" />
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.bootstrap.min.css" />
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.bootstrap.mobile.min.css" />

    <script src="https://kendo.cdn.telerik.com/2016.2.714/js/jquery.min.js"></script>
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
    <script src="https://kendo.cdn.telerik.com/2016.2.714/js/kendo.all.min.js"></script>

    <script id="page-template" type="text/ng-template">
      <div class="page" kendo-droptarget style="{{ 'width:' + (p.width + 2) + 'px; height:' + (p.height + 2) + 'px;' }}" ng-repeat="p in model.transaction.selectedDocument.pages">
            <div class="field" data-fieldname="f.fieldName" kendo-draggable k-hint="model.draggableHint" k-dragstart="model.onDragStart" k-dragend="model.onDragEnd" ng-repeat="f in p.fields" style="{{ 'left:' + f.left + 'px;bottom:' + f.bottom + 'px;width:' + f.width + 'px;height:' + f.height + 'px;' }}">
                <div></div>
            </div>
        </div>
        ```{{ model | json }}```
    </script>

    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <page-image-component></page-image-component>
  </body>

</html>
</code>```

SCRIPT.JS

```<code>// Code goes here
console.clear();

function pageImageController(TransactionFactory) {
    var model = this;
    model.transaction = TransactionFactory;

    model.draggableHint = function (e) {
        return e.clone();
    }

    model.onDragStart = function (e) {
        console.log(e);
        e.currentTarget.hide();
    }

    model.onDragEnd = function (e) {
        console.log(e);
        //e.currentTarget.css("left", "0px").css("top", "0px");
        var field = e.currentTarget[0];

        console.log(e.currentTarget)

        e.currentTarget.show();
    }
}

var app = angular.module("app", ["kendo.directives"]);

app.factory('TransactionFactory', function () {
    var transaction = {
        selectedDocument: {
          fileName: "my.pdf",
          pages: [{
            pageNumber: 1,
            width: 400,
            height: 500,
            fields: [
              {
                fieldName: "my field 1",
                width: 75,
                height: 13,
                left: 50,
                bottom: 300,
                instance: 1
              },
              {
                fieldName: "another field 1",
                width: 65,
                height: 13,
                left: 200,
                bottom: 440,
                instance: 1
              },
            ]
          }]
        }
    };

    return transaction;
});

app.component("pageImageComponent", {
    template: $("#page-template").html(),
    controllerAs: "model",
    controller: ["TransactionFactory", pageImageController]
});
</code>```

STYLE.CSS

```<code>/* Styles go here */

.page
{
  border: 1px solid black;
  position: relative;
}

.field
{
  background-color: #ddd;
  position: absolute;
}
</code>```

答:
I think I figured it out and I think it's efficient enough for rock and roll.

Here's the Plunker

```<code>function pageImageController(TransactionFactory) {
    var model = this;
    model.transaction = TransactionFactory;

    var tempLeft = 0;
    var tempTop = 0;

    model.draggableHint = function (e) {
        return e.clone();
    }

    model.onDragStart = function (e) {
        //console.log(e);
        e.currentTarget.hide();
    }

    model.onDrop = function (e) {
      tempLeft = e.draggable.hint.offset().left -9;
      tempTop = e.draggable.hint.offset().top +2;

      console.log(e.draggable);
    }

    model.onDragEnd = function (e) {
      //console.log(e);
      var field = e.currentTarget[0];

      //console.log(field)

      var fieldIndex = field.attributes['data-fieldindex'].value;
      var pageIndex = field.attributes['data-pageindex'].value;

      //console.log(fieldIndex);
      //console.log(pageIndex);
      var tempBottom = model.transaction.selectedDocument.pages[pageIndex].height - tempTop;
      model.transaction.selectedDocument.pages[pageIndex].fields[fieldIndex].left = tempLeft;
      model.transaction.selectedDocument.pages[pageIndex].fields[fieldIndex].bottom = tempBottom;

      e.currentTarget.css("left", tempLeft + "px").css("bottom", tempBottom + "px");

      e.currentTarget.show();
    }
}
</code>```

Body:
My code allows for dragging and dropping of form fields overlaying an page image.  I'm using Kendo-ui for the drag/drop but that's not critical to the answer, I don't think, and the demo is overly simplified and doesn't contain the image.  I need to be able to change the angular model's coordinates to reflect the dropped location so I can save it.  The meat of my question is HOW to update the model.  What's the most efficient way of doing this since I can possibly have hundreds of fields?  Is it possible to bind to the left/bottom CSS coordinates?  Should I update the CSS manually using jQuery and then update the model?

Here's the plunker with my code

INDEX.HTML

<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.common-bootstrap.min.css" />
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.bootstrap.min.css" />
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.bootstrap.mobile.min.css" />

    <link rel="stylesheet" href="style.css" />

    <page-image-component></page-image-component>

SCRIPT.JS

// Code goes here
console.clear();

function pageImageController(TransactionFactory) {
    var model = this;
    model.transaction = TransactionFactory;

    model.draggableHint = function (e) {
        return e.clone();
    }

    model.onDragStart = function (e) {
        console.log(e);
        e.currentTarget.hide();
    }

    model.onDragEnd = function (e) {
        console.log(e);
        //e.currentTarget.css("left", "0px").css("top", "0px");
        var field = e.currentTarget[0];

        console.log(e.currentTarget)

        e.currentTarget.show();
    }
}

var app = angular.module("app", ["kendo.directives"]);

app.factory('TransactionFactory', function () {
    var transaction = {
        selectedDocument: {
          fileName: "my.pdf",
          pages: [{
            pageNumber: 1,
            width: 400,
            height: 500,
            fields: [
              {
                fieldName: "my field 1",
                width: 75,
                height: 13,
                left: 50,
                bottom: 300,
                instance: 1
              },
              {
                fieldName: "another field 1",
                width: 65,
                height: 13,
                left: 200,
                bottom: 440,
                instance: 1
              },
            ]
          }]
        }
    };

    return transaction;
});

app.component("pageImageComponent", {
    template: $("#page-template").html(),
    controllerAs: "model",
    controller: ["TransactionFactory", pageImageController]
});

STYLE.CSS

/* Styles go here */

.page
{
  border: 1px solid black;
  position: relative;
}

.field
{
  background-color: #ddd;
  position: absolute;
}

Body:
I think I figured it out and I think it's efficient enough for rock and roll.

Here's the Plunker

function pageImageController(TransactionFactory) {
    var model = this;
    model.transaction = TransactionFactory;

    var tempLeft = 0;
    var tempTop = 0;

    model.draggableHint = function (e) {
        return e.clone();
    }

    model.onDragStart = function (e) {
        //console.log(e);
        e.currentTarget.hide();
    }

    model.onDrop = function (e) {
      tempLeft = e.draggable.hint.offset().left -9;
      tempTop = e.draggable.hint.offset().top +2;

      console.log(e.draggable);
    }

    model.onDragEnd = function (e) {
      //console.log(e);
      var field = e.currentTarget[0];

      //console.log(field)

      var fieldIndex = field.attributes['data-fieldindex'].value;
      var pageIndex = field.attributes['data-pageindex'].value;

      //console.log(fieldIndex);
      //console.log(pageIndex);
      var tempBottom = model.transaction.selectedDocument.pages[pageIndex].height - tempTop;
      model.transaction.selectedDocument.pages[pageIndex].fields[fieldIndex].left = tempLeft;
      model.transaction.selectedDocument.pages[pageIndex].fields[fieldIndex].bottom = tempBottom;

      e.currentTarget.css("left", tempLeft + "px").css("bottom", tempBottom + "px");

      e.currentTarget.show();
    }
}


问:
Get latest shape in ArrayList to paint on top of other shapes - Java
Since this is schoolwork I do not want a complete solution but rather a push in the right direction on what I should be looking at (hence why there is no code).

I got a class that handle mouse input. From that class I check if user hold down mouse button on a shape and then set that shape to be the active shape. While the user drags the shape the shape moves along with it and changes position accordingly. Once the mouse is released the selectedShape is set to null and the panel is being repainted.

I want that the selectedShape is on top of all the other shapes, so if the selected shape is being dragged over any other shape it is infront.

From what I understand the repaint() method just repaint them as they appear in the ArrayList and I need to use another method to paint that shape at top (visually speaking).

Where would I go about to add this functionality? In the MouseHandler class?

Classes included that are relevant:
MyShape - Parent class
 Triangle, Square, Circle - Child - has its own draw(g) method and setPosition
MouseHandler - mouse movement and calls each shape to set new position.
MyShapeHandler - add/remove shapes from list
Panel - create instance of shapes and add to ArrayList using MyShapeHandler help method addShape. Draws each shape in ArrayList using drawComponent(g).
Window - JFrame that adds panel

答: You can try to rearrange the list so that the desired shape is first/last. Experiment and see if the shape's index in the list corresponds to its location in the front or back on the screen.</p>


问:
Compare columns in 2 files, append data for shared items and print the non shared items of the first file
I have found similar questions as mine but none helped me with my specific problem (and i'm not quite sure whether there actually is such an easy solution..)

I have two files:

file1:

```<code>a b c
d e f
g h i
</code>```

file2:

```<code>a b x y z
d e x
f h i
</code>```

Desired Output:

```<code>a b c x y z
d e f x
g h i
</code>```

So, I want all the rows and columns from file 1 and additionally, if there is a match of the first two columns in file 2, I want to append the rest of those columns (from file 2) to the ones in file 1 and write it in a new file.

I have tried with awk but so far I have only managed to append the columns for those rows that have a match, but the other ones (in my example the "g,h,i" row) is not printed.
Another issue seems to be that the items in file 2 do not always have the same amount of columns.

Does anyone have an idea how to solve this?

Thank you!

答:
Use the following approach:

```<code>awk 'FNR==NR{k=$1$2; $1=$2=""; a[k]=$0; next}
     { if($1$2 in a){print $0a[$1$2] } else print $0}' file2 file1 | tr -s ' '
</code>```

The output:

```<code>a b c x y z
d e f x
g h i
</code>```

FNR==NR - ensures performing the first file

k=$1$2; - k is a key for associative array which accumulates all column values from the second file except the first two columns(as they become a key/hash). For ex. for the first file2 line the array will be indexeed as a['ab']='x y z'

Body:
I have found similar questions as mine but none helped me with my specific problem (and i'm not quite sure whether there actually is such an easy solution..)

I have two files:

file1:

a b c
d e f
g h i

file2:

a b x y z
d e x
f h i

Desired Output:

a b c x y z
d e f x
g h i

So, I want all the rows and columns from file 1 and additionally, if there is a match of the first two columns in file 2, I want to append the rest of those columns (from file 2) to the ones in file 1 and write it in a new file.

I have tried with awk but so far I have only managed to append the columns for those rows that have a match, but the other ones (in my example the "g,h,i" row) is not printed.
Another issue seems to be that the items in file 2 do not always have the same amount of columns.

Does anyone have an idea how to solve this?

Thank you!

Body:
Use the following approach:

awk 'FNR==NR{k=$1$2; $1=$2=""; a[k]=$0; next}
     { if($1$2 in a){print $0a[$1$2] } else print $0}' file2 file1 | tr -s ' '

The output:

a b c x y z
d e f x
g h i

FNR==NR - ensures performing the first file

k=$1$2; - k is a key for associative array which accumulates all column values from the second file except the first two columns(as they become a key/hash). For ex. for the first file2 line the array will be indexeed as a['ab']='x y z'


问:
Angular 2 i18n-internationalisation : message.xlf is empty
I 've been following the angular cookbook for internationalization : https://angular.io/docs/ts/latest/cookbook/i18n.html#!#angular-i18n

after a long dependency debugging time, i manage to generate a message.xlf file, without any error but,
nothing has been extracted, the xlf is empty.

it seems to not see the i18n in my tags...

is there anyone who managed to solve this?

message.xlf

<?xml version="1.0" encoding="UTF-8" ?>
    <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
      <file source-language="en" datatype="plaintext" original="ng2.template">

      </file>
    </xliff>

答:
In my case thing was in that I have to start ng-xi18n with parametr '-p path/to/tsconfig.json', because my ts-source files are not in the root, they are in separate directory (src/client/, I've used angular-seed@mgechev to start project from scratch).
I mean my i18n task in package.json looks like:

```<code>"i18n": "ng-xi18n -p src/client/tsconfig.json"
</code>```

then

```<code>$ npm run i18n
</code>```

will generate messages.xlf in src/client directory.

Body:
In my case thing was in that I have to start ng-xi18n with parametr '-p path/to/tsconfig.json', because my ts-source files are not in the root, they are in separate directory (src/client/, I've used angular-seed@mgechev to start project from scratch).
I mean my i18n task in package.json looks like:

"i18n": "ng-xi18n -p src/client/tsconfig.json"

then

$ npm run i18n

will generate messages.xlf in src/client directory.


问:
simple IOS code with OpenCV can run on simulator but fail at real device
I am a beginner for IOS and using OpenCV in IOS, I drag opencv2.framework into my project, as codes shown below:

```<code>#import "opencv2/opencv.hpp"
#import "opencv2/highgui/ios.h"

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIImage* a = [UIImage imageNamed:@"jay1.jpg"];

    cv::Mat b;
    UIImageToMat(a, b);
    cv::cvtColor(b, b, CV_BGR2GRAY);
    UIImage* c = MatToUIImage(b);
    self.view.backgroundColor = [UIColor colorWithPatternImage:c];

    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Welcome to OpenCV" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
</code>```

This code can run successfully on Simulator. While I run it on a real device, I got a error, and I can't get further details (while clicking this error message, no response).

```<code>Apple Mach-O Linker (ld) Error:
error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

My Xcode(8.3) and IOS(10.3) device are all the latest versions, and OpenCV version is 2.4.9. I had also drag some necessary frameworks such as:

```<code>QuartzCore.framework
CoreVideo.framework
CoreMedia.framework
CoreImage.framework
AVFoundation.framework
AssetsLibrary.framework
Accelerate.framework
CoreGraphics.framework
Foundation.framework
UIKit.framework
opencv2.framework
</code>```

Could anybody tell me how to run these codes on my real device. Thank you for helping me.

答: It's because your opencv2.framework was built with only x86 and x86-64 architectures. You need to either find one that includes armv7, armv7s (for 32-bit iPhones) and arm64 (for iphone 6 and later), or build one from source (see instruction).

Body:
I am a beginner for IOS and using OpenCV in IOS, I drag opencv2.framework into my project, as codes shown below:

#import "opencv2/opencv.hpp"
#import "opencv2/highgui/ios.h"

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIImage* a = [UIImage imageNamed:@"jay1.jpg"];

    cv::Mat b;
    UIImageToMat(a, b);
    cv::cvtColor(b, b, CV_BGR2GRAY);
    UIImage* c = MatToUIImage(b);
    self.view.backgroundColor = [UIColor colorWithPatternImage:c];

    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Welcome to OpenCV" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

This code can run successfully on Simulator. While I run it on a real device, I got a error, and I can't get further details (while clicking this error message, no response).

Apple Mach-O Linker (ld) Error:
error: linker command failed with exit code 1 (use -v to see invocation)

My Xcode(8.3) and IOS(10.3) device are all the latest versions, and OpenCV version is 2.4.9. I had also drag some necessary frameworks such as:

QuartzCore.framework
CoreVideo.framework
CoreMedia.framework
CoreImage.framework
AVFoundation.framework
AssetsLibrary.framework
Accelerate.framework
CoreGraphics.framework
Foundation.framework
UIKit.framework
opencv2.framework

Could anybody tell me how to run these codes on my real device. Thank you for helping me.


问:
Angular 2 with CLI - Component template from different server
I have a specific use case where the component's html template can load from multiple places.

For example,

```<code>@Component({
  selector: 'app-home',
  template: require('http://xyz/home.component.html'),  **// This can be from local or any other server**
  styleUrls: [require('http://xyz/home.component.css')],
})
</code>```

Need help in understanding how can I go about this or what are my alternatives.

Thanks

答:
You can't provide template url to component that points not to local path and you can't require not from local path, but still you can achieve what you want by creating component dynamically from template content.

As downside, you will have to always depend on Angular JIT compiler instead of AoT compiler (see more here https://angular.io/docs/ts/latest/cookbook/aot-compiler.html). Also you will need to have CORS requests enabled on your server.

You can do what you want like next:

Use http (https://angular.io/docs/ts/latest/guide/server-communication.html) to fetch your template content from other server.

Compile template like it is recommended in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?.

Write selector of your dynamic component somewhere inside application in template where you want to include it (i.e. something like <dynamic-detail></dynamic-detail>).

See this Plunker for example implementation (can be cleaned and improved further): http://plnkr.co/edit/ZLYGBRl41SlTNoX8xQeD

Remember, this is not intended way of how Angular2 should be used, so beware using this in production.

Body:
I have a specific use case where the component's html template can load from multiple places.

For example,

@Component({
  selector: 'app-home',
  template: require('http://xyz/home.component.html'),  **// This can be from local or any other server**
  styleUrls: [require('http://xyz/home.component.css')],
})

Need help in understanding how can I go about this or what are my alternatives.

Thanks


问:
Binding data to a dropdown using angularjs
I have a typescript controller with an init method below. I am able to get all the data I want in the messageresult
which is good.

```<code>         init() {
                     this.accountLocationService.getAccountLocationCollection(this.customerNumber)
                        .success(messageresult => {
                            this.acctLocationCollection = messageresult;
                            //alert(this.acctLocationCollection.accountlocation[0].aliasName);
                        })
                        .error(error => {
                            alert(error);
                        });
                }
</code>```

The acctLocationCollection can have two or more  objects and I need to bind all the values of the
aliasName in a dropdown below.
How can I achive this ? This is my first AngularJs project.

```<code>        <div id="acctDetail">
            <p>Select an Account:</p>
            <div class="selectAccount">
                <select class="selAccounts" name="DeliverToCustomerNumber" ng-change="" id="DeliverToCustomerNumber"
                        ng-options="ac for ac in alc.acctLocationCollection.aliasName">
                </select>
            </div>
            <div id="address">
                <dl>
                    <dd class="acctName">{{alc.acctLocationCollection.DeliverToCompanyName}}</dd>
                    <dd class="acctNo">{{alc.acctLocationCollection.DeliverToCustomerNumber}}</dd>
                </dl>
            </div>
        </div>
</code>```

Data looks like this in console.log

```<code>    object
    accountlocation:Array[2]
    0:object
      aliasName:"1234"
      deliverToCustomerNumber: "25235"

    1:object
      aliasName:"2345"
      deliverToCustomerNumber: "23523"
</code>```

答:
You don't have an ng-model on your select so I will just assume you want to store the object from your acctLocationCollection. To do this you simply need to structure your ng-options as follows:

```<code><select class="selAccounts"
        name="DeliverToCustomerNumber"
        id="DeliverToCustomerNumber"
        ng-model="alc.selectedAcctLocation"
        ng-options="ac as ac.aliasName for ac in alc.acctLocationCollection">
</select>
</code>```

angular.module('app', [])
  .controller('ctrl', function() {
    this.selectedAcctLocation = {};
    this.acctLocation = [{
      aliasName: "1234",
      deliverToCustomerNumber: "25235"
    }, {
      aliasName: "2345",
      deliverToCustomerNumber: "23523"
    }];
    console.log(this.acctLocation);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as alc">
  By object: <select ng-model="alc.selectedAcctLocation" ng-options="ac as ac.aliasName for ac in alc.acctLocation"></select><br/>
  By (key,value): <select ng-model="alc.selectedAcctLocation" ng-options="value as value.aliasName for (key,value) in alc.acctLocation"></select>
  <div style="margin-top:10px;">
    alc.acctLocation:
    <ul>
      <li ng-repeat="(key,value) in alc.acctLocation">{{key}}: {{value}}</li>
    </ul>
  </div>
  <div>selectedAcctLocation: {{alc.selectedAcctLocation | json}}</div>
</div></code>```

Body:
I have a typescript controller with an init method below. I am able to get all the data I want in the messageresult
which is good.

         init() {
                     this.accountLocationService.getAccountLocationCollection(this.customerNumber)
                        .success(messageresult => {
                            this.acctLocationCollection = messageresult;
                            //alert(this.acctLocationCollection.accountlocation[0].aliasName);
                        })
                        .error(error => {
                            alert(error);
                        });
                }

The acctLocationCollection can have two or more  objects and I need to bind all the values of the
aliasName in a dropdown below.
How can I achive this ? This is my first AngularJs project.

Select an Account:

                <select class="selAccounts" name="DeliverToCustomerNumber" ng-change="" id="DeliverToCustomerNumber"
                        ng-options="ac for ac in alc.acctLocationCollection.aliasName">
                </select>

{{alc.acctLocationCollection.DeliverToCompanyName}}

{{alc.acctLocationCollection.DeliverToCustomerNumber}}

Data looks like this in console.log

    object
    accountlocation:Array[2]
    0:object
      aliasName:"1234"
      deliverToCustomerNumber: "25235"

    1:object
      aliasName:"2345"
      deliverToCustomerNumber: "23523"

Body:
You don't have an ng-model on your select so I will just assume you want to store the object from your acctLocationCollection. To do this you simply need to structure your ng-options as follows:

<select class="selAccounts"
        name="DeliverToCustomerNumber"
        id="DeliverToCustomerNumber"
        ng-model="alc.selectedAcctLocation"
        ng-options="ac as ac.aliasName for ac in alc.acctLocationCollection">
</select>

angular.module('app', [])
  .controller('ctrl', function() {
    this.selectedAcctLocation = {};
    this.acctLocation = [{
      aliasName: "1234",
      deliverToCustomerNumber: "25235"
    }, {
      aliasName: "2345",
      deliverToCustomerNumber: "23523"
    }];
    console.log(this.acctLocation);
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as alc">
  By object: <select ng-model="alc.selectedAcctLocation" ng-options="ac as ac.aliasName for ac in alc.acctLocation"></select><br/>
  By (key,value): <select ng-model="alc.selectedAcctLocation" ng-options="value as value.aliasName for (key,value) in alc.acctLocation"></select>
  <div style="margin-top:10px;">
    alc.acctLocation:
    <ul>
      <li ng-repeat="(key,value) in alc.acctLocation">{{key}}: {{value}}</li>
    </ul>
  </div>
  <div>selectedAcctLocation: {{alc.selectedAcctLocation | json}}</div>
</div>


问:
Remove all punctuation from string, except if it's between digits
I have a text that contains words and numbers. I'll give a representative example of the text:

```<code>string = "This is a 1example of the text. But, it only is 2.5 percent of all data"
</code>```

I'd like to convert it to something like:

```<code>"This is a  1 example of the text But it only is  2.5  percent of all data"
</code>```

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

```<code>item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item
</code>```

The result is :

```<code> >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"
</code>```

I'm almost there but can't figure out that last peace.

答:
I tried this and it worked very well.

a = "This is a 1example of the text. But, it only is 2.5 percent of all data"
 a.replace(". ", " ").replace(", "," ")

Notice that, in replace function there is space after punctuation. I just replaced punctuation and space with only space.

Body:
I have a text that contains words and numbers. I'll give a representative example of the text:

string = "This is a 1example of the text. But, it only is 2.5 percent of all data"

I'd like to convert it to something like:

"This is a  1 example of the text But it only is  2.5  percent of all data"

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item

The result is :

 >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"

I'm almost there but can't figure out that last peace.


问:
C# USB eToken signature and validation issue
I have an x509 certificate with a public and private key that is stored on a safenet usb token.

I have some data I want to sign.  I need to use the public key of the certificate to verify the signature.

Ultimate code doing the signing with my own self signed certificate:

```<code>RSACryptoServiceProvider rsa1 = (RSACryptoServiceProvider)useCertificate.PrivateKey;
byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
</code>```

And the code to verify using the public key of the certificate:

```<code>RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);
</code>```

With the self signed certificate this works fine.  The signature I get back is 256

Bytes.

With the token using this code to obtain the signature and then verify it, I get only 128 Byte signature and the verify fails:

```<code>CspParameters csp = new CspParameters(1, "SafeNet RSA CSP");
csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
csp.KeyNumber = (int)KeyNumber.Signature;
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);
</code>```

Verify code same as above.

I note that the certificate I want to use is the default in the token.  Why am I only getting a 128 Byte signature back instead of 256?  I suspect that is why it won't verify.

Do I need some other parameters and settings in my csp?

Thanks

* Update based on comments *

It's clear that I am using 1024 bits when I specify the csp.keyNumber = (int)KeyNumber.Signature - but this is the only way the token actually returns anything.  Even though the token key size is 2048 bits and the key specification is AT_KEYEXCHANGE.  When I use the exchange keynumber which I think is actually correct, then when I try to compute a signature I am prompted to login, but then I get an exception "The parameter is invalid".   So I need one of 2 things as far as I can see:

1 - how to use the public key to verify the signature using 1024 bits (without the token - we need to verify on a machine without the token).

or

2 - how to set whatever is incorrect so that we can get passed the exception -- which I think is the better idea.

Does anyone have any advice on what I can do about this exception or what might be causing it?

Full exception details below:

HResult = -2147024809
Message = The parameter is incorrect.
Stack Trace

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, String str)
   at TE.Program.Main(String[] args) in z:\Work\compusolve\enctest\TE\TE\Program.cs:line 77

答:
I have to challenge your assertion that it's actually the default key container key (you may have caused that one to be created the first time your code ran, since you didn't assert the UseExistingKey flag).

Assuming the certificate is in your cert store, run certutil -user -silent store my and find the certificate entry and check the Key Container value:

```<code>================ Certificate 11 ================
Serial Number: 0123456789abcdeffedcba9876543210
Issuer: CN=Intermediate Certificate Authority
 NotBefore: 10/21/2016 7:26 AM
 NotAfter: 10/21/2017 7:26 AM
Subject: CN=bartonjs
Non-root Certificate
Template:
Cert Hash(sha1): 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14
  Key Container = le-Smartcard-987abcdf-6332-43-16531
  Provider = Microsoft Base Smart Card Crypto Provider
</code>```

If you copy/paste whatever value that is and use it as the key container name your signatures will probably start being the correct size.

(If your certificate is in the machine store instead of the user store, omit the -user option)

Body:
I have an x509 certificate with a public and private key that is stored on a safenet usb token.

I have some data I want to sign.  I need to use the public key of the certificate to verify the signature.

Ultimate code doing the signing with my own self signed certificate:

RSACryptoServiceProvider rsa1 = (RSACryptoServiceProvider)useCertificate.PrivateKey;
byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));

And the code to verify using the public key of the certificate:

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);

With the self signed certificate this works fine.  The signature I get back is 256

Bytes.

With the token using this code to obtain the signature and then verify it, I get only 128 Byte signature and the verify fails:

CspParameters csp = new CspParameters(1, "SafeNet RSA CSP");
csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
csp.KeyNumber = (int)KeyNumber.Signature;
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);

Verify code same as above.

I note that the certificate I want to use is the default in the token.  Why am I only getting a 128 Byte signature back instead of 256?  I suspect that is why it won't verify.

Do I need some other parameters and settings in my csp?

Thanks

* Update based on comments *

It's clear that I am using 1024 bits when I specify the csp.keyNumber = (int)KeyNumber.Signature - but this is the only way the token actually returns anything.  Even though the token key size is 2048 bits and the key specification is AT_KEYEXCHANGE.  When I use the exchange keynumber which I think is actually correct, then when I try to compute a signature I am prompted to login, but then I get an exception "The parameter is invalid".   So I need one of 2 things as far as I can see:

1 - how to use the public key to verify the signature using 1024 bits (without the token - we need to verify on a machine without the token).

or

2 - how to set whatever is incorrect so that we can get passed the exception -- which I think is the better idea.

Does anyone have any advice on what I can do about this exception or what might be causing it?

Full exception details below:

HResult = -2147024809
Message = The parameter is incorrect.
Stack Trace

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, String str)
   at TE.Program.Main(String[] args) in z:\Work\compusolve\enctest\TE\TE\Program.cs:line 77

Body:
I have to challenge your assertion that it's actually the default key container key (you may have caused that one to be created the first time your code ran, since you didn't assert the UseExistingKey flag).

Assuming the certificate is in your cert store, run certutil -user -silent store my and find the certificate entry and check the Key Container value:

================ Certificate 11 ================
Serial Number: 0123456789abcdeffedcba9876543210
Issuer: CN=Intermediate Certificate Authority
 NotBefore: 10/21/2016 7:26 AM
 NotAfter: 10/21/2017 7:26 AM
Subject: CN=bartonjs
Non-root Certificate
Template:
Cert Hash(sha1): 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14
  Key Container = le-Smartcard-987abcdf-6332-43-16531
  Provider = Microsoft Base Smart Card Crypto Provider

If you copy/paste whatever value that is and use it as the key container name your signatures will probably start being the correct size.

(If your certificate is in the machine store instead of the user store, omit the -user option)


问:
Angular 2 Cross Doamin Call in local servers is not working
My Angular 2 application is running at 8100 port and API project which is build using node and express running at different port 3003. API project is not a rest API project.

When I try to call one of the API from Rest Client or Postman I'm getting the response.

Even if try to call API from the node, it is working fine.

While making API call from Angular 2 project it is showing 404 error.

Angular 2 code -

```<code>getApplications() {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('cache-control', 'no-cache');
        headers.append('Access-Control-Allow-Origin', '*');

        return this.http.post('http://localhost:3003/applications/list', {}, {})
            .map(res => res.json());
}
</code>```

NodeJS working request -

```<code>var request = require("request");

var options = {
  method: 'POST',
  url: 'http://localhost:3003/application/list',
  headers:
   {
     'cache-control': 'no-cache',
     'content-type': 'application/json'
   }
 };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
</code>```

Postman Request -

答:
I guess you made a typo:

Browser:
http://localhost:3003/application/list

In Angular:
http://localhost:3003/applications/list

Body:
My Angular 2 application is running at 8100 port and API project which is build using node and express running at different port 3003. API project is not a rest API project.

When I try to call one of the API from Rest Client or Postman I'm getting the response.

Even if try to call API from the node, it is working fine.

While making API call from Angular 2 project it is showing 404 error.

Angular 2 code -

getApplications() {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('cache-control', 'no-cache');
        headers.append('Access-Control-Allow-Origin', '*');

        return this.http.post('http://localhost:3003/applications/list', {}, {})
            .map(res => res.json());
}

NodeJS working request -

var request = require("request");

var options = {
  method: 'POST',
  url: 'http://localhost:3003/application/list',
  headers:
   {
     'cache-control': 'no-cache',
     'content-type': 'application/json'
   }
 };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

Postman Request -


问:
Aurelia iterate over map where keys are strings
I'm having trouble getting Aurelia to iterate over a map where the keys are strings (UUIDs).

Here is an example of the data I'm getting from an API running somewhere else:

```<code>my_data = {
  "5EI22GER7NE2XLDCPXPT5I2ABE": {
    "my_property": "a value"
  },
  "XWBFODLN6FHGXN3TWF22RBDA7A": {
    "my_property": "another value"
  }
}
</code>```

And I'm trying to use something like this:

```<code><template>
<div class="my_class">
    <ul class="list-group">
        <li repeat.for="[key, value] of my_data" class="list-group-item">
                <span>${key} - ${value.my_property}</span>
        </li>
    </ul>
</div>
</template>
</code>```

But Aurelia is telling me that Value for 'my_data' is non-repeatable.

I've found various answer by googling, but they have not been clearly explained or incomplete. Either I'm googling wrong or a good SO question and answer is needed.

答:
As another resource to the one supplied by ry8806, I also use a Value Converter:

```<code>export class KeysValueConverter {
  toView(obj) {
    if (obj !== null && typeof obj === 'object') {
      return Reflect.ownKeys(obj).filter(x => x !== '__observers__');
    } else {
      return null;
    }
  }
}
</code>```

It can easily be used to do what you're attempting, like this:

```<code><template>
<div class="my_class">
    <ul class="list-group">
        <li repeat.for="key of my_data | keys" class="list-group-item">
                <span>${key} - ${my_data[key]}</span>
        </li>
    </ul>
</div>
</template>
</code>```

Body:
I'm having trouble getting Aurelia to iterate over a map where the keys are strings (UUIDs).

Here is an example of the data I'm getting from an API running somewhere else:

my_data = {
  "5EI22GER7NE2XLDCPXPT5I2ABE": {
    "my_property": "a value"
  },
  "XWBFODLN6FHGXN3TWF22RBDA7A": {
    "my_property": "another value"
  }
}

And I'm trying to use something like this:

<template>

                ${key} - ${value.my_property}

</template>

But Aurelia is telling me that Value for 'my_data' is non-repeatable.

I've found various answer by googling, but they have not been clearly explained or incomplete. Either I'm googling wrong or a good SO question and answer is needed.

Body:
As another resource to the one supplied by ry8806, I also use a Value Converter:

export class KeysValueConverter {
  toView(obj) {
    if (obj !== null && typeof obj === 'object') {
      return Reflect.ownKeys(obj).filter(x => x !== '__observers__');
    } else {
      return null;
    }
  }
}

It can easily be used to do what you're attempting, like this:

<template>
<div class="my_class">
    <ul class="list-group">
        <li repeat.for="key of my_data | keys" class="list-group-item">
                <span>${key} - ${my_data[key]}</span>
        </li>
    </ul>
</div>
</template>


问:
TFS connection API
I am connecting to TFS using the following code, Can someone guide me on which API I should so that I dont have to provide user name , domain and pass.

Application should pick the windows credential through which I have logged in to the system.

TeamFoundationServer tfServer = new TeamFoundationServer(@"domain", new NetworkCredential("username", ","password", "domain"));

tfServer.Authenticate();

答:
I see this has already been answered, however, you can just omit the network credentials, and it will use the currently logged-in user.  e.g.:</p>

```<code>var TfsServer = new TeamFoundationServer("http://tfs:8080");
</code>```

Title: TFS connection API

Body:
I see this has already been answered, however, you can just omit the network credentials, and it will use the currently logged-in user.  e.g.:

var TfsServer = new TeamFoundationServer("http://tfs:8080");


问:
Intermediate results from joblib
I'm trying to learn the joblib module as an alternative to the builtin multiprocessing module in python. I'm used to using multiprocessing.imap to run a function over an iterable and returning the results as they come in. In this minimal working example, I can't figure out how to do it with joblib:

```<code>import joblib, time

def hello(n):
    time.sleep(1)
    print "Inside function", n
    return n

with joblib.Parallel(n_jobs=1) as MP:

    func = joblib.delayed(hello)
    for x in MP(func(x) for x in range(3)):
        print "Outside function", x
</code>```

Which prints:

```<code>Inside function 0
Inside function 1
Inside function 2
Outside function 0
Outside function 1
Outside function 2
</code>```

I'd like to see the output:

```<code>Inside function 0
Outside function 0
Inside function 1
Outside function 1
Inside function 2
Outside function 2
</code>```

Or something similar, indicating that the iterable MP(...) is not waiting for all the results to complete. For longer demo change n_jobs=-1 and range(100).

答:
To get Immediate results from joblib, for instance:

```<code>from joblib._parallel_backends import MultiprocessingBackend

class ImmediateResult_Backend(MultiprocessingBackend):
    def callback(self, result):
        print("\tImmediateResult function %s" % (result))

    # Overload apply_async and set callback=self.callback
    def apply_async(self, func, callback=None):
        applyResult = super().apply_async(func, self.callback)
        return applyResult

joblib.register_parallel_backend('custom', ImmediateResult_Backend, make_default=True)

with joblib.Parallel(n_jobs=2) as parallel:
    func = parallel(delayed(hello)(y) for y in range(3))
    for f in func:
        print("Outside function %s" % (f))
</code>```

Output:

Note: I use time.sleep(n * random.randrange(1,5)) in def hello(...), therefore processes become different ready.

Inside function 0

  Inside function 1

      ImmediateResult function [0]

  Inside function 2

      ImmediateResult function [1]

      ImmediateResult function [2]

  Outside function 0

  Outside function 1

  Outside function 2

Tested with Python:3.4.2 - joblib:0.11

Title: Intermediate results from joblib

Body:
I'm trying to learn the joblib module as an alternative to the builtin multiprocessing module in python. I'm used to using multiprocessing.imap to run a function over an iterable and returning the results as they come in. In this minimal working example, I can't figure out how to do it with joblib:

import joblib, time

def hello(n):
    time.sleep(1)
    print "Inside function", n
    return n

with joblib.Parallel(n_jobs=1) as MP:

    func = joblib.delayed(hello)
    for x in MP(func(x) for x in range(3)):
        print "Outside function", x

Which prints:

Inside function 0
Inside function 1
Inside function 2
Outside function 0
Outside function 1
Outside function 2

I'd like to see the output:

Inside function 0
Outside function 0
Inside function 1
Outside function 1
Inside function 2
Outside function 2

Or something similar, indicating that the iterable MP(...) is not waiting for all the results to complete. For longer demo change n_jobs=-1 and range(100).

Body:
To get Immediate results from joblib, for instance:

from joblib._parallel_backends import MultiprocessingBackend

class ImmediateResult_Backend(MultiprocessingBackend):
    def callback(self, result):
        print("\tImmediateResult function %s" % (result))

    # Overload apply_async and set callback=self.callback
    def apply_async(self, func, callback=None):
        applyResult = super().apply_async(func, self.callback)
        return applyResult

joblib.register_parallel_backend('custom', ImmediateResult_Backend, make_default=True)

with joblib.Parallel(n_jobs=2) as parallel:
    func = parallel(delayed(hello)(y) for y in range(3))
    for f in func:
        print("Outside function %s" % (f))

Output:

Note: I use time.sleep(n * random.randrange(1,5)) in def hello(...), therefore processes become different ready.

Inside function 0

  Inside function 1

      ImmediateResult function [0]

  Inside function 2

      ImmediateResult function [1]

      ImmediateResult function [2]

  Outside function 0

  Outside function 1

  Outside function 2

Tested with Python:3.4.2 - joblib:0.11


问:
ASP.NET Core return excel file (xlsx) directly in one call to the server (on the fly)?
I have found solution for generating excel file (xlsx) on the server.On first call it deletes the file demo.xlsx if it exists and generates new demo.xlsx.

First call
http://localhost:8000/api/importexport/export

it generates excel file (xlsx) and sends url for download

Second call
http://localhost:8000/demo.xlsx

downloads the file.
In Startup class in Configure method you must add
app.UseStaticFiles();

Here is the link for solution
http://www.talkingdotnet.com/import-export-xlsx-asp-net-core/

The problem with this solution is that I have two calls to server.
I want in one call
http://localhost:8000/api/importexport/export
to directly download excel file (xlsx).
I heard that its possible to download excel file (xlsx) in one call without creating file on the server(on the fly).
I would be glad to see better solution in one call to the server.

答:
Here is my solution

```<code>   private readonly IHostingEnvironment _hostingEnvironment;

    public ImportExportController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpGet]
    [Route("Export")]
    public IActionResult Export()
    {
        string sWebRootFolder = _hostingEnvironment.WebRootPath;
        string sFileName = @"demo.xlsx";
        string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
        FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            // add a new worksheet to the empty workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            //First add the headers
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            //Add values
            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save(); //Save the workbook.
        }
        var result = PhysicalFile(Path.Combine(sWebRootFolder, sFileName), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        Response.Headers["Content-Disposition"] = new ContentDispositionHeaderValue("attachment")
        {
            FileName = file.Name
        }.ToString();

        return result;
    }
</code>```

If someone have better solution please post it.

Body:
Here is my solution

   private readonly IHostingEnvironment _hostingEnvironment;

    public ImportExportController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpGet]
    [Route("Export")]
    public IActionResult Export()
    {
        string sWebRootFolder = _hostingEnvironment.WebRootPath;
        string sFileName = @"demo.xlsx";
        string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
        FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            // add a new worksheet to the empty workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            //First add the headers
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            //Add values
            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save(); //Save the workbook.
        }
        var result = PhysicalFile(Path.Combine(sWebRootFolder, sFileName), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        Response.Headers["Content-Disposition"] = new ContentDispositionHeaderValue("attachment")
        {
            FileName = file.Name
        }.ToString();

        return result;
    }

If someone have better solution please post it.


问:
How to efficiently find small typos in source code files?
I would like to recursively search a large code base (mostly python, HTML and javascript) for typos in comments, strings and also variable/method/class names. Strong preference for something that runs in a terminal.

The problem is that spell checkers like aspell or scspell find almost only false positives (e.g. programming terms, camelcased terms) while I would be happy if it could help me primarily find simple typos like scrambled or missing letters e.g. maintenane vs. maintenance, resticted vs. restricted, dpeloyment vs. deployment.

What I was playing with so far is:

```<code>for f in **/*.py ; do echo $f ; aspell list < $f |  uniq -c ; done
</code>```

but it will find anything like: assertEqual, MyTestCase, lifecycle

答:
This solution of my own focuses on python files but in the end also found them in html and js. It still needed manual sorting out of false positives but that only took few minutes work and it identified about 150 typos in comments that then also could be found in the non-comment parts.

Save this as executable file e.g extractcomments:

```<code>#!/usr/bin/env python3
import argparse
import io
import tokenize

if __name__ == "__main__":
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('filename')
    args = parser.parse_args()

    with io.open(args.filename, "r", encoding="utf-8") as sourcefile:
        for t in tokenize.generate_tokens(sourcefile.readline):
            if t.type == tokenize.COMMENT:
                print(t.string.lstrip("#").strip())
</code>```

Collect all comments for further processing:

```<code>for f in **/*.py ; do  ~/extractcomments $f >> ~/comments.txt ; done
</code>```

Run it recursively on your code base with one or more aspell dictionaries and collect all it identified as typos and count their occurrences:

```<code>aspell <~/comments.txt --lang=en list|aspell --lang=de list | sort | uniq -c | sort -n > ~/typos.txt
</code>```

Produces something like:

```<code>10 availabe
 8 assignement
 7 hardwird
</code>```

Take the list without leading numbers, clean out the false positives, copy it to a 2nd file correct.txt and run aspell on it to get desired replacement for each typo: aspell -c correct.txt

Now paste the two files to get a format of typo;correction with paste -d";" typos.txt correct.txt > known_typos.csv

Now we want to recursively replace those in our codebase:

```<code>#!/bin/bash

root_dir=$(git rev-parse --show-toplevel)

while IFS=";" read -r typo fix ; do
    git grep -l -z -w "${typo}" -- "*.py" "*.html"  | xargs -r --null sed -i "s/\b${typo}\b/${fix}/g"
done < $root_dir/known_typos.csv
</code>```

My bash skills are poor so there is certainly space for improvement.

Update: I could find more typos in method names by running this:

```<code>grep -r def --include \*.py . | cut -d ":" -f 2- |tr "_" " " | aspell --lang=en list | sort -u
</code>```

Update2: Managed to fix typos that are e.g. inside underscored names or strings that do not have word boundaries as such e.g i_am_a_typpo3:

```<code>#!/bin/bash

root_dir=$(git rev-parse --show-toplevel)
while IFS=";" read -r typo fix ; do
    echo ${typo}
    find $root_dir  \( -name '*.py' -or -name '*.html' \) -print0 | xargs -0 perl -pi -e "s/(?<![a-zA-Z])${typo}(?![a-zA-Z])/${fix}/g"
done < $root_dir/known_typos.csv
</code>```

Body:
I would like to recursively search a large code base (mostly python, HTML and javascript) for typos in comments, strings and also variable/method/class names. Strong preference for something that runs in a terminal.

The problem is that spell checkers like aspell or scspell find almost only false positives (e.g. programming terms, camelcased terms) while I would be happy if it could help me primarily find simple typos like scrambled or missing letters e.g. maintenane vs. maintenance, resticted vs. restricted, dpeloyment vs. deployment.

What I was playing with so far is:

for f in **/*.py ; do echo $f ; aspell list < $f |  uniq -c ; done

but it will find anything like: assertEqual, MyTestCase, lifecycle

Body:
This solution of my own focuses on python files but in the end also found them in html and js. It still needed manual sorting out of false positives but that only took few minutes work and it identified about 150 typos in comments that then also could be found in the non-comment parts.

Save this as executable file e.g extractcomments:

#!/usr/bin/env python3
import argparse
import io
import tokenize

if __name__ == "__main__":
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('filename')
    args = parser.parse_args()

    with io.open(args.filename, "r", encoding="utf-8") as sourcefile:
        for t in tokenize.generate_tokens(sourcefile.readline):
            if t.type == tokenize.COMMENT:
                print(t.string.lstrip("#").strip())

Collect all comments for further processing:

for f in **/*.py ; do  ~/extractcomments $f >> ~/comments.txt ; done

Run it recursively on your code base with one or more aspell dictionaries and collect all it identified as typos and count their occurrences:

aspell <~/comments.txt --lang=en list|aspell --lang=de list | sort | uniq -c | sort -n > ~/typos.txt

Produces something like:

10 availabe
 8 assignement
 7 hardwird

Take the list without leading numbers, clean out the false positives, copy it to a 2nd file correct.txt and run aspell on it to get desired replacement for each typo: aspell -c correct.txt

Now paste the two files to get a format of typo;correction with paste -d";" typos.txt correct.txt > known_typos.csv

Now we want to recursively replace those in our codebase:

#!/bin/bash

root_dir=$(git rev-parse --show-toplevel)

while IFS=";" read -r typo fix ; do
    git grep -l -z -w "${typo}" -- "*.py" "*.html"  | xargs -r --null sed -i "s/\b${typo}\b/${fix}/g"
done < $root_dir/known_typos.csv

My bash skills are poor so there is certainly space for improvement.

Update: I could find more typos in method names by running this:

grep -r def --include \*.py . | cut -d ":" -f 2- |tr "_" " " | aspell --lang=en list | sort -u

Update2: Managed to fix typos that are e.g. inside underscored names or strings that do not have word boundaries as such e.g i_am_a_typpo3:

#!/bin/bash

root_dir=$(git rev-parse --show-toplevel)
while IFS=";" read -r typo fix ; do
    echo ${typo}
    find $root_dir  \( -name '*.py' -or -name '*.html' \) -print0 | xargs -0 perl -pi -e "s/(?<![a-zA-Z])${typo}(?![a-zA-Z])/${fix}/g"
done < $root_dir/known_typos.csv

ContentLicense: CC BY-SA 4.0


问:
Hide or show div based on children's content
After trial and error with many solutions found on SO for hiding and displaying content using jquery based on textarea content I have ended up with a piece of script that nearly does what I want. I'm doing this in MVC 5, though I don't think that any consequence for this dilemma.

I have an edit page which has many optional text areas that can either be empty or have some text, these come from a database. What I wish to do is to hide them by default if they contain no text. They are grouped and they are toggleable with a click of the description text above them.

This is how I have them grouped, displaying one area:

```<code>    <div class="togglerDesc">
    <p class="pointerToggler"><strong>XXX description</strong></p>
        <div class="hiddenContainer">
            <div class="optionalArea">
                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p1, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p1, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p1, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p2, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p2, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p2, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p3, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p3, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p3, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

And the script I have is:

```<code>$(document).ready(function () {
        if (!$.trim($(".optionalArea textarea").val()).length < 1) {
            $(".optionalArea textarea").parents(".hiddenContainer").show();
        }
});
</code>```

Now this works just fine if the immediate text area, Q1p1 in my example has text in it. However if it is empty it does not show the div even if the two other textareas have text in them. It does seem my problem here is that the script is not taking all of the divs into account and only checks the first one. How could I change it so it takes all of the text areas within .optionalArea into account?

答:
If you can ensure you don't have blank spaces or line-breaks alone on the textareas you can try with a simple selector match if it isn't empty:

```<code>$(document).ready(function () {
  $(".optionalArea textarea:not(:empty)").parents('.hiddenContainer').show()
});
</code>```

Fiddle Demo

Note: An empty space or line break will take the element as with content.

With your actual code what you can do is something that allows you evaluate if any of the items has content like:

```<code>$(document).ready(function () {
  $(".optionalArea textarea").filter(function(){
        return $.trim($(this).val())
  }).parents('.hiddenContainer').show()
});
</code>```

Fiddle Demo

Body:
After trial and error with many solutions found on SO for hiding and displaying content using jquery based on textarea content I have ended up with a piece of script that nearly does what I want. I'm doing this in MVC 5, though I don't think that any consequence for this dilemma.

I have an edit page which has many optional text areas that can either be empty or have some text, these come from a database. What I wish to do is to hide them by default if they contain no text. They are grouped and they are toggleable with a click of the description text above them.

This is how I have them grouped, displaying one area:

XXX description

                    @Html.LabelFor(model => model.Q1p1, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p1, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p1, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Q1p2, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p2, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p2, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Q1p3, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p3, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p3, "", new { @class = "text-danger" })

And the script I have is:

$(document).ready(function () {
        if (!$.trim($(".optionalArea textarea").val()).length < 1) {
            $(".optionalArea textarea").parents(".hiddenContainer").show();
        }
});

Now this works just fine if the immediate text area, Q1p1 in my example has text in it. However if it is empty it does not show the div even if the two other textareas have text in them. It does seem my problem here is that the script is not taking all of the divs into account and only checks the first one. How could I change it so it takes all of the text areas within .optionalArea into account?

Body:
If you can ensure you don't have blank spaces or line-breaks alone on the textareas you can try with a simple selector match if it isn't empty:

$(document).ready(function () {
  $(".optionalArea textarea:not(:empty)").parents('.hiddenContainer').show()
});

Fiddle Demo

Note: An empty space or line break will take the element as with content.

With your actual code what you can do is something that allows you evaluate if any of the items has content like:

$(document).ready(function () {
  $(".optionalArea textarea").filter(function(){
        return $.trim($(this).val())
  }).parents('.hiddenContainer').show()
});

Fiddle Demo


问:
can a aspx page have more than one aspx.cs class to inherit?
i want to know, can one aspx page have two or more code behind page?
like if i have page collge.aspx, by default it will inherit college.aspx.cs, i want to know can't it inherit more then one aspx.cs. If not then why?</p>

答:
In .NET you only have single inheritance, but multiple interface implementation.

have two or more code behind page?

Well in .NET you have the principle of partial classes so you could create multiple files and spread the logic of that one class over these files. In ASP.NET the .aspx.designer.cs file does the same actually.


问:
Rotate TImage inside a procedure (without using TTimer)
I was trying to make a simple animation inside a TButton procedure of a TImage rotating from a degree to another on Android using Delphi-Firemonkey (Berlin) like this:

```<code>procedure TForm1.Button1Click(Sender: TObject);
begin
while Image1.RotationAngle < 360 do begin
Image1.RotationAngle := Image1.RotationAngle+1;
Image1.Repaint;
Sleep(1);
end;
end;
</code>```

I've tried with and without Image1.Repaint but the animation simply does not work, but when using a TTimer it works perfectly. Anyone has any idea how to solve this?

答:
add FMX.Ani to uses clause, and use TAnimator in button onlick event:

```<code>procedure TForm1.Button1Click(Sender: TObject);
begin
 Image1.RotationAngle:=0;
 TAnimator.AnimateFloat(Image1,'RotationAngle',360,1,TAnimationType.InOut, TInterpolationType.Exponential );
end;
</code>```

look into the docs for AnimateFloat, AnimateFloatWait, AnimateFloatDelay for detailed explanation of the params

Body:
I was trying to make a simple animation inside a TButton procedure of a TImage rotating from a degree to another on Android using Delphi-Firemonkey (Berlin) like this:

procedure TForm1.Button1Click(Sender: TObject);
begin
while Image1.RotationAngle < 360 do begin
Image1.RotationAngle := Image1.RotationAngle+1;
Image1.Repaint;
Sleep(1);
end;
end;

I've tried with and without Image1.Repaint but the animation simply does not work, but when using a TTimer it works perfectly. Anyone has any idea how to solve this?

Body:
add FMX.Ani to uses clause, and use TAnimator in button onlick event:

procedure TForm1.Button1Click(Sender: TObject);
begin
 Image1.RotationAngle:=0;
 TAnimator.AnimateFloat(Image1,'RotationAngle',360,1,TAnimationType.InOut, TInterpolationType.Exponential );
end;

look into the docs for AnimateFloat, AnimateFloatWait, AnimateFloatDelay for detailed explanation of the params