问:
ggplot in shiny app go to rstudio plot window
I have a shiny app that draw some ggplot2 plots in app. Now I’m making it into a package and export the plot drawing as a function. I found once I draw some ggplot in RStudio and start my shiny app, then all plots in my shiny app went to the RStudio plot pane.

I have tracked down the problem to very specific location and made a minimal working example.

This shiny app draw a ggplot, though it first save the ggplot into png with ggsave, then return the ggplot object to renderPlot so that it is shown in app.

```<code>library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      ggsave("plot.png", g)
    }
    g
  })
}
shinyApp(ui = ui, server = server)
</code>```

If I run this simple code in RStudio first

```<code>library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point()
</code>```

then run the app above, the plot in app is shown in RStudio plot window.

If I set SAVE_PLOT <- FALSE then the app will have plot shown correctly. This show the problem is caused by ggsave.

I didn’t try if plot first and save it later will not have this problem, because the plot in my real app is reactive, plot it first means I need to wrap every plot into a reactive instead of just write in renderPlot.

If I run dev.off after the ggplot in console, the plot will not go to rstudio. Though this is obviously not a solution either.

According to ggsave code,
it create a new device then turn off current device after saving. Is it possible that it actually messed up in this case and turned off the shiny plot device also?

It's also possible to be something with Shiny, or with RStudio.

UPDATE: the problem is not specific to RStudio, the R console have same problem.

答:
Thanks for hints from @Claus Wilke, I don't think we should turn off the current device but we can save the device and restore it.

We can use this to work around the problem:

```<code>library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      cur_dev <- dev.cur()
      ggsave("plot.png", g)
      dev.set(cur_dev)
    }
    g
  })
}
shinyApp(ui = ui, server = server)
</code>```

Thanks to @wch, issue has been created in ggplot2 repo since it's a ggsave bug.

Body:
I have a shiny app that draw some ggplot2 plots in app. Now I’m making it into a package and export the plot drawing as a function. I found once I draw some ggplot in RStudio and start my shiny app, then all plots in my shiny app went to the RStudio plot pane.

I have tracked down the problem to very specific location and made a minimal working example.

This shiny app draw a ggplot, though it first save the ggplot into png with ggsave, then return the ggplot object to renderPlot so that it is shown in app.

library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      ggsave("plot.png", g)
    }
    g
  })
}
shinyApp(ui = ui, server = server)

If I run this simple code in RStudio first

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point()

then run the app above, the plot in app is shown in RStudio plot window.

If I set SAVE_PLOT <- FALSE then the app will have plot shown correctly. This show the problem is caused by ggsave.

I didn’t try if plot first and save it later will not have this problem, because the plot in my real app is reactive, plot it first means I need to wrap every plot into a reactive instead of just write in renderPlot.

If I run dev.off after the ggplot in console, the plot will not go to rstudio. Though this is obviously not a solution either.

According to ggsave code,
it create a new device then turn off current device after saving. Is it possible that it actually messed up in this case and turned off the shiny plot device also?

It's also possible to be something with Shiny, or with RStudio.

UPDATE: the problem is not specific to RStudio, the R console have same problem.

Body:
Thanks for hints from @Claus Wilke, I don't think we should turn off the current device but we can save the device and restore it.

We can use this to work around the problem:

library(shiny)
library(ggplot2)
SAVE_PLOT <- TRUE
ui <- fluidPage(fluidRow(column(12, plotOutput("plot"))))
server <- function(input, output){
  output$plot <- renderPlot({
    g <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
    if (SAVE_PLOT) {
      cur_dev <- dev.cur()
      ggsave("plot.png", g)
      dev.set(cur_dev)
    }
    g
  })
}
shinyApp(ui = ui, server = server)

Thanks to @wch, issue has been created in ggplot2 repo since it's a ggsave bug.


来源: stackexchange

问:
accept multiple JSON formats in web service
In my REST web service I need to accept JSON that can have two different structures.

Currently I have:

```<code>@Path("/")
public class MyAppResource {
    ...
    @Context private HttpServletRequest request;
    ...
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public MyResponseItem check(MyRequestItem body) {
        ...
    }
}
</code>```

where

```<code>public class MyRequestItem {
    ...
    @JsonCreator
    public MyRequestItem(@JsonProperty("data") ArrayList<TextItem> data) {
        ...
    }
    ...
}
</code>```

and

```<code>class TextItem {
    ...
    @JsonCreator
    public TextItem(@JsonProperty("count") int count,
                    @JsonProperty("text") String text) {
        ...
    }
    ...
}
</code>```

So it accepts JSON of the form {"data":[{"count":123,"text":"abc"},...]}.

In addition to the above format I need to accept this format: {"data":["abc",...]}. That is, I think I need to change TextItem so that it can either be a String or a class as above.

How to achieve this?

答:
If you don't mind it to be the same class for both cases(TextItem), the easiest option for you is to add 1 more TextItem constructor with single string argument.

Here is demo:

```<code>public class Main {
    public static String json1 = "{\"data\":[{\"count\":123,\"text\":\"abc\"}]}";
    public static String json2 = "{\"data\":[\"abc\"]}";
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(json1, MyRequestItem.class));
        System.out.println(mapper.readValue(json2, MyRequestItem.class));
    }

    @Data //  lombok.Data;
    @ToString // lombok.ToString;
    public static class MyRequestItem {
        private List<TextItem> data;
        @JsonCreator
        public MyRequestItem(@JsonProperty("data") ArrayList<TextItem> data) {
            this.data = data;
        }
    }

    @Data
    @ToString
    public static class TextItem {
        private int count;
        private String text;
        @JsonCreator
        public TextItem(@JsonProperty("count") int count,
                        @JsonProperty("text") String text) {
            this.count = count;
            this.text = text;
        }

        // this is the only thing you need to add to make it work
        public TextItem( String text) {
            this.text = text;
        }
    }
}
</code>```

Result:

MyRequestItem(data=[TextItem(count=123, text=abc)])

MyRequestItem(data=[TextItem(count=0, text=abc)])

ContentLicense: CC BY-SA 3.0

Body:
In my REST web service I need to accept JSON that can have two different structures.

Currently I have:

@Path("/")
public class MyAppResource {
    ...
    @Context private HttpServletRequest request;
    ...
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public MyResponseItem check(MyRequestItem body) {
        ...
    }
}

where

public class MyRequestItem {
    ...
    @JsonCreator
    public MyRequestItem(@JsonProperty("data") ArrayList<TextItem> data) {
        ...
    }
    ...
}

and

class TextItem {
    ...
    @JsonCreator
    public TextItem(@JsonProperty("count") int count,
                    @JsonProperty("text") String text) {
        ...
    }
    ...
}

So it accepts JSON of the form {"data":[{"count":123,"text":"abc"},...]}.

In addition to the above format I need to accept this format: {"data":["abc",...]}. That is, I think I need to change TextItem so that it can either be a String or a class as above.

How to achieve this?

Body:
If you don't mind it to be the same class for both cases(TextItem), the easiest option for you is to add 1 more TextItem constructor with single string argument.

Here is demo:

public class Main {
    public static String json1 = "{\"data\":[{\"count\":123,\"text\":\"abc\"}]}";
    public static String json2 = "{\"data\":[\"abc\"]}";
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(json1, MyRequestItem.class));
        System.out.println(mapper.readValue(json2, MyRequestItem.class));
    }

    @Data //  lombok.Data;
    @ToString // lombok.ToString;
    public static class MyRequestItem {
        private List<TextItem> data;
        @JsonCreator
        public MyRequestItem(@JsonProperty("data") ArrayList<TextItem> data) {
            this.data = data;
        }
    }

    @Data
    @ToString
    public static class TextItem {
        private int count;
        private String text;
        @JsonCreator
        public TextItem(@JsonProperty("count") int count,
                        @JsonProperty("text") String text) {
            this.count = count;
            this.text = text;
        }

        // this is the only thing you need to add to make it work
        public TextItem( String text) {
            this.text = text;
        }
    }
}

Result:

MyRequestItem(data=[TextItem(count=123, text=abc)])

MyRequestItem(data=[TextItem(count=0, text=abc)])


问:
How to move 12 digit numbers from richtextbox to textbox2
I want to move 12 digit numbers from richtextbox to textbox2 by a program.

I enter these words for richtextbox

```<code>sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd
</code>```

I need to get only these 12 digit numbers to  textbox2..

I tried this code but it types System.Text.RegularExpressions.MatchCollection not these digits

Here i use code for that

```<code>private void button2_Click(object sender, EventArgs e)
{
    Regex RX = new Regex("[0-9]{1,12}$");
    textBox2.Text = (RX.Matches(richTextBox1.Text)).ToString();
}
</code>```

I don't know how to move these numebrs to the textbox2.. Please help me enter image description here

答:
You can simply use LINQ for this purposes. If you want to get just 512025151988:

```<code>textBox2.Text = string.Join("",richTextBox1.Text.SkipWhile(c =>
               !char.IsDigit(c)).TakeWhile(char.IsDigit));
</code>```

Or if you want to get all numbers (512025151988,512025151988,512025151988,512025151988,512025151988):

```<code>textBox2.Text = string.Join(",",richTextBox1.Text.Split(',')
                .Select(d => string.Join("",d
                .SkipWhile(c => !char.IsDigit(c)).TakeWhile(char.IsDigit))))
                .TrimStart(',').TrimEnd(',');
</code>```

Replace first comma with space if you need to join results with space. string.Join(" ",...

Body:
I want to move 12 digit numbers from richtextbox to textbox2 by a program.

I enter these words for richtextbox

sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd

I need to get only these 12 digit numbers to  textbox2..

I tried this code but it types System.Text.RegularExpressions.MatchCollection not these digits

Here i use code for that

private void button2_Click(object sender, EventArgs e)
{
    Regex RX = new Regex("[0-9]{1,12}$");
    textBox2.Text = (RX.Matches(richTextBox1.Text)).ToString();
}

I don't know how to move these numebrs to the textbox2.. Please help me enter image description here

Body:
You can simply use LINQ for this purposes. If you want to get just 512025151988:

textBox2.Text = string.Join("",richTextBox1.Text.SkipWhile(c =>
               !char.IsDigit(c)).TakeWhile(char.IsDigit));

Or if you want to get all numbers (512025151988,512025151988,512025151988,512025151988,512025151988):

textBox2.Text = string.Join(",",richTextBox1.Text.Split(',')
                .Select(d => string.Join("",d
                .SkipWhile(c => !char.IsDigit(c)).TakeWhile(char.IsDigit))))
                .TrimStart(',').TrimEnd(',');

Replace first comma with space if you need to join results with space. string.Join(" ",...


问:
The below VBA code populates list of filenames in the same sheet, but I want the result dataset to be generated into a different worksheet?

Please check the below query and help me in modifying the query, so that the result dataset gets populated into a different worksheet.

```<code>Sub MainList()
    'Updateby20150706
    Set folder = Application.FileDialog(msoFileDialogFolderPicker)
    If folder.Show <> -1 Then Exit Sub
    xDir = folder.SelectedItems(1)
    Call ListFilesInFolder(xDir, True)
    End Sub
    Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
    Dim xFileSystemObject As Object
    Dim xFolder As Object
    Dim xSubFolder As Object
    Dim xFile As Object
    Dim rowIndex As Long

    Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Set xFolder = xFileSystemObject.GetFolder(xFolderName)
    rowIndex = Application.ActiveSheet.Range("B65536").End(xlUp).Row + 1
    For Each xFile In xFolder.Files
      Application.ActiveSheet.Cells(rowIndex, 2).Formula = xFile.Name
      rowIndex = rowIndex + 1
    Next xFile
    If xIsSubfolders Then
      For Each xSubFolder In xFolder.Subfolders
        ListFilesInFolder xSubFolder.Path, True
      Next xSubFolder
    End If
    Set xFile = Nothing
    Set xFolder = Nothing
    Set xFileSystemObject = Nothing
    End Sub
    Function GetFileOwner(ByVal xPath As String, ByVal xName As String)
    Dim xFolder As Object
    Dim xFolderItem As Object
    Dim xShell As Object
    xName = StrConv(xName, vbUnicode)
    xPath = StrConv(xPath, vbUnicode)
    Set xShell = CreateObject("Shell.Application")
    Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))
    If Not xFolder Is Nothing Then
      Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))
    End If
    If Not xFolderItem Is Nothing Then
      GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
    Else
      GetFileOwner = ""
    End If
    Set xShell = Nothing
    Set xFolder = Nothing
    Set xFolderItem = Nothing
    End Function
</code>```

Please let me know how to do the modification and let me know if you have any questions or comments. Thanks.

答:
Add an index to Application.Worksheets(sheetIndex):
Change

```<code>For Each xFile In xFolder.Files
      Application.ActiveSheet.Cells(rowIndex, 2).Formula = xFile.Name
      rowIndex = rowIndex + 1
    Next xFile
</code>```

to

```<code>sheetIndex = 1
For Each xFile In xFolder.Files
      Application.Worksheets(sheetIndex).Cells(rowIndex, 2).Formula = xFile.Name
      rowIndex = rowIndex + 1
      sheetIndex = sheetIndex + 1
    Next xFile
</code>```

Body:
Please check the below query and help me in modifying the query, so that the result dataset gets populated into a different worksheet.

Sub MainList()
    'Updateby20150706
    Set folder = Application.FileDialog(msoFileDialogFolderPicker)
    If folder.Show <> -1 Then Exit Sub
    xDir = folder.SelectedItems(1)
    Call ListFilesInFolder(xDir, True)
    End Sub
    Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
    Dim xFileSystemObject As Object
    Dim xFolder As Object
    Dim xSubFolder As Object
    Dim xFile As Object
    Dim rowIndex As Long

    Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Set xFolder = xFileSystemObject.GetFolder(xFolderName)
    rowIndex = Application.ActiveSheet.Range("B65536").End(xlUp).Row + 1
    For Each xFile In xFolder.Files
      Application.ActiveSheet.Cells(rowIndex, 2).Formula = xFile.Name
      rowIndex = rowIndex + 1
    Next xFile
    If xIsSubfolders Then
      For Each xSubFolder In xFolder.Subfolders
        ListFilesInFolder xSubFolder.Path, True
      Next xSubFolder
    End If
    Set xFile = Nothing
    Set xFolder = Nothing
    Set xFileSystemObject = Nothing
    End Sub
    Function GetFileOwner(ByVal xPath As String, ByVal xName As String)
    Dim xFolder As Object
    Dim xFolderItem As Object
    Dim xShell As Object
    xName = StrConv(xName, vbUnicode)
    xPath = StrConv(xPath, vbUnicode)
    Set xShell = CreateObject("Shell.Application")
    Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))
    If Not xFolder Is Nothing Then
      Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))
    End If
    If Not xFolderItem Is Nothing Then
      GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
    Else
      GetFileOwner = ""
    End If
    Set xShell = Nothing
    Set xFolder = Nothing
    Set xFolderItem = Nothing
    End Function

Please let me know how to do the modification and let me know if you have any questions or comments. Thanks.

Body:
Add an index to Application.Worksheets(sheetIndex):
Change

For Each xFile In xFolder.Files
      Application.ActiveSheet.Cells(rowIndex, 2).Formula = xFile.Name
      rowIndex = rowIndex + 1
    Next xFile

to

sheetIndex = 1
For Each xFile In xFolder.Files
      Application.Worksheets(sheetIndex).Cells(rowIndex, 2).Formula = xFile.Name
      rowIndex = rowIndex + 1
      sheetIndex = sheetIndex + 1
    Next xFile


问:
Unable to change X/Y axis value in D3
I am using the following code to  create a D3 figure for.In This,I am trying to plot a few weather related data.In the code ,I am trying change the axis value but unable to do it. It is getting fixed to the default value I have provided in the beginning. Can someone please help me with it. The dataset I am using is json data(link:https://drive.google.com/file/d/13-unvzxvjmFWVgfSKRJObZJc81VriyIf/view?usp=sharing).

following is the code I am using.

```<code><!DOCTYPE html>
<html>
<meta charset="utf-8">

<style>
body {
  font: 11px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.dot {
  stroke: #000;
}

.tooltip {
  position: absolute;
  width: 200px;
  height: 28px;
  pointer-events: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,       //900
    height = 500 - margin.top - margin.bottom;      //450

// setup fill color
    var colorScale = d3.scale.linear()
                            .domain([-15, 30])
                            .range(["blue","red"]);

// add the graph canvas to the body of the webpage
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// add the tooltip area to the webpage
var tooltip = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);
var selectData = [ { "text" : "meantempm" },
                   { "text" : "meanpressurem" },
                   { "text" : "meanwindspdm" },
                   { "text" : "humidity" },
                   ]
   var body = d3.select('body');
// load data
d3.json("weatherdata.json", function(error, data) {

  // change string (from CSV) into number format
    data.forEach(function(d) {//to check the utility
    d.meanwindspdm = +d.history.dailysummary[0].meanwindspdm;
    d.meantempm = +d.history.dailysummary[0].meantempm;
    d.meanpressurem = +d.history.dailysummary[0].meanpressurem;
    d.humidity = +d.history.dailysummary[0].humidity;

//    console.log(d);
  });

// setup x
var xExtent = d3.extent(data, function(d) { return (d.meanpressurem);}), //given
    xScale = d3.scale.linear().domain(xExtent).range([0, width]), // value -> display   //given
    xValue = function(d) { return ((d.meanpressurem));}, // data -> value
    xMap = function(d) { return xScale(d.meanpressurem);}, // data -> display
    xAxis = d3.svg.axis().scale(xScale).orient("bottom"); //given

// setup y
var yExtent = d3.extent(data, function(d) {return (d.meantempm);}),
    yValue = function(d) { return d.meantempm;}, // data -> value
    yScale = d3.scale.linear().domain(yExtent).range([height, 0]), // value -> display
    yMap = function(d) { return yScale(yValue(d));}, // data -> display
    yAxis = d3.svg.axis().scale(yScale).orient("left");

//new addition
  // Select X-axis Variable
  var defs = body.append('defs')
    .text('X-Axis:')
  var yInput = body.append('select')
      .attr('id','xSelect')
      .on('change',xChange)
    .selectAll('option')
      .data(selectData)
      .enter()
    .append('option')
      .attr('value', function (d) { return d.text }) ///check
      .text(function (d) { return d.text ;})
  //body.append('br')

  // Select Y-axis Variable
  var span = body.append('defs')
      .text('Y-Axis: ')
  var yInput = body.append('select')
      .attr('id','ySelect')
       .on('change',yChange)
    .selectAll('option')
      .data(selectData)
      .enter()
    .append('option')
      .attr('value', function (d) { return d.text })//check
      .text(function (d) { return d.text ;})
  body.append('br')

//new addition upto

  // x-axis
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("class", "label")
      .attr('id','xAxisLabel')
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text("meanwindspdm");

  // y-axis
  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("class", "label")
      .attr('id','yAxisLabel')
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("meantempm");

  // draw dots
  svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", xMap)
      .attr("cy", yMap)
      .style("fill", function(d){return colorScale(d.meantempm)})
      .on("mouseover", function(d) {
          tooltip.transition()
               .duration(200)
               .style("opacity", .9);
          tooltip.html(d.history.date.pretty + "<br/> (" + xValue(d)
            + ", " + yValue(d) + ")")
               .style("left", (d3.event.pageX + 5) + "px")
               .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
          tooltip.transition()
               .duration(500)
               .style("opacity", 0);
      });

  // draw legend
  var legend = svg.selectAll(".legend")
      .data(colorScale.domain())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  // draw legend colored rectangles
  legend.append("rect")
      .attr("x", width - 10)
      .attr("width", 10)
      .attr("height", 10)
      .style("fill", colorScale);

  // draw legend text
  legend.append("text")
      .attr("x", width - 16)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d;})
      // new addiiton/////////

    function yChange() {
    var value = this.value // get the new y value
    yScale // change the yScale
      .domain([
        d3.min([0,d3.min(data,function (d) { return +d.history.dailysummary[0][value] })]),
        d3.max([0,d3.max(data,function (d) { return +d.history.dailysummary[0][value] })])
        ])
    yAxis.scale(yScale) // change the yScale
    d3.select('#yAxis') // redraw the yAxis
      .transition().duration(50)
      .call(yAxis)
    d3.select('#yAxisLabel') // change the yAxisLabel
      .text(value)
    d3.selectAll('circle') // move the circles
      .transition().duration(50)
         .delay(50)
      //.delay(function (d,i) { return i*100})
        .attr('cy',function (d) { return yScale(+d.history.dailysummary[0][value]) })
  }

  function xChange() {
    var value = this.value   // get the new x value
    console.log(value);
    console.log(data);
    xScale // change the xScale
        .domain([
        d3.min([0,d3.min(data,function (d) {console.log( +d.history.dailysummary[0][value] ) ; return +d.history.dailysummary[0][value] })]),
        d3.max([0,d3.max(data,function (d) { return +d.history.dailysummary[0][value] })])
        ])

    xAxis.scale(xScale) // change the xScale //issue here I guess`enter code here`
    d3.select('#xAxis') // redraw the xAxis
      .transition().duration(50)
      .call(xAxis)
    d3.select('#xAxisLabel') // change the xAxisLabel
      .transition().duration(50)
      .text(value)
    d3.selectAll('circle') // move the circles
      .transition().duration(50)
      .delay(50)
      //.delay(function (d,i) { return i*100})
        .attr('cx',function (d) {  return xScale(+d.history.dailysummary[0][value]); })

  }
      // new addiiton upto/////////
});

</script>
</body>
</html>
</code>```

答:
If I'm reading your code correctly you are trying to select and element with id xAxis or yAxis, which you have not specified in the code given, which you gave

```<code>.attr("class", "x axis")
</code>```

Try using d3.select(".x") and d3.select(".y") instead of d3.select("#xAxis") and d3.select("#yAxis").

Title: Unable to change X/Y axis value in D3

Body:
I am using the following code to  create a D3 figure for.In This,I am trying to plot a few weather related data.In the code ,I am trying change the axis value but unable to do it. It is getting fixed to the default value I have provided in the beginning. Can someone please help me with it. The dataset I am using is json data(link:https://drive.google.com/file/d/13-unvzxvjmFWVgfSKRJObZJc81VriyIf/view?usp=sharing).

following is the code I am using.

<!DOCTYPE html>

<meta charset="utf-8">

Body:
If I'm reading your code correctly you are trying to select and element with id xAxis or yAxis, which you have not specified in the code given, which you gave

.attr("class", "x axis")

Try using d3.select(".x") and d3.select(".y") instead of d3.select("#xAxis") and d3.select("#yAxis").


问:
Guava Optional working with multiple objects and fields
I have few classes:

```<code>    public class Person {
        private String personName;
        private String personSurname;
        private int age;
        private Task task;
        private Document document;
    //getters and setters

    public class Task {
        private long taskNumber;
        private String taskDescription;
        private String taskPriority;
    //get&set

    public class Document {
        private String docName;
        private String docDescription;
        private long docNumber;
        private String docType;
        private DocumentAuthor documentAuthor;
    // get&set

    public class DocumentAuthor {
        private String documentAuthorName;
        private long documentAuthorNumber;
        private String documentAuthorDescription;
    // get&set
</code>```

And after create Person object I need to build description (with StringBuilder) from some fields like: personName, personSurname, taskDescription, docDescription and documentAuthorDescription. The thing is when I must check nullables of some objects/fields (I don’t want to store nulls in description). In this moment I do this on this way:

```<code>    private static String setStringBuilder(Person person) {
            StringBuilder sb = new StringBuilder();
            //create Optional objects for every class except Person:
            Optional<Document> personDocument = Optional.fromNullable(person.getDocument());
            Optional<Task> personTask = Optional.fromNullable(person.getTask());
            Optional<DocumentAuthor> personDocumentAuthor = Optional.fromNullable(person.getDocument().getDocumentAuthor());
            //create List where i add fields for description
            List<Optional<String>> list = new ArrayList();
            list.add(Optional.fromNullable(person.getPersonName()));
            list.add(Optional.fromNullable(person.getPersonSurname()));
            //in this section i check presents of objects:
            if (personDocument.isPresent()) {
                list.add(Optional.fromNullable(person.getDocument().getDocDescription()));
                list.add(Optional.fromNullable(person.getDocument().getDocType()));
            }
            if (personTask.isPresent()) {
                list.add(Optional.fromNullable(person.getTask().getTaskDescription()));
            }
            if (personDocumentAuthor.isPresent()) {
                list.add(Optional.fromNullable(person.getDocument().getDocumentAuthor().getDocumentAuthorName()));
            }
            //here i build StringBuilder from fields stored in list
            for (Optional<String> optional : list) {
                if (optional.isPresent()) {
                    sb.append(optional.get());
                    sb.append(" ");
                }
            }
            String description = sb.toString();
            return description;
        }
</code>```

But I believe there is some coolest way to do this with Guava Optionals. Especially when I check for nulls witch if’s. So pls give me some advices and forgive me my bad bad english :)

答:
Don't worry about the "coolest" way to solve a problem, focus instead on the "cleanest", "safest", and "easiest to maintain" solutions.

Dealing with null is certainly error-prone, and has caused countless bugs, but they are a part of the Java language, and sometimes they're what you need.

In particular, it generally makes more sense to expose Optionals at API boundaries (e.g. as the return type of public methods), rather than return possibly-null values. That allows your callers to confidently and safely work with your code without fear of unexpected NPEs. Your private implementation may well be better off just using null or some other concept to represent absence however.

As a rule of thumb, Optional should make your code safer and easier to use. If you find yourself jumping through hoops in order to make things Optional step back and consider alternative approaches.

Body:
I have few classes:

    public class Person {
        private String personName;
        private String personSurname;
        private int age;
        private Task task;
        private Document document;
    //getters and setters

    public class Task {
        private long taskNumber;
        private String taskDescription;
        private String taskPriority;
    //get&set

    public class Document {
        private String docName;
        private String docDescription;
        private long docNumber;
        private String docType;
        private DocumentAuthor documentAuthor;
    // get&set

    public class DocumentAuthor {
        private String documentAuthorName;
        private long documentAuthorNumber;
        private String documentAuthorDescription;
    // get&set

And after create Person object I need to build description (with StringBuilder) from some fields like: personName, personSurname, taskDescription, docDescription and documentAuthorDescription. The thing is when I must check nullables of some objects/fields (I don’t want to store nulls in description). In this moment I do this on this way:

    private static String setStringBuilder(Person person) {
            StringBuilder sb = new StringBuilder();
            //create Optional objects for every class except Person:
            Optional<Document> personDocument = Optional.fromNullable(person.getDocument());
            Optional<Task> personTask = Optional.fromNullable(person.getTask());
            Optional<DocumentAuthor> personDocumentAuthor = Optional.fromNullable(person.getDocument().getDocumentAuthor());
            //create List where i add fields for description
            List<Optional<String>> list = new ArrayList();
            list.add(Optional.fromNullable(person.getPersonName()));
            list.add(Optional.fromNullable(person.getPersonSurname()));
            //in this section i check presents of objects:
            if (personDocument.isPresent()) {
                list.add(Optional.fromNullable(person.getDocument().getDocDescription()));
                list.add(Optional.fromNullable(person.getDocument().getDocType()));
            }
            if (personTask.isPresent()) {
                list.add(Optional.fromNullable(person.getTask().getTaskDescription()));
            }
            if (personDocumentAuthor.isPresent()) {
                list.add(Optional.fromNullable(person.getDocument().getDocumentAuthor().getDocumentAuthorName()));
            }
            //here i build StringBuilder from fields stored in list
            for (Optional<String> optional : list) {
                if (optional.isPresent()) {
                    sb.append(optional.get());
                    sb.append(" ");
                }
            }
            String description = sb.toString();
            return description;
        }

But I believe there is some coolest way to do this with Guava Optionals. Especially when I check for nulls witch if’s. So pls give me some advices and forgive me my bad bad english :)


问:
How to find mean for subset using R?
Using the pre-installed dataset in R, mtcars, I'm trying to find the mean of the "mpg" variable for only Mercedes cars. I am new to R and learning on my own. I've figured out the average for mpg of all cars using the following:

read.csv ("mtcars.csv")
mean(mtcars$mpg)

I thought of using something like a GROUP BY, to group only the 'Mercedes cars, but can't seem to figure it out. I'm sure it's really simple so I'm a little frustrated I'm not seeing what to do here next....

This is what the file looks like: https://gist.github.com/seankross/a412dfbd88b3db70b74b

答:
In base R, mtcars is a built-in data frame. You can type mtcars in the console to view it.

Here I printed the first 10 rows of the mtcars data frame.

```<code>head(mtcars, 10)
#                    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
# Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
# Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
# Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

The information you need, the model, is stored in the row names. To access that information, we can use the rownames function.

```<code>rownames(mtcars)
# [1] "Mazda RX4"           "Mazda RX4 Wag"       "Datsun 710"
# [4] "Hornet 4 Drive"      "Hornet Sportabout"   "Valiant"
# [7] "Duster 360"          "Merc 240D"           "Merc 230"
# [10] "Merc 280"            "Merc 280C"           "Merc 450SE"
# [13] "Merc 450SL"          "Merc 450SLC"         "Cadillac Fleetwood"
# [16] "Lincoln Continental" "Chrysler Imperial"   "Fiat 128"
# [19] "Honda Civic"         "Toyota Corolla"      "Toyota Corona"
# [22] "Dodge Challenger"    "AMC Javelin"         "Camaro Z28"
# [25] "Pontiac Firebird"    "Fiat X1-9"           "Porsche 914-2"
# [28] "Lotus Europa"        "Ford Pantera L"      "Ferrari Dino"
# [31] "Maserati Bora"       "Volvo 142E"
</code>```

The next thing we need to do is filter the row names to see if there are any elements match "Merc". We can use grepl to achieve this, which returns a logical vector if there is a match. Here "^Merc" means to capture string with a beginning in "Merc".

```<code>grepl("^Merc", rownames(mtcars))
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
# [14]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [27] FALSE FALSE FALSE FALSE FALSE FALSE
</code>```

Finally, we can use the logical vector to subset the mtcars data frame. After the subset, we can calculate the average of mpg of the subset.

```<code>mtcars_merc <- mtcars[grepl("^Merc", rownames(mtcars)), ]
mean(mtcars_merc$mpg)
# [1] 19.01429
</code>```

Title: How to find mean for subset using R?

Body:
In base R, mtcars is a built-in data frame. You can type mtcars in the console to view it.

Here I printed the first 10 rows of the mtcars data frame.

head(mtcars, 10)
#                    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
# Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
# Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
# Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

The information you need, the model, is stored in the row names. To access that information, we can use the rownames function.

rownames(mtcars)
# [1] "Mazda RX4"           "Mazda RX4 Wag"       "Datsun 710"
# [4] "Hornet 4 Drive"      "Hornet Sportabout"   "Valiant"
# [7] "Duster 360"          "Merc 240D"           "Merc 230"
# [10] "Merc 280"            "Merc 280C"           "Merc 450SE"
# [13] "Merc 450SL"          "Merc 450SLC"         "Cadillac Fleetwood"
# [16] "Lincoln Continental" "Chrysler Imperial"   "Fiat 128"
# [19] "Honda Civic"         "Toyota Corolla"      "Toyota Corona"
# [22] "Dodge Challenger"    "AMC Javelin"         "Camaro Z28"
# [25] "Pontiac Firebird"    "Fiat X1-9"           "Porsche 914-2"
# [28] "Lotus Europa"        "Ford Pantera L"      "Ferrari Dino"
# [31] "Maserati Bora"       "Volvo 142E"

The next thing we need to do is filter the row names to see if there are any elements match "Merc". We can use grepl to achieve this, which returns a logical vector if there is a match. Here "^Merc" means to capture string with a beginning in "Merc".

grepl("^Merc", rownames(mtcars))
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
# [14]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [27] FALSE FALSE FALSE FALSE FALSE FALSE

Finally, we can use the logical vector to subset the mtcars data frame. After the subset, we can calculate the average of mpg of the subset.

mtcars_merc <- mtcars[grepl("^Merc", rownames(mtcars)), ]
mean(mtcars_merc$mpg)
# [1] 19.01429


问:
How can I loop SOLines in MailSettings email Body for Acumatica ReportDesigner
Our customers would like us to include fields from the SO Lines in our Sales Order confirmation email, which we are making available to be sent as part of the MailSettings Body for the Sales Order Confirmation report created through ReportDesigner.

Hypothetically, we are able to loop SO Lines like this for an Email Notification by using a foreach loop in the HTML, but I have been unsuccessful with this approach.  (The GUI insists on translating my <> symbols into the ascii codes when I try save the directly edited HTML.)

I do not see a way of doing this at all in the MailSettings Body.  How can I loop the data here?

EDIT: I found the instructions for linking to the email notification template from within the report so I can use one for both, so if anyone can help solve the mystery of using the  within the Email Notification HTML without it automatically replacing the <> characters with ascii that will also solve my problem.

答: I was able to solve this using the Notification Template; my error was in trying to do the  loop in the HTML code instead of pasting directly into the Visual page.  Functionality is quite limited in terms of being able to add headers for the table outside of the loop, but I got it working by adding another table outside the loop and setting width percentages for both tables.  Ugly, but functional.</p>


答:
Split with a comma, then take all items that are of length 12 and are all digits:

```<code>var richTextBox1_Text = "sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd";
Console.Write(
        string.Join(",",
            richTextBox1_Text.Split(',')
                .Where(m=>m.Length==12 && m.All(char.IsDigit))));
# => 512025151988,512025151988,512025151988,512025151988,512025151988
</code>```

See the C# demo

In your code:

```<code>textBox2.Text = string.Join(",",
            richTextBox1.Text.Split(',')
                .Where(m=>m.Length==12 && m.All(char.IsDigit)));
</code>```

For more complex scenarios, use a \b\d{12}\b regex like this:

```<code>textBox2.Text = string.Join("\r\n",
            Regex.Matches(richTextBox1.Text, @"\b\d{12}\b")
                .Cast<Match>()
                .Select(m => m.Value));
</code>```

Title: How to move 12 digit numbers from richtextbox to textbox2

Body:
Split with a comma, then take all items that are of length 12 and are all digits:

var richTextBox1_Text = "sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd";
Console.Write(
        string.Join(",",
            richTextBox1_Text.Split(',')
                .Where(m=>m.Length==12 && m.All(char.IsDigit))));
# => 512025151988,512025151988,512025151988,512025151988,512025151988

See the C# demo

In your code:

textBox2.Text = string.Join(",",
            richTextBox1.Text.Split(',')
                .Where(m=>m.Length==12 && m.All(char.IsDigit)));

For more complex scenarios, use a \b\d{12}\b regex like this:

textBox2.Text = string.Join("\r\n",
            Regex.Matches(richTextBox1.Text, @"\b\d{12}\b")
                .Cast<Match>()
                .Select(m => m.Value));


问:
DataGridView rightmost column user increase size not working
I have a strange issue with a DataGridView on a WinForm. I can resize all columns via mouse, but for the rightmost I can only shrink and not increase the size.

Does anyone know how to solve this?

答:
This is by design. When you Click/Hold your mouse button, the mouse is captured and cannot leave the client area, with the effect of blocking the resize. You have to give it a push.

I tried not to P/Invoke to release the capture.

See if this works for you (of course if any AutoSize mode is set, nothing will happen).

```<code>private bool IsLastColumn = false;
private bool IsMouseDown = false;
private int MouseLocationX = 0;
private int lastColumnIndex;

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
   var dgv = sender as DataGridView;
   lastColumnIndex = dgv.Columns
       .OfType<DataGridViewColumn>()
       .Where(c => c.Visible)
       .OrderBy(c => c.DisplayIndex)
       .Last()
       .Index;

   //Check if the mouse pointer is contained in last column boundaries
   //In the middle of it because clicking the divider of the row before
   //the last may be seen as inside the last too.
   Point location = new Point(e.X - (dgv.Columns[lastColumnIndex].Width / 2), e.Y);
   if (dgv.GetColumnDisplayRectangle(lastColumnIndex, true).Contains(location))
   {
      //Store a positive checks and the current mouse position
      IsLastColumn = true;
      IsMouseDown = true;
      MouseLocationX = e.Location.X;
   }
}

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
   var dgv = sender as DataGridView;

   //If it's the last column and the left mouse button is pressed...
   if ((IsLastColumn) && (IsMouseDown) && (e.Button == MouseButtons.Left))
   {
      // Adding the width of the vertical scrollbar, if any.
      int cursorXPosition = e.X;
      if (dgv.Controls.OfType<VScrollBar>().Where(s => s.Visible).Count() > 0)
      {
          cursorXPosition += SystemInformation.VerticalScrollBarWidth;
      }

      //... calculate the offset of the movement.
      //You'll have to play with it a bit, though
      int colWidth = dgv.Columns[lastColumnIndex].Width;
      int colWidthOffset = colWidth + (e.X - MouseLocationX) > 0 ? (e.X - MouseLocationX) : 1;
      //If mouse pointer reaches the limit of the clientarea...
      if ((colWidthOffset > -1) && (cursorXPosition >= dgv.ClientSize.Width - 1))
      {
         //...resize the column and move the scrollbar offset
         dgv.HorizontalScrollingOffset = dgv.ClientSize.Width + colWidth + colWidthOffset;
         dgv.Columns[lastColumnIndex].Width = colWidth + colWidthOffset;
      }
   }
}

private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
{
    IsMouseDown = false;
    IsLastColumn = false;
}
</code>```

Body:
This is by design. When you Click/Hold your mouse button, the mouse is captured and cannot leave the client area, with the effect of blocking the resize. You have to give it a push.

I tried not to P/Invoke to release the capture.

See if this works for you (of course if any AutoSize mode is set, nothing will happen).

private bool IsLastColumn = false;
private bool IsMouseDown = false;
private int MouseLocationX = 0;
private int lastColumnIndex;

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
   var dgv = sender as DataGridView;
   lastColumnIndex = dgv.Columns
       .OfType<DataGridViewColumn>()
       .Where(c => c.Visible)
       .OrderBy(c => c.DisplayIndex)
       .Last()
       .Index;

   //Check if the mouse pointer is contained in last column boundaries
   //In the middle of it because clicking the divider of the row before
   //the last may be seen as inside the last too.
   Point location = new Point(e.X - (dgv.Columns[lastColumnIndex].Width / 2), e.Y);
   if (dgv.GetColumnDisplayRectangle(lastColumnIndex, true).Contains(location))
   {
      //Store a positive checks and the current mouse position
      IsLastColumn = true;
      IsMouseDown = true;
      MouseLocationX = e.Location.X;
   }
}

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
   var dgv = sender as DataGridView;

   //If it's the last column and the left mouse button is pressed...
   if ((IsLastColumn) && (IsMouseDown) && (e.Button == MouseButtons.Left))
   {
      // Adding the width of the vertical scrollbar, if any.
      int cursorXPosition = e.X;
      if (dgv.Controls.OfType<VScrollBar>().Where(s => s.Visible).Count() > 0)
      {
          cursorXPosition += SystemInformation.VerticalScrollBarWidth;
      }

      //... calculate the offset of the movement.
      //You'll have to play with it a bit, though
      int colWidth = dgv.Columns[lastColumnIndex].Width;
      int colWidthOffset = colWidth + (e.X - MouseLocationX) > 0 ? (e.X - MouseLocationX) : 1;
      //If mouse pointer reaches the limit of the clientarea...
      if ((colWidthOffset > -1) && (cursorXPosition >= dgv.ClientSize.Width - 1))
      {
         //...resize the column and move the scrollbar offset
         dgv.HorizontalScrollingOffset = dgv.ClientSize.Width + colWidth + colWidthOffset;
         dgv.Columns[lastColumnIndex].Width = colWidth + colWidthOffset;
      }
   }
}

private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
{
    IsMouseDown = false;
    IsLastColumn = false;
}

ContentLicense: CC BY-SA 4.0


问:
Correct way of overriding CSS
I'm currently working with Bootstrap and for my site I want to override certain default settings it comes with. A lot of Bootstrap rules are quite deeply nested and thus most often than not take priority over whatever I might define.

In my overrides css file, do I have a better option than to slap

```<code>!important
</code>```

on each rule, or is that how everybody's handling it these days?

答:
The easiest and first thing you should do is check the order of your stylesheet links in the head of your html file.

Link to the bootstrap CSS first, then, on the following line, link to your style.css (or similar) file.

If you have this order reversed, you may have trouble overriding certain style elements.

Title: Correct way of overriding CSS

Body:
I'm currently working with Bootstrap and for my site I want to override certain default settings it comes with. A lot of Bootstrap rules are quite deeply nested and thus most often than not take priority over whatever I might define.

In my overrides css file, do I have a better option than to slap

!important

on each rule, or is that how everybody's handling it these days?


问:
Finding the latitude and longitude from an address
I am trying to display markers on map in android by using address.

This is my code:

```<code>public void onMapReady(GoogleMap googleMap){
    mMap = googleMap;
    Geocoder coder= new Geocoder(this);
    try
    {
        String straddress = "155 Park Theater,Palo Alto,CA";
        Double latitude = 0.0;
        Double longitude = 0.0;
        List<Address> addresses = coder.getFromLocationName("155 Park Theater,Palo Alto,CA",1);
        Address location = addresses.get(0);
        LatLng p1 = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions().position(p1).title("California"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(p1));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
</code>```

If I do not put street number, then it will display the marker.
But, it will just display marker on the street. I want marker on particular location.

I am getting following error while inputting the whole address with street number. The "address" list is empty.

```<code>java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
</code>```

答:
Update your code with following : </p>

```<code> List<Address> address;
 LatLng latLng = null;

try {
    address = coder.getFromLocationName(strAddress,5);
    if (address==null) {
       return null;
    }
    Address location=address.get(0);
    latLng = new LatLng(location.getLatitude(),location.getLongitude());
    }
</code>```

Body:
I am trying to display markers on map in android by using address.

This is my code:

public void onMapReady(GoogleMap googleMap){
    mMap = googleMap;
    Geocoder coder= new Geocoder(this);
    try
    {
        String straddress = "155 Park Theater,Palo Alto,CA";
        Double latitude = 0.0;
        Double longitude = 0.0;
        List<Address> addresses = coder.getFromLocationName("155 Park Theater,Palo Alto,CA",1);
        Address location = addresses.get(0);
        LatLng p1 = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions().position(p1).title("California"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(p1));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

If I do not put street number, then it will display the marker.
But, it will just display marker on the street. I want marker on particular location.

I am getting following error while inputting the whole address with street number. The "address" list is empty.

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Body:
Update your code with following :

 List<Address> address;
 LatLng latLng = null;

try {
    address = coder.getFromLocationName(strAddress,5);
    if (address==null) {
       return null;
    }
    Address location=address.get(0);
    latLng = new LatLng(location.getLatitude(),location.getLongitude());
    }


问:
Aligning multiple images in Bootstrap
I have two image images that I cant work out how to align in the centre of my container, I have tried using text-align and justify-content but nothing seems to be working. This is the same for my nav bar where I cant work out how to align the text to the right but keep the logo to the left of the bar, which I though would be the text-align? Thanks</p>

```<code> <style>

        .buttons-1{
            background-color: darkgray;
            padding-top: 30px;
            text-align: center;
        }

        .row-1{
            background-color: ghostwhite;
        }

    .photography {
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;

}
        .middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.fadehover:hover img {
  opacity: 0.3;
}

.fadehover:hover .middle {
  opacity: 1;
}

.text {
  background-color: gray;
  color: greenyellow;
  font-size: 16px;
  padding: 16px 32px;
}

        .col-md-3{
            padding: 0;
        }

        .container-fluid {

            height:100%;
            min-height: 100%;
        }

        .row{
            width:100%;
            margin:0;
            padding:0;
            height:100%;
        }
    </style>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
  <a class="navbar-brand" href="#">
    <img src="Photos/logowhite.png" alt="logo" style="width:40px;"></a>

  <ul class="nav navbar-nav navbar-right">
    <li class="nav-item">
      <a class="nav-link" href="photography.html">Photography</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link 2</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link 3</a>
    </li>
  </ul>
</nav>

 <div class="container-fluid buttons-1 ">

    <div class="row ">
            <div class="col-md-3 d-none d-md-block photography fadehover">
               <a href="photography.html">
                   <img src="Photos/Buttons/photography%20button.png" alt="Photography" class="img-fluid photography"/>
                   <div class="middle">
                        <div class="text">Photography</div>
                   </div>
                </a>
            </div>

            <div class="col-md-3 d-none d-md-block photography fadehover">
               <a href="photography.html">
                   <img src="Photos/Buttons/photography%20button.png" alt="Photography" class="img-fluid photography"/>
                   <div class="middle">
                        <div class="text">Other</div>
                   </div>
                </a>
            </div>

                 </a>
            </div>

        </div>
    </div>
</code>```

答:
Sse the css </p>

```<code>.fadehover{text-align:center !important; display:block;}
</code>```

Title: Aligning multiple images in Bootstrap

Body:
I have two image images that I cant work out how to align in the centre of my container, I have tried using text-align and justify-content but nothing seems to be working. This is the same for my nav bar where I cant work out how to align the text to the right but keep the logo to the left of the bar, which I though would be the text-align? Thanks

      Photography

      Link 2

      Link 3

Photography

Other

Body:
Sse the css

.fadehover{text-align:center !important; display:block;}


问:
Pagination not working in DRF APIView
I am using APIView for get and post items.

I wanted to implement pagination for my API using Django Rest Framework, but it is not working.

I want to show 10 items per page but when I do api/v1/items?page=1, I get all the items and if I just do api/v1/items I get an empty list.

Here is what I have done:

```<code>from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        """
        Return a list of all items of this user.
        """
        reply = {}
        page = request.GET.get('page')
        print ('page is', page)
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.filter(owner=request.user)
            paginator = Paginator(items, 1)
            items_with_pagination = paginator.page(page)
            if page is not None:
                reply['data'].extend(ItemSerializer(items_with_pagination, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data)
</code>```

答:
paginator = None worked for me

```<code>> class NotesViewSet(viewsets.ModelViewSet):
>     queryset = Notes.objects.all()
>     serializer_class = NotesWriteSerializer
>     paginator = None
</code>```

Title: Pagination not working in DRF APIView

Body:
I am using APIView for get and post items.

I wanted to implement pagination for my API using Django Rest Framework, but it is not working.

I want to show 10 items per page but when I do api/v1/items?page=1, I get all the items and if I just do api/v1/items I get an empty list.

Here is what I have done:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        """
        Return a list of all items of this user.
        """
        reply = {}
        page = request.GET.get('page')
        print ('page is', page)
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.filter(owner=request.user)
            paginator = Paginator(items, 1)
            items_with_pagination = paginator.page(page)
            if page is not None:
                reply['data'].extend(ItemSerializer(items_with_pagination, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data)

Body:
paginator = None worked for me

> class NotesViewSet(viewsets.ModelViewSet):
>     queryset = Notes.objects.all()
>     serializer_class = NotesWriteSerializer
>     paginator = None


问:
reinclude excluded file in Intellij
In Intellij, if I have an error in a source file, then when building I can choose "Exclude from Compile" by right-clicking on the file in the build output.
But, now I would like to include the file again.  Where is the menu item that lets me put it back into the build?  (The file shows in the Project window, and has a small 'x' in its icon to show it is excluded, but I see no way to get this to go away.)

Edit - I found there is a compiler.xml file, and I found I can delete the file from the "excludeFromCompile" section, but still, there must be a menu item somewhere to do this.

答:
For Mac it would be :

1) Go to Preferences:

2) Expand Build, Execution,Deployment section

3) Expand Compiler sub section

4) All the excluded classes will be available in the Excludes

5) Delete the classes you want include for compilation and press Ok.
Hope it helps.

Title: reinclude excluded file in Intellij


问:
Understanding how to compile and correctly link multiple c++ files
I want to write a basic program that involves multiple c++ files, and then compile the program from Ubuntu terminal with g++.

main.cpp

```<code>#include "other.cpp"

int main()
{
     return test();
}
</code>```

other.cpp

```<code>#include <iostream>
using namespace std;

int test()
{

     cout<<"Hello" << endl;

     return 0;
}
</code>```

...and then I run

```<code>g++ main.cpp other.cpp
</code>```

Firstly, this does not work. I get the following error:

```<code>/tmp/ccXYALau.o: In function `test()':
other.cpp:(.text+0x0): multiple definition of `test()'
/tmp/ccCIj4co.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
</code>```

Even though I am clearly not defining test() twice? (question 1)

Secondly, I had to put

```<code>#include <iostream>
using namespace std;
</code>```

in other.cpp, instead of what would make more sense, main.cpp. This is because for some reason, even when I put the iostream include and the std namespacing at the top of main.cpp, other.cpp did not recognise iostream commands (cout, endl). I thought #include statements just put the c++ file contents where the #include statement is. What is the correct thing to do, and why does this not work? (question 2)

Finally, in general if my project gets more complex with more files, how does compiling all of them and linking them work (shouldn't all the includes be in main.cpp) and what is the process to compile them?  (question 3)

答:
When you #include a file you effectively copy/paste the contents of that file at the line of the include. Therefore, yes, you are including the method test() twice in your program.

You generally only include "header" files. These generally define the signature of the methods. With the body/implementation of the method in the .cpp file.

Body:
I want to write a basic program that involves multiple c++ files, and then compile the program from Ubuntu terminal with g++.

main.cpp

#include "other.cpp"

int main()
{
     return test();
}

other.cpp

#include <iostream>
using namespace std;

int test()
{

     cout<<"Hello" << endl;

     return 0;
}

...and then I run

g++ main.cpp other.cpp

Firstly, this does not work. I get the following error:

/tmp/ccXYALau.o: In function `test()':
other.cpp:(.text+0x0): multiple definition of `test()'
/tmp/ccCIj4co.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

Even though I am clearly not defining test() twice? (question 1)

Secondly, I had to put

#include <iostream>
using namespace std;

in other.cpp, instead of what would make more sense, main.cpp. This is because for some reason, even when I put the iostream include and the std namespacing at the top of main.cpp, other.cpp did not recognise iostream commands (cout, endl). I thought #include statements just put the c++ file contents where the #include statement is. What is the correct thing to do, and why does this not work? (question 2)

Finally, in general if my project gets more complex with more files, how does compiling all of them and linking them work (shouldn't all the includes be in main.cpp) and what is the process to compile them?  (question 3)


问:
How do I identify a string using a wildcard using R?
I'd like to count the duration of some words containing the number "0" after a string, as shown in the picture (I inserted a red dot under the words with the character I'd like to work with).
Is there anything like a wildcard so that I can work only with the words containing this string?

[Picture]

答:
Use:

```<code>grep('0',resultado2$TextGridLabel)
</code>```

to find the rows with a 0. If you want to see the whole dataset subsetted by your search parameter, just use brackets:

```<code>resultado2[grep('0',resultado2$TextGridLabel),]
</code>```

Body:
Use:

grep('0',resultado2$TextGridLabel)

to find the rows with a 0. If you want to see the whole dataset subsetted by your search parameter, just use brackets:

resultado2[grep('0',resultado2$TextGridLabel),]


问:
Cannot find module 'firebase-admin'
I'm trying to push to cloud functions for my iOS app.  I followed the Firebase does and installed node in my folder but now I'm getting this error trying to push it up

```<code>Error: Error parsing triggers: Cannot find module 'firebase-admin'
</code>```

UPDATES

Trying to get latest firebase-admin returns invalid

Running npm uninstall firebase-admin
and then running npm install firebase-admin puts out these errors...

答: I got a similar issue in my project. I solved it by removing the node_modules folder with rm -rf node_modules, then in package.json changing manually the versions for both firebase-functions to 0.7.3 and fire-amin to 5.5.0. After that just run npm install again.

Title: Cannot find module 'firebase-admin'

Body:
I'm trying to push to cloud functions for my iOS app.  I followed the Firebase does and installed node in my folder but now I'm getting this error trying to push it up

Error: Error parsing triggers: Cannot find module 'firebase-admin'

UPDATES

Trying to get latest firebase-admin returns invalid

Running npm uninstall firebase-admin
and then running npm install firebase-admin puts out these errors...


问:
Highlight cells based on cell content with Excel VBA
This is for an Microsoft Excel VBA macro. What it is supposed to do, for every row, when "Late" is entered into column C, to highlight the cell 2 spaces to the left and Range of cells 3 spaces to the right through 43. So example is C4 contains "Late", highlight A4 and F4:AW4. Same goes for the word "Hold" just a different color.</p>

```<code>Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = lastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i & ":AW" & i).ClearContents
        .Range("F" & i & ":AW" & i).ClearContents

     End If
  Next i
  Application.EnableEvents = True
End With
End Sub
</code>```

答:
This should work for you...

```<code>Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Application.EnableEvents = False
For i = lastRow To 1 Step -1
 If .Range("C" & i).Value = "LATE" Then
    Debug.Print "Checking Row: " & i
    .Range("A" & i).Interior.ColorIndex = 39
    .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
 ElseIf .Range("C" & i).Value = "HOLD" Then
    .Range("A" & i).Interior.ColorIndex = 43
    .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
 Else
    .Range("A" & i & ":AW" & i).ClearContents
    .Range("F" & i & ":AW" & i).ClearContents

 End If
Next i
Application.EnableEvents = True
End With
End Sub
</code>```

Tested and seems to work fine for me :)

Body:
This is for an Microsoft Excel VBA macro. What it is supposed to do, for every row, when "Late" is entered into column C, to highlight the cell 2 spaces to the left and Range of cells 3 spaces to the right through 43. So example is C4 contains "Late", highlight A4 and F4:AW4. Same goes for the word "Hold" just a different color.

Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
  lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
  Application.EnableEvents = False
  For i = lastRow To 1 Step -1
     If .Range("C" & i).Value = "LATE" Then
        Debug.Print "Checking Row: " & i
        .Range("A" & i).Interior.ColorIndex = 39
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
     ElseIf .Range("C" & i).Value = "HOLD" Then
        .Range("A" & i).Interior.ColorIndex = 43
        .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
     Else
        .Range("A" & i & ":AW" & i).ClearContents
        .Range("F" & i & ":AW" & i).ClearContents

     End If
  Next i
  Application.EnableEvents = True
End With
End Sub

Body:
This should work for you...

Private Sub Highlight_Condition(ByVal Target As Range)

Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Application.EnableEvents = False
For i = lastRow To 1 Step -1
 If .Range("C" & i).Value = "LATE" Then
    Debug.Print "Checking Row: " & i
    .Range("A" & i).Interior.ColorIndex = 39
    .Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
 ElseIf .Range("C" & i).Value = "HOLD" Then
    .Range("A" & i).Interior.ColorIndex = 43
    .Range("F" & i & ":AW" & i).Interior.ColorIndex = 43
 Else
    .Range("A" & i & ":AW" & i).ClearContents
    .Range("F" & i & ":AW" & i).ClearContents

 End If
Next i
Application.EnableEvents = True
End With
End Sub

Tested and seems to work fine for me :)


问:
Dependency parsing tree in Spacy
I have a sentence John saw a flashy hat at the store

How to represent this as a dependency tree as shown below?

```<code>(S
      (NP (NNP John))
      (VP
        (VBD saw)
        (NP (DT a) (JJ flashy) (NN hat))
        (PP (IN at) (NP (DT the) (NN store)))))
</code>```

I got this script from here

```<code>import spacy
from nltk import Tree
en_nlp = spacy.load('en')

doc = en_nlp("John saw a flashy hat at the store")

def to_nltk_tree(node):
    if node.n_lefts + node.n_rights > 0:
        return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
    else:
        return node.orth_

[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]
</code>```

I am getting the following but I am looking for a tree(NLTK) format.

```<code>     saw
  ____|_______________
 |        |           at
 |        |           |
 |       hat        store
 |     ___|____       |
John  a      flashy  the
</code>```

答:
To re-create an NLTK-style tree for SpaCy dependency parses, try using the draw method from nltk.tree instead of pretty_print:

```<code>import spacy
from nltk.tree import Tree

spacy_nlp = spacy.load("en")

def nltk_spacy_tree(sent):
    """
    Visualize the SpaCy dependency tree with nltk.tree
    """
    doc = spacy_nlp(sent)
    def token_format(token):
        return "_".join([token.orth_, token.tag_, token.dep_])

    def to_nltk_tree(node):
        if node.n_lefts + node.n_rights > 0:
            return Tree(token_format(node),
                       [to_nltk_tree(child)
                        for child in node.children]
                   )
        else:
            return token_format(node)

    tree = [to_nltk_tree(sent.root) for sent in doc.sents]
    # The first item in the list is the full tree
    tree[0].draw()
</code>```

Note that because SpaCy only currently supports dependency parsing and tagging at the word and noun-phrase level, SpaCy trees won't be as deeply structured as the ones you'd get from, for instance, the Stanford parser, which you can also visualize as a tree:

```<code>from nltk.tree import Tree
from nltk.parse.stanford import StanfordParser

# Note: Download Stanford jar dependencies first
# See https://stackoverflow.com/questions/13883277/stanford-parser-and-nltk
stanford_parser = StanfordParser(
    model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"
)

def nltk_stanford_tree(sent):
    """
    Visualize the Stanford dependency tree with nltk.tree
    """
    parse = stanford_parser.raw_parse(sent)
    tree = list(parse)
    # The first item in the list is the full tree
    tree[0].draw()
</code>```

Now if we run both, nltk_spacy_tree("John saw a flashy hat at the store.") will produce this image and nltk_stanford_tree("John saw a flashy hat at the store.") will produce this one.

Title: Dependency parsing tree in Spacy

Body:
I have a sentence John saw a flashy hat at the store

How to represent this as a dependency tree as shown below?

(S
      (NP (NNP John))
      (VP
        (VBD saw)
        (NP (DT a) (JJ flashy) (NN hat))
        (PP (IN at) (NP (DT the) (NN store)))))

I got this script from here

import spacy
from nltk import Tree
en_nlp = spacy.load('en')

doc = en_nlp("John saw a flashy hat at the store")

def to_nltk_tree(node):
    if node.n_lefts + node.n_rights > 0:
        return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
    else:
        return node.orth_

[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]

I am getting the following but I am looking for a tree(NLTK) format.

     saw
  ____|_______________
 |        |           at
 |        |           |
 |       hat        store
 |     ___|____       |
John  a      flashy  the

Body:
To re-create an NLTK-style tree for SpaCy dependency parses, try using the draw method from nltk.tree instead of pretty_print:

import spacy
from nltk.tree import Tree

spacy_nlp = spacy.load("en")

def nltk_spacy_tree(sent):
    """
    Visualize the SpaCy dependency tree with nltk.tree
    """
    doc = spacy_nlp(sent)
    def token_format(token):
        return "_".join([token.orth_, token.tag_, token.dep_])

    def to_nltk_tree(node):
        if node.n_lefts + node.n_rights > 0:
            return Tree(token_format(node),
                       [to_nltk_tree(child)
                        for child in node.children]
                   )
        else:
            return token_format(node)

    tree = [to_nltk_tree(sent.root) for sent in doc.sents]
    # The first item in the list is the full tree
    tree[0].draw()

Note that because SpaCy only currently supports dependency parsing and tagging at the word and noun-phrase level, SpaCy trees won't be as deeply structured as the ones you'd get from, for instance, the Stanford parser, which you can also visualize as a tree:

from nltk.tree import Tree
from nltk.parse.stanford import StanfordParser

# Note: Download Stanford jar dependencies first
# See https://stackoverflow.com/questions/13883277/stanford-parser-and-nltk
stanford_parser = StanfordParser(
    model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"
)

def nltk_stanford_tree(sent):
    """
    Visualize the Stanford dependency tree with nltk.tree
    """
    parse = stanford_parser.raw_parse(sent)
    tree = list(parse)
    # The first item in the list is the full tree
    tree[0].draw()

Now if we run both, nltk_spacy_tree("John saw a flashy hat at the store.") will produce this image and nltk_stanford_tree("John saw a flashy hat at the store.") will produce this one.


问:
Finding tweets containg a keyword in R and updating
Im using R in order to find words in strings that way i can categorize them in 2 columns. Im using grep to find all of the rows where the keyword exists, but im having trouble writing a loop to update another column with a value of 1 if the keyword exists in the string. Tweet.Text is the column name containing the strings, @casekeenum7 is the keyword im looking for and Keenum is the column that I would like to update with a value of 1 for each row that contains the keyword.

Code:

```<code>for (i in 1:length(Tweet.Text)){
  if(grep('@casekeenum',Tweet.Text[i])){
    Keenum[i]==1
  }
}
</code>```

Error:

```<code>Error in if (grep("@casekeenum7", Tweet.Text[i])) { :
  argument is of length zero
</code>```

答:
You do not need a for loop:

```<code>df = data.frame(Tweet.Text=c("Hello","@casekeenum"),
                Keenum=c(0,0))

df$Keenum[grepl("@casekeenum",df$Tweet.Text)]=1
</code>```

returns:

```<code>   Tweet.Text Keenum
1       Hello      0
2 @casekeenum      1
</code>```

Body:
Im using R in order to find words in strings that way i can categorize them in 2 columns. Im using grep to find all of the rows where the keyword exists, but im having trouble writing a loop to update another column with a value of 1 if the keyword exists in the string. Tweet.Text is the column name containing the strings, @casekeenum7 is the keyword im looking for and Keenum is the column that I would like to update with a value of 1 for each row that contains the keyword.

Code:

for (i in 1:length(Tweet.Text)){
  if(grep('@casekeenum',Tweet.Text[i])){
    Keenum[i]==1
  }
}

Error:

Error in if (grep("@casekeenum7", Tweet.Text[i])) { :
  argument is of length zero

Body:
You do not need a for loop:

df = data.frame(Tweet.Text=c("Hello","@casekeenum"),
                Keenum=c(0,0))

df$Keenum[grepl("@casekeenum",df$Tweet.Text)]=1

returns:

   Tweet.Text Keenum
1       Hello      0
2 @casekeenum      1


问:
use text to speech in making call on twilio php api
Good day,

Im creating reminder app that calls a number in certain time, currently I was using an uploaded mp3 file on my server:

here the code:

```<code>$sid = "ACxxxxxxxxxx";
$token = "2xxxxxxxxx";
$client = new Client($sid, $token);
$call = $client->calls->create(
         "$phone_number_to","$phone_number_from",
          array("url" =>
          "https://xxxxx.com/asset/mp3/reminder.mp3")
            );
$csid = $call->sid;
</code>```

the above code works, but now I wanted to use the text to speech feature on twilio to have a more customized voicemail per reminder..

how do I do this using $client-> api? Im not really familiar on how TwiML works though, maybe thats why im confused.

thanks!

答:
You change this line of your current code "url" => "https://xxxxx.com/asset/mp3/reminder.mp3" so that the URL points at the url hosting the script you want to use to generate your dynamic TwiML.

Then use the php TwiML library to generate the TwiML, it's pretty straightforward. We have a database with all out customers details in, I use code something along these lines to get their details based on caller ID and have Twilio greet them by first name:

```<code>$booked = SELECT * FROM table WHERE phone = $caller;
$name = explode(" ", $booked->name);
$firstname = $name[0];
$response->say("Hello $firstname. Thanks for calling......");
</code>```

It's ok but it's a bit robotic. We ended up extracting the 50 most common first names from the database and having a voiceover artist record greetings for each one. For callers with one of those 50 names we serve a specific mp3 file, everyone else gets the robot.

Body:
Good day,

Im creating reminder app that calls a number in certain time, currently I was using an uploaded mp3 file on my server:

here the code:

$sid = "ACxxxxxxxxxx";
$token = "2xxxxxxxxx";
$client = new Client($sid, $token);
$call = $client->calls->create(
         "$phone_number_to","$phone_number_from",
          array("url" =>
          "https://xxxxx.com/asset/mp3/reminder.mp3")
            );
$csid = $call->sid;

the above code works, but now I wanted to use the text to speech feature on twilio to have a more customized voicemail per reminder..

how do I do this using $client-> api? Im not really familiar on how TwiML works though, maybe thats why im confused.

thanks!

Body:
You change this line of your current code "url" => "https://xxxxx.com/asset/mp3/reminder.mp3" so that the URL points at the url hosting the script you want to use to generate your dynamic TwiML.

Then use the php TwiML library to generate the TwiML, it's pretty straightforward. We have a database with all out customers details in, I use code something along these lines to get their details based on caller ID and have Twilio greet them by first name:

$booked = SELECT * FROM table WHERE phone = $caller;
$name = explode(" ", $booked->name);
$firstname = $name[0];
$response->say("Hello $firstname. Thanks for calling......");

It's ok but it's a bit robotic. We ended up extracting the 50 most common first names from the database and having a voiceover artist record greetings for each one. For callers with one of those 50 names we serve a specific mp3 file, everyone else gets the robot.


问:
How to move 12 digit numbers from richtextbox to textbox2
I want to move 12 digit numbers from richtextbox to textbox2 by a program.

I enter these words for richtextbox

```<code>sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd
</code>```

I need to get only these 12 digit numbers to  textbox2..

I tried this code but it types System.Text.RegularExpressions.MatchCollection not these digits

Here i use code for that

```<code>private void button2_Click(object sender, EventArgs e)
{
    Regex RX = new Regex("[0-9]{1,12}$");
    textBox2.Text = (RX.Matches(richTextBox1.Text)).ToString();
}
</code>```

I don't know how to move these numebrs to the textbox2.. Please help me enter image description here

答:
I have created a method that returns a collection of strings, each containing a number.

```<code>public static IEnumerable<string> SeparateNumbers(string inputText)
{
    var matches = Regex.Matches(inputText, "[0-9]{12}");

    foreach (Match match in matches)
    {
        yield return inputText.Substring(match.Index, match.Length);
    }
}
</code>```

You would simply use it like this. I have also added a way to comma separate them again:

```<code>string inputText = "sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd";
var separatedNumbers = SeparateNumbers(inputText)
    .ToArray();
string numbersOnly = string.Join(',', separatedNumbers);
</code>```

I hope this helps.

Edit:

The reason that it gives you this: System.Text.RegularExpressions.MatchCollection is because of the default implementation of the ToString method, it simply gives you the full name of the type (including namespaces).

Also, if you want it to match any amount of numbers up to 12, simply change the regex to [0-9]{1,12} as you did initially.

Body:
I want to move 12 digit numbers from richtextbox to textbox2 by a program.

I enter these words for richtextbox

sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd

I need to get only these 12 digit numbers to  textbox2..

I tried this code but it types System.Text.RegularExpressions.MatchCollection not these digits

Here i use code for that

private void button2_Click(object sender, EventArgs e)
{
    Regex RX = new Regex("[0-9]{1,12}$");
    textBox2.Text = (RX.Matches(richTextBox1.Text)).ToString();
}

I don't know how to move these numebrs to the textbox2.. Please help me enter image description here

Body:
I have created a method that returns a collection of strings, each containing a number.

public static IEnumerable<string> SeparateNumbers(string inputText)
{
    var matches = Regex.Matches(inputText, "[0-9]{12}");

    foreach (Match match in matches)
    {
        yield return inputText.Substring(match.Index, match.Length);
    }
}

You would simply use it like this. I have also added a way to comma separate them again:

string inputText = "sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd";
var separatedNumbers = SeparateNumbers(inputText)
    .ToArray();
string numbersOnly = string.Join(',', separatedNumbers);

I hope this helps.

Edit:

The reason that it gives you this: System.Text.RegularExpressions.MatchCollection is because of the default implementation of the ToString method, it simply gives you the full name of the type (including namespaces).

Also, if you want it to match any amount of numbers up to 12, simply change the regex to [0-9]{1,12} as you did initially.


问:
Android Management API and MDM
I was going through the new Android Management API.

Now, Google has their own app called Android Device Policy which acts as an MDM app but MDM apps don't require a factory reset but why do we have to factory reset the device when enrolling with AFW using Android Management API.

Can't the Android Device Policy be manually installed and set as the device administrator?

答:
The Android Management API currently only supports the Device Owner mode, which has to be set during device setup after factory reset.

The Device Administrator mode, which doesn't require factory reset, is not supported by the Android Management API (at least not for now). You could manually set Android Device Policy as a device administrator but you wouldn't be able to use the API to manage the device.

Device Owner was introduced in Android 5.0, it gives much more capabilities than Device Administrator but requires factory reset as a security measure to prevent someone from taking full control of an existing device and its data.

Title: Android Management API and MDM


问:
javascript stopPropagation not working on input field
Have a simple div array with values that the user will choose from and an "other" field where they can put in their own number. I have a clearing div (lower right) that will clear the selection and input field; however, I also want to have a click event on the containing div as well.

I've searched and nothing seems to do the trick, the one that comes close is using stopPropagation so the click on a div doesn't trigger the containing div's script. It's working on all the divs but for some reason isn't working on the input field. everytime i click the number scrubber or try typing in the field it calls the reset script of the containing div. Is there something about an input field that causes the stopPropagation to not work? or am i missing something. None of the other things i found seemed to solve it.

HTML

```<code><div id="don_options">
    <div class="group">
        <div class="col"><span class="don">xxx</span></div>
        <div class="col"><span class="don">xxx</span></div>
        <div class="col"><span class="don">xxx</span></div>
    </div>

    <div class="group">
        <div class="col"><span class="don">xxx</span></div>
        <div class="col"><span class="don">xxx</span></div>
        <div class="col"><span class="don">xxx</span></div>
    </div>

    <div class="group">
        <div class="col"><span class="don">xxx</span></div>
        <div class="col"><span class="don">xxx</span></div>
        <div class="col"><span class="don">xxx</span></div>
    </div>

    <div class="group">
        <div class="col"><span class="don">Other</span><br class="mobile"><input id="other" name="other" type="number" min="3" step=".01" value="" size="25" maxlength="255" class="form-text2" placeholder="Other"></div>
        <div class="col"> </div>
        <div class="col"><span class="don">Clear</span></div>
    </div>
</div>
</code>```

Javascript

```<code>$('#don_options').on('click', function(e) {
    resetDon();
});

$('.don').on('click', function(e) {
    e.stopPropagation(); // stop bubbling to parent element
    //e.preventDefault();
    //e.cancelBubble = true;
    //e.stopImmediatePropagation();

    //lots of buttonesk goodness here
});

$('#other').on('keyup change click', function(e) {
    e.stopPropagation(); // stop bubbling to parent element
    //e.preventDefault();
    //e.cancelBubble = true;
    //e.stopImmediatePropagation();

    //more goodness here for the input field
});

function resetDon() {
    //clear "buttons" here
}
</code>```

Adding a quick screenshot for visual. Black box is the containing div

答:
In this code:

```<code>$('.don').on('click', function() {
   e.stopPropagation(); // stop bubbling to parent element
   ...
});
</code>```

e is undefined. It should be the function parameter:

```<code>$('.don').on('click', function(e) {
   e.stopPropagation(); // stop bubbling to parent element
   ...
});
</code>```

See full docs for $.on(). The event should be passed as parameter of the function (handler). Of course, you can skip it whenever you don't want to interact with it.

Body:
Have a simple div array with values that the user will choose from and an "other" field where they can put in their own number. I have a clearing div (lower right) that will clear the selection and input field; however, I also want to have a click event on the containing div as well.

I've searched and nothing seems to do the trick, the one that comes close is using stopPropagation so the click on a div doesn't trigger the containing div's script. It's working on all the divs but for some reason isn't working on the input field. everytime i click the number scrubber or try typing in the field it calls the reset script of the containing div. Is there something about an input field that causes the stopPropagation to not work? or am i missing something. None of the other things i found seemed to solve it.

HTML

xxx

xxx

xxx

xxx

xxx

xxx

xxx

xxx

xxx

Other
<input id="other" name="other" type="number" min="3" step=".01" value="" size="25" maxlength="255" class="form-text2" placeholder="Other">

Clear

Javascript

$('#don_options').on('click', function(e) {
    resetDon();
});

$('.don').on('click', function(e) {
    e.stopPropagation(); // stop bubbling to parent element
    //e.preventDefault();
    //e.cancelBubble = true;
    //e.stopImmediatePropagation();

    //lots of buttonesk goodness here
});

$('#other').on('keyup change click', function(e) {
    e.stopPropagation(); // stop bubbling to parent element
    //e.preventDefault();
    //e.cancelBubble = true;
    //e.stopImmediatePropagation();

    //more goodness here for the input field
});

function resetDon() {
    //clear "buttons" here
}

Adding a quick screenshot for visual. Black box is the containing div

Body:
In this code:

$('.don').on('click', function() {
   e.stopPropagation(); // stop bubbling to parent element
   ...
});

e is undefined. It should be the function parameter:

$('.don').on('click', function(e) {
   e.stopPropagation(); // stop bubbling to parent element
   ...
});

See full docs for $.on(). The event should be passed as parameter of the function (handler). Of course, you can skip it whenever you don't want to interact with it.


问:
Cannot call Google Apps Script doPost() method from Twilio number

Trying to receive an SMS at my Twilio number and send a POST request to a Google Apps Script app URL as a result of the received SMS.

I have this doPost() message:

```<code>function doPost(request) {

    return ContentService.createTextOutput("User says: "+JSON.stringify(request));
}
</code>```

Some text should be spit out containing the request data.

My doPost() method never gets called.  I can't tell if the POST request is actually being sent by Twilio.  I see in the Twilio number message log that my SMS is received by Twilio.  But after that I can't tell.  I have the Twilio number configured for webhook - HTTP POST, and the published URL of my Google Apps Script project.  If I change that to HTTP GET my doGet() method DOES get called.  I need to doPost() method called, though.  any suggestions?  TIA.

答: I decided to just use doGet().  See my response to the previous comment.</p>

Body:
Trying to receive an SMS at my Twilio number and send a POST request to a Google Apps Script app URL as a result of the received SMS.

I have this doPost() message:

function doPost(request) {

    return ContentService.createTextOutput("User says: "+JSON.stringify(request));
}

Some text should be spit out containing the request data.

My doPost() method never gets called.  I can't tell if the POST request is actually being sent by Twilio.  I see in the Twilio number message log that my SMS is received by Twilio.  But after that I can't tell.  I have the Twilio number configured for webhook - HTTP POST, and the published URL of my Google Apps Script project.  If I change that to HTTP GET my doGet() method DOES get called.  I need to doPost() method called, though.  any suggestions?  TIA.


问:
strftime() method?
I have a table in my database and the date column is in String format.

I tried using the strftime() function in a WHERE clause to get all the data for a specific month

```<code> String whereStatement=Constant.daily.Col_Remove +" = ? AND  "
                        +Constant.daily.Col_carowners_id +" IN( " +idOfMergeData+" ) AND "
                        +"strftime('%m', '"+Constant.daily.Col_date+"' ) = ? ";
 String [] ArgValues={"0",date_in_month};
</code>```

but no data is retrieved.

答:
Does Col_Remove really contain strings? If not, don't use a parameter.

And you are using quotes around the date column name, which makes it into a string and not a colum reference. Remove them:

```<code>                   +"strftime('%m', "+Constant.daily.Col_date+" ) = ? ";
                                   ^                           ^
</code>```

Title: strftime() method?

Body:
I have a table in my database and the date column is in String format.

I tried using the strftime() function in a WHERE clause to get all the data for a specific month

 String whereStatement=Constant.daily.Col_Remove +" = ? AND  "
                        +Constant.daily.Col_carowners_id +" IN( " +idOfMergeData+" ) AND "
                        +"strftime('%m', '"+Constant.daily.Col_date+"' ) = ? ";
 String [] ArgValues={"0",date_in_month};

but no data is retrieved.

Body:
Does Col_Remove really contain strings? If not, don't use a parameter.

And you are using quotes around the date column name, which makes it into a string and not a colum reference. Remove them:

                   +"strftime('%m', "+Constant.daily.Col_date+" ) = ? ";
                                   ^                           ^


问:
React.js website build works on one host, but not another
I am new to react.js . I have created a react website using create-rect-app. I have run: npm run build in git and got my static site files. Everything works on the test host, however when i moved hosts only index page works and navigating to other page gives 404 error. For routing im using react-router-dom.

How can i get my page to work on the other host?

Working host: http://000webhost.com/
Badly working host is some local provider

Edit: Basically i have pages such as /Home and /Contact.
Im using react-router-dom.

code:

```<code>import React, { Component } from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import logo from './logo.svg';
import './App.css';

import Home from './pages/Home.jsx';
import Contacts from './pages/Contacts.jsx';
import Our_products from './pages/Our_products.jsx';

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route exact path ="/" component={Home}/>
          <Route exact path ="/Home" component={Home}/>
          <Route exact path ="/Contacts" component={Contacts}/>
          <Route exact path ="/Our-products" component={Our_products}/>
        </div>
      </Router>
    );
  }
}

export default App;
</code>```

My index is linked to /Home as you can see from code. i have uploaded Build folder to public_html on both hosting platforms. On one site works normaly, on the other only /Home page shows up.

答:
So, you can ignore this, but what helped is changing

href="/" />```
</div>
</div>
</p>

<p>to </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><Link to="/" /></code>```

. Basically one hosting provider could render links as

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

<p>other only as </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><Link /></code>```

Body:
I am new to react.js . I have created a react website using create-rect-app. I have run: npm run build in git and got my static site files. Everything works on the test host, however when i moved hosts only index page works and navigating to other page gives 404 error. For routing im using react-router-dom.

How can i get my page to work on the other host?

Working host: http://000webhost.com/
Badly working host is some local provider

Edit: Basically i have pages such as /Home and /Contact.
Im using react-router-dom.

code:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import logo from './logo.svg';
import './App.css';

import Home from './pages/Home.jsx';
import Contacts from './pages/Contacts.jsx';
import Our_products from './pages/Our_products.jsx';

class App extends Component {
  render() {
    return (
      <Router>

          <Route exact path ="/" component={Home}/>
          <Route exact path ="/Home" component={Home}/>
          <Route exact path ="/Contacts" component={Contacts}/>
          <Route exact path ="/Our-products" component={Our_products}/>

      </Router>
    );
  }
}

export default App;

My index is linked to /Home as you can see from code. i have uploaded Build folder to public_html on both hosting platforms. On one site works normaly, on the other only /Home page shows up.

Body:
So, you can ignore this, but what helped is changing

<a href="/" />

to

<Link to="/" />

. Basically one hosting provider could render links as

<a />

other only as

<Link />


问:
How to remove leading "0." in a numeric R variable
How can one concisely change a numeric R variable (keeping it numeric) so that, e.g.,
"-0.34" becomes simply "-.34"?</p>

答: If it's for reporting in R Markdown I use the package MOTE with the function apa() and code: apa(-0.34, 2, FALSE) this will return -.34 in my documents.


问:
Print string while adding newlines
I'm trying to print out a string with embedded ruby to a webpage, if I use the following it ends up going off of the page.

```<code><%= comment.body %>
</code>```

I want to do something like this so that it automatically prints everything with new lines

```<code><%= comment.body[0..136] %>
<%= "\n" %>
<%= comment.body[137..250] %>
</code>```

I've done the following however it prints the characters with spaces between them and ignores spaces in the string.

```<code><% for i in 0..comment.body.length do %>
<%= i %>
<% end %>
</code>```

Thanks

答:
Why not use HTML? </p>

```<code><% for i in 0..comment.body.length do %>
  <%= i %><br>
<% end %>
</code>```

Title: Print string while adding newlines

Body:
I'm trying to print out a string with embedded ruby to a webpage, if I use the following it ends up going off of the page.

<%= comment.body %>

I want to do something like this so that it automatically prints everything with new lines

<%= comment.body[0..136] %>
<%= "\n" %>
<%= comment.body[137..250] %>

I've done the following however it prints the characters with spaces between them and ignores spaces in the string.

<% for i in 0..comment.body.length do %>
<%= i %>
<% end %>

Thanks

Body:
Why not use HTML?

<% for i in 0..comment.body.length do %>
  <%= i %><br>
<% end %>


问:
iPhone popup menu like iPad popover?
How can i implement this popup menu in iphone app like a popover in ipad?

EDIT: This is the best at moment: https://github.com/runway20/PopoverView

答:
You would have to manually instantiate a UIView using a custom background image or drawing with transparency, add some UIButtons (or other type of custom view) on top, and also somehow handle all touches outside that view.

Note that is is non-standard UI.  An actionsheet would be more HIG compliant.

Title: iPhone popup menu like iPad popover?

ContentLicense: CC BY-SA 2.5