答:
As @horcrux proposed i used the regex:

```<code>(\[\n.+\n.+\n\],\n)(\[\n.+\n.+\n\],\n){10}
</code>```

And replaced by

```<code>$1
</code>```

Title: How can i match 1 every 10 results using regex?

Body:
I have the following regex:

(^\[\s?.{1,15}\s?.{1,15}\s?\]\,$)

On my test file, i got 35k matches. I want to make a interval between the matches. In another words, "match" 1 every 10 matches.

Example:

[-51.039,-19.777], (match)
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777],
[-51.039,-19.777], (match)

Body:
As @horcrux proposed i used the regex:

(\[\n.+\n.+\n\],\n)(\[\n.+\n.+\n\],\n){10}

And replaced by

$1


来源: stackexchange

问:
geom_path with discrete boxplot data
Finally run out of ideas and links I could find to try and explain this so I need some help!

I'm trying to add a step-function to a ggplot chart using the cumSeg package. I did this successfully in this previous question, so I'm used to the usage of the function etc.

When I made the plot in that thread, it was fairly simple, just using an x vs y barplot for the mean values of x, and I added on error bars myself afterwards (thus it was a 16 x 2 dataframe).

I want to re-create this plot, but using sequential boxplots instead of bars, which I have done, using the raw data this time, which is ~250 observations in 16 factors (same factors as before).

Now when I try to add a geom_line,path or step it's complaining about the dimensions of the data not matching, because even though there are 16 factors/boxplots, there are now no longer 16 observations (Error: Aesthetics must be either length 1 or the same as the data (249): x, y, colour, group, fill)

To calculate the step function, I give it the means of each of the 16, which returns a 16-member vector, not ~250 (obviously).

How can I add the step function on to the box plot so that it understands it should pertain to the 16 factor values? I can't work out if it's a problem with the dataframe or how I'm giving it to ggplot.

I tried specifying it in a second dataframe, and passing it as geom_path(data=df2) instead of inheriting the main plots data, as in this question, but it still complains (Error: Aesthetics must be either length 1 or the same as the data (16): x, y, colour, group (the code below is in this form still)

```<code>data.melt <- melt(t(infile)

operon_gc <- 0.408891366
opgc_stdev <- 0.015712091
genome_gc <- 0.425031611
gengc_stdev <- 0.007587437

stepfunc <- jumpoints(y=aggregate(melted_data$value~melted_data$Var1, simplify=TRUE, FUN="mean")$`melted_data$value`, k=1, output="1")
func_data <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16), y = stepfunc$fitted.values)

# Make boxplot

bp <- ggplot(melted_data, aes(x=Var1, y=value*100, fill=Var1)) + theme_bw()

#bp <- bp + scale_x_discrete(name = "Locus") + scale_y_continuous(name="GC Content (%)")
bp <- bp + geom_rect(xmin=0, xmax=17,
                                 ymin=(operon_gc-opgc_stdev)*100,
                                 ymax=(operon_gc+opgc_stdev)*100,
                                 fill = "grey79", alpha=0.05)
bp <- bp + geom_rect(xmin=0, xmax=17,
                                 ymin=(genome_gc-gengc_stdev)*100,
                                 ymax=(genome_gc+gengc_stdev)*100,
                                 fill = "beige", alpha=.08)
bp <- bp + geom_abline(intercept=genome_gc*100, slope=0,
                                   colour="gray14", linetype=3)
bp <- bp + geom_abline(intercept=operon_gc*100, slope=0,
                                   colour="gray14", linetype=3)

bp <- bp + geom_boxplot(alpha = 0.7)

bp <- bp + scale_color_manual(values = c("GC Step Fit"="red"), guides(color="Regression"))

bp <- bp + geom_path(linetype=4, size=0.9, aes(x=func_data$x,
                                               y=func_data$y,
                                               color="GC Step Fit",
                                               group=1))
bp <- bp + theme(legend.position="bottom",
                 legend.direction="horizontal",
                 axis.text.x = element_text(angle=45, hjust=1)) + guides(fill=guide_legend(title="", nrow = 1))

bp
</code>```

Data

```<code>> dput(func_data)
structure(list(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16), y = c(0.452456815737206, 0.452456815737206, 0.452456815737206,
0.452456815737206, 0.452456815737206, 0.452456815737206, 0.452456815737206,
0.452456815737206, 0.452456815737206, 0.452456815737206, 0.452456815737206,
0.375047391939972, 0.375047391939972, 0.375047391939972, 0.375047391939972,
0.375047391939972)), .Names = c("x", "y"), row.names = c(NA,
-16L), class = "data.frame")

> dput(melted_data)
structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L,
16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L,
16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 14L, 15L, 16L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 15L, 16L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 15L, 16L, 11L), .Label = c("PVC1", "PVC2", "PVC3", "PVC4",
"PVC5", "PVC6", "PVC7", "PVC8", "PVC9", "PVC10", "PVC11", "PVC12",
"PVC13", "PVC14", "PVC15", "PVC16"), class = "factor"), Var2 = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 14L, 14L,
14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 15L,
15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 16L,
16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 17L
), value = c(0.404444444, 0.436329588, 0.46031746, 0.479318735,
0.466230937, 0.480874317, 0.476811594, 0.441558442, 0.449172577,
0.476525822, 0.452674897, 0.460918332, 0.368041912, 0.339160839,
0.415355269, 0.408163265, 0.401826484, 0.45411985, 0.468609865,
0.479735318, 0.464052288, 0.469945355, 0.476811594, 0.444032158,
0.453900709, 0.494004796, 0.467315716, 0.457805907, 0.387071651,
0.390737117, 0.408679065, 0.425170068, 0.355555556, 0.438069217,
0.423076923, 0.466666667, 0.450980392, 0.422222222, 0.469298246,
0.43196005, 0.416666667, 0.496402878, 0.428676201, 0.382113821,
0.349765258, 0.332280147, 0.373371925, 0.346448087, 0.415555556,
0.440508629, 0.435222672, 0.455833333, 0.446623094, 0.422222222,
0.463450292, 0.43258427, 0.425675676, 0.497584541, 0.422524565,
0.392592593, 0.362779741, 0.337552743, 0.379856115, 0.348888889,
0.391111111, 0.421004566, 0.426439232, 0.480367586, 0.472766885,
0.455555556, 0.495726496, 0.447565543, 0.424460432, 0.48441247,
0.435164835, 0.39600551, 0.3858393, 0.323655914, 0.383693046,
0.329988852, 0.395555556, 0.452380952, 0.454756381, 0.448129252,
0.496732026, 0.423728814, 0.502923977, 0.433832709, 0.41607565,
0.498800959, 0.399161736, 0.368421053, 0.386568387, 0.369901547,
0.398550725, 0.34006734, 0.406392694, 0.455840456, 0.458598726,
0.43792517, 0.501089325, 0.427777778, 0.49122807, 0.435081149,
0.416020672, 0.48441247, 0.40617284, 0.379298942, 0.402298851,
0.361462729, 0.396135266, 0.356666667, 0.353333333, 0.439182916,
0.469316597, 0.461868038, 0.490196078, 0.405555556, 0.505847953,
0.430529595, 0.406619385, 0.470023981, 0.395262768, 0.355072464,
0.373677249, 0.348008386, 0.382804995, 0.355481728, 0.415555556,
0.481481481, 0.4550036, 0.485074627, 0.501089325, 0.5, 0.51754386,
0.465043695, 0.438478747, 0.501199041, 0.457733481, 0.416815742,
0.360672976, 0.388285024, 0.397509579, 0.356589147, 0.384444444,
0.482917821, 0.452525253, 0.487864078, 0.501089325, 0.488888889,
0.513157895, 0.47627965, 0.475609756, 0.513189448, 0.471391657,
0.419797257, 0.38467433, 0.376081425, 0.396666667, 0.370985604,
0.42, 0.477777778, 0.436063218, 0.476782753, 0.490196078, 0.466666667,
0.51754386, 0.45505618, 0.44295302, 0.532374101, 0.460707635,
0.426019548, 0.35755814, 0.389842632, 0.388489209, 0.358730159,
0.422222222, 0.459610028, 0.473304473, 0.502487562, 0.509803922,
0.438888889, 0.516081871, 0.480024969, 0.457317073, 0.527577938,
0.460969293, 0.424148607, 0.386850153, 0.369161868, 0.397677794,
0.357696567, 0.433333333, 0.450704225, 0.429118774, 0.497031383,
0.505446623, 0.455555556, 0.492690058, 0.444444444, 0.409722222,
0.501199041, 0.444812362, 0.414860681, 0.361111111, 0.390096618,
0.394724221, 0.358803987, 0.426666667, 0.471837488, 0.495748299,
0.511982571, 0.45, 0.513157895, 0.465043695, 0.438478747, 0.498800959,
0.453200148, 0.409375, 0.329166667, 0.384172662, 0.38961039,
0.413333333, 0.406113537, 0.450728363, 0.435244161, 0.431693989,
0.441520468, 0.427745665, 0.378076063, 0.389671362, 0.427222222,
0.397905759, 0.423295455, 0.375268817, 0.391111111, 0.39893617,
0.461538462, 0.437367304, 0.448087432, 0.454678363, 0.421323057,
0.384787472, 0.394366197, 0.419141914, 0.401331931, 0.423768939,
0.368817204, 0.42680776)), .Names = c("Var1", "Var2", "value"
), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L,
25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L,
38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L,
51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L,
64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L,
77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L,
90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L,
102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L,
113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L,
124L, 125L, 126L, 127L, 128L, 129L, 130L, 131L, 132L, 133L, 134L,
135L, 136L, 137L, 138L, 139L, 140L, 141L, 142L, 143L, 144L, 145L,
146L, 147L, 148L, 149L, 150L, 151L, 152L, 153L, 154L, 155L, 156L,
157L, 158L, 159L, 160L, 161L, 162L, 163L, 164L, 165L, 166L, 167L,
168L, 169L, 170L, 171L, 172L, 173L, 174L, 175L, 176L, 177L, 178L,
179L, 180L, 181L, 182L, 183L, 184L, 185L, 186L, 187L, 188L, 189L,
190L, 191L, 192L, 193L, 194L, 195L, 196L, 197L, 198L, 199L, 200L,
201L, 202L, 203L, 204L, 205L, 206L, 207L, 208L, 209L, 210L, 212L,
213L, 214L, 215L, 216L, 217L, 218L, 219L, 220L, 222L, 223L, 224L,
225L, 226L, 228L, 229L, 230L, 231L, 232L, 233L, 234L, 235L, 236L,
239L, 240L, 241L, 242L, 244L, 245L, 246L, 247L, 248L, 249L, 250L,
251L, 252L, 255L, 256L, 267L), class = "data.frame")
</code>```

答:
I'm not exactly sure how I solved this. I can only assume I was making a really stupid mistake before, but here's the code that finally produced the desired outcome:

```<code>bp_gc <- ggplot(melted_data, aes(x=Var1, y=value*100)) + theme_bw()
bp_gc <- bp_gc + geom_rect(xmin=0, xmax=17,
                                 ymin=(operon_gc-opgc_stdev)*100,
                                 ymax=(operon_gc+opgc_stdev)*100,
                                 fill = "grey79", alpha=0.05)
bp_gc <- bp_gc + geom_rect(xmin=0, xmax=17,
                                 ymin=(genome_gc-gengc_stdev)*100,
                                 ymax=(genome_gc+gengc_stdev)*100,
                                 fill = "beige", alpha=.08)
bp_gc <- bp_gc + geom_abline(intercept=genome_gc*100, slope=0,
                                   colour="gray14", linetype=3)
bp_gc <- bp_gc + geom_abline(intercept=operon_gc*100, slope=0,
                                   colour="gray14", linetype=3)
bp_gc <- bp_gc + geom_boxplot(alpha = 0.7, fill="dodgerblue", color="gray11")
bp_gc <- bp_gc + ylab("GC Content (%)")
bp_gc <- bp_gc + xlab("Locus")
bp_gc <- bp_gc + theme(legend.position = "none",
                 axis.text.x = element_text(angle=45, hjust=1))
bp_gc <- bp_gc + coord_cartesian(ylim=c(30,60))
bp_gc <- bp_gc + geom_path(data=func_data, linetype=4, size=0.9, aes(x=x,y=y*100))

bp_gc
</code>```

ContentLicense: CC BY-SA 3.0

Title: geom_path with discrete boxplot data

Body:
Finally run out of ideas and links I could find to try and explain this so I need some help!

I'm trying to add a step-function to a ggplot chart using the cumSeg package. I did this successfully in this previous question, so I'm used to the usage of the function etc.

When I made the plot in that thread, it was fairly simple, just using an x vs y barplot for the mean values of x, and I added on error bars myself afterwards (thus it was a 16 x 2 dataframe).

I want to re-create this plot, but using sequential boxplots instead of bars, which I have done, using the raw data this time, which is ~250 observations in 16 factors (same factors as before).

Now when I try to add a geom_line,path or step it's complaining about the dimensions of the data not matching, because even though there are 16 factors/boxplots, there are now no longer 16 observations (Error: Aesthetics must be either length 1 or the same as the data (249): x, y, colour, group, fill)

To calculate the step function, I give it the means of each of the 16, which returns a 16-member vector, not ~250 (obviously).

How can I add the step function on to the box plot so that it understands it should pertain to the 16 factor values? I can't work out if it's a problem with the dataframe or how I'm giving it to ggplot.

I tried specifying it in a second dataframe, and passing it as geom_path(data=df2) instead of inheriting the main plots data, as in this question, but it still complains (Error: Aesthetics must be either length 1 or the same as the data (16): x, y, colour, group (the code below is in this form still)

data.melt <- melt(t(infile)

operon_gc <- 0.408891366
opgc_stdev <- 0.015712091
genome_gc <- 0.425031611
gengc_stdev <- 0.007587437

stepfunc <- jumpoints(y=aggregate(melted_data$value~melted_data$Var1, simplify=TRUE, FUN="mean")$`melted_data$value`, k=1, output="1")
func_data <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16), y = stepfunc$fitted.values)

# Make boxplot

bp <- ggplot(melted_data, aes(x=Var1, y=value*100, fill=Var1)) + theme_bw()

#bp <- bp + scale_x_discrete(name = "Locus") + scale_y_continuous(name="GC Content (%)")
bp <- bp + geom_rect(xmin=0, xmax=17,
                                 ymin=(operon_gc-opgc_stdev)*100,
                                 ymax=(operon_gc+opgc_stdev)*100,
                                 fill = "grey79", alpha=0.05)
bp <- bp + geom_rect(xmin=0, xmax=17,
                                 ymin=(genome_gc-gengc_stdev)*100,
                                 ymax=(genome_gc+gengc_stdev)*100,
                                 fill = "beige", alpha=.08)
bp <- bp + geom_abline(intercept=genome_gc*100, slope=0,
                                   colour="gray14", linetype=3)
bp <- bp + geom_abline(intercept=operon_gc*100, slope=0,
                                   colour="gray14", linetype=3)

bp <- bp + geom_boxplot(alpha = 0.7)

bp <- bp + scale_color_manual(values = c("GC Step Fit"="red"), guides(color="Regression"))

bp <- bp + geom_path(linetype=4, size=0.9, aes(x=func_data$x,
                                               y=func_data$y,
                                               color="GC Step Fit",
                                               group=1))
bp <- bp + theme(legend.position="bottom",
                 legend.direction="horizontal",
                 axis.text.x = element_text(angle=45, hjust=1)) + guides(fill=guide_legend(title="", nrow = 1))

bp

Data

> dput(func_data)
structure(list(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16), y = c(0.452456815737206, 0.452456815737206, 0.452456815737206,
0.452456815737206, 0.452456815737206, 0.452456815737206, 0.452456815737206,
0.452456815737206, 0.452456815737206, 0.452456815737206, 0.452456815737206,
0.375047391939972, 0.375047391939972, 0.375047391939972, 0.375047391939972,
0.375047391939972)), .Names = c("x", "y"), row.names = c(NA,
-16L), class = "data.frame")

> dput(melted_data)
structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L,
16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L,
16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 14L, 15L, 16L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 15L, 16L, 1L, 2L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 15L, 16L, 11L), .Label = c("PVC1", "PVC2", "PVC3", "PVC4",
"PVC5", "PVC6", "PVC7", "PVC8", "PVC9", "PVC10", "PVC11", "PVC12",
"PVC13", "PVC14", "PVC15", "PVC16"), class = "factor"), Var2 = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 14L, 14L,
14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 15L,
15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 16L,
16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 17L
), value = c(0.404444444, 0.436329588, 0.46031746, 0.479318735,
0.466230937, 0.480874317, 0.476811594, 0.441558442, 0.449172577,
0.476525822, 0.452674897, 0.460918332, 0.368041912, 0.339160839,
0.415355269, 0.408163265, 0.401826484, 0.45411985, 0.468609865,
0.479735318, 0.464052288, 0.469945355, 0.476811594, 0.444032158,
0.453900709, 0.494004796, 0.467315716, 0.457805907, 0.387071651,
0.390737117, 0.408679065, 0.425170068, 0.355555556, 0.438069217,
0.423076923, 0.466666667, 0.450980392, 0.422222222, 0.469298246,
0.43196005, 0.416666667, 0.496402878, 0.428676201, 0.382113821,
0.349765258, 0.332280147, 0.373371925, 0.346448087, 0.415555556,
0.440508629, 0.435222672, 0.455833333, 0.446623094, 0.422222222,
0.463450292, 0.43258427, 0.425675676, 0.497584541, 0.422524565,
0.392592593, 0.362779741, 0.337552743, 0.379856115, 0.348888889,
0.391111111, 0.421004566, 0.426439232, 0.480367586, 0.472766885,
0.455555556, 0.495726496, 0.447565543, 0.424460432, 0.48441247,
0.435164835, 0.39600551, 0.3858393, 0.323655914, 0.383693046,
0.329988852, 0.395555556, 0.452380952, 0.454756381, 0.448129252,
0.496732026, 0.423728814, 0.502923977, 0.433832709, 0.41607565,
0.498800959, 0.399161736, 0.368421053, 0.386568387, 0.369901547,
0.398550725, 0.34006734, 0.406392694, 0.455840456, 0.458598726,
0.43792517, 0.501089325, 0.427777778, 0.49122807, 0.435081149,
0.416020672, 0.48441247, 0.40617284, 0.379298942, 0.402298851,
0.361462729, 0.396135266, 0.356666667, 0.353333333, 0.439182916,
0.469316597, 0.461868038, 0.490196078, 0.405555556, 0.505847953,
0.430529595, 0.406619385, 0.470023981, 0.395262768, 0.355072464,
0.373677249, 0.348008386, 0.382804995, 0.355481728, 0.415555556,
0.481481481, 0.4550036, 0.485074627, 0.501089325, 0.5, 0.51754386,
0.465043695, 0.438478747, 0.501199041, 0.457733481, 0.416815742,
0.360672976, 0.388285024, 0.397509579, 0.356589147, 0.384444444,
0.482917821, 0.452525253, 0.487864078, 0.501089325, 0.488888889,
0.513157895, 0.47627965, 0.475609756, 0.513189448, 0.471391657,
0.419797257, 0.38467433, 0.376081425, 0.396666667, 0.370985604,
0.42, 0.477777778, 0.436063218, 0.476782753, 0.490196078, 0.466666667,
0.51754386, 0.45505618, 0.44295302, 0.532374101, 0.460707635,
0.426019548, 0.35755814, 0.389842632, 0.388489209, 0.358730159,
0.422222222, 0.459610028, 0.473304473, 0.502487562, 0.509803922,
0.438888889, 0.516081871, 0.480024969, 0.457317073, 0.527577938,
0.460969293, 0.424148607, 0.386850153, 0.369161868, 0.397677794,
0.357696567, 0.433333333, 0.450704225, 0.429118774, 0.497031383,
0.505446623, 0.455555556, 0.492690058, 0.444444444, 0.409722222,
0.501199041, 0.444812362, 0.414860681, 0.361111111, 0.390096618,
0.394724221, 0.358803987, 0.426666667, 0.471837488, 0.495748299,
0.511982571, 0.45, 0.513157895, 0.465043695, 0.438478747, 0.498800959,
0.453200148, 0.409375, 0.329166667, 0.384172662, 0.38961039,
0.413333333, 0.406113537, 0.450728363, 0.435244161, 0.431693989,
0.441520468, 0.427745665, 0.378076063, 0.389671362, 0.427222222,
0.397905759, 0.423295455, 0.375268817, 0.391111111, 0.39893617,
0.461538462, 0.437367304, 0.448087432, 0.454678363, 0.421323057,
0.384787472, 0.394366197, 0.419141914, 0.401331931, 0.423768939,
0.368817204, 0.42680776)), .Names = c("Var1", "Var2", "value"
), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L,
25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L,
38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L,
51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L,
64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L,
77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L,
90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L,
102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L,
113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L,
124L, 125L, 126L, 127L, 128L, 129L, 130L, 131L, 132L, 133L, 134L,
135L, 136L, 137L, 138L, 139L, 140L, 141L, 142L, 143L, 144L, 145L,
146L, 147L, 148L, 149L, 150L, 151L, 152L, 153L, 154L, 155L, 156L,
157L, 158L, 159L, 160L, 161L, 162L, 163L, 164L, 165L, 166L, 167L,
168L, 169L, 170L, 171L, 172L, 173L, 174L, 175L, 176L, 177L, 178L,
179L, 180L, 181L, 182L, 183L, 184L, 185L, 186L, 187L, 188L, 189L,
190L, 191L, 192L, 193L, 194L, 195L, 196L, 197L, 198L, 199L, 200L,
201L, 202L, 203L, 204L, 205L, 206L, 207L, 208L, 209L, 210L, 212L,
213L, 214L, 215L, 216L, 217L, 218L, 219L, 220L, 222L, 223L, 224L,
225L, 226L, 228L, 229L, 230L, 231L, 232L, 233L, 234L, 235L, 236L,
239L, 240L, 241L, 242L, 244L, 245L, 246L, 247L, 248L, 249L, 250L,
251L, 252L, 255L, 256L, 267L), class = "data.frame")

Body:
I'm not exactly sure how I solved this. I can only assume I was making a really stupid mistake before, but here's the code that finally produced the desired outcome:

bp_gc <- ggplot(melted_data, aes(x=Var1, y=value*100)) + theme_bw()
bp_gc <- bp_gc + geom_rect(xmin=0, xmax=17,
                                 ymin=(operon_gc-opgc_stdev)*100,
                                 ymax=(operon_gc+opgc_stdev)*100,
                                 fill = "grey79", alpha=0.05)
bp_gc <- bp_gc + geom_rect(xmin=0, xmax=17,
                                 ymin=(genome_gc-gengc_stdev)*100,
                                 ymax=(genome_gc+gengc_stdev)*100,
                                 fill = "beige", alpha=.08)
bp_gc <- bp_gc + geom_abline(intercept=genome_gc*100, slope=0,
                                   colour="gray14", linetype=3)
bp_gc <- bp_gc + geom_abline(intercept=operon_gc*100, slope=0,
                                   colour="gray14", linetype=3)
bp_gc <- bp_gc + geom_boxplot(alpha = 0.7, fill="dodgerblue", color="gray11")
bp_gc <- bp_gc + ylab("GC Content (%)")
bp_gc <- bp_gc + xlab("Locus")
bp_gc <- bp_gc + theme(legend.position = "none",
                 axis.text.x = element_text(angle=45, hjust=1))
bp_gc <- bp_gc + coord_cartesian(ylim=c(30,60))
bp_gc <- bp_gc + geom_path(data=func_data, linetype=4, size=0.9, aes(x=x,y=y*100))

bp_gc


问:
Matplotlib animate OHLC does not refresh
I am trying to build a graph that displays candlesticks of a datafeed. Below the code is provided. The graph is supposed to be animated but it does not update. Can anybode help please?</p>

```<code>class Graph(object):
def __init__(self, ticker_name):
    self.datafeed = self.get_datafeed(ticker_name)
    self.figure = plt.figure()
    self.ax1 = self.figure.add_subplot(211)
    self.ax2 = self.figure.add_subplot(212)
    animation.FuncAnimation(self.figure, self.animate, interval=10000, init_func=self.init_figure)
    plt.show()

def get_datafeed(self, ticker_name):
    self.parameters = {"ticker_name": ticker_name,
                       "history": 100}
    return DataFeed(self.parameters)

def init_figure(self):
    self.ax1.xaxis.set_major_formatter(DateFormatter('%H:%M'))
    self.ax1.grid()
    self.ax2.grid()
    self.ax1.set_title(self.parameters["ticker_name"].upper())

def animate(self, i):
    time.sleep(2)
    self.datafeed.refresh()
    data = self.datafeed.query(10)
    self.ax1.clear()
    self.ax2.clear()
    self.plot_candles(data[["time", "open", "high", "low", "close"]])

def plot_candles(self, df):
    df.loc[:, "time"] = df.time.apply(date2num)
    mpf.candlestick_ohlc(self.ax1, df.values.tolist(), width=0.0005, colordown="r", colorup="g")
    self.ax1.set_ylim(df["low"].min() - 5, df["high"].max() + 5)
</code>```

答:
Don't use time.sleep() in an animation. Instead use the interval argument of FuncAnimation to control the updating speed.

You also need to retain a reference to the FuncAnimation. Use

```<code>self.ani = animation.FuncAnimation( ... )
</code>```

Otherwise the FuncAnimation will be garbage collected as soon as the figure is shown.

(Note that if this does not solve the problem, you need to provide a

Minimal, Complete, and Verifiable example of the issue)

Body:
I am trying to build a graph that displays candlesticks of a datafeed. Below the code is provided. The graph is supposed to be animated but it does not update. Can anybode help please?

class Graph(object):
def __init__(self, ticker_name):
    self.datafeed = self.get_datafeed(ticker_name)
    self.figure = plt.figure()
    self.ax1 = self.figure.add_subplot(211)
    self.ax2 = self.figure.add_subplot(212)
    animation.FuncAnimation(self.figure, self.animate, interval=10000, init_func=self.init_figure)
    plt.show()

def get_datafeed(self, ticker_name):
    self.parameters = {"ticker_name": ticker_name,
                       "history": 100}
    return DataFeed(self.parameters)

def init_figure(self):
    self.ax1.xaxis.set_major_formatter(DateFormatter('%H:%M'))
    self.ax1.grid()
    self.ax2.grid()
    self.ax1.set_title(self.parameters["ticker_name"].upper())

def animate(self, i):
    time.sleep(2)
    self.datafeed.refresh()
    data = self.datafeed.query(10)
    self.ax1.clear()
    self.ax2.clear()
    self.plot_candles(data[["time", "open", "high", "low", "close"]])

def plot_candles(self, df):
    df.loc[:, "time"] = df.time.apply(date2num)
    mpf.candlestick_ohlc(self.ax1, df.values.tolist(), width=0.0005, colordown="r", colorup="g")
    self.ax1.set_ylim(df["low"].min() - 5, df["high"].max() + 5)

Body:
Don't use time.sleep() in an animation. Instead use the interval argument of FuncAnimation to control the updating speed.

You also need to retain a reference to the FuncAnimation. Use

self.ani = animation.FuncAnimation( ... )

Otherwise the FuncAnimation will be garbage collected as soon as the figure is shown.

(Note that if this does not solve the problem, you need to provide a

Minimal, Complete, and Verifiable example of the issue)


问:
How to get relative mouse position of screen which is transformed
In win2D, Get absolute mouse position is this (from Win2D Sprite Sample)

```<code>var point = e.GetCurrentPoint((UIElement)sender).Position.ToVector2();
</code>```

But, This is Absolute Position,

I make whether mouse is pointing Game Player

So, I made this Code, But It doesn't work.

```<code>        var rpoint = e.GetCurrentPoint(canvas).Position.ToVector2();

        // 사각형 길을 보여주기
        if ((rpoint.X > wizardPosition.X - 64) && (rpoint.X < wizardPosition.X + 64) && (rpoint.Y > wizardPosition.Y - 150) && (rpoint.Y < wizardPosition.Y + 42) )
        {
            if (ShowBorder == true) { ShowBorder = false; }

             else if (ShowBorder == false)
                ShowBorder = true;
        }
</code>```

Does anybody have solved this problem?

答:
I have solve myself. Anyway.
The code is this</p>

```<code>            var rpoint = e.GetCurrentPoint(this).Position.ToVector2();

        // Invert the display transform, to convert pointer positions into simulation rendertarget space.
        Matrix3x2 Mtransform;
        Matrix3x2.Invert(transform, out Mtransform);

        var xpoint = Vector2.Transform(rpoint, Mtransform);

        // 사각형 길을 보여주기
        if ((xpoint.X > wizardPosition.X - 64) && (xpoint.X < wizardPosition.X + 64) && (xpoint.Y > wizardPosition.Y - 150) && (xpoint.Y < wizardPosition.Y + 42) )
        {
            if (ShowBorder == true) { ShowBorder = false; }

             else if (ShowBorder == false)
                ShowBorder = true;
        }
</code>```

Body:
In win2D, Get absolute mouse position is this (from Win2D Sprite Sample)

var point = e.GetCurrentPoint((UIElement)sender).Position.ToVector2();

But, This is Absolute Position,

I make whether mouse is pointing Game Player

So, I made this Code, But It doesn't work.

        var rpoint = e.GetCurrentPoint(canvas).Position.ToVector2();

        // 사각형 길을 보여주기
        if ((rpoint.X > wizardPosition.X - 64) && (rpoint.X < wizardPosition.X + 64) && (rpoint.Y > wizardPosition.Y - 150) && (rpoint.Y < wizardPosition.Y + 42) )
        {
            if (ShowBorder == true) { ShowBorder = false; }

             else if (ShowBorder == false)
                ShowBorder = true;
        }

Does anybody have solved this problem?

Body:
I have solve myself. Anyway.
The code is this

            var rpoint = e.GetCurrentPoint(this).Position.ToVector2();

        // Invert the display transform, to convert pointer positions into simulation rendertarget space.
        Matrix3x2 Mtransform;
        Matrix3x2.Invert(transform, out Mtransform);

        var xpoint = Vector2.Transform(rpoint, Mtransform);

        // 사각형 길을 보여주기
        if ((xpoint.X > wizardPosition.X - 64) && (xpoint.X < wizardPosition.X + 64) && (xpoint.Y > wizardPosition.Y - 150) && (xpoint.Y < wizardPosition.Y + 42) )
        {
            if (ShowBorder == true) { ShowBorder = false; }

             else if (ShowBorder == false)
                ShowBorder = true;
        }


问:
OpenCV Python RTSP stream
I want to stream the video from IP camera by using RTSP. But I am having a problem. I have installed prerequirements and also, my RTSP link works on VlC player. But when I tried it in the editor and run it, it says Camera could not be found.

Here is my code.

```<code>import cv2
import numpy as np
cap = cv2.VideoCapture("rtsp://admin:admin@xxx.xxx.xxx.xxx:xxx/media/video1/video")

while True:
    ret, img = cap.read()
    if ret == True:
    cv2.imshow('video output', img)
    k = cv2.waitKey(10)& 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
</code>```

答:
Do check your installation of opencv has the capability to open videos. for this try

```<code>cap=cv2.VideoCapture(r"path/to/video/file")
ret,img=cap.read()
print ret
</code>```

If ret is True then your opencv install has the codecs necessary to handle videos and then confirm that the RTSP address is correct.

If ret is False then reinstall opencv using the steps here. I would recommend building opencv from source. But try the pre-built libraries first.

ContentLicense: CC BY-SA 4.0

Title: OpenCV Python RTSP stream

Body:
I want to stream the video from IP camera by using RTSP. But I am having a problem. I have installed prerequirements and also, my RTSP link works on VlC player. But when I tried it in the editor and run it, it says Camera could not be found.

Here is my code.

import cv2
import numpy as np
cap = cv2.VideoCapture("rtsp://admin:admin@xxx.xxx.xxx.xxx:xxx/media/video1/video")

while True:
    ret, img = cap.read()
    if ret == True:
    cv2.imshow('video output', img)
    k = cv2.waitKey(10)& 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

Body:
Do check your installation of opencv has the capability to open videos. for this try

cap=cv2.VideoCapture(r"path/to/video/file")
ret,img=cap.read()
print ret

If ret is True then your opencv install has the codecs necessary to handle videos and then confirm that the RTSP address is correct.

If ret is False then reinstall opencv using the steps here. I would recommend building opencv from source. But try the pre-built libraries first.


问:
how to wait untill chain of asyc calls is succeeded
I have a function which is making an async call
and upon sucess, its making another async call

ex:-

```<code>    function1 = () => {
      /*Some required Logic*/
  return fetch("myurl")
      .then((json) => {
        function2(json)

      })
      .catch((error) => {
        console.log(error)
      })
}

function2 = () => {
  /*Some required Logic*/
  return fetch("myurl2")
      .then((json) => {
        callthirdfunction(json)

      })
      .catch((error) => {
        console.log(error)
      })
}
</code>```

now here is the function 3
in which i am dependent on the success of function1

```<code>function3 = () => {
  /*Some required Logic*/
  function1().then(() => {
})
}
</code>```

Issue is it is only waiting untill the function1's asyc call is succeeded its not waiting for function2's async call to succeed

I know i can write like chain of asyn call but its not possible because of unavoidable circumstances

Any suggesstion or leads in this regard would be of great help

答:
If you want one promise to depend on another promise, you need to return the dependent promise from then.

Your code doesn't do anything with the result of function2:

```<code>return fetch("myurl")
  .then((json) => {
    function2(json)

  })
</code>```

That should read

```<code>.then((json) => {
  return function2(json)
})
</code>```

The whole point of then is that it allows chaining of subsequent promises by returning them from the callback.

Body:
I have a function which is making an async call
and upon sucess, its making another async call

ex:-

    function1 = () => {
      /*Some required Logic*/
  return fetch("myurl")
      .then((json) => {
        function2(json)

      })
      .catch((error) => {
        console.log(error)
      })
}

function2 = () => {
  /*Some required Logic*/
  return fetch("myurl2")
      .then((json) => {
        callthirdfunction(json)

      })
      .catch((error) => {
        console.log(error)
      })
}

now here is the function 3
in which i am dependent on the success of function1

function3 = () => {
  /*Some required Logic*/
  function1().then(() => {
})
}

Issue is it is only waiting untill the function1's asyc call is succeeded its not waiting for function2's async call to succeed

I know i can write like chain of asyn call but its not possible because of unavoidable circumstances

Any suggesstion or leads in this regard would be of great help

Body:
If you want one promise to depend on another promise, you need to return the dependent promise from then.

Your code doesn't do anything with the result of function2:

return fetch("myurl")
  .then((json) => {
    function2(json)

  })

That should read

.then((json) => {
  return function2(json)
})

The whole point of then is that it allows chaining of subsequent promises by returning them from the callback.


问:
JQuery call not working after Ajax call succeeds
I have an Ajax call that looks like this:

```<code>$("#start-upload-btn").click(function(){
    $.ajax({
        type: "post",
        url: "",
        data: {
            newProjectName: $('#project-name').val(),
            csrfmiddlewaretoken: csrfToken
        },
        success: function(data){
            $("#file-upload").click();
        }
    })
});
</code>```

Upon success I want to perform a click on the  element with id #file-upload to launch the file selection dialogue, but putting the code in success function fails to work. It works anywhere else. Is there something special about the scope of the Ajax success function? I really cannot figure this out.

Thanks

答:
There is nothing inherently problematic about issuing a click on any normal element (including a button) from an ajax success callback.

The problem is that a file-input dialog is not a "normal element". It has some specific security limitations - one of which clearly limits your interaction with it.

This is demonstrated by the following fiddle: https://jsfiddle.net/qhfwobpz/

You'll see that issuing a click on the file-upload directly works without a problem. Doing it from an ajax callback yo'll see the callback is called, but the file dialog never shows.

This answer gives more detail as to the "why" and it boils down to you can open the dialog from an event issued by the user but not purely programatically.

Body:
I have an Ajax call that looks like this:

$("#start-upload-btn").click(function(){
    $.ajax({
        type: "post",
        url: "",
        data: {
            newProjectName: $('#project-name').val(),
            csrfmiddlewaretoken: csrfToken
        },
        success: function(data){
            $("#file-upload").click();
        }
    })
});

Upon success I want to perform a click on the  element with id #file-upload to launch the file selection dialogue, but putting the code in success function fails to work. It works anywhere else. Is there something special about the scope of the Ajax success function? I really cannot figure this out.

Thanks


问:
how to avoid that the scroll bar on the right overlaps with the top navbar (bootstrap)?
I have a website with a navbar fixed to the top and a navbar on the left. When there is need for scrolling on the website, the scrollbar on the right overlaps with the top navbar. I would like the navbar to start below the top navbar.
I made a fiddle with an example of the problem

https://jsfiddle.net/jsmnsLm7/
(please make the window big, so that you can see all of the features of my navbar setup)

Here is the code which I also have in the fiddle (but stackoverlow forces me to put code in here as well... I think its much easier in the fiddle)

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active">
                <li><a href="#">item</a></li>
                <li><a href="#">item</a></li>
                <li><a href="#">item</a></li>
            </ul>
        </div>
        <!--/.nav-collapse -->
    </div>
</nav>
<div class="container">
    <div class="row row-offcanvas row-offcanvas-left">
        <div class="col-sm-3 col-md-2 sidebar-offcanvas" id="sidebar" role="navigation" style="width: 180px; position: fixed;">
            <br><br><br>
            <ul class="nav nav-sidebar">
                <li class="active"><a href="#">item0</a></li>
                <li><a href="#">item1</a></li>
                <li><a href="#">item2</a></li>
                <li><a href="#">item3</a></li>
            </ul>
        </div>
        <!--/span-->
        <div class="col-sm-9 col-md-10 main" style="margin-left: 180px;">
        </div>
    </div>
</div>
</code>```

I saw that some discussed this problem before on stackoverflow, and they suggested to add position: fixed to the css of the container. However, when I do that, the left navbar gets fixed to the very left of the page. I want the left navbar to be flexible and synchronous with the top navbar (as shown in the fiddle example)
thanks for any help
best
carl

答:
@Tasos' solution to hide body overflow is a good start, but using javascript to set the height doesn't work on browser resize events properly, at least on Chrome 59 (and document.height is now deprecated).

If you use position:absolute, top and bottom on main, you should be set: https://jsfiddle.net/vvsp60ya/

body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

nav {
  background-color: black;
  height: 50px;
  color: white;
}

h1 {
  padding: .5em;
  margin: 0;
}

main {
  position: absolute;
  top: 50px;
  bottom: 0;
  overflow-y: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <h1>Title</h1>
</nav>
<main>
  <div>
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
  </div>
</main></code>```

Body:
I have a website with a navbar fixed to the top and a navbar on the left. When there is need for scrolling on the website, the scrollbar on the right overlaps with the top navbar. I would like the navbar to start below the top navbar.
I made a fiddle with an example of the problem

https://jsfiddle.net/jsmnsLm7/
(please make the window big, so that you can see all of the features of my navbar setup)

Here is the code which I also have in the fiddle (but stackoverlow forces me to put code in here as well... I think its much easier in the fiddle)

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>

item

item

item

item0

item1

item2

item3

I saw that some discussed this problem before on stackoverflow, and they suggested to add position: fixed to the css of the container. However, when I do that, the left navbar gets fixed to the very left of the page. I want the left navbar to be flexible and synchronous with the top navbar (as shown in the fiddle example)
thanks for any help
best
carl

Body:
@Tasos' solution to hide body overflow is a good start, but using javascript to set the height doesn't work on browser resize events properly, at least on Chrome 59 (and document.height is now deprecated).

If you use position:absolute, top and bottom on main, you should be set: https://jsfiddle.net/vvsp60ya/

body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

nav {
  background-color: black;
  height: 50px;
  color: white;
}

h1 {
  padding: .5em;
  margin: 0;
}

main {
  position: absolute;
  top: 50px;
  bottom: 0;
  overflow-y: scroll;
}

<nav>
  <h1>Title</h1>
</nav>
<main>
  <div>
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
    text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
  </div>
</main>


问:
I cannot fetch data from using this code
```<code>public function orderView(Request $request){
    $orderByID = $request->id;
    $orderDetailsView = DB::table('order_details')
            ->where('order_id',$orderByID)
            ->get();
    return view('admin.order.vieworder', ['orderDetailsView' => $orderDetailsView]);
}
</code>```

If i return only $orderByID it shows the id. But using this id i cannot fetch data from the database table. it shows empty array.

答:
Try this code</p>

```<code>$orderss = DB::table('order_details')->where('order_id', '=', $orderByID)->get();
</code>```

Body:
public function orderView(Request $request){
    $orderByID = $request->id;
    $orderDetailsView = DB::table('order_details')
            ->where('order_id',$orderByID)
            ->get();
    return view('admin.order.vieworder', ['orderDetailsView' => $orderDetailsView]);
}

If i return only $orderByID it shows the id. But using this id i cannot fetch data from the database table. it shows empty array.

Body:
Try this code

$orderss = DB::table('order_details')->where('order_id', '=', $orderByID)->get();


问:
How to write a custom struct data type for PostgreSQL using internal types
I am using PostgreSQL 9.6. I would like to create a new currency type extension on PostgreSQL that contains a string and a numerical value.

According to the documentation https://www.postgresql.org/docs/9.6/static/sql-createtype.html, I can use compose type directly in PostgreSQL, but this is not what I want because I want to be able to represent the type using a string and do casting. So the solution is to create a custom type such as the example "box" type. The documentation shows:

```<code>CREATE TYPE box;

CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ;
CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ;

CREATE TYPE box (
   INTERNALLENGTH = 16,
   INPUT = my_box_in_function,
   OUTPUT = my_box_out_function
);
</code>```

But it's not really helpful as to HOW to write such a function. Further search shows that function can only be written in C and shows example of simple type, not struct type.

So I basically want something like

```<code>typedef struct {
    char code[4];
    Numeric  numeric;
} Currency
</code>```

I want to use fixed type Numeric, that would avoid me the extra effort of implementing varlena header. Besides currency usually have fixed decimal point. I also want to be able to use the Numeric type internally because it allows me to reuse the function of Numeric.

How can I use Numeric, such that I can use a similar syntax as from PostgreSQL (e.g. Numeric(10,2)) to define my struct? Can I use the numeric_in function inside my currency_in function?

答:
Both character and numeric are varlena, so you won't be able to store them in a fixed length data structure.

I would define the data type as

typedef struct {
    /* value times 100 */
    int64 value;
    /* currency name */
    char denomination[4];
} currency;
```

Storing the characters last avoids alignment problems.

Operations on the value are now simple integer operations. I don't expect that you want to multiply or devide two currency values; that wouldn't make much sense.

Body:
I am using PostgreSQL 9.6. I would like to create a new currency type extension on PostgreSQL that contains a string and a numerical value.

According to the documentation https://www.postgresql.org/docs/9.6/static/sql-createtype.html, I can use compose type directly in PostgreSQL, but this is not what I want because I want to be able to represent the type using a string and do casting. So the solution is to create a custom type such as the example "box" type. The documentation shows:

CREATE TYPE box;

CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ;
CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ;

CREATE TYPE box (
   INTERNALLENGTH = 16,
   INPUT = my_box_in_function,
   OUTPUT = my_box_out_function
);

But it's not really helpful as to HOW to write such a function. Further search shows that function can only be written in C and shows example of simple type, not struct type.

So I basically want something like

typedef struct {
    char code[4];
    Numeric  numeric;
} Currency

I want to use fixed type Numeric, that would avoid me the extra effort of implementing varlena header. Besides currency usually have fixed decimal point. I also want to be able to use the Numeric type internally because it allows me to reuse the function of Numeric.

How can I use Numeric, such that I can use a similar syntax as from PostgreSQL (e.g. Numeric(10,2)) to define my struct? Can I use the numeric_in function inside my currency_in function?

Body:
Both character and numeric are varlena, so you won't be able to store them in a fixed length data structure.

I would define the data type as

typedef struct {
    /* value times 100 */
    int64 value;
    /* currency name */
    char denomination[4];
} currency;

Storing the characters last avoids alignment problems.

Operations on the value are now simple integer operations. I don't expect that you want to multiply or devide two currency values; that wouldn't make much sense.


问:
GWT and an unreproducable 503 error

I have a web-application built with GWT (2.0.3) and run on Apache Tomcat 6.

My application uses long polling to enable client-server conversations.
When a client is unable to connect to the server it displays a disconnected message on the page and grays out the controls until it is able to resume conversation with the server.

This happens through the use of the onFailure method of the rpc services; I keep track on how many consequtive exceptions I've received and if it passes a defined threshhold the above scenario happens.

This allows notifying the user of a problem while in the background continuing to resume the server conversation.

This has been the configuration for about 6 months, and without a problem.

I compiled the application after a change and wanted to see it in stand-alone mode so I started up tomcat (not via eclipse) and everything seemed to work fine.

When I ctrl+c'd the apache (while having clients up) I saw the clients displaying a 503 error instead of my app with the disconnected message.

I then tried to reproduce the issue but was unable as the next times the app behaved as expected.

I'm not sure if it's relevant but recently I added an UncaughtExceptionHandler to my module's onModuleLoad.

Has anyone encountered such an issue?

Do you know how I can make my client immune to such an issue?

Thanks a lot,

Ittai

答: Probably your app tried to connect to server while it was in process of shutting down. Some of the services might have already shut so the request failed with internal server error. </p>

ContentLicense: CC BY-SA 2.5

Title: GWT and an unreproducable 503 error


问:
how to store id or any value in session variable and call session in all pages using ci?
controller: test.php

```<code><?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class Test extends CI_Controller
    {
        function __construct()
        {
            parent :: __construct();
            $this->load->helper(array('form', 'url', 'captcha', 'email'));
            $this->load->model('Fetch_data');
        }
        public function student()
        {
            $this->load->view('student-dashboard/index');
        }
    }
</code>```

view: login.php

```<code><?php
    if($this->input->post('login'))
    {
        $email2 = $this->input->post('email2');
        $password2 = $this->input->post('password2');

        $this->db->select('email,password');
        $this->db->from('students');
        $where = "email='$email2' and password = '$password2'";
        $this->db->where($where);
        $query = $this->db->get();
        $result = $query->result_array();
        $num = $query->num_rows();
        if($num >'0')
        {
            $this->db->select('email,password,student_id');
            $this->db->from('students');
            $where = "email='$email2' and password = '$password2'";
            $this->db->where($where);
            $query = $this->db->get();
            $result = $query->result_array();

            $data['student_id'] = $this->session->set_userdata('student_id',$result);
            if($result == true)
            {
                redirect('/test/student', $data);
            }
        }
        else
        {
            echo "<p style='color: red;font-weight: bold;'>Wrong email id or password! </p>";
        }
    }
?>
<form method="post">
    <div class="form-group">
        <input type="text" name="email2" id="email2" placeholder="Enter Your Email" class="text-line"/>
    </div>
    <div class="form-group">
        <input type="password" name="password2" id="password2" placeholder="Enter Your Password" class="text-line"/>
    </div>
    <div class="form-group">
        <input type="submit" name="login" id="login" value="Login" class="btn btn-warning"/>
    </div>
</form>
</code>```

I am new in codeigniter. In this code I am creating login form and it work perfectly. Now, I want to store student_id into session variable through which I can give welcome message on my all pages. So, How can I do this ? please help me.

Thank You

答:
If you want to add/create session data :

$data = array(
        'student_id'  => 'id',
        'name'     => 'name',

);

$this->session->set_userdata($data); ```
</div>
</div>
</p>

<p>In order to use Session library you should load it in the constructor method in each controller you need it as :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$this->load->library('session');</code>```

By doing this, session variables will be available for all views you are loading in this controller.
In your view you can give welcome message with :

<?php echo "Hello ".$this->session->userdata('student_id');?>```

Anyway, i suggest you to move your php code from the view (login.php) to the controller (test.php). It eases your work

Body:
controller: test.php

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class Test extends CI_Controller
    {
        function __construct()
        {
            parent :: __construct();
            $this->load->helper(array('form', 'url', 'captcha', 'email'));
            $this->load->model('Fetch_data');
        }
        public function student()
        {
            $this->load->view('student-dashboard/index');
        }
    }

view: login.php

<?php
    if($this->input->post('login'))
    {
        $email2 = $this->input->post('email2');
        $password2 = $this->input->post('password2');

        $this->db->select('email,password');
        $this->db->from('students');
        $where = "email='$email2' and password = '$password2'";
        $this->db->where($where);
        $query = $this->db->get();
        $result = $query->result_array();
        $num = $query->num_rows();
        if($num >'0')
        {
            $this->db->select('email,password,student_id');
            $this->db->from('students');
            $where = "email='$email2' and password = '$password2'";
            $this->db->where($where);
            $query = $this->db->get();
            $result = $query->result_array();

            $data['student_id'] = $this->session->set_userdata('student_id',$result);
            if($result == true)
            {
                redirect('/test/student', $data);
            }
        }
        else
        {
            echo "
Wrong email id or password!
";
        }
    }
?>
<form method="post">

        <input type="text" name="email2" id="email2" placeholder="Enter Your Email" class="text-line"/>

        <input type="password" name="password2" id="password2" placeholder="Enter Your Password" class="text-line"/>

        <input type="submit" name="login" id="login" value="Login" class="btn btn-warning"/>

</form>

I am new in codeigniter. In this code I am creating login form and it work perfectly. Now, I want to store student_id into session variable through which I can give welcome message on my all pages. So, How can I do this ? please help me.

Thank You

Body:
If you want to add/create session data :

$data = array(
        'student_id'  => 'id',
        'name'     => 'name',
        <!-- Your parameters -->
);

$this->session->set_userdata($data);

In order to use Session library you should load it in the constructor method in each controller you need it as :

$this->load->library('session');

By doing this, session variables will be available for all views you are loading in this controller.
In your view you can give welcome message with :

<?php echo "Hello ".$this->session->userdata('student_id');?>

Anyway, i suggest you to move your php code from the view (login.php) to the controller (test.php). It eases your work


问:
error1833: cannot change colum id
With prompt command, I have generated a database with doctine using reverse engineering. It worked perfectly:

```<code>php app/console doctrine:mapping:convert yml ./src/Gir/DatabaseBundle/Resources/config/doctrine/metadata/orm --from-database --force
</code>```

After, I create the entities:

```<code>php app/console doctrine:mapping:import GirDatabaseBundle annotation
</code>```

And the annotations:

```<code>php app/console doctrine:generate:entities GirDatabaseBundle
</code>```

Then, I installed the new update of Symfony with composer.phar.

Then, the FOSUserBundle in order to manage users in my project.

I have to update my database with doctrine using this prompt command in order to generate the table users and the entities, etc:

```<code>php app/console doctrine:schema:update --force
</code>```

When I do this command, doctrine send me this error in the windows prompt command:

```<code>**[Doctrine\DBAL\DBALException]**
An exception occured while executing 'ALTER TABLE agence CHANGE id id INT NOT NULL':
SQLSTATE[HY000]: General error: 1833 Cannot change colum 'id': used in a foreign key constraint 'fk_employe_agence1' of table 'gir.employe'

**[PDOException]**
SQLSTATE[HY000]: General error: 1833 Cannot change colum 'id': used in a foreign key constraint 'fk_employe_agence1' of table 'gir.employe'
</code>```

This the SQL of agence table:

```<code>--
-- Base de donnÃ©es :  `gir`
--

-- --------------------------------------------------------

--
-- Structure de la table `agence`
--

CREATE TABLE IF NOT EXISTS `agence` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nom` varchar(150) NOT NULL,
  `nomVoie` varchar(150) NOT NULL,
  `numVoie` int(5) DEFAULT NULL,
  `codePostal` int(5) NOT NULL,
  `comune` varchar(150) NOT NULL,
  `telephone` varchar(150) NOT NULL,
  `fax` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `entreprises_id` int(11) NOT NULL,
  PRIMARY KEY (`id`,`entreprises_id`),
  KEY `fk_agence_entreprises1_idx` (`entreprises_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
</code>```

And this is the SQL of employe table:

```<code>--
-- Base de donnÃ©es :  `enexgir`
--

-- --------------------------------------------------------

--
-- Structure de la table `employe`
--

CREATE TABLE IF NOT EXISTS `employe` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nom` varchar(45) NOT NULL,
  `prenom` varchar(45) NOT NULL,
  `poste` varchar(45) NOT NULL,
  `portable` varchar(45) NOT NULL,
  `ligneDirecte` varchar(45) NOT NULL,
  `faxDirect` varchar(45) NOT NULL,
  `email` varchar(150) NOT NULL,
  `etat` tinyint(1) NOT NULL,
  `agence_id` int(11) NOT NULL,
  PRIMARY KEY (`id`,`agence_id`),
  KEY `fk_employe_agence1_idx` (`agence_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

--
-- Contraintes pour les tables exportÃ©es
--

--
-- Contraintes pour la table `employe`
--
ALTER TABLE `employe`
  ADD CONSTRAINT `fk_employe_agence1` FOREIGN KEY (`agence_id`) REFERENCES `agence` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
</code>```

Someone should why and how to fix this with doctrine?

答:
This Solution is correct: https://stackoverflow.com/a/26628581/2400373

However if you work on Symfony 3, the correct is this:

```<code>bin/console doctrine:schema:update --dump-sql --complete >> dump.sql
</code>```

Never used the instruction php before this instruction.

Title: error1833: cannot change colum id

Body:
With prompt command, I have generated a database with doctine using reverse engineering. It worked perfectly:

php app/console doctrine:mapping:convert yml ./src/Gir/DatabaseBundle/Resources/config/doctrine/metadata/orm --from-database --force

After, I create the entities:

php app/console doctrine:mapping:import GirDatabaseBundle annotation

And the annotations:

php app/console doctrine:generate:entities GirDatabaseBundle

Then, I installed the new update of Symfony with composer.phar.

Then, the FOSUserBundle in order to manage users in my project.

I have to update my database with doctrine using this prompt command in order to generate the table users and the entities, etc:

php app/console doctrine:schema:update --force

When I do this command, doctrine send me this error in the windows prompt command:

**[Doctrine\DBAL\DBALException]**
An exception occured while executing 'ALTER TABLE agence CHANGE id id INT NOT NULL':
SQLSTATE[HY000]: General error: 1833 Cannot change colum 'id': used in a foreign key constraint 'fk_employe_agence1' of table 'gir.employe'

**[PDOException]**
SQLSTATE[HY000]: General error: 1833 Cannot change colum 'id': used in a foreign key constraint 'fk_employe_agence1' of table 'gir.employe'

This the SQL of agence table:

--
-- Base de donnÃ©es :  `gir`
--

-- --------------------------------------------------------

--
-- Structure de la table `agence`
--

CREATE TABLE IF NOT EXISTS `agence` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nom` varchar(150) NOT NULL,
  `nomVoie` varchar(150) NOT NULL,
  `numVoie` int(5) DEFAULT NULL,
  `codePostal` int(5) NOT NULL,
  `comune` varchar(150) NOT NULL,
  `telephone` varchar(150) NOT NULL,
  `fax` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `entreprises_id` int(11) NOT NULL,
  PRIMARY KEY (`id`,`entreprises_id`),
  KEY `fk_agence_entreprises1_idx` (`entreprises_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

And this is the SQL of employe table:

--
-- Base de donnÃ©es :  `enexgir`
--

-- --------------------------------------------------------

--
-- Structure de la table `employe`
--

CREATE TABLE IF NOT EXISTS `employe` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nom` varchar(45) NOT NULL,
  `prenom` varchar(45) NOT NULL,
  `poste` varchar(45) NOT NULL,
  `portable` varchar(45) NOT NULL,
  `ligneDirecte` varchar(45) NOT NULL,
  `faxDirect` varchar(45) NOT NULL,
  `email` varchar(150) NOT NULL,
  `etat` tinyint(1) NOT NULL,
  `agence_id` int(11) NOT NULL,
  PRIMARY KEY (`id`,`agence_id`),
  KEY `fk_employe_agence1_idx` (`agence_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

--
-- Contraintes pour les tables exportÃ©es
--

--
-- Contraintes pour la table `employe`
--
ALTER TABLE `employe`
  ADD CONSTRAINT `fk_employe_agence1` FOREIGN KEY (`agence_id`) REFERENCES `agence` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Someone should why and how to fix this with doctrine?

Body:
This Solution is correct: https://stackoverflow.com/a/26628581/2400373

However if you work on Symfony 3, the correct is this:

bin/console doctrine:schema:update --dump-sql --complete >> dump.sql

Never used the instruction php before this instruction.


问:
cygwin /dev/sd* disk association to hard drive
Under cygwin on Windows 7, how would I certainly determine the hard drive that some path /dev/sd*  corresponds in Windows?

For example, given cygwin path /dev/sdc, which Windows letter drive does it correspond, C:\, D:\, etc.?

The following don't appear available within cygwin; tool lshw, tool parted, path /dev/disk/....

答:
Assuming you are asking how to map Windows Disk to devices:</p>

```<code>$ cat /proc/partitions
major minor  #blocks  name   win-mounts

    8     0 175825944 sda
    8     1 175824896 sda1   C:\
    8    16 1953514582 sdb
    8    17 1953512448 sdb1   E:\
</code>```

Body:
Assuming you are asking how to map Windows Disk to devices:

$ cat /proc/partitions
major minor  #blocks  name   win-mounts

    8     0 175825944 sda
    8     1 175824896 sda1   C:\
    8    16 1953514582 sdb
    8    17 1953512448 sdb1   E:\


问:
jQuery if select is not selected add error
I'm trying to make the <select id="jobCategory"> and job <select id="industry"> fields mandatory by adding a error message.

Not sure if I have to make them also disable in order to do it properly.

My if statement doesn't work for both field.

Error message in red doesn't show.

var maleFemale = '';

$('#submitBtn').click(function() {

  var errors = false;
  if (maleFemale == '') {
    errors = true;
    $('#areYou').css('color', '#F00');
  } else {
    $('#areYou').css('color', '#000');
  }
  if ($("#twitterInput").val() == '' || $("#twitterInput").val() == '@yourname' || $("#twitterInput").val() == '@') {
    errors = true;
    $('#enterTwitterHandle').css('color', '#F00');
  } else {
    $('#enterTwitterHandle').css('color', '#000');
  }

  if ($('#jobCategory option:selected').length == 0) {
    alert('nothing selected');
    $('#enterCategory').css('color', '#F00');
  } else {
    $('#enterCategory').css('color', '#000');
  }

  if ($('#industry option:selected').length == 0) {
    alert('nothing selected');
    $('#enterIndustry').css('color', '#F00');
  } else {
    $('#enterIndustry').css('color', '#000');
  }

  if (!errors) {
    $('body').addClass('submitted');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#submitBtn {
  border: 1px solid red;
}</code>```

Are you...

Male

Female

Enter a Twitter handle

  <input type='text' id='twitterInput' value='@yourname' />

Select your job category

  <select id="jobCategory" class="select">
    <option value="" disabled selected>job category</option>
    <option value="it"> IT</option>
    <option value="finance">Finance</option>
    <option value="hr">HR</option>
    <option value="marketing">Marketing</option>
    <option value="security">Security</option>
    <option value="developer">Developer</option>
    <option value="others">Others</option>
  </select>

Select your industry

  <select id="industry" class="select">
    <option value="" disabled selected>industry</option>
    <option value="retail">Retail</option>
    <option value="travel-transportation">Travel & Transportation</option>
    <option value="telco-media">Telco / Media</option>
    <option value="banking">Banking</option>
    <option value="health-government">Health & Government</option>
    <option value="energy-utilities">Energy & Utilities</option>

  </select>

Discover your AI iD

```

答:
If you change:

```<code>if ($('#jobCategory option:selected').length == 0) {
</code>```

to

```<code>if ($('#jobCategory option:selected').val() == '') {
</code>```

And

```<code>if ($('#industry option:selected').length == 0)
</code>```

to

```<code>if ($('#industry option:selected').val() == '')
</code>```

this should work.

The original one finds the length == '12' (which is not 0) because the text inside the option is 'job category' which is 12 charactors long.

the new one will search for the values instead, which only == ''  on

<option value="" disabled selected>job category</option> which is basically nothing selected.

Working example:

var maleFemale = '';

$('#submitBtn').click(function() {

  var errors = false;
  if (maleFemale == '') {
    errors = true;
    $('#areYou').css('color', '#F00');
  } else {
    $('#areYou').css('color', '#000');
  }
  if ($("#twitterInput").val() == '' || $("#twitterInput").val() == '@yourname' || $("#twitterInput").val() == '@') {
    errors = true;
    $('#enterTwitterHandle').css('color', '#F00');
  } else {
    $('#enterTwitterHandle').css('color', '#000');
  }

  if ($('#jobCategory option:selected').val() == '') {
    alert('nothing selected');
    $('#enterCategory').css('color', '#F00');
  } else {
    $('#enterCategory').css('color', '#000');
  }

  if ($('#industry option:selected').val() == '') {
    alert('nothing selected');
    $('#enterIndustry').css('color', '#F00');
  } else {
    $('#enterIndustry').css('color', '#000');
  }

  if (!errors) {
    $('body').addClass('submitted');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#submitBtn {
  border: 1px solid red;
}</code>```

Are you...

Male

Female

Enter a Twitter handle

  <input type='text' id='twitterInput' value='@yourname' />

Select your job category

  <select id="jobCategory" class="select">
    <option value="" disabled selected>job category</option>
    <option value="it"> IT</option>
    <option value="finance">Finance</option>
    <option value="hr">HR</option>
    <option value="marketing">Marketing</option>
    <option value="security">Security</option>
    <option value="developer">Developer</option>
    <option value="others">Others</option>
  </select>

Select your industry

  <select id="industry" class="select">
    <option value="" disabled selected>industry</option>
    <option value="retail">Retail</option>
    <option value="travel-transportation">Travel & Transportation</option>
    <option value="telco-media">Telco / Media</option>
    <option value="banking">Banking</option>
    <option value="health-government">Health & Government</option>
    <option value="energy-utilities">Energy & Utilities</option>

  </select>

Discover your AI iD

```
</div>
</div>
</p>

<p>An alternative (but not recommended) is to search for the text itself inside the option:selected.</p>

<p>Like this:</p>

```if ($('#jobCategory option:selected').text == 'job category') {
```

Body:
I'm trying to make the <select id="jobCategory"> and job <select id="industry"> fields mandatory by adding a error message.

Not sure if I have to make them also disable in order to do it properly.

My if statement doesn't work for both field.

Error message in red doesn't show.

var maleFemale = '';

$('#submitBtn').click(function() {

  var errors = false;
  if (maleFemale == '') {
    errors = true;
    $('#areYou').css('color', '#F00');
  } else {
    $('#areYou').css('color', '#000');
  }
  if ($("#twitterInput").val() == '' || $("#twitterInput").val() == '@yourname' || $("#twitterInput").val() == '@') {
    errors = true;
    $('#enterTwitterHandle').css('color', '#F00');
  } else {
    $('#enterTwitterHandle').css('color', '#000');
  }

  if ($('#jobCategory option:selected').length == 0) {
    alert('nothing selected');
    $('#enterCategory').css('color', '#F00');
  } else {
    $('#enterCategory').css('color', '#000');
  }

  if ($('#industry option:selected').length == 0) {
    alert('nothing selected');
    $('#enterIndustry').css('color', '#F00');
  } else {
    $('#enterIndustry').css('color', '#000');
  }

  if (!errors) {
    $('body').addClass('submitted');
  }
});

#submitBtn {
  border: 1px solid red;
}

Are you...

Male

Female

Enter a Twitter handle

  <input type='text' id='twitterInput' value='@yourname' />

Select your job category

  <select id="jobCategory" class="select">
    <option value="" disabled selected>job category</option>
    <option value="it"> IT</option>
    <option value="finance">Finance</option>
    <option value="hr">HR</option>
    <option value="marketing">Marketing</option>
    <option value="security">Security</option>
    <option value="developer">Developer</option>
    <option value="others">Others</option>
  </select>

Select your industry

  <select id="industry" class="select">
    <option value="" disabled selected>industry</option>
    <option value="retail">Retail</option>
    <option value="travel-transportation">Travel & Transportation</option>
    <option value="telco-media">Telco / Media</option>
    <option value="banking">Banking</option>
    <option value="health-government">Health & Government</option>
    <option value="energy-utilities">Energy & Utilities</option>

  </select>

Discover your AI iD

Body:
If you change:

if ($('#jobCategory option:selected').length == 0) {

to

if ($('#jobCategory option:selected').val() == '') {

And

if ($('#industry option:selected').length == 0)

to

if ($('#industry option:selected').val() == '')

this should work.

The original one finds the length == '12' (which is not 0) because the text inside the option is 'job category' which is 12 charactors long.

the new one will search for the values instead, which only == ''  on

<option value="" disabled selected>job category</option> which is basically nothing selected.

Working example:

var maleFemale = '';

$('#submitBtn').click(function() {

  var errors = false;
  if (maleFemale == '') {
    errors = true;
    $('#areYou').css('color', '#F00');
  } else {
    $('#areYou').css('color', '#000');
  }
  if ($("#twitterInput").val() == '' || $("#twitterInput").val() == '@yourname' || $("#twitterInput").val() == '@') {
    errors = true;
    $('#enterTwitterHandle').css('color', '#F00');
  } else {
    $('#enterTwitterHandle').css('color', '#000');
  }

  if ($('#jobCategory option:selected').val() == '') {
    alert('nothing selected');
    $('#enterCategory').css('color', '#F00');
  } else {
    $('#enterCategory').css('color', '#000');
  }

  if ($('#industry option:selected').val() == '') {
    alert('nothing selected');
    $('#enterIndustry').css('color', '#F00');
  } else {
    $('#enterIndustry').css('color', '#000');
  }

  if (!errors) {
    $('body').addClass('submitted');
  }
});

#submitBtn {
  border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='form'>
  <p id='areYou'>Are you...</p>
  <div id='maleFemaleSelector'>
    <p class='maleFemaleSelectorBtn transform' id='maleBtn'>Male</p>
    <p class='maleFemaleSelectorBtn transform' id='femaleBtn'>Female</p>
    <div style='clear:both'></div>
  </div>

  <p id='enterTwitterHandle'>Enter a Twitter handle</p>
  <input type='text' id='twitterInput' value='@yourname' />
  <div style='clear:both'></div>

  <p id='enterCategory'>Select your job category</p>
  <select id="jobCategory" class="select">
    <option value="" disabled selected>job category</option>
    <option value="it"> IT</option>
    <option value="finance">Finance</option>
    <option value="hr">HR</option>
    <option value="marketing">Marketing</option>
    <option value="security">Security</option>
    <option value="developer">Developer</option>
    <option value="others">Others</option>
  </select>

  <div style='clear:both'></div>

  <p id='enterIndustry'>Select your industry</p>
  <select id="industry" class="select">
    <option value="" disabled selected>industry</option>
    <option value="retail">Retail</option>
    <option value="travel-transportation">Travel & Transportation</option>
    <option value="telco-media">Telco / Media</option>
    <option value="banking">Banking</option>
    <option value="health-government">Health & Government</option>
    <option value="energy-utilities">Energy & Utilities</option>

  </select>

  <p id='submitBtn'>Discover your AI iD</p>
  <div style='clear:both'></div>
</div>

An alternative (but not recommended) is to search for the text itself inside the option:selected.

Like this:

if ($('#jobCategory option:selected').text == 'job category') {


问:
JavaFX TableColumn.setCellValueFactory() throws null pointer
I got an issue with initializing one of my Tables.
I first start my Program and want to load Data later.

I got the following setup:

Main.java: initializes program and loads all the controllers, this works fine.
It also holds the functionality to load data, if done so it is being stored in a List.

TableViewController.java controlls one Tab of my program containing a TableView.

setMain is called in my Main.java when the program is started.

```<code>@FXML
private TableView<MyObject> tableView;
@FXML
private TableColumn<MyObject, String> columnOne;
@FXML
private TableColumn<MyObject, Integer> columnTwo;
@FXML
private TableColumn<MyObject, String> columnThree;

public void setMain(Main main) {
    this.main = main;
    tableView.setItems(main.getMyObjectObservableList());
}

public void updateContents() {
    columnOne.setCellValueFactory(value->value.getValue().getType());
    columnTwo.setCellValueFactory(value->value.getValue().getTotal().asObject());
    columnThree.setCellValueFactory(value->value.getValue().getTrend());
}
</code>```

I'm getting

```<code>java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException
</code>```

in row of columnOne.SetCellValueFactory;

I used Eclipse debugger and set a breakpoint at the updateContents, my TableView object is filled with data, from being loaded.

Why is the exception thrown?

EDIT1:

FXML:

```<code><TableView fx:id="tableView">
                 <columns>
                    <TableColumn fx:id="columnOne" prefWidth="411.0" text="title" />
                    <TableColumn fx:id="columnTwo" maxWidth="335.0" minWidth="-1.0" prefWidth="188.0" />
                    <TableColumn fx:id="columnThree" maxWidth="335.0" minWidth="-1.0" prefWidth="188.0" />
                 </columns>
              </TableView>
</code>```

Loading FXML:

```<code>    public void initTable() {
    try {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("view/Table.fxml"));
        AnchorPane table = (AnchorPane) loader.load();

        Tab t = new Tab();
        t.setText("Table");
        t.setContent(table);

        mainTabPane.getTabs().add(t);

        tableViewController = loader.getController();
        tableViewController.setMain(this);

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Update Contents:

```<code>public void loadData(File[] files) throws IOException {
//loading data here
myObjectObservableList.add( new MyObject(params));
TableViewController.updateContents();
}
</code>```

答:
The question was answered by fabian in one of the comments to the question itself.

Thanks!

Body:
I got an issue with initializing one of my Tables.
I first start my Program and want to load Data later.

I got the following setup:

Main.java: initializes program and loads all the controllers, this works fine.
It also holds the functionality to load data, if done so it is being stored in a List.

TableViewController.java controlls one Tab of my program containing a TableView.

setMain is called in my Main.java when the program is started.

@FXML
private TableView<MyObject> tableView;
@FXML
private TableColumn<MyObject, String> columnOne;
@FXML
private TableColumn<MyObject, Integer> columnTwo;
@FXML
private TableColumn<MyObject, String> columnThree;

public void setMain(Main main) {
    this.main = main;
    tableView.setItems(main.getMyObjectObservableList());
}

public void updateContents() {
    columnOne.setCellValueFactory(value->value.getValue().getType());
    columnTwo.setCellValueFactory(value->value.getValue().getTotal().asObject());
    columnThree.setCellValueFactory(value->value.getValue().getTrend());
}

I'm getting

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException

in row of columnOne.SetCellValueFactory;

I used Eclipse debugger and set a breakpoint at the updateContents, my TableView object is filled with data, from being loaded.

Why is the exception thrown?

EDIT1:

FXML:

<TableView fx:id="tableView">
                 <columns>
                    <TableColumn fx:id="columnOne" prefWidth="411.0" text="title" />
                    <TableColumn fx:id="columnTwo" maxWidth="335.0" minWidth="-1.0" prefWidth="188.0" />
                    <TableColumn fx:id="columnThree" maxWidth="335.0" minWidth="-1.0" prefWidth="188.0" />
                 </columns>
              </TableView>

Loading FXML:

    public void initTable() {
    try {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("view/Table.fxml"));
        AnchorPane table = (AnchorPane) loader.load();

        Tab t = new Tab();
        t.setText("Table");
        t.setContent(table);

        mainTabPane.getTabs().add(t);

        tableViewController = loader.getController();
        tableViewController.setMain(this);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Update Contents:

public void loadData(File[] files) throws IOException {
//loading data here
myObjectObservableList.add( new MyObject(params));
TableViewController.updateContents();
}


问:
How to export to excel columns in dataGrid which are checked by user
I have a dataTable in c# application which looks like this:

```<code><DataGrid x:Name="dg1" Grid.Column="1" Grid.Row="0"  Grid.RowSpan="2"  SelectionMode="Extended" CanUserAddRows="False" ScrollViewer.VerticalScrollBarVisibility="Auto"  CanUserDeleteRows="False"  SelectedIndex="{Binding SelectedIndex}" VerticalAlignment="Top" AutoGenerateColumns="False"  IsReadOnly="True"    Margin="20,150,20,20" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="" Binding="{Binding no}" Visibility="Hidden" />
            <DataGridTextColumn Header="Issue ID" Binding="{Binding IssueID}" Width="0.4*" />
            <DataGridTextColumn Header="Summary" Binding="{Binding Summary}" Width="0.4*"/>
            <DataGridTextColumn Header="Type" Binding="{Binding Type}" Width="0.4*" />
            <DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="0.4*"/>
            <DataGridTextColumn Header="Label" Binding="{Binding Label}"  Width="0.4*"/>
            <DataGridTextColumn Header="Components" Binding="{Binding Components}" Width="0.4*" />
            <DataGridTextColumn Header="Empty Fields" Binding="{Binding EmptyFields}" Width="0.4*" />
            <DataGridTextColumn Header="Reporter" Binding="{Binding Reporter}" Width="0.4*" />
            <DataGridTextColumn Header="Requester" Binding="{Binding Requester}" Width="0.4*" />
            <DataGridTextColumn Header="Requesting Team" Binding="{Binding RequestingTeam}" Width="0.4*" />
            <DataGridTextColumn Header="Assignee" Binding="{Binding Assignee}" Width="0.4*"/>

        </DataGrid.Columns>

    </DataGrid>
</code>```

I poulate this datagrid by downloading some jsons and parsing them. I want to export the output to excel but provide an option to the user to select the columns to export to excel. Can anyone provide a code or any reference to how this could be done.

答: Figured out the solution on my own. I opened a new form when the export to excel button on this form is clicked. This new form has checkboxes for each column of the table and a button to export the checked boxes to excel. I checked each checkbox in the onclick event of the button and if they are checked then added the respective column to excel.</p>

Body:
I have a dataTable in c# application which looks like this:

<DataGrid x:Name="dg1" Grid.Column="1" Grid.Row="0"  Grid.RowSpan="2"  SelectionMode="Extended" CanUserAddRows="False" ScrollViewer.VerticalScrollBarVisibility="Auto"  CanUserDeleteRows="False"  SelectedIndex="{Binding SelectedIndex}" VerticalAlignment="Top" AutoGenerateColumns="False"  IsReadOnly="True"    Margin="20,150,20,20" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="" Binding="{Binding no}" Visibility="Hidden" />
            <DataGridTextColumn Header="Issue ID" Binding="{Binding IssueID}" Width="0.4*" />
            <DataGridTextColumn Header="Summary" Binding="{Binding Summary}" Width="0.4*"/>
            <DataGridTextColumn Header="Type" Binding="{Binding Type}" Width="0.4*" />
            <DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="0.4*"/>
            <DataGridTextColumn Header="Label" Binding="{Binding Label}"  Width="0.4*"/>
            <DataGridTextColumn Header="Components" Binding="{Binding Components}" Width="0.4*" />
            <DataGridTextColumn Header="Empty Fields" Binding="{Binding EmptyFields}" Width="0.4*" />
            <DataGridTextColumn Header="Reporter" Binding="{Binding Reporter}" Width="0.4*" />
            <DataGridTextColumn Header="Requester" Binding="{Binding Requester}" Width="0.4*" />
            <DataGridTextColumn Header="Requesting Team" Binding="{Binding RequestingTeam}" Width="0.4*" />
            <DataGridTextColumn Header="Assignee" Binding="{Binding Assignee}" Width="0.4*"/>

        </DataGrid.Columns>

    </DataGrid>

I poulate this datagrid by downloading some jsons and parsing them. I want to export the output to excel but provide an option to the user to select the columns to export to excel. Can anyone provide a code or any reference to how this could be done.


问:
AmazonClientException in Application for Amazon ML
I am referring to the following resource to create an Application for doing real time predictions using model I already trained using Amazon ML.

targeted-marketing-java

I had replaced the value with the Name of the model and I have already created an endpoint in my AWS ML Console. But when I execute the main function, I am getting the following exception:

```<code>Exception in thread "main" com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
    at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
    at com.amazonaws.services.machinelearning.AmazonMachineLearningClient.invoke(AmazonMachineLearningClient.java:1983)
    at com.amazonaws.services.machinelearning.AmazonMachineLearningClient.getMLModel(AmazonMachineLearningClient.java:1585)
    at ML.RealtimePredict.lookupEndpoint(RealtimePredict.java:58)
    at ML.RealtimePredict.predict(RealtimePredict.java:45)
    at ML.RealtimePredict.main(RealtimePredict.java:21)
</code>```

This is the program I am using (Java):

```<code>    package ML;

import java.util.HashMap;
import java.util.Map;

import com.amazonaws.services.machinelearning.AmazonMachineLearningClient;
import com.amazonaws.services.machinelearning.model.*;

public class RealtimePredict {
    public static void main(String[] args) {
        String mlModelId = "ModelID--I provided this";

        RealtimePredict rtp = new RealtimePredict(mlModelId);

        // Example meta-data and data
        String metaData = "X1,X2";

        String data = "20,25";
        Map<String, String> record = rtp.parseArgs(
                metaData.trim().split(","), data.trim().split(","));
        PredictResult response = rtp.predict(record);
        System.out.println(response);
    }

    private AmazonMachineLearningClient client;
    private String mlModelId;
    private String predictEndpoint;

    public RealtimePredict(String mlModelId) {
        client = new AmazonMachineLearningClient();
        this.mlModelId = mlModelId;
    }

    private Map<String, String> parseArgs(String[] metaData, String[] data) {
        Map<String, String> record = new HashMap<>();

        for (int i = 0; i < (
                metaData.length < data.length ? metaData.length : data.length); i++) {
            record.put(metaData[i].trim(), data[i].trim());
        }
        return record;
    }

    private PredictResult predict(Map<String, String> record) {
        lookupEndpoint();
        PredictRequest request = new PredictRequest()
                .withMLModelId(mlModelId)
                .withPredictEndpoint(predictEndpoint)
                .withRecord(record);
        return client.predict(request);
    }

    /**
     * finds the realtime endpoint for this ML Model
     */
    private void lookupEndpoint() {
        GetMLModelRequest request = new GetMLModelRequest().withMLModelId(mlModelId);
        GetMLModelResult model = client.getMLModel(request);
        predictEndpoint = model.getEndpointInfo().getEndpointUrl();
    }
}
</code>```

Can someone please help me fix this. I reckon that I need to provide the access key and security key. But I couldn't find much help on how I can do that. Thanks.

答:
The Java code must have credentials to be able to call AWS services. It is searching for these credentials in a few locations until it gives up and print put the above exception.

Please read this documentation about the different locations to set up these credentials: http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html

The best practice is to use the default credential profiles file in the local development, and IAM roles for the instance/container/Lambda when running it in the cloud.

Body:
I am referring to the following resource to create an Application for doing real time predictions using model I already trained using Amazon ML.

targeted-marketing-java

I had replaced the value with the Name of the model and I have already created an endpoint in my AWS ML Console. But when I execute the main function, I am getting the following exception:

Exception in thread "main" com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
    at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
    at com.amazonaws.services.machinelearning.AmazonMachineLearningClient.invoke(AmazonMachineLearningClient.java:1983)
    at com.amazonaws.services.machinelearning.AmazonMachineLearningClient.getMLModel(AmazonMachineLearningClient.java:1585)
    at ML.RealtimePredict.lookupEndpoint(RealtimePredict.java:58)
    at ML.RealtimePredict.predict(RealtimePredict.java:45)
    at ML.RealtimePredict.main(RealtimePredict.java:21)

This is the program I am using (Java):

    package ML;

import java.util.HashMap;
import java.util.Map;

import com.amazonaws.services.machinelearning.AmazonMachineLearningClient;
import com.amazonaws.services.machinelearning.model.*;

public class RealtimePredict {
    public static void main(String[] args) {
        String mlModelId = "ModelID--I provided this";

        RealtimePredict rtp = new RealtimePredict(mlModelId);

        // Example meta-data and data
        String metaData = "X1,X2";

        String data = "20,25";
        Map<String, String> record = rtp.parseArgs(
                metaData.trim().split(","), data.trim().split(","));
        PredictResult response = rtp.predict(record);
        System.out.println(response);
    }

    private AmazonMachineLearningClient client;
    private String mlModelId;
    private String predictEndpoint;

    public RealtimePredict(String mlModelId) {
        client = new AmazonMachineLearningClient();
        this.mlModelId = mlModelId;
    }

    private Map<String, String> parseArgs(String[] metaData, String[] data) {
        Map<String, String> record = new HashMap<>();

        for (int i = 0; i < (
                metaData.length < data.length ? metaData.length : data.length); i++) {
            record.put(metaData[i].trim(), data[i].trim());
        }
        return record;
    }

    private PredictResult predict(Map<String, String> record) {
        lookupEndpoint();
        PredictRequest request = new PredictRequest()
                .withMLModelId(mlModelId)
                .withPredictEndpoint(predictEndpoint)
                .withRecord(record);
        return client.predict(request);
    }

    /**
     * finds the realtime endpoint for this ML Model
     */
    private void lookupEndpoint() {
        GetMLModelRequest request = new GetMLModelRequest().withMLModelId(mlModelId);
        GetMLModelResult model = client.getMLModel(request);
        predictEndpoint = model.getEndpointInfo().getEndpointUrl();
    }
}

Can someone please help me fix this. I reckon that I need to provide the access key and security key. But I couldn't find much help on how I can do that. Thanks.


问:
conversion from NSTimeInterval to hour,minutes,seconds,milliseconds in swift
My code is here:

```<code>func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {

    var ti = NSInteger(interval)
    var ms = ti * 1000
    var seconds = ti % 60
    var minutes = (ti / 60) % 60
    var hours = (ti / 3600)

      return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms)
}
</code>```

in output the milliseconds give wrong result.Please give an idea how to find milliseconds correctly.

答:
Swift 3 solution for iOS 8+, macOS 10.10+ if the zero-padding of the hours doesn't matter:</p>

```<code>func stringFromTime(interval: TimeInterval) -> String {
    let ms = Int(interval.truncatingRemainder(dividingBy: 1) * 1000)
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute, .second]
    return formatter.string(from: interval)! + ".\(ms)"
}

print(stringFromTime(interval: 12345.67)) // "3:25:45.670"
</code>```

Body:
My code is here:

func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {

    var ti = NSInteger(interval)
    var ms = ti * 1000
    var seconds = ti % 60
    var minutes = (ti / 60) % 60
    var hours = (ti / 3600)

      return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms)
}

in output the milliseconds give wrong result.Please give an idea how to find milliseconds correctly.

Body:
Swift 3 solution for iOS 8+, macOS 10.10+ if the zero-padding of the hours doesn't matter:

func stringFromTime(interval: TimeInterval) -> String {
    let ms = Int(interval.truncatingRemainder(dividingBy: 1) * 1000)
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute, .second]
    return formatter.string(from: interval)! + ".\(ms)"
}

print(stringFromTime(interval: 12345.67)) // "3:25:45.670"