问:
How can I use forms in libreoffice base to add/modify data in a many-to-many relationship?
I am essentially trying to create a glorified contacts list using LibreOffice Base. Many of our contacts have multiple addresses (office, mailing, home), and sometimes multiple people have the same address.

I've created a simple contacts table with the Contact ID, Last Name, and First Name. I've created an address table with an Address ID, City, State, etc. I've also created a junction table with Contact ID and Address ID, and connected the three tables using the relationships tool.

Now I want to add everything into a single form. I watched this youtube video, which was very helpful, but I want to be able to add new cities instead of only selecting from a pre-established list. So I followed along with the video, but set the columns to "combo box" instead of "list box." However, when I try that I get an error message:

Error inserting the new record

SQL Status: 23000
Error code: -177

Integrity constraint violation - no parent SYS_FK_94 table: Address Table in statement [INSERT INTO "Contact-Address Junction" ( "Address ID","Contact ID") VALUES ( ?,?)]

I assume there's something obvious that I'm missing, but at this point I'm pretty stuck.

E: I took more screenshots to show the relationships, tables, and how things connect in the form:

答:
In the video you cite, this is kind of silly as there is no need for a many to many relationship.  The author could have simply added a Movie ID field to the genre Table, (so multiple genre records can point to each movie record).

I have a complex many-to-many contacts structure that I'm in the process of porting from MS Access to LibreOffice.  It has 4 primary data tables: Groups, Address, Phones, and People.  And there are 6 link tables to connect those primary tables: GroupAddress, GroupPhone, GroupPerson; AddressPhone, AddressPerson; and finaly PhonePerson.  Unlike the video you cite above with only 2 fields, in my link tables there are 3 fields.  GroupAddress for example has GroupAddressID (the unique id for the link table itself), GroupID (which points to the Groups table), and AddressID (which points to the addresses table).  This allows any number of addresses per each group, and at the same time, any number of groups per each address.

So the whole thing has maximum data flexibility:  For example it allows for unlimited number of people per group, each person can have an unlimited number of phones or addresses, each address an unlimited number of people, etc.

Implementing it in LO:  Because in LO you can't edit a query based on more than one table (you can view it, but not edit it), like you can in Access, (and therefore you also can't build a form with a table that can edit a query based on more than one table), in LO this is not as clean as it is in Access.

In Access it works very well and the link tables manage themselves!  In LO you have to manually edit the link tables in a separate table.  I'm starting to think about how I might use some macros to improve on this, but for the moment it's bare bones.

To give you a better idea, the first form to edit Groups, which also edits the group's addresses, people, and phones (not just those tables, but also the links to those tables) looks like this:

```<code>Group lookup pulldown (used to find a group record)
(this is a drop down box with custom code that helps me find group records)

Group editing fields, e.g. Group name, category, url, etc
</code>```

Then below that

```<code>Group-Person links table
</code>```

Then to the right of that

```<code>Persons table (plural) - to create new person, then..
</code>```

And below that

```<code>Person table (singular)
 [pointed to by Group-Person link]
 to view person pointed to.
</code>```

Group-Address links || (similar structure to above)

  (for example, when a business has two or more addresses)

Group-Phone links || (similar structure to above)

  (this is for phone#'s that the group owns directly, not personal phones of the group's members, and not phones tied to specific addresses).

----------

Then there are 3 other similar forms,

one for Addresses w/ Person, Group & Phone links;

one for Phones w/ Group, Address & Person links;

and one for People w/ Group, Address and phone links;

Here is a screen shot of the first of the 4 editing forms, to edit the groups and the links associated with the group:

Hope this helps.  I would be interested to see what you develop.  Thanks.

Body:
In the video you cite, this is kind of silly as there is no need for a many to many relationship.  The author could have simply added a Movie ID field to the genre Table, (so multiple genre records can point to each movie record).

I have a complex many-to-many contacts structure that I'm in the process of porting from MS Access to LibreOffice.  It has 4 primary data tables: Groups, Address, Phones, and People.  And there are 6 link tables to connect those primary tables: GroupAddress, GroupPhone, GroupPerson; AddressPhone, AddressPerson; and finaly PhonePerson.  Unlike the video you cite above with only 2 fields, in my link tables there are 3 fields.  GroupAddress for example has GroupAddressID (the unique id for the link table itself), GroupID (which points to the Groups table), and AddressID (which points to the addresses table).  This allows any number of addresses per each group, and at the same time, any number of groups per each address.

So the whole thing has maximum data flexibility:  For example it allows for unlimited number of people per group, each person can have an unlimited number of phones or addresses, each address an unlimited number of people, etc.

Implementing it in LO:  Because in LO you can't edit a query based on more than one table (you can view it, but not edit it), like you can in Access, (and therefore you also can't build a form with a table that can edit a query based on more than one table), in LO this is not as clean as it is in Access.

In Access it works very well and the link tables manage themselves!  In LO you have to manually edit the link tables in a separate table.  I'm starting to think about how I might use some macros to improve on this, but for the moment it's bare bones.

To give you a better idea, the first form to edit Groups, which also edits the group's addresses, people, and phones (not just those tables, but also the links to those tables) looks like this:

Group lookup pulldown (used to find a group record)
(this is a drop down box with custom code that helps me find group records)

Group editing fields, e.g. Group name, category, url, etc

Then below that

Group-Person links table

Then to the right of that

Persons table (plural) - to create new person, then..

And below that

Person table (singular)
 [pointed to by Group-Person link]
 to view person pointed to.

Group-Address links || (similar structure to above)

  (for example, when a business has two or more addresses)

Group-Phone links || (similar structure to above)

  (this is for phone#'s that the group owns directly, not personal phones of the group's members, and not phones tied to specific addresses).

----------

Then there are 3 other similar forms,

one for Addresses w/ Person, Group & Phone links;

one for Phones w/ Group, Address & Person links;

and one for People w/ Group, Address and phone links;

Here is a screen shot of the first of the 4 editing forms, to edit the groups and the links associated with the group:

Hope this helps.  I would be interested to see what you develop.  Thanks.


来源: stackexchange

问:
Enable user to fill in data
I would like to enable user to pick up a file from a given year/ month etc. and bring data into the file I'm working on.

For this, I've created a "Parameters" sheet where I've labelled the cells "Year" and "Month". When I put these variables in the code, it triggers error.
I believe I'm declaring Y and Z incorrectly, and also concatenating it poorly into the last line. I tested the code without Y/Z variables and actual file location and it works.

```<code>Dim wkb As Workbook
Dim wks As Worksheet
Dim Y As String
Dim Z As String
Y = ThisWorkbook.Sheets("Parameters").Cells("Year")
Z = ThisWorkbook.Sheets("Parameters").Cells("Month")
Set wkb = Workbooks.Open("W:\01-Forecasts\&Y&\Monthly Forecast\&Z&\File.xlsm")
</code>```

答:
Use Range not Cells()

And all vba variables need to be outside the quotes and concatenated with &

```<code>Dim wkb As Workbook
Dim wks As Worksheet
Dim Y As String
Dim Z As String
Y = ThisWorkbook.Sheets("Parameters").Range("Year")
Z = ThisWorkbook.Sheets("Parameters").Range("Month")
Set wkb = Workbooks.Open("W:\01-Forecasts\" & Y & " \Monthly Forecast\" & Z & "\File.xlsm")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Enable user to fill in data

Body:
I would like to enable user to pick up a file from a given year/ month etc. and bring data into the file I'm working on.

For this, I've created a "Parameters" sheet where I've labelled the cells "Year" and "Month". When I put these variables in the code, it triggers error.
I believe I'm declaring Y and Z incorrectly, and also concatenating it poorly into the last line. I tested the code without Y/Z variables and actual file location and it works.

Dim wkb As Workbook
Dim wks As Worksheet
Dim Y As String
Dim Z As String
Y = ThisWorkbook.Sheets("Parameters").Cells("Year")
Z = ThisWorkbook.Sheets("Parameters").Cells("Month")
Set wkb = Workbooks.Open("W:\01-Forecasts\&Y&\Monthly Forecast\&Z&\File.xlsm")

Body:
Use Range not Cells()

And all vba variables need to be outside the quotes and concatenated with &

Dim wkb As Workbook
Dim wks As Worksheet
Dim Y As String
Dim Z As String
Y = ThisWorkbook.Sheets("Parameters").Range("Year")
Z = ThisWorkbook.Sheets("Parameters").Range("Month")
Set wkb = Workbooks.Open("W:\01-Forecasts\" & Y & " \Monthly Forecast\" & Z & "\File.xlsm")


问:
How many socket connections can a web server handle?
Say if I was to get shared, virtual or dedicated hosting, I read somewhere a server/machine can only handle 64,000 TCP connections at one time, is this true? How many could any type of hosting handle regardless of bandwidth? I'm assuming HTTP works over TCP.

Would this mean only 64,000 users could connect to the website, and if I wanted to serve more I'd have to move to a web farm?

答:
I think that the number of concurrent socket connections one web server can handle largely depends on the amount of resources each connection consumes and the amount of total resource available on the server barring any other web server resource limiting configuration.

To illustrate, if every socket connection consumed 1MB of server resource and the server has 16GB of RAM available (theoretically) this would mean it would only be able to handle (16GB / 1MB) concurrent connections. I think it's as simple as that... REALLY!

So regardless of how the web server handles connections, every connection will ultimately consume some resource.


问:
Delay animated arcs with .attrTween method
I am trying to create an animated arc diagram. I've been able to create the type of animation I want, but I would like to add a delay.

To create the animation I am using the .attrTween method.

This is the main portion of my code with my delay attempt:

```<code>svg.selectAll(".arcs")
      .data(data)
      .enter()
      .append("path")
      .style("stroke", "#832129")
      .attr("class", "arc")
      .attr("d", function(d){
        var To_scale = xScale(d.experience),
            From_scale = xScale(0),
            y = yScale(0),
            dx = To_scale - From_scale,
            dy = y,
            dr = Math.sqrt(dx * dx + dy * dy);
        return "M" + From_scale + " " + y + " A 43 50 0 0 1 " + To_scale + " " + y;
      })
      .style("fill", "none")
      .style("opacity", 1)
      .call(transition)
      .on("mouseover",  function(d){
        var thisClass = d3.select(this).attr("class")
          d3.select(this).style("stroke", "white").style("opacity", 1)
          d3.selectAll(".arcs").style("opacity", 0.1)

        })
        .on("mouseout",  function(d){
          d3.select(this).style("stroke", "#832129").style("opacity", 1)
        })

// DELAY ATTEMPT HERE

function transition(path){
        path.transition()
          .delay(function(d, i){ return i * 1000})
          .duration(2500)
          .attrTween("stroke-dasharray", tweenDash)

      }

      function tweenDash(){
        var l = this.getTotalLength(),
            i = d3.interpolateString("0," + l, l + "," + l)
            return function(t){ return i(t); };
      }
</code>```

The problem with this method is it just makes the chart appear with no delay or animation. I have also tried .delay(100), but that just delays the animation.

I would like the delay/animation to look something like this https://twitter.com/sxywu/status/937510554310123520 where the arcs appear one after another. I am just confused as to why .delay(function(d, i){ return i * 1000}) doesn't work.

My full code can be seen on my bl.ocks page here: https://bl.ocks.org/JulienAssouline/7236f0632102c6e2d3399208c4c90c26

Thank you.

答:
Set opacity to 0 for your arcs:

```<code> svg.selectAll(".arcs")
  .data(data)
  .enter()
  .append("path")
  ...
  .style("opacity", 0) // <== !!!
  ...
</code>```

And rewrite your transition function this way:

```<code>function transition(path){
  path.each(function(pathItem, index) {
    d3.select(this).transition()
    .delay(index + 200)
    .duration(index * 5 + 1000)
    .on('start',function() {
        d3.select(this).style("opacity", 1)
    })
    .attrTween("stroke-dasharray", tweenDash)
  })
}
</code>```

Here we specify a transition parameters for every item in your selection separately. You can play with delay and duration values as you need.

Check working example based on your code. I hardcoded part of your csv data here (with the full dataset all paths will draw) to able to use jsFiddle, but all the other code the same.

Body:
I am trying to create an animated arc diagram. I've been able to create the type of animation I want, but I would like to add a delay.

To create the animation I am using the .attrTween method.

This is the main portion of my code with my delay attempt:

svg.selectAll(".arcs")
      .data(data)
      .enter()
      .append("path")
      .style("stroke", "#832129")
      .attr("class", "arc")
      .attr("d", function(d){
        var To_scale = xScale(d.experience),
            From_scale = xScale(0),
            y = yScale(0),
            dx = To_scale - From_scale,
            dy = y,
            dr = Math.sqrt(dx * dx + dy * dy);
        return "M" + From_scale + " " + y + " A 43 50 0 0 1 " + To_scale + " " + y;
      })
      .style("fill", "none")
      .style("opacity", 1)
      .call(transition)
      .on("mouseover",  function(d){
        var thisClass = d3.select(this).attr("class")
          d3.select(this).style("stroke", "white").style("opacity", 1)
          d3.selectAll(".arcs").style("opacity", 0.1)

        })
        .on("mouseout",  function(d){
          d3.select(this).style("stroke", "#832129").style("opacity", 1)
        })

// DELAY ATTEMPT HERE

function transition(path){
        path.transition()
          .delay(function(d, i){ return i * 1000})
          .duration(2500)
          .attrTween("stroke-dasharray", tweenDash)

      }

      function tweenDash(){
        var l = this.getTotalLength(),
            i = d3.interpolateString("0," + l, l + "," + l)
            return function(t){ return i(t); };
      }

The problem with this method is it just makes the chart appear with no delay or animation. I have also tried .delay(100), but that just delays the animation.

I would like the delay/animation to look something like this https://twitter.com/sxywu/status/937510554310123520 where the arcs appear one after another. I am just confused as to why .delay(function(d, i){ return i * 1000}) doesn't work.

My full code can be seen on my bl.ocks page here: https://bl.ocks.org/JulienAssouline/7236f0632102c6e2d3399208c4c90c26

Thank you.

Body:
Set opacity to 0 for your arcs:

 svg.selectAll(".arcs")
  .data(data)
  .enter()
  .append("path")
  ...
  .style("opacity", 0) // <== !!!
  ...

And rewrite your transition function this way:

function transition(path){
  path.each(function(pathItem, index) {
    d3.select(this).transition()
    .delay(index + 200)
    .duration(index * 5 + 1000)
    .on('start',function() {
        d3.select(this).style("opacity", 1)
    })
    .attrTween("stroke-dasharray", tweenDash)
  })
}

Here we specify a transition parameters for every item in your selection separately. You can play with delay and duration values as you need.

Check working example based on your code. I hardcoded part of your csv data here (with the full dataset all paths will draw) to able to use jsFiddle, but all the other code the same.


问:
SCNAction.rotateTo starts spinning when written programmatically using ARKit - Scenekit
I am using ARKit - Scenekit to create a AR based app. I am able to successfully place the 3D model. On user tap i am trying to rotate a particular node by -120 degrees using rotateTo method. This should ideally cause smooth rotate animation. But instead the node spins around the object really fast and finally ends at -120 degrees. When i try to do the same directly in scene editor by drag-dropping rotateto action it works just fine. Only when i try to do this programmatically, it starts spinning really fast and i am not even able to preview the rotation.

Below is the code i am using to rotate the node,

```<code> let rotateAction =  SCNAction.rotateTo(x: 0, y: 0, z: -120, duration: 2)
 self.virtualObjectManager.lastUsedObject?.childNodes[0].childNodes[0].childNodes[0].runAction(rotateAction, completionHandler: {
            })
</code>```

Initial angle of the node is (0,0,0). I am trying to change it to (0,0,-120). Any one please let me know what is the issue here?

答:
The scenekit editor uses degrees, but SCNAction.rotateTo expects the angle in radians.

```<code>let angle = CGFloat(-120.0 * .pi / 180)
let rotateAction =  SCNAction.rotateTo(x: 0, y: 0, z: angle, duration: 2)
</code>```

Body:
I am using ARKit - Scenekit to create a AR based app. I am able to successfully place the 3D model. On user tap i am trying to rotate a particular node by -120 degrees using rotateTo method. This should ideally cause smooth rotate animation. But instead the node spins around the object really fast and finally ends at -120 degrees. When i try to do the same directly in scene editor by drag-dropping rotateto action it works just fine. Only when i try to do this programmatically, it starts spinning really fast and i am not even able to preview the rotation.

Below is the code i am using to rotate the node,

 let rotateAction =  SCNAction.rotateTo(x: 0, y: 0, z: -120, duration: 2)
 self.virtualObjectManager.lastUsedObject?.childNodes[0].childNodes[0].childNodes[0].runAction(rotateAction, completionHandler: {
            })

Initial angle of the node is (0,0,0). I am trying to change it to (0,0,-120). Any one please let me know what is the issue here?

Body:
The scenekit editor uses degrees, but SCNAction.rotateTo expects the angle in radians.

let angle = CGFloat(-120.0 * .pi / 180)
let rotateAction =  SCNAction.rotateTo(x: 0, y: 0, z: angle, duration: 2)


问:
How to repeat sequence when condition is met
I have found variations of this question, and I know modulos can possibly be used but I am having a difficult time putting it all together.

I have a sequence of observations by ID and seconds. When the cumulitive amount of seconds by id increments greater than 5 seconds, I would like to restart the count. Could someone help me answer this question in dplyr?

Original df

```<code>df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df
   id val
1   1   2
2   1  10
3   1  12
4   1  15
5   1  17
6   2   2
7   2   4
8   2   7
9   2   8
10  3  12
11  3  15
12  3  20
13  3  25
</code>```

Desired Outcome

```<code>finalResult
   id val reset
1   1   2     1
2   1  10     2
3   1  12     2
4   1  15     3
5   1  17     3
6   2   2     1
7   2   4     1
8   2   7     2
9   2   8     2
10  3  12     1
11  3  15     1
12  3  20     2
13  3  25     3
</code>```

Edit

Thanks for the responses yesterday but I encountered some problems with the given solutions.

On this data set the code works on some instances.

```<code>sub.df <- structure(list(`ID` = c("1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1"
), dateFormat = structure(c(1479955726, 1479955726, 1483703713,
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061
), class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")), .Names = c("ID",
                                                                           "dateFormat"), row.names = c(NA, -9L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))
</code>```

Solution Used:

```<code>jj <- sub.df %>%
  group_by(`ID`) %>%
  arrange(`ID`,`dateFormat`)%>%
  mutate(totalTimeInt = difftime(dateFormat,first(dateFormat),units = 'secs'))%>%
  mutate(totalTimeFormat   = as.numeric(totalTimeInt))%>%
  mutate(reset = cumsum(
    Reduce(
      function(x, y)
        if (x + y >= 5) 0
        else x + y,

        diff(totalTimeFormat), init = 0, accumulate = TRUE
    ) == 0
  ))%>%
  mutate(reset_2 = cumsum(
    accumulate(
      diff(totalTimeFormat),
      ~if (.x + .y >= 5) 0 else .x + .y,
      .init = 0
    ) == 0
  ))
</code>```

Outcome

```<code># A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     3       3
5     1 2017-01-06 05:55:13  9680654 secs         9680654     4       4
6     1 2017-05-19 05:46:49 21167750 secs        21167750     5       5
7     1 2017-05-19 05:46:49 21167750 secs        21167750     6       6
8     1 2017-06-12 05:57:59 23242020 secs        23242020     7       7
9     1 2017-06-12 05:57:59 23242020 secs        23242020     8       8
</code>```

What happens is that for the first two observation it correctly counts that as 1 instance. When it reaches the third and fourth observation this should only be counted as two observations as there was essentially no time that passed between those two instances.

Correct Output:

```<code># A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
5     1 2017-01-06 05:55:13  9680654 secs         9680654     3       3
6     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
7     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
8     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5
9     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5
</code>```

答:
If you use Reduce with accumulate = TRUE (or purrr::accumulate, if you prefer), you can reset the running difference when it is greater than or equal to 5. Calling cumsum on whether that total is 0 will return the number of resets.

library(tidyverse)

df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df %>%
    group_by(id) %>%
    mutate(reset = cumsum(
        Reduce(
            function(x, y) if (x + y >= 5) 0 else x + y,
            diff(val), init = 0, accumulate = TRUE
        ) == 0
    ))
#> # A tibble: 13 x 3
#> # Groups:   id [3]
#>       id   val reset
#>    <dbl> <dbl> <int>
#>  1     1     2     1
#>  2     1    10     2
#>  3     1    12     2
#>  4     1    15     3
#>  5     1    17     3
#>  6     2     2     1
#>  7     2     4     1
#>  8     2     7     2
#>  9     2     8     2
#> 10     3    12     1
#> 11     3    15     1
#> 12     3    20     2
#> 13     3    25     3
```

<p>or with <code>purrr::accumulate</code>,</p>

<pre class="lang-r prettyprint-override"><code>df %>%
    group_by(id) %>%
    mutate(reset = cumsum(
        accumulate(
            diff(val),
            ~if (.x + .y >= 5) 0 else .x + .y,
            .init = 0
        ) == 0
    ))
#> # A tibble: 13 x 3
#> # Groups:   id [3]
#>       id   val reset
#>    <dbl> <dbl> <int>
#>  1     1     2     1
#>  2     1    10     2
#>  3     1    12     2
#>  4     1    15     3
#>  5     1    17     3
#>  6     2     2     1
#>  7     2     4     1
#>  8     2     7     2
#>  9     2     8     2
#> 10     3    12     1
#> 11     3    15     1
#> 12     3    20     2
#> 13     3    25     3
</code>```

Regarding the edit, the issue is that some of the diffs are 0, which is the same as what it's counting to see resets. The simplest solution is to use NA instead of zero as a reset value:

library(tidyverse)

sub.df <- structure(list(`ID` = c("1", "1", "1", "1", "1", "1", "1", "1", "1"),
                         dateFormat = structure(c(1479955726, 1479955726, 1483703713,
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061),
                            class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")),
                    .Names = c("ID", "dateFormat"), row.names = c(NA, -9L),
                    class = c("tbl_df", "tbl", "data.frame"))

sub.df %>%
    group_by(ID) %>%
    arrange(ID, dateFormat) %>%
    mutate(reset = cumsum(is.na(
               accumulate(diff(dateFormat),
                          ~{
                              s <- sum(.x, .y, na.rm = TRUE);
                              if (s >= 5) NA else s
                          },
                          .init = NA)
    )))
#> # A tibble: 9 x 3
#> # Groups:   ID [1]
#>      ID          dateFormat reset
#>   <chr>              <dttm> <int>
#> 1     1 2016-09-16 05:50:59     1
#> 2     1 2016-09-16 05:51:01     1
#> 3     1 2016-11-23 20:48:46     2
#> 4     1 2016-11-23 20:48:46     2
#> 5     1 2017-01-06 05:55:13     3
#> 6     1 2017-05-19 05:46:49     4
#> 7     1 2017-05-19 05:46:49     4
#> 8     1 2017-06-12 05:57:59     5
#> 9     1 2017-06-12 05:57:59     5
```

<p>Ultimately this approach faces limitations, too, though, as if any values actually <em>are</em> <code>NA</code>, it will increment similarly. A more robust solution would be to return a list of two elements from each iteration, one for the total with resets, and one for the reset count. This is more work to implement, though:</p>

<pre class="lang-r prettyprint-override"><code>sub.df %>%
    group_by(ID) %>%
    arrange(ID, dateFormat) %>%
    mutate(total_reset = accumulate(
        transpose(list(total = diff(dateFormat), reset = rep(0, n() - 1))),
        ~{
            s <- .x$total + .y$total;
            if (s >= 5) {
                data_frame(total = 0, reset = .x$reset + 1)
            } else {
                data_frame(total = s, reset = .x$reset)
            }
        },
        .init = data_frame(total = 0, reset = 1)
    )) %>%
    unnest()
#> # A tibble: 9 x 4
#> # Groups:   ID [1]
#>      ID          dateFormat total reset
#>   <chr>              <dttm> <dbl> <dbl>
#> 1     1 2016-09-16 05:50:59     0     1
#> 2     1 2016-09-16 05:51:01     2     1
#> 3     1 2016-11-23 20:48:46     0     2
#> 4     1 2016-11-23 20:48:46     0     2
#> 5     1 2017-01-06 05:55:13     0     3
#> 6     1 2017-05-19 05:46:49     0     4
#> 7     1 2017-05-19 05:46:49     0     4
#> 8     1 2017-06-12 05:57:59     0     5
#> 9     1 2017-06-12 05:57:59     0     5
</code>```

The total looks a little silly, but if you look at the diff, it's actually correct.

Body:
I have found variations of this question, and I know modulos can possibly be used but I am having a difficult time putting it all together.

I have a sequence of observations by ID and seconds. When the cumulitive amount of seconds by id increments greater than 5 seconds, I would like to restart the count. Could someone help me answer this question in dplyr?

Original df

df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df
   id val
1   1   2
2   1  10
3   1  12
4   1  15
5   1  17
6   2   2
7   2   4
8   2   7
9   2   8
10  3  12
11  3  15
12  3  20
13  3  25

Desired Outcome

finalResult
   id val reset
1   1   2     1
2   1  10     2
3   1  12     2
4   1  15     3
5   1  17     3
6   2   2     1
7   2   4     1
8   2   7     2
9   2   8     2
10  3  12     1
11  3  15     1
12  3  20     2
13  3  25     3

Edit

Thanks for the responses yesterday but I encountered some problems with the given solutions.

On this data set the code works on some instances.

sub.df <- structure(list(`ID` = c("1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1"
), dateFormat = structure(c(1479955726, 1479955726, 1483703713,
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061
), class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")), .Names = c("ID",
                                                                           "dateFormat"), row.names = c(NA, -9L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))

Solution Used:

jj <- sub.df %>%
  group_by(`ID`) %>%
  arrange(`ID`,`dateFormat`)%>%
  mutate(totalTimeInt = difftime(dateFormat,first(dateFormat),units = 'secs'))%>%
  mutate(totalTimeFormat   = as.numeric(totalTimeInt))%>%
  mutate(reset = cumsum(
    Reduce(
      function(x, y)
        if (x + y >= 5) 0
        else x + y,

        diff(totalTimeFormat), init = 0, accumulate = TRUE
    ) == 0
  ))%>%
  mutate(reset_2 = cumsum(
    accumulate(
      diff(totalTimeFormat),
      ~if (.x + .y >= 5) 0 else .x + .y,
      .init = 0
    ) == 0
  ))

Outcome

# A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     3       3
5     1 2017-01-06 05:55:13  9680654 secs         9680654     4       4
6     1 2017-05-19 05:46:49 21167750 secs        21167750     5       5
7     1 2017-05-19 05:46:49 21167750 secs        21167750     6       6
8     1 2017-06-12 05:57:59 23242020 secs        23242020     7       7
9     1 2017-06-12 05:57:59 23242020 secs        23242020     8       8

What happens is that for the first two observation it correctly counts that as 1 instance. When it reaches the third and fourth observation this should only be counted as two observations as there was essentially no time that passed between those two instances.

Correct Output:

# A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
5     1 2017-01-06 05:55:13  9680654 secs         9680654     3       3
6     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
7     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
8     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5
9     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5

Body:
If you use Reduce with accumulate = TRUE (or purrr::accumulate, if you prefer), you can reset the running difference when it is greater than or equal to 5. Calling cumsum on whether that total is 0 will return the number of resets.

library(tidyverse)

df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df %>%
    group_by(id) %>%
    mutate(reset = cumsum(
        Reduce(
            function(x, y) if (x + y >= 5) 0 else x + y,
            diff(val), init = 0, accumulate = TRUE
        ) == 0
    ))
#> # A tibble: 13 x 3
#> # Groups:   id [3]
#>       id   val reset
#>    <dbl> <dbl> <int>
#>  1     1     2     1
#>  2     1    10     2
#>  3     1    12     2
#>  4     1    15     3
#>  5     1    17     3
#>  6     2     2     1
#>  7     2     4     1
#>  8     2     7     2
#>  9     2     8     2
#> 10     3    12     1
#> 11     3    15     1
#> 12     3    20     2
#> 13     3    25     3

or with purrr::accumulate,

df %>%
    group_by(id) %>%
    mutate(reset = cumsum(
        accumulate(
            diff(val),
            ~if (.x + .y >= 5) 0 else .x + .y,
            .init = 0
        ) == 0
    ))
#> # A tibble: 13 x 3
#> # Groups:   id [3]
#>       id   val reset
#>    <dbl> <dbl> <int>
#>  1     1     2     1
#>  2     1    10     2
#>  3     1    12     2
#>  4     1    15     3
#>  5     1    17     3
#>  6     2     2     1
#>  7     2     4     1
#>  8     2     7     2
#>  9     2     8     2
#> 10     3    12     1
#> 11     3    15     1
#> 12     3    20     2
#> 13     3    25     3

Regarding the edit, the issue is that some of the diffs are 0, which is the same as what it's counting to see resets. The simplest solution is to use NA instead of zero as a reset value:

library(tidyverse)

sub.df <- structure(list(`ID` = c("1", "1", "1", "1", "1", "1", "1", "1", "1"),
                         dateFormat = structure(c(1479955726, 1479955726, 1483703713,
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061),
                            class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")),
                    .Names = c("ID", "dateFormat"), row.names = c(NA, -9L),
                    class = c("tbl_df", "tbl", "data.frame"))

sub.df %>%
    group_by(ID) %>%
    arrange(ID, dateFormat) %>%
    mutate(reset = cumsum(is.na(
               accumulate(diff(dateFormat),
                          ~{
                              s <- sum(.x, .y, na.rm = TRUE);
                              if (s >= 5) NA else s
                          },
                          .init = NA)
    )))
#> # A tibble: 9 x 3
#> # Groups:   ID [1]
#>      ID          dateFormat reset
#>   <chr>              <dttm> <int>
#> 1     1 2016-09-16 05:50:59     1
#> 2     1 2016-09-16 05:51:01     1
#> 3     1 2016-11-23 20:48:46     2
#> 4     1 2016-11-23 20:48:46     2
#> 5     1 2017-01-06 05:55:13     3
#> 6     1 2017-05-19 05:46:49     4
#> 7     1 2017-05-19 05:46:49     4
#> 8     1 2017-06-12 05:57:59     5
#> 9     1 2017-06-12 05:57:59     5

Ultimately this approach faces limitations, too, though, as if any values actually are NA, it will increment similarly. A more robust solution would be to return a list of two elements from each iteration, one for the total with resets, and one for the reset count. This is more work to implement, though:

sub.df %>%
    group_by(ID) %>%
    arrange(ID, dateFormat) %>%
    mutate(total_reset = accumulate(
        transpose(list(total = diff(dateFormat), reset = rep(0, n() - 1))),
        ~{
            s <- .x$total + .y$total;
            if (s >= 5) {
                data_frame(total = 0, reset = .x$reset + 1)
            } else {
                data_frame(total = s, reset = .x$reset)
            }
        },
        .init = data_frame(total = 0, reset = 1)
    )) %>%
    unnest()
#> # A tibble: 9 x 4
#> # Groups:   ID [1]
#>      ID          dateFormat total reset
#>   <chr>              <dttm> <dbl> <dbl>
#> 1     1 2016-09-16 05:50:59     0     1
#> 2     1 2016-09-16 05:51:01     2     1
#> 3     1 2016-11-23 20:48:46     0     2
#> 4     1 2016-11-23 20:48:46     0     2
#> 5     1 2017-01-06 05:55:13     0     3
#> 6     1 2017-05-19 05:46:49     0     4
#> 7     1 2017-05-19 05:46:49     0     4
#> 8     1 2017-06-12 05:57:59     0     5
#> 9     1 2017-06-12 05:57:59     0     5

The total looks a little silly, but if you look at the diff, it's actually correct.


问:
Bootstrap 4 last version Carousal buttons is not working
my next/prev buttons are not working. Can someone help me. Thanks!I am new to coding I have researched a bunch and tried different things but nothing is working.</p>

```<code><section class="section-main">
<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
                <ol class="carousel-indicators">
                    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
                    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
                    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
                </ol>
                <div class="carousel-inner" role="listbox">
                    <div class="carousel-item active">
                        <img class="d-block img-fluid" src="img/slide1.jpg" alt="First slide">
                    </div>
                    <div class="carousel-item">
                        <img class="d-block img-fluid" src="img/slide2.jpg" alt="Second slide">
                    </div>
                    <div class="carousel-item">
                        <img class="d-block img-fluid" src="img/slide3.jpg" alt="Third slide">
                    </div>
                </div>
                <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="sr-only">Previous</span>
                </a>
                <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="sr-only">Next</span>
                </a>
            </div>
            <div class="col-md-4">
            </div>
        </div>
    </div>
</code>```

答:
try adding the required javascript libraries that Bootstrap uses in between the head tags at the top of your html file.

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</code>```

An example of what the full html file would look like with the above libraries inbetween the head tags.

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</head>

<body>
  <section class="section-main">
    <div class="container">
      <div class="row">
        <div class="col-md-8">
          <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
            <ol class="carousel-indicators">
              <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
              <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
              <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
            </ol>
            <div class="carousel-inner" role="listbox">
              <div class="carousel-item active">
                <img class="d-block img-fluid" src="img/slide1.png" alt="First slide">
              </div>
              <div class="carousel-item">
                <img class="d-block img-fluid" src="img/slide2.png" alt="Second slide">
              </div>
              <div class="carousel-item">
                <img class="d-block img-fluid" src="img/slide3.png" alt="Third slide">
              </div>
            </div>
            <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
              <span class="carousel-control-prev-icon" aria-hidden="true"></span>
              <span class="sr-only">Previous</span>
            </a>
            <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
              <span class="carousel-control-next-icon" aria-hidden="true"></span>
              <span class="sr-only">Next</span>
            </a>
          </div>
          <div class="col-md-4">
          </div>
        </div>
      </div>
    </div>
  </section>
</body>
</html>
</code>```

A link to the documentation Bootstrap provides explaining how to get started.

https://getbootstrap.com/docs/4.0/getting-started/introduction/

I hope this helps

Body:
my next/prev buttons are not working. Can someone help me. Thanks!I am new to coding I have researched a bunch and tried different things but nothing is working.

                    Previous

                    Next

Body:
try adding the required javascript libraries that Bootstrap uses in between the head tags at the top of your html file.

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

An example of what the full html file would look like with the above libraries inbetween the head tags.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</head>

<body>
  <section class="section-main">
    <div class="container">
      <div class="row">
        <div class="col-md-8">
          <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
            <ol class="carousel-indicators">
              <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
              <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
              <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
            </ol>
            <div class="carousel-inner" role="listbox">
              <div class="carousel-item active">
                <img class="d-block img-fluid" src="img/slide1.png" alt="First slide">
              </div>
              <div class="carousel-item">
                <img class="d-block img-fluid" src="img/slide2.png" alt="Second slide">
              </div>
              <div class="carousel-item">
                <img class="d-block img-fluid" src="img/slide3.png" alt="Third slide">
              </div>
            </div>
            <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
              <span class="carousel-control-prev-icon" aria-hidden="true"></span>
              <span class="sr-only">Previous</span>
            </a>
            <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
              <span class="carousel-control-next-icon" aria-hidden="true"></span>
              <span class="sr-only">Next</span>
            </a>
          </div>
          <div class="col-md-4">
          </div>
        </div>
      </div>
    </div>
  </section>
</body>
</html>

A link to the documentation Bootstrap provides explaining how to get started.

https://getbootstrap.com/docs/4.0/getting-started/introduction/

I hope this helps


问:
When I send notification is marking as completed but I am still not getting messages in device
I use Firebase for sending notifications to all application users, but even Firebase shows that the message status is Complete, I'm still not getting messages in devices (using emulators).

This is my code :
MyFirebaseMessagingService class :

```<code>import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("myLog","NotificationTitle : "+remoteMessage.getNotification().getTitle());

    }
}
</code>```

MyFirebaseInstanceIDService class :

```<code>import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();

        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d("myLog","Token is : "+token);

    }
}
</code>```

This is the gradle :

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support:design:27.0.2'
    compile 'com.android.support:support-v4:27.0.2'
    compile 'com.github.amigold.fundapter:library:1.0'
    compile 'rongi.rotate-layout:rotate-layout:3.0.0'
    compile 'me.grantland:autofittextview:0.2.+'
    testCompile 'junit:junit:4.12'
    compile'com.google.firebase:firebase-messaging:11.6.2'
    compile 'com.google.firebase:firebase-core:11.6.2'
    compile 'com.google.maps.android:android-maps-utils:0.5+'
    compile 'com.google.android.gms:play-services:11.6.2'

}

apply plugin: 'com.google.gms.google-services'
</code>```

This is the Manifest :

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/logofppt"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:replace="android:icon">

    <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service android:name=".MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBOhBdH1WXX9jz9kSk8nVmoQgKaM4N0_vs" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.nobar" />
    <activity
        android:name=".SplashScreen"
        android:theme="@style/AppTheme.nobar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".TDIinfo"
        android:label="TDI" />
    <activity
        android:name=".TCAinfo"
        android:label="TCA" />
    <activity
        android:name=".INFOGinfo"
        android:label="INFOG" />
    <activity
        android:name=".TRIinfo"
        android:label="TRI" />
    <activity android:name=".TMSIRinfo" android:label="TMSIR"/>
    <activity android:name=".TLWinfo" android:label="TLW" />
    <activity android:name=".J2EEinfo" android:label="J2EE"/>
</application>
</code>```

This is the error :

```<code>D/FA: Logging event (FE): notification_receive(_nr), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
D/myLog: NotificationTitle : Emplois
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
D/FA: Logging event (FE): notification_foreground(_nf), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
V/FA: Processing queued up service tasks: 2
E/FA: Discarding data. Failed to send event to service
E/FA: Discarding data. Failed to send event to service
V/FA: Processing queued up service tasks: 0
I/art: Do partial code cache collection, code=60KB, data=50KB
I/art: After code cache collection, code=60KB, data=50KB
I/art: Increasing code cache capacity to 256KB
</code>```

Please! if you have any idea how o solve this, please leave a comment..

答:
You need to update your Google Play Services on your device

GooglePlayServicesUtil: Google Play services out of date.  Requires
  11720000 but found 9683470

Body:
I use Firebase for sending notifications to all application users, but even Firebase shows that the message status is Complete, I'm still not getting messages in devices (using emulators).

This is my code :
MyFirebaseMessagingService class :

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("myLog","NotificationTitle : "+remoteMessage.getNotification().getTitle());

    }
}

MyFirebaseInstanceIDService class :

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();

        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d("myLog","Token is : "+token);

    }
}

This is the gradle :

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support:design:27.0.2'
    compile 'com.android.support:support-v4:27.0.2'
    compile 'com.github.amigold.fundapter:library:1.0'
    compile 'rongi.rotate-layout:rotate-layout:3.0.0'
    compile 'me.grantland:autofittextview:0.2.+'
    testCompile 'junit:junit:4.12'
    compile'com.google.firebase:firebase-messaging:11.6.2'
    compile 'com.google.firebase:firebase-core:11.6.2'
    compile 'com.google.maps.android:android-maps-utils:0.5+'
    compile 'com.google.android.gms:play-services:11.6.2'

}

apply plugin: 'com.google.gms.google-services'

This is the Manifest :

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/logofppt"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:replace="android:icon">

    <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service android:name=".MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBOhBdH1WXX9jz9kSk8nVmoQgKaM4N0_vs" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.nobar" />
    <activity
        android:name=".SplashScreen"
        android:theme="@style/AppTheme.nobar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".TDIinfo"
        android:label="TDI" />
    <activity
        android:name=".TCAinfo"
        android:label="TCA" />
    <activity
        android:name=".INFOGinfo"
        android:label="INFOG" />
    <activity
        android:name=".TRIinfo"
        android:label="TRI" />
    <activity android:name=".TMSIRinfo" android:label="TMSIR"/>
    <activity android:name=".TLWinfo" android:label="TLW" />
    <activity android:name=".J2EEinfo" android:label="J2EE"/>
</application>

This is the error :

D/FA: Logging event (FE): notification_receive(_nr), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
D/myLog: NotificationTitle : Emplois
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
D/FA: Logging event (FE): notification_foreground(_nf), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
V/FA: Processing queued up service tasks: 2
E/FA: Discarding data. Failed to send event to service
E/FA: Discarding data. Failed to send event to service
V/FA: Processing queued up service tasks: 0
I/art: Do partial code cache collection, code=60KB, data=50KB
I/art: After code cache collection, code=60KB, data=50KB
I/art: Increasing code cache capacity to 256KB

Please! if you have any idea how o solve this, please leave a comment..


问:
Tensorflow Object Detection Killed before starting
I am running docker image tensorflow:1.1.0. I have added the tensorflow object detection api github by cloning it locally and giving my docker a connection to the folder. I am trying to recreate their pet example.

I believe I have all code and code in the right places. However, when I try to retrain, tensorflow kills itself before starting to train, but does not give any issues or errors.

```<code>INFO:tensorflow:Starting Session.
INFO:tensorflow:Starting Queues.
INFO:tensorflow:global_step/sec: 0
Killed
</code>```

I imagine I have something out or oder, but without any errors or output I don't know where to look!

I am following the guide here to run things locally: link. The pet data was obtained from the same GitHub: link. I got my model configuration from the same GitHub as well. link

I choose inception_v2.

答:
I now realize that I was simply running out of memory as soon as I started. When I switched to ssd_mobilenet_v1_coco_2017_11_17 and changed batch_size = 1, it all worked.

This still doesn't entirely fix my problem though. I'll have to figure out how to provide more memory for the call.

Body:
I am running docker image tensorflow:1.1.0. I have added the tensorflow object detection api github by cloning it locally and giving my docker a connection to the folder. I am trying to recreate their pet example.

I believe I have all code and code in the right places. However, when I try to retrain, tensorflow kills itself before starting to train, but does not give any issues or errors.

INFO:tensorflow:Starting Session.
INFO:tensorflow:Starting Queues.
INFO:tensorflow:global_step/sec: 0
Killed

I imagine I have something out or oder, but without any errors or output I don't know where to look!

I am following the guide here to run things locally: link. The pet data was obtained from the same GitHub: link. I got my model configuration from the same GitHub as well. link

I choose inception_v2.


问:
iOS 11 prefersLargeTitles not updating until scroll
I implemented a basic UIViewController with a UITableView that's wrapped in a UINavigationController. I set prefersLargeTitles to true:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.title = "Coffees"
}
</code>```

However, the title stays small until I scroll the view, at which point it enlarges. I tried moving that call to where I create the UINavigationController, but there was no effect. I am sure the navigationController is not nil when I set prefersLargeTitles.

Should I be updating that property elsewhere? Or should I file a Radar?

Update:

This only seems to happen if my view contains a UITableView or is itself a UITableViewController

答: I had the same problem. Although you are not using Storyboards but I hope this could help someone. I checked "Prefer Large Titles" for the Navigation Controller (not the View Controller) I embedded my TableViewController in. All the View Controllers after the Navigation Controller turned and had large titles, and it should work.

Body:
I implemented a basic UIViewController with a UITableView that's wrapped in a UINavigationController. I set prefersLargeTitles to true:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.title = "Coffees"
}

However, the title stays small until I scroll the view, at which point it enlarges. I tried moving that call to where I create the UINavigationController, but there was no effect. I am sure the navigationController is not nil when I set prefersLargeTitles.

Should I be updating that property elsewhere? Or should I file a Radar?

Update:

This only seems to happen if my view contains a UITableView or is itself a UITableViewController


问:
Is there a class I can use to extract elements from messy HTML
I've got a requirement to grab text out of some pretty messy html. Lets say I need the 3rd list item from the first list in the page. There may or may not be closing tags on the li's, they may be in mixed cases, have classes etc.

I was wondering if, in a console application, is is possible to use a class (DOMDocument???) to load the HTML into a DOM, which would atleast sanitize it somewhat, then parse it out of there.

This seems like something that should be solved already, but I've not found anything too relevant except this vintage regex solution http://www.vsj.co.uk/articles/display.asp?id=389

Any thoughts on if this is a good approach and the correct classes to investigate would be appreciated.

答: The Html Agility Pack can be used to work with 'messy' Html in a DOM fashion.</p>

ContentLicense: CC BY-SA 2.5


问:
How to center everything inside navbar
I want to center everything in bootstrap navbar, it's my code:

```<code>    <nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>
</code>```

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

```<code>.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }
</code>```

still doesn't work

答:
Or make wrapper with fixed width (if navbar doesnt change alot).</p>

```<code><nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="wrap" style="
    margin: 0 auto;
    width: 550px;
">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
    </div>
  </div>
</nav>
</code>```

Title: How to center everything inside navbar

Body:
I want to center everything in bootstrap navbar, it's my code:

      WebSiteName

Home

Page 1

Page 2

Page 3

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }

still doesn't work

Body:
Or make wrapper with fixed width (if navbar doesnt change alot).

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="wrap" style="
    margin: 0 auto;
    width: 550px;
">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
    </div>
  </div>
</nav>


问:
How to partition memory of NFC tag(classic)?
I am looking for a way to partition memory(8Kb) of NFC tag. Because while writing a large amount of data to NFC tag from NFC device, there might be the chances of data loss of NFC tag while tapping NFC tag. So will partition the memory into 2 parts. or any other solution for this?

Please help. Thanks in advance.

答: Simple solution: write a chunk of data, read back, if ok Repeat, if not Ok raise an exception ...</p>


问:
Git - I want toget back to the most recent commit, but I also have a modified file I can't lose

I want my branch to be up to date (not behind by any commits) without making any new commits and leaving my tracked and modified file alone. I want to keep the changes in this file. I accidentally ran "git reset HEAD~" to see what it did and now I can't undo "git reset HEAD~".

In short, below is the order of events and my failed attempt at correcting it.

```<code><modified file>
git reset --soft HEAD~
git stash
git merge --ff-only
git stash pop
</code>```

After the "git reset --soft HEAD~" command, I expected the following three commands to effectively reverse it.

What I actually got back was...

error: Your local changes to the following files would be overwritten by merge:

README.md

Please commit your changes or stash them before you can merge.

Aborting

Any help is greatly appreciated!

答:
You will be much better off by abandoning ever using git stash and instead just always checking in changes on temporary branches. Things get much clearer and more robust as well as making things that git stash cannot do possible.

From your current state run

```<code>git checkout -b stash-branch-001
git commit -am stash
# Now all your pending changes are saved, like git stash does, but properly saved
# on a branch with all the benefits of a branch that stash cannot provide.

git checkout master
git fetch origin      # Get latest and greatest from upstream
git status            # Always run git status and verify before reset --hard
git reset --hard origin/master
# At this point git status should say "Your branch is up-to-date with
# 'origin/master'"
</code>```

Then to bring back the saved changes run (in the general case):

```<code>git rebase master stash-branch-001   # Implicit changes the checked out branch...
git checkout master                  # ... so change back
git reset orign/master
# At this point git status should say "modified: README.md"
</code>```

or in this particular case where there is only one commit on the temporary branch you could run just

```<code>git cherry-pick stash-branch-001
git reset HEAD^
</code>```

instead. When satisfied just delete the temporary branch.

I stopped using git stash around ten years ago I think. It provides zero benefits that checking in on temporary branches does not provide. Maybe there is a few less characters to type, but it is conceptually much simpler to just always check in and rebase like you always do instead of doing something differently for saving changes temporarily.

Viewing the changes then is just git log -p ..., git diff ..., gitk or any of your regular git command instead of having one single, special case git stash show command.

If you have multiple temporary changes ongoing, bringing them in and out
in any order becomes straight forward, instead of being forced to pop them in sequence like stash does.

Having the changes checked in on a branch provides great flexibility in allowing you to bring back the temporary changes in any branch (and possibly multiple) whereas git stash pop is very limited in its requirement: The working directory must match the index..

So all in all, do yourself a favour and stop using git stash.

Body:
I want my branch to be up to date (not behind by any commits) without making any new commits and leaving my tracked and modified file alone. I want to keep the changes in this file. I accidentally ran "git reset HEAD~" to see what it did and now I can't undo "git reset HEAD~".

In short, below is the order of events and my failed attempt at correcting it.

<modified file>
git reset --soft HEAD~
git stash
git merge --ff-only
git stash pop

After the "git reset --soft HEAD~" command, I expected the following three commands to effectively reverse it.

What I actually got back was...

error: Your local changes to the following files would be overwritten by merge:

README.md

Please commit your changes or stash them before you can merge.

Aborting

Any help is greatly appreciated!

Body:
You will be much better off by abandoning ever using git stash and instead just always checking in changes on temporary branches. Things get much clearer and more robust as well as making things that git stash cannot do possible.

From your current state run

git checkout -b stash-branch-001
git commit -am stash
# Now all your pending changes are saved, like git stash does, but properly saved
# on a branch with all the benefits of a branch that stash cannot provide.

git checkout master
git fetch origin      # Get latest and greatest from upstream
git status            # Always run git status and verify before reset --hard
git reset --hard origin/master
# At this point git status should say "Your branch is up-to-date with
# 'origin/master'"

Then to bring back the saved changes run (in the general case):

git rebase master stash-branch-001   # Implicit changes the checked out branch...
git checkout master                  # ... so change back
git reset orign/master
# At this point git status should say "modified: README.md"

or in this particular case where there is only one commit on the temporary branch you could run just

git cherry-pick stash-branch-001
git reset HEAD^

instead. When satisfied just delete the temporary branch.

I stopped using git stash around ten years ago I think. It provides zero benefits that checking in on temporary branches does not provide. Maybe there is a few less characters to type, but it is conceptually much simpler to just always check in and rebase like you always do instead of doing something differently for saving changes temporarily.

Viewing the changes then is just git log -p ..., git diff ..., gitk or any of your regular git command instead of having one single, special case git stash show command.

If you have multiple temporary changes ongoing, bringing them in and out
in any order becomes straight forward, instead of being forced to pop them in sequence like stash does.

Having the changes checked in on a branch provides great flexibility in allowing you to bring back the temporary changes in any branch (and possibly multiple) whereas git stash pop is very limited in its requirement: The working directory must match the index..

So all in all, do yourself a favour and stop using git stash.


问:
GNUPlot: plot different ranges with different styles
I know this should be pretty simple, but I haven't been able to find a similar example.

I need to plot different ranges of a datafile differently, but on the same graph.

For instance, say my datafile represents a function with x and y values. I want to plot the first N values using a style like lines, and then the next M values using a different style, like points.

I was thinking I would need a plot command similar to this:

```<code>plot [1:5] "my.data" using 1:2 with lines, [6:12] using 1:2 with points, [13:19] using 1:2 with lines
</code>```

Essentially I want to distinguish different areas of the functions.

Any ideas? I am sorry if it sounds like I'm rambling but I am quite stumped.

Thanks in advance!

答:
you could do the following:

```<code> plot "mydat.txt" using 1:($1>0 ? $2 : 1/0) with lines,
 "" using 1:($1<=0 ? $2 : 1/0) with points
</code>```

edit: I dit test it, and it works, when x variable < 0 you will have points. Of course you can make the conditions in such a way you can accomodate many different graph formats as long as the x values of your function are in the datafile.

Body:
I know this should be pretty simple, but I haven't been able to find a similar example.

I need to plot different ranges of a datafile differently, but on the same graph.

For instance, say my datafile represents a function with x and y values. I want to plot the first N values using a style like lines, and then the next M values using a different style, like points.

I was thinking I would need a plot command similar to this:

plot [1:5] "my.data" using 1:2 with lines, [6:12] using 1:2 with points, [13:19] using 1:2 with lines

Essentially I want to distinguish different areas of the functions.

Any ideas? I am sorry if it sounds like I'm rambling but I am quite stumped.

Thanks in advance!

Body:
you could do the following:

 plot "mydat.txt" using 1:($1>0 ? $2 : 1/0) with lines,
 "" using 1:($1<=0 ? $2 : 1/0) with points

edit: I dit test it, and it works, when x variable < 0 you will have points. Of course you can make the conditions in such a way you can accomodate many different graph formats as long as the x values of your function are in the datafile.


问:
Trying to extract data from another websites permalink. How?
I am wondering how one would go about  using a permalink from another website to extract data about that particular permalink, especially in the case of looking for specific information. Kind of how youtube has websites that essentially use the link to the video to download and convert it to mp3 format. Its for a college project in HTML5, but upon researching the subject (for about a week) I didnt come up with alot of information on how to go about it using html. Any help in advance will be appreciated. Just basic structure is necessary. im not good or anything, I just want to actually learn, so i need some directional pointing that way i get on the right track.

Thanks in advance :)

Oh and to be more direct, I mean in such a way as to list certain products at the price they are being listed on the site they are being listed on. However, from within my own site. (all in html...)Figured I should be more direct.

答:
Those websites that extract audio from Youtube probably doing it using Python or something similar

This might help you.


问:
UWP app (C#) - Same code click event button
I have an UWP app published in Microsoft/Windows Store, and I have many repeated code, and I want simplify my code. I have a button that appears several times in my application (always with the same name) and its design changes, but the code is always the same (click event button). To avoid duplicate code, can I write the event code to click the button once and use wherever I want?</p>

答:
It's really easy to do. Create a shared method with the code and in the handler for each Button, just call it from each button's event handler.

Example:

You have a Page with 3 Buttons

```<code><Page
    x:Class="App2.MainPage"
    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"
    mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button x:Name="Button1" Click="Button1_OnClick"></Button>
        <Button x:Name="Button2" Click="Button2_OnClick"></Button>
        <Button x:Name="Button3" Click="Button3_OnClick"></Button>
    </StackPanel>
</Page>
</code>```

And in the code-behind file (MainPage.xaml.cs)

```<code>public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void Button1_OnClick(object sender, RoutedEventArgs e)
    {
        ButtonHandlers.Handle(sender, e);
    }

    private void Button2_OnClick(object sender, RoutedEventArgs e)
    {
        ButtonHandlers.Handle(sender, e);
    }

    private void Button3_OnClick(object sender, RoutedEventArgs e)
    {
        ButtonHandlers.Handle(sender, e);
    }
}

internal static class ButtonHandlers
{
    public static void Handle(object sender, RoutedEventArgs routedEventArgs)
    {
        // This is shared!
    }
}
</code>```

I think you can get the idea. Anyways, you should take a look to the MVVM architectural pattern. Adding event handlers to Buttons isn't the way to work under XAML based applications, like UWP or WPF :)

Body:
It's really easy to do. Create a shared method with the code and in the handler for each Button, just call it from each button's event handler.

Example:

You have a Page with 3 Buttons

<Page
    x:Class="App2.MainPage"
    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"
    mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button x:Name="Button1" Click="Button1_OnClick"></Button>
        <Button x:Name="Button2" Click="Button2_OnClick"></Button>
        <Button x:Name="Button3" Click="Button3_OnClick"></Button>
    </StackPanel>
</Page>

And in the code-behind file (MainPage.xaml.cs)

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void Button1_OnClick(object sender, RoutedEventArgs e)
    {
        ButtonHandlers.Handle(sender, e);
    }

    private void Button2_OnClick(object sender, RoutedEventArgs e)
    {
        ButtonHandlers.Handle(sender, e);
    }

    private void Button3_OnClick(object sender, RoutedEventArgs e)
    {
        ButtonHandlers.Handle(sender, e);
    }
}

internal static class ButtonHandlers
{
    public static void Handle(object sender, RoutedEventArgs routedEventArgs)
    {
        // This is shared!
    }
}

I think you can get the idea. Anyways, you should take a look to the MVVM architectural pattern. Adding event handlers to Buttons isn't the way to work under XAML based applications, like UWP or WPF :)


问:
Alt Codes not navigating out of User Control
In our application's main processing form, we utilise alt codes (Having &Label as the label text to quickly navigate to a control using Alt-L, for example) for quick navigation to hop around the screen if the user needs to move out of the traditional navigation flow - but recently we have hit a snag:

We have a user control which handles quite a bit on the form, which has a control within it that needs to share an alt-code (Alt-R), with another control outside of the user control. Normally, this wouldn't be an issue, since we could just set them both to Alt-R, and Alt-R would toggle between the two. Since one of the controls is inside the user control, and one is not, however, once the focus is within the user control, it won't toggle outside of the user control with two controls sharing an Alt code.

Is there any property I can set to allow this without writing custom logic to handle? The main issue with custom logic is that some of these alt-codes can be user defined, and it wouldn't be ideal to have to write an all-encompassing handling method when I imagine this should just work within the normal Windows Forms Engine

答:
I couldn't find a different solution than using P/Invoke for this.

If it doesn't fit in the scheme, there might be an alternate trivial way.

First problem: intercept a KeyDown event.

The KeyDown event handler is not that useful in this case, so you have to go "under" and get the WindowProc message.

Second problem: let the Container control know that a KeyDown event has to be processed. Couldn't find any good solution other than using PostMessage.

Declare the dll import:

```<code>Imports System.Runtime.InteropServices

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function PostMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean
End Function
</code>```

Then override the ProcessCmdKey of the UserControl:

```<code>Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
  'If ALT has been pressed...
  If (keyData And Keys.Alt) > 0 Then
     '... if another key is pressed aswell...
     If (keyData Xor Keys.Alt) > 64 Then
        '...pass the information to the container to see if it is interested
        PostMessage(Me.ParentForm.Handle, CType(msg.Msg, UInt32), msg.WParam, msg.LParam)
        Return True
     End If
  End If
  'Not a key we are interested in
  Return MyBase.ProcessCmdKey(msg, keyData)
End Function
</code>```

If you can't/won't P/Invoke, you might obtain a similar effect setting the focus to a random control in the parent container.

So, substitute PostMessage with:

```<code>Me.ParentForm.Controls(0).Focus()
</code>```

But this, of course, will move the focus for any ALT/key combination.

Body:
I couldn't find a different solution than using P/Invoke for this.

If it doesn't fit in the scheme, there might be an alternate trivial way.

First problem: intercept a KeyDown event.

The KeyDown event handler is not that useful in this case, so you have to go "under" and get the WindowProc message.

Second problem: let the Container control know that a KeyDown event has to be processed. Couldn't find any good solution other than using PostMessage.

Declare the dll import:

Imports System.Runtime.InteropServices

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function PostMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean
End Function

Then override the ProcessCmdKey of the UserControl:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
  'If ALT has been pressed...
  If (keyData And Keys.Alt) > 0 Then
     '... if another key is pressed aswell...
     If (keyData Xor Keys.Alt) > 64 Then
        '...pass the information to the container to see if it is interested
        PostMessage(Me.ParentForm.Handle, CType(msg.Msg, UInt32), msg.WParam, msg.LParam)
        Return True
     End If
  End If
  'Not a key we are interested in
  Return MyBase.ProcessCmdKey(msg, keyData)
End Function

If you can't/won't P/Invoke, you might obtain a similar effect setting the focus to a random control in the parent container.

So, substitute PostMessage with:

Me.ParentForm.Controls(0).Focus()

But this, of course, will move the focus for any ALT/key combination.

ContentLicense: CC BY-SA 4.0


问:
Linking MS Access Database with Visual Studio 2005 Windows Form Application
Im programming in C++. And need to store data into database made in MS Access. How can i establish the connection and store and retrieve data?</p>

答: Used to be ODBC; now I'm not so sure.  This might affect your direction.</p>


问:
How to draw lines consisting of repeating images in (Py)GTK?
I am currently writing a Python program on Linux using the pygtk library. I already managed to make the windows background transparent and pass all clicks to the windows below my window. So now I have got an invisible window which would do nothing since any click and key events will be forwarded to the window below.

Now I would like to use an external program / device that tells my program where to draw lines. I already managed to do so.

But what is the right and most efficient way to draw a line onto the screen / window consisting of repeating single images. Let's say I've got a part of a laser line (8x8 pixels) and now I want to draw a line from coordinates (0,0) to (20,12) and then maybe to (22, 15), then to (25, 15) and so on. The user will paint it.

My final question is: how do I draw a line textured with a small repeated single png image given many coordinates the user draws onto the window (which looks like the screen because its background is invisible)?

答:
Have a look at GooCanvas. This library (built on the drawing tools from Gdk/Gtk - Cairo) takes care of much of the details of drawing the items, and also takes care of automatic redrawing. You can draw lines using textures, images etc. Also, you can define handlers on events of each layer, and each element drawn.

The result is a widget, which can be packed anywhere in the GUI. Look for not GooCanvas 2.0.x - not the old 1.x strain. It can be used in Python through introspection.

You can set the fill-color to a pixbuf (not directly a PNG, but easily convertible)


问:
Logical data model - how to indicate optional FK?
If a logical data model is modelling entities with optional foreign keys, how is that indicated on the model? I'm looking at one now, where, for example, we have:

```<code>COUNTRY 1:1 ----------- 0:N TRANSACTION
</code>```

The TRANSACTION entity contains a country attribute that may or may not have a value. I would have thought that in this case, the optionality of the FK would be shown as:

```<code>COUNTRY 0:1 ----------- 0:N TRANSACTION
</code>```

Is that correct? Or does the 1:1 also imply "IFF a value is provided"?

答:
The short answer is that you're correct. If a TRANSACTION has an optional association with a COUNTRY, then using min-max notation we would indicate

```<code>COUNTRY 0:1 ----------- 0:N TRANSACTION
</code>```

1:1 doesn't imply "IFF a value is provided", it explicitly states a value must be provided.

Body:
If a logical data model is modelling entities with optional foreign keys, how is that indicated on the model? I'm looking at one now, where, for example, we have:

COUNTRY 1:1 ----------- 0:N TRANSACTION

The TRANSACTION entity contains a country attribute that may or may not have a value. I would have thought that in this case, the optionality of the FK would be shown as:

COUNTRY 0:1 ----------- 0:N TRANSACTION

Is that correct? Or does the 1:1 also imply "IFF a value is provided"?

Body:
The short answer is that you're correct. If a TRANSACTION has an optional association with a COUNTRY, then using min-max notation we would indicate

COUNTRY 0:1 ----------- 0:N TRANSACTION

1:1 doesn't imply "IFF a value is provided", it explicitly states a value must be provided.


问:
Django and get_absolute_url
I have simple "post" model which represents an entry for my blog:

```<code>class Post(models.Model):
    title = models.CharField('title', max_length=200)
    slug = models.SlugField('slug', unique_for_date='creation_time')
    creation_time = models.DateTimeField('creation time', auto_now_add=True)
    content = models.TextField('content')

    @permalink
    def get_absolute_url(self):
        return ('devblog_post_url', (), {
            'year': self.creation_time.year,
            'month': self.creation_time.month,
            'day': self.creation_time.day,
            'slug': self.slug})
</code>```

At the index of my blog, I want to paginate these Posts with this view:

```<code>def index_view(request):
    published_posts = Post.objects.all()
    paginator = Paginator(published_posts, 10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        post_list = paginator.page(page)
    except (EmptyPage, InvalidPage):
        post_list = paginator.page(paginator.num_pages)

    return render_to_response('devblog_index.html', {"post_list": post_list})
</code>```

And now here is the problem, I get blank urls once I call the get_absolute_url method for a post with devblog_index.html template:

```<code>{% for post in post_list.object_list %}
    <a href="/{{ post.get_absolute_url }}/">{{ post.title }}</a><br />
{% endfor %}
</code>```

EDIT:

Here is my urls.py for my application:

from django.conf.urls.defaults import *

```<code>urlpatterns = patterns('',
    url(r'^$',
        view='devblog.views.index_view',
        name='devblog_index'
    ),
    url(r'^(?P<year>\d{4})/(?P<month>\w{1,2)/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
        view='devblog.views.post_view', name='devblog_post_url'
    )
)
</code>```

at the main urls.py, I simple include it as (r'^blog/', include('devblog.urls'))

Where can be the problem for this blank string url ?

Regards

答: Change (?P<month>\w{1,2) to (?P<month>\d{1,2}).

Title: Django and get_absolute_url

Body:
I have simple "post" model which represents an entry for my blog:

class Post(models.Model):
    title = models.CharField('title', max_length=200)
    slug = models.SlugField('slug', unique_for_date='creation_time')
    creation_time = models.DateTimeField('creation time', auto_now_add=True)
    content = models.TextField('content')

    @permalink
    def get_absolute_url(self):
        return ('devblog_post_url', (), {
            'year': self.creation_time.year,
            'month': self.creation_time.month,
            'day': self.creation_time.day,
            'slug': self.slug})

At the index of my blog, I want to paginate these Posts with this view:

def index_view(request):
    published_posts = Post.objects.all()
    paginator = Paginator(published_posts, 10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        post_list = paginator.page(page)
    except (EmptyPage, InvalidPage):
        post_list = paginator.page(paginator.num_pages)

    return render_to_response('devblog_index.html', {"post_list": post_list})

And now here is the problem, I get blank urls once I call the get_absolute_url method for a post with devblog_index.html template:

{% for post in post_list.object_list %}
    {{ post.title }}

{% endfor %}

EDIT:

Here is my urls.py for my application:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    url(r'^$',
        view='devblog.views.index_view',
        name='devblog_index'
    ),
    url(r'^(?P<year>\d{4})/(?P<month>\w{1,2)/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
        view='devblog.views.post_view', name='devblog_post_url'
    )
)

at the main urls.py, I simple include it as (r'^blog/', include('devblog.urls'))

Where can be the problem for this blank string url ?

Regards


问:
 element adding a random space after word
I'm using Angular4 and I'm noticing this really weird issue where one of my span elements adds an extra space to the end of a word like this:

The only CSS properties being set are font-family, -webkit-font-smoothing, line-height and box-sizing.

I tried changing the word-spacing and white-space properties but that did not work either. I've never encountered this issue before so any advice would be helpful

答:
Found that it wasn't a CSS issue but actually with the newlines in the template code.

Here was the code beforehand:

```<code><span *ngFor="let ingredient of keyIngredients; let i = index;">
    <span *ngIf="i > 0">, </span>
    <span *ngIf="i === keyIngredients.length - 1">and </span>
    <span [innerHTML]="ingredient"></span>
</span>
</code>```

I removed the newlines and put all the spans in one line to resolve it.

Title: <span> element adding a random space after word

Body:
Found that it wasn't a CSS issue but actually with the newlines in the template code.

Here was the code beforehand:

<span *ngFor="let ingredient of keyIngredients; let i = index;">
    <span *ngIf="i > 0">,&nbsp;</span>
    <span *ngIf="i === keyIngredients.length - 1">and&nbsp;</span>
    <span [innerHTML]="ingredient"></span>
</span>

I removed the newlines and put all the spans in one line to resolve it.


问:
"Deterministic" pseudorandom number generation
I am in a situation where I need to generate a very large (~10^16 elements) random matrix with a certain random sparsity pattern. Obviously storing all of these elements is completely infeasible. Only a few of the elements are needed at any given time, so they can be drawn on-demand - however, once an element is stored, it may be needed later, and it's important that the same value is used. i.e, elements cannot be thrown out and randomly redrawn - once a random element is drawn, it needs to be saved.

Based on the problem itself, there are potentially some clever ways to handle this that I won't get into. However, a colleague says that it should be possible to deterministically generate these random numbers as needed by using a pseudorandom number generator with seed given by the index in the matrix, i.e. use i + N*j for element (i, j) of the matrix where the matrix is size N*N. This would not be calling the rand() function, but using the underlying pseudorandom function with specific arguments to deterministically generate previously drawn random values. Then no numbers would need to be saved, and they could be deterministically redrawn on demand.

My understanding of PRG's was that for a sequence of numbers appear random, you must fix the seed. Does the above approach make sense? It seems to me to be like repeatedly re-seeding the PRG and just taking the first element.

答:
Not a precise answer, but some tryes.

A hash function seems to be a simple and efficient mean to achieve your goal.

Here are some good ideas about integer to integer hash-functions.

From this article I try that :

```<code>from numba import uint64, njit
import pylab as pl

@njit(uint64(uint64,uint64))
def hash64(i,j) :
    x= i + (j << 32)
    x = (x ^ (x >> 30)) * (0xbf58476d1ce4e5b9);
    x = (x ^ (x >> 27)) * (0x94d049bb133111eb);
    x = x ^ (x >> 31);
    return x;

n=1000
im=[[hash64(i,j) for i in range(n)] for j in range(n)]
pl.subplot(121)
pl.imshow(im)
pl.colorbar()
pl.subplot(122)
pl.hist(np.array(im).ravel(),bins=100)
pl.show()
</code>```

This numba hash64 function compute a hash code in ~ 200 ns.

And this plot (even it demonstrates nothing) shows that this function could be a good candidate.

By contrast the python hash function (hash((i,j)) on tuple) do not pass the test :

Here for A Knuth Generator :

And some benchmarks :

```<code>In [61]: %timeit hash64(0,1)
215 ns ± 9.11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [62]: %timeit np.random.seed(0+1<<30);a=np.random.randint(2**30)
4.18 µs ± 126 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [63]:%timeit  hash((0,1))
102 ns ± 19.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
</code>```

Body:
Not a precise answer, but some tryes.

A hash function seems to be a simple and efficient mean to achieve your goal.

Here are some good ideas about integer to integer hash-functions.

From this article I try that :

from numba import uint64, njit
import pylab as pl

@njit(uint64(uint64,uint64))
def hash64(i,j) :
    x= i + (j << 32)
    x = (x ^ (x >> 30)) * (0xbf58476d1ce4e5b9);
    x = (x ^ (x >> 27)) * (0x94d049bb133111eb);
    x = x ^ (x >> 31);
    return x;

n=1000
im=[[hash64(i,j) for i in range(n)] for j in range(n)]
pl.subplot(121)
pl.imshow(im)
pl.colorbar()
pl.subplot(122)
pl.hist(np.array(im).ravel(),bins=100)
pl.show()

This numba hash64 function compute a hash code in ~ 200 ns.

And this plot (even it demonstrates nothing) shows that this function could be a good candidate.

By contrast the python hash function (hash((i,j)) on tuple) do not pass the test :

Here for A Knuth Generator :

And some benchmarks :

In [61]: %timeit hash64(0,1)
215 ns ± 9.11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [62]: %timeit np.random.seed(0+1<<30);a=np.random.randint(2**30)
4.18 µs ± 126 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [63]:%timeit  hash((0,1))
102 ns ± 19.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)