问:
Function with dplyr, tidyr and ggplot
How can I make a function that takes a column and uses that in dplyr, tidyr and ggplot?

```<code>df <- data.frame(date_col = c(1,1,2,2,3,4,4,5,5),
                 col_a = c('a','b','a','b','a','a','b','a','b'),
                 val_col = runif(9))
</code>```

How do I write a function takes a parameter param_col instead of the hardcoded col_a

```<code>df %>%
  group_by(date_col, col_a) %>%
  summarise(val_col = sum(val_col)) %>%
  complete(col_a, date_col) %>%
  ggplot(aes(date_col, val_col, color = col_a)) +
  geom_line()
</code>```

The dplyr and ggplot calls work in the code outlined below. But how should the complete call be written? Or should complete_ be used?

Is there a more canonical way of doing this?

```<code>plot_nice_chart <- function(df, param_col) {

  enq_param_col <- enquo(param_col)
  str_param_col <- deparse(substitute(param_col))

  # aggregate data based on group_by_col,
  # explicitly fill in NA's for missing to avoid interpolation
  df %>%
     group_by(!!enq_param_col, date_col) %>%
     summarise(val_col = sum(val_col)) %>%
     complete(<what-should-be-here?>, date_col) %>%
     ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
        geom_line()
}
</code>```

答:
The development version of tidyr, tidyr_0.6.3.9000, now uses tidyeval, so if you want to update to that you could use !! as you did in group_by.

```<code>plot_nice_chart <- function(df, param_col) {

     enq_param_col <- enquo(param_col)
     str_param_col <- deparse(substitute(param_col))
     str_param_col
     df %>%
          group_by(!!enq_param_col, date_col) %>%
          summarise(val_col = sum(val_col)) %>%
          ungroup() %>%
          complete(!!enq_param_col, date_col) %>%
          ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
          geom_line()
}
</code>```

Using the current version, you can use complete_ with variables as strings.

```<code>plot_nice_chart <- function(df, param_col) {

     enq_param_col <- enquo(param_col)
     str_param_col <- deparse(substitute(param_col))

     df %>%
          group_by(!!enq_param_col, date_col) %>%
          summarise(val_col = sum(val_col)) %>%
          ungroup() %>%
          complete_( c(str_param_col, "date_col") ) %>%
          ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
          geom_line()
}
</code>```

Title: Function with dplyr, tidyr and ggplot

Body:
How can I make a function that takes a column and uses that in dplyr, tidyr and ggplot?

df <- data.frame(date_col = c(1,1,2,2,3,4,4,5,5),
                 col_a = c('a','b','a','b','a','a','b','a','b'),
                 val_col = runif(9))

How do I write a function takes a parameter param_col instead of the hardcoded col_a

df %>%
  group_by(date_col, col_a) %>%
  summarise(val_col = sum(val_col)) %>%
  complete(col_a, date_col) %>%
  ggplot(aes(date_col, val_col, color = col_a)) +
  geom_line()

The dplyr and ggplot calls work in the code outlined below. But how should the complete call be written? Or should complete_ be used?

Is there a more canonical way of doing this?

plot_nice_chart <- function(df, param_col) {

  enq_param_col <- enquo(param_col)
  str_param_col <- deparse(substitute(param_col))

  # aggregate data based on group_by_col,
  # explicitly fill in NA's for missing to avoid interpolation
  df %>%
     group_by(!!enq_param_col, date_col) %>%
     summarise(val_col = sum(val_col)) %>%
     complete(<what-should-be-here?>, date_col) %>%
     ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
        geom_line()
}

Body:
The development version of tidyr, tidyr_0.6.3.9000, now uses tidyeval, so if you want to update to that you could use !! as you did in group_by.

plot_nice_chart <- function(df, param_col) {

     enq_param_col <- enquo(param_col)
     str_param_col <- deparse(substitute(param_col))
     str_param_col
     df %>%
          group_by(!!enq_param_col, date_col) %>%
          summarise(val_col = sum(val_col)) %>%
          ungroup() %>%
          complete(!!enq_param_col, date_col) %>%
          ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
          geom_line()
}

Using the current version, you can use complete_ with variables as strings.

plot_nice_chart <- function(df, param_col) {

     enq_param_col <- enquo(param_col)
     str_param_col <- deparse(substitute(param_col))

     df %>%
          group_by(!!enq_param_col, date_col) %>%
          summarise(val_col = sum(val_col)) %>%
          ungroup() %>%
          complete_( c(str_param_col, "date_col") ) %>%
          ggplot(aes_string("date_col", "val_col", color = str_param_col)) +
          geom_line()
}


来源: stackexchange

问:
wrapper function; function that returns function
I am not sure how to write a wrapper function for something that includes magrittr pipe (%>%). I am trying to create a wrapper function that returns addPolyline(), addPolygon() or addCircleMarkers() depending on the layer type but I have not been successful. It seems the answer will be in Hadley's Advanced material but most likely it went over my head. As a simple example, how can I make something like the following example work:

```<code>library(leaflet)

wrapper <- function() {
  myfunc <- function() {addPolylines(data = leaflet::atlStorms2005)}
  return(myfunc)
}

# I want this
leaflet() %>% addTiles() %>% addPolylines(data = leaflet::atlStorms2005)

# but I need a wrapper function
leaflet() %>% addTiles() %>% wrapper()
</code>```

答:
It doesn't seem like you need a function that returns a function. You just need a function that can call other functions.</p>

```<code>wrapper <- function(x) {
  x %>% addPolylines(data = leaflet::atlStorms2005)
}

leaflet() %>% addTiles() %>% wrapper()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am not sure how to write a wrapper function for something that includes magrittr pipe (%>%). I am trying to create a wrapper function that returns addPolyline(), addPolygon() or addCircleMarkers() depending on the layer type but I have not been successful. It seems the answer will be in Hadley's Advanced material but most likely it went over my head. As a simple example, how can I make something like the following example work:

library(leaflet)

wrapper <- function() {
  myfunc <- function() {addPolylines(data = leaflet::atlStorms2005)}
  return(myfunc)
}

# I want this
leaflet() %>% addTiles() %>% addPolylines(data = leaflet::atlStorms2005)

# but I need a wrapper function
leaflet() %>% addTiles() %>% wrapper()

Body:
It doesn't seem like you need a function that returns a function. You just need a function that can call other functions.

wrapper <- function(x) {
  x %>% addPolylines(data = leaflet::atlStorms2005)
}

leaflet() %>% addTiles() %>% wrapper()


问:
R: nls not picking up additional arguments when used in custom function in geom_smooth
This is a question that relates to my earlier question geom_smooth with facet_grid and different fitting functions. In that question, I was trying to use a different fitting function in geom_smooth for each facet in a facet grid for ggplot2. Marco Sandri kindly provided an answer that I am trying to adapt to use user-defined formulas rather than existing formulas (e.g., lm, loess). Here is the my code.

```<code># Load library
library(ggplot2)

# Load data
data(mtcars)

# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
  smooth.call <- match.call()

  if(as.numeric(unique(data$PANEL)) == 6) {
    # Nonlinear regression
    method.name <- eval(parse(text="nls"))
    # Specify formula
    formula <- as.formula("y ~ a * x^b")
    # Add initial parameters
    smooth.call[["start"]] <- c(a = 10, b = -0.5)
  }else{
    # Linear regression
    method.name <- eval(parse(text="lm"))
  }

  # Add function name
  smooth.call[[1]] <- method.name
  # Perform fit
  eval.parent(smooth.call)
}

# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth")
print(p)
</code>```

In this code, I define a function custom.smooth that chooses the model to be fit. In this example, all models are linear regressions except for panel 6, which is a user-defined function y ~ a*x^b. Running this code gives the error:

Warning message: Computation failed in stat_smooth(): singular
  gradient matrix at initial parameter estimates

Nevertheless, when I run nls on the data in panel 6 with these initial parameters I get no such error (i.e., nls(mpg ~ a * disp^b, mtcars %>% filter(gear == 5, am == 1), start = c(a = 10, b = -0.5))). This makes me think that nls isn't seeing the start values I specify. I have also tried specifying these parameters in the geom_smooth function like this:

```<code>p <- p + geom_smooth(method = "custom.smooth", method.args = list(start = c(a = 10, b = -0.5)))
</code>```

but I run into the same issue. Any ideas how I can get my start values to nls? Or is there another reason why the code isn't working?

答:
Here's the solution, which greatly benefited from this post. I don't know why the previous version didn't work, but this seems to work fine.

```<code># Load library
library(ggplot2)

# Load data
data(mtcars)

# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
  smooth.call <- match.call()

  if(as.numeric(unique(data$PANEL)) == 6) {
    # Nonlinear regression
    smooth.call[[1]] <- quote(nls)
    # Specify formula
    smooth.call$formula <- as.formula("y ~ a * x ^ b")
    # Add initial parameters
    smooth.call$start <- c(a = 300, b = -0.5)
  }else{
    # Linear regression
    smooth.call[[1]] <- quote(lm)
  }

  # Perform fit
  eval.parent(smooth.call)
}

# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth", se = FALSE)
print(p)
</code>```

Body:
This is a question that relates to my earlier question geom_smooth with facet_grid and different fitting functions. In that question, I was trying to use a different fitting function in geom_smooth for each facet in a facet grid for ggplot2. Marco Sandri kindly provided an answer that I am trying to adapt to use user-defined formulas rather than existing formulas (e.g., lm, loess). Here is the my code.

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
  smooth.call <- match.call()

  if(as.numeric(unique(data$PANEL)) == 6) {
    # Nonlinear regression
    method.name <- eval(parse(text="nls"))
    # Specify formula
    formula <- as.formula("y ~ a * x^b")
    # Add initial parameters
    smooth.call[["start"]] <- c(a = 10, b = -0.5)
  }else{
    # Linear regression
    method.name <- eval(parse(text="lm"))
  }

  # Add function name
  smooth.call[[1]] <- method.name
  # Perform fit
  eval.parent(smooth.call)
}

# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth")
print(p)

In this code, I define a function custom.smooth that chooses the model to be fit. In this example, all models are linear regressions except for panel 6, which is a user-defined function y ~ a*x^b. Running this code gives the error:

Warning message: Computation failed in stat_smooth(): singular
  gradient matrix at initial parameter estimates

Nevertheless, when I run nls on the data in panel 6 with these initial parameters I get no such error (i.e., nls(mpg ~ a * disp^b, mtcars %>% filter(gear == 5, am == 1), start = c(a = 10, b = -0.5))). This makes me think that nls isn't seeing the start values I specify. I have also tried specifying these parameters in the geom_smooth function like this:

p <- p + geom_smooth(method = "custom.smooth", method.args = list(start = c(a = 10, b = -0.5)))

but I run into the same issue. Any ideas how I can get my start values to nls? Or is there another reason why the code isn't working?

Body:
Here's the solution, which greatly benefited from this post. I don't know why the previous version didn't work, but this seems to work fine.

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
  smooth.call <- match.call()

  if(as.numeric(unique(data$PANEL)) == 6) {
    # Nonlinear regression
    smooth.call[[1]] <- quote(nls)
    # Specify formula
    smooth.call$formula <- as.formula("y ~ a * x ^ b")
    # Add initial parameters
    smooth.call$start <- c(a = 300, b = -0.5)
  }else{
    # Linear regression
    smooth.call[[1]] <- quote(lm)
  }

  # Perform fit
  eval.parent(smooth.call)
}

# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth", se = FALSE)
print(p)


问:
Conditional require file in webpack
I want to bundle the files into my production build only if it is not for DEBUG;

So I've use webpack.DefinePlugin and set the variable DEBUG === true.

Also config webpack.UglifyJsPlugin with default options

And in the js file, I do like this:

```<code>const A = DEBUG === true ? null : require('./some-debug.js');
//do things with A, for example
console.log(A)
</code>```

I checked the final bundle file, A is replaced with null (so DefinePlugin is working fine), but the content of some-debug.js file is still in the bundle js.

Is it possible to let webpack not require the file?

ps:
I think I can use resolve.alias to resolve './some-debug.js' --> undefined. But I want to keep my webpack.config.js generic, dont' want to apply too many resolve.alias entries.

Thanks

答:
It doesn't work with ternary operator.</p>

```<code>let A;
if (DEBUG === true) {
  A = require('./some-debug.js');
}
</code>```

Title: Conditional require file in webpack

Body:
I want to bundle the files into my production build only if it is not for DEBUG;

So I've use webpack.DefinePlugin and set the variable DEBUG === true.

Also config webpack.UglifyJsPlugin with default options

And in the js file, I do like this:

const A = DEBUG === true ? null : require('./some-debug.js');
//do things with A, for example
console.log(A)

I checked the final bundle file, A is replaced with null (so DefinePlugin is working fine), but the content of some-debug.js file is still in the bundle js.

Is it possible to let webpack not require the file?

ps:
I think I can use resolve.alias to resolve './some-debug.js' --> undefined. But I want to keep my webpack.config.js generic, dont' want to apply too many resolve.alias entries.

Thanks

Body:
It doesn't work with ternary operator.

let A;
if (DEBUG === true) {
  A = require('./some-debug.js');
}


问:
RxJs getValue for nested BehaviorSubject object
I'm working with angular 4 and RxJS 5, I have an object with the following structure (with nested subjects, in this example only 2 levels):

```<code>objs = BehaviorSubject<MyObj[]>;

MyObj = {
    prop1: BehaviorSubject<string> = "prop1";
    prop2: BehaviorSubject<string> = "prop2";

    prop1.subscribe(newValue => prop2 = prop1);
}
</code>```

So if I try to output the value of objs I got something like the following:

```<code>console.log(objs.value) =>
    [
    {
        prop1: BehaviorSubject<string>;
        prop2: BehaviorSubject<string>;
        },
    {
        ...
    }]
</code>```

so the result doesn't include the values of prop1 and prop2 but I still have BehaviorSubject at the second level.

Is there a way to get the nested objs value like the following?:

```<code>objs = [{
    prop1: "prop1";
    prop2: "prop2"
 }, {...}]
</code>```

I'm wondering if there's a sort of the knockout ko.toJSON (http://knockoutjs.com/documentation/plugins-mapping.html)

Do you think it is generally a bad practice to have nested BehaviorSubjects or people do it everyday :)?

答:
No, there is nothing builtin that does that.  You could certainly roll your own method.  This might be something you can start with:

```<code>function isPrimitive(obj: any) {
  return obj !== Object(obj);
}

function desubjectify(obj: any) {

  if(isPrimitive(obj)) {
    return obj;
  }

  if(obj instanceof BehaviorSubject) {
    return desubjectify(obj.value);
  }

  let transformed: any = {};
  for(let key of Object.keys(obj).filter(key => !key.startsWith('_'))) {
    let value = obj[key];
    if(value instanceof BehaviorSubject) {
      transformed[key] = desubjectify(value.value);
    } else {
      transformed[key] = desubjectify(value);
    }
  }
  return transformed;
}
</code>```

Nested behavior subjects seems fishy to me but I wouldn't rule it out immediately with out knowing more details.  However, I would recommend you find a good tutorial on ngrx/store and read it.  Anytime people start to work a lot with behavior subjects I would recommend this.

Body:
I'm working with angular 4 and RxJS 5, I have an object with the following structure (with nested subjects, in this example only 2 levels):

objs = BehaviorSubject<MyObj[]>;

MyObj = {
    prop1: BehaviorSubject<string> = "prop1";
    prop2: BehaviorSubject<string> = "prop2";

    prop1.subscribe(newValue => prop2 = prop1);
}

So if I try to output the value of objs I got something like the following:

console.log(objs.value) =>
    [
    {
        prop1: BehaviorSubject<string>;
        prop2: BehaviorSubject<string>;
        },
    {
        ...
    }]

so the result doesn't include the values of prop1 and prop2 but I still have BehaviorSubject at the second level.

Is there a way to get the nested objs value like the following?:

objs = [{
    prop1: "prop1";
    prop2: "prop2"
 }, {...}]

I'm wondering if there's a sort of the knockout ko.toJSON (http://knockoutjs.com/documentation/plugins-mapping.html)

Do you think it is generally a bad practice to have nested BehaviorSubjects or people do it everyday :)?

Body:
No, there is nothing builtin that does that.  You could certainly roll your own method.  This might be something you can start with:

function isPrimitive(obj: any) {
  return obj !== Object(obj);
}

function desubjectify(obj: any) {

  if(isPrimitive(obj)) {
    return obj;
  }

  if(obj instanceof BehaviorSubject) {
    return desubjectify(obj.value);
  }

  let transformed: any = {};
  for(let key of Object.keys(obj).filter(key => !key.startsWith('_'))) {
    let value = obj[key];
    if(value instanceof BehaviorSubject) {
      transformed[key] = desubjectify(value.value);
    } else {
      transformed[key] = desubjectify(value);
    }
  }
  return transformed;
}

Nested behavior subjects seems fishy to me but I wouldn't rule it out immediately with out knowing more details.  However, I would recommend you find a good tutorial on ngrx/store and read it.  Anytime people start to work a lot with behavior subjects I would recommend this.


问:
ADO Text Driver Trimming Leading Space
I'm using ADODB with the Microsoft Text Driver to parse a text file in Excel.

The problem is that some lines of the file have a leading space, and this leading space is getting chopped.

When I do a GetString(,1) on my recordset, a line like:
" description DO NOT USE"

gets trimmed to:

"description DO NOT USE"

...this is problematic because I'm actually parsing a Cisco config file, and the leading space is useful in figuring out if I'm still in the same object or not.

For example with text like:

```<code>object-group network ABC_Group
 network-object host 192.10.24.71
 network-object host 192.10.24.72
 network-object host 192.10.24.20
 network-object host 192.10.24.21
object-group network XYZ_hosts
 network-object host 192.10.24.55
 network-object host 192.10.24.26
</code>```

...I am using the leading space to tell me that I am still in the same object-group.

Any ideas on how to get ADODB to keep the leading space when it reads the text file?

I initially tried using just the FileStreamObject, but discovered that the file I was reading had some lines ending in Chr(13) and some ending in both Chr(13) and Chr(10), which was throwing off the Readline method.

答:
Sorry, earlier version of this answer used C#.  For VBA, you have to do a little more heavy lifting.

If the file is small enough to fit in memory, you could read the whole thing in as a string, and then split it:

```<code>Private Function SplitFileContents(ByVal fileContents As String) As String()

    Dim arrResult() As String
    Dim resultCount As Long
    Dim crPos As Long
    Dim lfPos As Long
    dim endPos As Long

    Do While Len(fileContents) > 0
        crPos = InStr(fileContents, vbCr)
        lfPos = InStr(fileContents, vbLf)

        If crPos = 0 And lfPos = 0 Then
            ReDim Preserve arrResult(0 To resultCount)
            arrResult(resultCount) = fileContents
            resultCount = resultCount + 1
            Exit Do
        ElseIf crPos = 0 Then
            endPos = lfPos
        ElseIf lfPos = 0 Then
            endPos = crPos
        ElseIf crPos < lfPos Then
            endPos = crPos
        Else
            endPos = lfPos
        End If

        If endPos > 1 Then
            ReDim Preserve arrResult(0 To resultCount)
            arrResult(resultCount) = Left$(fileContents, endPos - 1)
            resultCount = resultCount + 1
        End If

        If endPos = Len(fileContents) Then
            fileContents = ""
        Else
            fileContents = Mid$(fileContents, endPos + 1)
        End If
    Loop

    If resultCount = 0 Then
        ReDim arrResult(0 to 0)
        arrResult(0) = ""
    End If

    SplitFileContents = arrResult
End Function
</code>```

Alternatively, there are several possible approaches using the fixed-width format, which would preserve leading spaces.  These articles discuss using the schema.ini file to specify a fixed-width file format:

http://support.microsoft.com/kb/187670

http://office.microsoft.com/en-us/access-help/initializing-the-text-data-source-driver-HP001032166.aspx

ContentLicense: CC BY-SA 2.5

Title: ADO Text Driver Trimming Leading Space

Body:
I'm using ADODB with the Microsoft Text Driver to parse a text file in Excel.

The problem is that some lines of the file have a leading space, and this leading space is getting chopped.

When I do a GetString(,1) on my recordset, a line like:
" description DO NOT USE"

gets trimmed to:

"description DO NOT USE"

...this is problematic because I'm actually parsing a Cisco config file, and the leading space is useful in figuring out if I'm still in the same object or not.

For example with text like:

object-group network ABC_Group
 network-object host 192.10.24.71
 network-object host 192.10.24.72
 network-object host 192.10.24.20
 network-object host 192.10.24.21
object-group network XYZ_hosts
 network-object host 192.10.24.55
 network-object host 192.10.24.26

...I am using the leading space to tell me that I am still in the same object-group.

Any ideas on how to get ADODB to keep the leading space when it reads the text file?

I initially tried using just the FileStreamObject, but discovered that the file I was reading had some lines ending in Chr(13) and some ending in both Chr(13) and Chr(10), which was throwing off the Readline method.

Body:
Sorry, earlier version of this answer used C#.  For VBA, you have to do a little more heavy lifting.

If the file is small enough to fit in memory, you could read the whole thing in as a string, and then split it:

Private Function SplitFileContents(ByVal fileContents As String) As String()

    Dim arrResult() As String
    Dim resultCount As Long
    Dim crPos As Long
    Dim lfPos As Long
    dim endPos As Long

    Do While Len(fileContents) > 0
        crPos = InStr(fileContents, vbCr)
        lfPos = InStr(fileContents, vbLf)

        If crPos = 0 And lfPos = 0 Then
            ReDim Preserve arrResult(0 To resultCount)
            arrResult(resultCount) = fileContents
            resultCount = resultCount + 1
            Exit Do
        ElseIf crPos = 0 Then
            endPos = lfPos
        ElseIf lfPos = 0 Then
            endPos = crPos
        ElseIf crPos < lfPos Then
            endPos = crPos
        Else
            endPos = lfPos
        End If

        If endPos > 1 Then
            ReDim Preserve arrResult(0 To resultCount)
            arrResult(resultCount) = Left$(fileContents, endPos - 1)
            resultCount = resultCount + 1
        End If

        If endPos = Len(fileContents) Then
            fileContents = ""
        Else
            fileContents = Mid$(fileContents, endPos + 1)
        End If
    Loop

    If resultCount = 0 Then
        ReDim arrResult(0 to 0)
        arrResult(0) = ""
    End If

    SplitFileContents = arrResult
End Function

Alternatively, there are several possible approaches using the fixed-width format, which would preserve leading spaces.  These articles discuss using the schema.ini file to specify a fixed-width file format:

http://support.microsoft.com/kb/187670

http://office.microsoft.com/en-us/access-help/initializing-the-text-data-source-driver-HP001032166.aspx


问:
UISearchController search bar overlap first cell when active
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

```<code> -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}
</code>```

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

答:
I managed to resolve this issue by combining RJiryes answer with scroll to top. </p>

```<code>-(void)willPresentSearchController:(UISearchController *)searchController{

     [self.contactsTableView setContentInset:UIEdgeInsetsMake(20, 0, 0, 0)];
     [self.contactsTableView setContentOffset:CGPointMake(0.0f, -self.contactsTableView.contentInset.top) animated:YES];
 }

-(void)willDismissSearchController:(UISearchController *)searchController{

     [self.contactsTableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}
</code>```

Body:
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

 -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

Body:
I managed to resolve this issue by combining RJiryes answer with scroll to top.

-(void)willPresentSearchController:(UISearchController *)searchController{

     [self.contactsTableView setContentInset:UIEdgeInsetsMake(20, 0, 0, 0)];
     [self.contactsTableView setContentOffset:CGPointMake(0.0f, -self.contactsTableView.contentInset.top) animated:YES];
 }

-(void)willDismissSearchController:(UISearchController *)searchController{

     [self.contactsTableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}


问:
How to findout how many number of tuples are there in a GROUP
This is my input

```<code>10001 AMERICAN EXPRESS,TX, Y
10001 BOFA,IL,N
10001 CHASE,NJ,Y
10002 CHASE,IL,Y
10002 BOFA,TX,Y
10002 AMERICAN EXPRESS,NJ,Y
</code>```

10001 AMERICAN EXPRESS,TX, Y
10001 BOFA,IL,N
10001 CHASE,NJ,Y
10002 CHASE,IL,Y
10002 BOFA,TX,Y```
</div>
</div>
</p>
<p>I have to group my using key
Intermediate output</p>
```10001, {(AMERICAN EXPRESS,TX,Y),(BOFA,IL,N),(CHASE,NJ,Y)}
10002, {(CHASE,IL,Y),(BOFA,TX,Y)}
```
<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>10001, {(AMERICAN EXPRESS,TX,Y),(BOFA,IL,N),(CHASE,NJ,Y)}
10002, {(CHASE,IL,Y),(BOFA,TX,Y)}</code>```

Then i have to find out how many keys are there in each group having more than one tuple.

```<code>1001, count(tuples)>1 - count -3
1002, Count(tuples)>1 - count 2
</code>```

Can someone please help me out.

答:
COUNT on the second field to get the counts after grouping and FILTER all groups with a count > 1.</p>

```<code>A = LOAD 'data.txt' USING PigStorage(',') AS (f1:int,f2:chararray,f3:chararray,f4:chararray);
B = GROUP A BY f1;
C = FOREACH B GENERATE group,COUNT(f2) AS Total;
D = FILTER C BY (Total > 1);
DUMP D;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is my input

10001 AMERICAN EXPRESS,TX, Y
10001 BOFA,IL,N
10001 CHASE,NJ,Y
10002 CHASE,IL,Y
10002 BOFA,TX,Y
10002 AMERICAN EXPRESS,NJ,Y

10001 AMERICAN EXPRESS,TX, Y
10001 BOFA,IL,N
10001 CHASE,NJ,Y
10002 CHASE,IL,Y
10002 BOFA,TX,Y

I have to group my using key
Intermediate output

10001, {(AMERICAN EXPRESS,TX,Y),(BOFA,IL,N),(CHASE,NJ,Y)}
10002, {(CHASE,IL,Y),(BOFA,TX,Y)}

10001, {(AMERICAN EXPRESS,TX,Y),(BOFA,IL,N),(CHASE,NJ,Y)}
10002, {(CHASE,IL,Y),(BOFA,TX,Y)}

Then i have to find out how many keys are there in each group having more than one tuple.

1001, count(tuples)>1 - count -3
1002, Count(tuples)>1 - count 2

Can someone please help me out.

Body:
COUNT on the second field to get the counts after grouping and FILTER all groups with a count > 1.

A = LOAD 'data.txt' USING PigStorage(',') AS (f1:int,f2:chararray,f3:chararray,f4:chararray);
B = GROUP A BY f1;
C = FOREACH B GENERATE group,COUNT(f2) AS Total;
D = FILTER C BY (Total > 1);
DUMP D;


问:
Weird scanf behaviour
I was working on a C program and I found a weird behaviour with scanf:

```<code>#include <stdio.h>

int main() {
    int *a, i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        scanf("%u", &a[i]);
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}
</code>```

For 10 input I sent + and the output was like:

```<code>1
0
239646720
32767
0
0
239646727
32767
239646771
32767
</code>```

I expected a memory leak, could any one please explain me this behaviour ?

答:
Since you're not allocating any memory dynamically, you will not get a memory leak. You are, however, accessing unallocated memory, which is not the same as a memory leak.

I'm not sure what you're trying to accomplish by entering a +, but the behavior of using an uninitialized pointer is undefined.

Title: Weird scanf behaviour

Body:
I was working on a C program and I found a weird behaviour with scanf:

#include <stdio.h>

int main() {
    int *a, i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        scanf("%u", &a[i]);
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}

For 10 input I sent + and the output was like:

1
0
239646720
32767
0
0
239646727
32767
239646771
32767

I expected a memory leak, could any one please explain me this behaviour ?


问:
wxPython: Network Graph - clickable with context menu - Any pkgs?
Hi
I would like to create a wxpython application with a window where I can create a network graph.  I have heard (never used) of graphviz and NetworkX, but it seems to me that they only creates graph given some input data.  I would like to do the opposite - i.e., create drag and drop nodes and links from a pallete menu.  The nodes and links should be right-clickable with context menu popups. Eg., I should be able to right click a node and click "properties" in context menu - where I can fill in ip address, number of ports, their mac addresses etc.  </p>

<p>I believe graphviz will not allow me to do that.  Is there any good package to do this ?  Must be free / open-source. </p>

答:
Take a look at the wx.lib.ogl package.  It has the basics of what you would need to build diagrams of shapes, labels, lines, arrows, etc. and you can allow the user to interact with them to move them around the window, etc.  It is not perfect, but people are using it for this type of thing quite a bit.

Another possibility for you might be wx.lib.floatcanvas.  They both have their strengths and weaknesses, so it really depends on which is the best fit for your needs.

Body:
Hi
I would like to create a wxpython application with a window where I can create a network graph.  I have heard (never used) of graphviz and NetworkX, but it seems to me that they only creates graph given some input data.  I would like to do the opposite - i.e., create drag and drop nodes and links from a pallete menu.  The nodes and links should be right-clickable with context menu popups. Eg., I should be able to right click a node and click "properties" in context menu - where I can fill in ip address, number of ports, their mac addresses etc.

I believe graphviz will not allow me to do that.  Is there any good package to do this ?  Must be free / open-source.


问:
Generic Static Class as Service Locator
I am applying the Service Locator pattern as described in Game Programming Patterns, and am wondering about a possible generic implementation. The following code does work, but I am confused about using a class that is both generic and static.

The idea of the following C# code is to provide a "global" service to other parts of the application, exposing only an interface rather than the full implementation. Each service registered using this method will only have one instance in the application, but I want to be able to easily swap in/out different implementations of the provided interfaces.

My question is: when I use the following class to provide different services throughout my application, how does C# know that I am referring to different services of different types? Intuitively, I would almost think that the static variable, _service, would be overridden with each new service.

```<code>public static class ServiceLocator<T>
{
    static T _service;

    public static T GetService()
    {
        return _service;
    }

    public static void Provide(T service)
    {
        _service = service;
    }
}
</code>```

Here's some usage:

```<code>// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();
</code>```

答:
I use this for cases where I can't use dependency injection all the way down (like WebForms) but I want to write testable classes that are resolved by a DI container.

The usage looks like

```<code>using(var resolved = new ResolvedService<ISomeService>())
{
    resolved.Service.DoSomething();
}
</code>```

The good:

You can use a DI container to resolve and release resources

It's disposable, and disposing causes the container to release the resources

It keeps the container and service registrations out of sight

The bad:

It requires a static class, but that's also in the composition root so it's not too bad.

As written it depends directly on Windsor. It's easy to replace that with any other container. Maybe one day I'll break this apart so that ServiceLocator isn't coupled to any particular container. But for now it's trivial to change that.

Using this means that while the larger component (like an .aspx page) isn't testable, what I inject into it is testable. It just gave me a crazy thought - I could write orchestrators for WebForms pages so that they're mostly testable. But hopefully I'll never need to do that.

```<code>internal class ServiceLocator
{
    private static IWindsorContainer _container;

    internal static void Initialize(IWindsorContainer container)
    {
        _container = container;
    }
    internal static TService Resolve<TService>(string key = null)
    {
        if (_container == null)
        {
            throw new InvalidOperationException(
                "ServiceLocator must be initialized with a container by calling Initialize(container).");
        }
        try
        {
            return string.IsNullOrEmpty(key)
                ? _container.Resolve<TService>()
                : _container.Resolve<TService>(key);
        }
        catch (ComponentNotFoundException ex)
        {
            throw new InvalidOperationException(string.Format("No component for {0} has been registered.", typeof(TService).FullName), ex);
        }
    }

    internal static void Release(object resolved)
    {
        _container.Release(resolved);
    }
}

public class ResolvedService<TService> : IDisposable
{
    private bool _disposed;

    private readonly TService _resolvedInstance;

    public TService Service
    {
        get { return _resolvedInstance; }
    }

    public ResolvedService(string key = null)
    {
        _resolvedInstance = ServiceLocator.Resolve<TService>(key);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~ResolvedService()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        ServiceLocator.Release(_resolvedInstance);
        _disposed = true;
    }
}
</code>```

Title: Generic Static Class as Service Locator

Body:
I am applying the Service Locator pattern as described in Game Programming Patterns, and am wondering about a possible generic implementation. The following code does work, but I am confused about using a class that is both generic and static.

The idea of the following C# code is to provide a "global" service to other parts of the application, exposing only an interface rather than the full implementation. Each service registered using this method will only have one instance in the application, but I want to be able to easily swap in/out different implementations of the provided interfaces.

My question is: when I use the following class to provide different services throughout my application, how does C# know that I am referring to different services of different types? Intuitively, I would almost think that the static variable, _service, would be overridden with each new service.

public static class ServiceLocator<T>
{
    static T _service;

    public static T GetService()
    {
        return _service;
    }

    public static void Provide(T service)
    {
        _service = service;
    }
}

Here's some usage:

// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();

Body:
I use this for cases where I can't use dependency injection all the way down (like WebForms) but I want to write testable classes that are resolved by a DI container.

The usage looks like

using(var resolved = new ResolvedService<ISomeService>())
{
    resolved.Service.DoSomething();
}

The good:

You can use a DI container to resolve and release resources

It's disposable, and disposing causes the container to release the resources

It keeps the container and service registrations out of sight

The bad:

It requires a static class, but that's also in the composition root so it's not too bad.

As written it depends directly on Windsor. It's easy to replace that with any other container. Maybe one day I'll break this apart so that ServiceLocator isn't coupled to any particular container. But for now it's trivial to change that.

Using this means that while the larger component (like an .aspx page) isn't testable, what I inject into it is testable. It just gave me a crazy thought - I could write orchestrators for WebForms pages so that they're mostly testable. But hopefully I'll never need to do that.

internal class ServiceLocator
{
    private static IWindsorContainer _container;

    internal static void Initialize(IWindsorContainer container)
    {
        _container = container;
    }
    internal static TService Resolve<TService>(string key = null)
    {
        if (_container == null)
        {
            throw new InvalidOperationException(
                "ServiceLocator must be initialized with a container by calling Initialize(container).");
        }
        try
        {
            return string.IsNullOrEmpty(key)
                ? _container.Resolve<TService>()
                : _container.Resolve<TService>(key);
        }
        catch (ComponentNotFoundException ex)
        {
            throw new InvalidOperationException(string.Format("No component for {0} has been registered.", typeof(TService).FullName), ex);
        }
    }

    internal static void Release(object resolved)
    {
        _container.Release(resolved);
    }
}

public class ResolvedService<TService> : IDisposable
{
    private bool _disposed;

    private readonly TService _resolvedInstance;

    public TService Service
    {
        get { return _resolvedInstance; }
    }

    public ResolvedService(string key = null)
    {
        _resolvedInstance = ServiceLocator.Resolve<TService>(key);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~ResolvedService()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        ServiceLocator.Release(_resolvedInstance);
        _disposed = true;
    }
}


问:
How can I limit a TextView's size without using 'maxwidth'?
I've been trying to create a layout for a RecyclerView item, but I'm, having trouble getting there. I'll try my best to explain what I want and what I've gotten so far.
My design has a Button, a TextView, a couple of ImageViews and a LinearLayout with some ImageViews inside it. The image below explains it well.

The gray elements have fixed width and position (the button to the left and the LL with ivs to the right).

The green and red ivs have fixed width but should be positioned to the right of the blue tv, UNLESS the blue tv is too big and tries to push them on top of the gray LL to the right. In that case, the text is cut short and an ellipsis is added at the end.

The green and red ivs may or may not be visible (visibility="true" or "gone"). The blue tv should occupy their spaces if they're "gone" (and if there's enough text content in it to do so).

I've gotten sort of close to what I want: the blue tv and the red and green ivs are inside a LinearLayout with a gravity=left attribute. The blue tv has the ellipsis=end attribute. The one thing that's still wrong is the blue tv has to have a maxwidth attribute so it does not push the green/red ivs over the gray LinearLayout to the right. So, when the red or green ivs are "gone", there's an empty space to the right (before the gray LinearLayout) since the blue tv's maxwidth limits it.

Is there a way to achieve this? How can I eliminate the maxwidth attribute and still prevent the textview content from pushing the green and red ivs too far to the right and overruning the gray LinearLayout?

I don't have any experience with ConstraintLayout (and am a beginner in android development). Is there a way to achieve this using it?

Here's the code I have so far.

```<code><LinearLayout
    android:id="@+id/leiaute"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <Button
        android:id="@+id/quad_done_undone"
        android:layout_width="17.6dp"
        android:layout_height="16dp"
        android:layout_marginLeft="14dp"
        android:src="@drawable/circulo_unchecked"/>

    <LinearLayout
        android:id="@+id/itemClickableArea"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:gravity="left|center_vertical"
        android:orientation="horizontal"
        android:background="?attr/selectableItemBackground">

        <TextView
            android:id="@+id/titulo"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:ellipsize="end"
            android:fontFamily="sans-serif"
            android:gravity="left|center_vertical"
            android:maxLines="1"
            android:maxWidth="210dp"
            android:text="Lorem Ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
            android:textColor="@color/preto"
            android:textSize="13sp"
            android:visibility="visible"/>

        <ImageButton
            android:id="@+id/descricao"
            android:layout_width="16dp"
            android:layout_height="13.5dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="1dp"
            android:background="@drawable/description_icon"/>

        <ImageView
            android:id="@+id/play"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:src="@drawable/play"
            android:tint="@color/cinza3"
            android:visibility="visible"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="36dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dp"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/data_hora"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:fontFamily="sans-serif"
            android:gravity="center"
            android:maxLines="2"
            android:textColor="@color/textList"
            android:textSize="12sp"
            tools:text="31 mar\n9:42"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/repeat"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginRight="2dp"
                android:src="@drawable/repeat"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/locale"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:src="@drawable/locale"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/alarm"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginLeft="2dp"
                android:src="@drawable/alarm"
                android:tint="@color/iconesList"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</code>```

答:
Add this layout in your res

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<Button
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:background="#757575"
    android:text="bt" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="60dp"
    android:layout_weight="1"
    android:gravity="left"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:singleLine="true"
        android:text="Lorem Ipsum is simple. Lorem Ipsum is simple. Lorem Ipsum is simple." />

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="#4CAF50" />

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="#F44336" />
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:background="#757575"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Linear layout"
        android:textAlignment="center"
        android:textColor="#FFFFFF" />
</LinearLayout>
</code>```

Then try this command in your code:

```<code>    TextView textView = (TextView) findViewById(R.id.content);
    int screenWidth = yourScreenWidth();
    int buttonWidth = buttonLeft.getWidth();
    int linearlayoutWidth = linearlayoutRight.getWidth();
    int greeenIvWidth = greenIv.getVisibility() == View.VISIBLE ? greenIv.getWidth() : 0;
    int redIvWidth = redIv.getVisibility() == View.VISIBLE ? redIv.getWidth() : 0;
    textView.setMaxWidth(screenWidth - buttonWidth - linearlayoutWidth - greeenIvWidth - redIvWidth);
</code>```

I just calculate maxWidth of TextView, so it will be matched your conditions

2 green/red ImageView is on the right of your TextView when your content is short

TextView will take all the space if the content is long.

Body:
I've been trying to create a layout for a RecyclerView item, but I'm, having trouble getting there. I'll try my best to explain what I want and what I've gotten so far.
My design has a Button, a TextView, a couple of ImageViews and a LinearLayout with some ImageViews inside it. The image below explains it well.

The gray elements have fixed width and position (the button to the left and the LL with ivs to the right).

The green and red ivs have fixed width but should be positioned to the right of the blue tv, UNLESS the blue tv is too big and tries to push them on top of the gray LL to the right. In that case, the text is cut short and an ellipsis is added at the end.

The green and red ivs may or may not be visible (visibility="true" or "gone"). The blue tv should occupy their spaces if they're "gone" (and if there's enough text content in it to do so).

I've gotten sort of close to what I want: the blue tv and the red and green ivs are inside a LinearLayout with a gravity=left attribute. The blue tv has the ellipsis=end attribute. The one thing that's still wrong is the blue tv has to have a maxwidth attribute so it does not push the green/red ivs over the gray LinearLayout to the right. So, when the red or green ivs are "gone", there's an empty space to the right (before the gray LinearLayout) since the blue tv's maxwidth limits it.

Is there a way to achieve this? How can I eliminate the maxwidth attribute and still prevent the textview content from pushing the green and red ivs too far to the right and overruning the gray LinearLayout?

I don't have any experience with ConstraintLayout (and am a beginner in android development). Is there a way to achieve this using it?

Here's the code I have so far.

<LinearLayout
    android:id="@+id/leiaute"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <Button
        android:id="@+id/quad_done_undone"
        android:layout_width="17.6dp"
        android:layout_height="16dp"
        android:layout_marginLeft="14dp"
        android:src="@drawable/circulo_unchecked"/>

    <LinearLayout
        android:id="@+id/itemClickableArea"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:gravity="left|center_vertical"
        android:orientation="horizontal"
        android:background="?attr/selectableItemBackground">

        <TextView
            android:id="@+id/titulo"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:ellipsize="end"
            android:fontFamily="sans-serif"
            android:gravity="left|center_vertical"
            android:maxLines="1"
            android:maxWidth="210dp"
            android:text="Lorem Ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
            android:textColor="@color/preto"
            android:textSize="13sp"
            android:visibility="visible"/>

        <ImageButton
            android:id="@+id/descricao"
            android:layout_width="16dp"
            android:layout_height="13.5dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="1dp"
            android:background="@drawable/description_icon"/>

        <ImageView
            android:id="@+id/play"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:src="@drawable/play"
            android:tint="@color/cinza3"
            android:visibility="visible"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="36dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dp"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/data_hora"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:fontFamily="sans-serif"
            android:gravity="center"
            android:maxLines="2"
            android:textColor="@color/textList"
            android:textSize="12sp"
            tools:text="31 mar\n9:42"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/repeat"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginRight="2dp"
                android:src="@drawable/repeat"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/locale"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:src="@drawable/locale"
                android:tint="@color/iconesList"/>

            <ImageView
                android:id="@+id/alarm"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:layout_marginLeft="2dp"
                android:src="@drawable/alarm"
                android:tint="@color/iconesList"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Body:
Add this layout in your res

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<Button
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:background="#757575"
    android:text="bt" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="60dp"
    android:layout_weight="1"
    android:gravity="left"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:singleLine="true"
        android:text="Lorem Ipsum is simple. Lorem Ipsum is simple. Lorem Ipsum is simple." />

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="#4CAF50" />

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="#F44336" />
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:background="#757575"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Linear layout"
        android:textAlignment="center"
        android:textColor="#FFFFFF" />
</LinearLayout>

Then try this command in your code:

    TextView textView = (TextView) findViewById(R.id.content);
    int screenWidth = yourScreenWidth();
    int buttonWidth = buttonLeft.getWidth();
    int linearlayoutWidth = linearlayoutRight.getWidth();
    int greeenIvWidth = greenIv.getVisibility() == View.VISIBLE ? greenIv.getWidth() : 0;
    int redIvWidth = redIv.getVisibility() == View.VISIBLE ? redIv.getWidth() : 0;
    textView.setMaxWidth(screenWidth - buttonWidth - linearlayoutWidth - greeenIvWidth - redIvWidth);

I just calculate maxWidth of TextView, so it will be matched your conditions

2 green/red ImageView is on the right of your TextView when your content is short

TextView will take all the space if the content is long.


问:
Get max value from a map with keys corresponding to a list in Java 7
I have a Map<String, Double> and a List<String>.

The list actually contains possible keys for the map.
Now, I want the max value in the map corresponding to the list of keys.

For eg:

Map

(a, 3),
  (b, 4),
  (c, 5),
  (d, 6),
  (e, 7)

List

b,
  d

Output should be = 6

Current solution:

```<code>public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    Double maxDiscount = 0d;

    for (String key : list) {
        Double discount = map.get(key);
        if (discount > maxDiscount) {
            maxDiscount = discount;
        }
    }
    return maxDiscount;
}
</code>```

How can I do it more efficiently?

答:
Simple approach:

```<code>    Double max = 0.; //Or your min value (-Double.MAX_VALUE if negatives are allowed)
    for(String key : keyList) {
        if(hashmap.contains(key) && hashmap.get(key) > max)
            max = hashmap.get(key);
    }
    System.out.println(max);
</code>```

You can use streams, but I don't think it's really a better solution (terribly difficult to read, and you'd have to use Java 8):

```<code>System.out.print(
               hashmap.entrySet().stream()
                  .filter(entry -> keyList.contains(entry.getKey()))
                  .max((p1, p2) -> Double.compare( p1.getValue(), p2.getValue()))
                  .get()
                  .getValue()
       );
</code>```

Body:
I have a Map<String, Double> and a List<String>.

The list actually contains possible keys for the map.
Now, I want the max value in the map corresponding to the list of keys.

For eg:

Map

(a, 3),
  (b, 4),
  (c, 5),
  (d, 6),
  (e, 7)

List

b,
  d

Output should be = 6

Current solution:

public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    Double maxDiscount = 0d;

    for (String key : list) {
        Double discount = map.get(key);
        if (discount > maxDiscount) {
            maxDiscount = discount;
        }
    }
    return maxDiscount;
}

How can I do it more efficiently?

Body:
Simple approach:

    Double max = 0.; //Or your min value (-Double.MAX_VALUE if negatives are allowed)
    for(String key : keyList) {
        if(hashmap.contains(key) && hashmap.get(key) > max)
            max = hashmap.get(key);
    }
    System.out.println(max);

You can use streams, but I don't think it's really a better solution (terribly difficult to read, and you'd have to use Java 8):

System.out.print(
               hashmap.entrySet().stream()
                  .filter(entry -> keyList.contains(entry.getKey()))
                  .max((p1, p2) -> Double.compare( p1.getValue(), p2.getValue()))
                  .get()
                  .getValue()
       );


问:
How to splice onto socketfd?
The manual mentioned splice() can transfer data between two arbitrary filedescriptors, also onto a socketfd. This works if the file is send at once. Therefore the filesize has to be lower than PIPE_BUF_SZ (=65536).

But, how to handle bigger files? I want to understand the difference to sendfile() syscall. How would you rewrite the sendfile() syscall?

The second splice returns with Invalid argument. I guess it is because the socketfd is not seekable.

```<code>size_t len = 800000; //e.g.
static int do_copy(int in_fd, int out_fd)
{
    loff_t in_off = 0, out_off = 0;
    static int buf_size = 65536;
    off_t len;
    int filedes[2];
    int err = -1;

    if(pipe(filedes) < 0) {
        perror("pipe:");
        goto out;
    }

    while(len > 0) {
        if(buf_size > len) buf_size = len;
        /* move to pipe buffer. */
        err = splice(in_fd, &in_off, filedes[1], NULL, buf_size, SPLICE_F_MOVE | SPLICE_F_MORE);
        if(err < 0) {
            perror("splice:");
            goto out_close;
        }
        /* move from pipe buffer to out_fd */
        err = splice(filedes[0], NULL, out_fd, &out_off, buf_size, SPLICE_F_MOVE | SPLICE_F_MORE);
        if(err < 0) {
            perror("splice2:");
            goto out_close;
        }
        len -= buf_size;
    }
    err = 0;
    out_close:
    close(filedes[0]);
    close(filedes[1]);

    out:
    return err;
}
</code>```

答:
sendfile() systemcall does not check if the filedescriptor is seekable. The only check onto that fd is, if you can read (FMODE_READ) onto the fd.

splice() does some more checks. Among others, if the fd is seekable (FMODE_PREAD) / (FMODE_PWRITE).

That's why sendfile works, but splice won't.

Title: How to splice onto socketfd?

Body:
The manual mentioned splice() can transfer data between two arbitrary filedescriptors, also onto a socketfd. This works if the file is send at once. Therefore the filesize has to be lower than PIPE_BUF_SZ (=65536).

But, how to handle bigger files? I want to understand the difference to sendfile() syscall. How would you rewrite the sendfile() syscall?

The second splice returns with Invalid argument. I guess it is because the socketfd is not seekable.

size_t len = 800000; //e.g.
static int do_copy(int in_fd, int out_fd)
{
    loff_t in_off = 0, out_off = 0;
    static int buf_size = 65536;
    off_t len;
    int filedes[2];
    int err = -1;

    if(pipe(filedes) < 0) {
        perror("pipe:");
        goto out;
    }

    while(len > 0) {
        if(buf_size > len) buf_size = len;
        /* move to pipe buffer. */
        err = splice(in_fd, &in_off, filedes[1], NULL, buf_size, SPLICE_F_MOVE | SPLICE_F_MORE);
        if(err < 0) {
            perror("splice:");
            goto out_close;
        }
        /* move from pipe buffer to out_fd */
        err = splice(filedes[0], NULL, out_fd, &out_off, buf_size, SPLICE_F_MOVE | SPLICE_F_MORE);
        if(err < 0) {
            perror("splice2:");
            goto out_close;
        }
        len -= buf_size;
    }
    err = 0;
    out_close:
    close(filedes[0]);
    close(filedes[1]);

    out:
    return err;
}


问:
How does this JS code look like in if...else format?
How would the following be written in an if/else format?

```<code>hours == 0 ? 12 : (hours > 12) ? hours - 12 : hours
</code>```

答:
```<code>if (hours == 0) {
  return 12;
} else if (hours > 12) {
  return hours - 12;
} else {
  return hours;
}
</code>```

Ideally, you should also use '===' operator instead of '=='.

Body:
How would the following be written in an if/else format?

hours == 0 ? 12 : (hours > 12) ? hours - 12 : hours

Body:
if (hours == 0) {
  return 12;
} else if (hours > 12) {
  return hours - 12;
} else {
  return hours;
}

Ideally, you should also use '===' operator instead of '=='.


问:
How can I rotate an image by any degree?
I have animated gif and I'm using a class to parse the images(frames) from it.
The class is:

```<code>using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.IO;

public class AnimatedGif
{
    private List<AnimatedGifFrame> mImages = new List<AnimatedGifFrame>();
    public AnimatedGif(string path)
    {
        Image img = Image.FromFile(path);
        int frames = img.GetFrameCount(FrameDimension.Time);
        if (frames <= 1) throw new ArgumentException("Image not animated");
        byte[] times = img.GetPropertyItem(0x5100).Value;
        int frame = 0;
        for (; ; )
        {
            int dur = BitConverter.ToInt32(times, 4 * frame);
            mImages.Add(new AnimatedGifFrame(new Bitmap(img), dur));
            if (++frame >= frames) break;
            img.SelectActiveFrame(FrameDimension.Time, frame);
        }
        img.Dispose();
    }
    public List<AnimatedGifFrame> Images { get { return mImages; } }
}

public class AnimatedGifFrame
{
    private int mDuration;
    private Image mImage;
    internal AnimatedGifFrame(Image img, int duration)
    {
        mImage = img; mDuration = duration;
    }
    public Image Image { get { return mImage; } }
    public int Duration { get { return mDuration; } }
}
</code>```

Now in form1 I loop over the frames in this case 4 and I want to rotate the animation by any degree. Now its rotating each 45 or 90 degrees. I want to add more frames(images) to the animation so if I set the rotation to 31 or to 10 degrees so I will see the animation rotating in 10 degrees.

This is the code in Form1 which is not working good. I'm using a function for the rotation which I didn't test yet if its any working.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AnimatedGifEditor
{
    public partial class Form1 : Form
    {
        Image myImage;
        AnimatedGif myGif;
        Bitmap bitmap;

        public Form1()
        {
            InitializeComponent();

            myImage = Image.FromFile(@"D:\fananimation.gif");
            myGif = new AnimatedGif(@"D:\fananimation.gif");
            for (int i = 0; i < myGif.Images.Count; i++)
            {
                pictureBox1.Image = myGif.Images[3].Image;
                bitmap = new Bitmap(pictureBox1.Image);
                rotateImage(bitmap, 76);
                pictureBox1.Image = bitmap;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

private Bitmap RotateImg(Bitmap bmp, float angle, Color bkColor)
    {
        int w = bmp.Width;
        int h = bmp.Height;
        bmp.PixelFormat pf = default(bmp.PixelFormat);
        if (bkColor == Color.Transparent)
        {
            pf = bmp.Format32bppArgb;
        }
        else
        {
            pf = bmp.PixelFormat;
        }

        Bitmap tempImg = new Bitmap(w, h, pf);
        Graphics g = Graphics.FromImage(tempImg);
        g.Clear(bkColor);
        g.DrawImageUnscaled(bmp, 1, 1);
        g.Dispose();

        GraphicsPath path = new GraphicsPath();
        path.AddRectangle(new RectangleF(0f, 0f, w, h));
        Matrix mtrx = new Matrix();
        //Using System.Drawing.Drawing2D.Matrix class
        mtrx.Rotate(angle);
        RectangleF rct = path.GetBounds(mtrx);
        Bitmap newImg = new Bitmap(Convert.ToInt32(rct.Width), Convert.ToInt32(rct.Height), pf);
        g = Graphics.FromImage(newImg);
        g.Clear(bkColor);
        g.TranslateTransform(-rct.X, -rct.Y);
        g.RotateTransform(angle);
        g.InterpolationMode = InterpolationMode.HighQualityBilinear;
        g.DrawImageUnscaled(tempImg, 0, 0);
        g.Dispose();
        tempImg.Dispose();
        return newImg;
    }
    }
}
</code>```

The animated gif I'm using for the test can be found here:

答:
I tried the answer of @Omar myself and realized, that the original image gets cut at the sides ... i've rewritten it so it resizes the image to the new sizes:

```<code>private static Bitmap RotateImage(Bitmap bmp, float angle)
{
    float alpha = angle;

    //edit: negative angle +360
    while(alpha <0) alpha +=360;

    float gamma = 90;
    float beta = 180 - angle - gamma;

    float c1 = bmp.Height;
    float a1 = (float)(c1 * Math.Sin(alpha * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));
    float b1 = (float)(c1 * Math.Sin(beta * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));

    float c2 = bmp.Width;
    float a2 = (float)(c2 * Math.Sin(alpha * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));
    float b2 = (float)(c2 * Math.Sin(beta * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));

    int width = Convert.ToInt32(b2 + a1);
    int height = Convert.ToInt32(b1 + a2);

    Bitmap rotatedImage = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(rotatedImage))
    {
        g.TranslateTransform(rotatedImage.Width / 2, rotatedImage.Height / 2); //set the rotation point as the center into the matrix
        g.RotateTransform(angle); //rotate
        g.TranslateTransform(-rotatedImage.Width / 2, -rotatedImage.Height / 2); //restore rotation point into the matrix
        g.DrawImage(bmp, new Point((width - bmp.Width) / 2, (height - bmp.Height) / 2)); //draw the image on the new bitmap
    }
    return rotatedImage;
}
</code>```

Body:
I have animated gif and I'm using a class to parse the images(frames) from it.
The class is:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.IO;

public class AnimatedGif
{
    private List<AnimatedGifFrame> mImages = new List<AnimatedGifFrame>();
    public AnimatedGif(string path)
    {
        Image img = Image.FromFile(path);
        int frames = img.GetFrameCount(FrameDimension.Time);
        if (frames <= 1) throw new ArgumentException("Image not animated");
        byte[] times = img.GetPropertyItem(0x5100).Value;
        int frame = 0;
        for (; ; )
        {
            int dur = BitConverter.ToInt32(times, 4 * frame);
            mImages.Add(new AnimatedGifFrame(new Bitmap(img), dur));
            if (++frame >= frames) break;
            img.SelectActiveFrame(FrameDimension.Time, frame);
        }
        img.Dispose();
    }
    public List<AnimatedGifFrame> Images { get { return mImages; } }
}

public class AnimatedGifFrame
{
    private int mDuration;
    private Image mImage;
    internal AnimatedGifFrame(Image img, int duration)
    {
        mImage = img; mDuration = duration;
    }
    public Image Image { get { return mImage; } }
    public int Duration { get { return mDuration; } }
}

Now in form1 I loop over the frames in this case 4 and I want to rotate the animation by any degree. Now its rotating each 45 or 90 degrees. I want to add more frames(images) to the animation so if I set the rotation to 31 or to 10 degrees so I will see the animation rotating in 10 degrees.

This is the code in Form1 which is not working good. I'm using a function for the rotation which I didn't test yet if its any working.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AnimatedGifEditor
{
    public partial class Form1 : Form
    {
        Image myImage;
        AnimatedGif myGif;
        Bitmap bitmap;

        public Form1()
        {
            InitializeComponent();

            myImage = Image.FromFile(@"D:\fananimation.gif");
            myGif = new AnimatedGif(@"D:\fananimation.gif");
            for (int i = 0; i < myGif.Images.Count; i++)
            {
                pictureBox1.Image = myGif.Images[3].Image;
                bitmap = new Bitmap(pictureBox1.Image);
                rotateImage(bitmap, 76);
                pictureBox1.Image = bitmap;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

private Bitmap RotateImg(Bitmap bmp, float angle, Color bkColor)
    {
        int w = bmp.Width;
        int h = bmp.Height;
        bmp.PixelFormat pf = default(bmp.PixelFormat);
        if (bkColor == Color.Transparent)
        {
            pf = bmp.Format32bppArgb;
        }
        else
        {
            pf = bmp.PixelFormat;
        }

        Bitmap tempImg = new Bitmap(w, h, pf);
        Graphics g = Graphics.FromImage(tempImg);
        g.Clear(bkColor);
        g.DrawImageUnscaled(bmp, 1, 1);
        g.Dispose();

        GraphicsPath path = new GraphicsPath();
        path.AddRectangle(new RectangleF(0f, 0f, w, h));
        Matrix mtrx = new Matrix();
        //Using System.Drawing.Drawing2D.Matrix class
        mtrx.Rotate(angle);
        RectangleF rct = path.GetBounds(mtrx);
        Bitmap newImg = new Bitmap(Convert.ToInt32(rct.Width), Convert.ToInt32(rct.Height), pf);
        g = Graphics.FromImage(newImg);
        g.Clear(bkColor);
        g.TranslateTransform(-rct.X, -rct.Y);
        g.RotateTransform(angle);
        g.InterpolationMode = InterpolationMode.HighQualityBilinear;
        g.DrawImageUnscaled(tempImg, 0, 0);
        g.Dispose();
        tempImg.Dispose();
        return newImg;
    }
    }
}

The animated gif I'm using for the test can be found here:

Body:
I tried the answer of @Omar myself and realized, that the original image gets cut at the sides ... i've rewritten it so it resizes the image to the new sizes:

private static Bitmap RotateImage(Bitmap bmp, float angle)
{
    float alpha = angle;

    //edit: negative angle +360
    while(alpha <0) alpha +=360;

    float gamma = 90;
    float beta = 180 - angle - gamma;

    float c1 = bmp.Height;
    float a1 = (float)(c1 * Math.Sin(alpha * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));
    float b1 = (float)(c1 * Math.Sin(beta * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));

    float c2 = bmp.Width;
    float a2 = (float)(c2 * Math.Sin(alpha * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));
    float b2 = (float)(c2 * Math.Sin(beta * Math.PI / 180) / Math.Sin(gamma * Math.PI / 180));

    int width = Convert.ToInt32(b2 + a1);
    int height = Convert.ToInt32(b1 + a2);

    Bitmap rotatedImage = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(rotatedImage))
    {
        g.TranslateTransform(rotatedImage.Width / 2, rotatedImage.Height / 2); //set the rotation point as the center into the matrix
        g.RotateTransform(angle); //rotate
        g.TranslateTransform(-rotatedImage.Width / 2, -rotatedImage.Height / 2); //restore rotation point into the matrix
        g.DrawImage(bmp, new Point((width - bmp.Width) / 2, (height - bmp.Height) / 2)); //draw the image on the new bitmap
    }
    return rotatedImage;
}


问:
Message lost when recipient disconnect suddenly in Ejabberd
Message lost when recipient disconnect from INTERNET suddenly due to some network problem. In this case I want to stop message lose.

Example: User A and B are online and chatting. A send messages to B. Then suddenly User B lost INTERNET connection, in meantime User A is still sending messages to B. Server assume B is still on-line because don't know there is net problem at B.

I am using Ejabberd 16.08 . Please suggest the way how can I resolve this issue.

答:
Assuming a standard c2s connection, I would suggest using Stream Management, which is supported by ejabberd, but also requires client support. This won't prevent "lost" messages, but it will allow for faster detection and notification when user B doesn't disconnect cleanly.

Another alternative is to use XMPP over BOSH, which has a number of client libraries available depending on your exact platform. BOSH acts very similarly to Stream Management, and the same caveats apply.

There will always be cases, due to the nature of internet communications, where the server believes a message to be sent, but the client has not received it. In such cases, it can help to use Message Archive Management to synchronize user B's client when it reconnects.


问:
How to correctly store connection strings in environment variables for retrieval by production ASP.Net Core MVC applications
I am working on an ASP.NET Core MVC application and I am having an issue with my connection strings.

I have an ASPNETCORE_ENVIRONMENT variable set to Production on my production server and my production server is a Windows Server 2012R2 running IIS. I also have the DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed on the production server.

During development, I am using UserSecrets to hold my connection string. This is working properly.

For production, I want my connection strings in environment variables on my production server and this is where I am having an issue. I suspect that it may be in the way I am structuring the environment variable.

When I try to access the database in production I get an error indicating basically that it can't cannot parse the connection string.

```<code>An exception occurred in the database while iterating the results of a query.

System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2
parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
</code>```

If I put the connection string in appSettings.json, the production server works just fine.

So, here is an example of my appSettings.json file showing the connection string that works in production;

```<code>{
  "ConnectionStrings": {
     "TestDb": "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
  },

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

If I deploy this appSettings.json file to production, it works OK.

In my ASP.Net Core application, in the Startup.cs file, I have the following;

```<code>public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

}
</code>```

My understanding is that the last builder.add... listed has priority, so in my case, if a connection string exists in the environment, it should take priority over anything in appsettings.

So in production, if I use the following appSettings.config file;

```<code>{
  "ConnectionStrings": {
     "TestDb": "Placeholder for connection string. Overridden by User Secrets in Development and Environment Variables in Production. "
  },

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

It should not matter what I have as a value for ConnectionStrings:TestDb in that appsettings.json file if I have an environment variable for the connection string.

Listed below is the environment variable I am using;

```<code>Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
</code>```

However, when I use this setup, I get an error when I try to access the database indicating that it can't parse the connection string.

I have to assume that the problem is the way I have the connection string specified in the environment variable, but after quite a while searching online, I have not been able to find an example of exactly what the environment variable value should look like. For example, do I need to put leading and trailing single quotes around the entire string? Does individual sections of the connection string need single or double quotes?

Any help, such as an example of a proper connection string defined in an environment variable, would be greatly appreciated.

答:
if you don't want to store in appsettings, store it in the file
C:\Windows\System32\inetsrv\config\applicationHost.config. It will be able to work.</p>

Body:
I am working on an ASP.NET Core MVC application and I am having an issue with my connection strings.

I have an ASPNETCORE_ENVIRONMENT variable set to Production on my production server and my production server is a Windows Server 2012R2 running IIS. I also have the DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed on the production server.

During development, I am using UserSecrets to hold my connection string. This is working properly.

For production, I want my connection strings in environment variables on my production server and this is where I am having an issue. I suspect that it may be in the way I am structuring the environment variable.

When I try to access the database in production I get an error indicating basically that it can't cannot parse the connection string.

An exception occurred in the database while iterating the results of a query.

System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2
parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)

If I put the connection string in appSettings.json, the production server works just fine.

So, here is an example of my appSettings.json file showing the connection string that works in production;

{
  "ConnectionStrings": {
     "TestDb": "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
  },

    ...
    ...
    ...
  }
}

If I deploy this appSettings.json file to production, it works OK.

In my ASP.Net Core application, in the Startup.cs file, I have the following;

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

}

My understanding is that the last builder.add... listed has priority, so in my case, if a connection string exists in the environment, it should take priority over anything in appsettings.

So in production, if I use the following appSettings.config file;

{
  "ConnectionStrings": {
     "TestDb": "Placeholder for connection string. Overridden by User Secrets in Development and Environment Variables in Production. "
  },

    ...
    ...
    ...
  }
}

It should not matter what I have as a value for ConnectionStrings:TestDb in that appsettings.json file if I have an environment variable for the connection string.

Listed below is the environment variable I am using;

Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"

However, when I use this setup, I get an error when I try to access the database indicating that it can't parse the connection string.

I have to assume that the problem is the way I have the connection string specified in the environment variable, but after quite a while searching online, I have not been able to find an example of exactly what the environment variable value should look like. For example, do I need to put leading and trailing single quotes around the entire string? Does individual sections of the connection string need single or double quotes?

Any help, such as an example of a proper connection string defined in an environment variable, would be greatly appreciated.


问:
Changing number values for text on Y Axis label for dc.js ScatterPlot
I have a scatter plot that charts unique events per date on my X axis and when they happened on each day, by the second, on the Y axis.

To accomplish this I took the date data that I use for the X axis, and ran it through a function that would output the exact second of the day in which the event happened (0 to 86400). In that sense, my Y axis goes from 0 seconds to 86400 seconds.

This allowed me to represent each even uniquely as a dot on my chart down to the second.

I'm pretty happy with the outcome of my chart:

The only issue is my Y label goes from 0 to 86400. I would like to change the text to a familiar HH AM/PM format, perhaps something along the lines of "0 to 23, where ie: if (y value = 3600) return "1 AM".

My scatterplot looks like this:

```<code>scatterPlot
        .width(window.innerWidth-100)
        .height(window.innerHeight/2)
        .x(d3.time.scale().domain([minDate, maxDate]))
        .brushOn(false)
        .mouseZoomable(true)
        // .title(function (d) {
        //     return "Event: " + d['text'];
        // })
        .clipPadding(5)
        .yAxisLabel("Hour of the day")
        .elasticY(true)
        .dimension(eventsByDateAndHourDim)
        .group(eventsByDateAndHourGroup);
</code>```

I tried to do this:

```<code>scatterPlot.yAxis().tickFormat(function (d) {
    if (domain = 43200)
        return "12 PM";
})
</code>```

But that only changes all labels to "12 PM". I'm not sure how to refer to the actual value of my Y domain.

I tried using the group "if (eventsByDateAndHourGroup = 43200)..." but that didn't work either.

答:
The parameter to the function passed to the tickFormat() method is the Y coordinate which needs to be formatted.

So you should be able to do something like

```<code>scatterPlot.yAxis().tickFormat(function (d) {
    var hour = Math.floor(d/3600),
        pm = hour > 11;
    if(pm) hour -= 12;
    if(hour === 0) hour = 12;
    return String(hour) + (pm ? ' PM' : ' AM');
});
</code>```

Or you can use d3.time.format.utc for a more robust, elegant solution:

```<code>var hourFormat = d3.time.format.utc('%I %p');
scatterPlot.yAxis().tickFormat(function (d) {
    var date = new Date(d*1000);
    return hourFormat(date);
});
</code>```

This is somewhat less efficient, because Date objects are slow, but it probably doesn't matter for processing a dozen ticks.

Body:
I have a scatter plot that charts unique events per date on my X axis and when they happened on each day, by the second, on the Y axis.

To accomplish this I took the date data that I use for the X axis, and ran it through a function that would output the exact second of the day in which the event happened (0 to 86400). In that sense, my Y axis goes from 0 seconds to 86400 seconds.

This allowed me to represent each even uniquely as a dot on my chart down to the second.

I'm pretty happy with the outcome of my chart:

The only issue is my Y label goes from 0 to 86400. I would like to change the text to a familiar HH AM/PM format, perhaps something along the lines of "0 to 23, where ie: if (y value = 3600) return "1 AM".

My scatterplot looks like this:

scatterPlot
        .width(window.innerWidth-100)
        .height(window.innerHeight/2)
        .x(d3.time.scale().domain([minDate, maxDate]))
        .brushOn(false)
        .mouseZoomable(true)
        // .title(function (d) {
        //     return "Event: " + d['text'];
        // })
        .clipPadding(5)
        .yAxisLabel("Hour of the day")
        .elasticY(true)
        .dimension(eventsByDateAndHourDim)
        .group(eventsByDateAndHourGroup);

I tried to do this:

scatterPlot.yAxis().tickFormat(function (d) {
    if (domain = 43200)
        return "12 PM";
})

But that only changes all labels to "12 PM". I'm not sure how to refer to the actual value of my Y domain.

I tried using the group "if (eventsByDateAndHourGroup = 43200)..." but that didn't work either.

Body:
The parameter to the function passed to the tickFormat() method is the Y coordinate which needs to be formatted.

So you should be able to do something like

scatterPlot.yAxis().tickFormat(function (d) {
    var hour = Math.floor(d/3600),
        pm = hour > 11;
    if(pm) hour -= 12;
    if(hour === 0) hour = 12;
    return String(hour) + (pm ? ' PM' : ' AM');
});

Or you can use d3.time.format.utc for a more robust, elegant solution:

var hourFormat = d3.time.format.utc('%I %p');
scatterPlot.yAxis().tickFormat(function (d) {
    var date = new Date(d*1000);
    return hourFormat(date);
});

This is somewhat less efficient, because Date objects are slow, but it probably doesn't matter for processing a dozen ticks.


问:
"type mismatch" trying to hide rows using vba
What I want to do is hide rows so my interface is lighter but I get the following error message when I i compile my code:

Type mismatch (Error 13)

```<code>Public Function keepAdditionalRowsHidden()

Dim startRow As Long
Dim lastrow As Long

Dim startRowString As String
Dim endRowString As String

startRow = 40
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row

startRowString = CStr(startRow)
endRowString = CStr(lastrow)

ActiveSheet.Rows("startRow:endRow").EntireRow.Hidden = True

End Function
</code>```

答:
This code solved my challenge, but is there cleaner way to define last row of the excel, like this way?

endRow = 1048576

```<code>Public Function keepAdditionalRowsHidden()

        Dim startRow As Long
        Dim endRow As Long

        startRow = ER.row + 1

        endRow = 1048576 ' last row of the excel

        ActiveSheet.Rows(startRow & ":" & endRow).EntireRow.Hidden = True
End Functioncode here
</code>```

Body:
What I want to do is hide rows so my interface is lighter but I get the following error message when I i compile my code:

Type mismatch (Error 13)

Public Function keepAdditionalRowsHidden()

Dim startRow As Long
Dim lastrow As Long

Dim startRowString As String
Dim endRowString As String

startRow = 40
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row

startRowString = CStr(startRow)
endRowString = CStr(lastrow)

ActiveSheet.Rows("startRow:endRow").EntireRow.Hidden = True

End Function

Body:
This code solved my challenge, but is there cleaner way to define last row of the excel, like this way?

endRow = 1048576

Public Function keepAdditionalRowsHidden()

        Dim startRow As Long
        Dim endRow As Long

        startRow = ER.row + 1

        endRow = 1048576 ' last row of the excel

        ActiveSheet.Rows(startRow & ":" & endRow).EntireRow.Hidden = True
End Functioncode here


问:
ajax and json_encode() form validation error
I am able to display success and fail messages if the form has validation errors or not but I am not sure how to get the errors to display one under each other in this php code:

```<code>$errors = array();
    $response = array();

    if(empty($_POST['name'])) {

        $errors['name'] = "Name required";
    }

    if(empty($_POST['email'])) {

        $errors['email'] = "Email required";
    }

    $response['errors'] = $errors;

    if($errors) {

        $response['success'] = false;
        $response['message'] = "Fail";

    } else {

        $reponse['success'] = true;
        $response['message'] = "<div class='alert alert-success'>Article added</div>";
    }

    echo json_encode($response);
</code>```

The line I need to change is probably:

```<code>$response['message'] = "Fail";
</code>```

答:
I am not sure I understand your issue, but if the goal is for the user to get the list of errors encountered, then everything you did was quite correct.

The errors are in

```<code>$response['errors']
</code>```

so the json_encoded result of $response permits Javascript (client-side) to browse those errors as an array, and correctly print them.

You should not return HTML formatted text. It's the role of the View (client) to render the results, accordingly to CSS rules.

So I would say that there is nothing to change here. On success == false the client must print the errors from { 'errors' : { ... }}

If you cannot/don't want to edit the client-side Javascript / rendering page, then you have to concatenate a string with
 or a

 and provide this one in $response['message']. It's ugly, but whoever has constraints still has solutions.

Body:
I am able to display success and fail messages if the form has validation errors or not but I am not sure how to get the errors to display one under each other in this php code:

$errors = array();
    $response = array();

    if(empty($_POST['name'])) {

        $errors['name'] = "Name required";
    }

    if(empty($_POST['email'])) {

        $errors['email'] = "Email required";
    }

    $response['errors'] = $errors;

    if($errors) {

        $response['success'] = false;
        $response['message'] = "Fail";

    } else {

        $reponse['success'] = true;
        $response['message'] = "
Article added
";
    }

    echo json_encode($response);

The line I need to change is probably:

$response['message'] = "Fail";

Body:
I am not sure I understand your issue, but if the goal is for the user to get the list of errors encountered, then everything you did was quite correct.

The errors are in

$response['errors']

so the json_encoded result of $response permits Javascript (client-side) to browse those errors as an array, and correctly print them.

You should not return HTML formatted text. It's the role of the View (client) to render the results, accordingly to CSS rules.

So I would say that there is nothing to change here. On success == false the client must print the errors from { 'errors' : { ... }}

If you cannot/don't want to edit the client-side Javascript / rendering page, then you have to concatenate a string with <br> or a <ul><li> and provide this one in $response['message']. It's ugly, but whoever has constraints still has solutions.