问:
Calculating piecewise quantile linear regression with segmented package R
I am looking for a way to obtain the piecewise quantile linear regression with R. I have been able to compute the Quantile regression with the package  quantreg. However, I don't want just 1 unique slope but want to check for breakpoints in my dataset. I have seen that the segmented package can do so. While it works good if the fit is carried out with lm or glm (as shown below in an example), it doesn't manage to work for quantile.

On the segmented package info I have read that there is a segmented.default  which can be used for specific regression models, such as Quantiles. However, when I apply it for my quantile outcome it gives me the following errors:

Error in diag(vv) : invalid 'nrow' value (too large or NA)
  In addition: Warning message:
  cannot compute the covariance matrix

If instead of using K=2 I use for example psi I get other type of errors:

Error in rq.fit.br(x, y, tau = tau, ...) : Singular design matrix

I have created an example with the mtcars data so you can see the errors that I get.

```<code>library(quantreg)
library(segmented)

data(mtcars)

out.rq <- rq(mpg ~ wt, data= mtcars)
out.lm <- lm(mpg ~ wt, data= mtcars)

# Plotting the results
plot(mpg ~ wt, data = mtcars, pch = 1, main = "mpg ~ wt")
abline(out.lm, col = "red", lty = 2)
abline(out.rq, col = "blue", lty = 2)
legend("topright", legend = c("linear", "quantile"), col = c("red", "blue"), lty = 2)

#Generating segmented LM
o <- segmented(out.lm, seg.Z= ~wt, npsi=2, control=seg.control(display=FALSE))
plot(o, lwd=2, col=2:6, main="Segmented regression", res=FALSE) #lwd: line width #col: from 2 to 6 #RES: show datapoints

#Generating segmented Quantile
#using K=2
o.quantile <- segmented.default(out.rq, seg.Z= ~wt, control=seg.control(display=FALSE, K=2))
# using psi
o.quantile <- segmented.default(out.rq, seg.Z= ~wt, psi=list(wt=c(2,4)), control=seg.control(display=FALSE))
</code>```

答:
I came across this post after a long time because I have the same issue. Just in case others might be stuck with the problem in the future, I wanted to point out what the problem is.

I examined "segmented.default". There is a line in the source code as follows:

```<code>Cov <- try(vcov(objF), silent = TRUE)
</code>```

vcov is used to calculate the covariance matrix but does not work for quantile regression object objF. To get the covariance matrix for quantile regression, you need:

```<code>summary(objF,se="boot",cov=TRUE)$cov
</code>```

Here, I used bootstrap method to compute the covariance matrix by selecting se="boot" but you should choose the appropriate method for you. Check ?summary.rq then "se" section for different methods.

Additionally, you need to assign the row/column names as follows:

```<code>dimnames(Cov)[[1]] <- dimnames(Cov)[[2]] <- unlist(attributes(objF$coef))
</code>```

After modifying the function, it worked for me.

Body:
I am looking for a way to obtain the piecewise quantile linear regression with R. I have been able to compute the Quantile regression with the package  quantreg. However, I don't want just 1 unique slope but want to check for breakpoints in my dataset. I have seen that the segmented package can do so. While it works good if the fit is carried out with lm or glm (as shown below in an example), it doesn't manage to work for quantile.

On the segmented package info I have read that there is a segmented.default  which can be used for specific regression models, such as Quantiles. However, when I apply it for my quantile outcome it gives me the following errors:

Error in diag(vv) : invalid 'nrow' value (too large or NA)
  In addition: Warning message:
  cannot compute the covariance matrix

If instead of using K=2 I use for example psi I get other type of errors:

Error in rq.fit.br(x, y, tau = tau, ...) : Singular design matrix

I have created an example with the mtcars data so you can see the errors that I get.

library(quantreg)
library(segmented)

data(mtcars)

out.rq <- rq(mpg ~ wt, data= mtcars)
out.lm <- lm(mpg ~ wt, data= mtcars)

# Plotting the results
plot(mpg ~ wt, data = mtcars, pch = 1, main = "mpg ~ wt")
abline(out.lm, col = "red", lty = 2)
abline(out.rq, col = "blue", lty = 2)
legend("topright", legend = c("linear", "quantile"), col = c("red", "blue"), lty = 2)

#Generating segmented LM
o <- segmented(out.lm, seg.Z= ~wt, npsi=2, control=seg.control(display=FALSE))
plot(o, lwd=2, col=2:6, main="Segmented regression", res=FALSE) #lwd: line width #col: from 2 to 6 #RES: show datapoints

#Generating segmented Quantile
#using K=2
o.quantile <- segmented.default(out.rq, seg.Z= ~wt, control=seg.control(display=FALSE, K=2))
# using psi
o.quantile <- segmented.default(out.rq, seg.Z= ~wt, psi=list(wt=c(2,4)), control=seg.control(display=FALSE))

Body:
I came across this post after a long time because I have the same issue. Just in case others might be stuck with the problem in the future, I wanted to point out what the problem is.

I examined "segmented.default". There is a line in the source code as follows:

Cov <- try(vcov(objF), silent = TRUE)

vcov is used to calculate the covariance matrix but does not work for quantile regression object objF. To get the covariance matrix for quantile regression, you need:

summary(objF,se="boot",cov=TRUE)$cov

Here, I used bootstrap method to compute the covariance matrix by selecting se="boot" but you should choose the appropriate method for you. Check ?summary.rq then "se" section for different methods.

Additionally, you need to assign the row/column names as follows:

dimnames(Cov)[[1]] <- dimnames(Cov)[[2]] <- unlist(attributes(objF$coef))

After modifying the function, it worked for me.


来源: stackexchange

问:
Gap between border and page edge
I have added a border around my page which should stay fixed even when the page scrolls.
How do I remove the small gap between the red border and the edge of page??

body::before {
    content: '';
    position: fixed;
    top: 5px;
    left: 10px;
    right: 10px;
    bottom: 10px;
    border: 15px solid red;
    padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras porttitor, purus non hendrerit bibendum, mauris nisi maximus metus, sit amet commodo augue purus quis lorem. Nullam laoreet nibh nisi, eu suscipit libero varius id. Nunc lobortis odio eu tempor vulputate. Sed placerat nisi gravida lorem laoreet congue. Nam blandit faucibus molestie. Sed tempus mi a arcu eleifend, ut malesuada elit ultricies. Sed odio leo, tempus non accumsan nec, condimentum viverra arcu. Nullam accumsan, elit sed vulputate ultricies, elit lorem interdum lectus, ut feugiat ipsum diam sed nulla. Etiam et pharetra turpis. Duis accumsan quam sit amet interdum blandit. Sed auctor hendrerit mauris ac vestibulum. Nam at dapibus lacus, non mattis turpis. Suspendisse potenti. Quisque vel condimentum enim, quis tincidunt purus. Fusce cursus odio non venenatis dictum. Maecenas felis felis, blandit a dictum ut, blandit sed justo.

Vestibulum placerat placerat elit eget auctor. Suspendisse auctor massa eros, a lobortis leo faucibus a. Pellentesque mi nibh, efficitur vitae dignissim quis, egestas luctus ante. Maecenas at blandit tellus. Sed eleifend, erat commodo sollicitudin egestas, nisl ante sollicitudin sem, eu venenatis nisi mauris at orci. Aliquam erat volutpat. Phasellus nulla augue, dapibus et sem ac, vestibulum ultricies risus. Donec ut lectus risus. Mauris tincidunt, ipsum quis rhoncus scelerisque, quam augue molestie eros, dapibus gravida neque diam in quam. Sed vulputate ante ut tortor rhoncus maximus. Curabitur id facilisis leo, ac suscipit orci. Fusce auctor neque quis fringilla pretium.

Cras nec eros id est ullamcorper consequat. Quisque pellentesque venenatis pretium. Sed a ullamcorper massa. Morbi eget rutrum nisl. Nullam semper tellus ut purus lacinia ornare. Quisque sagittis auctor erat, sed volutpat turpis. Suspendisse vehicula faucibus lectus, nec iaculis turpis mattis ut. Aliquam dapibus felis lectus, sit amet mattis nunc ullamcorper quis. Nam dictum nibh ac pretium vehicula. Cras porta in neque nec convallis. Cras libero tellus, luctus id velit vel, molestie egestas nunc. Morbi vitae dolor metus. Donec vitae interdum sem, vitae condimentum ante. Cras in turpis et nisl tincidunt vehicula.

Sed ut magna commodo, iaculis velit vel, cursus velit. Curabitur nunc sem, maximus et ullamcorper in, venenatis vel sapien. Praesent vulputate, purus sit amet rhoncus lacinia, urna lectus venenatis dui, in elementum velit quam nec urna. Curabitur quis efficitur sem. Proin id feugiat mi. Duis sed diam vitae tortor mollis auctor vitae non erat. Aenean pulvinar accumsan luctus. Fusce at massa suscipit, gravida risus ut, laoreet tortor. Praesent vitae purus elit. Praesent feugiat augue eu tellus scelerisque, vel fringilla ligula suscipit.

Nulla ac elementum neque. Integer tincidunt sollicitudin cursus. Proin a lacus augue. Etiam scelerisque scelerisque commodo. Nulla eros felis, aliquet at tincidunt in, vulputate sit amet libero. Mauris sed vulputate urna, ac consectetur lacus. Duis eget lorem blandit, laoreet velit in, sagittis augue. Vestibulum ut erat quis ipsum aliquam fermentum. Ut varius odio lacus, ut dictum dolor laoreet non. Donec feugiat dictum magna, mollis mattis nibh bibendum quis. Sed ornare risus vel massa tristique, vel iaculis enim aliquet. Sed mauris erat, faucibus sit amet hendrerit eget, suscipit sed neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</code>```

答:
try adding this to your css, the browser, by default adds some margin and padding to every container

```<code>* {margin: 0!important; padding:0!important;}
</code>```

then you will have to add margins and paddings you need them

ContentLicense: CC BY-SA 4.0

Title: Gap between border and page edge

Body:
I have added a border around my page which should stay fixed even when the page scrolls.
How do I remove the small gap between the red border and the edge of page??

body::before {
    content: '';
    position: fixed;
    top: 5px;
    left: 10px;
    right: 10px;
    bottom: 10px;
    border: 15px solid red;
    padding: 0px;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras porttitor, purus non hendrerit bibendum, mauris nisi maximus metus, sit amet commodo augue purus quis lorem. Nullam laoreet nibh nisi, eu suscipit libero varius id. Nunc lobortis odio eu tempor vulputate. Sed placerat nisi gravida lorem laoreet congue. Nam blandit faucibus molestie. Sed tempus mi a arcu eleifend, ut malesuada elit ultricies. Sed odio leo, tempus non accumsan nec, condimentum viverra arcu. Nullam accumsan, elit sed vulputate ultricies, elit lorem interdum lectus, ut feugiat ipsum diam sed nulla. Etiam et pharetra turpis. Duis accumsan quam sit amet interdum blandit. Sed auctor hendrerit mauris ac vestibulum. Nam at dapibus lacus, non mattis turpis. Suspendisse potenti. Quisque vel condimentum enim, quis tincidunt purus. Fusce cursus odio non venenatis dictum. Maecenas felis felis, blandit a dictum ut, blandit sed justo.

Vestibulum placerat placerat elit eget auctor. Suspendisse auctor massa eros, a lobortis leo faucibus a. Pellentesque mi nibh, efficitur vitae dignissim quis, egestas luctus ante. Maecenas at blandit tellus. Sed eleifend, erat commodo sollicitudin egestas, nisl ante sollicitudin sem, eu venenatis nisi mauris at orci. Aliquam erat volutpat. Phasellus nulla augue, dapibus et sem ac, vestibulum ultricies risus. Donec ut lectus risus. Mauris tincidunt, ipsum quis rhoncus scelerisque, quam augue molestie eros, dapibus gravida neque diam in quam. Sed vulputate ante ut tortor rhoncus maximus. Curabitur id facilisis leo, ac suscipit orci. Fusce auctor neque quis fringilla pretium.

Cras nec eros id est ullamcorper consequat. Quisque pellentesque venenatis pretium. Sed a ullamcorper massa. Morbi eget rutrum nisl. Nullam semper tellus ut purus lacinia ornare. Quisque sagittis auctor erat, sed volutpat turpis. Suspendisse vehicula faucibus lectus, nec iaculis turpis mattis ut. Aliquam dapibus felis lectus, sit amet mattis nunc ullamcorper quis. Nam dictum nibh ac pretium vehicula. Cras porta in neque nec convallis. Cras libero tellus, luctus id velit vel, molestie egestas nunc. Morbi vitae dolor metus. Donec vitae interdum sem, vitae condimentum ante. Cras in turpis et nisl tincidunt vehicula.

Sed ut magna commodo, iaculis velit vel, cursus velit. Curabitur nunc sem, maximus et ullamcorper in, venenatis vel sapien. Praesent vulputate, purus sit amet rhoncus lacinia, urna lectus venenatis dui, in elementum velit quam nec urna. Curabitur quis efficitur sem. Proin id feugiat mi. Duis sed diam vitae tortor mollis auctor vitae non erat. Aenean pulvinar accumsan luctus. Fusce at massa suscipit, gravida risus ut, laoreet tortor. Praesent vitae purus elit. Praesent feugiat augue eu tellus scelerisque, vel fringilla ligula suscipit.

Nulla ac elementum neque. Integer tincidunt sollicitudin cursus. Proin a lacus augue. Etiam scelerisque scelerisque commodo. Nulla eros felis, aliquet at tincidunt in, vulputate sit amet libero. Mauris sed vulputate urna, ac consectetur lacus. Duis eget lorem blandit, laoreet velit in, sagittis augue. Vestibulum ut erat quis ipsum aliquam fermentum. Ut varius odio lacus, ut dictum dolor laoreet non. Donec feugiat dictum magna, mollis mattis nibh bibendum quis. Sed ornare risus vel massa tristique, vel iaculis enim aliquet. Sed mauris erat, faucibus sit amet hendrerit eget, suscipit sed neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Body:
try adding this to your css, the browser, by default adds some margin and padding to every container

* {margin: 0!important; padding:0!important;}

then you will have to add margins and paddings you need them


问:
Infinite sideways scroll animation of images
I'm trying to animate back and forth (or infinite scroll to the right) a bunch of images but I'm facing an issue in which when the animation starts (and when it reverses) the images are hidden outside of view.

That's because I'm using translate(-100%).

If possible, I would like to not depend of knowing the image size or limiting the viewport size to make this work.

(Ignore the speed of the animation, I'm going to set to a longer duration later)

 .slideshow {
  height: 150px;
  /*max-width: 800px;*/ /*The width of the page cannot be a problem*/
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  transform: translate3d(0, 0, 0);
}

.slideshow > div {
  height: 150px;
  width: 2000px; /*I don't want to have to input a width.*/
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  transform: translate3d(0, 0, 0);
}

.move > img {
  height: 150px;
}

.slideshow .move {
animation: moveSlideshow 10s linear infinite alternate-reverse;
}

.slideshow .move:hover {
-webkit-animation-play-state: paused;
-moz-animation-play-state: paused;
-o-animation-play-state: paused;
animation-play-state: paused;
}

@keyframes moveSlideshow {
  0% {
transform: translateX(0%);
  }
  100% {
transform: translateX(-100%);  /*The width of the page needs to be taken into consideration*/
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slideshow">
  <div class="move">
 <img src="https://via.placeholder.com/300x150">
 <img src="https://via.placeholder.com/300x150">
 <img src="https://via.placeholder.com/300x150">
 <img src="https://via.placeholder.com/300x150">
 <img src="https://via.placeholder.com/300x150">
 <img src="https://via.placeholder.com/300x150">
  </div>
</div></code>```

I also tried to use: transform: translateX(100%) translateX(-50px);, but it does not work.

My first goal was to make an infinite scroller, when the animation reaches the end, it should start again, but without being noticeable (smooth restart, end image needs to be followed by the start image).

If I'm unable to do that, I would like to have a back and forth animation, but starting with the last image touching the right edge of the viewport.
(With the code above, the animation starts with the images to the left)

How can I fix this animation?
(To enable infinite smooth scrolling or to not disappear from the view)

Edit:

I managed to make it work with the animation back and forth, by using these keyframes:

```<code>@keyframes moveSlideshow {
  0% {
    transform: translateX(0%);
  }
  100% {
    -ms-transform: translateX(-100%) translateX(100vw);
    transform: translateX(calc(-100% + 100vw));
  }
}
</code>```

Now, the last image starts at the right and the first image ends at the left.
The only problem is that the speed in which the animation plays changes when the viewport width changes.

答:
To make the scroll continous and infinite you need to duplicate your images.

Then it's easy to achieve what you want:

Note: In the initial state, the first move element is displayed , aligned to the left. The second move element is to the right of this, and not visible because it's out of the container.

We will move both of them 100% to the left. The first one will get out of sight thru the left, and in some moment will leave a blank to the right. But the second one is moving at the same speed, so will fill the blank that the first leaves.

The animation ends when the second one has moved 100%,so it is displayed at the same place that was the first one. Now the animation starts again, and the first one is displayed instead, but you won't notce this change.

.slideshow {
  height: 150px;
  margin: 0 auto;
  position: relative;
  transform: translate3d(0, 0, 0);
  display: flex;
  width: 100%;
  overflow: hidden;
  background-color: blue;
}

.move {
  height: 100%;
  transform: translate3d(0, 0, 0);
  display: flex;
  animation: moveSlideshow 10s linear infinite;
}

.move:nth-child(2) img {
  opacity: 0.4;

}
.move > img {
  height: 150px;
  width: auto;
}

.slideshow:hover .move {
  animation-play-state: paused;
}

@keyframes moveSlideshow {
  0% {
    transform: translateX(0%);
  }
  100% {
    transform: translateX(-100%);
    /*The width of the page needs to be taken into consideration*/
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slideshow">
  <div class="move">
    <img src="https://via.placeholder.com/400x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/200x150">
  </div>
  <div class="move">
    <img src="https://via.placeholder.com/400x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/200x150">
  </div>
</div></code>```

Body:
I'm trying to animate back and forth (or infinite scroll to the right) a bunch of images but I'm facing an issue in which when the animation starts (and when it reverses) the images are hidden outside of view.

That's because I'm using translate(-100%).

If possible, I would like to not depend of knowing the image size or limiting the viewport size to make this work.

(Ignore the speed of the animation, I'm going to set to a longer duration later)

 .slideshow {
  height: 150px;
  /*max-width: 800px;*/ /*The width of the page cannot be a problem*/
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  transform: translate3d(0, 0, 0);
}

.slideshow > div {
  height: 150px;
  width: 2000px; /*I don't want to have to input a width.*/
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  transform: translate3d(0, 0, 0);
}

.move > img {
  height: 150px;
}

.slideshow .move {
animation: moveSlideshow 10s linear infinite alternate-reverse;
}

.slideshow .move:hover {
-webkit-animation-play-state: paused;
-moz-animation-play-state: paused;
-o-animation-play-state: paused;
animation-play-state: paused;
}

@keyframes moveSlideshow {
  0% {
transform: translateX(0%);
  }
  100% {
transform: translateX(-100%);  /*The width of the page needs to be taken into consideration*/
  }
}

I also tried to use: transform: translateX(100%) translateX(-50px);, but it does not work.

My first goal was to make an infinite scroller, when the animation reaches the end, it should start again, but without being noticeable (smooth restart, end image needs to be followed by the start image).

If I'm unable to do that, I would like to have a back and forth animation, but starting with the last image touching the right edge of the viewport.
(With the code above, the animation starts with the images to the left)

How can I fix this animation?
(To enable infinite smooth scrolling or to not disappear from the view)

Edit:

I managed to make it work with the animation back and forth, by using these keyframes:

@keyframes moveSlideshow {
  0% {
    transform: translateX(0%);
  }
  100% {
    -ms-transform: translateX(-100%) translateX(100vw);
    transform: translateX(calc(-100% + 100vw));
  }
}

Now, the last image starts at the right and the first image ends at the left.
The only problem is that the speed in which the animation plays changes when the viewport width changes.

Body:
To make the scroll continous and infinite you need to duplicate your images.

Then it's easy to achieve what you want:

Note: In the initial state, the first move element is displayed , aligned to the left. The second move element is to the right of this, and not visible because it's out of the container.

We will move both of them 100% to the left. The first one will get out of sight thru the left, and in some moment will leave a blank to the right. But the second one is moving at the same speed, so will fill the blank that the first leaves.

The animation ends when the second one has moved 100%,so it is displayed at the same place that was the first one. Now the animation starts again, and the first one is displayed instead, but you won't notce this change.

.slideshow {
  height: 150px;
  margin: 0 auto;
  position: relative;
  transform: translate3d(0, 0, 0);
  display: flex;
  width: 100%;
  overflow: hidden;
  background-color: blue;
}

.move {
  height: 100%;
  transform: translate3d(0, 0, 0);
  display: flex;
  animation: moveSlideshow 10s linear infinite;
}

.move:nth-child(2) img {
  opacity: 0.4;

}
.move > img {
  height: 150px;
  width: auto;
}

.slideshow:hover .move {
  animation-play-state: paused;
}

@keyframes moveSlideshow {
  0% {
    transform: translateX(0%);
  }
  100% {
    transform: translateX(-100%);
    /*The width of the page needs to be taken into consideration*/
  }
}

<div class="slideshow">
  <div class="move">
    <img src="https://via.placeholder.com/400x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/200x150">
  </div>
  <div class="move">
    <img src="https://via.placeholder.com/400x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/300x150">
    <img src="https://via.placeholder.com/200x150">
  </div>
</div>


问:
symfony 5 mercure bundle HTTP/1.1 400 Bad Request returned
I'm trying to use symfony mercure bundle but it doesn't seem to work even with the example given on the documentation.
here is my code in my controller

```<code>/**
 * @Route("/test", name="test")
 */
class TestController extends AbstractController
{

    public function __invoke(PublisherInterface $publisher): Response
    {
        $update = new Update(
            '/chat',
            json_encode(['status' => 'OutOfStock'])
        );

        // The Publisher service is an invokable object
        $publisher($update);

        return new Response('published!');
    }

}
</code>```

and this the error i get.

HTTP/1.1 400 Bad Request returned for "http://localhost:3000/.well-known/mercure".

does anyone have any idea what's wrong?

error image here

here is a github link for a my project

答:
I found ...
there was an error in my environment variable

MERCURE_PUBLISH_URL = http: // localhost: 3000 / .well-known / mercury

instead of

MERCURE_PUBLISH_URL = http: // localhost: 3000 //.
  Well-known / mercury,

one slash too many .
thank you all

Body:
I'm trying to use symfony mercure bundle but it doesn't seem to work even with the example given on the documentation.
here is my code in my controller

/**
 * @Route("/test", name="test")
 */
class TestController extends AbstractController
{

    public function __invoke(PublisherInterface $publisher): Response
    {
        $update = new Update(
            '/chat',
            json_encode(['status' => 'OutOfStock'])
        );

        // The Publisher service is an invokable object
        $publisher($update);

        return new Response('published!');
    }

}

and this the error i get.

HTTP/1.1 400 Bad Request returned for "http://localhost:3000/.well-known/mercure".

does anyone have any idea what's wrong?

error image here

here is a github link for a my project


问:
google recaptcha returns false due to "invalid-input-secret"
I have installed the latest recaptcha from google but it always returns false upon post submit and always returning "invalid-input-secret" error even though the verification is always correct from the frontend view. What could be the reason on this. Btw I am testing everything in localhost xampp with phalcon framework. Here is the part where I check the captcha:

```<code>protected function validate_data($post, $ip){

    $validation = new Validation();
    $validation->add(
        'user_name',
        new PresenceOf(
            array(
                'message' => 'The Username is required'
            )
        )
    );
    $validation->add(
        'email',
        new PresenceOf(
            array(
                'message' => 'The e-mail is required'
            )
        )
    );
    $validation->add(
        'password',
        new PresenceOf(
            array(
                'message' => 'The Password is required'
            )
        )
    );
    $validation->add(
        'cpassword',
        new PresenceOf(
            array(
                'message' => 'The Confirmation Password is required'
            )
        )
    );
    $validation->add(
        'email',
        new Email(
            array(
                'message' => 'The e-mail is not valid'
            )
        )
    );

    $validation->add('password',
        new Confirmation(array(
           'message' => 'Password doesn\'t match confirmation',
           'with' => 'cpassword'
           )
        )
    );

    $error = $validation->validate($post);
    $errors = array();
    if(count($error)){
        foreach($error as $e){
            $errors[] = $e;
        }
    }

    $data = array(
        'secret' => "my secret key",
        'response' => $post['g-recaptcha-response'],
        'remoteip' => $ip
    );

    $verify = curl_init();
    curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
    curl_setopt($verify, CURLOPT_POST, true);
    curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($verify);

    $captcha = json_decode($res);

    if($captcha->success == false){
        $errors[] = "Invalid Captcha, You are a freakin robot!";
    }

    return $errors;

}
</code>```

what could be the reason here? here is the output when you dump the response:

```<code>object(stdClass)#70 (2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(20) "invalid-input-secret" } }
</code>```

答:
For javascript

In my case I used environment variable
 I defined the variable with double quotes"6Lfg1_0UAAAAABWdUn5gNhXEuLxhpkQyheDpLbnB". So when the secret key passed via url it will be included with double quotes. it was the issue in my case. the double quotes should not be included in the url.

When you define the environment variable define with single quotes like below:

RECAPTCHA_SECRET_KEY='6Lfg1_0UAAAAABWdUn5gNhXEuLxhpkQyheDpLbnB'

ContentLicense: CC BY-SA 3.0

Body:
I have installed the latest recaptcha from google but it always returns false upon post submit and always returning "invalid-input-secret" error even though the verification is always correct from the frontend view. What could be the reason on this. Btw I am testing everything in localhost xampp with phalcon framework. Here is the part where I check the captcha:

protected function validate_data($post, $ip){

    $validation = new Validation();
    $validation->add(
        'user_name',
        new PresenceOf(
            array(
                'message' => 'The Username is required'
            )
        )
    );
    $validation->add(
        'email',
        new PresenceOf(
            array(
                'message' => 'The e-mail is required'
            )
        )
    );
    $validation->add(
        'password',
        new PresenceOf(
            array(
                'message' => 'The Password is required'
            )
        )
    );
    $validation->add(
        'cpassword',
        new PresenceOf(
            array(
                'message' => 'The Confirmation Password is required'
            )
        )
    );
    $validation->add(
        'email',
        new Email(
            array(
                'message' => 'The e-mail is not valid'
            )
        )
    );

    $validation->add('password',
        new Confirmation(array(
           'message' => 'Password doesn\'t match confirmation',
           'with' => 'cpassword'
           )
        )
    );

    $error = $validation->validate($post);
    $errors = array();
    if(count($error)){
        foreach($error as $e){
            $errors[] = $e;
        }
    }

    $data = array(
        'secret' => "my secret key",
        'response' => $post['g-recaptcha-response'],
        'remoteip' => $ip
    );

    $verify = curl_init();
    curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
    curl_setopt($verify, CURLOPT_POST, true);
    curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($verify);

    $captcha = json_decode($res);

    if($captcha->success == false){
        $errors[] = "Invalid Captcha, You are a freakin robot!";
    }

    return $errors;

}

what could be the reason here? here is the output when you dump the response:

object(stdClass)#70 (2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(20) "invalid-input-secret" } }


问:
Wrap the IsNumeric function of SqlFunctions
I'd like to wrap the SqlFunctions.IsNumeric function so that I can use it in other layer without the need to add reference to System.Data (no matter why).

Here is what I did -
In my Repository Interfaces:

```<code>public interface IUtils
{
    Expression<Func<bool>> IsNumeric(string str);
}
</code>```

In my ef layer:

```<code>public class EFUtils : IUtils
{
    public Expression<Func<bool>> IsNumeric(string str)
    {
        return () => SqlFunctions.IsNumeric(str) == 1;
    }
}
</code>```

In my business later:

```<code>public class RepositoryUtils
{
    protected static IUtils Utils { get; set; }

    static RepositoryUtils()
    {
        Utils = ObjectFactory.GetInstance<IUtils>(); //Using structureMap
    }

    public static Expression<Func< bool>> IsNumeric(string str)
    {
        return Utils.IsNumeric(str);
    }
}
</code>```

The problem is that now, after I exposed the method, I don't really know how to use it..

It is something like:

```<code>Customers.OrderBy(x=>**Order by is numeric on x.Name);
</code>```

Any idea?

答:
The RepositoryUtils returns Expression<Func<bool>>, so it should be like this:

```<code>Customers.OrderBy(x => RepositoryUtils.IsNumeric(x.Name).Compile()());
</code>```

By this code you compile the lambda expression and then call it.

UPD. I don't see for what purpose Expression<Func<bool>> is used. I'd use a simple bool:

```<code>public class EFUtils : IUtils
{
    public bool IsNumeric(string str)
    {
        return SqlFunctions.IsNumeric(str) == 1;
    }
}

public class RepositoryUtils
{
    protected static IUtils Utils { get; set; }

    static RepositoryUtils()
    {
        Utils = ObjectFactory.GetInstance<IUtils>(); //Using structureMap
    }

    public static bool IsNumeric(string str)
    {
        return Utils.IsNumeric(str);
    }
}
</code>```

Then the lambda expression will be simpler:

```<code>Customers.OrderBy(x => RepositoryUtils.IsNumeric(x.Name));
</code>```

Body:
I'd like to wrap the SqlFunctions.IsNumeric function so that I can use it in other layer without the need to add reference to System.Data (no matter why).

Here is what I did -
In my Repository Interfaces:

public interface IUtils
{
    Expression<Func<bool>> IsNumeric(string str);
}

In my ef layer:

public class EFUtils : IUtils
{
    public Expression<Func<bool>> IsNumeric(string str)
    {
        return () => SqlFunctions.IsNumeric(str) == 1;
    }
}

In my business later:

public class RepositoryUtils
{
    protected static IUtils Utils { get; set; }

    static RepositoryUtils()
    {
        Utils = ObjectFactory.GetInstance<IUtils>(); //Using structureMap
    }

    public static Expression<Func< bool>> IsNumeric(string str)
    {
        return Utils.IsNumeric(str);
    }
}

The problem is that now, after I exposed the method, I don't really know how to use it..

It is something like:

Customers.OrderBy(x=>**Order by is numeric on x.Name);

Any idea?

Body:
The RepositoryUtils returns Expression<Func<bool>>, so it should be like this:

Customers.OrderBy(x => RepositoryUtils.IsNumeric(x.Name).Compile()());

By this code you compile the lambda expression and then call it.

UPD. I don't see for what purpose Expression<Func<bool>> is used. I'd use a simple bool:

public class EFUtils : IUtils
{
    public bool IsNumeric(string str)
    {
        return SqlFunctions.IsNumeric(str) == 1;
    }
}

public class RepositoryUtils
{
    protected static IUtils Utils { get; set; }

    static RepositoryUtils()
    {
        Utils = ObjectFactory.GetInstance<IUtils>(); //Using structureMap
    }

    public static bool IsNumeric(string str)
    {
        return Utils.IsNumeric(str);
    }
}

Then the lambda expression will be simpler:

Customers.OrderBy(x => RepositoryUtils.IsNumeric(x.Name));


问:
How to set breakpoints in Material ui grid to make it responsive
I am using Material ui Grid to arrange my ui elements. Below is my code

```<code><Grid container spacing={3}>
<Grid container item xs={12} sm={12} md={12} style={{ marginTop: '-1.5%', marginRight: '1%' }}>
<Grid item xs={7} sm={7} md={7}>
   <label className={classes.title}> Title </label>
</Grid>
<Grid item xs={5} sm={5} md={5}>
   <label style = {{marginLeft: '25%'}}> Lable 1 </label>
   <label> Lable 2 </label>
</Grid>
</Grid>
</code>```

Now, as per the above code, i want to make design responsive based on screen sizes and add breakpoints, how can i achieve it? Also, is there any way to handle the browser resolution/zoom, my design goes to horizontal scroll with bigger zoom.

答:
To make this work import

```<code>import {createMuiTheme,ThemeProvider} from "@material-ui/core/styles"
</code>```

As stated above you use the following code to set your breakpoints. You are not limited to the pre defined names you can use any name you want. The values are the min-width for the breaking point. So in this case XS stops at 449px.

```<code>const theme = createMuiTheme({
 breakpoints: {
   values: {
    xs: 0,
    sm: 450,
    md: 600,
    lg: 900,
    xl: 1200,
    tablet:1024
  }
}
});
</code>```

You then have to use a theme provider to implement it.

```<code><ThemeProvider theme={theme}>
   <Grid container><Grid item xs={12}>Some stuff</Grid></Grid>
</ThemeProvider>
</code>```

Body:
I am using Material ui Grid to arrange my ui elements. Below is my code

<Grid container spacing={3}>
<Grid container item xs={12} sm={12} md={12} style={{ marginTop: '-1.5%', marginRight: '1%' }}>
<Grid item xs={7} sm={7} md={7}>
    Title
</Grid>
<Grid item xs={5} sm={5} md={5}>
    Lable 1
    Lable 2
</Grid>
</Grid>

Now, as per the above code, i want to make design responsive based on screen sizes and add breakpoints, how can i achieve it? Also, is there any way to handle the browser resolution/zoom, my design goes to horizontal scroll with bigger zoom.

Body:
To make this work import

import {createMuiTheme,ThemeProvider} from "@material-ui/core/styles"

As stated above you use the following code to set your breakpoints. You are not limited to the pre defined names you can use any name you want. The values are the min-width for the breaking point. So in this case XS stops at 449px.

const theme = createMuiTheme({
 breakpoints: {
   values: {
    xs: 0,
    sm: 450,
    md: 600,
    lg: 900,
    xl: 1200,
    tablet:1024
  }
}
});

You then have to use a theme provider to implement it.

<ThemeProvider theme={theme}>
   <Grid container><Grid item xs={12}>Some stuff</Grid></Grid>
</ThemeProvider>


问:
Opening Android Settings programmatically
How can I open settings programmatically?</p>

答:
I used the code from the most upvoted answer:

startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
```
<p>It <strong>opens the device settings in the same window</strong>, thus got the users of my android application (finnmglas/Launcher) for android stuck in there.</p>
<p>The answer <strong>for 2020 and beyond</strong> (in Kotlin):</p>
```startActivity(Intent(Settings.ACTION_SETTINGS))
```

It works in my app, should also be working in yours without any unwanted consequences.

Body:
I used the code from the most upvoted answer:

startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);

It opens the device settings in the same window, thus got the users of my android application (finnmglas/Launcher) for android stuck in there.

The answer for 2020 and beyond (in Kotlin):

startActivity(Intent(Settings.ACTION_SETTINGS))

It works in my app, should also be working in yours without any unwanted consequences.


问:
error: result of comparison against a string literal is unspecified for C
So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

```<code>#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}
</code>```

答:
Your code has three issues:

1.

if (a == "david")

a decays to a pointer to the first element of array a.

"david" is a string literal.

With the if Statement, you attempt to compare the address of the array a by the address of the string literal "david". String comparison dies not work that way in C.

Use strcmp() - header string.h to compare strings.

strcmp() returns 0 if the strings are equal. To make the if condition turn true you need to use ! negation operator.

2.

There is a misplaced ; between the if condition and if body. Remove it.

3.

The use of cs50.h is deprecated. If you are not required to use it explicitly, leave your hands off from it.

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

int main (void) {
    char a[20];

    printf("ENTER YOUR NAME FOR READING:\n");

    if (!fgets(a, sizeof a, stdin))
    {
         fputs("Failure at input", stderr);
         // further Error routine.
    }

    a[strcspn(a, "\n")] = 0;

    if (!strcmp(a,"david"))
    {
        printf("...");
    }
}
</code>```

Body:
So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}

Body:
Your code has three issues:

1.

if (a == "david")

a decays to a pointer to the first element of array a.

"david" is a string literal.

With the if Statement, you attempt to compare the address of the array a by the address of the string literal "david". String comparison dies not work that way in C.

Use strcmp() - header string.h to compare strings.

strcmp() returns 0 if the strings are equal. To make the if condition turn true you need to use ! negation operator.

2.

There is a misplaced ; between the if condition and if body. Remove it.

3.

The use of cs50.h is deprecated. If you are not required to use it explicitly, leave your hands off from it.

#include <stdio.h>
#include <string.h>

int main (void) {
    char a[20];

    printf("ENTER YOUR NAME FOR READING:\n");

    if (!fgets(a, sizeof a, stdin))
    {
         fputs("Failure at input", stderr);
         // further Error routine.
    }

    a[strcspn(a, "\n")] = 0;

    if (!strcmp(a,"david"))
    {
        printf("...");
    }
}


问:
How can I make an if else function in custom XPath in the graphical mapping node in IIB?
In the graphical mapping node in IIB (IBM Integration Bus) I need to assign a text value to an element of the response message. I want to do this with the Built-in XPath transforms in the mapping node.

The text value is conditional based on whether the element exists or is empty in the request message.

What is going wrong in below XPath code?

if (fn:exists($BookName) and (fn:nilled( $BookName) = false)) then 'text1' else 'text2'

答:
There's nothing intrinsically wrong with your code, so it would be good to know how it is failing.

There are all sorts of mistakes you might be making, for example in misunderstanding what the exists() and nilled() functions do, but we really can't guess without seeing the symptoms, and a bit more context - e.g. what is $BookName actually bound to?


问:
filtering out values in a multi-dimensional array in php
I have a situation where I have two arrays and I use one array(A) to determine which elements of the second array(B) I need to use. Since I will be combing B multiple times and each time I will not need the previously used elements I have written a function that I call sift_array.

```<code>function sift_array(&$array, $key, $value){
   foreach($array as $element){
      if($element[$key] == $value){$temp[] = $element;}
      else{$temp2[] = $element;}
   }
   $array = $temp2;
   return $temp;
}</code>```

I am curious if there is a faster way to perform this function.

Here is an example of how I use this function.

In my web app users can set up a 'bot' to perform an action so many times while they are away/logged off. I have a program that will run periodically to operate the bots. The bots can not run the same action if it was the last bot to do so.

The bots array has 3 key elements     : account_id, action_id, job_id
The job array has 1 key element      : job_id.

I pass in the bots array then for the $key I pass 'job_id' and for the $value I pass the job id I am working with, say job 1.

```<code>$runTheseBots = sift_array($bots, 'job_id', 1);
executeBots($runTheseBots);</code>```

This will have a faster execution time because all the bots that deal with job 1 are already handled.

```<code>$runTheseBots = sift_array($bots, 'job_id', 2);
executeBots($runTheseBots);</code>```

答:
There are plenty of ways to implement this, but I'll just comment on how you've done it:

```<code>function sift_array(&$array, $key, $value){
   foreach($array as $i => $element){
      if($element[$key] == $value){
        $temp[] = $element;
        unset($array[$i]);
      }
   }
   return $temp;
}
</code>```

Here we are saving memory and time (well, maybe not time... benchmark to see) by not making a copy of $array. Simply delete the element after you move it to the new array.

Again, I don't claim this to be the best way of doing it... just a way to optimize what you've already done.

Body:
I have a situation where I have two arrays and I use one array(A) to determine which elements of the second array(B) I need to use. Since I will be combing B multiple times and each time I will not need the previously used elements I have written a function that I call sift_array.

function sift_array(&$array, $key, $value){
   foreach($array as $element){
      if($element[$key] == $value){$temp[] = $element;}
      else{$temp2[] = $element;}
   }
   $array = $temp2;
   return $temp;
}

I am curious if there is a faster way to perform this function.

Here is an example of how I use this function.

In my web app users can set up a 'bot' to perform an action so many times while they are away/logged off. I have a program that will run periodically to operate the bots. The bots can not run the same action if it was the last bot to do so.

The bots array has 3 key elements     : account_id, action_id, job_id
The job array has 1 key element      : job_id.

I pass in the bots array then for the $key I pass 'job_id' and for the $value I pass the job id I am working with, say job 1.

$runTheseBots = sift_array($bots, 'job_id', 1);
executeBots($runTheseBots);

This will have a faster execution time because all the bots that deal with job 1 are already handled.

$runTheseBots = sift_array($bots, 'job_id', 2);
executeBots($runTheseBots);

Body:
There are plenty of ways to implement this, but I'll just comment on how you've done it:

function sift_array(&$array, $key, $value){
   foreach($array as $i => $element){
      if($element[$key] == $value){
        $temp[] = $element;
        unset($array[$i]);
      }
   }
   return $temp;
}

Here we are saving memory and time (well, maybe not time... benchmark to see) by not making a copy of $array. Simply delete the element after you move it to the new array.

Again, I don't claim this to be the best way of doing it... just a way to optimize what you've already done.


问:
Python: URL images download. The URL contains an accented letter. I'm getting an error
There is a problem that the URLs in the .csv file contain accented letters (á, é, í, etc.). If it has an accented character in it, I get an error.

```<code>import pandas as pd
import urllib.request

def url_to_jpg(i, url, file_path):

    filename = 'image-{}.jpg'.format(i)
    full_path = '{}{}'.format(file_path, filename)
    urllib.request.urlretrieve(url, full_path)

    print('{} saved.'.format(filename))

    return None

FILENAME = 'imgs_urls.csv'
FILE_PATH = 'images/'

urls = pd.read_csv(FILENAME, encoding ='latin1')

for i, url in enumerate(urls.values):
    url_to_jpg(i, url[0], FILE_PATH)
</code>```

Picture of the error:

Can somebody help me?

答:
You cannot use URLs with non-ASCII characters, you need to clean/convert them before.

In your case, you would add the clean_url function below into your loop. This worked with your link in python 3:

urllib.parse.urlsplit splits the URL into the components

urllib.parse.quote will properly escape the Unicode
characters

urllib.parse.urlunsplit will join it back together

.

```<code>import urllib.request
import urllib.parse

def url_to_jpg(url, file_path):
    urllib.request.urlretrieve(url, file_path)
    print('{} saved.'.format(file_path))

def clean_url(url):
    url = urllib.parse.urlsplit(url)
    url = list(url)
    url[2] = urllib.parse.quote(url[2])
    url = urllib.parse.urlunsplit(url)
    return url

url = u'<url_with_non_ascii_char>'

url = clean_url(url)
url_to_jpg(url, "test.jpg")
</code>```

Body:
There is a problem that the URLs in the .csv file contain accented letters (á, é, í, etc.). If it has an accented character in it, I get an error.

import pandas as pd
import urllib.request

def url_to_jpg(i, url, file_path):

    filename = 'image-{}.jpg'.format(i)
    full_path = '{}{}'.format(file_path, filename)
    urllib.request.urlretrieve(url, full_path)

    print('{} saved.'.format(filename))

    return None

FILENAME = 'imgs_urls.csv'
FILE_PATH = 'images/'

urls = pd.read_csv(FILENAME, encoding ='latin1')

for i, url in enumerate(urls.values):
    url_to_jpg(i, url[0], FILE_PATH)

Picture of the error:

Can somebody help me?

Body:
You cannot use URLs with non-ASCII characters, you need to clean/convert them before.

In your case, you would add the clean_url function below into your loop. This worked with your link in python 3:

urllib.parse.urlsplit splits the URL into the components

urllib.parse.quote will properly escape the Unicode
characters

urllib.parse.urlunsplit will join it back together

.

import urllib.request
import urllib.parse

def url_to_jpg(url, file_path):
    urllib.request.urlretrieve(url, file_path)
    print('{} saved.'.format(file_path))

def clean_url(url):
    url = urllib.parse.urlsplit(url)
    url = list(url)
    url[2] = urllib.parse.quote(url[2])
    url = urllib.parse.urlunsplit(url)
    return url

url = u'<url_with_non_ascii_char>'

url = clean_url(url)
url_to_jpg(url, "test.jpg")


问:
R Count and CountDistinct elements of a list
I'm facing a little problem: I've used the Tweeter API and I obtained something like:

```<code>id <- c(1:4)
val <- c(100,150,170,200)
tex <- c("[#price", "#quant]","[#good]","[#good] [#price]")
db <- data.frame(id,val,tex)
</code>```

I would like to count the total number of Hashtags and also the number of the unique hashtags in the simplest way because then I need to put everything inside a reactive database in order to create a dashboard through Shiny.

Thx for your help.

答:
An option with str_extract

```<code>library(stringr)
unique(unlist(str_extract_all(db$tex, "#\\w+")))
#[1] "#price" "#quant" "#good"
</code>```

Or with base R using strsplit

```<code>setdiff(unique(unlist(strsplit(db$tex, "[][ ]+"))), "")
#[1] "#price" "#quant" "#good"
</code>```

Body:
I'm facing a little problem: I've used the Tweeter API and I obtained something like:

id <- c(1:4)
val <- c(100,150,170,200)
tex <- c("[#price", "#quant]","[#good]","[#good] [#price]")
db <- data.frame(id,val,tex)

I would like to count the total number of Hashtags and also the number of the unique hashtags in the simplest way because then I need to put everything inside a reactive database in order to create a dashboard through Shiny.

Thx for your help.

Body:
An option with str_extract

library(stringr)
unique(unlist(str_extract_all(db$tex, "#\\w+")))
#[1] "#price" "#quant" "#good"

Or with base R using strsplit

setdiff(unique(unlist(strsplit(db$tex, "[][ ]+"))), "")
#[1] "#price" "#quant" "#good"


问:
Chrome 83: Change colors of new form styling
With the new Chrome update Chrome is displaying improved default form styling.
According to the post I would say it should be possible to change this form theme to match the color set of a website.

We were going for beautiful, webby, and neutral. We hope that every design system would see a bit of themselves in the new designs and easily imagine how they might be adapted for their own branding.

I have spend the last few hours searching and trying to get rid of the default blue color that has a very bad contrast with rest of my website. Aside from using '-webkit-appearance: none;' and restyling things like checkboxes myself I'm not sure if it's possible.

Does anyone experience this issue as well or have a solution or documentation I'm missing?

答:
My solution to bring back the grey/black checkboxes, targeting only desktop versions of Chrome >= 83.</p>

```<code>if (window.chrome) {
    var ua = navigator.appVersion;
    if (ua.indexOf('Mobile') === -1) {
        var flag = ua.indexOf('Chrome/');
        if (flag !== -1) {
            var version = parseInt(ua.substr(flag + 7, 2));
            if (version >= 83) {
                var chromeStyle       = document.createElement('style');
                chromeStyle.type      = 'text/css';
                chromeStyle.innerText = 'input[type="checkbox"] {-webkit-filter: brightness(0.9);} input[type="checkbox"]:checked {-webkit-filter: grayscale(100%) invert(100%) brightness(1.3);}';
                document.head.appendChild(chromeStyle);
            }
        }
    }
}
</code>```

Body:
My solution to bring back the grey/black checkboxes, targeting only desktop versions of Chrome >= 83.

if (window.chrome) {
    var ua = navigator.appVersion;
    if (ua.indexOf('Mobile') === -1) {
        var flag = ua.indexOf('Chrome/');
        if (flag !== -1) {
            var version = parseInt(ua.substr(flag + 7, 2));
            if (version >= 83) {
                var chromeStyle       = document.createElement('style');
                chromeStyle.type      = 'text/css';
                chromeStyle.innerText = 'input[type="checkbox"] {-webkit-filter: brightness(0.9);} input[type="checkbox"]:checked {-webkit-filter: grayscale(100%) invert(100%) brightness(1.3);}';
                document.head.appendChild(chromeStyle);
            }
        }
    }
}


问:
Arithmetic on a pointer to void error when compile a third party library
I'm trying to compile a third party library, but for some reason I'm getting an error. The library is likely compiled differently. I've read up on the error but I can't seem to figure out what the issue is! :(

```<code>struct sfo_entry {
    char* key;
    size_t size;
    size_t area;
    void* value;
    enum sfo_value_format format;
    struct sfo_entry* next;
    struct sfo_entry* prev;
};

struct sfo {
    struct sfo_entry* entries;
};

bool sfo_load_from_memory(struct sfo* sfo, const void* data, size_t data_size) {
    struct sfo_header* hdr;
    struct sfo_table_entry* entry_table;
    struct sfo_table_entry* entry;

    entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));

    // ...

    return true;
}
</code>```

The error is as follows:

```<code> sfo.cpp:150:47: error: arithmetic on a pointer to void
         entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));
                                                 ~~~~ ^
</code>```

答:
The error is that arithmetic is not allowed on pointers of type void *, nor on pointers to any other incomplete type.  This is consistent with the fact that pointer arithmetic is defined in terms of the size of the pointed-to type, which is unknown for incomplete types.

Some compilers implement an extension that would apply here, treating pointer arithmetic on void * as if the pointed-to type had size 1.  Often, this is exactly what the author of the code intended, as appears to be the case in your code.  In that event, you could consider fixing this flaw in the code by changing the affected line to

```<code>    entry_table = (struct sfo_table_entry*)((char *)data + sizeof(*hdr));
</code>```

Body:
I'm trying to compile a third party library, but for some reason I'm getting an error. The library is likely compiled differently. I've read up on the error but I can't seem to figure out what the issue is! :(

struct sfo_entry {
    char* key;
    size_t size;
    size_t area;
    void* value;
    enum sfo_value_format format;
    struct sfo_entry* next;
    struct sfo_entry* prev;
};

struct sfo {
    struct sfo_entry* entries;
};

bool sfo_load_from_memory(struct sfo* sfo, const void* data, size_t data_size) {
    struct sfo_header* hdr;
    struct sfo_table_entry* entry_table;
    struct sfo_table_entry* entry;

    entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));

    // ...

    return true;
}

The error is as follows:

 sfo.cpp:150:47: error: arithmetic on a pointer to void
         entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));
                                                 ~~~~ ^

Body:
The error is that arithmetic is not allowed on pointers of type void *, nor on pointers to any other incomplete type.  This is consistent with the fact that pointer arithmetic is defined in terms of the size of the pointed-to type, which is unknown for incomplete types.

Some compilers implement an extension that would apply here, treating pointer arithmetic on void * as if the pointed-to type had size 1.  Often, this is exactly what the author of the code intended, as appears to be the case in your code.  In that event, you could consider fixing this flaw in the code by changing the affected line to

    entry_table = (struct sfo_table_entry*)((char *)data + sizeof(*hdr));


问:
How to stop insert in a transaction in SQL Server?
Create query using BEGIN TRAN statement to insert two rows within BEGIN TRY if transaction count is greater than 1, catch error and rollback the transaction, otherwise print “transaction committed” (this is my teacher question the idea is that it should not insert more than 1 row by using the @@trancount is greater than one the transaction is rolled back)

This is the code that I wrote

```<code>BEGIN TRY
    BEGIN TRAN;

        INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
        PRINT @@TRANCOUNT

        BEGIN TRAN
            INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
            PRINT @@TRANCOUNT

            IF @@TRANCOUNT > 1
                PRINT 'Rollback the transaction...';
            ELSE
                PRINT 'transaction succeeded';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH;
</code>```

It keeps inserting the two rows even though the trans count is greater than 1

How can I fix this?!!

This is the result

答:
I suppose you're looking for using @@ROWCOUNT instead of @@TRANCOUNT

```<code>BEGIN TRY
  BEGIN TRAN MyTran;
    INSERT INTO Countries(Name) VALUES
    ('Italy'),
    ('Jorden');
    IF @@ROWCOUNT > 1
      ROLLBACK TRAN MyTran;
        ELSE
          COMMIT TRAN MyTran;
END TRY
BEGIN CATCH
  RAISERROR ('Error Message',
             16, -- Severity.
             1 -- State.
             );
  ROLLBACK TRAN MyTran;
END CATCH;
</code>```

If you really want to use nested transactions and use @@TRANCOUNT

```<code>BEGIN TRY
  BEGIN TRAN MyTran;
    INSERT INTO Countries(Name) VALUES ('Italy');
      BEGIN TRAN MySecTran;
        INSERT INTO Countries(Name) VALUES ('Jorden');
        IF @@TRANCOUNT > 1
          ROLLBACK TRAN;
            ELSE
              COMMIT TRAN;
END TRY
BEGIN CATCH
    RAISERROR ('Error Message',
               16, -- Severity.
               1 -- State.
               );
    ROLLBACK TRAN;
END CATCH;
</code>```

Here is a db<>fiddle where you can un-comment one of the two and see how it's working.

Update:

i checked it again. it did not insert any row in the table. but it should insert the first one

Then you need to save the tran as

```<code>BEGIN TRY
  BEGIN TRAN MyTran;
    INSERT INTO Countries(Name) VALUES ('Italy');
    SAVE TRAN MySaveTran;
  BEGIN TRAN MySecTran;
    INSERT INTO Countries(Name) VALUES ('Jorden');
    IF @@TRANCOUNT > 1
      ROLLBACK TRAN MySaveTran;
  COMMIT TRAN;
END TRY
BEGIN CATCH
  RAISERROR ('Error Message',
             16, -- Severity.
             1 -- State.
             );
  ROLLBACK TRAN;
END CATCH;
</code>```

Body:
Create query using BEGIN TRAN statement to insert two rows within BEGIN TRY if transaction count is greater than 1, catch error and rollback the transaction, otherwise print “transaction committed” (this is my teacher question the idea is that it should not insert more than 1 row by using the @@trancount is greater than one the transaction is rolled back)

This is the code that I wrote

BEGIN TRY
    BEGIN TRAN;

        INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
        PRINT @@TRANCOUNT

        BEGIN TRAN
            INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
            PRINT @@TRANCOUNT

            IF @@TRANCOUNT > 1
                PRINT 'Rollback the transaction...';
            ELSE
                PRINT 'transaction succeeded';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH;

It keeps inserting the two rows even though the trans count is greater than 1

How can I fix this?!!

This is the result

Body:
I suppose you're looking for using @@ROWCOUNT instead of @@TRANCOUNT

BEGIN TRY
  BEGIN TRAN MyTran;
    INSERT INTO Countries(Name) VALUES
    ('Italy'),
    ('Jorden');
    IF @@ROWCOUNT > 1
      ROLLBACK TRAN MyTran;
        ELSE
          COMMIT TRAN MyTran;
END TRY
BEGIN CATCH
  RAISERROR ('Error Message',
             16, -- Severity.
             1 -- State.
             );
  ROLLBACK TRAN MyTran;
END CATCH;

If you really want to use nested transactions and use @@TRANCOUNT

BEGIN TRY
  BEGIN TRAN MyTran;
    INSERT INTO Countries(Name) VALUES ('Italy');
      BEGIN TRAN MySecTran;
        INSERT INTO Countries(Name) VALUES ('Jorden');
        IF @@TRANCOUNT > 1
          ROLLBACK TRAN;
            ELSE
              COMMIT TRAN;
END TRY
BEGIN CATCH
    RAISERROR ('Error Message',
               16, -- Severity.
               1 -- State.
               );
    ROLLBACK TRAN;
END CATCH;

Here is a db<>fiddle where you can un-comment one of the two and see how it's working.

Update:

i checked it again. it did not insert any row in the table. but it should insert the first one

Then you need to save the tran as

BEGIN TRY
  BEGIN TRAN MyTran;
    INSERT INTO Countries(Name) VALUES ('Italy');
    SAVE TRAN MySaveTran;
  BEGIN TRAN MySecTran;
    INSERT INTO Countries(Name) VALUES ('Jorden');
    IF @@TRANCOUNT > 1
      ROLLBACK TRAN MySaveTran;
  COMMIT TRAN;
END TRY
BEGIN CATCH
  RAISERROR ('Error Message',
             16, -- Severity.
             1 -- State.
             );
  ROLLBACK TRAN;
END CATCH;


问:
Pass Params from screen to Header component react navigation
My problem is that I can't able to pass the function as a param to the header component in react-navigation v5.

From the given code below in filtersscreen.js, I want to pass savefilters to headerRight which is in navigation.js.

I can view the save param in log-1. But Why can't I able to get the save param in log-2 which is FilterNavigator.

I'm receiving warning when I use setParams() - "Non-serializable values were found in the navigation state, which can break usage such as persisting and restoring state. This might happen if you passed non-serializable values such as function, class instances etc. in params. If you need to use components with callbacks in your options, you can use 'navigation.setOptions' instead. See https://reactnavigation.org/docs/troubleshooting.html#i-get-the-warning-we-found-non-serializable-values-in-the-navigation-state for more details."

When I use navigation.setOptions({ save: savefilters }) I can't find the save in route.params.save

I new to react-native, I request you to help me out of this problem.

I read the docs React Navigation v5.

I logged the output below.
Thank You.

navigation.js

```<code>const FiltersNavigator = props => {
  return (
    <screen.Navigator initialRouteName="Filters">
      <screen.Screen
        options={{
          title: 'Filters',
          headerRight: () => (
            <View>
              <TouchableNativeFeedback>
                <MaterialCommunityIcons
                  name="content-save"
                  color="white"
                  size={28}
                  style={{padding: 15}}
                  onPress={() => console.log(props)} //log-2 attached below
                />
              </TouchableNativeFeedback>
            </View>
          ),
        }}
        name="Filters Meals"
        component={FiltersScreen}
      />
    </screen.Navigator>
  );
};
</code>```

FiltersScreen.js

```<code>const FilterSwitch = props => {
  return (
    <View style={styles.filterContainer}>
      <Text>{props.label}</Text>
      <Switch
        trackColor={{true: Colors.primaryColor}}
        thumbColor={Colors.primaryColor}
        value={props.state}
        onValueChange={props.onChange}
      />
    </View>
  );
};

const FiltersScreen = props => {
  const {navigation} = props;
  const [isGlutenFree, setIsGlutenFree] = useState(false);
  const [isLactoseFree, setIsLactoseFree] = useState(false);
  const [isVegan, setIsVegan] = useState(false);
  const [isVegetarian, setIsVegetarian] = useState(false);

  const saveFilters = useCallback(() => {
    const appliedFilters = {
      glutenFree: isGlutenFree,
      lactoseFree: isLactoseFree,
      vegan: isVegan,
      vegetarian: isVegetarian,
    };

  }, [isGlutenFree, isLactoseFree, isVegan, isVegetarian]);

  useEffect(() => {
    navigation.setParams({
      save: saveFilters,
    });
    console.log('useEffect : ', props); //log-1 attached below
  }, [saveFilters]);

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Available Filters / Restrictions</Text>
      <FilterSwitch
        label="Gluten-Free"
        state={isGlutenFree}
        onChange={newValue => setIsGlutenFree(newValue)}
      />
      <FilterSwitch
        label="Lactose-Free"
        state={isLactoseFree}
        onChange={newValue => setIsLactoseFree(newValue)}
      />
      <FilterSwitch
        label="Vegan"
        state={isVegan}
        onChange={newValue => setIsVegan(newValue)}
      />
      <FilterSwitch
        label="Vegetarian"
        state={isVegetarian}
        onChange={newValue => setIsVegetarian(newValue)}
      />
    </View>
  );
};
</code>```

log-1

```<code>{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "pop": [Function anonymous
        ],
        "popToTop": [Function anonymous
        ],
        "push": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "replace": [Function anonymous
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters Meals-7XbV4LEyLo",
        "name": "Filters Meals",
        "params": {
            "save": [Function anonymous
            ]
        }
    }
}
</code>```

log-2

```<code>{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters-6CuzlMQv2w",
        "name": "Filters",
        "params": undefined,
        "state": {
            "index": 0,
            "key": "stack-7UXVGRjyv-",
            "routeNames": [Array
            ],
            "routes": [Array
            ],
            "stale": false,
            "type": "stack"
        }
    }
}
</code>```

答:
In the second line of the FilterNavigator, put

```<code>const { save } = props.route.params;
</code>```

then further down

```<code>onPress = {save}
</code>```

Body:
My problem is that I can't able to pass the function as a param to the header component in react-navigation v5.

From the given code below in filtersscreen.js, I want to pass savefilters to headerRight which is in navigation.js.

I can view the save param in log-1. But Why can't I able to get the save param in log-2 which is FilterNavigator.

I'm receiving warning when I use setParams() - "Non-serializable values were found in the navigation state, which can break usage such as persisting and restoring state. This might happen if you passed non-serializable values such as function, class instances etc. in params. If you need to use components with callbacks in your options, you can use 'navigation.setOptions' instead. See https://reactnavigation.org/docs/troubleshooting.html#i-get-the-warning-we-found-non-serializable-values-in-the-navigation-state for more details."

When I use navigation.setOptions({ save: savefilters }) I can't find the save in route.params.save

I new to react-native, I request you to help me out of this problem.

I read the docs React Navigation v5.

I logged the output below.
Thank You.

navigation.js

const FiltersNavigator = props => {
  return (
    <screen.Navigator initialRouteName="Filters">
      <screen.Screen
        options={{
          title: 'Filters',
          headerRight: () => (
            <View>
              <TouchableNativeFeedback>
                <MaterialCommunityIcons
                  name="content-save"
                  color="white"
                  size={28}
                  style={{padding: 15}}
                  onPress={() => console.log(props)} //log-2 attached below
                />
              </TouchableNativeFeedback>
            </View>
          ),
        }}
        name="Filters Meals"
        component={FiltersScreen}
      />
    </screen.Navigator>
  );
};

FiltersScreen.js

const FilterSwitch = props => {
  return (
    <View style={styles.filterContainer}>
      <Text>{props.label}</Text>
      <Switch
        trackColor={{true: Colors.primaryColor}}
        thumbColor={Colors.primaryColor}
        value={props.state}
        onValueChange={props.onChange}
      />
    </View>
  );
};

const FiltersScreen = props => {
  const {navigation} = props;
  const [isGlutenFree, setIsGlutenFree] = useState(false);
  const [isLactoseFree, setIsLactoseFree] = useState(false);
  const [isVegan, setIsVegan] = useState(false);
  const [isVegetarian, setIsVegetarian] = useState(false);

  const saveFilters = useCallback(() => {
    const appliedFilters = {
      glutenFree: isGlutenFree,
      lactoseFree: isLactoseFree,
      vegan: isVegan,
      vegetarian: isVegetarian,
    };

  }, [isGlutenFree, isLactoseFree, isVegan, isVegetarian]);

  useEffect(() => {
    navigation.setParams({
      save: saveFilters,
    });
    console.log('useEffect : ', props); //log-1 attached below
  }, [saveFilters]);

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Available Filters / Restrictions</Text>
      <FilterSwitch
        label="Gluten-Free"
        state={isGlutenFree}
        onChange={newValue => setIsGlutenFree(newValue)}
      />
      <FilterSwitch
        label="Lactose-Free"
        state={isLactoseFree}
        onChange={newValue => setIsLactoseFree(newValue)}
      />
      <FilterSwitch
        label="Vegan"
        state={isVegan}
        onChange={newValue => setIsVegan(newValue)}
      />
      <FilterSwitch
        label="Vegetarian"
        state={isVegetarian}
        onChange={newValue => setIsVegetarian(newValue)}
      />
    </View>
  );
};

log-1

{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "pop": [Function anonymous
        ],
        "popToTop": [Function anonymous
        ],
        "push": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "replace": [Function anonymous
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters Meals-7XbV4LEyLo",
        "name": "Filters Meals",
        "params": {
            "save": [Function anonymous
            ]
        }
    }
}

log-2

{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters-6CuzlMQv2w",
        "name": "Filters",
        "params": undefined,
        "state": {
            "index": 0,
            "key": "stack-7UXVGRjyv-",
            "routeNames": [Array
            ],
            "routes": [Array
            ],
            "stale": false,
            "type": "stack"
        }
    }
}

Body:
In the second line of the FilterNavigator, put

const { save } = props.route.params;

then further down

onPress = {save}


问:
Deploying Angular App on minikube and expose via port
I have issue with deploying angular app on minikube. I am not able to expose the running angular container on browser.

Below are my setup files.

Minikube start command

```<code>$ minikube start --driver=docker
</code>```

Dockerfile

```<code>FROM node:10-alpine AS node
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build-prod
FROM nginx:alpine
COPY --from=node /app/dist/shopping-wepapp /usr/share/nginx/html
</code>```

Deployment configuration file

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-cart
spec:
  replicas: 2
  selector:
    matchLabels:
      app: shop-cart
  template:
    metadata:
      labels:
        app: shop-cart
        version: v1
    spec:
      containers:
        - name: shop-cart
          image:  kavin1995/development:shop-cart-app-07-04-2020-14-00
          imagePullPolicy: Always
          ports:
            - containerPort: 80
</code>```

Service configuration file

```<code>apiVersion: v1
kind: Service
metadata:
  name: shop-cart-service
spec:
  selector:
    app: shop-cart
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
    nodePort: 31000
  type: NodePort
</code>```

Port exposing command

```<code>$ minikube service shop-cart-service --url
</code>```

答:
The problem seems to be the use of the docker driver: the minikube IP is a container IP and cannot be accessed outside of the docker host.

The only way to expose the nodePort outside would be to publish the port on the running minikube container (which only expose this: 127.0.0.1:32771->22/tcp, 127.0.0.1:32770->2376/tcp, 127.0.0.1:32769->5000/tcp, 127.0.0.1:32768->8443/tcp)

One way to do this would be (even if ugly) :

CONTAINER_IP=`minikube ip`
SERVICE_NAME=shop-cart-service
SERVICE_NODE_PORT=`kubectl get service ${SERVICE_NAME} --output jsonpath='{.spec.ports[0].nodePort}'`

iptables -t nat -A DOCKER -p tcp --dport ${SERVICE_NODE_PORT} -j DNAT --to-destination ${CONTAINER_IP}:${SERVICE_NODE_PORT}
iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp --source ${CONTAINER_IP} --destination ${CONTAINER_IP} --dport ${SERVICE_NODE_PORT}
iptables -A DOCKER -j ACCEPT -p tcp --destination ${CONTAINER_IP} --dport ${SERVICE_NODE_PORT}
```

Body:
I have issue with deploying angular app on minikube. I am not able to expose the running angular container on browser.

Below are my setup files.

Minikube start command

$ minikube start --driver=docker

Dockerfile

FROM node:10-alpine AS node
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build-prod
FROM nginx:alpine
COPY --from=node /app/dist/shopping-wepapp /usr/share/nginx/html

Deployment configuration file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-cart
spec:
  replicas: 2
  selector:
    matchLabels:
      app: shop-cart
  template:
    metadata:
      labels:
        app: shop-cart
        version: v1
    spec:
      containers:
        - name: shop-cart
          image:  kavin1995/development:shop-cart-app-07-04-2020-14-00
          imagePullPolicy: Always
          ports:
            - containerPort: 80

Service configuration file

apiVersion: v1
kind: Service
metadata:
  name: shop-cart-service
spec:
  selector:
    app: shop-cart
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
    nodePort: 31000
  type: NodePort

Port exposing command

$ minikube service shop-cart-service --url


问:
Makefile:252: recipe for target 'install' failed
I'm trying to install pwlib on my asterisk/ubuntu 16.04 Server, but when I try to run make install I get the following error message:

```<code>( for dir in /usr/local/lib \
             /usr/local/bin \
             /usr/local/include/ptlib \
                     /usr/local/include/ptlib/unix/ptlib \
                     /usr/local/include/ptclib \
                     /usr/local/share/pwlib/make ; \
        do mkdir -p $dir ; chmod 755 $dir ; \
done )
/usr/bin/install -c -m 444 lib/libpt_linux_x86_64_r.so.1.12.0 /usr/local/lib
/usr/bin/install: cannot stat 'lib/libpt_linux_x86_64_r.so.1.12.0': No such file or directory
Makefile:252: recipe for target 'install' failed
make: *** [install] Error 1
</code>```

Thank you in advance for your help!

Greetings

Alessio

答:
Aware this is an old post but for anyone with a similar issue:

Sometimes running

```<code>make install
</code>```

will throw this error while

```<code>sudo make install
</code>```

will work

Body:
I'm trying to install pwlib on my asterisk/ubuntu 16.04 Server, but when I try to run make install I get the following error message:

( for dir in /usr/local/lib \
             /usr/local/bin \
             /usr/local/include/ptlib \
                     /usr/local/include/ptlib/unix/ptlib \
                     /usr/local/include/ptclib \
                     /usr/local/share/pwlib/make ; \
        do mkdir -p $dir ; chmod 755 $dir ; \
done )
/usr/bin/install -c -m 444 lib/libpt_linux_x86_64_r.so.1.12.0 /usr/local/lib
/usr/bin/install: cannot stat 'lib/libpt_linux_x86_64_r.so.1.12.0': No such file or directory
Makefile:252: recipe for target 'install' failed
make: *** [install] Error 1

Thank you in advance for your help!

Greetings

Alessio

Body:
Aware this is an old post but for anyone with a similar issue:

Sometimes running

make install

will throw this error while

sudo make install

will work


问:
Can you integrate SSIS project with website?
According to my project requirements, I need to develop a few pages on the company website where the user would upload an excel sheet to transfer the data to MS SQL Server. I am getting started with SSIS but I want to know how to make this part of a web page.</p>

答: You could schedule the SSIS in a sql job to run every few minutes or so.  Use a for each loop so that it doesn't actually do anything if there is not file.</p>


问:
Django REST Framework Authentication keyword
I'm trying to rename the Rest_framework TokenAuthentication keyword from "Token" to "Bearer" as suggested in the Documentation I have subclassed the TokenAuthentication class like this:

in module: user/authentication.py

```<code>from rest_framework import authentication

class TokenAuthentication(authentication.TokenAuthentication):
    """
    Simple token based authentication.
    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string "Token ".  For example:
    Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
    """

    keyword = 'Bearer'
</code>```

in module app/settings.py

```<code> REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
         'user.authentication.TokenAuthentication',
     ),
 }
</code>```

It is still sending me a 401 Unauthorized when im using 'Authorization: Bearer ...token...' but not with 'Authorization: Token ...token...'

What am I doing wrong ?

答: You are missing one last step. Import your TokenAuthentication class that contains the new keyword in your View class instead of the default TokenAuthentication class.

Body:
I'm trying to rename the Rest_framework TokenAuthentication keyword from "Token" to "Bearer" as suggested in the Documentation I have subclassed the TokenAuthentication class like this:

in module: user/authentication.py

from rest_framework import authentication

class TokenAuthentication(authentication.TokenAuthentication):
    """
    Simple token based authentication.
    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string "Token ".  For example:
    Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
    """

    keyword = 'Bearer'

in module app/settings.py

 REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
         'user.authentication.TokenAuthentication',
     ),
 }

It is still sending me a 401 Unauthorized when im using 'Authorization: Bearer ...token...' but not with 'Authorization: Token ...token...'

What am I doing wrong ?


问:
Spring AOP with prototype beans
I am using Spring AOP to fire metrics in our application. I have created an annotation @CaptureMetrics  which has an @around  advice associated with it. The advice is invoked fine from all the methods tagged with @CaptureMetrics except for a case when a method is invoked on a  prototype bean.

The annotation has @Target({ElementType.TYPE, ElementType.METHOD})

PointCut expression:

```<code>@Around(value = "execution(* *.*(..)) && @annotation(captureMetrics)",
      argNames = "joinPoint,captureMetrics")
</code>```

Prototype bean creation

```<code>@Bean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public DummyService getDummyServicePrototypeBean(int a, String b) {
    return new DummyService(a, b);
  }
</code>```

DummyService has a method called dummyMethod(String dummyString)

```<code>    @CaptureMetrics(type = MetricType.SOME_TYPE, name = "XYZ")
          public Response dummyMethod(id) throws Exception {
           // Do some work here
        }
</code>```

When dummyService.dummyMethod("123") is invoked from some other service, the @Around advice is not called.

Config class

```<code>@Configuration
public class DummyServiceConfig {

  @Bean
  public DummyServiceRegistry dummyServiceRegistry(
      @Value("${timeout}") Integer timeout,
      @Value("${dummy.secrets.path}") Resource dummySecretsPath) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, String> transactionSourceToTokens = mapper.readValue(
        dummySecretsPath.getFile(), new TypeReference<Map<String, String>>() {
        });
    DummyServiceRegistry registry = new DummyServiceRegistry();
    transactionSourceToTokens.forEach((transactionSource, token) ->
        registry.register(transactionSource,
            getDummyServicePrototypeBean(timeout, token)));

    return registry;
  }

  @Bean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public DummyService getDummyServicePrototypeBean(int a, String b) {
    return new DummyService(a, b);
  }

}
</code>```

Singleton Registry class

```<code>public class DummyServiceRegistry {
  private final Map<String, DummyService> transactionSourceToService = new HashMap<>();

  public void register(String transactionSource, DummyService dummyService) {
    this.transactionSourceToService.put(transactionSource, dummyService);
  }

  public Optional<DummyService> lookup(String transactionSource) {
    return Optional.ofNullable(transactionSourceToService.get(transactionSource));
  }
}
</code>```

Any advice on this please?

Note:

The prototype Dummy service is used to call a third party client. It is a prototype bean as it has a state that varies based on whose behalf it is going to call the third party.

A singleton registry bean during initialization builds a map of {source_of_request, dummyService_prototype}. To get the dummyService prototype it calls getDummyServicePrototypeBean()

答:
The configuration, registry and prototype dummy bean were correct.

I was testing the flow using an existing integration test and there instead of supplying a prototype Bean, new objects of DummyService were instantiated using the new keyword. It wasn't a spring managed bean.

Spring AOP works only with Spring managed beans.

Title: Spring AOP with prototype beans

Body:
I am using Spring AOP to fire metrics in our application. I have created an annotation @CaptureMetrics  which has an @around  advice associated with it. The advice is invoked fine from all the methods tagged with @CaptureMetrics except for a case when a method is invoked on a  prototype bean.

The annotation has @Target({ElementType.TYPE, ElementType.METHOD})

PointCut expression:

@Around(value = "execution(* *.*(..)) && @annotation(captureMetrics)",
      argNames = "joinPoint,captureMetrics")

Prototype bean creation

@Bean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public DummyService getDummyServicePrototypeBean(int a, String b) {
    return new DummyService(a, b);
  }

DummyService has a method called dummyMethod(String dummyString)

    @CaptureMetrics(type = MetricType.SOME_TYPE, name = "XYZ")
          public Response dummyMethod(id) throws Exception {
           // Do some work here
        }

When dummyService.dummyMethod("123") is invoked from some other service, the @Around advice is not called.

Config class

@Configuration
public class DummyServiceConfig {

  @Bean
  public DummyServiceRegistry dummyServiceRegistry(
      @Value("${timeout}") Integer timeout,
      @Value("${dummy.secrets.path}") Resource dummySecretsPath) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, String> transactionSourceToTokens = mapper.readValue(
        dummySecretsPath.getFile(), new TypeReference<Map<String, String>>() {
        });
    DummyServiceRegistry registry = new DummyServiceRegistry();
    transactionSourceToTokens.forEach((transactionSource, token) ->
        registry.register(transactionSource,
            getDummyServicePrototypeBean(timeout, token)));

    return registry;
  }

  @Bean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public DummyService getDummyServicePrototypeBean(int a, String b) {
    return new DummyService(a, b);
  }

}

Singleton Registry class

public class DummyServiceRegistry {
  private final Map<String, DummyService> transactionSourceToService = new HashMap<>();

  public void register(String transactionSource, DummyService dummyService) {
    this.transactionSourceToService.put(transactionSource, dummyService);
  }

  public Optional<DummyService> lookup(String transactionSource) {
    return Optional.ofNullable(transactionSourceToService.get(transactionSource));
  }
}

Any advice on this please?

Note:

The prototype Dummy service is used to call a third party client. It is a prototype bean as it has a state that varies based on whose behalf it is going to call the third party.

A singleton registry bean during initialization builds a map of {source_of_request, dummyService_prototype}. To get the dummyService prototype it calls getDummyServicePrototypeBean()


问:
Why is Power BI creating null values? How can I prevent Power BI to add null values below my data?
I have an excel file which I regularly update in Power BI.

I added an additional line, which did not cause any issues to my operations, however, Power BI also added three "null" lines afterwards.

I do not understand why.

I thus created a table, because I thought that I would prevent this.

But I still have "null" rows appended to my lines.

The only remedy that I found is to filter rows on a column (Lapin) which as no null (and which should never in future), in the following way:

```<code> #"Filtered Rows" = Table.SelectRows(#"Added Custom", each ([Lapin] = "Snip"))
in
    #"Filtered Rows"
</code>```

This is a really bad solution however, and I wish to address the root issue.

答:
On importing from Excel, you can get dummy rows that are due to formatting, hidden formulas, rows that are holding over something in the cell reference in the background. Its not just Power BI, this happens on importing into SQL Server tables, Pandas, and on exporting the Excel to csv etc. The best option is to us the remove rows function in the Power Query

Select Remove Rows > Remove Blank Rows

Body:
I have an excel file which I regularly update in Power BI.

I added an additional line, which did not cause any issues to my operations, however, Power BI also added three "null" lines afterwards.

I do not understand why.

I thus created a table, because I thought that I would prevent this.

But I still have "null" rows appended to my lines.

The only remedy that I found is to filter rows on a column (Lapin) which as no null (and which should never in future), in the following way:

 #"Filtered Rows" = Table.SelectRows(#"Added Custom", each ([Lapin] = "Snip"))
in
    #"Filtered Rows"

This is a really bad solution however, and I wish to address the root issue.


问:
Finding authorization framework to be used on a ASP.NET MVC project
I have a asp.net mvc project and persistent is handled by repositories . Form authentication is used. Now I need implement authorization . For example , I need to ensure a manager user can only open his/her taskes and assign workers to the taskes.  A worker will only see taskes that have been assigned to him/her.  A super-moderator can edit everything.
Is there any ready to use framework that allow me to define permissions ?

I am in the process of evaluating Ayende Rhino Security . Where can I get more examples codes ? What is your opinion on Rhino Security ?

My project use Linq to SQL and has not made use of NHibernate. Can Rhino Security works without NHibernate ?

答:
Check out this one also. It is easy to use.

http://code.google.com/p/saf-framework/

ContentLicense: CC BY-SA 2.5


问:
Is it possible for async method to ever return null in C#?
Digging through some old code, I have noticed a call to an asyncmethod and then a check for the task being returned for null.

```<code>async Task<Something> DoSomeStuffAsync()
{
    //...
    return null; //not the actual return, but I guess it doesn't matter
}

var result = DoSomeStuffAsync(); //without await
if(result == null)
{
    //does this part makes any sense
}
</code>```

From my understanding of the async keyword, this scenario will never be possible because the result of an async method will always be wrapped in a Task but just to check, am I missing something?

Is there any case when an async method will return null in C#?

答:
According to MSDN article async methods can have the following return types:

Task, for an async method that returns a value.

Task, for an async method that performs an operation but returns no value. void, for an event handler.

Starting with C# 7.0, any type that has an accessible GetAwaiter method. The object returned by the GetAwaiter method must implement
  the System.Runtime.CompilerServices.ICriticalNotifyCompletion
  interface.

Starting with C# 8.0, IAsyncEnumerable, for an async method that returns an async stream.

So Task represents the execution of the asynchronous method and it should never be null,  because Task represents the ongoing process for the caller with a commitment to produce an actual value when the work is complete.

Body:
Digging through some old code, I have noticed a call to an asyncmethod and then a check for the task being returned for null.

async Task<Something> DoSomeStuffAsync()
{
    //...
    return null; //not the actual return, but I guess it doesn't matter
}

var result = DoSomeStuffAsync(); //without await
if(result == null)
{
    //does this part makes any sense
}

From my understanding of the async keyword, this scenario will never be possible because the result of an async method will always be wrapped in a Task but just to check, am I missing something?

Is there any case when an async method will return null in C#?


问:
How to display integers with decimals, in .csv file generated with Spreadsheet (), php?
Currently I generate the .csv with this function, basically I just pass it an array for the rows to create in the .csv file

```<code>public function make_csv_file($data)
    {
        $spreadsheet = new Spreadsheet();

        //create csv file
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->fromArray($data, null, 'A1');

        $writer = new Csv($spreadsheet);

        $writer->setDelimiter(',');
        $writer->setEnclosure('');
        $writer->setLineEnding("\r\n");
        $writer->setSheetIndex(0);

        header('Content-Type: application/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="report.csv"');

        return $writer;
    }
</code>```

As you will see the quantity 113033, I need to show it as 113033.00 and 555.13 if it is ok like this. The detail is that in the arrangement that happened to it if it goes as 113033.00 but the library passes it to 113033

I tried:

```<code>  $sheet->getStyle('M1')
    ->getNumberFormat()
    ->setFormatCode(NumberFormat::FORMAT_NUMBER_00);
</code>```

But it's not working

答: CSV files don't have formatting, that is up to the program that read them to interpret things as they wish. If you want to format a number in a certain way, you have to store the value as a string which you probably don't want to do. The alternative is to use a file format like Excel which does support formatting.</p>

Body:
Currently I generate the .csv with this function, basically I just pass it an array for the rows to create in the .csv file

public function make_csv_file($data)
    {
        $spreadsheet = new Spreadsheet();

        //create csv file
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->fromArray($data, null, 'A1');

        $writer = new Csv($spreadsheet);

        $writer->setDelimiter(',');
        $writer->setEnclosure('');
        $writer->setLineEnding("\r\n");
        $writer->setSheetIndex(0);

        header('Content-Type: application/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="report.csv"');

        return $writer;
    }

As you will see the quantity 113033, I need to show it as 113033.00 and 555.13 if it is ok like this. The detail is that in the arrangement that happened to it if it goes as 113033.00 but the library passes it to 113033

I tried:

  $sheet->getStyle('M1')
    ->getNumberFormat()
    ->setFormatCode(NumberFormat::FORMAT_NUMBER_00);

But it's not working


问:
Make box responsive in CSS
I am trying to make the box responsive to scale with the mobile but it turns out it is very small when I resize the window.

Here is the HTML code:

```<code>            <div class="box">
                <h1>Health Status</h1>

                    <input type="text" id="check_infected" name="infected_check" placeholder="Infected by Corona? (Yes/No)">

                    <input type="submit" onclick="UpdateHealth();" value="Update">

                <div class="bottom-text">
                    We ensure to secure your health as well as the public health
                </div>
</code>```

Here is the CSS code:

```<code>.box{
    width: 30%;
    padding-top: 30px;
    padding-bottom: 30px;
    padding-left: 100px;
    padding-right: 100px;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: #ffffff;
    text-align: center;
}

@media only screen and (min-width: 375px) and (max-width: 812px) {
    .box{
        padding-top: 60px;
        padding-bottom: 60px;
    }

  }
</code>```

This is the image when it is not resized:

It turns out very small when it is resized:

How can I make the box scale with the screen or at least make the responsive box easier to see?

答: Short answer: your image width is 30% in your CSS code. When your screen is 1000px the image is normal with 300px but when you use a mobile phone with 320px screen the image is only 96px.</p>

Title: Make box responsive in CSS

Body:
I am trying to make the box responsive to scale with the mobile but it turns out it is very small when I resize the window.

Here is the HTML code:

Health Status

                    <input type="text" id="check_infected" name="infected_check" placeholder="Infected by Corona? (Yes/No)">

                    <input type="submit" onclick="UpdateHealth();" value="Update">

                    We ensure to secure your health as well as the public health

Here is the CSS code:

.box{
    width: 30%;
    padding-top: 30px;
    padding-bottom: 30px;
    padding-left: 100px;
    padding-right: 100px;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: #ffffff;
    text-align: center;
}

@media only screen and (min-width: 375px) and (max-width: 812px) {
    .box{
        padding-top: 60px;
        padding-bottom: 60px;
    }

  }

This is the image when it is not resized:

It turns out very small when it is resized:

How can I make the box scale with the screen or at least make the responsive box easier to see?