问:
Group data frame columns by their dates (which comprise column titles) and summarize instances of 1s and 0s in R
I have a bit of annoying coding problem, about which I'd appreciate your assistance.

Here are some sample data:

```<code>ID     "2013-03-20"    "2013-04-09"    "2013-04-11"    "2013-04-17"
5167f            0               0               0               1
1214m            0               0               0               0
1844f            0               1               1               0
2113m            0               0               1               1
</code>```

Here's the rub: notice how the column names of the sample data frame comprise dates, and some dates can be close to one another. The ID column is a simple unique identifier for the observations.

Here are my goals:

(1) I'd like to be able to first group the columns by whether or not they each fall within a 2-week (or 14-day) range (i.e. that is defined by 2-week increments starting on "2013-03-20" until "2016-12-20"); thus, if they do fall within the same range, they'd receive the same identifier (for a new data frame; e.g., Period1 for any dates that fall between "2013-03-20" and "2013-04-03").

(2) Once all of the date columns are assigned to a particular period, I then want to summarize the cell data (of 0s and 1s) per period in the following way: if any 1 appears in a particular period for an individual (at all) then that individual would receive a 1 for the whole period (also, if the individual only has 0s for that period, then it would receive a 0 for that single period).

(3) Once this workflow is defined, I then want to group the dates by seasons and years based on their month codes (e.g., WinterYYYY = December, January, February; SpringYYYY = March, April, May; SummerYYYY = June, July, August; and FallYYYY = September, October, November) to produce a new data frame.

In summary, to demonstrate the products manually:

(End Product for Goals 1 and 2; i.e. for just first two columns in the sample data [date ranges in parentheses are just for a guide])

```<code>ID     Period1 ("2013-03-20" - "2013-04-03")        Period2 ("2013-04-04" - "2013-04-18")
5167f                                    0                                 1
1214m                                    0                                 0
1844f                                    0                                 1
2113m                                    0                                 1
</code>```

(End Product for Goals 2 and 3; i.e. for all columns in the sample data [month ranges in parentheses are just for a guide])

```<code>ID                Spring2013  (March - May)
5167f                                    1
1214m                                    0
1844f                                    1
2113m                                    1
</code>```

Perhaps, something from the dplyr package could be useful, but I'm not quite sure.

Thank you for any help, in advance. Please feel free to ask any follow-up questions for clarifications.

-AD-

答:
Please put your data in a tidy format first.

```<code>library(dplyr)
data <- gather(data, date, value, -ID )
</code>```

Then try:

```<code>library(lubridate)
data$date  <- ymd(data$date)
data <-  mutate(data, period = date - as.Date("2013-03-20")) #difference in days
data <- mutate(data, period2 = ceiling(as.numeric(data$period)/14))
data$period2 <- ifelse(data$period2 == 0, 1, data$period2) #change period 0 to period 1

newdat <- data %>%
          group_by(ID, period2) %>%
          summarise(result = ifelse(sum(value)>0, 1, 0))
</code>```

Use the spread() function to change back to the original format.

Body:
I have a bit of annoying coding problem, about which I'd appreciate your assistance.

Here are some sample data:

ID     "2013-03-20"    "2013-04-09"    "2013-04-11"    "2013-04-17"
5167f            0               0               0               1
1214m            0               0               0               0
1844f            0               1               1               0
2113m            0               0               1               1

Here's the rub: notice how the column names of the sample data frame comprise dates, and some dates can be close to one another. The ID column is a simple unique identifier for the observations.

Here are my goals:

(1) I'd like to be able to first group the columns by whether or not they each fall within a 2-week (or 14-day) range (i.e. that is defined by 2-week increments starting on "2013-03-20" until "2016-12-20"); thus, if they do fall within the same range, they'd receive the same identifier (for a new data frame; e.g., Period1 for any dates that fall between "2013-03-20" and "2013-04-03").

(2) Once all of the date columns are assigned to a particular period, I then want to summarize the cell data (of 0s and 1s) per period in the following way: if any 1 appears in a particular period for an individual (at all) then that individual would receive a 1 for the whole period (also, if the individual only has 0s for that period, then it would receive a 0 for that single period).

(3) Once this workflow is defined, I then want to group the dates by seasons and years based on their month codes (e.g., WinterYYYY = December, January, February; SpringYYYY = March, April, May; SummerYYYY = June, July, August; and FallYYYY = September, October, November) to produce a new data frame.

In summary, to demonstrate the products manually:

(End Product for Goals 1 and 2; i.e. for just first two columns in the sample data [date ranges in parentheses are just for a guide])

ID     Period1 ("2013-03-20" - "2013-04-03")        Period2 ("2013-04-04" - "2013-04-18")
5167f                                    0                                 1
1214m                                    0                                 0
1844f                                    0                                 1
2113m                                    0                                 1

(End Product for Goals 2 and 3; i.e. for all columns in the sample data [month ranges in parentheses are just for a guide])

ID                Spring2013  (March - May)
5167f                                    1
1214m                                    0
1844f                                    1
2113m                                    1

Perhaps, something from the dplyr package could be useful, but I'm not quite sure.

Thank you for any help, in advance. Please feel free to ask any follow-up questions for clarifications.

-AD-

Body:
Please put your data in a tidy format first.

library(dplyr)
data <- gather(data, date, value, -ID )

Then try:

library(lubridate)
data$date  <- ymd(data$date)
data <-  mutate(data, period = date - as.Date("2013-03-20")) #difference in days
data <- mutate(data, period2 = ceiling(as.numeric(data$period)/14))
data$period2 <- ifelse(data$period2 == 0, 1, data$period2) #change period 0 to period 1

newdat <- data %>%
          group_by(ID, period2) %>%
          summarise(result = ifelse(sum(value)>0, 1, 0))

Use the spread() function to change back to the original format.


来源: stackexchange

问:
Draw a line with a gradient brush (fade out from start to end point)
My task is pretty simple: draw a line from point A to point B and set different colors at point A and B, e.g. White at A and Black at B to fade out the line.

I tried doing this using a LinearGradientBrush:

```<code>var brush = new LinearGradientBrush(
                    Color.FromArgb(255, 0, 0, 0),
                    Color.FromArgb(255, 255, 0, 0), new Point(0, 0), new Point(1,1));
var pen = new Pen(brush, 10.0);

dc.DrawLine(pen, new Point (300, 300), new Point(300, 100));
</code>```

But this does not produce the wanted results since the GradientBrush is mapped according to the bounding box of the object. Therefore, the results for line going from 100/100 to 200/200 and a line going the opposite direction are the same (which is not what I want).

How could I solve this using WPF? Thanks.

Edit: I need to use the low level graphics functions (such as DrawLine) for performance reasons because I draw a lot of lines.

答:
The MappingMode property on the brush allows you to specify absolute coordinates for the start / end points, or coordinates relative to the shapes bounds:

http://msdn.microsoft.com/en-us/library/system.windows.media.gradientbrush.mappingmode.aspx

ContentLicense: CC BY-SA 2.5

Body:
My task is pretty simple: draw a line from point A to point B and set different colors at point A and B, e.g. White at A and Black at B to fade out the line.

I tried doing this using a LinearGradientBrush:

var brush = new LinearGradientBrush(
                    Color.FromArgb(255, 0, 0, 0),
                    Color.FromArgb(255, 255, 0, 0), new Point(0, 0), new Point(1,1));
var pen = new Pen(brush, 10.0);

dc.DrawLine(pen, new Point (300, 300), new Point(300, 100));

But this does not produce the wanted results since the GradientBrush is mapped according to the bounding box of the object. Therefore, the results for line going from 100/100 to 200/200 and a line going the opposite direction are the same (which is not what I want).

How could I solve this using WPF? Thanks.

Edit: I need to use the low level graphics functions (such as DrawLine) for performance reasons because I draw a lot of lines.


问:
Firebase - Download specific child (Swift 3)
I have attached a picture of my JSON tree

```<code>{
  "-Ko4cg3ik5OFsnLTI4q4" : {
    "FacebookPage" : {
      "id" : "187736205061418",
      "page" : "partyunlimitedtoronto"
    },
    "MapView" : {
      "Edate" : 523940400,
      "Sdate" : 523929600,
      "intersted" : 3843,
      "lat" : 45.510772273476,
      "lng" : -73.563586483671,
      "type" : "MUSIC",
      "userID" : 1373802105986614,
      "visibility" : "Public"
    },
    "address" : "Théâtre Corona",
    "bio" : "evenko & Greenland Productions présentent\t\nMogwai\navec/with Xander Harris \nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 24 mars à 10h\n\n37$ à 42$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: March 24 at 10am\n\n$37 to $42\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
    "name" : "Mogwai // Montréal",
    "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17361785_10155183713782422_6829705267219994059_n.jpg?oh=150f6f53c74233b70b7f1b372c1db1e4&oe=59CF07EE",
    "site" : "http://www.evenko.ca/fr/evenements/12392/mogwai/theatre-corona/12-06-2017",
    "status" : "normal"
  },
  "-Ko4cgP2rXJCIRBODWpm" : {
    "FacebookPage" : {
      "id" : "620998508097068",
      "page" : "partyunlimitedtoronto"
    },
    "MapView" : {
      "Edate" : 43223454,
      "Sdate" : 65837495,
      "interested" : 2355,
      "lat" : 45.3846583,
      "lng" : -74.4736583,
      "type" : "Party",
      "userID" : 1373802105986614,
      "visibility " : "Public"
    },
    "address" : "Théâtre Corona",
    "bio" : "Greenland Productions & evenko présentent\t\t\t\t\t\t\nNazareth\t\t\t\navec/with Les Deuxluxes\t\n\nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 14 avril à midi \n\n44,50$ à 48$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: April 14 at noon\n\n$44,50 to $48\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
    "name" : "Nazareth // Montréal",
    "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17759677_10155255160737422_1735715699829358715_n.jpg?oh=1d6d1c250c2c6b38c6ef0de4483bd0a9&oe=5A0C4879",
    "site" : "http://www.evenko.ca/fr/evenements/12489/nazareth/theatre-corona/08-03-2017",
    "status" : "normal"
  }
}
</code>```

So I'm attempting to only download the "MapView" node inside every child when I run my program but in this case, I won't know the name of the parent of "MapView". Is there any way to only download a specific child like in this case. Otherwise, I was thinking whether I should use this style of structuring.

```<code>{
  "EventView" : {
    "-Ko4cg3ik5OFsnLTI4q4" : {
      "FacebookPage" : {
        "id" : "187736205061418",
        "page" : "partyunlimitedtoronto"
      },
      "address" : "Théâtre Corona",
      "bio" : "evenko & Greenland Productions présentent\t\nMogwai\navec/with Xander Harris \nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 24 mars à 10h\n\n37$ à 42$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: March 24 at 10am\n\n$37 to $42\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
      "name" : "Mogwai // Montréal",
      "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17361785_10155183713782422_6829705267219994059_n.jpg?oh=150f6f53c74233b70b7f1b372c1db1e4&oe=59CF07EE",
      "site" : "http://www.evenko.ca/fr/evenements/12392/mogwai/theatre-corona/12-06-2017",
      "status" : "normal"
    },
    "-Ko4cgP2rXJCIRBODWpm" : {
      "FacebookPage" : {
        "id" : "620998508097068",
        "page" : "partyunlimitedtoronto"
      },
      "address" : "Théâtre Corona",
      "bio" : "Greenland Productions & evenko présentent\t\t\t\t\t\t\nNazareth\t\t\t\navec/with Les Deuxluxes\t\n\nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 14 avril à midi \n\n44,50$ à 48$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: April 14 at noon\n\n$44,50 to $48\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
      "name" : "Nazareth // Montréal",
      "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17759677_10155255160737422_1735715699829358715_n.jpg?oh=1d6d1c250c2c6b38c6ef0de4483bd0a9&oe=5A0C4879",
      "site" : "http://www.evenko.ca/fr/evenements/12489/nazareth/theatre-corona/08-03-2017",
      "status" : "normal"
    }
  },
  "MapView" : {
    "-Ko4cg3ik5OFsnLTI4q4" : {
      "Edate" : 534312000,
      "Sdate" : 534301200,
      "intersted" : 652,
      "lat" : 45.4827983,
      "lng" : -73.575107687761,
      "type" : "MUSIC",
      "userID" : "1373802105986614",
      "visibility" : "Public"
    },
    "-Ko4cgP2rXJCIRBODWpm" : {
      "Edate" : 523508400,
      "Sdate" : 523497600,
      "intersted" : 382,
      "lat" : 45.4827983,
      "lng" : -73.575107687761,
      "type" : "MUSIC",
      "userID" : "1373802105986614",
      "visibility" : "Public"
    }
  }
}
</code>```

where in this case I would have the information in a separate child but where there are parent nodes with the same name in both EventView and MapView.

答:
For the First structure

This structure will definitely make our query download the whole EventView node

```<code>var AllMapViews = []; //<-- array of all mapview objects

var path = "/EventView";
firebase.database().ref(path)
                .once("value")
                .then(eventViews => {

                    eventViews.forEach(thisevent => {

                       AllMapViews.push(thisevent.val().MapView);

                    })
                });
</code>```

Hence the result of the above will look like this

```<code>AllMapViews = [
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
...
]
</code>```

For the Second structure (My Choice)

This structure will allow our query download only MapViews for all EventViews. Hence, making it the structure of choice in your implementation. Though it will need you to monitor the main EventView nodes often to know when the main event is deleted so that you can also delete it's corresponding MapView.

```<code>var AllMapViews = []; //<-- array of all mapview objects

    var path = "/MapViews";
    firebase.database().ref(path)
                    .once("value")
                    .then(mapViews => {

                        mapViews.forEach(map => {

                           AllMapViews.push(map.val());

                        })
                    });
</code>```

Hence the result of the above will look like this

```<code>AllMapViews = [
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
...
]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have attached a picture of my JSON tree

{
  "-Ko4cg3ik5OFsnLTI4q4" : {
    "FacebookPage" : {
      "id" : "187736205061418",
      "page" : "partyunlimitedtoronto"
    },
    "MapView" : {
      "Edate" : 523940400,
      "Sdate" : 523929600,
      "intersted" : 3843,
      "lat" : 45.510772273476,
      "lng" : -73.563586483671,
      "type" : "MUSIC",
      "userID" : 1373802105986614,
      "visibility" : "Public"
    },
    "address" : "Théâtre Corona",
    "bio" : "evenko & Greenland Productions présentent\t\nMogwai\navec/with Xander Harris \nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 24 mars à 10h\n\n37$ à 42$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: March 24 at 10am\n\n$37 to $42\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
    "name" : "Mogwai // Montréal",
    "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17361785_10155183713782422_6829705267219994059_n.jpg?oh=150f6f53c74233b70b7f1b372c1db1e4&oe=59CF07EE",
    "site" : "http://www.evenko.ca/fr/evenements/12392/mogwai/theatre-corona/12-06-2017",
    "status" : "normal"
  },
  "-Ko4cgP2rXJCIRBODWpm" : {
    "FacebookPage" : {
      "id" : "620998508097068",
      "page" : "partyunlimitedtoronto"
    },
    "MapView" : {
      "Edate" : 43223454,
      "Sdate" : 65837495,
      "interested" : 2355,
      "lat" : 45.3846583,
      "lng" : -74.4736583,
      "type" : "Party",
      "userID" : 1373802105986614,
      "visibility " : "Public"
    },
    "address" : "Théâtre Corona",
    "bio" : "Greenland Productions & evenko présentent\t\t\t\t\t\t\nNazareth\t\t\t\navec/with Les Deuxluxes\t\n\nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 14 avril à midi \n\n44,50$ à 48$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: April 14 at noon\n\n$44,50 to $48\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
    "name" : "Nazareth // Montréal",
    "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17759677_10155255160737422_1735715699829358715_n.jpg?oh=1d6d1c250c2c6b38c6ef0de4483bd0a9&oe=5A0C4879",
    "site" : "http://www.evenko.ca/fr/evenements/12489/nazareth/theatre-corona/08-03-2017",
    "status" : "normal"
  }
}

So I'm attempting to only download the "MapView" node inside every child when I run my program but in this case, I won't know the name of the parent of "MapView". Is there any way to only download a specific child like in this case. Otherwise, I was thinking whether I should use this style of structuring.

{
  "EventView" : {
    "-Ko4cg3ik5OFsnLTI4q4" : {
      "FacebookPage" : {
        "id" : "187736205061418",
        "page" : "partyunlimitedtoronto"
      },
      "address" : "Théâtre Corona",
      "bio" : "evenko & Greenland Productions présentent\t\nMogwai\navec/with Xander Harris \nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 24 mars à 10h\n\n37$ à 42$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: March 24 at 10am\n\n$37 to $42\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
      "name" : "Mogwai // Montréal",
      "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17361785_10155183713782422_6829705267219994059_n.jpg?oh=150f6f53c74233b70b7f1b372c1db1e4&oe=59CF07EE",
      "site" : "http://www.evenko.ca/fr/evenements/12392/mogwai/theatre-corona/12-06-2017",
      "status" : "normal"
    },
    "-Ko4cgP2rXJCIRBODWpm" : {
      "FacebookPage" : {
        "id" : "620998508097068",
        "page" : "partyunlimitedtoronto"
      },
      "address" : "Théâtre Corona",
      "bio" : "Greenland Productions & evenko présentent\t\t\t\t\t\t\nNazareth\t\t\t\navec/with Les Deuxluxes\t\n\nPortes: 19h00 - Spectacle: 20h00\n\nMise en vente: 14 avril à midi \n\n44,50$ à 48$\n\nPrix lors de l’achat à la billetterie / Des frais de manutention peuvent s’appliquer lors de l’achat en ligne.\n\n.....................................................\n\nDoors: 7:00 pm - Show: 8:00 pm\n\nOn Sale: April 14 at noon\n\n$44,50 to $48\n\nPrices for box office purchase / Handling fees may apply for online purchase.",
      "name" : "Nazareth // Montréal",
      "pic" : "https://scontent.xx.fbcdn.net/v/t1.0-9/17759677_10155255160737422_1735715699829358715_n.jpg?oh=1d6d1c250c2c6b38c6ef0de4483bd0a9&oe=5A0C4879",
      "site" : "http://www.evenko.ca/fr/evenements/12489/nazareth/theatre-corona/08-03-2017",
      "status" : "normal"
    }
  },
  "MapView" : {
    "-Ko4cg3ik5OFsnLTI4q4" : {
      "Edate" : 534312000,
      "Sdate" : 534301200,
      "intersted" : 652,
      "lat" : 45.4827983,
      "lng" : -73.575107687761,
      "type" : "MUSIC",
      "userID" : "1373802105986614",
      "visibility" : "Public"
    },
    "-Ko4cgP2rXJCIRBODWpm" : {
      "Edate" : 523508400,
      "Sdate" : 523497600,
      "intersted" : 382,
      "lat" : 45.4827983,
      "lng" : -73.575107687761,
      "type" : "MUSIC",
      "userID" : "1373802105986614",
      "visibility" : "Public"
    }
  }
}

where in this case I would have the information in a separate child but where there are parent nodes with the same name in both EventView and MapView.

Body:
For the First structure

This structure will definitely make our query download the whole EventView node

var AllMapViews = []; //<-- array of all mapview objects

var path = "/EventView";
firebase.database().ref(path)
                .once("value")
                .then(eventViews => {

                    eventViews.forEach(thisevent => {

                       AllMapViews.push(thisevent.val().MapView);

                    })
                });

Hence the result of the above will look like this

AllMapViews = [
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
...
]

For the Second structure (My Choice)

This structure will allow our query download only MapViews for all EventViews. Hence, making it the structure of choice in your implementation. Though it will need you to monitor the main EventView nodes often to know when the main event is deleted so that you can also delete it's corresponding MapView.

var AllMapViews = []; //<-- array of all mapview objects

    var path = "/MapViews";
    firebase.database().ref(path)
                    .once("value")
                    .then(mapViews => {

                        mapViews.forEach(map => {

                           AllMapViews.push(map.val());

                        })
                    });

Hence the result of the above will look like this

AllMapViews = [
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
{ "EventDate":343,"Sdate" : 65837495 ..},
...
]


问:
JavaScript timer not working on multiple instance
Below is a result of a loop and I want to run timer to count up to the set time for each of the loop result.

```<code><span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>

<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>

<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
</code>```

The timer script:

```<code>$(document).ready(function(){

  $('[data-time]').each(function() {
    console.log($(this))
    var $this = $(this),
      finalTime = $(this).data('time'),
      url       = $(this).data('url')

    // Set the date we're counting down to
    var countDownDate = new Date(finalTime).getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

      // Get todays date and time
      var now = new Date().getTime();

      // Find the distance between now an the count down date
      var distance = countDownDate - now;

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // Display the result in an element with id="demo"
      document.getElementById("time").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("time").innerHTML = "EXPIRED";
      }
    }, 1000);
  })
})
</code>```

So am using Laravel and jQuery to run the timer.

I want assistance with the code because it is not working.

答:
The trick is to "save" you intervals in an array.

If you do not do it, it gets overwritten on each loop iteration.

Then, to refer to the right span element, you have to get the iteration index for later use in an .eq() method.

You can't use an id in a loop, since it has to be unique.

Have a look at comments within the code.

$(document).ready(function(){

  // an arrary to store the intervals created.
  var timerArray = [];

  $('[data-time]').each(function(index) {
    console.log($(this).data("time"));

    var finalTime = $(this).data('time');

    // Set the date we're counting down to
    var countDownDate = new Date(finalTime).getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

      // this Index will be used to refer to the right span.
      var thisIndex = index;
      console.log("interval "+thisIndex);

      // Get todays date and time
      var now = new Date().getTime();

      // Find the distance between now an the count down date
      var distance = countDownDate - now;

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // Leading zeros...
      if(hours<10){hours="0"+hours}
      if(minutes<10){minutes="0"+minutes}
      if(seconds<10){seconds="0"+seconds}

      // Display the result in an element with id="demo"
      $('[data-time]').eq(thisIndex).html( days + "d " + hours + "h " + minutes + "m " + seconds + "s " );

      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(timerArray[thisIndex]);
        $('[data-time]').eq(thisIndex).html("EXPIRED");
      }
    }, 1000);

    // Place this timer in an array... So it won't be overwritten.
    timerArray.push(x);
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span data-time="07/08/2017 12:30:00"></span><br>
<br>
<span data-time="07/10/2017 19:50:30"></span><br>
<br>
<span data-time="07/12/2017 5:24:24"></span><br>
<br></code>```

Run the snippet in "full page" or look at this CodePen.

Body:
Below is a result of a loop and I want to run timer to count up to the set time for each of the loop result.

created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}">

created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}">

created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}">

The timer script:

$(document).ready(function(){

  $('[data-time]').each(function() {
    console.log($(this))
    var $this = $(this),
      finalTime = $(this).data('time'),
      url       = $(this).data('url')

    // Set the date we're counting down to
    var countDownDate = new Date(finalTime).getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

      // Get todays date and time
      var now = new Date().getTime();

      // Find the distance between now an the count down date
      var distance = countDownDate - now;

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // Display the result in an element with id="demo"
      document.getElementById("time").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("time").innerHTML = "EXPIRED";
      }
    }, 1000);
  })
})

So am using Laravel and jQuery to run the timer.

I want assistance with the code because it is not working.

Body:
The trick is to "save" you intervals in an array.

If you do not do it, it gets overwritten on each loop iteration.

Then, to refer to the right span element, you have to get the iteration index for later use in an .eq() method.

You can't use an id in a loop, since it has to be unique.

Have a look at comments within the code.

$(document).ready(function(){

  // an arrary to store the intervals created.
  var timerArray = [];

  $('[data-time]').each(function(index) {
    console.log($(this).data("time"));

    var finalTime = $(this).data('time');

    // Set the date we're counting down to
    var countDownDate = new Date(finalTime).getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

      // this Index will be used to refer to the right span.
      var thisIndex = index;
      console.log("interval "+thisIndex);

      // Get todays date and time
      var now = new Date().getTime();

      // Find the distance between now an the count down date
      var distance = countDownDate - now;

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // Leading zeros...
      if(hours<10){hours="0"+hours}
      if(minutes<10){minutes="0"+minutes}
      if(seconds<10){seconds="0"+seconds}

      // Display the result in an element with id="demo"
      $('[data-time]').eq(thisIndex).html( days + "d " + hours + "h " + minutes + "m " + seconds + "s " );

      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(timerArray[thisIndex]);
        $('[data-time]').eq(thisIndex).html("EXPIRED");
      }
    }, 1000);

    // Place this timer in an array... So it won't be overwritten.
    timerArray.push(x);
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span data-time="07/08/2017 12:30:00"></span><br>
<br>
<span data-time="07/10/2017 19:50:30"></span><br>
<br>
<span data-time="07/12/2017 5:24:24"></span><br>
<br>

Run the snippet in "full page" or look at this CodePen.


问:
Subscript out of range (Error 9): Loop through a folder of Excel files, copy cells and paste in the current worksheet
I'm a beginner in VBA and have to work on some task to open a folder consists of scientific results in Excel files, select some cells based on a specific key from each Excel file and retrieve these data to the current workbook/worksheet in a sort of final table.

I'm getting this error

Subscript out of range (Error 9)

and I know the reason because it can't find the current worksheet to paste the data as required.

The current workbook named Task and current worksheet Output

Here's the edited code:

```<code>Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            sht.Cells(i, 6).Copy 'BW
            sht.Cells(i, 8).Copy 'Spec_symbol

       ' copy to the final sheet
        erow = current.Worksheets("Output").Cells(85, 1)

       ActiveSheet.Cells(erow, 1).Select
       ActiveSheet.Paste
       ActiveWorkbook.Save
       ActiveWorkbook.Close
       Application.CutCopyMode = False
        End If

Next i
Next element

  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

I guess the problem now is that this line returns Nothing, however it opens the right worksheet and both myPath & myFile are correct!

```<code>Set wb = Workbooks.Open(Filename:=myPath & myFile)
</code>```

答:
So, here's the working code: it does retrieve data to the current worksheet, hope it helps anybody in the future.</p>

```<code>Option Explicit
Sub LoopAllExcelFilesInFolder()

Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim saywhat
Dim zItem
Dim arr(3) As String
Dim element As Variant
Dim LastRow As Long
Dim BW As Long
Dim RowCount As Integer
arr(0) = "aclr_utra1"
arr(1) = "aclr_utra2"
arr(2) = "aclr_eutra"

Path = ThisWorkbook.Path                        'set a default path

'**********************************************
'DISPLAY FOLDER SELECTION BOX..                   'display folder picker
'**********************************************
With Application.FileDialog(msoFileDialogFolderPicker)          'use shortcut
saywhat = "Select the source folder for the source datafiles.." 'define browser text
.Title = saywhat                                'show heading message for THIS dialog box
.AllowMultiSelect = False                       'allow only one file to be selected
.InitialFileName = Path                         'set default source folder
zItem = .Show                                   'display the file selection dialog

.InitialFileName = ""                           'clear and reset search folder\file filter

If zItem = 0 Then Exit Sub                      'User cancelled; 0=no folder chosen

Path = .SelectedItems(1)                        'selected folder
End With                                        'end of shortcut

If Right(Path, 1) <> "\" Then                   'check for required last \ in path
Path = Path & "\"                               'add required last \ if missing
End If                                          'end of test fro required last \ char

Debug.Print Path
Filename = Dir(Path & "*.xlsm")

Debug.Print Filename

Do While Len(Filename) > 0
Set wbk = Workbooks.Open(Filename:=Path & Filename)
      Dim i As Integer
      LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
        For Each element In arr
          ' Retrieve and copy the matched results
            For i = 35 To LastRow
                If ActiveSheet.Cells(i, 9).Value = CStr(element) Then

                    Debug.Print CStr(element)
                    Debug.Print ActiveSheet.Cells(i, 7).Value
                    BW = ActiveSheet.Cells(i, 7).Select 'BW
                    Range(Selection, Selection.End(xlDown)).Select
                    Range(Selection, Selection.End(xlToRight)).Select
                    Selection.Copy
                    Windows("Task.xlsm").Activate
                    Range("A1").Select
                    RowCount = Worksheets("Output").Range("A1").CurrentRegion.Rows.Count
                    With Worksheets("Output").Range("A1").Offset(RowCount, 0) = BW
                    End With
                    ActiveWorkbook.Save
                    End If

            Next i
        Next element

wbk.Close True
Filename = Dir

Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

Body:
I'm a beginner in VBA and have to work on some task to open a folder consists of scientific results in Excel files, select some cells based on a specific key from each Excel file and retrieve these data to the current workbook/worksheet in a sort of final table.

I'm getting this error

Subscript out of range (Error 9)

and I know the reason because it can't find the current worksheet to paste the data as required.

The current workbook named Task and current worksheet Output

Here's the edited code:

Sub LoopAllExcelFilesInFolder()

  Dim wb As Workbook, current As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim FldrPicker As FileDialog
  Dim sht As Worksheet

  'set source workbook
  Set current = ThisWorkbook

 'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

  'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

   'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set sht = wb.Worksheets(1)

      ' create an array with the keys' names
      Dim arr(3) As String
      Dim element As Variant

      arr(0) = "aclr_utra1"
      arr(1) = "aclr_utra2"
      arr(2) = "aclr_eutra"

      ' get the last row in each worksheet
       Dim LastRow As Integer, i As Integer, erow As Integer
       LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
      For Each element In arr

      ' Retrieve and copy the matched results

        For i = 35 To LastRow
            If sht.Cells(i, 9).Value = CStr(element) Then

            sht.Cells(i, 6).Copy 'BW
            sht.Cells(i, 8).Copy 'Spec_symbol

       ' copy to the final sheet
        erow = current.Worksheets("Output").Cells(85, 1)

       ActiveSheet.Cells(erow, 1).Select
       ActiveSheet.Paste
       ActiveWorkbook.Save
       ActiveWorkbook.Close
       Application.CutCopyMode = False
        End If

Next i
Next element

  'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
    Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

I guess the problem now is that this line returns Nothing, however it opens the right worksheet and both myPath & myFile are correct!

Set wb = Workbooks.Open(Filename:=myPath & myFile)

Body:
So, here's the working code: it does retrieve data to the current worksheet, hope it helps anybody in the future.

Option Explicit
Sub LoopAllExcelFilesInFolder()

Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim saywhat
Dim zItem
Dim arr(3) As String
Dim element As Variant
Dim LastRow As Long
Dim BW As Long
Dim RowCount As Integer
arr(0) = "aclr_utra1"
arr(1) = "aclr_utra2"
arr(2) = "aclr_eutra"

Path = ThisWorkbook.Path                        'set a default path

'**********************************************
'DISPLAY FOLDER SELECTION BOX..                   'display folder picker
'**********************************************
With Application.FileDialog(msoFileDialogFolderPicker)          'use shortcut
saywhat = "Select the source folder for the source datafiles.." 'define browser text
.Title = saywhat                                'show heading message for THIS dialog box
.AllowMultiSelect = False                       'allow only one file to be selected
.InitialFileName = Path                         'set default source folder
zItem = .Show                                   'display the file selection dialog

.InitialFileName = ""                           'clear and reset search folder\file filter

If zItem = 0 Then Exit Sub                      'User cancelled; 0=no folder chosen

Path = .SelectedItems(1)                        'selected folder
End With                                        'end of shortcut

If Right(Path, 1) <> "\" Then                   'check for required last \ in path
Path = Path & "\"                               'add required last \ if missing
End If                                          'end of test fro required last \ char

Debug.Print Path
Filename = Dir(Path & "*.xlsm")

Debug.Print Filename

Do While Len(Filename) > 0
Set wbk = Workbooks.Open(Filename:=Path & Filename)
      Dim i As Integer
      LastRow = ActiveSheet.Range("J" & Rows.Count).End(xlUp).Row

      'create two nested loops to retrieve the results with each key
        For Each element In arr
          ' Retrieve and copy the matched results
            For i = 35 To LastRow
                If ActiveSheet.Cells(i, 9).Value = CStr(element) Then

                    Debug.Print CStr(element)
                    Debug.Print ActiveSheet.Cells(i, 7).Value
                    BW = ActiveSheet.Cells(i, 7).Select 'BW
                    Range(Selection, Selection.End(xlDown)).Select
                    Range(Selection, Selection.End(xlToRight)).Select
                    Selection.Copy
                    Windows("Task.xlsm").Activate
                    Range("A1").Select
                    RowCount = Worksheets("Output").Range("A1").CurrentRegion.Rows.Count
                    With Worksheets("Output").Range("A1").Offset(RowCount, 0) = BW
                    End With
                    ActiveWorkbook.Save
                    End If

            Next i
        Next element

wbk.Close True
Filename = Dir

Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub


问:
Profile picture default size
AS in facebook,orkut what should be  the profile pic settings height,width etc so that the image is clear and do not have any distortion when viewing it</p>

```<code>     <img src="image.gif"  style="height:75px;width:130px;"  />
</code>```

答:
Try this instead. It should work:</p>

```<code><img src="image.gif"  style="max-height:75px;width:130px;"  />
</code>```

Title: Profile picture default size

Body:
Try this instead. It should work:

<img src="image.gif"  style="max-height:75px;width:130px;"  />


问:
How to calculate multiple columns from multiple columns in pandas
I am trying to calculate multiple colums from multiple columns in a pandas dataframe using a function.
The function takes three arguments -a-, -b-, and -c- and and returns three calculated values -sum-, -prod- and -quot-. In my pandas data frame I have three coumns -a-, -b- and and -c- from which I want to calculate the columns -sum-, -prod- and -quot-.

The mapping that I do works only when I have exactly three rows. I do not know what is going wrong, although I expect that it has to do something with selecting the correct axis. Could someone explain what is happening and how I can calculate the values that I would like to have.
Below are the situations that I have tested.

INITIAL VALUES

```<code>def sum_prod_quot(a,b,c):
    sum  = a + b + c
    prod = a * b * c
    quot = a / b / c
    return (sum, prod, quot)

df = pd.DataFrame({ 'a': [20, 100, 18],
                    'b': [ 5,  10,  3],
                    'c': [ 2,  10,  6],
                    'd': [ 1,   2,  3]
                 })

df
    a   b   c  d
0   20   5   2  1
1  100  10  10  2
2   18   3   6  3
</code>```

CALCULATION STEPS

Using exactly three rows

When I calculate three columns from this dataframe and using the function function I get:

```<code>df['sum'], df['prod'], df['quot'] = \
        list( map(sum_prod_quot, df['a'], df['b'], df['c']))

df
     a   b   c  d    sum     prod   quot
0   20   5   2  1   27.0    120.0   27.0
1  100  10  10  2  200.0  10000.0  324.0
2   18   3   6  3    2.0      1.0    1.0
</code>```

This is exactly the result that I want to have: The sum-column has the sum of the elements in the columns a,b,c; the prod-column has the product of the elements in the columns a,b,c and the quot-column has the quotients of the elements in the columns a,b,c.

Using more than three rows

When I expand the dataframe with one row, I get an error!

The data frame is defined as:

```<code>df = pd.DataFrame({ 'a': [20, 100, 18, 40],
                    'b': [ 5,  10,  3, 10],
                    'c': [ 2,  10,  6,  4],
                    'd': [ 1,   2,  3,  4]
                 })
df
     a   b   c  d
0   20   5   2  1
1  100  10  10  2
2   18   3   6  3
3   40  10   4  4
</code>```

The call is

```<code>df['sum'], df['prod'], df['quot'] = \
        list( map(sum_prod_quot, df['a'], df['b'], df['c']))
</code>```

The result is

```<code>...
    list( map(sum_prod_quot, df['a'], df['b'], df['c']))
ValueError: too many values to unpack (expected 3)
</code>```

while I would expect an extra row:

```<code>df
     a   b   c  d    sum     prod   quot
0   20   5   2  1   27.0    120.0   27.0
1  100  10  10  2  200.0  10000.0  324.0
2   18   3   6  3    2.0      1.0    1.0
3   40  10   4  4   54.0   1600.0    1.0
</code>```

Using less than three rows

When I reduce tthe dataframe with one row I get also an error.
The dataframe is defined as:

```<code>df = pd.DataFrame({ 'a': [20, 100],
                    'b': [ 5,  10],
                    'c': [ 2,  10],
                    'd': [ 1,   2]
                 })
df
     a   b   c  d
0   20   5   2  1
1  100  10  10  2
</code>```

The call is

```<code>df['sum'], df['prod'], df['quot'] = \
        list( map(sum_prod_quot, df['a'], df['b'], df['c']))
</code>```

The result is

```<code>...
    list( map(sum_prod_quot, df['a'], df['b'], df['c']))
ValueError: need more than 2 values to unpack
</code>```

while I would expect a row less:

```<code>df
     a   b   c  d    sum     prod   quot
0   20   5   2  1   27.0    120.0   27.0
1  100  10  10  2  200.0  10000.0  324.0
</code>```

QUESTIONS

The questions I have:

1)  Why do I get these errors?

2)  How do I have to modify the call such that I get the desired data frame?

NOTE

In this link a similar question is asked, but the given answer did not work for me.

答:
The answer doesn't seem correct for 3 rows as well. Can you check other values except first row and first column. Looking at the results, product of 20*5*2 is NOT 120, it's 200 and is placed below in sum column. You need to form list in correct way before assigning to new columns. You can try use following to set the new columns:

```<code>df['sum'], df['prod'], df['quot'] = zip(*map(sum_prod_quot, df['a'], df['b'], df['c']))
</code>```

For details follow the link

Body:
I am trying to calculate multiple colums from multiple columns in a pandas dataframe using a function.
The function takes three arguments -a-, -b-, and -c- and and returns three calculated values -sum-, -prod- and -quot-. In my pandas data frame I have three coumns -a-, -b- and and -c- from which I want to calculate the columns -sum-, -prod- and -quot-.

The mapping that I do works only when I have exactly three rows. I do not know what is going wrong, although I expect that it has to do something with selecting the correct axis. Could someone explain what is happening and how I can calculate the values that I would like to have.
Below are the situations that I have tested.

INITIAL VALUES

def sum_prod_quot(a,b,c):
    sum  = a + b + c
    prod = a * b * c
    quot = a / b / c
    return (sum, prod, quot)

df = pd.DataFrame({ 'a': [20, 100, 18],
                    'b': [ 5,  10,  3],
                    'c': [ 2,  10,  6],
                    'd': [ 1,   2,  3]
                 })

df
    a   b   c  d
0   20   5   2  1
1  100  10  10  2
2   18   3   6  3

CALCULATION STEPS

Using exactly three rows

When I calculate three columns from this dataframe and using the function function I get:

df['sum'], df['prod'], df['quot'] = \
        list( map(sum_prod_quot, df['a'], df['b'], df['c']))

df
     a   b   c  d    sum     prod   quot
0   20   5   2  1   27.0    120.0   27.0
1  100  10  10  2  200.0  10000.0  324.0
2   18   3   6  3    2.0      1.0    1.0

This is exactly the result that I want to have: The sum-column has the sum of the elements in the columns a,b,c; the prod-column has the product of the elements in the columns a,b,c and the quot-column has the quotients of the elements in the columns a,b,c.

Using more than three rows

When I expand the dataframe with one row, I get an error!

The data frame is defined as:

df = pd.DataFrame({ 'a': [20, 100, 18, 40],
                    'b': [ 5,  10,  3, 10],
                    'c': [ 2,  10,  6,  4],
                    'd': [ 1,   2,  3,  4]
                 })
df
     a   b   c  d
0   20   5   2  1
1  100  10  10  2
2   18   3   6  3
3   40  10   4  4

The call is

df['sum'], df['prod'], df['quot'] = \
        list( map(sum_prod_quot, df['a'], df['b'], df['c']))

The result is

...
    list( map(sum_prod_quot, df['a'], df['b'], df['c']))
ValueError: too many values to unpack (expected 3)

while I would expect an extra row:

df
     a   b   c  d    sum     prod   quot
0   20   5   2  1   27.0    120.0   27.0
1  100  10  10  2  200.0  10000.0  324.0
2   18   3   6  3    2.0      1.0    1.0
3   40  10   4  4   54.0   1600.0    1.0

Using less than three rows

When I reduce tthe dataframe with one row I get also an error.
The dataframe is defined as:

df = pd.DataFrame({ 'a': [20, 100],
                    'b': [ 5,  10],
                    'c': [ 2,  10],
                    'd': [ 1,   2]
                 })
df
     a   b   c  d
0   20   5   2  1
1  100  10  10  2

The call is

df['sum'], df['prod'], df['quot'] = \
        list( map(sum_prod_quot, df['a'], df['b'], df['c']))

The result is

...
    list( map(sum_prod_quot, df['a'], df['b'], df['c']))
ValueError: need more than 2 values to unpack

while I would expect a row less:

df
     a   b   c  d    sum     prod   quot
0   20   5   2  1   27.0    120.0   27.0
1  100  10  10  2  200.0  10000.0  324.0

QUESTIONS

The questions I have:

1)  Why do I get these errors?

2)  How do I have to modify the call such that I get the desired data frame?

NOTE

In this link a similar question is asked, but the given answer did not work for me.

Body:
The answer doesn't seem correct for 3 rows as well. Can you check other values except first row and first column. Looking at the results, product of 20*5*2 is NOT 120, it's 200 and is placed below in sum column. You need to form list in correct way before assigning to new columns. You can try use following to set the new columns:

df['sum'], df['prod'], df['quot'] = zip(*map(sum_prod_quot, df['a'], df['b'], df['c']))

For details follow the link


问:
How to extract string after some character
I need to extract a known portion from a given string.

```<code>Ex:

test_str="http://localhost:8080/course-single.html"
</code>```

I need to extract "course-single" from above string. What is the most easiest way to do that?

答:
Use regular expressions:

```<code>word = re.search('\d/(.*?)\.html', test)
print word.groups()[0]
</code>```

Output:

```<code>course-single
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to extract a known portion from a given string.

Ex:

test_str="http://localhost:8080/course-single.html"

I need to extract "course-single" from above string. What is the most easiest way to do that?

Body:
Use regular expressions:

word = re.search('\d/(.*?)\.html', test)
print word.groups()[0]

Output:

course-single


问:
In my VUE application "this" keyword does select a DOM object
I am writing a VUE.js and FullCalendar application in my Calendar.vue component I run into a problem, the this keyword will not select an element. The template of the component looks like this:

```<code>    <template>
       <div id="calendar" :event-sources="eventSources" @event-selected="eventSelected" @event-created="eventCreated" :config="config">
          <button id="red" v-on:click="time">time</button>
          <full-calendar id="target" ref="calendarC" :navLinks="true" :event-sources="eventSources" @event-selected="eventSelected" @day-click="click"@event-created="eventCreated" :config="config"></full-calendar>
       </div>
   </template>
</code>```

And the function where my "this" keyword is not working is here:

```<code>    click: function(date, jsEvent, view) {
       $("#red").css('background-color', 'red'); //here the jQuery works
       $(this.selected).css('background-color', 'red');//here nothing happens
    }
</code>```

So when I click on an element in my calendar the button with the id red turns red which lets me know jQuery is working properly. But the element I click on does not turn red.

答:
As far as I know, Vue.js doesn't have a built-in concept of a 'selected' element. You may be better off by using the date returned by the day-click event to figure out what the CSS selector is, and then using that to set the background-color. See below for some untested code based on the answer to a related SO question:

```<code>click: function(date, jsEvent, view) {
    $("#red").css('background-color', 'red');

    var moment = date.toDate();
    MyDateString = moment.getFullYear() + '-'
                   + ('0' + (moment.getMonth() + 1) ).slice(-2)
                   + "-" +('0' + moment.getDate()).slice(-2);
    $('[data-date='+MyDateString+']').css({'background-color', 'red'});
}
</code>```

Source: Change day number color on click - not background

Body:
I am writing a VUE.js and FullCalendar application in my Calendar.vue component I run into a problem, the this keyword will not select an element. The template of the component looks like this:

    <template>

          <button id="red" v-on:click="time">time</button>
          <full-calendar id="target" ref="calendarC" :navLinks="true" :event-sources="eventSources" @event-selected="eventSelected" @day-click="click"@event-created="eventCreated" :config="config"></full-calendar>

   </template>

And the function where my "this" keyword is not working is here:

    click: function(date, jsEvent, view) {
       $("#red").css('background-color', 'red'); //here the jQuery works
       $(this.selected).css('background-color', 'red');//here nothing happens
    }

So when I click on an element in my calendar the button with the id red turns red which lets me know jQuery is working properly. But the element I click on does not turn red.

Body:
As far as I know, Vue.js doesn't have a built-in concept of a 'selected' element. You may be better off by using the date returned by the day-click event to figure out what the CSS selector is, and then using that to set the background-color. See below for some untested code based on the answer to a related SO question:

click: function(date, jsEvent, view) {
    $("#red").css('background-color', 'red');

    var moment = date.toDate();
    MyDateString = moment.getFullYear() + '-'
                   + ('0' + (moment.getMonth() + 1) ).slice(-2)
                   + "-" +('0' + moment.getDate()).slice(-2);
    $('[data-date='+MyDateString+']').css({'background-color', 'red'});
}

Source: Change day number color on click - not background


问:
Docker Rails Tutorial generated files not exists
I am trying basic Docker & Rails tutorials on my windows10 home OS with Docker toolbox.

```<code>Client: 17.05.0-ce
Server: 17.06.0-ce
</code>```

And hello-world tutorials works!

Now I am trying this youtube tutorial: https://www.youtube.com/watch?v=KH6pcHb6Wug&lc=z12ocxayznynslzjj04chbtgiwbhuf4z5xk0k.1499518307572479

And everything looks okay until I check rails generated project files.
In terminal showing like files are generating but when I use the command 'ls -l' its show only my manually created files (4).

What's happening with Rails generated files?
Where they go?

Here is docker-compose.yml content:

```<code>version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/deep
    ports:
      - "3000:3000"
    depends_on:
      - db
</code>```

Here is Dockerfile content:

```<code>FROM ruby:2.3.3

ENV HOME /home/rails/deep

# Install PGsql dependencies and js engine
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR $HOME

# Install gems
ADD Gemfile* $HOME/
RUN bundle install

# Add the app code
ADD . $HOME
</code>```

Here is my terminal at end: https://ibb.co/c2eqFF

I found the solution:
https://github.com/laradock/laradock/issues/508

Just need to place a .env file next to your docker-compose.yml file, with the following content : COMPOSE_CONVERT_WINDOWS_PATHS=1

Body:
I am trying basic Docker & Rails tutorials on my windows10 home OS with Docker toolbox.

Client: 17.05.0-ce
Server: 17.06.0-ce

And hello-world tutorials works!

Now I am trying this youtube tutorial: https://www.youtube.com/watch?v=KH6pcHb6Wug&lc=z12ocxayznynslzjj04chbtgiwbhuf4z5xk0k.1499518307572479

And everything looks okay until I check rails generated project files.
In terminal showing like files are generating but when I use the command 'ls -l' its show only my manually created files (4).

What's happening with Rails generated files?
Where they go?

Here is docker-compose.yml content:

version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/deep
    ports:
      - "3000:3000"
    depends_on:
      - db

Here is Dockerfile content:

FROM ruby:2.3.3

ENV HOME /home/rails/deep

# Install PGsql dependencies and js engine
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR $HOME

# Install gems
ADD Gemfile* $HOME/
RUN bundle install

# Add the app code
ADD . $HOME

Here is my terminal at end: https://ibb.co/c2eqFF

I found the solution:
https://github.com/laradock/laradock/issues/508

Just need to place a .env file next to your docker-compose.yml file, with the following content : COMPOSE_CONVERT_WINDOWS_PATHS=1


问:
LINQ to SQL using GROUP BY and COUNT(DISTINCT)
I have to perform the following SQL query:

```<code>select answer_nbr, count(distinct user_nbr)
from tpoll_answer
where poll_nbr = 16
group by answer_nbr
</code>```

The LINQ to SQL query

```<code>from a in tpoll_answer
where a.poll_nbr = 16 select a.answer_nbr, a.user_nbr distinct
</code>```

maps to the following SQL query:

```<code>select distinct answer_nbr, distinct user_nbr
from tpoll_answer
where poll_nbr = 16
</code>```

So far, so good. However the problem raises when trying to GROUP the results, as I'm not being able to find a LINQ to SQL query that maps to the first query I wrote here (thank you LINQPad for making this process a lot easier). The following is the only one that I've found that gives me the desired result:

```<code>from answer in tpoll_answer where answer.poll_nbr = 16 _
group by a_id = answer.answer_nbr into votes = count(answer.user_nbr)
</code>```

Which in turns produces the follwing ugly and non-optimized at all SQL query:

```<code>SELECT [t1].[answer_nbr] AS [a_id], (
    SELECT COUNT(*)
    FROM (
        SELECT CONVERT(Bit,[t2].[user_nbr]) AS [value], [t2].[answer_nbr], [t2].[poll_nbr]
        FROM [TPOLL_ANSWER] AS [t2]
        ) AS [t3]
    WHERE ([t3].[value] = 1) AND ([t1].[answer_nbr] = [t3].[answer_nbr]) AND ([t3].[poll_nbr] = @p0)
    ) AS [votes]
FROM (
    SELECT [t0].[answer_nbr]
    FROM [TPOLL_ANSWER] AS [t0]
    WHERE [t0].[poll_nbr] = @p0
    GROUP BY [t0].[answer_nbr]
    ) AS [t1]
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [16]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
</code>```

Any help will be more than appreciated.

答:
This is how you do a distinct count query.  Note that you have to filter out the nulls.

```<code>var useranswercount = (from a in tpoll_answer
where user_nbr != null && answer_nbr != null
select user_nbr).Distinct().Count();
</code>```

If you combine this with into your current grouping code, I think you'll have your solution.

OwnerDisplayName: Leandro López

Body:
I have to perform the following SQL query:

select answer_nbr, count(distinct user_nbr)
from tpoll_answer
where poll_nbr = 16
group by answer_nbr

The LINQ to SQL query

from a in tpoll_answer
where a.poll_nbr = 16 select a.answer_nbr, a.user_nbr distinct

maps to the following SQL query:

select distinct answer_nbr, distinct user_nbr
from tpoll_answer
where poll_nbr = 16

So far, so good. However the problem raises when trying to GROUP the results, as I'm not being able to find a LINQ to SQL query that maps to the first query I wrote here (thank you LINQPad for making this process a lot easier). The following is the only one that I've found that gives me the desired result:

from answer in tpoll_answer where answer.poll_nbr = 16 _
group by a_id = answer.answer_nbr into votes = count(answer.user_nbr)

Which in turns produces the follwing ugly and non-optimized at all SQL query:

SELECT [t1].[answer_nbr] AS [a_id], (
    SELECT COUNT(*)
    FROM (
        SELECT CONVERT(Bit,[t2].[user_nbr]) AS [value], [t2].[answer_nbr], [t2].[poll_nbr]
        FROM [TPOLL_ANSWER] AS [t2]
        ) AS [t3]
    WHERE ([t3].[value] = 1) AND ([t1].[answer_nbr] = [t3].[answer_nbr]) AND ([t3].[poll_nbr] = @p0)
    ) AS [votes]
FROM (
    SELECT [t0].[answer_nbr]
    FROM [TPOLL_ANSWER] AS [t0]
    WHERE [t0].[poll_nbr] = @p0
    GROUP BY [t0].[answer_nbr]
    ) AS [t1]
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [16]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

Any help will be more than appreciated.

Body:
This is how you do a distinct count query.  Note that you have to filter out the nulls.

var useranswercount = (from a in tpoll_answer
where user_nbr != null && answer_nbr != null
select user_nbr).Distinct().Count();

If you combine this with into your current grouping code, I think you'll have your solution.

OwnerDisplayName: GeekyMonkey


问:
Using MacRuby to Test iPhone Application?
I have an existing iPhone app, written in Objective-C, that I'd like to add some automated tests to. I've read this article about testing with MacRuby, which sounds great but it's aimed at testing desktop frameworks.

How can I add MacRuby tests to my iPhone app? The Ruby code doesn't recognize my Objective-C classes, and I don't know how to set it up to do that. Do I need to somehow point it at the compiled code or the headers?

答: MacRuby doesn't run on iOS, nor do I see that happening any time soon. I have been working on a port of Bacon (a Ruby rspec clone) to the Nu language: https://github.com/alloy/NuBacon. I still have to do some cleaning and write a blog post about it, I'll see if I can spare some time today to do so.</p>


问:
How can I remove from string the four first characters? iMacros
How can I remove from string the four first characters with iMacros.
I know it something with EVAL function but don't know how to write it.
TY</p>

答:
I know nothing of iMacros, but a quick look at the docs suggests

```<code>SET !SHORTENEDSTRING = EVAL("\"{{!EXTRACT}}\".substr(4)")
</code>```

The \" escapes the double-quote characters inside the string. {{!EXTRACT}} is for what was extracted by a previous iMacros statement. The .substr(4) is a JavaScript function: MDN substr documentation, and remember that it uses a zero-based index.

Body:
I know nothing of iMacros, but a quick look at the docs suggests

SET !SHORTENEDSTRING = EVAL("\"{{!EXTRACT}}\".substr(4)")

The \" escapes the double-quote characters inside the string. {{!EXTRACT}} is for what was extracted by a previous iMacros statement. The .substr(4) is a JavaScript function: MDN substr documentation, and remember that it uses a zero-based index.


问:
Can't locate XML/Writer.pm in @INC
can someone help me to exclude below the error.

Thanks in advance

Can't locate XML/Writer.pm in @INC (@INC contains: /home/svceln/usr/lib/perl5/site_perl/5.16.2/x86_64-linux /home/svceln/usr/lib/perl5/site_perl/5.16.2 /home/svceln/usr/lib/perl5/5.16.2/x86_64-linux /home/svceln/usr/lib/perl5/5.16.2 .) at /opt/apps/tomcat_scripts/allocate_ports.pl line 7.
BEGIN failed--compilation aborted at /opt/apps/tomcat_scripts/allocate_ports.pl line 7.
Error in allocating ports, server.xml cannot run`

The script i am using

```<code>#!/home/svceln/usr/bin/perl -w
# allocate_ports.pl

# allocate ports, create port_config.xml and write to stdout

use strict;
use XML::Writer;
use IO::File;enter code here
use File::Basename;

my ($increment) = 0;
my ($execDir) = dirname($0);

$#ARGV eq 0 or die "Usage: allocate_ports.pl server_name\n";

my ($port_read) = new IO::File ("$execDir/port_increment.txt");
if (defined $port_read) {
  while (<$port_read>) {
    chomp;
    $increment = $_;
  }
  $port_read->close() or die "Can't close port_increment.txt: $!";
} else {
  $increment = 0;
}
</code>```

答:
It might be in a package, say libxml-writer-perl, assuming Debian.

apt-cache search XML::Writer gives a list of packages if your system uses apt.

Depends on how you are getting your perl modules.

Title: Can't locate XML/Writer.pm in @INC

Body:
can someone help me to exclude below the error.

Thanks in advance

Can't locate XML/Writer.pm in @INC (@INC contains: /home/svceln/usr/lib/perl5/site_perl/5.16.2/x86_64-linux /home/svceln/usr/lib/perl5/site_perl/5.16.2 /home/svceln/usr/lib/perl5/5.16.2/x86_64-linux /home/svceln/usr/lib/perl5/5.16.2 .) at /opt/apps/tomcat_scripts/allocate_ports.pl line 7.
BEGIN failed--compilation aborted at /opt/apps/tomcat_scripts/allocate_ports.pl line 7.
Error in allocating ports, server.xml cannot run`

The script i am using

#!/home/svceln/usr/bin/perl -w
# allocate_ports.pl

# allocate ports, create port_config.xml and write to stdout

use strict;
use XML::Writer;
use IO::File;enter code here
use File::Basename;

my ($increment) = 0;
my ($execDir) = dirname($0);

$#ARGV eq 0 or die "Usage: allocate_ports.pl server_name\n";

my ($port_read) = new IO::File ("$execDir/port_increment.txt");
if (defined $port_read) {
  while (<$port_read>) {
    chomp;
    $increment = $_;
  }
  $port_read->close() or die "Can't close port_increment.txt: $!";
} else {
  $increment = 0;
}


答:
Using Python 3, use the urllib module, then trim out the parts you don't want from the resulting "path" you want:

```<code>>>> from urllib.parse import urlparse
>>> url_str = "http://localhost:8080/course-single.html"
>>> urlparse(url_str).path.split('.')[0][1:]
'course-single'
</code>```

Details:

urlparse(url_str) will yield:

```<code>ParseResult(
    scheme='http', netloc='localhost:8080', path='/course-single.html',
    params='', query='', fragment=''
)
</code>```

So, you extract the path:

urlparse(url_str).path: to get: '/course-single.html'

Then you need to remove the parts you are not interested in, so split on the ., which will give you ['/course-single', 'html']. So, just access the first item ([0]), remove the first slash with [1:] slice and that gives you your final result of course-single.

Multiple slashes

If you have a longer url, and you need that last part, then you can do the following, and it should work for whatever length url you provide:

```<code>>>> url_str = "http://localhost:8080/a/b/c/course-single.html"
>>> urlparse(url_str)
ParseResult(scheme='http', netloc='localhost:8080', path='/a/b/c/course-single.html', params='', query='', fragment='')
>>> urlparse(url_str).path.rsplit('/', 1)[-1].split('.')[0]
'course-single'
</code>```

Title: How to extract string after some character

Body:
Using Python 3, use the urllib module, then trim out the parts you don't want from the resulting "path" you want:

>>> from urllib.parse import urlparse
>>> url_str = "http://localhost:8080/course-single.html"
>>> urlparse(url_str).path.split('.')[0][1:]
'course-single'

Details:

urlparse(url_str) will yield:

ParseResult(
    scheme='http', netloc='localhost:8080', path='/course-single.html',
    params='', query='', fragment=''
)

So, you extract the path:

urlparse(url_str).path: to get: '/course-single.html'

Then you need to remove the parts you are not interested in, so split on the ., which will give you ['/course-single', 'html']. So, just access the first item ([0]), remove the first slash with [1:] slice and that gives you your final result of course-single.

Multiple slashes

If you have a longer url, and you need that last part, then you can do the following, and it should work for whatever length url you provide:

>>> url_str = "http://localhost:8080/a/b/c/course-single.html"
>>> urlparse(url_str)
ParseResult(scheme='http', netloc='localhost:8080', path='/a/b/c/course-single.html', params='', query='', fragment='')
>>> urlparse(url_str).path.rsplit('/', 1)[-1].split('.')[0]
'course-single'


问:
Is the viewport meta tag supported by the Amazon Silk browser on Kindle Fire?
I'm trying to use the viewport meta tag to scale HTML content when viewed on the Kindle Fire.

I have set up the following test page:

```<code><!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="initial-scale=2.5, maximum-scale=2.5, minimum-scale=2.5, width=device-width, user-scalable=no" />
</head>
<body>
  <div style="width: 100px; height: 100px; background: red;">Hello World</div>
</body>
</html>
</code>```

If I change the number from 2.5 to say 1.0 for example, this causes the content to be scaled down on the iPhone 4S. However, it appears to have no effect on the size of the content when viewed in the Amazon Silk browser on Kindle Fire.

Has anyone else experienced this? Is there a problem in my markup that could cause this?

Note:  I have tried changing the 'Desktop or mobile view' browser setting to Automatic, Mobile and Desktop - none of these settings changed anything about the appearance of the page.

答:
It is supported:

Keep in mind the following when developing web content for Silk and Fire devices:

• The viewport is the portion of the browser dedicated to displaying the webpage. Viewport size and
screen size for mobile devices are not necessarily identical. They differ because the browser uses up
some screen real estate to show its chrome. You can use the viewport meta element (p. 36) to
specify attributes of the viewport, including width and height.

Test each property by itself to determine specific support for each option:

width

height

initial-scale

minimum-scale

maximum-scale

user-scalable

References

Amazon Silk Developer Guide: CSS3 Support - viewport meta element (pdf)

Screen Resolution - Amazon Silk

Dev.Opera — An Introduction to Meta Viewport and @viewport

CSS Device Adaptation Module Level 1: Properties

Evidence Versus Proof

The 4 Types of Evidence ~ Writing Simplified

Body:
I'm trying to use the viewport meta tag to scale HTML content when viewed on the Kindle Fire.

I have set up the following test page:

<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=2.5, maximum-scale=2.5, minimum-scale=2.5, width=device-width, user-scalable=no" />

Hello World

If I change the number from 2.5 to say 1.0 for example, this causes the content to be scaled down on the iPhone 4S. However, it appears to have no effect on the size of the content when viewed in the Amazon Silk browser on Kindle Fire.

Has anyone else experienced this? Is there a problem in my markup that could cause this?

Note:  I have tried changing the 'Desktop or mobile view' browser setting to Automatic, Mobile and Desktop - none of these settings changed anything about the appearance of the page.


问:
Meteor react on Gcloud
I am trying to deploy my Meteor React app on Google's cloud but when I try deploying it, I get the error saying that MONGO_URL needs to be specified. I build my meteor app and cd to my bundle folder where I do gcloud app deploy. Here is my package.json

```<code>{
    "private": true,
    "scripts": {
        "start": "node main.js",
        "install": "(cd programs/server && npm install)"
    },
    "engines": {
        "node": "6.6.0"
    }
}
</code>```

How can I find out my meteor mongo username and password. Running regular meteor did not ask me for my username and password. And here is my app.yaml

```<code>runtime: nodejs
env: flex
threadsafe: true
automatic_scaling:
    max_num_instances: 1
env_variables:
    MONGO_URL: 'mongodb://[user]:[pass]@[host]:[port]/[db]'
    ROOT_URL: 'https://...'
    METEOR_SETTINGS: '{}'
</code>```

I don't know what to put for MONGO_URL and ROOT_URL if I am deploying on gcloud. Also I have settings file for my project. Should it go under METER_SETTINGS in app.yaml?  I apologize for asking too many question but this is my first time dealing with gcloud :)

答:
This question is a little old, but it's still getting some views from Google so let's answer by parts, first you need to understand how Meteor interacts with MongoDB in development and production. When you're coding your app, just executing meteor run does all the magic, because Meteor deploys an internal MongoDB. This is not recommended for real production usage and won't work well under any container based architecture (such as Docker, Google App Engine, Heroku etc.).

Given that, you'll need to deploy a separate instance in Google Compute Engine based on MongoDB. Google has them ready to launch in the Google Cloud Launcher, just search for "MongoDB".

I recommend the Bitnami's one, which is easier to configure if you're just beginning.

Google will create an instance automatically and you'll be given a root username and password, alongside a public IP address to connect to the instance.

Run the command below to access Mongo from a terminal:

```<code># Use this template for the command
mongo "mongodb://root:PASSWORD@IP_ADDRESS/" --authenticationDatabase admin

# For example, with sample values
mongo "mongodb://root:8sdjkfh8876@127.0.0.1/" --authenticationDatabase admin
</code>```

Now, create a new user for Meteor to connect on your newly created database. Never give it the root credentials, it won't work and it's not safe. For example, naming the database as myapp.

```<code>use myapp;
db.createUser({
  user: "meteor_app",
  pwd: "A_SECURE_PASSWORD",
  roles: [ "readWrite", "dbAdmin" ]
})
</code>```

Now, you exit this connection and test your new user.

```<code>mongo "mongodb://meteor_app:A_SECURE_PASSWORD@IP_ADDRESS/myapp"
</code>```

If everything is OK, you now have your MONGO_URL.

```<code># Put this in the app.yaml file, env variables sections
MONGO_URL: "mongodb://meteor_app:A_SECURE_PASSWORD@IP_ADDRESS/myapp"
</code>```

Title: Meteor react on Gcloud

Body:
I am trying to deploy my Meteor React app on Google's cloud but when I try deploying it, I get the error saying that MONGO_URL needs to be specified. I build my meteor app and cd to my bundle folder where I do gcloud app deploy. Here is my package.json

{
    "private": true,
    "scripts": {
        "start": "node main.js",
        "install": "(cd programs/server && npm install)"
    },
    "engines": {
        "node": "6.6.0"
    }
}

How can I find out my meteor mongo username and password. Running regular meteor did not ask me for my username and password. And here is my app.yaml

runtime: nodejs
env: flex
threadsafe: true
automatic_scaling:
    max_num_instances: 1
env_variables:
    MONGO_URL: 'mongodb://[user]:[pass]@[host]:[port]/[db]'
    ROOT_URL: 'https://...'
    METEOR_SETTINGS: '{}'

I don't know what to put for MONGO_URL and ROOT_URL if I am deploying on gcloud. Also I have settings file for my project. Should it go under METER_SETTINGS in app.yaml?  I apologize for asking too many question but this is my first time dealing with gcloud :)

Body:
This question is a little old, but it's still getting some views from Google so let's answer by parts, first you need to understand how Meteor interacts with MongoDB in development and production. When you're coding your app, just executing meteor run does all the magic, because Meteor deploys an internal MongoDB. This is not recommended for real production usage and won't work well under any container based architecture (such as Docker, Google App Engine, Heroku etc.).

Given that, you'll need to deploy a separate instance in Google Compute Engine based on MongoDB. Google has them ready to launch in the Google Cloud Launcher, just search for "MongoDB".

I recommend the Bitnami's one, which is easier to configure if you're just beginning.

Google will create an instance automatically and you'll be given a root username and password, alongside a public IP address to connect to the instance.

Run the command below to access Mongo from a terminal:

# Use this template for the command
mongo "mongodb://root:PASSWORD@IP_ADDRESS/" --authenticationDatabase admin

# For example, with sample values
mongo "mongodb://root:8sdjkfh8876@127.0.0.1/" --authenticationDatabase admin

Now, create a new user for Meteor to connect on your newly created database. Never give it the root credentials, it won't work and it's not safe. For example, naming the database as myapp.

use myapp;
db.createUser({
  user: "meteor_app",
  pwd: "A_SECURE_PASSWORD",
  roles: [ "readWrite", "dbAdmin" ]
})

Now, you exit this connection and test your new user.

mongo "mongodb://meteor_app:A_SECURE_PASSWORD@IP_ADDRESS/myapp"

If everything is OK, you now have your MONGO_URL.

# Put this in the app.yaml file, env variables sections
MONGO_URL: "mongodb://meteor_app:A_SECURE_PASSWORD@IP_ADDRESS/myapp"


问:
subprocess "TypeError: a bytes-like object is required, not 'str'"
I'm using this code from a previously asked question a few years ago, however, I believe this is outdated. Trying to run the code, I receive the error above. I'm still a novice in Python, so I could not get much clarification from similar questions. Does anyone know why this is happening?

```<code>import subprocess

def getLength(filename):
  result = subprocess.Popen(["ffprobe", filename],
    stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  return [x for x in result.stdout.readlines() if "Duration" in x]

print(getLength('bell.mp4'))
</code>```

Traceback

```<code>Traceback (most recent call last):
  File "B:\Program Files\ffmpeg\bin\test3.py", line 7, in <module>
    print(getLength('bell.mp4'))
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in getLength
    return [x for x in result.stdout.readlines() if "Duration" in x]
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in <listcomp>
    return [x for x in result.stdout.readlines() if "Duration" in x]
TypeError: a bytes-like object is required, not 'str'
</code>```

答:
Like the errror says, "Duration" is a string. Whereas, the X is a byte like object as results.stdout.readlines() reads the lines in the output as bytecode and not string.

Hence store "Duration" in a variable, say str_var and encode it into a byte array object using str_var.encode('utf-8').

Refer to [this][1].

[1] : Best way to convert string to bytes in Python 3?

Body:
I'm using this code from a previously asked question a few years ago, however, I believe this is outdated. Trying to run the code, I receive the error above. I'm still a novice in Python, so I could not get much clarification from similar questions. Does anyone know why this is happening?

import subprocess

def getLength(filename):
  result = subprocess.Popen(["ffprobe", filename],
    stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  return [x for x in result.stdout.readlines() if "Duration" in x]

print(getLength('bell.mp4'))

Traceback

Traceback (most recent call last):
  File "B:\Program Files\ffmpeg\bin\test3.py", line 7, in <module>
    print(getLength('bell.mp4'))
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in getLength
    return [x for x in result.stdout.readlines() if "Duration" in x]
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in <listcomp>
    return [x for x in result.stdout.readlines() if "Duration" in x]
TypeError: a bytes-like object is required, not 'str'


问:
Why do I need a different syntax when testing for an exception with Jasmine?
I'm new to Jasmine, so apologies if this is a dumb question.

I have a test like this...

```<code>it("should calculate factorial 5", function() {
  expect(MathsUtils.fact(5)).toBe(120);
});
</code>```

This works fine. My fact function throws an exception if you pass it a negative number, so I tried to test that with the following...

```<code>it("should throw an exception when passed -1", function() {
  expect(MathsUtils.fact(-1)).toThrow("n! does not exist for negative numbers");
});
</code>```

However, this failed. After some searching, I discovered that if I change this test to look like this...

```<code>it("should throw an exception when passed -1", function() {
  expect(function() { MathsUtils.fact(-1); }).toThrow("n! does not exist for negative numbers");
});
</code>```

...it passes. However, if I change my first test in a similar manner...

```<code>it("should calculate factorial 5", function() {
  expect(function() { MathsUtils.fact(5); }).toBe(120);
});
</code>```

...it fails.

Why do I need a different syntax for the two tests? Neither seems to work for the other.

As I said, I'm new with Jasmine, so if this is covered in the docs, please point me in the right direction, as I couldn't see any explanation.

答:
This is an addendum to the comments in Soren's answer.

expect is doing the execution and can catch the exception as what is passed is a function pointer and not an already evaluated value

Take a look under the hood of Jasmine 2.6:

When you call the expect() method several things happen ...

Create the Expectation which is defined here

The "toThrow" matcher defines a compare() method which is mixed into the Expectation object.

tl;dr:

In toThrow() the actual value, along with the expected value, was passed by the compare() call. The value is evaluated as function call within a try/catch block.

```<code>function toThrow(util) {
  return {
    compare: function(actual, expected) {
      var result = { pass: false },
        threw = false,
        thrown;

      if (typeof actual != 'function') {
        throw new Error(getErrorMsg('Actual is not a Function'));
      }

      try {
        actual();
      } catch (e) {
        threw = true;
        thrown = e;
      }

      if (!threw) {
        result.message = 'Expected function to throw an exception.';
        return result;
      }

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

Why do I need a different syntax for the two tests? Neither seems to work for the other.

After reading toThrow() this should be clearer.

While a primitive type like a number or a string passed to, say, the toBe() matcher can be evaluated immediately, the "value" of an exception (that are the threw and thrown variables up there) is created when thrown and when not thrown. Thus the macher should hold the control of the execution.

Note that

```<code>it("should throw", function() {
    expect(someFunction()).toThrow("meh");
});
</code>```

will semi-work since someFunction() may throw and the suite will catch that exception and report a spec failure when the closure passed to it() is being executed.

But since in this case neither expect() nor toThrow() are called, it's not able to check for the message nor the type (like toThrowError() does). It's only able to detect that the spec failed.

This small example which can run in NodeJS or a browser console should make it even clearer ...

You can also make your own expectation function:

```<code>// Expectation constructor
function Expectation(actual, reporter) {
    this.actual = actual;
    this.reporter = reporter;
}

// matcher "mixed in"
Expectation.prototype.toThrow = function(expected) {
    try {
        this.actual();

        // No exception thrown, this state is wrong
        this.reporter(false, "Expected " + this.actual.name + " to throw but it did not throw");
    } catch(e) {
        // This exception was expected, this state is correct

        if (e.message !== expected) {
            // But the message was wrong

            this.reporter(false, "Expected " + this.actual.name + " to throw " + expected + " but it threw " + e.message);
        } else {
            // And its message was correct

            this.reporter(true);
        }
    }
};

// Helper to report (log)
function report(passed, msg) {
    if (!passed) {
        console.error(msg);
    } else {
        console.log("passed");
    }
}

// Helper to create expectation
function expect(actual) {
    return new Expectation(actual, report);
}

> function correctError() { throw new Error("meh!"); }
> expect(correctError).toThrow("meh!");
< passed

> function badMessageError() { throw new Error("hehe"); }
> expect(badMessageError).toThrow("meh!");
< Expected badMessageError to throw meh! but it threw hehe

> function noError() { /* no action */ }
> expect(noError).toThrow("meh!");
< Expected noError to throw but it did not throw
</code>```

Per your comment

[...] I'm a C# programmer by day, [...]

there's a nice C# answer to a similar question that implements the same behaviour like Jasmine.

Body:
I'm new to Jasmine, so apologies if this is a dumb question.

I have a test like this...

it("should calculate factorial 5", function() {
  expect(MathsUtils.fact(5)).toBe(120);
});

This works fine. My fact function throws an exception if you pass it a negative number, so I tried to test that with the following...

it("should throw an exception when passed -1", function() {
  expect(MathsUtils.fact(-1)).toThrow("n! does not exist for negative numbers");
});

However, this failed. After some searching, I discovered that if I change this test to look like this...

it("should throw an exception when passed -1", function() {
  expect(function() { MathsUtils.fact(-1); }).toThrow("n! does not exist for negative numbers");
});

...it passes. However, if I change my first test in a similar manner...

it("should calculate factorial 5", function() {
  expect(function() { MathsUtils.fact(5); }).toBe(120);
});

...it fails.

Why do I need a different syntax for the two tests? Neither seems to work for the other.

As I said, I'm new with Jasmine, so if this is covered in the docs, please point me in the right direction, as I couldn't see any explanation.

Body:
This is an addendum to the comments in Soren's answer.

expect is doing the execution and can catch the exception as what is passed is a function pointer and not an already evaluated value

Take a look under the hood of Jasmine 2.6:

When you call the expect() method several things happen ...

Create the Expectation which is defined here

The "toThrow" matcher defines a compare() method which is mixed into the Expectation object.

tl;dr:

In toThrow() the actual value, along with the expected value, was passed by the compare() call. The value is evaluated as function call within a try/catch block.

function toThrow(util) {
  return {
    compare: function(actual, expected) {
      var result = { pass: false },
        threw = false,
        thrown;

      if (typeof actual != 'function') {
        throw new Error(getErrorMsg('Actual is not a Function'));
      }

      try {
        actual();
      } catch (e) {
        threw = true;
        thrown = e;
      }

      if (!threw) {
        result.message = 'Expected function to throw an exception.';
        return result;
      }

      // ...
    }
  }
}

Why do I need a different syntax for the two tests? Neither seems to work for the other.

After reading toThrow() this should be clearer.

While a primitive type like a number or a string passed to, say, the toBe() matcher can be evaluated immediately, the "value" of an exception (that are the threw and thrown variables up there) is created when thrown and when not thrown. Thus the macher should hold the control of the execution.

Note that

it("should throw", function() {
    expect(someFunction()).toThrow("meh");
});

will semi-work since someFunction() may throw and the suite will catch that exception and report a spec failure when the closure passed to it() is being executed.

But since in this case neither expect() nor toThrow() are called, it's not able to check for the message nor the type (like toThrowError() does). It's only able to detect that the spec failed.

This small example which can run in NodeJS or a browser console should make it even clearer ...

You can also make your own expectation function:

// Expectation constructor
function Expectation(actual, reporter) {
    this.actual = actual;
    this.reporter = reporter;
}

// matcher "mixed in"
Expectation.prototype.toThrow = function(expected) {
    try {
        this.actual();

        // No exception thrown, this state is wrong
        this.reporter(false, "Expected " + this.actual.name + " to throw but it did not throw");
    } catch(e) {
        // This exception was expected, this state is correct

        if (e.message !== expected) {
            // But the message was wrong

            this.reporter(false, "Expected " + this.actual.name + " to throw " + expected + " but it threw " + e.message);
        } else {
            // And its message was correct

            this.reporter(true);
        }
    }
};

// Helper to report (log)
function report(passed, msg) {
    if (!passed) {
        console.error(msg);
    } else {
        console.log("passed");
    }
}

// Helper to create expectation
function expect(actual) {
    return new Expectation(actual, report);
}

> function correctError() { throw new Error("meh!"); }
> expect(correctError).toThrow("meh!");
< passed

> function badMessageError() { throw new Error("hehe"); }
> expect(badMessageError).toThrow("meh!");
< Expected badMessageError to throw meh! but it threw hehe

> function noError() { /* no action */ }
> expect(noError).toThrow("meh!");
< Expected noError to throw but it did not throw

Per your comment

[...] I'm a C# programmer by day, [...]

there's a nice C# answer to a similar question that implements the same behaviour like Jasmine.


问:
change Geom_smooth default legend color
I am using geom_smooth and it gives me default legend line color blue that I cannot use in the plot. Is there a way of changing the default color for geom_smooth legend line?

for example, I wand to change the legend colour to black for line type in the following plot

```<code>      library(reshape2)
    library(ggplot2)
d1<-melt(mtcars,id=c("mpg","cyl"))
        p<-ggplot(d1,aes(x=mpg,y=value,factor=variable,color=cyl))
        p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5,  inherit.aes = T)+
          scale_linetype_manual("line type",labels = rp, values=c(1,5,4,3))
</code>```

答:
if you add + guides(linetype = guide_legend(override.aes= list(color = "black"))) to your last plot do

This solves thanks @Mike

Title: change Geom_smooth default legend color

Body:
I am using geom_smooth and it gives me default legend line color blue that I cannot use in the plot. Is there a way of changing the default color for geom_smooth legend line?

for example, I wand to change the legend colour to black for line type in the following plot

      library(reshape2)
    library(ggplot2)
d1<-melt(mtcars,id=c("mpg","cyl"))
        p<-ggplot(d1,aes(x=mpg,y=value,factor=variable,color=cyl))
        p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5,  inherit.aes = T)+
          scale_linetype_manual("line type",labels = rp, values=c(1,5,4,3))


问:
Android Studio device preview without device frame has gone
I got the design file from GoogleCloudPlatform/appengine-endpoints-helloendpoints-android project and made small changes. I changed the theme to a dark one. I don't know how this happened but I don't see the device controls or border/frame anymore. How can I reset it? Other design files are showing alright.

Finally found the reason. When I clicked on the black outer region of the preview window, a toolbar appears above it. First button on the left is called Toggle Viewport Render Mode. This brought back my device view.

答: Click on preview window and press button 'F' on keyboard.</p>