问:
Improving performance of drawing Tiled bitmaps in wpf
I'm looking for a way to improve the performance of some drawing I am doing. Currently it is a 32x32 grid of tiles that I am drawing. Using the following code to draw onto the drawing context

```<code>for (int x = startX; x < endX; x++)
        {
            for (int y = startY; y < endY; y++)
            {
                dg.Children.Add(
                    new ImageDrawing(_mapTiles[GameWorldObject.GameMap[x, y].GraphicsTile.TileStartPoint],
                        new Rect(CountX * 8, CountY * 8, 8, 8)
                        ));

                dg.Children.Add(
                    new GeometryDrawing(
                        null,
                        new Pen(
                            new SolidColorBrush(
                                Color.FromRgb(255, 0, 20)), .3),
                                new RectangleGeometry(
                                    new Rect(CountX * 8, CountY * 8, 8, 8)
                                )
                            )
                        );

                CountY++;
            }
            CountY = 0;
            CountX++;
        }

        dc.DrawDrawing(dg);
</code>```

The Image I am drawing is a CachedBitmap. Even using a CachedBitmap, I still have a delay of about a half second each time I need to redraw the Canvas.

Not sure if there is a more performant way to handle drawing to this grid. Eventually I want to expand control to function as a mini-map, so I need to keep that in mind.

Also, I tried previously to just draw each bitmap directly to the drawing context but that seems a bit slower.

答:
If it's mostly static minimap draw it into an Image, and draw that image. Or you can do a big image, where you draw the whole map into it, and just draw the current visible part of it.

Edit: And maybe this blog post worth a check, whether you are drawing it with software or hardware acceleration on.

Body:
I'm looking for a way to improve the performance of some drawing I am doing. Currently it is a 32x32 grid of tiles that I am drawing. Using the following code to draw onto the drawing context

for (int x = startX; x < endX; x++)
        {
            for (int y = startY; y < endY; y++)
            {
                dg.Children.Add(
                    new ImageDrawing(_mapTiles[GameWorldObject.GameMap[x, y].GraphicsTile.TileStartPoint],
                        new Rect(CountX * 8, CountY * 8, 8, 8)
                        ));

                dg.Children.Add(
                    new GeometryDrawing(
                        null,
                        new Pen(
                            new SolidColorBrush(
                                Color.FromRgb(255, 0, 20)), .3),
                                new RectangleGeometry(
                                    new Rect(CountX * 8, CountY * 8, 8, 8)
                                )
                            )
                        );

                CountY++;
            }
            CountY = 0;
            CountX++;
        }

        dc.DrawDrawing(dg);

The Image I am drawing is a CachedBitmap. Even using a CachedBitmap, I still have a delay of about a half second each time I need to redraw the Canvas.

Not sure if there is a more performant way to handle drawing to this grid. Eventually I want to expand control to function as a mini-map, so I need to keep that in mind.

Also, I tried previously to just draw each bitmap directly to the drawing context but that seems a bit slower.


来源: stackexchange

问:
Android: Unable to retrieve the Uri of a folder
I have an app which allows the user to pick a folder via the Android file picker Intent.ACTION_OPEN_DOCUMENT_TREE and then creates a ZIP file in the selected folder which eventually will be shared.
I can retrieve the selected folder Uri via Uri uri = data.getData(); in the OnActivityResult function.

This works, an example Uri with my SD card selected looks like this: content://com.android.externalstorage.documents/tree/15E6-0F1A%3A

Now I need to temporarily store a ZIP file in the applications cache folder, before sharing it out. But I struggle to get to the Content Uri of the cache folder?

What I thought I need to do is the below:

```<code>File filePath = new File(this.getCacheDir(), "");
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", filePath);
</code>```

And the send the Uri on to the function which creates and shares the ZIP file, but calling FileProvider.getUriForFile with a folder leads to a crash of the application. java.lang.StringIndexOutOfBoundsException

As soon as I create a file in the cache folder and use this file handle to call FileProvider.getUriForFile I get a proper Uri:

```<code>File filePath = new File(this.getCacheDir(), "");
File newFile = new File(filePath, "tmpFileName");
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", newFile);
</code>```

So it seems like FileProvider.getUriForFile can't handle folders?

I searched up and down but somehow everything I found was specifically about files, where I need a folder Uri. I have tried alternatives like DocumentFile and File but all I ended up with is "file" Uris' and not "content" Uris.

Therefore my question is, does anyone know of a way to get a content Uri from a folder, or more specifically, how can I get the content Uri of this.getCacheDir()?

答:
I can retrieve the selected folder Uri via Uri uri = data.getData(); in the OnActivityResult function.

That is not a folder. It is a document tree. Note, in particular, that it does not have to represent a directory on a filesystem.

Now I need to temporarily store a ZIP file in the applications cache folder, before sharing it out

Create a File object pointing to your desired destination file in getCacheDir(), then use standard Java file I/O to copy or create your ZIP file using that File object. Note that no Uri values are needed for this.

So it seems like FileProvider.getUriForFile can't handle folders?

Correct.

And the send the Uri on to the function which creates and shares the ZIP file

The Uri that you share will point to the ZIP file. You do not need a Uri that somehow points to getCacheDir(). You can use ordinary file I/O to create the ZIP file, without involving a Uri.

how can I get the content Uri of this.getCacheDir()?

There is nothing that is part of Android that really supports this concept, and you do not need it.

ContentLicense: CC BY-SA 4.0

Body:
I have an app which allows the user to pick a folder via the Android file picker Intent.ACTION_OPEN_DOCUMENT_TREE and then creates a ZIP file in the selected folder which eventually will be shared.
I can retrieve the selected folder Uri via Uri uri = data.getData(); in the OnActivityResult function.

This works, an example Uri with my SD card selected looks like this: content://com.android.externalstorage.documents/tree/15E6-0F1A%3A

Now I need to temporarily store a ZIP file in the applications cache folder, before sharing it out. But I struggle to get to the Content Uri of the cache folder?

What I thought I need to do is the below:

File filePath = new File(this.getCacheDir(), "");
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", filePath);

And the send the Uri on to the function which creates and shares the ZIP file, but calling FileProvider.getUriForFile with a folder leads to a crash of the application. java.lang.StringIndexOutOfBoundsException

As soon as I create a file in the cache folder and use this file handle to call FileProvider.getUriForFile I get a proper Uri:

File filePath = new File(this.getCacheDir(), "");
File newFile = new File(filePath, "tmpFileName");
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", newFile);

So it seems like FileProvider.getUriForFile can't handle folders?

I searched up and down but somehow everything I found was specifically about files, where I need a folder Uri. I have tried alternatives like DocumentFile and File but all I ended up with is "file" Uris' and not "content" Uris.

Therefore my question is, does anyone know of a way to get a content Uri from a folder, or more specifically, how can I get the content Uri of this.getCacheDir()?


问:
Change image source from JavaScript in spring boot
I am trying to change the source of an image in an html document every few seconds with a JavaScript function within a spring boot project but the typical way of changing the source does not appear to be working. I have tried to match the format of setting the image source with no luck either.
Here is where I initially set the source: </p>

```<code><!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<body>

<div style="text-align:center">
    <button onclick="playPause()">Play/Pause</button>
    <button onclick="zoomOut()">Zoom Out</button>
    <button onclick="zoomIn()">Zoom In</button>
    <br><br>
    <img id = "img1" src="../static/images/6car_1.png"; th:src="@{images/6car_1.png}"/>
</div>

    <script>
        var zoom = 6;
        var initialPath = "../static/images/";
        var count = 1;
        var isPlaying = true;
        playPhotos();
        function playPause() {
            if (isPlaying)
                isPlaying = false;
            else{
                isPlaying = true;
                playPhotos();
            }

        }
        function playPhotos(){
            var firstPart = initialPath  + zoom + "car_" + count +".png"
            var secondPart = "@{images/" + zoom + "car_" + count +".png}"
            if(count <=13){
                document.getElementById("img1").src = firstPart;
                th:src = secondPart;
                count++;
            }
            else{
                count = 1;
                document.getElementById("img1").src = firstPart;
                th:src = secondPart;
            }
            if(isPlaying){
                setTimeout("playPhotos()",200);
            }

        }

        function zoomOut(){
            if((zoom - 1) >= 1){
                zoom--;
            }
        }

        function zoomIn(){
            if((zoom + 1) <= 10){
                zoom++;
            }
        }
    </script>

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

答:
I edited it and it works because I created the variable "zoom" , "isPlaying" and called playPhotos (). You didn't specify those details ? If you have an error other than function operation, please upload all of your code as a snippet. I'll update my answer accordingly.

var initialPath = "../static/images/";
var count = 1;
var isPlaying = true;
let zoom = "zoom"
playPhotos()

function playPhotos() {
  var firstPart = `${initialPath}${zoom}car_${count}.png`; //try
  var secondPart = `@{images/${zoom}car_${count}.png`;  // try
  if (count <= 13) {
    document.getElementById("img1").src = firstPart;
    th: src = secondPart;
    count++;
  } else {
    count = 1;
    document.getElementById("img1").src = firstPart;
    th: src = secondPart;
    count++;

  }
  if (isPlaying) {
    setTimeout("playPhotos()", 200);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="img1" src="../static/images/6car_1.png" ; th:src="@{images/6car_1.png}" /></code>```

Body:
I am trying to change the source of an image in an html document every few seconds with a JavaScript function within a spring boot project but the typical way of changing the source does not appear to be working. I have tried to match the format of setting the image source with no luck either.
Here is where I initially set the source:

<!DOCTYPE html>

    <button onclick="playPause()">Play/Pause</button>
    <button onclick="zoomOut()">Zoom Out</button>
    <button onclick="zoomIn()">Zoom In</button>

Body:
I edited it and it works because I created the variable "zoom" , "isPlaying" and called playPhotos (). You didn't specify those details ? If you have an error other than function operation, please upload all of your code as a snippet. I'll update my answer accordingly.

var initialPath = "../static/images/";
var count = 1;
var isPlaying = true;
let zoom = "zoom"
playPhotos()

function playPhotos() {
  var firstPart = `${initialPath}${zoom}car_${count}.png`; //try
  var secondPart = `@{images/${zoom}car_${count}.png`;  // try
  if (count <= 13) {
    document.getElementById("img1").src = firstPart;
    th: src = secondPart;
    count++;
  } else {
    count = 1;
    document.getElementById("img1").src = firstPart;
    th: src = secondPart;
    count++;

  }
  if (isPlaying) {
    setTimeout("playPhotos()", 200);
  }
}

<img id="img1" src="../static/images/6car_1.png" ; th:src="@{images/6car_1.png}" />


问:
trying to understand function construction
I am trying to understand function construction so I can cut down on my repeated code. All the snippets I have see deal with returning values and was hoping someone could shed some light on why this doesn't work.</p>

```<code><div id = 'box1' style = 'background-color: green; height: 100px; width: 50px' >
</div>

var box =  $('#box1');

function pushCard(x){
    if(x.style.opacity == 0.5){
    x.style.opacity = 1;
}
else {
x.style.opacity = 0.5;
}

}

box.click(pushCard(box));
</code>```

答:
You don't want to call the function as you pass it. You can just pass the function, then when you click it will pass the event. The element is the event target

var box = $('#box1');

function pushCard(event) {
  let x = event.target
  if (x.style.opacity == 0.5) {
    x.style.opacity = 1;
  } else {
    x.style.opacity = 0.5;
  }
}

box.click(pushCard);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div></code>```

You can also use this to get the clicked object:

var box = $('#box1');

function pushCard() {
  if (this.style.opacity == 0.5) {
    this.style.opacity = 1;
  } else {
    this.style.opacity = 0.5;
  }
}

box.click(pushCard);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div></code>```

Body:
I am trying to understand function construction so I can cut down on my repeated code. All the snippets I have see deal with returning values and was hoping someone could shed some light on why this doesn't work.

var box =  $('#box1');

function pushCard(x){
    if(x.style.opacity == 0.5){
    x.style.opacity = 1;
}
else {
x.style.opacity = 0.5;
}

}

box.click(pushCard(box));

Body:
You don't want to call the function as you pass it. You can just pass the function, then when you click it will pass the event. The element is the event target

var box = $('#box1');

function pushCard(event) {
  let x = event.target
  if (x.style.opacity == 0.5) {
    x.style.opacity = 1;
  } else {
    x.style.opacity = 0.5;
  }
}

box.click(pushCard);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div>

You can also use this to get the clicked object:

var box = $('#box1');

function pushCard() {
  if (this.style.opacity == 0.5) {
    this.style.opacity = 1;
  } else {
    this.style.opacity = 0.5;
  }
}

box.click(pushCard);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div>


问:
Syntax for three-piece segmented regression using NLS in R when concave
My goal is to fit a three-piece (i.e., two break-point) regression model to make predictions using propagate's predictNLS function, making sure to define knots as parameters, but my model formula seems off.

I've used the segmented package to estimate the breakpoint locations (used as starting values in NLS), but would like to keep my models in the NLS format, specifically, nlsLM {minipack.lm} because I am fitting other types of curves to my data using NLS, want to allow NLS to optimize the knot values, am sometimes using variable weights, and need to be able to easily calculate the Monte Carlo confidence intervals from propagate. Though I'm very close to having the right syntax for the formula, I'm not getting the expected/required behaviour near the breakpoint(s). The segments SHOULD meet directly at the breakpoints (without any jumps), but at least on this data, I'm getting a weird local minimum at the breakpoint (see plots below).

Below is an example of my data and general process. I believe my issue to be in the NLS formula.

```<code>library(minpack.lm)
library(segmented)

y <- c(-3.99448113, -3.82447011, -3.65447803, -3.48447030, -3.31447855, -3.14448753, -2.97447972, -2.80448401, -2.63448380, -2.46448069, -2.29448796, -2.12448912, -1.95448783, -1.78448797, -1.61448563, -1.44448719, -1.27448469, -1.10448651, -0.93448525, -0.76448637, -0.59448626, -0.42448586, -0.25448588, -0.08448548,  0.08551417,  0.25551393,  0.42551411,  0.59551395,  0.76551389,  0.93551398)

x <- c(61586.1711, 60330.5550, 54219.9925, 50927.5381, 48402.8700, 45661.9175, 37375.6023, 33249.1248, 30808.6131, 28378.6508, 22533.3782, 13901.0882, 11716.5669, 11004.7305, 10340.3429,  9587.7994,  8736.3200,  8372.1482,  8074.3709,  7788.1847,  7499.6721,  7204.3168,  6870.8192,  6413.0828,  5523.8097,  3961.6114,  3460.0913,  2907.8614, 2016.1158,   452.8841)

df<- data.frame(x,y)

#Use Segmented to get estimates for parameters with 2 breakpoints
my.seg2 <- segmented(lm(y ~ x, data = df), seg.Z = ~ x, npsi = 2)

#extract knot, intercept, and coefficient values to use as NLS start points
my.knot1 <- my.seg2$psi[1,2]
my.knot2 <- my.seg2$psi[2,2]
my.m_2 <- slope(my.seg2)$x[1,1]
my.b1 <- my.seg2$coefficients[[1]]
my.b2 <- my.seg2$coefficients[[2]]
my.b3 <- my.seg2$coefficients[[3]]

#Fit a NLS model to ~replicate segmented model. Presumably my model formula is where the problem lies
my.model <- nlsLM(y~m*x+b+(b2*(ifelse(x>=knot1&x<=knot2,1,0)*(x-knot1))+(b3*ifelse(x>knot2,1,0)*(x-knot2-knot1))),data=df, start = c(m = my.m_2, b = my.b1, b2 = my.b2, b3 = my.b3, knot1 = my.knot1, knot2 = my.knot2))
</code>```

How it should look

```<code>plot(my.seg2)
</code>```

How it does look

```<code>plot(x, y)
lines(x=x, y=predict(my.model), col='black', lty = 1, lwd = 1)
</code>```

I was pretty sure I had it "right", but when the 95% confidence intervals are plotted with the line and prediction resolution (e.g., the density of x points) is increased, things seem dramatically incorrect.

Thank you all for your help.

答:
It may, in part, reflect a limitation in segmented. segmented returns a single change point value without quantifying the associated uncertainty. Redoing the analysis using mcp which returns Bayesian posteriors, we see that the second change point is bimodally distributed:

library(mcp)
model = list(
  y ~ 1 + x,  # Intercept + slope in first segment
  ~ 0 + x,  # Only slope changes in the next segments
  ~ 0 + x
)

# Fit it with a large number of samples and plot the change point posteriors
fit = mcp(model, data = data.frame(x, y), iter = 50000, adapt = 10000)
plot_pars(fit, regex_pars = "^cp*", type = "dens_overlay")
```

<p><img src="https://i.stack.imgur.com/iLvD0.png" alt="enter image description here"></p>

<p>FYI, <code>mcp</code> can plot credible intervals as well (the red dashed lines):</p>

<pre class="lang-r prettyprint-override"><code>plot(fit, q_fit = TRUE)
</code>```

Body:
My goal is to fit a three-piece (i.e., two break-point) regression model to make predictions using propagate's predictNLS function, making sure to define knots as parameters, but my model formula seems off.

I've used the segmented package to estimate the breakpoint locations (used as starting values in NLS), but would like to keep my models in the NLS format, specifically, nlsLM {minipack.lm} because I am fitting other types of curves to my data using NLS, want to allow NLS to optimize the knot values, am sometimes using variable weights, and need to be able to easily calculate the Monte Carlo confidence intervals from propagate. Though I'm very close to having the right syntax for the formula, I'm not getting the expected/required behaviour near the breakpoint(s). The segments SHOULD meet directly at the breakpoints (without any jumps), but at least on this data, I'm getting a weird local minimum at the breakpoint (see plots below).

Below is an example of my data and general process. I believe my issue to be in the NLS formula.

library(minpack.lm)
library(segmented)

y <- c(-3.99448113, -3.82447011, -3.65447803, -3.48447030, -3.31447855, -3.14448753, -2.97447972, -2.80448401, -2.63448380, -2.46448069, -2.29448796, -2.12448912, -1.95448783, -1.78448797, -1.61448563, -1.44448719, -1.27448469, -1.10448651, -0.93448525, -0.76448637, -0.59448626, -0.42448586, -0.25448588, -0.08448548,  0.08551417,  0.25551393,  0.42551411,  0.59551395,  0.76551389,  0.93551398)

x <- c(61586.1711, 60330.5550, 54219.9925, 50927.5381, 48402.8700, 45661.9175, 37375.6023, 33249.1248, 30808.6131, 28378.6508, 22533.3782, 13901.0882, 11716.5669, 11004.7305, 10340.3429,  9587.7994,  8736.3200,  8372.1482,  8074.3709,  7788.1847,  7499.6721,  7204.3168,  6870.8192,  6413.0828,  5523.8097,  3961.6114,  3460.0913,  2907.8614, 2016.1158,   452.8841)

df<- data.frame(x,y)

#Use Segmented to get estimates for parameters with 2 breakpoints
my.seg2 <- segmented(lm(y ~ x, data = df), seg.Z = ~ x, npsi = 2)

#extract knot, intercept, and coefficient values to use as NLS start points
my.knot1 <- my.seg2$psi[1,2]
my.knot2 <- my.seg2$psi[2,2]
my.m_2 <- slope(my.seg2)$x[1,1]
my.b1 <- my.seg2$coefficients[[1]]
my.b2 <- my.seg2$coefficients[[2]]
my.b3 <- my.seg2$coefficients[[3]]

#Fit a NLS model to ~replicate segmented model. Presumably my model formula is where the problem lies
my.model <- nlsLM(y~m*x+b+(b2*(ifelse(x>=knot1&x<=knot2,1,0)*(x-knot1))+(b3*ifelse(x>knot2,1,0)*(x-knot2-knot1))),data=df, start = c(m = my.m_2, b = my.b1, b2 = my.b2, b3 = my.b3, knot1 = my.knot1, knot2 = my.knot2))

How it should look

plot(my.seg2)

How it does look

plot(x, y)
lines(x=x, y=predict(my.model), col='black', lty = 1, lwd = 1)

I was pretty sure I had it "right", but when the 95% confidence intervals are plotted with the line and prediction resolution (e.g., the density of x points) is increased, things seem dramatically incorrect.

Thank you all for your help.

Body:
It may, in part, reflect a limitation in segmented. segmented returns a single change point value without quantifying the associated uncertainty. Redoing the analysis using mcp which returns Bayesian posteriors, we see that the second change point is bimodally distributed:

library(mcp)
model = list(
  y ~ 1 + x,  # Intercept + slope in first segment
  ~ 0 + x,  # Only slope changes in the next segments
  ~ 0 + x
)

# Fit it with a large number of samples and plot the change point posteriors
fit = mcp(model, data = data.frame(x, y), iter = 50000, adapt = 10000)
plot_pars(fit, regex_pars = "^cp*", type = "dens_overlay")

FYI, mcp can plot credible intervals as well (the red dashed lines):

plot(fit, q_fit = TRUE)


问:
VBA FormulaArray pulling data from one table to another
I have two tables. Table1 is on another sheet, where I'm trying to pull the data, Table2 is on the Header sheet, where I'm putting the data. It's an array formula, where the data will be placed over multiple cells. This seems to be where I'm getting stuck. I can't seem to get it to paste, giving me a "1004 error" (if not using databodyrange) and "method or data member not found" (if using ListColumn).

Value Bought Tracker is on the Header page
FinalTableSource[Buy Value] is on the second page

Here it is now with some updated code, but I'm still getting a 1004 error.

```<code>Public Sub MakeFinalTable_Click()
'Resize Table

Dim ws As Worksheet, lo As ListObject

Set ws = Sheets("Header")
Set lo = ws.ListObjects("FinalTable")

lo.ListColumns("Value Bought Tracker").DataBodyRange.FormulaArray = "=IFERROR(INDEX(FinalTableSource[Buy Value],SMALL(IF(FinalTableSource[Buy Value]<>"",ROW(FinalTableSource[Buy Value])-ROW(INDEX(FinalTableSource[Buy Value],1,1))+1),ROWS(AA$4:AA4))),"""")"

End Sub
</code>```

Thank you for any help!

答:
```<code>Dim ws As Worksheet, lo as ListObject

Set ws = Sheets("Header")
Set lo = ws.ListObjects(1)

lo.ListColumns("Value Bought Tracker").DataBodyRange.FormulaArray = "=IFERROR(INDEX(FinalTableSource[Buy Value],SMALL(IF(FinalTableSource[Buy Value]<>"",ROW(FinalTableSource[Buy Value])-ROW(INDEX(FinalTableSource[Buy Value],1,1))+1),ROWS(AA$4:AA4))),"")"
</code>```

<p>Edit: break your lines down so there's only one thing going on in each line; then you can more-easily see where the problem is - </p>

```<code>Public Sub MakeFinalTable_Click()

    Dim ws As Worksheet, lo As ListObject, lc As ListColumn, rng As Range

    Set ws = Sheets("Header")
    Set lo = ws.ListObjects("FinalTable")
    Set lc = lo.ListColumns("Value Bought Tracker")
    Set rng = lc.DataBodyRange

    rng.FormulaArray = "=IFERROR(INDEX(FinalTableSource[Buy Value]," & _
                       "SMALL(IF(FinalTableSource[Buy Value]<>""""," & _
                       "ROW(FinalTableSource[Buy Value])-" & _
                       "ROW(INDEX(FinalTableSource[Buy Value],1,1))+1),ROWS(AA$4:AA4))),"""")"

End Sub
</code>```

Body:
I have two tables. Table1 is on another sheet, where I'm trying to pull the data, Table2 is on the Header sheet, where I'm putting the data. It's an array formula, where the data will be placed over multiple cells. This seems to be where I'm getting stuck. I can't seem to get it to paste, giving me a "1004 error" (if not using databodyrange) and "method or data member not found" (if using ListColumn).

Value Bought Tracker is on the Header page
FinalTableSource[Buy Value] is on the second page

Here it is now with some updated code, but I'm still getting a 1004 error.

Public Sub MakeFinalTable_Click()
'Resize Table

Dim ws As Worksheet, lo As ListObject

Set ws = Sheets("Header")
Set lo = ws.ListObjects("FinalTable")

lo.ListColumns("Value Bought Tracker").DataBodyRange.FormulaArray = "=IFERROR(INDEX(FinalTableSource[Buy Value],SMALL(IF(FinalTableSource[Buy Value]<>"",ROW(FinalTableSource[Buy Value])-ROW(INDEX(FinalTableSource[Buy Value],1,1))+1),ROWS(AA$4:AA4))),"""")"

End Sub

Thank you for any help!

Body:
Dim ws As Worksheet, lo as ListObject

Set ws = Sheets("Header")
Set lo = ws.ListObjects(1)

lo.ListColumns("Value Bought Tracker").DataBodyRange.FormulaArray = "=IFERROR(INDEX(FinalTableSource[Buy Value],SMALL(IF(FinalTableSource[Buy Value]<>"",ROW(FinalTableSource[Buy Value])-ROW(INDEX(FinalTableSource[Buy Value],1,1))+1),ROWS(AA$4:AA4))),"")"

Edit: break your lines down so there's only one thing going on in each line; then you can more-easily see where the problem is -

Public Sub MakeFinalTable_Click()

    Dim ws As Worksheet, lo As ListObject, lc As ListColumn, rng As Range

    Set ws = Sheets("Header")
    Set lo = ws.ListObjects("FinalTable")
    Set lc = lo.ListColumns("Value Bought Tracker")
    Set rng = lc.DataBodyRange

    rng.FormulaArray = "=IFERROR(INDEX(FinalTableSource[Buy Value]," & _
                       "SMALL(IF(FinalTableSource[Buy Value]<>""""," & _
                       "ROW(FinalTableSource[Buy Value])-" & _
                       "ROW(INDEX(FinalTableSource[Buy Value],1,1))+1),ROWS(AA$4:AA4))),"""")"

End Sub


问:
add start from constraint to a column in mysql
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table</p>

```<code>mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+
</code>```

答: ALTER TABLE sales_log AUTO_INCREMENT = 101;</p>

ContentLicense: CC BY-SA 3.0

Body:
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table

mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+


问:
Primitive Recursive Functions Excercise in Haskell
For a functional programming excercise I am required to apply primitive recursive functions in haskell. However I do not quite understand yet the definition (and application) of this type of functions.

We are presented the data type Nat to be used, its constructor is:
data Nat = Zero | Succ Nat

To my understanding this means that the type "Nat" can be either a Zero or a Natural Succesor.

Then we have a recursor:

```<code>recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero = a
recNat a h (Succ n) = h n (recNat a h n)
</code>```

Which I understand is meant to apply recursion to a function?

And I've also been given an example of an addition function using the recursor:

```<code>addR :: Nat -> Nat -> Nat
addR m n = recNat n (\ _ y -> Succ y) m
</code>```

But I don't get how it works, it uses the recNat function with the given two Nats, and also uses an anonymous function as input for recNat ( that is the part I'm not sure what it does! )

So my main issue is what does this do in the function exactly > \ _ y -> Succ y

I'm suppossed to apply this same recursor (RecNat) to apply other operations to Nat, but I'm stuck still trying to understand the example!

答:
You’re right that data Nat = Zero | Succ Nat means that a Nat may be Zero or the Successor of another Nat; this represents natural numbers as a linked list, i.e.:

```<code>zero, one, two, three, four, five :: Nat

zero  = Zero
one   = Succ Zero                              -- or: Succ zero
two   = Succ (Succ Zero)                       --     Succ one
three = Succ (Succ (Succ Zero))                --     Succ two
four  = Succ (Succ (Succ (Succ Zero)))         --     Succ three
five  = Succ (Succ (Succ (Succ (Succ Zero))))  --     Succ four
-- …
</code>```

The function of recNat is to fold over a Nat: recNat z k takes a Nat and “counts down” by ones to the final Zero, calling k on every intermediate Succ, and replacing the Zero with z:

```<code>recNat z k three
recNat z k (Succ (Succ (Succ Zero)))

-- by second equation of ‘recNat’:
k two                (recNat z k two)
k (Succ (Succ Zero)) (recNat z k (Succ (Succ Zero)))

-- by second equation of ‘recNat’:
k two                (k one         (recNat z k one))
k (Succ (Succ Zero)) (k (Succ Zero) (recNat z k (Succ Zero)))

-- by second equation of ‘recNat’:
k two                (k one         (k zero (recNat z k zero)))
k (Succ (Succ Zero)) (k (Succ Zero) (k Zero (recNat z k Zero)))

-- by first equation of ‘recNat’:
k two                (k one         (k zero z))
k (Succ (Succ Zero)) (k (Succ Zero) (k Zero z))
</code>```

The lambda \ _ y -> Succ y has type a -> Nat -> Nat; it just ignores its first argument and returns the successor of its second argument. Here’s an illustration of how addR works to compute the sum of two Nats:

```<code>addR two three
addR (Succ (Succ Zero)) (Succ (Succ (Succ Zero)))

-- by definition of ‘addR’:
recNat three                     (\ _ y -> Succ y) two
recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) (Succ (Succ Zero))

-- by second equation of ‘recNat’:
(\ _ y -> Succ y) one         (recNat three                     (\ _ y -> Succ y) one)
(\ _ y -> Succ y) (Succ Zero) (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) (Succ Zero))

-- by application of the lambda:
Succ (recNat three                     (\ _ y -> Succ y) one)
Succ (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) (Succ Zero))

-- by second equation of ‘recNat’:
Succ ((\ _ y -> Succ y) zero (recNat three                     (\ _ y -> Succ y) zero))
Succ ((\ _ y -> Succ y) zero (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) zero))

-- by application of the lambda:
Succ (Succ (recNat three                     (\ _ y -> Succ y) zero))
Succ (Succ (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) zero))

-- by first equation of ‘recNat’:
Succ (Succ three)
Succ (Succ (Succ (Succ (Succ Zero))))

-- by definition of ‘five’:
five
Succ (Succ (Succ (Succ (Succ Zero))))
</code>```

As you can see, what’s happening here is we’re essentially taking off each Succ from one number and putting it on the end of the other, or equivalently, replacing the Zero in one number with the other number, i.e., the steps go like this:

```<code>1+1+0 + 1+1+1+0           2 + 3
1+(1+0 + 1+1+1+0)      1+(1 + 3)
1+1+(0 + 1+1+1+0)    1+1+(0 + 3)
1+1+(1+1+1+0)        1+1+(3)
1+1+1+1+1+0          5
</code>```

The inner lambda always ignores its first argument with _, so it may be simpler to see how this works with a simpler definition of recNat that literally replaces Zero with a value z and Succ with a function s:

```<code>recNat' :: a -> (a -> a) -> Nat -> a
recNat' z _ Zero     = z
recNat' z s (Succ n) = s (recNat z s n)
</code>```

Then addition is slightly simplified:

```<code>addR' m n = recNat' n Succ m
</code>```

This literally says “to compute the sum of m and n, add one m times to n”.

You may find it easier to play around with these numbers if you make a Num instance and Show instance for them:

```<code>{-# LANGUAGE InstanceSigs #-}  -- for explicitness

instance Num Nat where

  fromInteger :: Integer -> Nat
  fromInteger n
    | n <= 0    = Zero
    | otherwise = Succ (fromInteger (n - 1))

  (+) :: Nat -> Nat -> Nat
  (+) = addR

  (*) :: Nat -> Nat -> Nat
  (*) = …  -- left as an exercise

  (-) :: Nat -> Nat -> Nat
  (-) = …  -- left as an exercise

  abs :: Nat -> Nat
  abs n = n

  signum :: Nat -> Nat
  signum Zero   = Zero
  signum Succ{} = Succ Zero

  negate :: Nat -> Nat
  negate n = n  -- somewhat hackish

instance Show Nat where
  show n = show (recNat' (+ 1) 0 n :: Int)
</code>```

Then you can write 2 + 3 :: Nat and have it display as 5.

Body:
For a functional programming excercise I am required to apply primitive recursive functions in haskell. However I do not quite understand yet the definition (and application) of this type of functions.

We are presented the data type Nat to be used, its constructor is:
data Nat = Zero | Succ Nat

To my understanding this means that the type "Nat" can be either a Zero or a Natural Succesor.

Then we have a recursor:

recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero = a
recNat a h (Succ n) = h n (recNat a h n)

Which I understand is meant to apply recursion to a function?

And I've also been given an example of an addition function using the recursor:

addR :: Nat -> Nat -> Nat
addR m n = recNat n (\ _ y -> Succ y) m

But I don't get how it works, it uses the recNat function with the given two Nats, and also uses an anonymous function as input for recNat ( that is the part I'm not sure what it does! )

So my main issue is what does this do in the function exactly > \ _ y -> Succ y

I'm suppossed to apply this same recursor (RecNat) to apply other operations to Nat, but I'm stuck still trying to understand the example!

Body:
You’re right that data Nat = Zero | Succ Nat means that a Nat may be Zero or the Successor of another Nat; this represents natural numbers as a linked list, i.e.:

zero, one, two, three, four, five :: Nat

zero  = Zero
one   = Succ Zero                              -- or: Succ zero
two   = Succ (Succ Zero)                       --     Succ one
three = Succ (Succ (Succ Zero))                --     Succ two
four  = Succ (Succ (Succ (Succ Zero)))         --     Succ three
five  = Succ (Succ (Succ (Succ (Succ Zero))))  --     Succ four
-- …

The function of recNat is to fold over a Nat: recNat z k takes a Nat and “counts down” by ones to the final Zero, calling k on every intermediate Succ, and replacing the Zero with z:

recNat z k three
recNat z k (Succ (Succ (Succ Zero)))

-- by second equation of ‘recNat’:
k two                (recNat z k two)
k (Succ (Succ Zero)) (recNat z k (Succ (Succ Zero)))

-- by second equation of ‘recNat’:
k two                (k one         (recNat z k one))
k (Succ (Succ Zero)) (k (Succ Zero) (recNat z k (Succ Zero)))

-- by second equation of ‘recNat’:
k two                (k one         (k zero (recNat z k zero)))
k (Succ (Succ Zero)) (k (Succ Zero) (k Zero (recNat z k Zero)))

-- by first equation of ‘recNat’:
k two                (k one         (k zero z))
k (Succ (Succ Zero)) (k (Succ Zero) (k Zero z))

The lambda \ _ y -> Succ y has type a -> Nat -> Nat; it just ignores its first argument and returns the successor of its second argument. Here’s an illustration of how addR works to compute the sum of two Nats:

addR two three
addR (Succ (Succ Zero)) (Succ (Succ (Succ Zero)))

-- by definition of ‘addR’:
recNat three                     (\ _ y -> Succ y) two
recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) (Succ (Succ Zero))

-- by second equation of ‘recNat’:
(\ _ y -> Succ y) one         (recNat three                     (\ _ y -> Succ y) one)
(\ _ y -> Succ y) (Succ Zero) (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) (Succ Zero))

-- by application of the lambda:
Succ (recNat three                     (\ _ y -> Succ y) one)
Succ (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) (Succ Zero))

-- by second equation of ‘recNat’:
Succ ((\ _ y -> Succ y) zero (recNat three                     (\ _ y -> Succ y) zero))
Succ ((\ _ y -> Succ y) zero (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) zero))

-- by application of the lambda:
Succ (Succ (recNat three                     (\ _ y -> Succ y) zero))
Succ (Succ (recNat (Succ (Succ (Succ Zero))) (\ _ y -> Succ y) zero))

-- by first equation of ‘recNat’:
Succ (Succ three)
Succ (Succ (Succ (Succ (Succ Zero))))

-- by definition of ‘five’:
five
Succ (Succ (Succ (Succ (Succ Zero))))

As you can see, what’s happening here is we’re essentially taking off each Succ from one number and putting it on the end of the other, or equivalently, replacing the Zero in one number with the other number, i.e., the steps go like this:

1+1+0 + 1+1+1+0           2 + 3
1+(1+0 + 1+1+1+0)      1+(1 + 3)
1+1+(0 + 1+1+1+0)    1+1+(0 + 3)
1+1+(1+1+1+0)        1+1+(3)
1+1+1+1+1+0          5

The inner lambda always ignores its first argument with _, so it may be simpler to see how this works with a simpler definition of recNat that literally replaces Zero with a value z and Succ with a function s:

recNat' :: a -> (a -> a) -> Nat -> a
recNat' z _ Zero     = z
recNat' z s (Succ n) = s (recNat z s n)

Then addition is slightly simplified:

addR' m n = recNat' n Succ m

This literally says “to compute the sum of m and n, add one m times to n”.

You may find it easier to play around with these numbers if you make a Num instance and Show instance for them:

{-# LANGUAGE InstanceSigs #-}  -- for explicitness

instance Num Nat where

  fromInteger :: Integer -> Nat
  fromInteger n
    | n <= 0    = Zero
    | otherwise = Succ (fromInteger (n - 1))

  (+) :: Nat -> Nat -> Nat
  (+) = addR

  (*) :: Nat -> Nat -> Nat
  (*) = …  -- left as an exercise

  (-) :: Nat -> Nat -> Nat
  (-) = …  -- left as an exercise

  abs :: Nat -> Nat
  abs n = n

  signum :: Nat -> Nat
  signum Zero   = Zero
  signum Succ{} = Succ Zero

  negate :: Nat -> Nat
  negate n = n  -- somewhat hackish

instance Show Nat where
  show n = show (recNat' (+ 1) 0 n :: Int)

Then you can write 2 + 3 :: Nat and have it display as 5.


问:
Is there any way to pair Bluetooth device in Windows programmatically
there's a question:
Is there any way to pair Bluetooth device in Windows programmatically? (c++, c#)

thanks for replies

答: Microsoft has introduced Windows.Devices.Enumeration API available for UWP and traditional applications, which makes pairing of bluetooth devices very easy (for details look at the official C# and C++ example). As far as I understand it is the API which is used by built-in "Bluetooth & other devices" UI dialog. As of an example of what console utility you can write using this API you can take a look at my console BluetoothDevicePairing utility.</p>


问:
Is it undefined behaviour to have a reference to freed memory?
In C++, is it undefined behaviour to free memory that is still referred to by a reference, even if that reference is not used again? For example, does the following function invoke undefined behaviour?</p>

```<code>void foo() {
    std::map<std::string, int> mymap;
    {
        int& val = mymap["eight"];
        val = 8;
        mymap.erase("eight"); // Oops! val still refers to mymap["eight"]
        // val is not used again
    }
    std::cout << "Entry count: " << mymap.size() << "\n";
}
</code>```

答:
From [associative.reqmts]p9, we see(emphasis mine):

The insert and emplace members shall not affect the validity of iterators and references to the container,
  and the erase members shall invalidate only iterators and references to the erased elements.

This is from N4659 [basic.stc]p4 1 (again, emphasis mine):

When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values (6.9.2). Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

Although the text talks specifically about pointers, there is no reason to believe that it is not applicable to references(well, in a way they can be thought of as pointers). Also note the fact that it says "Any other use", so as long as you don't use the pointers/references in an expression after it has been invalidated, the behaviour should be well defined.

1 Note: Looks like this text was added in N4659 and doesn't seem to be present in earlier versions of the standard.

Body:
In C++, is it undefined behaviour to free memory that is still referred to by a reference, even if that reference is not used again? For example, does the following function invoke undefined behaviour?

void foo() {
    std::map<std::string, int> mymap;
    {
        int& val = mymap["eight"];
        val = 8;
        mymap.erase("eight"); // Oops! val still refers to mymap["eight"]
        // val is not used again
    }
    std::cout << "Entry count: " << mymap.size() << "\n";
}


问:
How to change the Text color of Menu item in Android?
Can I change the background color of a Menu item in Android?

Please let me know if anyone have any solution to this. The last option will be obviously to customize it but is there any way for changing the text color without customizing it.

答:
Options menu in android can be customized to set the background or change the text appearance. The background and text color in the menu couldn’t be changed using themes and styles. The android source code (data\res\layout\icon_menu_item_layout.xml)uses a custom item of class “com.android.internal.view.menu.IconMenuItem”View for the menu layout. We can make changes in the above class to customize the menu. To achieve the same, use LayoutInflater factory class and set the background and text color for the view.</p>

```
<code>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    getLayoutInflater().setFactory(new Factory() {
        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {
            if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
                try{
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    new Handler().post(new Runnable() {
                        public void run() {
                            // set the background drawable
                            view .setBackgroundResource(R.drawable.my_ac_menu_background);

                            // set the text color
                            ((TextView) view).setTextColor(Color.WHITE);
                        }
                    });
                    return view;
                } catch (InflateException e) {
                    } catch (ClassNotFoundException e) {}
            }
            return null;
        }
    });
    return super.onCreateOptionsMenu(menu);
}

</code>
```

ContentLicense: CC BY-SA 2.5

Body:
Options menu in android can be customized to set the background or change the text appearance. The background and text color in the menu couldn’t be changed using themes and styles. The android source code (data\res\layout\icon_menu_item_layout.xml)uses a custom item of class “com.android.internal.view.menu.IconMenuItem”View for the menu layout. We can make changes in the above class to customize the menu. To achieve the same, use LayoutInflater factory class and set the background and text color for the view.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    getLayoutInflater().setFactory(new Factory() {
        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {
            if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
                try{
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    new Handler().post(new Runnable() {
                        public void run() {
                            // set the background drawable
                            view .setBackgroundResource(R.drawable.my_ac_menu_background);

                            // set the text color
                            ((TextView) view).setTextColor(Color.WHITE);
                        }
                    });
                    return view;
                } catch (InflateException e) {
                    } catch (ClassNotFoundException e) {}
            }
            return null;
        }
    });
    return super.onCreateOptionsMenu(menu);
}


问:
How to edit html element with Javascript dom?
i try to edit the span element inside with javascript dom:

```<code><div class="data">
<span>Jan. 16, 2019</span>
</div>
</code>```

So that only last 4 characters are shown,

```<code>var list = document.getElementById("data");
list.removeChild(list.childNodes[3]);
</code>```

But it doesnot work

答:
Two things are going wrong. You are looking for an ID, but the HTML does not have an ID. Also showing the last 4 characters is not going alright.

I would propose to add an id to the span:

   Jan. 16, 2019

```

```var span = document.getElementById("date");
var date = span.textContent;
span.textContent = date.substr(date.length - 4);
```

Body:
i try to edit the span element inside with javascript dom:

Jan. 16, 2019

So that only last 4 characters are shown,

var list = document.getElementById("data");
list.removeChild(list.childNodes[3]);

But it doesnot work

Body:
Two things are going wrong. You are looking for an ID, but the HTML does not have an ID. Also showing the last 4 characters is not going alright.

I would propose to add an id to the span:

<div class="data">
   <span id="date">Jan. 16, 2019</span>
</div>

var span = document.getElementById("date");
var date = span.textContent;
span.textContent = date.substr(date.length - 4);


问:
HSum up rows in a dataframe that have the same property in R
I hope this question hasn't been asked two often (first time user).

I have a data frame called data2003 and for simplicity I'll say it looks something like this:

```<code>ID   Weight   North   South
1    0.5      1       0
2    0.7      0       1
3    1.0      0       1
4    1.4      0       1
5    .95      1       0
6    1.1      1       0

</code>```

I want to add up the values in weight column that correspond to North and South dummy variables--so only include weight in the count when the North value in the same row is 1.

What I've done is make subsets for North and South:

```<code>subset2003N <- subset(data2003, data2003$North == 1 )
sum2003N <-sum(subset2003N$Weight)
</code>```

The problem is that I have 6 zones, not just north and south, and datasets for two other years. Is there a way to simply do this in one line of code without cluttering up my global environment with so many subsets?

答:
Here is a tidyverse solution.

```<code>data2003 %>%
  pivot_longer(
    cols = -c(ID, Weight),
    names_to = 'dir',
    values_to = 'value'
  ) %>%
  group_by(dir) %>%
  summarise(Sum = sum(Weight*value))
## A tibble: 2 x 2
#  dir     Sum
#  <chr> <dbl>
#1 North  2.55
#2 South  3.10
</code>```

Body:
I hope this question hasn't been asked two often (first time user).

I have a data frame called data2003 and for simplicity I'll say it looks something like this:

ID   Weight   North   South
1    0.5      1       0
2    0.7      0       1
3    1.0      0       1
4    1.4      0       1
5    .95      1       0
6    1.1      1       0

I want to add up the values in weight column that correspond to North and South dummy variables--so only include weight in the count when the North value in the same row is 1.

What I've done is make subsets for North and South:

subset2003N <- subset(data2003, data2003$North == 1 )
sum2003N <-sum(subset2003N$Weight)

The problem is that I have 6 zones, not just north and south, and datasets for two other years. Is there a way to simply do this in one line of code without cluttering up my global environment with so many subsets?

Body:
Here is a tidyverse solution.

data2003 %>%
  pivot_longer(
    cols = -c(ID, Weight),
    names_to = 'dir',
    values_to = 'value'
  ) %>%
  group_by(dir) %>%
  summarise(Sum = sum(Weight*value))
## A tibble: 2 x 2
#  dir     Sum
#  <chr> <dbl>
#1 North  2.55
#2 South  3.10


问:
Command to run boot service program from background (through command line)
```<code>@SpringBootApplication

public class IFMApp extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(IFMApp.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(IFMApp.class);
    }
}
</code>```

I want to run above boot service program (IFMApp) through the command line (linux terminal).

The War/Jar files i built:-

1. ifmservice.war

2. ifmservice-jar-with-dependencies.jar

3. ifmservice-tests.jar

Help will be greatly appreciated. Thanks

答:
Firstly ,go to  your target folder in your  project  and then  type in :

java -jar  your_jar_Name

Body:
@SpringBootApplication

public class IFMApp extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(IFMApp.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(IFMApp.class);
    }
}

I want to run above boot service program (IFMApp) through the command line (linux terminal).

The War/Jar files i built:-

1. ifmservice.war

2. ifmservice-jar-with-dependencies.jar

3. ifmservice-tests.jar

Help will be greatly appreciated. Thanks


问:
Assign constant char to character array inside structure in VC++
I want a linked list structure in my VC++ application

My structure is:-

```<code>struct xml_data {
    int id;
    char file_name[50];
    char url_source[50];
    struct xml_Data *next;
}xml_data1;
</code>```

If I declare a variable like

```<code>struct xml_data *var;
const char* abc;
</code>```

I want to assign a value from a const char* variable to the structure members.

I tried using

```<code>var->file_name=abc;
</code>```

but it is giving an error that it cannot convert const char* to char[50]...

this may be a small problem but I am very new in using data structures....

答:
xml_data::file_name is an array and is not modifiable. It always sticked to the &file_name[0] (address of 1st element).

At the max you can copy the content of the pointer into that array using strcpy/strncpy/memcpy or equivalent.

Body:
I want a linked list structure in my VC++ application

My structure is:-

struct xml_data {
    int id;
    char file_name[50];
    char url_source[50];
    struct xml_Data *next;
}xml_data1;

If I declare a variable like

struct xml_data *var;
const char* abc;

I want to assign a value from a const char* variable to the structure members.

I tried using

var->file_name=abc;

but it is giving an error that it cannot convert const char* to char[50]...

this may be a small problem but I am very new in using data structures....


问:
Getting error "No such module" using Xcode, but the framework is there
I'm currently coding in Swift, and I've got an error:

No such module Social

But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "Embedded Binaries".

The frameworks is in Objective-C, so I wrote a Bridge Header for it.

Please, how can I make Xcode recognize the framework?

答:
TL;DR: Check your Podfile for target-specific shared_pods

After beating my head against the wall and trying literally every single other answer posted here over the last week, I finally found a solution.

I have two separate targets - one for release and one for development. The development target was created long after the release target, which lead me to forget some setup steps for that target.

I was able to get my project to compile properly using my release target, but my development target was having an issue.

After looking at my Podfile for the twentieth time, I noticed that I only had the following, under my shared_pods definition:

```<code>target 'Release' do
  shared_pods
end
</code>```

What I needed to do was add my second target to my Podfile, and that fixed the issue:

```<code>target 'Release' do
  shared_pods
end

target 'Development' do
    shared_pods
end
</code>```

Hopefully this saves someone a few days of frustration.

Body:
TL;DR: Check your Podfile for target-specific shared_pods

After beating my head against the wall and trying literally every single other answer posted here over the last week, I finally found a solution.

I have two separate targets - one for release and one for development. The development target was created long after the release target, which lead me to forget some setup steps for that target.

I was able to get my project to compile properly using my release target, but my development target was having an issue.

After looking at my Podfile for the twentieth time, I noticed that I only had the following, under my shared_pods definition:

target 'Release' do
  shared_pods
end

What I needed to do was add my second target to my Podfile, and that fixed the issue:

target 'Release' do
  shared_pods
end

target 'Development' do
    shared_pods
end

Hopefully this saves someone a few days of frustration.


问:
how to test a setter in c# ?and why?
I am getting started with c#. I am asked to do an assignement that contains writing a unit test for a setter and checking its output. I don't follow the meaning of testing something very trivial that does not contain any logic. here's the example (SetKeywords() is the method to be tested):</p>

```<code>public struct Keyword
{
    private string keyword;
    private KeywordTypes type;

    public Keyword(string keyword, KeywordTypes Type =
    KeywordTypes.String)
    {
        this.keyword = keyword;
        this.type = Type;
    }

    public string GetString()
    {
        return this.keyword;
    }

    public KeywordTypes WhichType()
    {
        return this.type;
    }
}

public class ShopParser
{
    private Keyword[] keywords = new Keyword[0];

    public void **SetKeywords**(Keyword[] tags)
    {
        keywords = tags;
    }
}
    public Keyword[] GetKeywords()
    {
            return this.keywords;
    }
    public static KeywordPair[] ExtractFromTaG(ShopParser parser, string
    serializedInput)
    {
            var findings = new KeywordPair[0];
            foreach (var keyword in parser.GetKeywords())
            {
                var start = serializedInput.IndexOf(keyword.GetStart());

                // Check if keyword is in input string, if not continue
                with next keyword.

                if (start <= -1) continue;

                var end = serializedInput.LastIndexOf(keyword.GetEnd());

                // Extract the thing between the tags. Tag excluded
                start += keyword.GetStart().Length;

                var substring = serializedInput.Substring(start, end -
                start);

                // Add substring to result list

                var tmp = new KeywordPair[findings.Length + 1];
                var i = 0;
                for (; i < findings.Length; ++i)
                {
                    tmp[i] = findings[i];
                }
                tmp[i] = new KeywordPair(keyword, substring);
                findings = tmp;
            }
            return findings;
    }

}
</code>```

答:
How to test?

When you call SetKeywords, it should do something. Right now it sets the internal array keywords. So the question you need to ask yourself is how can you be sure it did that? Well you have a GetKeywords method which returns the internal array so we can use that to conduct our tests as below:

```<code>[TestClass]
public class ShopParserTests
{
    [TestMethod]
    public void SetKeyWords__WhenGivenAnArray__MustSetTheInternalArray()
    {
        // Arrange
        var k1 = new Keyword("One", KeywordTypes.String);
        var k2 = new Keyword("Two");
        var parser = new ShopParser();
        var keys = new Keyword[] { k1, k2 };

        // Act
        parser.SetKeywords(keys);

        // Assert
        Keyword[] keysReturned = parser.GetKeywords();
        Assert.AreEqual(keysReturned[0].GetString(), k1.GetString());
        Assert.AreEqual(keysReturned[0].WhichType(), k1.WhichType());
        Assert.AreEqual(keysReturned[1].GetString(), k2.GetString());
        Assert.AreEqual(keysReturned[1].WhichType(), k2.WhichType());

        // More tests
    }
}
</code>```

Some Suggestions

Keep in mind that you may need to write a lot more tests based on your requirements. For example, what if the user does this:

```<code>Keyword[] keysReturned = parser.GetKeywords();
keys[0] = new Keyword();
</code>```

Do you want to allow that?

Also, in C# your classes can be simplified and take advantage of properties. So your Keyword and ShopParser classes be written like this:

```<code>public struct Keyword
{
    public Keyword(string keyword, KeywordTypes type =
    KeywordTypes.String)
    {
        this.TheKeyword = keyword;
        this.KeyType= type;
    }

    public string TheKeyword { get; private set; }
    public KeywordTypes KeyType { get; private set; }
}

public class ShopParser
{
    public void SetKeywords(Keyword[] tags)
    {
        this.KeyWords = tags;
    }

    public Keyword[] KeyWords { get; private set; }
}
</code>```

Title: how to test a setter in c# ?and why?

Body:
I am getting started with c#. I am asked to do an assignement that contains writing a unit test for a setter and checking its output. I don't follow the meaning of testing something very trivial that does not contain any logic. here's the example (SetKeywords() is the method to be tested):

public struct Keyword
{
    private string keyword;
    private KeywordTypes type;

    public Keyword(string keyword, KeywordTypes Type =
    KeywordTypes.String)
    {
        this.keyword = keyword;
        this.type = Type;
    }

    public string GetString()
    {
        return this.keyword;
    }

    public KeywordTypes WhichType()
    {
        return this.type;
    }
}

public class ShopParser
{
    private Keyword[] keywords = new Keyword[0];

    public void **SetKeywords**(Keyword[] tags)
    {
        keywords = tags;
    }
}
    public Keyword[] GetKeywords()
    {
            return this.keywords;
    }
    public static KeywordPair[] ExtractFromTaG(ShopParser parser, string
    serializedInput)
    {
            var findings = new KeywordPair[0];
            foreach (var keyword in parser.GetKeywords())
            {
                var start = serializedInput.IndexOf(keyword.GetStart());

                // Check if keyword is in input string, if not continue
                with next keyword.

                if (start <= -1) continue;

                var end = serializedInput.LastIndexOf(keyword.GetEnd());

                // Extract the thing between the tags. Tag excluded
                start += keyword.GetStart().Length;

                var substring = serializedInput.Substring(start, end -
                start);

                // Add substring to result list

                var tmp = new KeywordPair[findings.Length + 1];
                var i = 0;
                for (; i < findings.Length; ++i)
                {
                    tmp[i] = findings[i];
                }
                tmp[i] = new KeywordPair(keyword, substring);
                findings = tmp;
            }
            return findings;
    }

}

Body:
How to test?

When you call SetKeywords, it should do something. Right now it sets the internal array keywords. So the question you need to ask yourself is how can you be sure it did that? Well you have a GetKeywords method which returns the internal array so we can use that to conduct our tests as below:

[TestClass]
public class ShopParserTests
{
    [TestMethod]
    public void SetKeyWords__WhenGivenAnArray__MustSetTheInternalArray()
    {
        // Arrange
        var k1 = new Keyword("One", KeywordTypes.String);
        var k2 = new Keyword("Two");
        var parser = new ShopParser();
        var keys = new Keyword[] { k1, k2 };

        // Act
        parser.SetKeywords(keys);

        // Assert
        Keyword[] keysReturned = parser.GetKeywords();
        Assert.AreEqual(keysReturned[0].GetString(), k1.GetString());
        Assert.AreEqual(keysReturned[0].WhichType(), k1.WhichType());
        Assert.AreEqual(keysReturned[1].GetString(), k2.GetString());
        Assert.AreEqual(keysReturned[1].WhichType(), k2.WhichType());

        // More tests
    }
}

Some Suggestions

Keep in mind that you may need to write a lot more tests based on your requirements. For example, what if the user does this:

Keyword[] keysReturned = parser.GetKeywords();
keys[0] = new Keyword();

Do you want to allow that?

Also, in C# your classes can be simplified and take advantage of properties. So your Keyword and ShopParser classes be written like this:

public struct Keyword
{
    public Keyword(string keyword, KeywordTypes type =
    KeywordTypes.String)
    {
        this.TheKeyword = keyword;
        this.KeyType= type;
    }

    public string TheKeyword { get; private set; }
    public KeywordTypes KeyType { get; private set; }
}

public class ShopParser
{
    public void SetKeywords(Keyword[] tags)
    {
        this.KeyWords = tags;
    }

    public Keyword[] KeyWords { get; private set; }
}


问:
About directionality in a topological graph
I am solving this question on LeetCode.com.  A statement in the question says:

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

My aim is to come up with a graphical representation.  My question is, as per the above statement, should I create a graph from:

a. 0 -> 1; or

b. 1 -> 0?

The reason I am confused is, if I come up with the former, I would actually do the opposite of what is required - I would visit 0 before I do the prerequisite 1.  On the other hand, if I do it the latter way, what if there's a scenario wherein to take course 0, I have to take multiple prerequisite courses, say, 1 and 2?  Using the latter representation, I would end up completing course 0 from 1 (thanks to the edge), without first doing course 2.

How should I create the directional edge?

答: It doesn't matter. If you reverse all your edges and topological sort, the result that you'll get will be the reverse of some topological ordering of the original graph. Do it in whichever way makes the most sense to you.</p>


问:
How to resolve "The type com.sun.crypto.provider.SunJCE is not accessible" with Java11?
I am trying to migrate my application from Java 8 to Java 11. In of one of my project classes, I have the line Security.addProvider(new com.sun.crypto.provider.SunJCE());. I am getting a compile error for this line. How to resolve this?

答:
You can't access com.sun packages without explicitly setting them on your compile options. After adding --add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED to compilerArgs it compiles without any error.

Code:

```<code>   Security.addProvider(new com.sun.crypto.provider.SunJCE());
</code>```

Maven:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>

    <properties>
        <java.version>11</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <compilerArgs>
                        <arg>--add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED</arg>
                    </compilerArgs>

                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

java.security.Security.getProviders() returns you all the providers including the SunJCE.

```<code>   Stream.of(java.security.Security.getProviders()).forEach(System.out::println);
</code>```

So better option to get the SunJCE instane is java.security.Security.getProvider("SunJCE")

Body:
You can't access com.sun packages without explicitly setting them on your compile options. After adding --add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED to compilerArgs it compiles without any error.

Code:

   Security.addProvider(new com.sun.crypto.provider.SunJCE());

Maven:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>

    <properties>
        <java.version>11</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <compilerArgs>
                        <arg>--add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED</arg>
                    </compilerArgs>

                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

java.security.Security.getProviders() returns you all the providers including the SunJCE.

   Stream.of(java.security.Security.getProviders()).forEach(System.out::println);

So better option to get the SunJCE instane is java.security.Security.getProvider("SunJCE")


问:
CertManager Letsencrypt CertificateRequest "failed to perform self check GET request"
Waiting for http-01 challenge propagation: failed to perform self check GET request, it's similar to this bug https://github.com/jetstack/cert-manager/issues/656
but all solutions from GitHub ticket comments didn't help.

I'm trying to set up CertManager on DigitalOcean as described in this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes
I didn't get any error but the request from CertManager is waiting in pending state more than 40 hours.

I have successfully configured Ingress with Nginx, then I created a namespace and created CertManager CRDs:

$ kubectl create namespace cert-manager
$ kubectl apply --validate=false -f https://github.com/jetstack/cert-manager/releases/download/v0.12.0/cert-manager.yaml
```
<p>I can see all <code>CertManager</code> pods as expected:</p>
```$ kubectl get pods --namespace cert-manager
NAME                                       READY   STATUS    RESTARTS   AGE
cert-manager-5c47f46f57-gxhwv              1/1     Running   0          42h
cert-manager-cainjector-6659d6844d-xp75s   1/1     Running   0          42h
cert-manager-webhook-547567b88f-k4dv2      1/1     Running   0          42h
```
<p>Then I created staging issuer:</p>
<pre class="lang-yaml prettyprint-override"><code>---
apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: letsencrypt-staging
  namespace: cert-manager
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: some@email.here
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
      - http01:
          ingress:
            class: nginx
</code>```

And updated Ingress configuration:

---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: echo-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    # cert-manager.io/cluster-issuer: "letsencrypt-prod"
    cert-manager.io/cluster-issuer: "letsencrypt-staging"
spec:
  tls:
    - hosts:
        - echo.some.domain
      secretName: ingress-tls
  rules:
    - host: echo.some.domain
      http:
        paths:
          - backend:
              serviceName: echo1
              servicePort: 80
```
<p>But after that, <code>CertManager</code> didn't update certificate and waiting in <code>InProgress</code> state:</p>
<pre class="lang-sh prettyprint-override"><code>$ date
Wed 18 Dec 2019 01:58:08 PM MSK

$ kubectl describe cert

...
Status:
  Conditions:
    Last Transition Time:  2019-12-16T17:23:56Z
    Message:               Waiting for CertificateRequest "ingress-tls-1089568541" to complete
    Reason:                InProgress
    Status:                False
    Type:                  Ready
Events:                    <none>
</code>```

Instead of using Fake LE Intermediate X1 as a CN it returns CN=Kubernetes Ingress Controller Fake Certificate,O=Acme Co

$ kubectl describe CertificateRequest
Status:
  Conditions:
    Last Transition Time:  2019-12-16T17:50:05Z
    Message:               Waiting on certificate issuance from order default/ingress-tls-1089568541-1576201144: "pending"
    Reason:                Pending
    Status:                False
    Type:                  Ready
Events:                    <none>
```
<p>What can be the problem with <code>CertManager</code> and how to fix it?</p>
<hr />
<p>Update:</p>
<p>Ingress logs contains these errors:</p>
```$ kubectl -n ingress-nginx logs  nginx-ingress-controller-7754db565c-g557h

I1218 17:24:30.331127       6 status.go:295] updating Ingress default/cm-acme-http-solver-4dkdn status from [] to [{xxx.xxx.xxx.xxx }]
I1218 17:24:30.333250       6 status.go:295] updating Ingress default/cm-acme-http-solver-9dpqc status from [] to [{xxx.xxx.xxx.xxx }]
I1218 17:24:30.341292       6 event.go:209] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default", Name:"cm-acme-http-solver-4dkdn", UID:"2e523b74-8bbb-41c7-be8a-44d8db8abd6e", APIVersion:"extensions/v1beta1", ResourceVersion:"722472", FieldPath:""}): type: 'Normal' reason: 'UPDATE' Ingress default/cm-acme-http-solver-4dkdn
I1218 17:24:30.344340       6 event.go:209] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default", Name:"cm-acme-http-solver-9dpqc", UID:"b574a3b6-6c5b-4266-a4e2-6ff2de2d78e0", APIVersion:"extensions/v1beta1", ResourceVersion:"722473", FieldPath:""}): type: 'Normal' reason: 'UPDATE' Ingress default/cm-acme-http-solver-9dpqc
W1218 17:24:30.442276       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate
W1218 17:24:30.442950       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate
W1218 17:24:33.775476       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate
W1218 17:24:33.775956       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate
```
<hr />
<p>Update2:</p>
<p>Secret for <code>ingress-tls</code> is available as expected:</p>
<pre class="lang-yaml prettyprint-override"><code>$ kubectl get secret ingress-tls -o yaml

apiVersion: v1
data:
  ca.crt: ""
  tls.crt: ""
  tls.key: <secret-key-data-base64-encoded>
kind: Secret
metadata:
  annotations:
    cert-manager.io/certificate-name: ingress-tls
    cert-manager.io/issuer-kind: ClusterIssuer
    cert-manager.io/issuer-name: letsencrypt-staging
  creationTimestamp: "2019-12-16T17:23:56Z"
  name: ingress-tls
  namespace: default
  resourceVersion: "328801"
  selfLink: /api/v1/namespaces/default/secrets/ingress-tls
  uid: 5d640b66-1572-44a1-94e4-6d85a73bf21c
type: kubernetes.io/tls
</code>```

Update3:

I've found that cert-manager pod is failing with log:

```<code>E1219 11:06:08.294011       1 sync.go:184] cert-manager/controller/challenges "msg"="propagation check failed" "error"="failed to perform self check GET request 'http://<some.domain>/.well-known/acme-challenge/<some-path>': Get http://<some.domain>/.well-known/acme-challenge/<some-path>: dial tcp xxx.xxx.xxx.xxx:80: connect: connection timed out" "dnsName"="<some.domain>" "resource_kind"="Challenge" "resource_name"="ingress-tls-1089568541-1576201144-1086699008" "resource_namespace"="default" "type"="http-01"
</code>```

Challenge status:

```<code>$ kubectl describe challenge ingress-tls-1089568541-1576201144-471532423

Name:         ingress-tls-1089568541-1576201144-471532423
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  acme.cert-manager.io/v1alpha2
Kind:         Challenge
Metadata:
  Creation Timestamp:  2019-12-19T11:32:19Z
  Finalizers:
    finalizer.acme.cert-manager.io
  Generation:  1
  Owner References:
    API Version:           acme.cert-manager.io/v1alpha2
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Order
    Name:                  ingress-tls-1089568541-1576201144
    UID:                   7d19d86f-0b56-4756-aa20-bb85caf80b9e
  Resource Version:        872062
  Self Link:               /apis/acme.cert-manager.io/v1alpha2/namespaces/default/challenges/ingress-tls-1089568541-1576201144-471532423
  UID:                     503a8b4e-dc60-4080-91d9-2847815af1cc
Spec:
  Authz URL:  https://acme-staging-v02.api.letsencrypt.org/acme/authz-v3/123456
  Dns Name:   <domain>
  Issuer Ref:
    Group:  cert-manager.io
    Kind:   ClusterIssuer
    Name:   letsencrypt-staging
  Key:      <key>
  Solver:
    http01:
      Ingress:
        Class:  nginx
  Token:        <token>
  Type:         http-01
  URL:          https://acme-staging-v02.api.letsencrypt.org/acme/chall-v3/12345/abc
  Wildcard:     false
Status:
  Presented:   true
  Processing:  true
  Reason:      Waiting for http-01 challenge propagation: failed to perform self check GET request 'http://<domain>/.well-known/acme-challenge/<token>': Get http://<domain>/.well-known/acme-challenge/<token>: dial tcp xxx.xxx.xxx.xxx:80: connect: connection timed out
  State:       pending
Events:
  Type    Reason     Age    From          Message
  ----    ------     ----   ----          -------
  Normal  Started    4m28s  cert-manager  Challenge scheduled for processing
  Normal  Presented  4m28s  cert-manager  Presented challenge using http-01 challenge mechanism
</code>```

I tried to delete the challenge to re-trigger it, but it failed with same error after one-two minutes. I checked that I can access challenge URL from cluster nodes (using kubectl run -it ... and wget http://<domain>/.well-known/acme-challenge/<token> from inside new pod.

答:
In my case the cert-manager wanted to request the challenge via an internal ip-address.

failed to perform self check GET request 'http:///.well-known/acme-challenge/': Get http:///.well-known/acme-challenge/: dial tcp 10.67.0.8:80: connect: connection timed out

i.e. the DNS-resolution was broken. I fixed this by changing the deployment of cert-manager to accept only external DNS-servers like so

spec:
  template:
    spec:
      dnsConfig:
        nameservers:
        - 8.8.8.8
      dnsPolicy: None
```

This is how you do it. Also created an Issue so we can change that with the helm installation

Body:
Waiting for http-01 challenge propagation: failed to perform self check GET request, it's similar to this bug https://github.com/jetstack/cert-manager/issues/656
but all solutions from GitHub ticket comments didn't help.

I'm trying to set up CertManager on DigitalOcean as described in this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes
I didn't get any error but the request from CertManager is waiting in pending state more than 40 hours.

I have successfully configured Ingress with Nginx, then I created a namespace and created CertManager CRDs:

$ kubectl create namespace cert-manager
$ kubectl apply --validate=false -f https://github.com/jetstack/cert-manager/releases/download/v0.12.0/cert-manager.yaml

I can see all CertManager pods as expected:

$ kubectl get pods --namespace cert-manager
NAME                                       READY   STATUS    RESTARTS   AGE
cert-manager-5c47f46f57-gxhwv              1/1     Running   0          42h
cert-manager-cainjector-6659d6844d-xp75s   1/1     Running   0          42h
cert-manager-webhook-547567b88f-k4dv2      1/1     Running   0          42h

Then I created staging issuer:

---
apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: letsencrypt-staging
  namespace: cert-manager
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: some@email.here
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
      - http01:
          ingress:
            class: nginx

And updated Ingress configuration:

---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: echo-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    # cert-manager.io/cluster-issuer: "letsencrypt-prod"
    cert-manager.io/cluster-issuer: "letsencrypt-staging"
spec:
  tls:
    - hosts:
        - echo.some.domain
      secretName: ingress-tls
  rules:
    - host: echo.some.domain
      http:
        paths:
          - backend:
              serviceName: echo1
              servicePort: 80

But after that, CertManager didn't update certificate and waiting in InProgress state:

$ date
Wed 18 Dec 2019 01:58:08 PM MSK

$ kubectl describe cert

...
Status:
  Conditions:
    Last Transition Time:  2019-12-16T17:23:56Z
    Message:               Waiting for CertificateRequest "ingress-tls-1089568541" to complete
    Reason:                InProgress
    Status:                False
    Type:                  Ready
Events:                    <none>

Instead of using Fake LE Intermediate X1 as a CN it returns CN=Kubernetes Ingress Controller Fake Certificate,O=Acme Co

$ kubectl describe CertificateRequest
Status:
  Conditions:
    Last Transition Time:  2019-12-16T17:50:05Z
    Message:               Waiting on certificate issuance from order default/ingress-tls-1089568541-1576201144: "pending"
    Reason:                Pending
    Status:                False
    Type:                  Ready
Events:                    <none>

What can be the problem with CertManager and how to fix it?

Update:

Ingress logs contains these errors:

$ kubectl -n ingress-nginx logs  nginx-ingress-controller-7754db565c-g557h

I1218 17:24:30.331127       6 status.go:295] updating Ingress default/cm-acme-http-solver-4dkdn status from [] to [{xxx.xxx.xxx.xxx }]
I1218 17:24:30.333250       6 status.go:295] updating Ingress default/cm-acme-http-solver-9dpqc status from [] to [{xxx.xxx.xxx.xxx }]
I1218 17:24:30.341292       6 event.go:209] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default", Name:"cm-acme-http-solver-4dkdn", UID:"2e523b74-8bbb-41c7-be8a-44d8db8abd6e", APIVersion:"extensions/v1beta1", ResourceVersion:"722472", FieldPath:""}): type: 'Normal' reason: 'UPDATE' Ingress default/cm-acme-http-solver-4dkdn
I1218 17:24:30.344340       6 event.go:209] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default", Name:"cm-acme-http-solver-9dpqc", UID:"b574a3b6-6c5b-4266-a4e2-6ff2de2d78e0", APIVersion:"extensions/v1beta1", ResourceVersion:"722473", FieldPath:""}): type: 'Normal' reason: 'UPDATE' Ingress default/cm-acme-http-solver-9dpqc
W1218 17:24:30.442276       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate
W1218 17:24:30.442950       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate
W1218 17:24:33.775476       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate
W1218 17:24:33.775956       6 controller.go:1042] Error getting SSL certificate "default/ingress-tls": local SSL certificate default/ingress-tls was not found. Using default certificate

Update2:

Secret for ingress-tls is available as expected:

$ kubectl get secret ingress-tls -o yaml

apiVersion: v1
data:
  ca.crt: ""
  tls.crt: ""
  tls.key: <secret-key-data-base64-encoded>
kind: Secret
metadata:
  annotations:
    cert-manager.io/certificate-name: ingress-tls
    cert-manager.io/issuer-kind: ClusterIssuer
    cert-manager.io/issuer-name: letsencrypt-staging
  creationTimestamp: "2019-12-16T17:23:56Z"
  name: ingress-tls
  namespace: default
  resourceVersion: "328801"
  selfLink: /api/v1/namespaces/default/secrets/ingress-tls
  uid: 5d640b66-1572-44a1-94e4-6d85a73bf21c
type: kubernetes.io/tls

Update3:

I've found that cert-manager pod is failing with log:

E1219 11:06:08.294011       1 sync.go:184] cert-manager/controller/challenges "msg"="propagation check failed" "error"="failed to perform self check GET request 'http://<some.domain>/.well-known/acme-challenge/<some-path>': Get http://<some.domain>/.well-known/acme-challenge/<some-path>: dial tcp xxx.xxx.xxx.xxx:80: connect: connection timed out" "dnsName"="<some.domain>" "resource_kind"="Challenge" "resource_name"="ingress-tls-1089568541-1576201144-1086699008" "resource_namespace"="default" "type"="http-01"

Challenge status:

$ kubectl describe challenge ingress-tls-1089568541-1576201144-471532423

Name:         ingress-tls-1089568541-1576201144-471532423
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  acme.cert-manager.io/v1alpha2
Kind:         Challenge
Metadata:
  Creation Timestamp:  2019-12-19T11:32:19Z
  Finalizers:
    finalizer.acme.cert-manager.io
  Generation:  1
  Owner References:
    API Version:           acme.cert-manager.io/v1alpha2
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Order
    Name:                  ingress-tls-1089568541-1576201144
    UID:                   7d19d86f-0b56-4756-aa20-bb85caf80b9e
  Resource Version:        872062
  Self Link:               /apis/acme.cert-manager.io/v1alpha2/namespaces/default/challenges/ingress-tls-1089568541-1576201144-471532423
  UID:                     503a8b4e-dc60-4080-91d9-2847815af1cc
Spec:
  Authz URL:  https://acme-staging-v02.api.letsencrypt.org/acme/authz-v3/123456
  Dns Name:   <domain>
  Issuer Ref:
    Group:  cert-manager.io
    Kind:   ClusterIssuer
    Name:   letsencrypt-staging
  Key:      <key>
  Solver:
    http01:
      Ingress:
        Class:  nginx
  Token:        <token>
  Type:         http-01
  URL:          https://acme-staging-v02.api.letsencrypt.org/acme/chall-v3/12345/abc
  Wildcard:     false
Status:
  Presented:   true
  Processing:  true
  Reason:      Waiting for http-01 challenge propagation: failed to perform self check GET request 'http://<domain>/.well-known/acme-challenge/<token>': Get http://<domain>/.well-known/acme-challenge/<token>: dial tcp xxx.xxx.xxx.xxx:80: connect: connection timed out
  State:       pending
Events:
  Type    Reason     Age    From          Message
  ----    ------     ----   ----          -------
  Normal  Started    4m28s  cert-manager  Challenge scheduled for processing
  Normal  Presented  4m28s  cert-manager  Presented challenge using http-01 challenge mechanism

I tried to delete the challenge to re-trigger it, but it failed with same error after one-two minutes. I checked that I can access challenge URL from cluster nodes (using kubectl run -it ... and wget http://<domain>/.well-known/acme-challenge/<token> from inside new pod.

Body:
In my case the cert-manager wanted to request the challenge via an internal ip-address.

failed to perform self check GET request 'http:///.well-known/acme-challenge/': Get http:///.well-known/acme-challenge/: dial tcp 10.67.0.8:80: connect: connection timed out

i.e. the DNS-resolution was broken. I fixed this by changing the deployment of cert-manager to accept only external DNS-servers like so

spec:
  template:
    spec:
      dnsConfig:
        nameservers:
        - 8.8.8.8
      dnsPolicy: None

This is how you do it. Also created an Issue so we can change that with the helm installation


问:
dynamic subdomain does not draw $_GET variables
So trough the big hassle of this finding for the right script and yadayadayada I now have a CNAME redirecting myawesomeblog.mysite.com to mysite.com/?blog=myawesomeblog and a .htaccess code like the following

```<code>RewriteEngine On

# Prevent people from going to to index.php directly and spoofing the
# subdomain value, since this may not be a desirable action
RewriteCond %{THE_REQUEST} ^[A-Z]+\index\.php.*(\?|&)blog=
RewriteRule ^.*$ http://%{HTTP_HOST}/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^.*$ index.php?blog=%1
</code>```

It all works, except that I need to get *.mysite.com/?get=something&get2=something-more working as well, I have no idea how to make it happen tho'

All help is appreciated.

答:
You probably need an extra flag to your rules:

```<code>RewriteRule ^.*$ http://%{HTTP_HOST}/ [R=301,L,QSA]

RewriteRule ^.*$ index.php?blog=%1 [L,QSA]
</code>```

R as in redirect. L as in last. QSA as in query string append.

Body:
So trough the big hassle of this finding for the right script and yadayadayada I now have a CNAME redirecting myawesomeblog.mysite.com to mysite.com/?blog=myawesomeblog and a .htaccess code like the following

RewriteEngine On

# Prevent people from going to to index.php directly and spoofing the
# subdomain value, since this may not be a desirable action
RewriteCond %{THE_REQUEST} ^[A-Z]+\index\.php.*(\?|&)blog=
RewriteRule ^.*$ http://%{HTTP_HOST}/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^.*$ index.php?blog=%1

It all works, except that I need to get *.mysite.com/?get=something&get2=something-more working as well, I have no idea how to make it happen tho'

All help is appreciated.

Body:
You probably need an extra flag to your rules:

RewriteRule ^.*$ http://%{HTTP_HOST}/ [R=301,L,QSA]

RewriteRule ^.*$ index.php?blog=%1 [L,QSA]

R as in redirect. L as in last. QSA as in query string append.


问:
Why won't my other input values not insert to my database?
I'm trying to insert my forms into my database, but the "reden" input will only enter when I type it in my textbox. The values of my radio buttons don't seem to enter. How do I fix this? this is a file for making a simple registration. The varchar value of "reden" in my databse is (20) so I don't understand why it doesn't show up. It's just black.

```<code> <?php
    $Groep = $_POST['Groep'];
    $reden = $_POST['reden'];
    //$RDatum = $_POST[STR_TO_DATE('$$RDatum', '%m/%d/%Y')];

    date_default_timezone_set('UTC');
    $timestamp = strtotime($_POST['tijdstip']);
    $tijdstip=date("Y-m-d", $timestamp);

    if (!empty($Groep) || !empty($tijdstip) )
        {
        $host = "localhost";
        $dbUsername = "root";
        $dbPassword = "root";
        $dbname = "gevuldetomaat";

    //create connection
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
    if ($conn->connect_error)   {
     die("Connection failed: ". $conn->connect_error);
                                } else      {
    $INSERT ="INSERT INTO reservering (Tijdstip, reden, Groep) values(?, ?, ?)";
    $stmt = $conn->prepare($INSERT);
    $stmt->bind_param("sss",$tijdstip, $reden, $Groep);
    $stmt->execute(); // Run the INSERT statement
    if ($stmt->errno)   { // Check for errors
        die("Error in inserting: " . $stmt->error); // Print last error
                        }
        else    { // No errors
        echo "New record inserted sucessfully"; // Success message
                }
                                                            }
    }
?>
</code>```

This is my html code

```<code>    <!DOCTYPE html>

<html lang="en"
<head>
    <title>De Gevulde Tomaat</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="Reservering.css">
</head>
<body>

<form action="Reservering.php" method="POST">
  <table>
  <tr>
    <td style="color:white">GROEP :</td>
    <td><input type="number" name="Groep" required></td>
    </tr>
<tr>
<tr>
    <td style="color:white">Reden :</td>
</tr>
<tr>
    <td><input type="radio" name="reden" value="Verjaardag">Verjaardag</td>
    <td style="color:white"><label for="Verjaardag">Verjaardag</label><br></td>
</tr>
<tr>
    <td><input type="radio" name="reden" value="Anniversary">Anniversary</td>
    <td style="color:white"><label for="Anniversary">Anniversary</label><br></td>
 </tr>
 <tr>
    <td style="color:white">Other :</td>
    <td><input type="text" name="reden"></td>
  </tr>
<tr>
    <td style="color:white">DAG :</td>
    <td><input type="date" name="tijdstip" required></td>
   </tr>
<tr>
    <td><input type="submit" value="Submit"></td>
   </tr>
  </table>
 </form>
</body>
</code>```

答:
Your third element named reden is not a radio input. This overwrites the radio value with the empty input.

```<code><input type="text" name="reden">
</code>```

rename the other option:

```<code><td style="color:white">Other :</td>
<td><input type="text" name="reden_other_text" /></td>
</code>```

You can use JS to have that behave differently.

Additionally, your empty check should use and not or to ensure both values are not empty.

```<code>if (!empty($Groep) && !empty($tijdstip))
</code>```

and should check for $reden as well if that is required.

You can use ternary to determine which one to use:

```<code>$reden = !empty($_POST['reden_other_text']) ? $_POST['reden_other_text'] : reden_other_text$_POST['reden'];
</code>```

Body:
I'm trying to insert my forms into my database, but the "reden" input will only enter when I type it in my textbox. The values of my radio buttons don't seem to enter. How do I fix this? this is a file for making a simple registration. The varchar value of "reden" in my databse is (20) so I don't understand why it doesn't show up. It's just black.

 <?php
    $Groep = $_POST['Groep'];
    $reden = $_POST['reden'];
    //$RDatum = $_POST[STR_TO_DATE('$$RDatum', '%m/%d/%Y')];

    date_default_timezone_set('UTC');
    $timestamp = strtotime($_POST['tijdstip']);
    $tijdstip=date("Y-m-d", $timestamp);

    if (!empty($Groep) || !empty($tijdstip) )
        {
        $host = "localhost";
        $dbUsername = "root";
        $dbPassword = "root";
        $dbname = "gevuldetomaat";

    //create connection
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
    if ($conn->connect_error)   {
     die("Connection failed: ". $conn->connect_error);
                                } else      {
    $INSERT ="INSERT INTO reservering (Tijdstip, reden, Groep) values(?, ?, ?)";
    $stmt = $conn->prepare($INSERT);
    $stmt->bind_param("sss",$tijdstip, $reden, $Groep);
    $stmt->execute(); // Run the INSERT statement
    if ($stmt->errno)   { // Check for errors
        die("Error in inserting: " . $stmt->error); // Print last error
                        }
        else    { // No errors
        echo "New record inserted sucessfully"; // Success message
                }
                                                            }
    }
?>

This is my html code

    <!DOCTYPE html>

<html lang="en"

    <title>De Gevulde Tomaat</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="Reservering.css">

<form action="Reservering.php" method="POST">

    GROEP :
    <input type="number" name="Groep" required>

    Reden :

    <input type="radio" name="reden" value="Verjaardag">Verjaardag
    Verjaardag

    <input type="radio" name="reden" value="Anniversary">Anniversary
    Anniversary

    Other :
    <input type="text" name="reden">

    DAG :
    <input type="date" name="tijdstip" required>

    <input type="submit" value="Submit">

 </form>

Body:
Your third element named reden is not a radio input. This overwrites the radio value with the empty input.

<input type="text" name="reden">

rename the other option:

<td style="color:white">Other :</td>
<td><input type="text" name="reden_other_text" /></td>

You can use JS to have that behave differently.

Additionally, your empty check should use and not or to ensure both values are not empty.

if (!empty($Groep) && !empty($tijdstip))

and should check for $reden as well if that is required.

You can use ternary to determine which one to use:

$reden = !empty($_POST['reden_other_text']) ? $_POST['reden_other_text'] : reden_other_text$_POST['reden'];