问:
Shiny reactive subset
I am trying to subset data frame of three column (StockCode,Price,label)

but I had to used reactive and my ask is how to render label

I need somethink like renderText(dataset()$label)

ui.R

```<code>library(shiny)

# Define UI for app that draws a histogram ----
ui <- fluidPage(

  # App title ----
  titlePanel("Hello Shiny!"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(
     uiOutput("codePanel")

    ),

    # Main panel for displaying outputs ----
    mainPanel(

     textOutput("text")

    )
  )
)
</code>```

server.R

```<code>server <- function(input, output) {

output$codePanel<-renderUI({

selectInput("codeInput",label ="choose code",choices =data$StockCode)

})

dataset<-reactive({

subset(data,data$StockCode==input$codeInput)

})

 output$text<-renderText(dataset())

}
</code>```

答:
I could not get renderDataTable from DT to work.  A message said some functions were masked.  So, I removed DT and added in some code from the R Studio tutorial on tables and data.frames.  This is what I came up with:

```<code>library(shiny)

ui <- fluidPage(

  # App title ----
  titlePanel("Subsetting Iris Dataset"),

  sidebarLayout(

    # Sidebar panel for inputs
    sidebarPanel(
      uiOutput("codePanel"),

      # Input: Numeric entry for number of obs to view
      numericInput(inputId = "obs",
                   label = "Number of observations to view:",
                   value = 10)
    ),

    mainPanel(
      tableOutput("view")
    )
  )
)

server <- function(input, output) {

  filt <- selectInput("codeInput", label = "choose code",
                       choices = unique(iris$Species))

  output$codePanel <- renderUI({ filt

  })

  dataset <- reactive({

    subset(iris, Species == input$codeInput)

  })

  output$view <- renderTable(head(dataset(), n = input$obs))

}

shinyApp(ui = ui, server = server)
</code>```

Title: Shiny reactive subset

Body:
I am trying to subset data frame of three column (StockCode,Price,label)

but I had to used reactive and my ask is how to render label

I need somethink like renderText(dataset()$label)

ui.R

library(shiny)

# Define UI for app that draws a histogram ----
ui <- fluidPage(

  # App title ----
  titlePanel("Hello Shiny!"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(
     uiOutput("codePanel")

    ),

    # Main panel for displaying outputs ----
    mainPanel(

     textOutput("text")

    )
  )
)

server.R

server <- function(input, output) {

output$codePanel<-renderUI({

selectInput("codeInput",label ="choose code",choices =data$StockCode)

})

dataset<-reactive({

subset(data,data$StockCode==input$codeInput)

})

 output$text<-renderText(dataset())

}

Body:
I could not get renderDataTable from DT to work.  A message said some functions were masked.  So, I removed DT and added in some code from the R Studio tutorial on tables and data.frames.  This is what I came up with:

library(shiny)

ui <- fluidPage(

  # App title ----
  titlePanel("Subsetting Iris Dataset"),

  sidebarLayout(

    # Sidebar panel for inputs
    sidebarPanel(
      uiOutput("codePanel"),

      # Input: Numeric entry for number of obs to view
      numericInput(inputId = "obs",
                   label = "Number of observations to view:",
                   value = 10)
    ),

    mainPanel(
      tableOutput("view")
    )
  )
)

server <- function(input, output) {

  filt <- selectInput("codeInput", label = "choose code",
                       choices = unique(iris$Species))

  output$codePanel <- renderUI({ filt

  })

  dataset <- reactive({

    subset(iris, Species == input$codeInput)

  })

  output$view <- renderTable(head(dataset(), n = input$obs))

}

shinyApp(ui = ui, server = server)


来源: stackexchange

问:
Android Studio device list stuck on loading
I'm trying to add a virtual phone to the device list, however, the device list is stuck on loading.

I use the default nexus 5 device on AVD:

I am on Windows 10 and trying to set up Flutter.

答: Go to File -> Invalidate Caches / Restart... -> Invalidate and Restart worked for me.

ContentLicense: CC BY-SA 4.0


问:
How to join fetch an attribute of element in collection with QueryDSL JPA
Entities as below:

```<code>class A {
    Long id;

    @ManyToMany
    @JoinTable(name = "rel_a_b", joinColumns = @JoinColumn(name = "a_id"), inverseJoinColumns = @JoinColumn(name = "b_id"))
    Set<B> bSet;
}

class B {
    Long id;

    @ManyToMany(mappedBy = "bSet")
    Set<A> aSet;

    @ManyToMany
    @JoinTable(name = "rel_b_c", joinColumns = @JoinColumn(name = "b_id"), inverseJoinColumns = @JoinColumn(name = "c_id"))
    Set<C> cSet;
}

class C {
    Long id;

    @ManyToMany(mappedBy = "cSet")
    Set<B> bSet;
}
</code>```

I need to select A entities and join fetch bSet and cSet in B entity. Using JPA Criteria, codes as below:

```<code>    final Fetch<A, B> bSetFetch = rootA.fetch("bSet", JoinType.LEFT);
    bSetFetch.fetch("cSet", JoinType.LEFT);
</code>```

are working perfectly, but I can't achieve this with QueryDSL. I tried

```<code>    final QA a = QA.a;
    jpaQuery
    .from(a)
    .leftJoin(a.bSet, QB.b).fetchJoin()
    .leftJoin(QB.b.cSet).fetchJoin()
    .select(a)
</code>```

but it throws exception that

```<code>query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=b,role=A.b,tableName=`b`,tableAlias=b4_,origin=a a2_,columns={a2_.id ,className=B}}] [select a
from A a
  left join fetch a.bSet as b
  left join fetch b.cSet]]
</code>```

, if without fetchJoin(), the results don't include bSet and cSet. Could anyone solve this?

答:
The fetch joins are applied correctly from a QueryDSL point of view. We can also observe this from the fact that the produced JPQL query looks correct.

The limitation here is that Hibernate only allows FETCH JOINS if the owner of the fetch association is projected in the select clause. cSet is an association on B, so you would need to project your b's or omit the fetch join for cSet. For example:

```<code>jpaQuery
    .from(a)
    .leftJoin(a.bSet, QB.b).fetchJoin()
    .leftJoin(QB.b.cSet).fetchJoin()
    .select(a, b)
</code>```

Now this will result in duplicate results for a due to the cardinality of bSet. That is just a limitation of fetch joins in Hibernate.

Alternatively, you could consider specifying a fetch graph for the query:

```<code>EntityGraph postGraph = em.getEntityGraph("post");
query.setHint("javax.persistence.fetchgraph", postGraph);
</code>```

For more information on using EntityGraphs see https://www.baeldung.com/jpa-entity-graph

Body:
Entities as below:

class A {
    Long id;

    @ManyToMany
    @JoinTable(name = "rel_a_b", joinColumns = @JoinColumn(name = "a_id"), inverseJoinColumns = @JoinColumn(name = "b_id"))
    Set bSet;
}

class B {
    Long id;

    @ManyToMany(mappedBy = "bSet")
    Set aSet;

    @ManyToMany
    @JoinTable(name = "rel_b_c", joinColumns = @JoinColumn(name = "b_id"), inverseJoinColumns = @JoinColumn(name = "c_id"))
    Set<C> cSet;
}

class C {
    Long id;

    @ManyToMany(mappedBy = "cSet")
    Set bSet;
}

I need to select A entities and join fetch bSet and cSet in B entity. Using JPA Criteria, codes as below:

    final Fetch bSetFetch = rootA.fetch("bSet", JoinType.LEFT);
    bSetFetch.fetch("cSet", JoinType.LEFT);

are working perfectly, but I can't achieve this with QueryDSL. I tried

    final QA a = QA.a;
    jpaQuery
    .from(a)
    .leftJoin(a.bSet, QB.b).fetchJoin()
    .leftJoin(QB.b.cSet).fetchJoin()
    .select(a)

but it throws exception that

query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=b,role=A.b,tableName=`b`,tableAlias=b4_,origin=a a2_,columns={a2_.id ,className=B}}] [select a
from A a
  left join fetch a.bSet as b
  left join fetch b.cSet]]

, if without fetchJoin(), the results don't include bSet and cSet. Could anyone solve this?

Body:
The fetch joins are applied correctly from a QueryDSL point of view. We can also observe this from the fact that the produced JPQL query looks correct.

The limitation here is that Hibernate only allows FETCH JOINS if the owner of the fetch association is projected in the select clause. cSet is an association on B, so you would need to project your b's or omit the fetch join for cSet. For example:

jpaQuery
    .from(a)
    .leftJoin(a.bSet, QB.b).fetchJoin()
    .leftJoin(QB.b.cSet).fetchJoin()
    .select(a, b)

Now this will result in duplicate results for a due to the cardinality of bSet. That is just a limitation of fetch joins in Hibernate.

Alternatively, you could consider specifying a fetch graph for the query:

EntityGraph postGraph = em.getEntityGraph("post");
query.setHint("javax.persistence.fetchgraph", postGraph);

For more information on using EntityGraphs see https://www.baeldung.com/jpa-entity-graph


问:
Why different pointer on  and /

All browsers show different cursor for
,  than . I checked in Chrome, Firefox, IE.

SPAN

DIV

LABEL```

Why it is so??
I went through MDN and questions of SO. but didn't find answer.

Please note: I am not looking for solution (cursor: auto) but reason

答:
I don't think that there is a difference between the span cursor and the div cursor, at least there isn't for me in safari and I would assume other browsers are the same.

The div and span tags are both generic containers (see MDN docs) so it wouldn't make sense for them to have specific, different cursors. Browsers should simply display the default text cursor.

Labels are different. From w3schools:

Most browsers will display the  element with the following default values:

label {
  cursor: default;
}
```

Which is the normal mouse-pointer. This is likely to be because the label element has a specific function, unlike the div or span – it is clickable and will affect the content of other input elements.

Generally, if I'm confused about a browser's default styles, I go to the w3schools CSS Default Values Reference, which usually explains why the browser is behaving as it is. You may also find this in the developer menu of the browser in question.

If you don't like the styles which the browser is applying, simply override them in your CSS. As you have already said in your question, specifying a cursor for the label tag would be a good solution.

Title: Why different pointer on <label> and <span>/<div>

Body:
All browsers show different cursor for
,  than . I checked in Chrome, Firefox, IE.

SPAN

DIV

LABEL

Why it is so??
I went through MDN and questions of SO. but didn't find answer.

Please note: I am not looking for solution (cursor: auto) but reason

Body:
I don't think that there is a difference between the span cursor and the div cursor, at least there isn't for me in safari and I would assume other browsers are the same.

The div and span tags are both generic containers (see MDN docs) so it wouldn't make sense for them to have specific, different cursors. Browsers should simply display the default text cursor.

Labels are different. From w3schools:

Most browsers will display the  element with the following default values:

label {
  cursor: default;
}

Which is the normal mouse-pointer. This is likely to be because the label element has a specific function, unlike the div or span – it is clickable and will affect the content of other input elements.

Generally, if I'm confused about a browser's default styles, I go to the w3schools CSS Default Values Reference, which usually explains why the browser is behaving as it is. You may also find this in the developer menu of the browser in question.

If you don't like the styles which the browser is applying, simply override them in your CSS. As you have already said in your question, specifying a cursor for the label tag would be a good solution.


问:
Regression models with same fitted values that output FALSE when compared to each other with equal operator in r
Given the cuadratic models for the odor dataset from the faraway package:

```<code>> lmod <- lm(odor ~ I(temp) + I(gas) + I(pack)+I(temp^2)+I(gas^2)+I(pack^2)+I(temp*gas)+I(gas*pack)+I(pack*temp),odor)
> lmod6 <- lm(odor ~ polym(temp,gas,pack,degree = 2),odor)
</code>```

Both models have the same fitted values:

```<code>> lmod$fitted
        1         2         3         4         5         6         7         8         9        10        11        12
 86.62500  45.87500  36.12500  28.37500  42.50000  15.25000  -3.25000 -24.50000  59.87500  29.37500  20.62500 -16.87500
       13        14        15
-30.66667 -30.66667 -30.66667
> lmod6$fitted
        1         2         3         4         5         6         7         8         9        10        11        12
 86.62500  45.87500  36.12500  28.37500  42.50000  15.25000  -3.25000 -24.50000  59.87500  29.37500  20.62500 -16.87500
       13        14        15
-30.66667 -30.66667 -30.66667
</code>```

However, when comparing these fitted values to each other they are not identical, why is that?

```<code>> table(lmod6$fitted==lmod$fitted)

FALSE  TRUE
   13     2
</code>```

Body:
Given the cuadratic models for the odor dataset from the faraway package:

> lmod <- lm(odor ~ I(temp) + I(gas) + I(pack)+I(temp^2)+I(gas^2)+I(pack^2)+I(temp*gas)+I(gas*pack)+I(pack*temp),odor)
> lmod6 <- lm(odor ~ polym(temp,gas,pack,degree = 2),odor)

Both models have the same fitted values:

> lmod$fitted
        1         2         3         4         5         6         7         8         9        10        11        12
 86.62500  45.87500  36.12500  28.37500  42.50000  15.25000  -3.25000 -24.50000  59.87500  29.37500  20.62500 -16.87500
       13        14        15
-30.66667 -30.66667 -30.66667
> lmod6$fitted
        1         2         3         4         5         6         7         8         9        10        11        12
 86.62500  45.87500  36.12500  28.37500  42.50000  15.25000  -3.25000 -24.50000  59.87500  29.37500  20.62500 -16.87500
       13        14        15
-30.66667 -30.66667 -30.66667

However, when comparing these fitted values to each other they are not identical, why is that?

> table(lmod6$fitted==lmod$fitted)

FALSE  TRUE
   13     2

Body:
This is a classic example of the floating point trap as described in chapter 1 of R Inferno by Patric Burns or R FAQ

The differences are zero up to floating point accuracy:

options(digits=20)
lmod$fitted - lmod6$fitted
                        1                          2
 0.0000000000000000000e+00  0.0000000000000000000e+00
                         3                          4
 7.1054273576010018587e-15  1.0658141036401502788e-14
                         5                          6
-7.1054273576010018587e-15 -3.5527136788005009294e-15
                         7                          8
 4.4408920985006261617e-16 -3.5527136788005009294e-15
                         9                         10
-1.4210854715202003717e-14 -1.4210854715202003717e-14
                        11                         12
 7.1054273576010018587e-15  3.5527136788005009294e-15
                        13                         14
 7.1054273576010018587e-15  7.1054273576010018587e-15
                        15
 7.1054273576010018587e-15

all.equal() function is designed for testing if the two vectors are "almost equal" (up to fp accuracy):

all.equal(lmod$fitted,lmod6$fitted)
[1] TRUE


问:
Segment Control doesn't work when embed in Navigation Bar [with video]
I'm trying to embed a Segment Control in the middle of a Navigation Bar, and as you can see from the video, the Navigation Bar isn't responsive.
The video

Anyone got any suggestions or workarounds? Thanks!!
source code : https://github.com/orihpt/SegemantControlIssue

答: Why won’t you try to insert segmented control without view? Just simply drag it to the navigation bar</p>


问:
Find the corrupted doc in DynamoDB
I am using dynamoose to scan a table. However one key (or more) seems to be corrupted. The scan fails with this error: Expected _modifiedAt to be of type number, instead found type object
The Schema is expecting a Number but somewhere in the table there is a doc where the key is an object.

How do I find this? We have thousands of keys, so I guess a simple search won't cut it.

Thanks

答:
So, since I need to do this because of a schema migration, I decided to simply export all data as CSV (This tool is only needed if you have over 100 keys, before that you can export directly within dynamoDB). And then write a custom migration script which handles all the error handling etc.

Hope this might help someone ;)

Title: Find the corrupted doc in DynamoDB


问:
What's the best way to check if a proxy workable in Qt?
I'm sending HTTP requests with QNetworkAccessManager example.

```<code>QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName("some proxy IP");
proxy.setPort(5555);
network_manager.setProxy(proxy);
</code>```

I want to check if a proxy can work before using it. I know I can just send a HTTP request to google with this proxy. But it will receive more than 1K data. It's relatively large since I would test many proxies. I don't think that's a good way. And I wanted to send ping via the proxy server. Seems no good way to send ping with Qt. If I use the WinAPI IcmpSendEcho to send ping, there's no way to assign a proxy.

答: Since you want to use the proxy using HTTP you could try and connect to the proxy using a QTcpSocket and see if the connection is actually established. If so you can proceed using the proxy address and port for further connections.

Body:
I'm sending HTTP requests with QNetworkAccessManager example.

QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName("some proxy IP");
proxy.setPort(5555);
network_manager.setProxy(proxy);

I want to check if a proxy can work before using it. I know I can just send a HTTP request to google with this proxy. But it will receive more than 1K data. It's relatively large since I would test many proxies. I don't think that's a good way. And I wanted to send ping via the proxy server. Seems no good way to send ping with Qt. If I use the WinAPI IcmpSendEcho to send ping, there's no way to assign a proxy.


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答:
 the difference: by example (gsub/gsub!)

```<code>string = "this_string"
string.gsub!("this", "that")
puts string #=> string = "that_string"

string = "this_string"
string.gsub("this, "that")
puts string #=> string is stil = "this_string"
</code>```

gsub without ! will return the value, but will not modify the original string. this is generally how the ! is used, without it nothing is modified. with it the original is modified

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

Body:
 the difference: by example (gsub/gsub!)

string = "this_string"
string.gsub!("this", "that")
puts string #=> string = "that_string"

string = "this_string"
string.gsub("this, "that")
puts string #=> string is stil = "this_string"

gsub without ! will return the value, but will not modify the original string. this is generally how the ! is used, without it nothing is modified. with it the original is modified


问:
AWS and CloudFormation: How to attach a Virtual Private Gateway to a Routing Table?
I'm trying to attach a Virtual Private Gateway to a Routing Table with CloudFormation

The following is the Route table JSON I have...

```<code> "PrivateRouteTable": {
            "Type": "AWS::EC2::RouteTable",
            "Properties": {
                "VpcId": {
                    "Ref": "VPC"
                },
                "Tags": [{
                    "Key": "Name",
                    "Value": "Private_RouteTable-AZ-A"
                }]
            }
        },
        "DefaultPrivateRoute": {
            "Type": "AWS::EC2::Route",
            "Properties": {
                "RouteTableId": {
                    "Ref": "PrivateRouteTable"
                },
                "DestinationCidrBlock": "0.0.0.0/0",
                "NatGatewayId": {
                    "Ref": "NatGateway"
                }
            }
        },
        "PrivateSubnetRouteTableAssociation": {
            "Type": "AWS::EC2::SubnetRouteTableAssociation",
            "Properties": {
                "RouteTableId": {
                    "Ref": "PrivateRouteTable"
                },
                "SubnetId": {
                    "Ref": "PrivateSN"
                }
            }
        }
</code>```

And this is the Virtual Private Gateway JSON I have..

```<code>"VirtualPrivateGateway": {
            "Type": "AWS::EC2::VPNGateway",
            "Properties": {
                "Type": "ipsec.1",
                "Tags": [{
                    "Key": "Name",
                    "Value": "Virtual Private Gateway"
                }]
            }
        },
        "AttachmentVPNGateway": {
            "Type": "AWS::EC2::VPCGatewayAttachment",
            "Properties": {
                "VpcId": {
                    "Ref": "VPC"
                },
                "VpnGatewayId": {
                    "Ref": "VirtualPrivateGateway"
                }
            }
        },
        "VPNConnection": {
            "Type": "AWS::EC2::VPNConnection",
            "Properties": {
                "Type": "ipsec.1",
                "CustomerGatewayId": {
                    "Ref": "CustomerGateway"
                },
                "StaticRoutesOnly": true,
                "Tags": [{
                    "Key": "Name",
                    "Value": "VPN_Connection"
                }],
                "VpnGatewayId": {
                    "Ref": "VirtualPrivateGateway"
                }
            }
        }
</code>```

There's more as well that creates the VPC, Subnet, etc, but I've left it out for simplicity sake.
The error happens if I try attach the VPG to the Route table with the following JSON...

```<code>        "VPGPrivateRoute": {
            "Type": "AWS::EC2::Route",
            "Properties": {
                "RouteTableId": {
                    "Ref": "PrivateRouteTable"
                },
                "DestinationCidrBlock": "0.0.0.0/0",
                "GatewayId": {
                    "Ref": "VirtualPrivateGateway"
                }
            }
        }
</code>```

The error I receive from CloudFormation...

```<code>The gateway ID 'vgw-xxxxxxxxxxx' does not exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidGatewayID.NotFound; Request ID: e29700b2-2d76-4e19-9d13-b6f84e22b01c)
</code>```

The documentation does say that I should be use "GatewayId" to associate a VPG to a route table.

答:
I think there should be DependsOn on the route table:

A VPN gateway route propagation depends on a VPC-gateway attachment when you have a VPN gateway.

Maybe the following will help:

```<code>    "VPGPrivateRoute": {
        "Type": "AWS::EC2::Route",
        "DependsOn" : "AttachmentVPNGateway",
        "Properties": {
            "RouteTableId": {
                "Ref": "PrivateRouteTable"
            },
            "DestinationCidrBlock": "0.0.0.0/0",
            "GatewayId": {
                "Ref": "VirtualPrivateGateway"
            }
        }
    }
</code>```

Body:
I'm trying to attach a Virtual Private Gateway to a Routing Table with CloudFormation

The following is the Route table JSON I have...

 "PrivateRouteTable": {
            "Type": "AWS::EC2::RouteTable",
            "Properties": {
                "VpcId": {
                    "Ref": "VPC"
                },
                "Tags": [{
                    "Key": "Name",
                    "Value": "Private_RouteTable-AZ-A"
                }]
            }
        },
        "DefaultPrivateRoute": {
            "Type": "AWS::EC2::Route",
            "Properties": {
                "RouteTableId": {
                    "Ref": "PrivateRouteTable"
                },
                "DestinationCidrBlock": "0.0.0.0/0",
                "NatGatewayId": {
                    "Ref": "NatGateway"
                }
            }
        },
        "PrivateSubnetRouteTableAssociation": {
            "Type": "AWS::EC2::SubnetRouteTableAssociation",
            "Properties": {
                "RouteTableId": {
                    "Ref": "PrivateRouteTable"
                },
                "SubnetId": {
                    "Ref": "PrivateSN"
                }
            }
        }

And this is the Virtual Private Gateway JSON I have..

"VirtualPrivateGateway": {
            "Type": "AWS::EC2::VPNGateway",
            "Properties": {
                "Type": "ipsec.1",
                "Tags": [{
                    "Key": "Name",
                    "Value": "Virtual Private Gateway"
                }]
            }
        },
        "AttachmentVPNGateway": {
            "Type": "AWS::EC2::VPCGatewayAttachment",
            "Properties": {
                "VpcId": {
                    "Ref": "VPC"
                },
                "VpnGatewayId": {
                    "Ref": "VirtualPrivateGateway"
                }
            }
        },
        "VPNConnection": {
            "Type": "AWS::EC2::VPNConnection",
            "Properties": {
                "Type": "ipsec.1",
                "CustomerGatewayId": {
                    "Ref": "CustomerGateway"
                },
                "StaticRoutesOnly": true,
                "Tags": [{
                    "Key": "Name",
                    "Value": "VPN_Connection"
                }],
                "VpnGatewayId": {
                    "Ref": "VirtualPrivateGateway"
                }
            }
        }

There's more as well that creates the VPC, Subnet, etc, but I've left it out for simplicity sake.
The error happens if I try attach the VPG to the Route table with the following JSON...

        "VPGPrivateRoute": {
            "Type": "AWS::EC2::Route",
            "Properties": {
                "RouteTableId": {
                    "Ref": "PrivateRouteTable"
                },
                "DestinationCidrBlock": "0.0.0.0/0",
                "GatewayId": {
                    "Ref": "VirtualPrivateGateway"
                }
            }
        }

The error I receive from CloudFormation...

The gateway ID 'vgw-xxxxxxxxxxx' does not exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidGatewayID.NotFound; Request ID: e29700b2-2d76-4e19-9d13-b6f84e22b01c)

The documentation does say that I should be use "GatewayId" to associate a VPG to a route table.

Body:
I think there should be DependsOn on the route table:

A VPN gateway route propagation depends on a VPC-gateway attachment when you have a VPN gateway.

Maybe the following will help:

    "VPGPrivateRoute": {
        "Type": "AWS::EC2::Route",
        "DependsOn" : "AttachmentVPNGateway",
        "Properties": {
            "RouteTableId": {
                "Ref": "PrivateRouteTable"
            },
            "DestinationCidrBlock": "0.0.0.0/0",
            "GatewayId": {
                "Ref": "VirtualPrivateGateway"
            }
        }
    }


问:
Why the recycler view test is not passed?
I've written the test, testing if the recycler view is displayed (id: comments_view), but it always fails and I've no idea why. When I'm checking for layout (id: cm), the test passes.

I have the following fragment code:

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="post"
            type="com.example.kotlinpostapi.apiObjects.Post" />
        <variable
            name="comments"
            type="java.util.List" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".views.MainActivity"
        android:id="@+id/cm">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/comments_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>
</code>```

The test code (I'm navigating to the fragment from another one):

```<code>@RunWith(AndroidJUnit4::class)
class CommentsListTest{

    @get: Rule
    val activityScenario = ActivityScenarioRule(MainActivity::class.java)

    @Test
    fun testCommentsAreDisplayed() {
        onView(withId(R.id.posts_view)).perform(actionOnItemAtPosition<PostAdapter.PostsViewHolder>(0, MyMatchers.clickChildView(R.id.show_comments_button)))

        //it fails
        onView(withId(R.id.comments_view)).check(matches(isDisplayed()))
        //it passes
        onView(withId(R.id.cm)).check(matches(isDisplayed()))
    }
}
</code>```

How is it possible, and how can I test my recycler view?

答:
The height of the RecyclerView is set to wrap_content and if the element is not visible at least 90% the test fails.

What you could do is to check one of the RecyclerView children.

I firstly declare the following method:

```<code>fun nthChildOf(parentMatcher: Matcher<View?>, childPosition: Int): Matcher<View?>? {
    return object : TypeSafeMatcher<View>() {
        override fun describeTo(description: Description) {
            description.appendText("with $childPosition child view of type parentMatcher")
        }

        override fun matchesSafely(view: View): Boolean {
            if (view.parent !is ViewGroup) {
                return parentMatcher.matches(view.parent)
            }
            val group = view.parent as ViewGroup
            return parentMatcher.matches(view.parent) && group.getChildAt(childPosition) == view
        }
    }
}
</code>```

with this you can check whether its first child is displayed:

```<code>onView(nthChildOf(withId(R.id.comments_view), 0)).check(matches(isDisplayed()))
</code>```

And to check one element of its children (recyclerview_element_id for example):

```<code>onView(allOf(
        withId(R.id.recyclerview_element_id),
        isDescendantOfA(
                nthChildOf(withId(R.id.comments_view), 0))
)).check(matches(isDisplayed()))
</code>```

Another thing you could try if your RecyclerView expands to the available space of the screen is to change the layout of the RecyclerView to have all the constraints set and with and height to 0dp:

```<code><androidx.recyclerview.widget.RecyclerView
            android:id="@+id/comments_view"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
</code>```

I have it this way and doing:

```<code>onView(withId(R.id.myRecyclerviewId)).check(matches(isDisplayed()))
</code>```

works for me.

Body:
I've written the test, testing if the recycler view is displayed (id: comments_view), but it always fails and I've no idea why. When I'm checking for layout (id: cm), the test passes.

I have the following fragment code:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="post"
            type="com.example.kotlinpostapi.apiObjects.Post" />
        <variable
            name="comments"
            type="java.util.List" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".views.MainActivity"
        android:id="@+id/cm">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/comments_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

The test code (I'm navigating to the fragment from another one):

@RunWith(AndroidJUnit4::class)
class CommentsListTest{

    @get: Rule
    val activityScenario = ActivityScenarioRule(MainActivity::class.java)

    @Test
    fun testCommentsAreDisplayed() {
        onView(withId(R.id.posts_view)).perform(actionOnItemAtPosition<PostAdapter.PostsViewHolder>(0, MyMatchers.clickChildView(R.id.show_comments_button)))

        //it fails
        onView(withId(R.id.comments_view)).check(matches(isDisplayed()))
        //it passes
        onView(withId(R.id.cm)).check(matches(isDisplayed()))
    }
}

How is it possible, and how can I test my recycler view?

Body:
The height of the RecyclerView is set to wrap_content and if the element is not visible at least 90% the test fails.

What you could do is to check one of the RecyclerView children.

I firstly declare the following method:

fun nthChildOf(parentMatcher: Matcher<View?>, childPosition: Int): Matcher<View?>? {
    return object : TypeSafeMatcher<View>() {
        override fun describeTo(description: Description) {
            description.appendText("with $childPosition child view of type parentMatcher")
        }

        override fun matchesSafely(view: View): Boolean {
            if (view.parent !is ViewGroup) {
                return parentMatcher.matches(view.parent)
            }
            val group = view.parent as ViewGroup
            return parentMatcher.matches(view.parent) && group.getChildAt(childPosition) == view
        }
    }
}

with this you can check whether its first child is displayed:

onView(nthChildOf(withId(R.id.comments_view), 0)).check(matches(isDisplayed()))

And to check one element of its children (recyclerview_element_id for example):

onView(allOf(
        withId(R.id.recyclerview_element_id),
        isDescendantOfA(
                nthChildOf(withId(R.id.comments_view), 0))
)).check(matches(isDisplayed()))

Another thing you could try if your RecyclerView expands to the available space of the screen is to change the layout of the RecyclerView to have all the constraints set and with and height to 0dp:

<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/comments_view"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

I have it this way and doing:

onView(withId(R.id.myRecyclerviewId)).check(matches(isDisplayed()))

works for me.


问:
WifiP2pManager.initialize returns null
WifiP2pManager.initialize returns null. I am using Droid 4, Android version 4.0.4 and built my app with API level 14.

```<code>...
</code>```

_p2pChannel = _p2pManager.initialize(this, getMainLooper(),
                                    new WifiP2pManager.ChannelListener() {

```<code>@Override
public void onChannelDisconnected() {
     Log.e(TAG, "Peer-to-peer manager channel disconnected.");
     //TODO: Manage the re-creation of the channel
     _p2pChannel = null;
}
});

if (_p2pChannel == null) {
    Log.e(TAG, "P2P Manager failed to initialize.");
    return;
}

....
</code>```

Android Manifest has:

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-feature
    android:name="android.hardware.wifi.direct"
    android:required="true"/>
</code>```

答: Its because of your emulator probably,i'd this problem and rum my app in native android emulator(android studio) and my problem was solved</p>

Title: WifiP2pManager.initialize returns null

Body:
WifiP2pManager.initialize returns null. I am using Droid 4, Android version 4.0.4 and built my app with API level 14.

...

_p2pChannel = _p2pManager.initialize(this, getMainLooper(),
                                    new WifiP2pManager.ChannelListener() {

@Override
public void onChannelDisconnected() {
     Log.e(TAG, "Peer-to-peer manager channel disconnected.");
     //TODO: Manage the re-creation of the channel
     _p2pChannel = null;
}
});

if (_p2pChannel == null) {
    Log.e(TAG, "P2P Manager failed to initialize.");
    return;
}

....

Android Manifest has:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-feature
    android:name="android.hardware.wifi.direct"
    android:required="true"/>


问:
Redshift - How to SUM number over last 4 weeks as a window function per row?
is it possible to SUM a number over a special time period in Amazon Redshift with a WINDOW-Function?

As an example I'm counting login numbers for different companies per day.
What I now want per row is, that it sums up the logins over the last 4 weeks (referenced by the date of the row): The field which I'm serarching for is marked yellow in the screenshot.

Thanks in advance for your help.

答:
If you have data for each day, then you can use rows:

```<code>select t.*,
       sum(logs) over (partition by company
                       order by date
                       rows between 27 preceding and current row
                      ) as logins_4_weeks
from t;
</code>```

Redshift does not yet support range for the window frame, so this is your best bet.

Body:
If you have data for each day, then you can use rows:

select t.*,
       sum(logs) over (partition by company
                       order by date
                       rows between 27 preceding and current row
                      ) as logins_4_weeks
from t;

Redshift does not yet support range for the window frame, so this is your best bet.


问:
Could REST API OPTIONS be used as the HATEOAS only request?
As I've understood it, REST MUST use the HATEOAS constraint to be implemented properly. My understanding of HATEOAS is that basically every resource should share information about what communication options it has and how the consumer can use those options to achieve their end goal.

My question is if the HTTP OPTIONS method could be used as a way to navigate a REST API. Basically the response from an OPTIONS request would include the possible actions to take on a resource which would make it possible to consume the API without knowing the endpoints.

e.g.
An initial request to the API

```<code>HTTP OPTIONS /api
</code>```

Could return all resources available for consumption and their relations. Like a massive tree to consume the API and all it has to offer. This idea doesn't neglect implementing HATEOAS on other responses as well, but the OPTIONS request would allow navigation without returning data that the consumer might not actually want to consume.

Is this a really bad idea? Or is it something that is commonly implemented. I'm currently attempting to  implement a REST API but I'm having a hard time understanding the benefit of HATEOAS if there is no way to navigate the API without actually requesting data that you might not necessarily need when consuming certain end points. And I assume HATEOAS aims to make clients consume resources by their relation and not actually hard coding the end point?

TL;DR

Could HTTP OPTIONS request act as a way to navigate a REST API by returning what communication options are available for the requested resource without actually returning the resource?

答:
According to RFC 7231

The OPTIONS HTTP method requests information about the communication options available for the target resource, at either the origin server or an intervening intermediary. This method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action.

...

A server generating a successful response to OPTIONS SHOULD send any header fields that might indicate optional features implemented by the server and applicable to the target resource (e.g., Allow), including potential extensions not defined by this specification. The response payload, if any, might also describe the communication options in a machine or human-readable representation.  A standard format for such a representation is not defined by this specification, but might be defined by future extensions to HTTP.  A server MUST generate a Content-Length field with a value of "0" if no payload body is to be sent in the response.

So, basically a response to an OPTIONS request will tell your client which HTTP operations may be performed on a certain resource. It is furthermore admissible to target the whole server on utilizing * instead of a specific resource URI.

A response to an OPTIONS request may look like this:

```<code>HTTP/1.1 204 No Content
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Date: Thu, 13 Oct 2016 11:45:00 GMT
Expires: Thu, 20 Oct 2016 11:45:00 GMT
Server: EOS (lax004/2813)
x-ec-custom-error: 1
</code>```

which states that a certain resource supports the mentioned operations in the Allow header of the resonse. Via the Cache-Control header a client knows that it by default can cache responses of safe requests (GET and HEAD) for up to 7 days (value is mentioned in seconds). The x-ec-custom-error header specifies a non-standard header that is specific to a particular software, in that particular case to a ECS Server. According to this Q & A the meaning isn't publicly documented and therefore application specific.

In regards to returning a tree of traversable resources from the given resource the OPTIONS operation was requested for, technically this could be possible, however, certain systems might produce an almost never-ending list of URIs. Therefore such a design is questionable for larger systems.

My understanding of HATEOAS is that basically every resource should share information about what communication options it has and how the consumer can use those options to achieve their end goal.

Hypertext as the engine of application state (HATEOAS) is basically just a requirement to use the interaction model used on the Web for decades quite successfully and offer the same functionality to applications. This enabled applications to surf  the Web similar like we humans do.

Great, but how does it work?

On the Web we use links and Web forms all the time. Through a Web form a server is able to teach a client basically what properties a certain resource supports or expects. But that's not all! The same form also tells your client where to send the request to (target URI), the HTTP method to use and, usually implicitly given, the media type the payload needs to be serialized to upon sending the request to the server. This, in essence, makes out-of-band API documentation unnecessary as all the information a client needs to make a valid request is given by the server already.

On a typical Web site you might have a table of entries which offers the option to add new entries, update or delete existing ones. Usually such links are hidden behind fancy images, i.e. a dustbin for deleting an entry and a pencil for editing an existing entry or the like where the image represents an affordance. The affordance of certain elements make it clear what you should do with it or what's the purpose of that element. A button on a page wants to be pushed while a slider widget wants to be changed while a text field waits for user input. As applications aren't that eager to work on images a further concept is used instead. Link relation names exactly serve this purpose. I.e. if you have a pageable collection consisting of multiple page à 25 entries i.e. you might be familiar with a widget containing arrows to page through that collection. A link here should usually be annotated with link relation names such as self, next, prev, first or last. The purpose of such links is quite clear, some others like prefetch, that indicates that a resource can be loaded in the background early as it is very likely that the next action may request it, might be less intuitive at first. Such link relation names should be standardized or at least follow the Web Linking extension mechanism.

Through the help of link-relation names a client that knows to look for URIs annotated with next i.e. will still work if the server decides to change its URI scheme as it treats the URI rather opaque.

Of course, both client and server need to support the same media type that furthermore is able to represent such capabilities. Plain application/json is i.e. not able to provide such a support. HAL JSON or JSON Hyper-Schema at least add support for links and link relation names to JSON based documents, while hal-forms, halo+json (halform) and ion might be used to teach a client how a request needs to be created. The question here shouldn't be which media type to support but how many different ones you want to support as the more media types your API is able to handle, the more likely it will be to interact with arbitrary clients not under your control.

These concepts allow you to basically use the controls given in the server response to "drive your workflow" forward. In essence, what you, as an API designer should do is to design the interactions of a client with your API so that it follows a certain, as Jim Webber termed it, domain application protocol or state machine as Asbjørn Ulsberg put it that basically guides a client through its task, i.e. ordering from your shop API.

So, in short, HATEOAS is comparable to Web surfing for applications by making use of named link relations and form-like media type representations that allow you to take actions solely on the response retrieved from a server directly instead of having to bake external knowledge stemming from some reference documentation page (Swagger, OpenAPI or the like) into your application.

But how does HATEOAS benefit the consumer in practice then?

First, it does not have to consult any external documentation other maybe than the current media type specification, though usually support for well-known media types is already backed into popular frameworks or at least allows to add support through plugins or further libraries. Once the media type is understood and supported interactions with all serivces that also support the same media type is possible, regardless of their domain. This allows to reuse the same client implementation to interact with service A and service B out of the box. In an RPC-like systems you'd need to integrate the API of service A first and if you want to interact with service B also you need to integrate those API separately. It's most likely that these APIs are incompatible and thus don't allow the reusage of the same classes.

Without knowing the URL for a resource, is the idea that the consumer can discover it by browsing the API, but they will still have a hard dependency on the actual URL? Or is HATEOAS purpose to leverage actions on a certain resource, i.e. the consumer knows the users end-point but he does not need to know the end-points for actions to take on the users resource cause those are provided by the API?

A client usually does not care about the URI itself, it cares about the content a URI may provide. Compare this to your typical browsing behavior. Do you prefer a meaningful text that summarizes that links content so you can decide whether to request that resource or do you prefer parsing and dissecting a URI to learn what it might do? Minifying or obfuscating URIs will do you no favor in the latter case though.

A further danger arise from URIs and resources that a client put meaning to. A slopy developer will interpret such URIs/resources and implement a tiny hack to interact with that service assuming the URI/resource will remain static. I.e. it is not unreasonable to consider a URI /api/users/1 to return some user related data and based on the response format a tiny Java class is written that expects to receive a field for username and one for email i.e.. If the server now decides to add additional data or rename its fields, the client suddenly will not be able to interact with that service further. And rest assured that in practice, especially in the EDI domain, you will have to interact with clients that are not meant to interact with the Web or where programmers implemented their own JSON framework that can't coope with changing orders of elements or can't handle additional optional fields, even though the spec contains notes on those issues. Fielding claimed that

A REST API should never have “typed” resources that are significant to the client. Specification authors may use resource types for describing server implementation behind the interface, but those types must be irrelevant and invisible to the client. The only types that are significant to a client are the current representation’s media type and standardized relation names. [ditto] (Source)

Instead of typed resources content type negotiation should be used to support interoperability of different stackholders in the network.

As such, the URI itself is just the identifier of a resource that is mainly used to learn where to send a request to. Through the help of meaningful link relation names a client should know that it is interested in i.e. http:/www.acme.com/rel/orders if it wants to send an order to the service and just looks up the URI that either is annotated with that Web Linking extension realtion name or that has an URI attached to it. Whether the link relation name is just an annotation (i.e. a further attribute on the URI element) or the URI being attached to the link-relation name (i.e. as an embedded object of the link relation name) is dependent on the actual media type. This way, if a server ever decides to change its URI scheme or move around resources, for whatever reason, the client will still be able to find the URI that way and it couldn't care less about the characters present in the URI or not. It just treats the URI as opaque thing. The nice thing here is, that a URI can be annotated with multiple link relation names simultaneously, which allows a server to "offer" that URI to clients that support different link-relation names. In the case of forms the URI to send the request to is probably contained in the action attribute of the form element or the like.

As you hopefully can see, with HATEOAS there is no need for a hard dependency on URIs, if so there may be a dependency on the link-relation name though. It still requires URIs to learn where to send the request to, but through looking up the URI via its accompanying link relation name you make the handling of URIs much more dynamic as it allows a server to change the URI anytime it wants to or has to.

Body:
As I've understood it, REST MUST use the HATEOAS constraint to be implemented properly. My understanding of HATEOAS is that basically every resource should share information about what communication options it has and how the consumer can use those options to achieve their end goal.

My question is if the HTTP OPTIONS method could be used as a way to navigate a REST API. Basically the response from an OPTIONS request would include the possible actions to take on a resource which would make it possible to consume the API without knowing the endpoints.

e.g.
An initial request to the API

HTTP OPTIONS /api

Could return all resources available for consumption and their relations. Like a massive tree to consume the API and all it has to offer. This idea doesn't neglect implementing HATEOAS on other responses as well, but the OPTIONS request would allow navigation without returning data that the consumer might not actually want to consume.

Is this a really bad idea? Or is it something that is commonly implemented. I'm currently attempting to  implement a REST API but I'm having a hard time understanding the benefit of HATEOAS if there is no way to navigate the API without actually requesting data that you might not necessarily need when consuming certain end points. And I assume HATEOAS aims to make clients consume resources by their relation and not actually hard coding the end point?

TL;DR

Could HTTP OPTIONS request act as a way to navigate a REST API by returning what communication options are available for the requested resource without actually returning the resource?

Body:
According to RFC 7231

The OPTIONS HTTP method requests information about the communication options available for the target resource, at either the origin server or an intervening intermediary. This method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action.

...

A server generating a successful response to OPTIONS SHOULD send any header fields that might indicate optional features implemented by the server and applicable to the target resource (e.g., Allow), including potential extensions not defined by this specification. The response payload, if any, might also describe the communication options in a machine or human-readable representation.  A standard format for such a representation is not defined by this specification, but might be defined by future extensions to HTTP.  A server MUST generate a Content-Length field with a value of "0" if no payload body is to be sent in the response.

So, basically a response to an OPTIONS request will tell your client which HTTP operations may be performed on a certain resource. It is furthermore admissible to target the whole server on utilizing * instead of a specific resource URI.

A response to an OPTIONS request may look like this:

HTTP/1.1 204 No Content
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Date: Thu, 13 Oct 2016 11:45:00 GMT
Expires: Thu, 20 Oct 2016 11:45:00 GMT
Server: EOS (lax004/2813)
x-ec-custom-error: 1

which states that a certain resource supports the mentioned operations in the Allow header of the resonse. Via the Cache-Control header a client knows that it by default can cache responses of safe requests (GET and HEAD) for up to 7 days (value is mentioned in seconds). The x-ec-custom-error header specifies a non-standard header that is specific to a particular software, in that particular case to a ECS Server. According to this Q & A the meaning isn't publicly documented and therefore application specific.

In regards to returning a tree of traversable resources from the given resource the OPTIONS operation was requested for, technically this could be possible, however, certain systems might produce an almost never-ending list of URIs. Therefore such a design is questionable for larger systems.

My understanding of HATEOAS is that basically every resource should share information about what communication options it has and how the consumer can use those options to achieve their end goal.

Hypertext as the engine of application state (HATEOAS) is basically just a requirement to use the interaction model used on the Web for decades quite successfully and offer the same functionality to applications. This enabled applications to surf  the Web similar like we humans do.

Great, but how does it work?

On the Web we use links and Web forms all the time. Through a Web form a server is able to teach a client basically what properties a certain resource supports or expects. But that's not all! The same form also tells your client where to send the request to (target URI), the HTTP method to use and, usually implicitly given, the media type the payload needs to be serialized to upon sending the request to the server. This, in essence, makes out-of-band API documentation unnecessary as all the information a client needs to make a valid request is given by the server already.

On a typical Web site you might have a table of entries which offers the option to add new entries, update or delete existing ones. Usually such links are hidden behind fancy images, i.e. a dustbin for deleting an entry and a pencil for editing an existing entry or the like where the image represents an affordance. The affordance of certain elements make it clear what you should do with it or what's the purpose of that element. A button on a page wants to be pushed while a slider widget wants to be changed while a text field waits for user input. As applications aren't that eager to work on images a further concept is used instead. Link relation names exactly serve this purpose. I.e. if you have a pageable collection consisting of multiple page à 25 entries i.e. you might be familiar with a widget containing arrows to page through that collection. A link here should usually be annotated with link relation names such as self, next, prev, first or last. The purpose of such links is quite clear, some others like prefetch, that indicates that a resource can be loaded in the background early as it is very likely that the next action may request it, might be less intuitive at first. Such link relation names should be standardized or at least follow the Web Linking extension mechanism.

Through the help of link-relation names a client that knows to look for URIs annotated with next i.e. will still work if the server decides to change its URI scheme as it treats the URI rather opaque.

Of course, both client and server need to support the same media type that furthermore is able to represent such capabilities. Plain application/json is i.e. not able to provide such a support. HAL JSON or JSON Hyper-Schema at least add support for links and link relation names to JSON based documents, while hal-forms, halo+json (halform) and ion might be used to teach a client how a request needs to be created. The question here shouldn't be which media type to support but how many different ones you want to support as the more media types your API is able to handle, the more likely it will be to interact with arbitrary clients not under your control.

These concepts allow you to basically use the controls given in the server response to "drive your workflow" forward. In essence, what you, as an API designer should do is to design the interactions of a client with your API so that it follows a certain, as Jim Webber termed it, domain application protocol or state machine as Asbjørn Ulsberg put it that basically guides a client through its task, i.e. ordering from your shop API.

So, in short, HATEOAS is comparable to Web surfing for applications by making use of named link relations and form-like media type representations that allow you to take actions solely on the response retrieved from a server directly instead of having to bake external knowledge stemming from some reference documentation page (Swagger, OpenAPI or the like) into your application.

But how does HATEOAS benefit the consumer in practice then?

First, it does not have to consult any external documentation other maybe than the current media type specification, though usually support for well-known media types is already backed into popular frameworks or at least allows to add support through plugins or further libraries. Once the media type is understood and supported interactions with all serivces that also support the same media type is possible, regardless of their domain. This allows to reuse the same client implementation to interact with service A and service B out of the box. In an RPC-like systems you'd need to integrate the API of service A first and if you want to interact with service B also you need to integrate those API separately. It's most likely that these APIs are incompatible and thus don't allow the reusage of the same classes.

Without knowing the URL for a resource, is the idea that the consumer can discover it by browsing the API, but they will still have a hard dependency on the actual URL? Or is HATEOAS purpose to leverage actions on a certain resource, i.e. the consumer knows the users end-point but he does not need to know the end-points for actions to take on the users resource cause those are provided by the API?

A client usually does not care about the URI itself, it cares about the content a URI may provide. Compare this to your typical browsing behavior. Do you prefer a meaningful text that summarizes that links content so you can decide whether to request that resource or do you prefer parsing and dissecting a URI to learn what it might do? Minifying or obfuscating URIs will do you no favor in the latter case though.

A further danger arise from URIs and resources that a client put meaning to. A slopy developer will interpret such URIs/resources and implement a tiny hack to interact with that service assuming the URI/resource will remain static. I.e. it is not unreasonable to consider a URI /api/users/1 to return some user related data and based on the response format a tiny Java class is written that expects to receive a field for username and one for email i.e.. If the server now decides to add additional data or rename its fields, the client suddenly will not be able to interact with that service further. And rest assured that in practice, especially in the EDI domain, you will have to interact with clients that are not meant to interact with the Web or where programmers implemented their own JSON framework that can't coope with changing orders of elements or can't handle additional optional fields, even though the spec contains notes on those issues. Fielding claimed that

A REST API should never have “typed” resources that are significant to the client. Specification authors may use resource types for describing server implementation behind the interface, but those types must be irrelevant and invisible to the client. The only types that are significant to a client are the current representation’s media type and standardized relation names. [ditto] (Source)

Instead of typed resources content type negotiation should be used to support interoperability of different stackholders in the network.

As such, the URI itself is just the identifier of a resource that is mainly used to learn where to send a request to. Through the help of meaningful link relation names a client should know that it is interested in i.e. http:/www.acme.com/rel/orders if it wants to send an order to the service and just looks up the URI that either is annotated with that Web Linking extension realtion name or that has an URI attached to it. Whether the link relation name is just an annotation (i.e. a further attribute on the URI element) or the URI being attached to the link-relation name (i.e. as an embedded object of the link relation name) is dependent on the actual media type. This way, if a server ever decides to change its URI scheme or move around resources, for whatever reason, the client will still be able to find the URI that way and it couldn't care less about the characters present in the URI or not. It just treats the URI as opaque thing. The nice thing here is, that a URI can be annotated with multiple link relation names simultaneously, which allows a server to "offer" that URI to clients that support different link-relation names. In the case of forms the URI to send the request to is probably contained in the action attribute of the form element or the like.

As you hopefully can see, with HATEOAS there is no need for a hard dependency on URIs, if so there may be a dependency on the link-relation name though. It still requires URIs to learn where to send the request to, but through looking up the URI via its accompanying link relation name you make the handling of URIs much more dynamic as it allows a server to change the URI anytime it wants to or has to.


问:
TestNG not Compatible with Eclipse Luna and Eclipse Indigo
I installed TestNG in Eclipse Luna and Eclipse Indigo but TestNG is not showing in the preferences window. I followed right step 2 times as mentioned at below link

http://www.guru99.com/all-about-testng-and-selenium.html

It is giving me the same problem in both versions of Eclipse... Any suggestion how to start working with TestNG?

答:
May be late to the Party but this works for me:

```<code>Install from update site
Select Help / Install New Software...
Enter the update site URL in "Work with:" field:
Update site for release: https://dl.bintray.com/testng-team/testng-eclipse-release/.
Make sure the check box next to URL is checked and click Next.
Eclipse will then guide you through the process.
</code>```

Link

Body:
May be late to the Party but this works for me:

Install from update site
Select Help / Install New Software...
Enter the update site URL in "Work with:" field:
Update site for release: https://dl.bintray.com/testng-team/testng-eclipse-release/.
Make sure the check box next to URL is checked and click Next.
Eclipse will then guide you through the process.

Link


问:
Coloring subsets in PCA biplot
I am working on a gene expression data frame called expression. My samples belong to different subgroups, indicated in the colname (i.e. all samples that contain "adk" in their colname belong to the same subgroup)

```<code>       adk1  adk2  bas1  bas2  bas3  non1  ...
gene1   1.1   1.3   2.2   2.3   2.8   1.6
gene2   2.5   2.3   4.1   4.6   4.2   1.9
gene3   1.6   1.8   0.5   0.4   0.9   2.2
...
</code>```

I already defined subsets using

```<code>adk <- expression[grepl('adk', names(expression))]
</code>```

I then did a PCA on this data set using

```<code>pca = prcomp (t(expression), center = F, scale= F)
</code>```

I now want to plot the PCs I got from the PCA against each other in a PCA biplot. For this, I want all samples that belong to the same subgroup to have the same color (so e.g. all "adk" samples should be green, all "bas" samples should be red and all "non" samples should be blue). I tried to use the color argument of the autoplot function from ggfortify, but I wansn't able to make it use my defined subsets.

I would be glad if someone could help me with this! Thanks :)

Edit: I'd like to give you an example of what I want to do, using the USArrests dataset:

```<code>head(USArrests)
           Murder Assault UrbanPop Rape
Alabama      13.2     236       58 21.2
Alaska       10.0     263       48 44.5
Arizona       8.1     294       80 31.0
Arkansas      8.8     190       50 19.5
California    9.0     276       91 40.6
Colorado      7.9     204       78 38.7

## Doing a PCA on the USArrests dataset

US.pca = prcomp(t(USArrests), center = F, scale = F)

## Now I can create a PCA biplot of PC1 and PC2 using the autoplot function (since I have ggfortify installed)

biplot1 = autoplot(US.pca,data=t(USArrests), x=1, y=2)
</code>```

I want all samples that contain an "e" in their colname (in this case "Murder" and "Rape") to be the same color. The "UrbanPop" and the "Assault" sample should be an individual color as well. I hope this makes things a little clearer :)

P.S. I run R in the latest version of RStudio on Windows 10

答:
You could try to use the library factoextra

Below an example.

```<code>      library("factoextra")
      library("FactoMineR")
      data("decathlon2")
      df <- decathlon2[1:23, 1:10]
      res.pca <- PCA(df,  graph = FALSE)
      fviz_pca_biplot(res.pca, repel = TRUE)
</code>```

Title: Coloring subsets in PCA biplot

Body:
I am working on a gene expression data frame called expression. My samples belong to different subgroups, indicated in the colname (i.e. all samples that contain "adk" in their colname belong to the same subgroup)

       adk1  adk2  bas1  bas2  bas3  non1  ...
gene1   1.1   1.3   2.2   2.3   2.8   1.6
gene2   2.5   2.3   4.1   4.6   4.2   1.9
gene3   1.6   1.8   0.5   0.4   0.9   2.2
...

I already defined subsets using

adk <- expression[grepl('adk', names(expression))]

I then did a PCA on this data set using

pca = prcomp (t(expression), center = F, scale= F)

I now want to plot the PCs I got from the PCA against each other in a PCA biplot. For this, I want all samples that belong to the same subgroup to have the same color (so e.g. all "adk" samples should be green, all "bas" samples should be red and all "non" samples should be blue). I tried to use the color argument of the autoplot function from ggfortify, but I wansn't able to make it use my defined subsets.

I would be glad if someone could help me with this! Thanks :)

Edit: I'd like to give you an example of what I want to do, using the USArrests dataset:

head(USArrests)
           Murder Assault UrbanPop Rape
Alabama      13.2     236       58 21.2
Alaska       10.0     263       48 44.5
Arizona       8.1     294       80 31.0
Arkansas      8.8     190       50 19.5
California    9.0     276       91 40.6
Colorado      7.9     204       78 38.7

## Doing a PCA on the USArrests dataset

US.pca = prcomp(t(USArrests), center = F, scale = F)

## Now I can create a PCA biplot of PC1 and PC2 using the autoplot function (since I have ggfortify installed)

biplot1 = autoplot(US.pca,data=t(USArrests), x=1, y=2)

I want all samples that contain an "e" in their colname (in this case "Murder" and "Rape") to be the same color. The "UrbanPop" and the "Assault" sample should be an individual color as well. I hope this makes things a little clearer :)

P.S. I run R in the latest version of RStudio on Windows 10

Body:
You could try to use the library factoextra

Below an example.

      library("factoextra")
      library("FactoMineR")
      data("decathlon2")
      df <- decathlon2[1:23, 1:10]
      res.pca <- PCA(df,  graph = FALSE)
      fviz_pca_biplot(res.pca, repel = TRUE)


问:
Calculate a pair of dates connected together
The following code outputs me next Friday and next Sunday. I need to output next Friday and next Sunday after the outputted Friday ,not just next Sunday. Otherwise If today is Friday or Saturday, It won't work.

Example: if today is Friday 05/06 my output will be Friday 05/13 and Sunday 05/07 instead of Sunday 05/15 (that is the output I need).

That is the code I'm using actually. How can I fix it to make it work ?

```<code><script type="text/javascript">
 function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date||new Date());
  ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
  return ret;
}

var date = new Date();
console.log(nextWeekdayDate(date, 5));

    $(document).ready(function() {
    $('#button').click(function(e) {
        var checkinf = nextWeekdayDate(null, 5);
        var [yyyy, mm, dd] = checkinf.toISOString().split('T')[0].split('-');
        var checkouts = nextWeekdayDate(null, 7);
            var [cyyy, cm, cd] = checkouts.toISOString().split('T')[0].split('-');

             window.open( "https://www.mydynamiclink.com" + variables );

                            });

        });

</script>

</code>```

thanks :)

答:
I think for the checkouts, you can simply increase the checkinf by two days if your  checkinf are correctly outputted.

What I mean is this:
 Instead of var checkouts = nextWeekdayDate(null, 7);

Your should do this:

var checkouts = checkinf.setDate(checkinf.getDay() + 2); //For the next sunday

Body:
The following code outputs me next Friday and next Sunday. I need to output next Friday and next Sunday after the outputted Friday ,not just next Sunday. Otherwise If today is Friday or Saturday, It won't work.

Example: if today is Friday 05/06 my output will be Friday 05/13 and Sunday 05/07 instead of Sunday 05/15 (that is the output I need).

That is the code I'm using actually. How can I fix it to make it work ?

thanks :)


问:
Getting others to use my apps with Visual C++
I am learning how to build games in Visual C++ and when I upload them so friends can check them out, they all end up with messages saying it can not run. I did some research and found that it is because I am compiling against a Dynamic library instead of a static library. Correct me if I am wrong anywhere please. Upon further research, I found that a lot of people do not advise going this direction but instead include the files needed by my game. </p>

<p>How would I go about distributing my games to friends and make it real easy for them to just open up my .exe and play the game? </p>

答: If you link to any DLLs, you also need to ship those along.  If you produce a single .exe in your output, you probably need your friends to install the MS Visual Studio redistributable package for your version of visual studio.  This is an example link for the VS 2010 one, but the one you give your friends should match your version.</p>

Body:
I am learning how to build games in Visual C++ and when I upload them so friends can check them out, they all end up with messages saying it can not run. I did some research and found that it is because I am compiling against a Dynamic library instead of a static library. Correct me if I am wrong anywhere please. Upon further research, I found that a lot of people do not advise going this direction but instead include the files needed by my game.

How would I go about distributing my games to friends and make it real easy for them to just open up my .exe and play the game?


问:
how to extract exactly those element from a column which is given in a list?
In the given data below  q is a list with some data and i want that if same data is present in z then only the element will appear

```<code> q=["q","e","z"]

 data frame
    0
   "q"
   "w"
   "e"
   "t"
   "e"
   "g"
   "t"
   "j"
   "k"
   "u"
   "z"
</code>```

desired result is

```<code> z="q"
   "e"
   "e"
   "z"
</code>```

答:
Still applicable if the data in 'z' is from a column of data, i.e. pandas or a list...the provided answer would need very light modification</p>

```<code>q
Out[11]: ['q', 'e', 'z']

z
Out[12]: ['q', 'w', 'e', 't', 'e', 'g', 't', 'j', 'k', 'u', 'z']

a = [ q_elm for q_elm in q for z_elm in z if q_elm==z_elm ]

a
Out[14]: ['q', 'e', 'e', 'z']

import pandas as pd

z = pd.DataFrame.from_dict({'someFancyKey':z})

z
Out[17]:
    0
0   q
1   w
2   e
3   t
4   e
5   g
6   t
7   j
8   k
9   u
10  z

a = [ q_elm for q_elm in q for z_elm in z['someFancyKey'] if q_elm==z_elm ]

a
Out[19]: ['q', 'e', 'e', 'z']
</code>```

Body:
In the given data below  q is a list with some data and i want that if same data is present in z then only the element will appear

 q=["q","e","z"]

 data frame
    0
   "q"
   "w"
   "e"
   "t"
   "e"
   "g"
   "t"
   "j"
   "k"
   "u"
   "z"

desired result is

 z="q"
   "e"
   "e"
   "z"

Body:
Still applicable if the data in 'z' is from a column of data, i.e. pandas or a list...the provided answer would need very light modification

q
Out[11]: ['q', 'e', 'z']

z
Out[12]: ['q', 'w', 'e', 't', 'e', 'g', 't', 'j', 'k', 'u', 'z']

a = [ q_elm for q_elm in q for z_elm in z if q_elm==z_elm ]

a
Out[14]: ['q', 'e', 'e', 'z']

import pandas as pd

z = pd.DataFrame.from_dict({'someFancyKey':z})

z
Out[17]:
    0
0   q
1   w
2   e
3   t
4   e
5   g
6   t
7   j
8   k
9   u
10  z

a = [ q_elm for q_elm in q for z_elm in z['someFancyKey'] if q_elm==z_elm ]

a
Out[19]: ['q', 'e', 'e', 'z']


问:
Weird event behavior in a Popup inside a DataGridColumnHeader
I'm not using any external libraries here, just plain WPF.

I have a DataGrid with a custom DataGridColumnHeader. This column header contains a ToggleButton to toggle a Popup. Inside the popup there is a TextBox. The problem I'm having is that doubleclicking inside the TextBox raises the MouseDoubleClick event on the DataGrid. Here's a simplified version containing numbered comments I will refer to afterwards

```<code><Window x:Class="PopupsAreWeird.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PopupsAreWeird" xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridColumnHeader">
                        <!-- 1) This eventhandler is never called -->
                        <Grid Control.MouseDoubleClick="Grid_MouseDoubleClick_1">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>

                            <ContentPresenter Grid.Column="0" />
                            <ToggleButton x:Name="openToggle" Grid.Column="1" Content="Open" />

                            <Popup IsOpen="{Binding ElementName=openToggle, Path=IsChecked}" StaysOpen="True">
                                <!-- 2) This eventhandler is always called, and the problem I am having is there regardless of whether I set e.Handled = true in this handler or not -->
                                <TextBox Width="200" MouseDoubleClick="TextBox_MouseDoubleClick" />
                            </Popup>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <!-- 3) This eventhandler is always called, but never should be -->
        <DataGrid MouseDoubleClick="DataGrid_MouseDoubleClick">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Header 1" Width="200" />
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Window>
</code>```

1) I do not understand why this handler is never called. This was meant to set e.Handled to true to stop bubbling upwards to the DataGrid. While Grid does not have a definition for MouseDoubleClick, it is my understanding that I can attach eventhandlers for any event to any element (like attaching ButtonBase.Click to a Panel element). Is this not true, or is there any special case here I am missing?

3) I want to avoid the double click event bubbling to here, but even if I set e.Handled to true in eventhandler 2, this eventhandler is called, and in that handler, e.Handled is false. I assume the reason is that the Popup is defined inside of DataGridColumnHeader, and for some weird reason 2 events are being raised, one for the tree of the popup, and one for the tree that contains the Popup element, but that seems a bit nonsensical.

I know Popup is a sort of weird thing in WPF, but this seems like I'm missing something obvious. Is there any way to achieve what I want, i.e. not have events (or at least the MouseDoubleClick event) bubble up to the DataGrid?

Thanks in advance,
David

答:
1) You are right, You can attach a handler for a routed event to any UIElement. But indeed the Popup is a special case. The Popup is a special control that behaves like Window. It can popup everywhere on the screen, always rendered top-most and is not necessarily bound to the application itself. That's why its visual tree is detached from the application's visual tree. Popup.Child will be a separate isolated visual tree. Microsoft Docs: Popup and the Visual Tree.

Since routed events traverse the visual tree to be handled by any node, it makes sense that bubbling/tunneling routed events inside the Popup will stop/start at the root of this isolated tree. So routed events that are originated in the Popup cannot be handled outside the Popup.

3) Short version: Control.MouseDoubleClick (and the preview version) is a special event that behaves different. This event is raised on each UIElement on the route when the event traverses the visual tree. So setting Handled to true has no effect.

To solve your problem, you should either handle UIElement.PreviewMousLeftButtonDown and check if the MouseButtonEventArgs.ClickCount equals 2 to detect a double click and then set Handled = true

or check if the type of the sender or RoutedEventArgs.Source is not TextBox before handling it (explicit event filtering).

"Although this routed event seems to follow a bubbling route through
  an element tree, it actually is a direct routed event that is raised
  along the element tree by each UIElement. If you set the Handled
  property to true in a MouseDoubleClick event handler, subsequent
  MouseDoubleClick events along the route will occur with Handled set to
  false. This is a higher-level event for control consumers who want to
  be notified when the user double-clicks the control and to handle the
  event in an application.

Control authors who want to handle mouse double clicks should use the
  MouseLeftButtonDown event when ClickCount is equal to two. This will
  cause the state of Handled to propagate appropriately in the case
  where another element in the element tree handles the event.

The Control class defines the PreviewMouseDoubleClick and
  MouseDoubleClick events, but not corresponding single-click events. To
  see if the user has clicked the control once, handle the MouseDown
  event (or one of its counterparts) and check whether the ClickCount
  property value is 1."

  Microsoft Docs: Control.MouseDoubleClick

Body:
I'm not using any external libraries here, just plain WPF.

I have a DataGrid with a custom DataGridColumnHeader. This column header contains a ToggleButton to toggle a Popup. Inside the popup there is a TextBox. The problem I'm having is that doubleclicking inside the TextBox raises the MouseDoubleClick event on the DataGrid. Here's a simplified version containing numbered comments I will refer to afterwards

<Window x:Class="PopupsAreWeird.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PopupsAreWeird" xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>

    </Window.Resources>
    <StackPanel Orientation="Vertical">

        <DataGrid MouseDoubleClick="DataGrid_MouseDoubleClick">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Header 1" Width="200" />
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Window>

1) I do not understand why this handler is never called. This was meant to set e.Handled to true to stop bubbling upwards to the DataGrid. While Grid does not have a definition for MouseDoubleClick, it is my understanding that I can attach eventhandlers for any event to any element (like attaching ButtonBase.Click to a Panel element). Is this not true, or is there any special case here I am missing?

3) I want to avoid the double click event bubbling to here, but even if I set e.Handled to true in eventhandler 2, this eventhandler is called, and in that handler, e.Handled is false. I assume the reason is that the Popup is defined inside of DataGridColumnHeader, and for some weird reason 2 events are being raised, one for the tree of the popup, and one for the tree that contains the Popup element, but that seems a bit nonsensical.

I know Popup is a sort of weird thing in WPF, but this seems like I'm missing something obvious. Is there any way to achieve what I want, i.e. not have events (or at least the MouseDoubleClick event) bubble up to the DataGrid?

Thanks in advance,
David


问:
SQL Server Management Studio -- where is Tools/Import and Export settings menu?
In Visual Studio, there is an Import and Export settings wizard which you can use to customize Visual Studio and save settings to a .settings file.

Do we have something like it in SQL Server Management Studio?

I'm constantly switching between several VM's and configuring each SSMS is a pain in the neck. I want to be able to save my settings to a file, then import it in all my VM's.

Thank you.

答:
Tools/Import and Export settings menu option disappeared from my menubar too (both for 2005 and 2008 SSMS versions), but I had and used it on my previous machine.

For now I copy my archived settings to destination like c:\Documents and Settings\gg\Moje dokumenty\SQL Server Management Studio Express\Settings\CurrentSettings-2008-09-30.vssettings.

And it works.


问:
Analysis of Eye-Tracking data in python (Eye-link)
I have data from eye-tracking (.edf file - from Eyelink by SR-research). I want to analyse it and get various measures such as fixation, saccade, duration, etc.
Is there an existing package to analyse Eye-Tracking data?
Thanks!</p>

答:
pyeparse seems to be another (yet currently unmaintained as it seems) library that can be used for eyelink data analysis.

Here is a short excerpt from their example:

```<code>import numpy as np
import matplotlib.pyplot as plt

import pyeparse as pp

fname = '../pyeparse/tests/data/test_raw.edf'

raw = pp.read_raw(fname)

# visualize initial calibration
raw.plot_calibration(title='5-Point Calibration')

# create heatmap
raw.plot_heatmap(start=3., stop=60.)
</code>```

EDIT: After I posted my answer I found a nice list compiling lots of potential tools for eyelink edf data analysis: https://github.com/davebraze/FDBeye/wiki/Researcher-Contributed-Eye-Tracking-Tools

Body:
pyeparse seems to be another (yet currently unmaintained as it seems) library that can be used for eyelink data analysis.

Here is a short excerpt from their example:

import numpy as np
import matplotlib.pyplot as plt

import pyeparse as pp

fname = '../pyeparse/tests/data/test_raw.edf'

raw = pp.read_raw(fname)

# visualize initial calibration
raw.plot_calibration(title='5-Point Calibration')

# create heatmap
raw.plot_heatmap(start=3., stop=60.)

EDIT: After I posted my answer I found a nice list compiling lots of potential tools for eyelink edf data analysis: https://github.com/davebraze/FDBeye/wiki/Researcher-Contributed-Eye-Tracking-Tools


问:
Docker cannot start on Windows
Executing docker version command on Windows returns the following results:

```<code>C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
</code>```

Running the diagnostics produces the following:

```<code>C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at <ScriptBlock>, <No file>: line 27
 [+] Service is running 127ms
 [+] Docker.exe is in path 2.14s
Describing User has permissions to use Docker daemon
 [+] docker.exe should not return access denied 42ms
Describing Windows container settings are correct
 [-] Do not have DisableVSmbOplock set to 1 53ms
   Expected: {0}
   But was:  {1}
   66:              $regvalue.VSmbDisableOplocks | Should Be 0
   at <ScriptBlock>, <No file>: line 66
 [+] Do not have zz values set 42ms
Describing The right container base images are installed
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/images/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
 [-] At least one of 'microsoft/windowsservercore' or 'microsoft/nanoserver' should be installed 129ms
   ValidationMetadataException: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   ParameterBindingValidationException: Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   at <ScriptBlock>, <No file>: line 90
Describing Container network is created
 [-] Error occurred in Describe block 1.08s
   RuntimeException: Cannot index into a null array.
   at <ScriptBlock>, <No file>: line 119
Showing output from: docker info

Showing output from: docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64

Showing output from: docker network ls

Warnings & errors from the last 24 hours
Logs saved to C:\Projects\logs_20161107-084122.csv
C:\Projects>
</code>```

答: For me this issue resolved by singing in Docker Desktop.

Title: Docker cannot start on Windows

Body:
Executing docker version command on Windows returns the following results:

C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

Running the diagnostics produces the following:

C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at


问:
How to inherit methods that return a reference to the current object?
There is a base class

```<code>class LineEditItem
{
public:
    LineEditItem(QLineEdit* le, const Values_t& values = Values_t()):
        values(values),
        le(le)
    {}
    LineEditItem &addValue(int v, const QString &s)
    {
        values[v] = s;
        return *this;
    }
    LineEditItem &addValues(const Values_t& vals)
    {
        for (auto key: vals.keys())
        {
            values[key] = vals[key];
        }
        return *this;
    }
    void setValue(uint32_t v)
    {
        QString str;
        if (values.contains(v))
        {
            str = values[v];
        }
        else
        {
            str = "";
        }
        le->setText(str);
    }
    void clearValue()
    {
        le->clear();
    }

protected:
    Values_t values;
    QLineEdit* le;
};
</code>```

There is a child class that must inherit the addValue and addValues methods

```<code>class LineEditItemBits: public LineEditItem
{
public:
    LineEditItemBits(QLineEdit* le, int begin, int end, const Values_t& values = Values_t()):
        LineEditItem(le, values),
        begin(begin),
        end(end)
    {}
    void setValue(uint32_t v)
    {
        int s = end - begin + 1;
        v = (v >> begin) & ((1 << s) - 1);
        LineEditItem::setValue(v);
    }
    LineEditItemBits &addValue(int v, const QString &s)
    {
        LineEditItem::addValue(v, s);
        return *this;
    }
    LineEditItemBits &addValues(const Values_t& vals)
    {
        LineEditItem::addValues(vals);
        return *this;
    }
private:
    int begin;
    int end;
};
</code>```

But you have to explicitly prescribe these methods and call base class methods from them.
How to inherit these methods from the base class so that they return a reference to the child class?

答: From my understanding you are trying to override these functions, so you should make them virtual in parent class.

Body:
There is a base class

class LineEditItem
{
public:
    LineEditItem(QLineEdit* le, const Values_t& values = Values_t()):
        values(values),
        le(le)
    {}
    LineEditItem &addValue(int v, const QString &s)
    {
        values[v] = s;
        return *this;
    }
    LineEditItem &addValues(const Values_t& vals)
    {
        for (auto key: vals.keys())
        {
            values[key] = vals[key];
        }
        return *this;
    }
    void setValue(uint32_t v)
    {
        QString str;
        if (values.contains(v))
        {
            str = values[v];
        }
        else
        {
            str = "";
        }
        le->setText(str);
    }
    void clearValue()
    {
        le->clear();
    }

protected:
    Values_t values;
    QLineEdit* le;
};

There is a child class that must inherit the addValue and addValues methods

class LineEditItemBits: public LineEditItem
{
public:
    LineEditItemBits(QLineEdit* le, int begin, int end, const Values_t& values = Values_t()):
        LineEditItem(le, values),
        begin(begin),
        end(end)
    {}
    void setValue(uint32_t v)
    {
        int s = end - begin + 1;
        v = (v >> begin) & ((1 << s) - 1);
        LineEditItem::setValue(v);
    }
    LineEditItemBits &addValue(int v, const QString &s)
    {
        LineEditItem::addValue(v, s);
        return *this;
    }
    LineEditItemBits &addValues(const Values_t& vals)
    {
        LineEditItem::addValues(vals);
        return *this;
    }
private:
    int begin;
    int end;
};

But you have to explicitly prescribe these methods and call base class methods from them.
How to inherit these methods from the base class so that they return a reference to the child class?


问:
Python: words replacing in huge text
I have a huge text and a list of words ~10K.
What is the fastest way in Python to replace all this words in text with some other word?

EDIT:
Text size >1Gb, text is human written, and "extremely tokenized" (any runs of alphanumeric characters and any other single symbols was splitted into new tokens)

a number of words >10K, each word frequency in text is 1
the replacement word is same in all replacements.
Python 2.5-2.7

答:
Wow! This is not trivial at all. Here is an idea:

```
Step 1: Quantize the text into words, signs etc.
        The function quantize accepts text as an argument,
        the output is the list of words and signs.
        def quantize(text: str) -> list:
            ...
        An inverse function that can construct the a from a given list:
        def dequantize(lst: list) -> str:
            ....

Step 2: Build a dictionary of quantized list, so that
        d_rep[word] = word
        Then, use the replacements word lists to transform this dictionary as follows:
        d_rep[word] = replacement

Step 3: Go through every word in quantized list and replace it with a value from
        d_rep dictionary. It might be the original word or a replacement.

Step 4: Dequantize the list and restore the text.
```

This should be optimal enough if you have a big text and a huge amount of search/replace words. Good luck! Ask, if you have any implementation questions.

Update:
With a single replacement word, it's even easier, create a set from the '10K' wordlist, and then for every word in quantized list, if word in set, replace it in that list.

In a pseudo-python-code:

```<code>qlist = quantize(text)

for i in range(0, len(qlist)):
    word = qlist[i]
    if word in wordlist_set:
        qlist[i] = 'replacement'

text = dequantize(qlist)
</code>```

Title: Python: words replacing in huge text

Body:
Wow! This is not trivial at all. Here is an idea:

Step 1: Quantize the text into words, signs etc.
        The function quantize accepts text as an argument,
        the output is the list of words and signs.
        def quantize(text: str) -> list:
            ...
        An inverse function that can construct the a from a given list:
        def dequantize(lst: list) -> str:
            ....

Step 2: Build a dictionary of quantized list, so that
        d_rep[word] = word
        Then, use the replacements word lists to transform this dictionary as follows:
        d_rep[word] = replacement

Step 3: Go through every word in quantized list and replace it with a value from
        d_rep dictionary. It might be the original word or a replacement.

Step 4: Dequantize the list and restore the text.

This should be optimal enough if you have a big text and a huge amount of search/replace words. Good luck! Ask, if you have any implementation questions.

Update:
With a single replacement word, it's even easier, create a set from the '10K' wordlist, and then for every word in quantized list, if word in set, replace it in that list.

In a pseudo-python-code:

qlist = quantize(text)

for i in range(0, len(qlist)):
    word = qlist[i]
    if word in wordlist_set:
        qlist[i] = 'replacement'

text = dequantize(qlist)