问:
How to fix "Type 'AttributeRouting.Framework.AttributeRoutingException' in assembly 'AttributeRouting, ...' is not marked as serializable." error?
I'm getting the error mentioned in the title but I'm not (obviously) serializing any objects that reference AttributeRouting, let alone the AttributeRoutingException type.

In Visual Studio the error info indicates that the relevant file is "ASPNETCOMPILER" – that's pretty unhelpful.

Superficially, this seems like it should be covered by one of these existing questions and their answers:

c# - Error - is not marked as serializable - Stack Overflow

c# - SerializationException Type "is not marked as serializable" - But it is - Stack Overflow

c# - Type in assembly is not marked as serializable - Stack Overflow

答:
By process of elimination I determined that this line was the culprit:

```<code>[DELETE("entities/{id:Guid}")]
</code>```

The line is an attribute on an ASP.NET MVC controller action method. The problem is the 'routing constraint' that indicates that id should be a GUID. The line should be like this instead:

```<code>[DELETE("entities/{id:guid}")]
</code>```

[The only difference is that guid is all lowercase.]

Body:
By process of elimination I determined that this line was the culprit:

[DELETE("entities/{id:Guid}")]

The line is an attribute on an ASP.NET MVC controller action method. The problem is the 'routing constraint' that indicates that id should be a GUID. The line should be like this instead:

[DELETE("entities/{id:guid}")]

[The only difference is that guid is all lowercase.]


来源: stackexchange

问:
CSS GRID - grid-template-areas with empty cells and auto placement
I’m trying to use the css grid layout module to display a 12 columns - 3 rows grid.

I need to have the 1st row to display only 2 elements (1st on the left hand side of the grid, 2nd on the right hand side).
I separated them with empty cells using 10 periods.

Then I need the following rows to display the remaining elements automatically.

I decided to go with grid-template-areas to have more control on positioning but might not be the best approach since it seems I have to give a specific grid-area name to all the elements.

Also, when I try using the auto grid-area property to the remaining cells so that they can automatically fill the 3rd row, it seems they fill the empty cells from the first row.

What would be the most effective way to solve this problem?

Here is my code:

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}
.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="elem elem1">
    elem1
  </div>
  <div class="elem elem2">
    elem2
  </div>
  <div class="elem elem3">
    elem3
  </div>
   <div class="elem elem4">
    elem4
  </div>
  <div class="elem elem5">
    elem5
  </div>
  <div class="elem elem6">
    elem6
  </div>
  <div class="elem elem7">
    elem7
  </div>
  <div class="elem elem8">
    elem8
  </div>
  <div class="elem elem9">
    elem9
  </div>
  <div class="elem elem10">
    elem10
  </div>
  <div class="elem elem11">
    elem11
  </div>
  <div class="elem elem12">
    elem12
  </div>
  <div class="elem elem13">
    elem13
  </div>
  <div class="elem elem14">
    elem14
  </div>
  <div class="elem elem15">
    elem15
  </div>
  <div class="elem elem16">
    elem16
  </div>
  <div class="elem elem17">
    elem17
  </div>
  <div class="elem elem18">
    elem18
  </div>
  <div class="elem elem19">
    elem19
  </div>
  <div class="elem elem20">
    elem20
  </div>
</div></code>```

Many thanks

答:
You could add an empty div in the HTML. Then layout the grid using grid-template-columns, and place the empty div where you want.
Example:

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
}

.spacer {
  grid-column: 2 / span 10;
}

.elem {
  text-align: center;
  color: white;
}

.elem1 {
  background-color: blue;
}

.elem2 {
  background-color: red;
}

.elem3 {
  background-color: cyan;
}

.elem4 {
  background-color: green;
}

.elem5 {
  background-color: magenta;
}

.elem6 {
  background-color: blue;
}

.elem7 {
  background-color: red;
}

.elem8 {
  background-color: cyan;
}

.elem9 {
  background-color: green;
}

.elem10 {
  background-color: magenta;
}

.elem11 {
  background-color: blue;
}

.elem12 {
  background-color: red;
}

.elem13 {
  background-color: cyan;
}

.elem14 {
  background-color: green;
}

.elem15 {
  background-color: magenta;
}

.elem16 {
  background-color: green;
}

.elem17 {
  background-color: magenta;
}

.elem18 {
  background-color: cyan;
}

.elem19 {
  background-color: magenta;
}

.elem20 {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="elem elem1">
    elem1
  </div>
  <div class="spacer"></div>
  <div class="elem elem2">
    elem2
  </div>
  <div class="elem elem3">
    elem3
  </div>
  <div class="elem elem4">
    elem4
  </div>
  <div class="elem elem5">
    elem5
  </div>
  <div class="elem elem6">
    elem6
  </div>
  <div class="elem elem7">
    elem7
  </div>
  <div class="elem elem8">
    elem8
  </div>
  <div class="elem elem9">
    elem9
  </div>
  <div class="elem elem10">
    elem10
  </div>
  <div class="elem elem11">
    elem11
  </div>
  <div class="elem elem12">
    elem12
  </div>
  <div class="elem elem13">
    elem13
  </div>
  <div class="elem elem14">
    elem14
  </div>
  <div class="elem elem15">
    elem15
  </div>
  <div class="elem elem16">
    elem16
  </div>
  <div class="elem elem17">
    elem17
  </div>
  <div class="elem elem18">
    elem18
  </div>
  <div class="elem elem19">
    elem19
  </div>
  <div class="elem elem20">
    elem20
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I’m trying to use the css grid layout module to display a 12 columns - 3 rows grid.

I need to have the 1st row to display only 2 elements (1st on the left hand side of the grid, 2nd on the right hand side).
I separated them with empty cells using 10 periods.

Then I need the following rows to display the remaining elements automatically.

I decided to go with grid-template-areas to have more control on positioning but might not be the best approach since it seems I have to give a specific grid-area name to all the elements.

Also, when I try using the auto grid-area property to the remaining cells so that they can automatically fill the 3rd row, it seems they fill the empty cells from the first row.

What would be the most effective way to solve this problem?

Here is my code:

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}
.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}

    elem1

    elem2

    elem3

    elem4

    elem5

    elem6

    elem7

    elem8

    elem9

    elem10

    elem11

    elem12

    elem13

    elem14

    elem15

    elem16

    elem17

    elem18

    elem19

    elem20

Many thanks

Body:
You could add an empty div in the HTML. Then layout the grid using grid-template-columns, and place the empty div where you want.
Example:

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
}

.spacer {
  grid-column: 2 / span 10;
}

.elem {
  text-align: center;
  color: white;
}

.elem1 {
  background-color: blue;
}

.elem2 {
  background-color: red;
}

.elem3 {
  background-color: cyan;
}

.elem4 {
  background-color: green;
}

.elem5 {
  background-color: magenta;
}

.elem6 {
  background-color: blue;
}

.elem7 {
  background-color: red;
}

.elem8 {
  background-color: cyan;
}

.elem9 {
  background-color: green;
}

.elem10 {
  background-color: magenta;
}

.elem11 {
  background-color: blue;
}

.elem12 {
  background-color: red;
}

.elem13 {
  background-color: cyan;
}

.elem14 {
  background-color: green;
}

.elem15 {
  background-color: magenta;
}

.elem16 {
  background-color: green;
}

.elem17 {
  background-color: magenta;
}

.elem18 {
  background-color: cyan;
}

.elem19 {
  background-color: magenta;
}

.elem20 {
  background-color: blue;
}

<div class="grid">
  <div class="elem elem1">
    elem1
  </div>
  <div class="spacer"></div>
  <div class="elem elem2">
    elem2
  </div>
  <div class="elem elem3">
    elem3
  </div>
  <div class="elem elem4">
    elem4
  </div>
  <div class="elem elem5">
    elem5
  </div>
  <div class="elem elem6">
    elem6
  </div>
  <div class="elem elem7">
    elem7
  </div>
  <div class="elem elem8">
    elem8
  </div>
  <div class="elem elem9">
    elem9
  </div>
  <div class="elem elem10">
    elem10
  </div>
  <div class="elem elem11">
    elem11
  </div>
  <div class="elem elem12">
    elem12
  </div>
  <div class="elem elem13">
    elem13
  </div>
  <div class="elem elem14">
    elem14
  </div>
  <div class="elem elem15">
    elem15
  </div>
  <div class="elem elem16">
    elem16
  </div>
  <div class="elem elem17">
    elem17
  </div>
  <div class="elem elem18">
    elem18
  </div>
  <div class="elem elem19">
    elem19
  </div>
  <div class="elem elem20">
    elem20
  </div>
</div>


问:
Sending nested JSON from rails app to hapijs app
I'm using rails 3.4, node 9, and Hapi js 16.5.2

 What i'm trying to do is send a nested JSON from a rails app to a hapi js app, but something weird is happening. I am using the Rest-Client request for sending a POST request. the JSON is of the following format:

```<code>data = {
    time => {
        start => "12.11.17",
        end => "13.11.17"
    },
    event => "party"
}
</code>```

The request is of the following form:

```<code>RestClient::Request.new(
    :method => :post,
    :url => "mynodeserverroute",
    :payload => data
).execute
</code>```

The problem is all the nested elements are sent really weirdly, instead of being of the form:

```<code>time: {
        start: "12.11.17",
        end: "13.11.17"
    }
</code>```

It comes back in the form

```<code>"time[start]": "12.11.17",
"time[end]": "13.11.17"
</code>```

Which makes it challenging to verify later of.
What am I doing wrong? I tried adding the following to the request:

```<code>:header => {
            :content_type => :json,
            :accept => :json
}
</code>```

but that didn't help as well.
Is there a different method to send a JSON via rails?

答:
The data looks wierd. It should look something like:

```<code>"time":{"start":"12.11.17","end":"13.11.17"}
</code>```

I don't know your setup.
But i would start with a simple rails build-in respond_to do in a controller, with a corresponding route. And after that implementing the RestClient::Request.

For example:

```<code>#routes.rb
...
get '/this-url-is-for-seeing-the-data' => 'controller_name#post_this'
...
</code>```

And then in the controller:

```<code>def post_this
  respond_to to |format|
    format.json { render json: { time: { start: "12.11.17", end: "13.11.17" } } }
  end
end
</code>```

You can now visit the url: /this-url-is-for-seeing-the-data.json and see the data in your browser.

Now you know it's right and you can build the rest, i hope :)

Good luck!

Body:
I'm using rails 3.4, node 9, and Hapi js 16.5.2

 What i'm trying to do is send a nested JSON from a rails app to a hapi js app, but something weird is happening. I am using the Rest-Client request for sending a POST request. the JSON is of the following format:

data = {
    time => {
        start => "12.11.17",
        end => "13.11.17"
    },
    event => "party"
}

The request is of the following form:

RestClient::Request.new(
    :method => :post,
    :url => "mynodeserverroute",
    :payload => data
).execute

The problem is all the nested elements are sent really weirdly, instead of being of the form:

time: {
        start: "12.11.17",
        end: "13.11.17"
    }

It comes back in the form

"time[start]": "12.11.17",
"time[end]": "13.11.17"

Which makes it challenging to verify later of.
What am I doing wrong? I tried adding the following to the request:

:header => {
            :content_type => :json,
            :accept => :json
}

but that didn't help as well.
Is there a different method to send a JSON via rails?

Body:
The data looks wierd. It should look something like:

"time":{"start":"12.11.17","end":"13.11.17"}

I don't know your setup.
But i would start with a simple rails build-in respond_to do in a controller, with a corresponding route. And after that implementing the RestClient::Request.

For example:

#routes.rb
...
get '/this-url-is-for-seeing-the-data' => 'controller_name#post_this'
...

And then in the controller:

def post_this
  respond_to to |format|
    format.json { render json: { time: { start: "12.11.17", end: "13.11.17" } } }
  end
end

You can now visit the url: /this-url-is-for-seeing-the-data.json and see the data in your browser.

Now you know it's right and you can build the rest, i hope :)

Good luck!


问:
Using tHttpRequest to download an Excel File from Sharepoint with Authentication
I want to download an Excel file from Sharepoint and use it as input for a tFileInputExcel component. tHttpRequest seems to be the only component able to download files from a sharepoint server with authentication.

What of course works is to download the file via tHttpRequest, write the response  to a file, and load that file with the tFileInputExcel component.

Example, but I don't want it like that.

However, I do not want an intermediate file and use the "stream" functionality of the tFileInputExcel component. What I do not achieve is to convert the downloaded content into a stream that is usable by the excel component:

```<code>((java.io.InputStream)globalMap.get("what goes here? And where does it come from?"))
</code>```

Here's an example using the tFileFetch component, but this component is not able to download from sharepoint with authentication.

答:
You can do it by writing the content returned by tHttpRequest to a ByteArrayOutputStream inside a tJavaFlex, then converting it to a ByteArrayInputStream like this :

Make sure you uncheck "Write response content to file" on tHttpRequest.

In my example I download a text file because I don't have a link to an excel, but it works the same. You can read your file as an input stream like this :

Body:
I want to download an Excel file from Sharepoint and use it as input for a tFileInputExcel component. tHttpRequest seems to be the only component able to download files from a sharepoint server with authentication.

What of course works is to download the file via tHttpRequest, write the response  to a file, and load that file with the tFileInputExcel component.

Example, but I don't want it like that.

However, I do not want an intermediate file and use the "stream" functionality of the tFileInputExcel component. What I do not achieve is to convert the downloaded content into a stream that is usable by the excel component:

((java.io.InputStream)globalMap.get("what goes here? And where does it come from?"))

Here's an example using the tFileFetch component, but this component is not able to download from sharepoint with authentication.


问:
Can operations be generalized?
I just wrote this code:

```<code>private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}
</code>```

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

答:
It looks about right to me, although I'd use a switch statement for this. But maybe I don't understand what you're trying to do?

```<code>switch(operation)
{
    case OperationEnum.Sum:      return aggregateValue + sourceValue;
    case OperationEnum.Subtract: return aggregateValue - sourceValue;
    case OperationEnum.Multiply: return aggregateValue * sourceValue;
    case OperationEnum.Divide:   return aggregateValue / sourceValue;
    default:
        throw new InvalidOperationException("Unsupported Aggregation Operation");
}
</code>```

It's essentially the same, but at least it looks prettier.

ContentLicense: CC BY-SA 2.5

Title: Can operations be generalized?

Body:
I just wrote this code:

private double PerformOperation(OperationEnum operation, double aggregateValue,
                                double sourceValue)
{
    if (operation == OperationEnum.Sum)
        return aggregateValue + sourceValue;
    if (operation == OperationEnum.Subtract)
        return aggregateValue - sourceValue;
    if (operation == OperationEnum.Multiply)
        return aggregateValue * sourceValue;
    if (operation == OperationEnum.Divide)
        return aggregateValue / sourceValue;
    throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It seems very repetitive.  Is there a way to generalize this?  So I don't have to have 4 lines that are the same except a different sign?

(Note: if there is a better way that does not use the OperationEnum that is great)

Body:
It looks about right to me, although I'd use a switch statement for this. But maybe I don't understand what you're trying to do?

switch(operation)
{
    case OperationEnum.Sum:      return aggregateValue + sourceValue;
    case OperationEnum.Subtract: return aggregateValue - sourceValue;
    case OperationEnum.Multiply: return aggregateValue * sourceValue;
    case OperationEnum.Divide:   return aggregateValue / sourceValue;
    default:
        throw new InvalidOperationException("Unsupported Aggregation Operation");
}

It's essentially the same, but at least it looks prettier.


问:
Cumsum excluding current value
I am new to R and I am trying to write a function to cumulatively sum previously ordered items by customers. I have already found an almost-fitting example of code on Stack Overflow, but I do not manage to modify it accordingly to my needs.

This is the code:

Fruits <- Fruits[order(Cars$order.id), ]  #sort data
Fruits$prev_Apples<-with(Fruits,
    ave(
        ave(Apples, customer.id, FUN=cumsum),  #get running sum per customer.id
        interaction(customer.id, order.id, drop=T),
    FUN=max, na.rm=T) #find largest sum per index per seg
)```
</div>
</div>
</p>

<p>And this is the Fruits data.frame:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>order.id   customer.id Apples  Peaches  Pears
1001    J Car Ltd     1    0    0
1002     Som Comp     0    2    0
1005    Richardson    0    0    1
1004    J Car Ltd     1    0    0
1003    J Car Ltd     2    0    0
1006    Richardson    1    0    1
1007     Aldridge     0    0    1
1008    J Car Ltd     0    0    1
1010     Som Comp     0    1    0
1009    J Car Ltd     1     0     0</code>```

This is what I would like to obtain:

order id customer id Apples Peaches Pears Prev_Apples
1001 J Car Ltd 1 0 0 0
1002 Som Comp 0 2 0 0
1003 J Car Ltd 2 0 0 1
1004 J Car Ltd 1 0 0 3
1005 Richardson 0 0 1 0
1006 Richardson 1 0 1 0
1007 Aldridge 0 0 1 0
1008 J Car Ltd 0 0 1 4
1009 J Car Ltd 1 0 0 4
1010 Som Comp 0 1 0 0```
</div>
</div>
</p>

<p>And this is what I actually get:  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>order id customer id Apples Peaches Pears Prev_Apples
1001 J Car Ltd 1 0 0 1
1002 Som Comp 0 2 0 0
1003 J Car Ltd 2 0 0 3
1004 J Car Ltd 1 0 0 4
1005 Richardson 0 0 1 0
1006 Richardson 1 0 1 1
1007 Aldridge 0 0 1 0
1008 J Car Ltd 0 0 1 4
1009 J Car Ltd 1 0 0 5
1010 Som Comp 0 1 0 0</code>```

So the problem is that cumsum includes also the current order of Apples, while I would like it to include only previous orders. How should I modify the code? Any answer will be highly appreciated.

答:
Assuming the input shown reproducibly in the Note at the end we sort Fruits fixing the erroneous reference to Cars and then use ave with cumsum subtracting the current value of Apples from cumsum cancelling the last value in the sum.

This gives the same answer as the one listed as expected in the question.

```<code>Fruits <- Fruits[order(Fruits$order.id), ]
transform(Fruits, Prev_Apples = ave(Apples, customer.id, FUN = cumsum) - Apples)
</code>```

giving:

```<code>   order.id customer.id Apples Peaches Pears Prev_Apples
1      1001   J Car Ltd      1       0     0           0
2      1002    Som Comp      0       2     0           0
5      1003   J Car Ltd      2       0     0           1
4      1004   J Car Ltd      1       0     0           3
3      1005  Richardson      0       0     1           0
6      1006  Richardson      1       0     1           0
7      1007    Aldridge      0       0     1           0
8      1008   J Car Ltd      0       0     1           4
10     1009   J Car Ltd      1       0     0           4
9      1010    Som Comp      0       1     0           0
</code>```

Note: The input in reproducible form is assumed to be:

```<code>Fruits <- structure(list(order.id = c(1001L, 1002L, 1005L, 1004L, 1003L,
1006L, 1007L, 1008L, 1010L, 1009L), customer.id = structure(c(2L,
4L, 3L, 2L, 2L, 3L, 1L, 2L, 4L, 2L), .Label = c("Aldridge", "J Car Ltd",
"Richardson", "Som Comp"), class = "factor"), Apples = c(1L,
0L, 0L, 1L, 2L, 1L, 0L, 0L, 0L, 1L), Peaches = c(0L, 2L, 0L,
0L, 0L, 0L, 0L, 0L, 1L, 0L), Pears = c(0L, 0L, 1L, 0L, 0L, 1L,
1L, 1L, 0L, 0L)), .Names = c("order.id", "customer.id", "Apples",
"Peaches", "Pears"), class = "data.frame", row.names = c(NA,
-10L))
</code>```

Title: Cumsum excluding current value

Body:
I am new to R and I am trying to write a function to cumulatively sum previously ordered items by customers. I have already found an almost-fitting example of code on Stack Overflow, but I do not manage to modify it accordingly to my needs.

This is the code:

Fruits <- Fruits[order(Cars$order.id), ]  #sort data
Fruits$prev_Apples<-with(Fruits,
    ave(
        ave(Apples, customer.id, FUN=cumsum),  #get running sum per customer.id
        interaction(customer.id, order.id, drop=T),
    FUN=max, na.rm=T) #find largest sum per index per seg
)

And this is the Fruits data.frame:

order.id   customer.id Apples  Peaches  Pears
1001    J Car Ltd     1    0    0
1002     Som Comp     0    2    0
1005    Richardson    0    0    1
1004    J Car Ltd     1    0    0
1003    J Car Ltd     2    0    0
1006    Richardson    1    0    1
1007     Aldridge     0    0    1
1008    J Car Ltd     0    0    1
1010     Som Comp     0    1    0
1009    J Car Ltd     1     0     0

This is what I would like to obtain:

order id customer id Apples Peaches Pears Prev_Apples
1001 J Car Ltd 1 0 0 0
1002 Som Comp 0 2 0 0
1003 J Car Ltd 2 0 0 1
1004 J Car Ltd 1 0 0 3
1005 Richardson 0 0 1 0
1006 Richardson 1 0 1 0
1007 Aldridge 0 0 1 0
1008 J Car Ltd 0 0 1 4
1009 J Car Ltd 1 0 0 4
1010 Som Comp 0 1 0 0

And this is what I actually get:

order id customer id Apples Peaches Pears Prev_Apples
1001 J Car Ltd 1 0 0 1
1002 Som Comp 0 2 0 0
1003 J Car Ltd 2 0 0 3
1004 J Car Ltd 1 0 0 4
1005 Richardson 0 0 1 0
1006 Richardson 1 0 1 1
1007 Aldridge 0 0 1 0
1008 J Car Ltd 0 0 1 4
1009 J Car Ltd 1 0 0 5
1010 Som Comp 0 1 0 0

So the problem is that cumsum includes also the current order of Apples, while I would like it to include only previous orders. How should I modify the code? Any answer will be highly appreciated.

Body:
Assuming the input shown reproducibly in the Note at the end we sort Fruits fixing the erroneous reference to Cars and then use ave with cumsum subtracting the current value of Apples from cumsum cancelling the last value in the sum.

This gives the same answer as the one listed as expected in the question.

Fruits <- Fruits[order(Fruits$order.id), ]
transform(Fruits, Prev_Apples = ave(Apples, customer.id, FUN = cumsum) - Apples)

giving:

   order.id customer.id Apples Peaches Pears Prev_Apples
1      1001   J Car Ltd      1       0     0           0
2      1002    Som Comp      0       2     0           0
5      1003   J Car Ltd      2       0     0           1
4      1004   J Car Ltd      1       0     0           3
3      1005  Richardson      0       0     1           0
6      1006  Richardson      1       0     1           0
7      1007    Aldridge      0       0     1           0
8      1008   J Car Ltd      0       0     1           4
10     1009   J Car Ltd      1       0     0           4
9      1010    Som Comp      0       1     0           0

Note: The input in reproducible form is assumed to be:

Fruits <- structure(list(order.id = c(1001L, 1002L, 1005L, 1004L, 1003L,
1006L, 1007L, 1008L, 1010L, 1009L), customer.id = structure(c(2L,
4L, 3L, 2L, 2L, 3L, 1L, 2L, 4L, 2L), .Label = c("Aldridge", "J Car Ltd",
"Richardson", "Som Comp"), class = "factor"), Apples = c(1L,
0L, 0L, 1L, 2L, 1L, 0L, 0L, 0L, 1L), Peaches = c(0L, 2L, 0L,
0L, 0L, 0L, 0L, 0L, 1L, 0L), Pears = c(0L, 0L, 1L, 0L, 0L, 1L,
1L, 1L, 0L, 0L)), .Names = c("order.id", "customer.id", "Apples",
"Peaches", "Pears"), class = "data.frame", row.names = c(NA,
-10L))


问:
Convert CSS Selectors to XPath selector in python without external libraries
Is it possible to convert complex CSS Selectors such as:

```<code>@[class="maintitle"] > .main-wrap #myid > .h1 bold
</code>```

To XPath in Python 3 without using external libraries? Or with regex?

I'm currently able to convert

```<code>@[class="maintitle"]
</code>```

to "//*[contains(@class,'maintitle')]" but cannot manage to create a global rule to convert these more complex selectors. Is it even possbile?

Edit: I can't use cssselect.

答:
Try below XPath

```<code>//*[@class="maintitle"]/*[contains(@class, "main-wrap")]//*[@id="myid"]/*[contains(@class="h1")]//bold
</code>```

If you need tool that can convert CSS to XPath for you, you can try lxml:

```<code>from cssselect import GenericTranslator
from lxml.etree import XPath

css_selector = """[class="maintitle"] > .main-wrap #myid > .h1 bold"""
print(XPath(GenericTranslator().css_to_xpath(css_selector)))
</code>```

Output (looks weird, but...):

```<code>descendant-or-self::*[@class = 'maintitle']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' main-wrap ')]/descendant-or-self::*/*[@id = 'myid']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' h1 ')]/descendant-or-self::*/bold
</code>```

Note that you might also need to add // at the beggining as:

```<code>print("//" + str(XPath(GenericTranslator().css_to_xpath(css_selector))))
</code>```

Body:
Is it possible to convert complex CSS Selectors such as:

@[class="maintitle"] > .main-wrap #myid > .h1 bold

To XPath in Python 3 without using external libraries? Or with regex?

I'm currently able to convert

@[class="maintitle"]

to "//*[contains(@class,'maintitle')]" but cannot manage to create a global rule to convert these more complex selectors. Is it even possbile?

Edit: I can't use cssselect.

Body:
Try below XPath

//*[@class="maintitle"]/*[contains(@class, "main-wrap")]//*[@id="myid"]/*[contains(@class="h1")]//bold

If you need tool that can convert CSS to XPath for you, you can try lxml:

from cssselect import GenericTranslator
from lxml.etree import XPath

css_selector = """[class="maintitle"] > .main-wrap #myid > .h1 bold"""
print(XPath(GenericTranslator().css_to_xpath(css_selector)))

Output (looks weird, but...):

descendant-or-self::*[@class = 'maintitle']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' main-wrap ')]/descendant-or-self::*/*[@id = 'myid']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' h1 ')]/descendant-or-self::*/bold

Note that you might also need to add // at the beggining as:

print("//" + str(XPath(GenericTranslator().css_to_xpath(css_selector))))


问:
ASP.NET MVC Upload file time out
I currently have an ASP.NET MVC project that has file uploading and it works great if the user has a good enough connection and their file is of a reasonable size.

The problem I'm running into is that sometimes a user might have a 56k connection (how they can live with it in this day and age, I don't know) or are uploading a larger file or some combination of the two.

I'd like to keep a small timeout for normal pages (90 seconds or so), but allow for a larger timeout for actions where a user is uploading. This is just one action, so I don't mind putting code inside just that singular action rather than a generic solution.

Ultimately, a solution that would automatically increase the timeout if Request.Files.Count > 0 would be the best.

答: Possible issue: If its not a timeout because of the zero activity, maybe its something to do with the built in size restriction, in the web.config httpRuntime section you could add/increase maxRequestLength="" to your size limit

Title: ASP.NET MVC Upload file time out


问:
Gravity forms jQuery variable to PHP variable populate dynamically
I would like to pass a jQuery variable to php variable, in purpose to make a database selection. Im using gravity forms for the process, the jQuery code get the data from the drop down(2) and add it to another field(5), but i need the selected data from the dropdown to use in database selection:

SELECT Title FROM table WHERE Status=$variable

and the selected value to add to the field 5 in gravity forms.

```<code>    add_filter("gform_pre_render_1", "monitor_dropdown");
    function monitor_dropdown($form){

        ?>
            <script type="text/javascript">
            jQuery(document).ready(function(){

                jQuery('#input_1_2').bind('change', function()
                {
                    //get selected value from drop down;
                    var selectedValue = jQuery("#input_1_2").val();
        $.post("hold.php", {"data": selectedValue}, function (txt) {
    alert(txt);
});
                    //populate a text field with the selected drop down value
                    //jQuery("#input_1_5").val(selectedValue);
                });
            });
            </script>

        <?php
        return $form;
        }
</code>```

hold.php

```<code>    add_filter( 'gform_field_value_url_data', 'populate_date' );
    function populate_date( $value) {
    $value2 = $_POST['data'];
    return $value2 ;
       }
// OR
       $value3 = $_POST['data'];
       return $value3;
</code>```

Even after adding the ajax im not still what i need, is the ajax right? Or where im wrong ?

答:
You can handle the Form submission in the $POST macro variable.

Your Form must look like this :

```<code><form action="link_to_your_php" method="post">
    <input id="input_1_5" name="input_1_5" />
    <input type="submit" value="Find" />
</form>
</code>```

Then you can handle the variable like this.

```<code><?php
    $variable = $POST['input_1_5'];
?>
</code>```

And then make your query

```<code>SELECT Title FROM table WHERE Status=$variable
</code>```

Body:
I would like to pass a jQuery variable to php variable, in purpose to make a database selection. Im using gravity forms for the process, the jQuery code get the data from the drop down(2) and add it to another field(5), but i need the selected data from the dropdown to use in database selection:

SELECT Title FROM table WHERE Status=$variable

and the selected value to add to the field 5 in gravity forms.

    add_filter("gform_pre_render_1", "monitor_dropdown");
    function monitor_dropdown($form){

        ?>

        <?php
        return $form;
        }

hold.php

    add_filter( 'gform_field_value_url_data', 'populate_date' );
    function populate_date( $value) {
    $value2 = $_POST['data'];
    return $value2 ;
       }
// OR
       $value3 = $_POST['data'];
       return $value3;

Even after adding the ajax im not still what i need, is the ajax right? Or where im wrong ?

Body:
You can handle the Form submission in the $POST macro variable.

Your Form must look like this :

<form action="link_to_your_php" method="post">
    <input id="input_1_5" name="input_1_5" />
    <input type="submit" value="Find" />
</form>

Then you can handle the variable like this.

<?php
    $variable = $POST['input_1_5'];
?>

And then make your query

SELECT Title FROM table WHERE Status=$variable


问:
How to Provide a View in Dagger2?
Below is the Activity, it is still using an old DI model, and i'm trying to migrate to Dagger2 (with dagger-android). I want to inject the Presenter, and as you can see, one dependency is the 'NewProjectDisplayer' which is a custom view in the activity.

This is the 'NewProjectDisplayer' which I want to provide to the Presenter

I have a Module (AppModule) which provides the global dependencies like ProjectService, LoginService etc..

Below is the NewProjectModule which I am having trouble with. One of the dependencies which is tied to the activity is the 'NewProjectDisplayer'. And I have no idea how I can provide it..

```<code>@Module
public class NewProjectActivityModule {

    @Provides
    NewProjectDisplayer provideNewProjectDisplayer(View view) {
        // ??? return view.findViewById(R.id.create_project_view);
    }

    @Provides
    NewProjectNavigator provideNewProjectNavigator(BaseActivity baseActivity) {
        return new AndroidNewProjectNavigator(baseActivity);
    }

    @Provides
    NewProjectPresenter provideNewProjectPresenter(NewProjectDisplayer displayer, //
                                                   ProjectService projectService,
                                                   LoginService loginService,
                                                   UserService userService,
                                                   NewProjectNavigator navigator, //
                                                   PermissionHandler permissionHandler,//
                                                   CropImageHandler cropImageHandler,//
                                                   RxSchedulers schedulers) {
        return new NewProjectPresenter(displayer, projectService, loginService,
                userService, navigator, permissionHandler, cropImageHandler, schedulers);
    }

}
</code>```

How can I provide this 'NewProjectDisplayer' so that the Presenter can be created and injected? I am using dagger-android.

答: You can't provide or do a findViewById on an activity module that is compatible with dagger-android, one reason being that the module is created before the view is actually on the hierarchy. Also, doing this is a not a good practice, but if you're still convinced you should do this, you could try creating a sub component that will have a module that provides the view dependency and it has to be created after setContentView, as suggested by @elmorabea.

Title: How to Provide a View in Dagger2?

Body:
Below is the Activity, it is still using an old DI model, and i'm trying to migrate to Dagger2 (with dagger-android). I want to inject the Presenter, and as you can see, one dependency is the 'NewProjectDisplayer' which is a custom view in the activity.

This is the 'NewProjectDisplayer' which I want to provide to the Presenter

I have a Module (AppModule) which provides the global dependencies like ProjectService, LoginService etc..

Below is the NewProjectModule which I am having trouble with. One of the dependencies which is tied to the activity is the 'NewProjectDisplayer'. And I have no idea how I can provide it..

@Module
public class NewProjectActivityModule {

    @Provides
    NewProjectDisplayer provideNewProjectDisplayer(View view) {
        // ??? return view.findViewById(R.id.create_project_view);
    }

    @Provides
    NewProjectNavigator provideNewProjectNavigator(BaseActivity baseActivity) {
        return new AndroidNewProjectNavigator(baseActivity);
    }

    @Provides
    NewProjectPresenter provideNewProjectPresenter(NewProjectDisplayer displayer, //
                                                   ProjectService projectService,
                                                   LoginService loginService,
                                                   UserService userService,
                                                   NewProjectNavigator navigator, //
                                                   PermissionHandler permissionHandler,//
                                                   CropImageHandler cropImageHandler,//
                                                   RxSchedulers schedulers) {
        return new NewProjectPresenter(displayer, projectService, loginService,
                userService, navigator, permissionHandler, cropImageHandler, schedulers);
    }

}

How can I provide this 'NewProjectDisplayer' so that the Presenter can be created and injected? I am using dagger-android.


问:
R server with REST API and user authentication
I need help from more exprienced R users. I am looking for R server app with REST API. I would like to send and run R script using HTTP and retrieve results.
The important thing is user authentication and authorization - scripts should be executed in separated workspace (like user home directory). The best solution will be user system account authentication/authorization.
Does anyone know such application?
I found application like OpenCPU but without authentication support.

In details:

r server app should be standalone application running on machine with Linux. It listen on HTTP port for request. Clients applications comunicate with server only via REST API. To execute R code, client must authenticate first using system account username and password. After succesful authentication user have access to their own home directory (or other dedicated workspace dir). User can read/writes files in workspace from R code. The R code to execute is sent as plain text in POST request. Eventualy it could be run as script from user's workspace directory. Support for full R functionality is required
The general idea is similar to RStudio Server or JupyterHub except the client is not web browser but external (for example Java) application.
Unfortunatelly I didn't found reasonable API documentation for RStudio or JupyterHub

答:
I have accomplished the same using RApache

http://rapache.net

You can run your R scripts by making a Rest call and can also pass arguments (GET and POST) to your scripts

```<code><Location /helloworld>
 SetHandler r-handler
 RFileHandler /path/helloworld.r
</Location>
</code>```

Here helloworld will be API endpoint and it will in turn execute the helloworld.r script

It also supports authentication as is build on top of Apache

Body:
I have accomplished the same using RApache

http://rapache.net

You can run your R scripts by making a Rest call and can also pass arguments (GET and POST) to your scripts

<Location /helloworld>
 SetHandler r-handler
 RFileHandler /path/helloworld.r
</Location>

Here helloworld will be API endpoint and it will in turn execute the helloworld.r script

It also supports authentication as is build on top of Apache


问:
How can I replace two double quotes with one double quotes using Regex without capturing occurrences of one double quote?
I'm trying to do a replace on a JSON string. Something like this:

```<code>'{"val1":"1","val2":"2"","val3":"","val4":""}'
</code>```

Looking at the value tied to key "val2", I'm getting two double quotes together " 2 " ", but I can't fix that because that's how I get the JSON, I'm trying to replace those occurrences with 1 double quote: from "2"" to "2"

I'm doing replace() but I can't find the right regex to do it. I have tried this:

```<code>replace(/""/g, '"')
</code>```

If I do this it will replace "val3" and "val4" too.

This one doesn't work:

```<code>replace(/[^:]+"";/g, '"')
</code>```

I'm trying to accomplish replace(REGEX_HERE):
From "SomeCharactersHere"" to "SomeCharactersHere"

答:
I would add the comma in the match part.

```<code>'{"val1":"1","val2":"2"","val3":"","val4":""}'.replace(/"",/g, '\",');
</code>```

I would also try to figure out why I'm getting badly formatted json :-)

Better yet:

```<code>'{"val1":"1","val2":"2"","val3":"","val4":""}'.replace(/"\([^"]+\)""/g, '"\1"')
</code>```

Body:
I'm trying to do a replace on a JSON string. Something like this:

'{"val1":"1","val2":"2"","val3":"","val4":""}'

Looking at the value tied to key "val2", I'm getting two double quotes together " 2 " ", but I can't fix that because that's how I get the JSON, I'm trying to replace those occurrences with 1 double quote: from "2"" to "2"

I'm doing replace() but I can't find the right regex to do it. I have tried this:

replace(/""/g, '"')

If I do this it will replace "val3" and "val4" too.

This one doesn't work:

replace(/[^:]+"";/g, '"')

I'm trying to accomplish replace(REGEX_HERE):
From "SomeCharactersHere"" to "SomeCharactersHere"

Body:
I would add the comma in the match part.

'{"val1":"1","val2":"2"","val3":"","val4":""}'.replace(/"",/g, '\",');

I would also try to figure out why I'm getting badly formatted json :-)

Better yet:

'{"val1":"1","val2":"2"","val3":"","val4":""}'.replace(/"\([^"]+\)""/g, '"\1"')


答:
You can try the following approach:</p>

```<code>In [96]: cols = df.columns[df.columns.str.contains('^i[sm]')]

In [97]: cols
Out[97]: Index(['is1', 'is5', 'is10', 'im1', 'im5', 'im10'], dtype='object')

In [98]: mask = df[cols].eq(df[cols].max(1), axis=0)

In [99]: mask
Out[99]:
     is1   is5   is10    im1    im5   im10
0  False  True  False  False  False  False
1  False  True  False  False  False  False
2  False  True  False  False   True  False
3  False  True  False  False  False  False
4  False  True  False  False  False  False

In [104]: df[['case']].join(mask.apply(lambda r: ', '.join(cols[r]), axis=1).to_frame('idx'))
Out[104]:
   case       idx
0   686       is5
1   950       is5
2  1005  is5, im5
3  1005       is5
4  1180       is5
</code>```

Title: Returning a Column Header which Corresponds to a Maximum Value in a Row

Body:
I have a dataframe that looks like this:

case    inc_date    is1     is5     is10    im1     im5     im10
686     6/8/1972    0.141   0.300   0.149   0.134   0.135   0.142
950     6/1/1945    0.160   0.345   0.172   0.088   0.096   0.138
1005    10/16/1945  0.164   0.261   0.151   0.131   0.261   0.133
1005    11/12/1947  0.146   0.310   0.182   0.112   0.129   0.121
1180    10/9/1945   0.159   0.278   0.134   0.141   0.138   0.150

I would like to find out the maximum(s) in each row and return the column name for which the value(s) are the maximum. For example, for the above dataframe, it'd return:

686 is5
950 is5
1005 is5, im5
1005 is5
1180 is5

Body:
You can try the following approach:

In [96]: cols = df.columns[df.columns.str.contains('^i[sm]')]

In [97]: cols
Out[97]: Index(['is1', 'is5', 'is10', 'im1', 'im5', 'im10'], dtype='object')

In [98]: mask = df[cols].eq(df[cols].max(1), axis=0)

In [99]: mask
Out[99]:
     is1   is5   is10    im1    im5   im10
0  False  True  False  False  False  False
1  False  True  False  False  False  False
2  False  True  False  False   True  False
3  False  True  False  False  False  False
4  False  True  False  False  False  False

In [104]: df[['case']].join(mask.apply(lambda r: ', '.join(cols[r]), axis=1).to_frame('idx'))
Out[104]:
   case       idx
0   686       is5
1   950       is5
2  1005  is5, im5
3  1005       is5
4  1180       is5


问:
How to debug CSS/Javascript hover issues
I often find myself wanting to debug CSS layout issues that involve DOM changes caused by Javascript in reaction to a hover event or different CSS rules applying due to the :hover selector.

Normally, I'd use Firebug to inspect the element that's giving me trouble and see what its CSS properties were, and where those properties come from. However, when hovering is involved, it becomes impossible, because as soon as you move your mouse down to the Firebug panel, the elements you're interested in are no longer hovered, the CSS rules that apply are different, and (in the case of JS hovers) the DOM is changed.

Is there any way I can "freeze" the state of the DOM and application of :hover in order to inspect the DOM as it was during a hover event?

Any other ideas on how to debug this sort of issue are welcome, of course.

答: I often make some alternate CSS or Javascript to "freeze" my hovered event; tweak it to perfection with Firebug and put my hover back in place.</p>


问:
I have updated to Python 2.7.14 which should support TLSv1.2 but still doesn't work
I have an https url that has TLSv1.2 certificates,  I have updated to Python 2.7.14 from 2.7.9 which should support TLSv1.2 but still doesn't work:</p>

```<code>>>> import urllib>>> urllib.urlopen(url)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\urllib.py", line 87, in urlopen
    return opener.open(url)
  File "C:\Python27\lib\urllib.py", line 213, in open
    return getattr(self, name)(url)
  File "C:\Python27\lib\urllib.py", line 443, in open_https
    h.endheaders(data)
  File "C:\Python27\lib\httplib.py", line 1038, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 882, in _send_output
    self.send(msg)
  File "C:\Python27\lib\httplib.py", line 844, in send
    self.connect()
  File "C:\Python27\lib\httplib.py", line 1263, in connect
    server_hostname=server_hostname)
  File "C:\Python27\lib\ssl.py", line 363, in wrap_socket
    _context=self)
  File "C:\Python27\lib\ssl.py", line 611, in __init__
    self.do_handshake()
  File "C:\Python27\lib\ssl.py", line 840, in do_handshake
    self._sslobj.do_handshake()
IOError: [Errno socket error] [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:661)
</code>```

答:
It was a compounded problem

The url was requiring TLSv1.2 (2.7.9 didn't support it) I had a

proxy that didn't support https

And although I fixed 1. the other issue (2.) was giving the same error

Solution:

was fixed by upgrading to Python 2.7.14

The proxy I had didn't support https so I added and exeption and now it works

(leave "for all protocols" checkbox empty and for the Secure section leave the address and port empty)

Body:
I have an https url that has TLSv1.2 certificates,  I have updated to Python 2.7.14 from 2.7.9 which should support TLSv1.2 but still doesn't work:

>>> import urllib>>> urllib.urlopen(url)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\urllib.py", line 87, in urlopen
    return opener.open(url)
  File "C:\Python27\lib\urllib.py", line 213, in open
    return getattr(self, name)(url)
  File "C:\Python27\lib\urllib.py", line 443, in open_https
    h.endheaders(data)
  File "C:\Python27\lib\httplib.py", line 1038, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 882, in _send_output
    self.send(msg)
  File "C:\Python27\lib\httplib.py", line 844, in send
    self.connect()
  File "C:\Python27\lib\httplib.py", line 1263, in connect
    server_hostname=server_hostname)
  File "C:\Python27\lib\ssl.py", line 363, in wrap_socket
    _context=self)
  File "C:\Python27\lib\ssl.py", line 611, in __init__
    self.do_handshake()
  File "C:\Python27\lib\ssl.py", line 840, in do_handshake
    self._sslobj.do_handshake()
IOError: [Errno socket error] [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:661)


问:
How to get the content of XML nodes that have little differences? (C#)
I want to parse different XML that all of them have the same content but with this differences:

Some of the XML are like:

```<code><ds:X509Data><ds:X509Certificate>MIIDtT[...]lLgXlaoNwM=</ds:X509Certificate></ds:X509Data>
</code>```

Others are:

```<code><dsig:X509Data><dsig:X509Certificate>MIIDtT[...]lLgXlaoNwM=</dsig:X509Certificate></dsig:X509Data>
</code>```

I want to get the content of the "X509Certificate" node to save it in a file.

For other parts of the XML that are always the same, I was using:

```<code>doc.GetElementsByTagName("CountryName");
</code>```

But I cant do the same here.

What should I do?

答:
You can use XDocument Class and query it with LINQ.

```<code>var certificates = from doc in xDoc.Root.documents()
         from attr in doc.Attributes()
         where attr.Name.ToString().Contains("X509Certificate")
         select attr;
</code>```

You can now loop through certificates and read in the values

Body:
I want to parse different XML that all of them have the same content but with this differences:

Some of the XML are like:

<ds:X509Data><ds:X509Certificate>MIIDtT[...]lLgXlaoNwM=</ds:X509Certificate></ds:X509Data>

Others are:

<dsig:X509Data><dsig:X509Certificate>MIIDtT[...]lLgXlaoNwM=</dsig:X509Certificate></dsig:X509Data>

I want to get the content of the "X509Certificate" node to save it in a file.

For other parts of the XML that are always the same, I was using:

doc.GetElementsByTagName("CountryName");

But I cant do the same here.

What should I do?

Body:
You can use XDocument Class and query it with LINQ.

var certificates = from doc in xDoc.Root.documents()
         from attr in doc.Attributes()
         where attr.Name.ToString().Contains("X509Certificate")
         select attr;

You can now loop through certificates and read in the values


问:
Modularizing Angular 5 App
I’m trying to split an Angular 5 app into modules.
The working code is this (the relevant code):

app.module.ts:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FooterComponent } from './path/to/component';

@NgModule({
  declarations: [AppComponent, FooterComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.component.html:

```<code><app-footer></app-footer>
</code>```

Now I want to use the footer to change it into a module (just the changes):

app.module.ts:

```<code>import { FooterModule } from './path/to/module';

@NgModule({
  declarations: [AppComponent, FooterModule],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

footer.module.ts:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule} from '@angular/router';
import { FooterComponent } from './footer.component';

@NgModule({
  declarations: [FooterComponent],
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: 'footer', component: FooterComponent }
    ])
  ]
})

export class FooterModule { }
</code>```

This code doesn't work and I don't know what is wrong.
Can you help me with a hint ?
Thanks in advance.

答:
You should import your module on the app.ts not declare it

app.module.ts:

```<code>import { FooterModule } from './path/to/module';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule,FooterModule],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And export FooterComponent on the footer.module
footer.module.ts:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule} from '@angular/router';
import { FooterComponent } from './footer.component';

@NgModule({
  declarations: [FooterComponent],
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: 'footer', component: FooterComponent }
    ])
  ],
  exports: [FooterComponent]
})

export class FooterModule { }
</code>```

Hope it helps

Title: Modularizing Angular 5 App

Body:
I’m trying to split an Angular 5 app into modules.
The working code is this (the relevant code):

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FooterComponent } from './path/to/component';

@NgModule({
  declarations: [AppComponent, FooterComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html:

<app-footer></app-footer>

Now I want to use the footer to change it into a module (just the changes):

app.module.ts:

import { FooterModule } from './path/to/module';

@NgModule({
  declarations: [AppComponent, FooterModule],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

footer.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule} from '@angular/router';
import { FooterComponent } from './footer.component';

@NgModule({
  declarations: [FooterComponent],
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: 'footer', component: FooterComponent }
    ])
  ]
})

export class FooterModule { }

This code doesn't work and I don't know what is wrong.
Can you help me with a hint ?
Thanks in advance.

Body:
You should import your module on the app.ts not declare it

app.module.ts:

import { FooterModule } from './path/to/module';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule,FooterModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

And export FooterComponent on the footer.module
footer.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule} from '@angular/router';
import { FooterComponent } from './footer.component';

@NgModule({
  declarations: [FooterComponent],
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: 'footer', component: FooterComponent }
    ])
  ],
  exports: [FooterComponent]
})

export class FooterModule { }

Hope it helps


问:
Unable to get the hidden field Value via ng-model
I'm new to Angular js and I'm Struggling to access the hidden field value via ng-model.Basically I'm using the Modal for editing.Here is my code for controller:

```<code>$scope.update = function(){
            $http({
                method:'POST',
                url:'http://localhost:8000/api/v1/edit',
                data: {id: $scope.editId , name: $scope.edit_name, email: $scope.edit_email, password: $scope.edit_password}
            }).then(function(response){
                $scope.updated_form_data_list = response.data;
            });
        };
    });
</code>```

I'm trying to set the Id for each record via javascript:

```<code><tbody ng-repeat="form_data in form_data_list"> //Displaying records from DB inside the Table
               <tr>
               <td>@{{ form_data.name }}</td>
               <td>@{{ form_data.email }}</td>
               <td>@{{ form_data.password }}</td>
               <td><Button type="button" onclick="setEditId(this.id)" data-toggle="modal" data-target="#modal_content" id="@{{form_data.id}}" ><span class="glyphicon glyphicon-pencil"></span></Button></td>
               </tr>
    </tbody>
</code>```

And I have set the value for hidden via javascript,Here it goes:

```<code><script type="text/javascript"> //setting the value of hidden field with id
    function setEditId(id){
        document.getElementById('editId').value=id;
    }
</script>
</code>```

I have ng-model as editId in the below code:

```<code><div class="modal fade" id="modal_content" role="dialog">
   ...
  <input type="hidden" name="id" id="editId" ng-model="editId">
   ...
<button ng-click="update()">Submit</button>
</code>```

When I click the Submit button I'm able to post other values except the id. Suggest me any Solution for this. Thanking You in Advance!

答:
since you are using js to set value of editID ng-model is not updated use

```<code>$scope.editId = id;
</code>```

to change value of your input

Body:
I'm new to Angular js and I'm Struggling to access the hidden field value via ng-model.Basically I'm using the Modal for editing.Here is my code for controller:

$scope.update = function(){
            $http({
                method:'POST',
                url:'http://localhost:8000/api/v1/edit',
                data: {id: $scope.editId , name: $scope.edit_name, email: $scope.edit_email, password: $scope.edit_password}
            }).then(function(response){
                $scope.updated_form_data_list = response.data;
            });
        };
    });

I'm trying to set the Id for each record via javascript:

 //Displaying records from DB inside the Table

               @{{ form_data.name }}
               @{{ form_data.email }}
               @{{ form_data.password }}
               <Button type="button" onclick="setEditId(this.id)" data-toggle="modal" data-target="#modal_content" id="@{{form_data.id}}" ></Button>

And I have set the value for hidden via javascript,Here it goes:

I have ng-model as editId in the below code:

   ...
  <input type="hidden" name="id" id="editId" ng-model="editId">
   ...
<button ng-click="update()">Submit</button>

When I click the Submit button I'm able to post other values except the id. Suggest me any Solution for this. Thanking You in Advance!

Body:
since you are using js to set value of editID ng-model is not updated use

$scope.editId = id;

to change value of your input


问:
How to grep and execute command for every multiline match
Is there the possibility to process a multiline grep-output by one command each?

I've got something like

```<code><fulldata>
<value>1</value>
<value>2</value>
</fulldata>
<fulldata>
<value>2</value>
<value>3</value>
</fulldata>
</code>```

and want to get means, standard deviation and do some other things with data-element on its own.

In this case, I want to execute

```<code>function printStatistics {
        mean1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sum / NR}')
        deviation1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sqrt(square / NR - (sum/NR)^2)}')
        size=$(cat $1 | wc -l)
        echo $mean1 $deviation1 $size
}
</code>```

with the expected result (for the sample data), idealy separated by newline:

```<code>1,5 0,7 2
2,5 0,7 2
</code>```

Running

```<code>cat add.xml | grep "<fulldata" -A 2001 | while read line ; do echo "Line: $line" ; done
</code>```

like suggested in How to grep and execute a command (for every match) does result in one entry for each line; but I want one entry for each entry (in order to execute awk stuff on it later).

Is this possible with grep, or is this a use case where another language would be more appropriate?

答:
It is bad practice to parse html/xml with grep, because its not reliable.  If you are using Mac OS X, you can use a preinstalled cli tool called xmllint to select specific elements.  On linux, you can use the standard package manager to get it.

There is also xgrep, and probably others that I dont know about.

Body:
Is there the possibility to process a multiline grep-output by one command each?

I've got something like

<fulldata>
<value>1</value>
<value>2</value>
</fulldata>
<fulldata>
<value>2</value>
<value>3</value>
</fulldata>

and want to get means, standard deviation and do some other things with data-element on its own.

In this case, I want to execute

function printStatistics {
        mean1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sum / NR}')
        deviation1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sqrt(square / NR - (sum/NR)^2)}')
        size=$(cat $1 | wc -l)
        echo $mean1 $deviation1 $size
}

with the expected result (for the sample data), idealy separated by newline:

1,5 0,7 2
2,5 0,7 2

Running

cat add.xml | grep "<fulldata" -A 2001 | while read line ; do echo "Line: $line" ; done

like suggested in How to grep and execute a command (for every match) does result in one entry for each line; but I want one entry for each entry (in order to execute awk stuff on it later).

Is this possible with grep, or is this a use case where another language would be more appropriate?


问:
How to use two different params hashes in one page (Rails)
Hi
I want to use two params hashes in one page

The job of this page is straightforward, it's an edit page, and I want it to send out notifications to a server once the editing job is done.

```<code>def update
      @description = Tempdescription.find(params[:id])
     @description.update_attributes(params[:tempdescription])
      sendnotification
end

def sendnotification
       params[:to_ids]="xxxx"
       sig = hash_params(params);
       params[:sig] = sig
     response = RestClient.post "http://api.xxxx.com/restserver.do",  params, :content_type => :json, :accept => :json
       render :text=>response
end

def hash_params(params)
      params = Hash[*params.sort.flatten]
    payload = ''
    params.sort.each do |pair|
         key, value = pair
     payload = payload + "#{key}=#{value}"
    end
    return Digest::MD5.hexdigest(payload + API_SECRET)
 end
</code>```

Not surprisingly the params in sendnotification also includes params used for updating

and the server returns 104 error

Therefore,
I tried

```<code>new_params=Hash[]
</code>```

and use new_params to replace the old params in sendnotification

But then rails complains

```<code> undefined method `<=>' for :session_key:Symbol
 app/controllers/tempdescriptions_controller.rb:72:in `<=>'
  app/controllers/tempdescriptions_controller.rb:72:in `sort'
  app/controllers/tempdescriptions_controller.rb:72:in `hash_params'
  app/controllers/tempdescriptions_controller.rb:45:in `sendnotification'
</code>```

So I am thinking if there is any way I can create another params?

Thanks in advance

答:
Ok, having complained about your formatting I suppose I should hazard an attempt at your problem.

This code:

```<code>def hash_params(params)
  params = Hash[*params.sort.flatten]
  payload = ''
  params.sort.each do |pair|
    key, value = pair
    payload = payload + "#{key}=#{value}"
  end
  return Digest::MD5.hexdigest(payload + API_SECRET)
end
</code>```

.. appears to accept a hash as its argument and then recreate it with the keys sorted. Presumably this code is targeted at ruby 1.9 otherwise that would be rather pointless. It then sorts again for no reason I can determine before joining the keys and values with = but without separating the pairs with &.

The error is a little mysterious though; I have no trouble sorting symbols with ruby 1.9. Perhaps you're running ruby 1.8?

Body:
Hi
I want to use two params hashes in one page

The job of this page is straightforward, it's an edit page, and I want it to send out notifications to a server once the editing job is done.

def update
      @description = Tempdescription.find(params[:id])
     @description.update_attributes(params[:tempdescription])
      sendnotification
end

def sendnotification
       params[:to_ids]="xxxx"
       sig = hash_params(params);
       params[:sig] = sig
     response = RestClient.post "http://api.xxxx.com/restserver.do",  params, :content_type => :json, :accept => :json
       render :text=>response
end

def hash_params(params)
      params = Hash[*params.sort.flatten]
    payload = ''
    params.sort.each do |pair|
         key, value = pair
     payload = payload + "#{key}=#{value}"
    end
    return Digest::MD5.hexdigest(payload + API_SECRET)
 end

Not surprisingly the params in sendnotification also includes params used for updating

and the server returns 104 error

Therefore,
I tried

new_params=Hash[]

and use new_params to replace the old params in sendnotification

But then rails complains

 undefined method `<=>' for :session_key:Symbol
 app/controllers/tempdescriptions_controller.rb:72:in `<=>'
  app/controllers/tempdescriptions_controller.rb:72:in `sort'
  app/controllers/tempdescriptions_controller.rb:72:in `hash_params'
  app/controllers/tempdescriptions_controller.rb:45:in `sendnotification'

So I am thinking if there is any way I can create another params?

Thanks in advance

Body:
Ok, having complained about your formatting I suppose I should hazard an attempt at your problem.

This code:

def hash_params(params)
  params = Hash[*params.sort.flatten]
  payload = ''
  params.sort.each do |pair|
    key, value = pair
    payload = payload + "#{key}=#{value}"
  end
  return Digest::MD5.hexdigest(payload + API_SECRET)
end

.. appears to accept a hash as its argument and then recreate it with the keys sorted. Presumably this code is targeted at ruby 1.9 otherwise that would be rather pointless. It then sorts again for no reason I can determine before joining the keys and values with = but without separating the pairs with &.

The error is a little mysterious though; I have no trouble sorting symbols with ruby 1.9. Perhaps you're running ruby 1.8?


问:
Reactive selects in Angular2
I'm trying to create a group of selects in a form, which changes dinamically depending on what the user is selecting (the user has to choose in the selects sequencially).

Problem is primarily in my onChange() function, because it doesn't seem to save the changes properly when the user selects a campus. If the user selected Campus1, the 'building' select should show only "2" as an option, whereas if the user selected Campus2, the 'building' select should show only "4" as an option.

Also, I don't know if my approach is quite correct, because I'm just fiddling by now but when this works I want the app to do the following:

Get data of places (campus, building, floor and zone) from an API we have at my workplace, which will give me a JSON.

Do what I'm doing, i.e., depending on what the user selects give him certain options.

Then the user can send this form (which is basically filters) to another API and get the lockers information.

Any help with this? Especially the first part, but it would be great if you could also tell me if I'm on the right path to achieve what I want to do on the second part. I've read Angular documentation about reactive forms but I can't seem to get how to do it properly. Thanks in advance.

Here is my ts file:

```<code>    import {Component} from 'angular2/core';
    class Locker {
      constructor(public Campus: string, public Building: string, public Floor: string, public Zone: string, public Type: string) { }
    }

    @Component({
        selector: 'my-app',
        template: `
        <div class="column small-12 large-2">
        <label class="sbw_light">Campus</label><br />
        <select name="campus" [(ngModel)]="campus" (change)="onChange()">
            <option *ngFor="#each of lockers" [value]="each.Campus">
              {{each.Campus}}
            </option>
        </select>
        <br>
            <label class="sbw_light">Building</label><br />
        <select name="building" [(ngModel)]="building">
            <option *ngFor="#each of buildings">
            <div *ngIf="campus == 'Campus1'">
              {{each}}
              </div>
            </option>
        </select>
      </div>
        `
    })
    export class AppComponent {

      campus: String = "";
      building: String = "";
      floor: String = "";
      zone: String = "";
      type: String = "";

      lockers: Locker[] = [new Locker("Campus1", "2", "2", "B", "Simple"),
                           new Locker("Campus2", "1", "1", "C", "Simple"),
                           new Locker("Campus2", "1", "0", "A", "Simple")];

      buildings = [];
      floors: = [];
      zones: = [];
      types: = [];

      onChange(){
        console.log(campus);
        if (campus == 'Campus1'){
          this.buildings.length = 0;
          this.buildings.push("2");
        }
        else{
          this.buildings.length = 0;
          this.buildings.push("4");
        }
      }

    }
</code>```

答:
Problem with ngModel change detection.It's fires when you change it (onChange) , but value 'cumpus' don't updated. So you should use something like:

```<code>(onChange)="valueChanged($event)"
</code>```

And in your component

```<code> valueChanged(event: any) {
   const campus = event.target.value;
   console.log(campus);
    if (campus == 'Campus1'){
      this.buildings.length = 0;
      this.buildings.push("2");
    }
    else{
      this.buildings.length = 0;
      this.buildings.push("4");
    }
</code>```

Title: Reactive selects in Angular2

Body:
I'm trying to create a group of selects in a form, which changes dinamically depending on what the user is selecting (the user has to choose in the selects sequencially).

Problem is primarily in my onChange() function, because it doesn't seem to save the changes properly when the user selects a campus. If the user selected Campus1, the 'building' select should show only "2" as an option, whereas if the user selected Campus2, the 'building' select should show only "4" as an option.

Also, I don't know if my approach is quite correct, because I'm just fiddling by now but when this works I want the app to do the following:

Get data of places (campus, building, floor and zone) from an API we have at my workplace, which will give me a JSON.

Do what I'm doing, i.e., depending on what the user selects give him certain options.

Then the user can send this form (which is basically filters) to another API and get the lockers information.

Any help with this? Especially the first part, but it would be great if you could also tell me if I'm on the right path to achieve what I want to do on the second part. I've read Angular documentation about reactive forms but I can't seem to get how to do it properly. Thanks in advance.

Here is my ts file:

    import {Component} from 'angular2/core';
    class Locker {
      constructor(public Campus: string, public Building: string, public Floor: string, public Zone: string, public Type: string) { }
    }

    @Component({
        selector: 'my-app',
        template: `

        Campus

        <select name="campus" [(ngModel)]="campus" (change)="onChange()">
            <option *ngFor="#each of lockers" [value]="each.Campus">
              {{each.Campus}}
            </option>
        </select>

            Building

        <select name="building" [(ngModel)]="building">
            <option *ngFor="#each of buildings">

              {{each}}

            </option>
        </select>

        `
    })
    export class AppComponent {

      campus: String = "";
      building: String = "";
      floor: String = "";
      zone: String = "";
      type: String = "";

      lockers: Locker[] = [new Locker("Campus1", "2", "2", "B", "Simple"),
                           new Locker("Campus2", "1", "1", "C", "Simple"),
                           new Locker("Campus2", "1", "0", "A", "Simple")];

      buildings = [];
      floors: = [];
      zones: = [];
      types: = [];

      onChange(){
        console.log(campus);
        if (campus == 'Campus1'){
          this.buildings.length = 0;
          this.buildings.push("2");
        }
        else{
          this.buildings.length = 0;
          this.buildings.push("4");
        }
      }

    }

Body:
Problem with ngModel change detection.It's fires when you change it (onChange) , but value 'cumpus' don't updated. So you should use something like:

(onChange)="valueChanged($event)"

And in your component

 valueChanged(event: any) {
   const campus = event.target.value;
   console.log(campus);
    if (campus == 'Campus1'){
      this.buildings.length = 0;
      this.buildings.push("2");
    }
    else{
      this.buildings.length = 0;
      this.buildings.push("4");
    }


问:
CSS GRID - grid-template-areas with empty cells and auto placement
I’m trying to use the css grid layout module to display a 12 columns - 3 rows grid.

I need to have the 1st row to display only 2 elements (1st on the left hand side of the grid, 2nd on the right hand side).
I separated them with empty cells using 10 periods.

Then I need the following rows to display the remaining elements automatically.

I decided to go with grid-template-areas to have more control on positioning but might not be the best approach since it seems I have to give a specific grid-area name to all the elements.

Also, when I try using the auto grid-area property to the remaining cells so that they can automatically fill the 3rd row, it seems they fill the empty cells from the first row.

What would be the most effective way to solve this problem?

Here is my code:

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}
.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="elem elem1">
    elem1
  </div>
  <div class="elem elem2">
    elem2
  </div>
  <div class="elem elem3">
    elem3
  </div>
   <div class="elem elem4">
    elem4
  </div>
  <div class="elem elem5">
    elem5
  </div>
  <div class="elem elem6">
    elem6
  </div>
  <div class="elem elem7">
    elem7
  </div>
  <div class="elem elem8">
    elem8
  </div>
  <div class="elem elem9">
    elem9
  </div>
  <div class="elem elem10">
    elem10
  </div>
  <div class="elem elem11">
    elem11
  </div>
  <div class="elem elem12">
    elem12
  </div>
  <div class="elem elem13">
    elem13
  </div>
  <div class="elem elem14">
    elem14
  </div>
  <div class="elem elem15">
    elem15
  </div>
  <div class="elem elem16">
    elem16
  </div>
  <div class="elem elem17">
    elem17
  </div>
  <div class="elem elem18">
    elem18
  </div>
  <div class="elem elem19">
    elem19
  </div>
  <div class="elem elem20">
    elem20
  </div>
</div></code>```

Many thanks

答:
Just leverage the default grid-auto-flow:row property and tell the "1st row - right" div where to start/end using grid-column.

Then you don't need the grid-areas at all.

Result:

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-auto-flow: row; /*typo corrected*/
}

.elem {
  text-align: center;
  color: white;
}

.elem1 {
  background-color: blue;
}

.elem2 {
  background-color: red;
  grid-column: 12/13;
}

.elem3 {
  background-color: cyan;
}

.elem4 {
  background-color: green;
}

.elem5 {
  background-color: magenta;
}

.elem6 {
  background-color: blue;
}

.elem7 {
  background-color: red;
}

.elem8 {
  background-color: cyan;
}

.elem9 {
  background-color: green;
}

.elem10 {
  background-color: magenta;
}

.elem11 {
  background-color: blue;
}

.elem12 {
  background-color: red;
}

.elem13 {
  background-color: cyan;
}

.elem14 {
  background-color: green;
}

.elem15 {
  background-color: magenta;
}

.elem16 {
  background-color: green;
}

.elem17 {
  background-color: magenta;
}

.elem18 {
  background-color: cyan;
}

.elem19 {
  background-color: magenta;
}

.elem20 {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="elem elem1">
    elem1
  </div>
  <div class="elem elem2">
    elem2
  </div>
  <div class="elem elem3">
    elem3
  </div>
  <div class="elem elem4">
    elem4
  </div>
  <div class="elem elem5">
    elem5
  </div>
  <div class="elem elem6">
    elem6
  </div>
  <div class="elem elem7">
    elem7
  </div>
  <div class="elem elem8">
    elem8
  </div>
  <div class="elem elem9">
    elem9
  </div>
  <div class="elem elem10">
    elem10
  </div>
  <div class="elem elem11">
    elem11
  </div>
  <div class="elem elem12">
    elem12
  </div>
  <div class="elem elem13">
    elem13
  </div>
  <div class="elem elem14">
    elem14
  </div>
  <div class="elem elem15">
    elem15
  </div>
  <div class="elem elem16">
    elem16
  </div>
  <div class="elem elem17">
    elem17
  </div>
  <div class="elem elem18">
    elem18
  </div>
  <div class="elem elem19">
    elem19
  </div>
  <div class="elem elem20">
    elem20
  </div>
</div></code>```

Body:
I’m trying to use the css grid layout module to display a 12 columns - 3 rows grid.

I need to have the 1st row to display only 2 elements (1st on the left hand side of the grid, 2nd on the right hand side).
I separated them with empty cells using 10 periods.

Then I need the following rows to display the remaining elements automatically.

I decided to go with grid-template-areas to have more control on positioning but might not be the best approach since it seems I have to give a specific grid-area name to all the elements.

Also, when I try using the auto grid-area property to the remaining cells so that they can automatically fill the 3rd row, it seems they fill the empty cells from the first row.

What would be the most effective way to solve this problem?

Here is my code:

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}
.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}

    elem1

    elem2

    elem3

    elem4

    elem5

    elem6

    elem7

    elem8

    elem9

    elem10

    elem11

    elem12

    elem13

    elem14

    elem15

    elem16

    elem17

    elem18

    elem19

    elem20

Many thanks

Body:
Just leverage the default grid-auto-flow:row property and tell the "1st row - right" div where to start/end using grid-column.

Then you don't need the grid-areas at all.

Result:

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-auto-flow: row; /*typo corrected*/
}

.elem {
  text-align: center;
  color: white;
}

.elem1 {
  background-color: blue;
}

.elem2 {
  background-color: red;
  grid-column: 12/13;
}

.elem3 {
  background-color: cyan;
}

.elem4 {
  background-color: green;
}

.elem5 {
  background-color: magenta;
}

.elem6 {
  background-color: blue;
}

.elem7 {
  background-color: red;
}

.elem8 {
  background-color: cyan;
}

.elem9 {
  background-color: green;
}

.elem10 {
  background-color: magenta;
}

.elem11 {
  background-color: blue;
}

.elem12 {
  background-color: red;
}

.elem13 {
  background-color: cyan;
}

.elem14 {
  background-color: green;
}

.elem15 {
  background-color: magenta;
}

.elem16 {
  background-color: green;
}

.elem17 {
  background-color: magenta;
}

.elem18 {
  background-color: cyan;
}

.elem19 {
  background-color: magenta;
}

.elem20 {
  background-color: blue;
}

<div class="grid">
  <div class="elem elem1">
    elem1
  </div>
  <div class="elem elem2">
    elem2
  </div>
  <div class="elem elem3">
    elem3
  </div>
  <div class="elem elem4">
    elem4
  </div>
  <div class="elem elem5">
    elem5
  </div>
  <div class="elem elem6">
    elem6
  </div>
  <div class="elem elem7">
    elem7
  </div>
  <div class="elem elem8">
    elem8
  </div>
  <div class="elem elem9">
    elem9
  </div>
  <div class="elem elem10">
    elem10
  </div>
  <div class="elem elem11">
    elem11
  </div>
  <div class="elem elem12">
    elem12
  </div>
  <div class="elem elem13">
    elem13
  </div>
  <div class="elem elem14">
    elem14
  </div>
  <div class="elem elem15">
    elem15
  </div>
  <div class="elem elem16">
    elem16
  </div>
  <div class="elem elem17">
    elem17
  </div>
  <div class="elem elem18">
    elem18
  </div>
  <div class="elem elem19">
    elem19
  </div>
  <div class="elem elem20">
    elem20
  </div>
</div>


问:
Can't access attributes from XML response using simplexml_load_string
I'm trying to use simplexml_load_string to get the Status and Text values from the following XML response;

```<code><?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="online" xml:lang="en" timestamp="2017-12-04T15:57:47.6693296+00:00">
  <Response>
    <Status code="402" text="	\n product 325552not in customer[20690]  pricelist" />
  </Response>
</cXML>
</code>```

In my PHP code I am getting the XML above from $reply:

```<code>$reply = curl_exec($curl);
</code>```

I am then using simplexml_load_string like so:

```<code>$responseData = simplexml_load_string($reply);
echo 'Sync Order - '. $order->getIncrementId() . ' Status '. $responseData->Response->Status['code'] .' - '. $responseData->Response->Status['text'];
</code>```

But this doesn't seem to get the code and text from the XML response above. Wondering if anyone has any ideas to help?

Thank you.

Note: The cXML is correct.

答:
I've tried it with the added xml header and UTF-16 encoding bit and it fails to load with an error...

PHP Warning:  simplexml_load_string(): Entity: line 1: parser error :
  Document labelled UTF-16 but has UTF-8 content in

A simple but crude way round it is to change the UTF in the xml element to UTF8...

```<code>$reply = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $reply);
$responseData = simplexml_load_string($reply);
</code>```

This then gives the output as expected...

```<code> Status 402 -
 product 325552not in customer[20690]  pricelist
</code>```

Body:
I'm trying to use simplexml_load_string to get the Status and Text values from the following XML response;

<?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="online" xml:lang="en" timestamp="2017-12-04T15:57:47.6693296+00:00">
  <Response>
    <Status code="402" text="
 product 325552not in customer[20690]  pricelist" />
  </Response>
</cXML>

In my PHP code I am getting the XML above from $reply:

$reply = curl_exec($curl);

I am then using simplexml_load_string like so:

$responseData = simplexml_load_string($reply);
echo 'Sync Order - '. $order->getIncrementId() . ' Status '. $responseData->Response->Status['code'] .' - '. $responseData->Response->Status['text'];

But this doesn't seem to get the code and text from the XML response above. Wondering if anyone has any ideas to help?

Thank you.

Note: The cXML is correct.

Body:
I've tried it with the added xml header and UTF-16 encoding bit and it fails to load with an error...

PHP Warning:  simplexml_load_string(): Entity: line 1: parser error :
  Document labelled UTF-16 but has UTF-8 content in

A simple but crude way round it is to change the UTF in the xml element to UTF8...

$reply = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $reply);
$responseData = simplexml_load_string($reply);

This then gives the output as expected...

 Status 402 -
 product 325552not in customer[20690]  pricelist


问:
mysql: How to tail, then cat /dev/null an *.ibd file
I am working on a solaris system running an optical routing EMS application that has generated an huge DATA_MAINTENANCE_LOG.ibd file.

It's taking up alot of space on the filesystem, I do not know mysql commands.

How do I effectively tail the content of this file, then safely clear it out?

答:
How do I effectively tail the content of this file, then safely clear it out?

You don't, unless you like corrupting your database.

It's a database file.  Delete the data from the database table, and if you're lucky MySQL will release the file space.  If not, and your MySQL instance is configured to store one table per file, drop the table and the file will be deleted.

Any consequences from deleting data from that table, or dropping that table, are your responsibility to determine.


问:
Can boost::smart_ptr be used in polymorphism?
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in polymorphism?</p>

```<code>class SomeClass
{
public:
    SomeClass()
    {
        a_ptr.reset(new SubClass);
    }
private:
    boost::scoped_ptr<SuperClass> a_ptr;
}
</code>```

答: I believe the answer is yes; boost pointers are coded such that derived classes are accepted wherever a superclass would be.</p>

Body:
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in polymorphism?

class SomeClass
{
public:
    SomeClass()
    {
        a_ptr.reset(new SubClass);
    }
private:
    boost::scoped_ptr<SuperClass> a_ptr;
}


问:
How to apply expander to ListViewItem?
Say I have the expander:(reference from the article)

```<code><ControlTemplate x:Key="SimpleExpanderTemp" TargetType="{x:Type Expander}">
<DockPanel>
    <ToggleButton x:Name="ExpanderButton"

                  DockPanel.Dock="Top"

                  Template="{StaticResource SimpleExpanderButtonTemp}"

                  Content="{TemplateBinding Header}"

                  IsChecked="{Binding Path=IsExpanded,
                  RelativeSource={RelativeSource TemplatedParent}}"

                  OverridesDefaultStyle="True"

                  Padding="1.5,0">
    </ToggleButton>
    <ContentPresenter x:Name="ExpanderContent"

                      Visibility="Collapsed"

                      DockPanel.Dock="Bottom"/>
</DockPanel>
<ControlTemplate.Triggers>
    <Trigger Property="IsExpanded" Value="True">
        <Setter TargetName="ExpanderContent"

          Property="Visibility" Value="Visible"/>
    </Trigger>
</ControlTemplate.Triggers>
</code>```

Now I want to use expander on ListViewItems.
The list view doesn't have the itemsSource. I use hard copy here.

```<code><ListView VerticalAlignment="Top>
    <Grid>
        <Grid.RowDefinitions>
             <RowDefinition />
             <RowDefinition />
        </Grid.RowDefinitions>
        <Expander Template="{StaticResource SimpleExpanderButtonTemp}" Grid.Row="0" />
        <ListViewItem Grid.Row="1>
            <StackPanel>
                 <Button Height="50"> Test</Botton>
            </StackPanel>
        </ListViewItem>
   </ListView>
</code>```

My question is how to apply the expander to the list view item? I think in the template the ContentPresenter is a placeholeder, then I will replace the ListViewItem with it?

EDIT

I want something like

Row 1 is a togglebutton.
Row 2 is a list view item.
Of course I have many list view items. Each one should have its expanders. In the image I only list one.

答:
You set the Content of the Expander to whatever you want, for example a ListViewItem:

```<code><Expander Template="{StaticResource SimpleExpanderButtonTemp}" Grid.Row="0">
    <ListViewItem Grid.Row="1">
        <StackPanel>
            <Button Height="50">Test</Button>
        </StackPanel>
    </ListViewItem>
</Expander>
</code>```

It's the Content that is expanded and collapsed.

You don't need to explicitly create ListViewItems inside a ListView though so you probably just want to add the StackPanel to the Expander:

```<code><Expander Template="{StaticResource SimpleExpanderButtonTemp}" Grid.Row="0">
    <StackPanel>
        <Button Height="50">Test</Button>
    </StackPanel>
</Expander>
</code>```

Title: How to apply expander to ListViewItem?

Body:
Say I have the expander:(reference from the article)

<ControlTemplate x:Key="SimpleExpanderTemp" TargetType="{x:Type Expander}">
<DockPanel>
    <ToggleButton x:Name="ExpanderButton"

                  DockPanel.Dock="Top"

                  Template="{StaticResource SimpleExpanderButtonTemp}"

                  Content="{TemplateBinding Header}"

                  IsChecked="{Binding Path=IsExpanded,
                  RelativeSource={RelativeSource TemplatedParent}}"

                  OverridesDefaultStyle="True"

                  Padding="1.5,0">
    </ToggleButton>
    <ContentPresenter x:Name="ExpanderContent"

                      Visibility="Collapsed"

                      DockPanel.Dock="Bottom"/>
</DockPanel>
<ControlTemplate.Triggers>
    <Trigger Property="IsExpanded" Value="True">
        <Setter TargetName="ExpanderContent"

          Property="Visibility" Value="Visible"/>
    </Trigger>
</ControlTemplate.Triggers>

Now I want to use expander on ListViewItems.
The list view doesn't have the itemsSource. I use hard copy here.

<ListView VerticalAlignment="Top>
    <Grid>
        <Grid.RowDefinitions>
             <RowDefinition />
             <RowDefinition />
        </Grid.RowDefinitions>
        <Expander Template="{StaticResource SimpleExpanderButtonTemp}" Grid.Row="0" />
        <ListViewItem Grid.Row="1>
            <StackPanel>
                 <Button Height="50"> Test</Botton>
            </StackPanel>
        </ListViewItem>
   </ListView>

My question is how to apply the expander to the list view item? I think in the template the ContentPresenter is a placeholeder, then I will replace the ListViewItem with it?

EDIT

I want something like

Row 1 is a togglebutton.
Row 2 is a list view item.
Of course I have many list view items. Each one should have its expanders. In the image I only list one.

Body:
You set the Content of the Expander to whatever you want, for example a ListViewItem:

<Expander Template="{StaticResource SimpleExpanderButtonTemp}" Grid.Row="0">
    <ListViewItem Grid.Row="1">
        <StackPanel>
            <Button Height="50">Test</Button>
        </StackPanel>
    </ListViewItem>
</Expander>

It's the Content that is expanded and collapsed.

You don't need to explicitly create ListViewItems inside a ListView though so you probably just want to add the StackPanel to the Expander:

<Expander Template="{StaticResource SimpleExpanderButtonTemp}" Grid.Row="0">
    <StackPanel>
        <Button Height="50">Test</Button>
    </StackPanel>
</Expander>


问:
Golang error inside docker
I get a strange error in docker when building my go app:

```<code>./main.go:31:9: cannot use db (type *"github.com/khwerhahn/somerepo/vendor/github.com/jinzhu/gorm".DB) as type *"app/vendor/github.com/jinzhu/gorm".DB in argument to Migrate
The command '/bin/sh -c go-wrapper install' returned a non-zero code: 2
</code>```

Could somebody hint me into the right direction, because locally the app runs just fine. Its just inside the docker container. I use glide to manage dependencies.

Dockerfile:

```<code>FROM golang:1.9
WORKDIR /go/src/app
COPY . .
RUN go-wrapper download
RUN go-wrapper install

CMD ["go-wrapper", "run"]
</code>```

//// Edit
This is how my structure looks. Glide manages the vendor folder. The docker build does the rest.

答:
It's because go get is called by go-wrapper download. This fetches the dependencies from the remote instead of looking in the vendor folder.

If your libraries are already vendored and the code is in the vendor folder, all you should have to do is go run or go install.

and why do you need go-wrapper when you can just do.

```<code>RUN glide install
RUN go install
WORKDIR "../bin"
RUN myapp
</code>```

Title: Golang error inside docker

Body:
I get a strange error in docker when building my go app:

./main.go:31:9: cannot use db (type *"github.com/khwerhahn/somerepo/vendor/github.com/jinzhu/gorm".DB) as type *"app/vendor/github.com/jinzhu/gorm".DB in argument to Migrate
The command '/bin/sh -c go-wrapper install' returned a non-zero code: 2

Could somebody hint me into the right direction, because locally the app runs just fine. Its just inside the docker container. I use glide to manage dependencies.

Dockerfile:

FROM golang:1.9
WORKDIR /go/src/app
COPY . .
RUN go-wrapper download
RUN go-wrapper install

CMD ["go-wrapper", "run"]

//// Edit
This is how my structure looks. Glide manages the vendor folder. The docker build does the rest.

Body:
It's because go get is called by go-wrapper download. This fetches the dependencies from the remote instead of looking in the vendor folder.

If your libraries are already vendored and the code is in the vendor folder, all you should have to do is go run or go install.

and why do you need go-wrapper when you can just do.

RUN glide install
RUN go install
WORKDIR "../bin"
RUN myapp


问:
Restore Google Cloud default network
I was trying to automatically bring up and down a GCP network along with some other components(instances, volumes, firewall-rules etc.). Unfortunately I deleted some firewall-rules and some other components of default network unintentionally. Now I want to restore the default network to it's previous state. Is there a way to do it automatically?</p>

答:
There is no way to automatically recover any network. But if you create a new VPC network, use the Automatic mode under 'Subnet creation mode' you can see the firewall rules there so you can copy them to be added manually, and if you finish the process you will have the same subnets that the original 'default' had and you can also manually add the subnets.

But if you do not have any resources using the 'default' network, you can delete it, and create a new VPC network with the mentioned 'Automatic' setup, call it 'default', and there you will have the default network again.

Title: Restore Google Cloud default network


问:
Script is telling me that it's not a function ERROR
Probably a really quick fix but I'm stuck on what it is - I'm getting information from an API (https://api.roleplay.co.uk/v1/player/76561198062083666) where the number of vehicles keeps changing, along with the classname and classtypes. I'm trying to create a list of the names of vehicles seperated by commas, and then give each vehicle name the class of its classtype as well so that I can colour them based on their type (i.e. car, boat, plane etc.). I believe my code down here isn't working because you can't put multiple variables behind the .join but how do i get past that?

```<code>var vehicleList = data.vehicles.map(v => v.classname);
var vehicleType = data.vehicles.map(v => v.classtype);

var content = ("<span class='" + vehicleType + "'>"+ vehicleList + "</span>).join(", ");

document.getElementById("vehicle").textContent = content;
</code>```

It's giving me the following error:

```<code>player.js:404 Uncaught TypeError: (((("<span class='" + vehicleType) + "'>") + vehicleList) + "</span>").join is not a function
    at Object.success (player.js:404)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)
</code>```

答: Bro i think,  vehicleType is array, you trying to add array with string thats why you getting this error, check vehicleType.</p>

Body:
Probably a really quick fix but I'm stuck on what it is - I'm getting information from an API (https://api.roleplay.co.uk/v1/player/76561198062083666) where the number of vehicles keeps changing, along with the classname and classtypes. I'm trying to create a list of the names of vehicles seperated by commas, and then give each vehicle name the class of its classtype as well so that I can colour them based on their type (i.e. car, boat, plane etc.). I believe my code down here isn't working because you can't put multiple variables behind the .join but how do i get past that?

var vehicleList = data.vehicles.map(v => v.classname);
var vehicleType = data.vehicles.map(v => v.classtype);

var content = (""+ vehicleList + ").join(", ");

document.getElementById("vehicle").textContent = content;

It's giving me the following error:

player.js:404 Uncaught TypeError: (((("") + vehicleList) + "").join is not a function
    at Object.success (player.js:404)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)