qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
3,225,907 | Is there an example for $\sum a\_nx^n$ with radius $R>0$ such that $a\_n \neq 0$ for some $n$ ($a\_n$ is not always $0$) but for all $x \in (-R,R)$ we have $\sum a\_nx^n=0$ | 2019/05/14 | [
"https://math.stackexchange.com/questions/3225907",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/547001/"
] | Since the power series $g$ is convergent in the radius, it is infinitely times differentiable there. Since it is uniformly 0 there, it must have each of its derivatives be 0. Therefore, the constant term of $\frac{d^n}{dx^n}g$ must be 0 for all $n$. This implies that $a\_n=0$ for all $n$. | Hint:
Differentiate the power series $n$ times to find $a\_n$. |
3,225,907 | Is there an example for $\sum a\_nx^n$ with radius $R>0$ such that $a\_n \neq 0$ for some $n$ ($a\_n$ is not always $0$) but for all $x \in (-R,R)$ we have $\sum a\_nx^n=0$ | 2019/05/14 | [
"https://math.stackexchange.com/questions/3225907",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/547001/"
] | No, this is not possible. The series converges uniformly on $(-R\_0, R\_0)$ for any $R\_0 < R$, so the coefficient $a\_n$ gives the $n$th derivative of the function $f(x)=\sum a\_nx^n$ defined by the power series at $x=0$. Therefore, if one of the coefficients $a\_n$ is nonzero then $f^{(n)}(0) = a\_n\neq 0$, so $f$ is nonconstant on any sufficiently small neighborhood of 0. | Hint:
Differentiate the power series $n$ times to find $a\_n$. |
44,988,957 | I am using geom\_smooth and it gives me default legend line color blue that I cannot use in the plot. Is there a way of changing the default color for geom\_smooth legend line?
for example, I wand to change the legend colour to black for line type in the following plot
```
library(reshape2)
library(ggplot2)
d1<-melt(mtcars,id=c("mpg","cyl"))
p<-ggplot(d1,aes(x=mpg,y=value,factor=variable,color=cyl))
p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5, inherit.aes = T)+
scale_linetype_manual("line type",labels = rp, values=c(1,5,4,3))
```
[](https://i.stack.imgur.com/84k2E.png) | 2017/07/08 | [
"https://Stackoverflow.com/questions/44988957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057644/"
] | Per my comment, if you add an override to your legend you can change how the color displays. This should work:
```
p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5, inherit.aes = T)+
scale_linetype_manual("line type",labels = c("100 yr", "50 yr", "25 yr"), values=c(1,5,4,3)) +
guides(linetype = guide_legend(override.aes= list(color = "black")))
```
And the resulting plot is:
[](https://i.stack.imgur.com/023d7.png) | if you add `+ guides(linetype = guide_legend(override.aes= list(color = "black")))` to your last plot do
This solves thanks @Mike |
36,912 | I want to type "xy-plane" in a document so that it "looks right" when I print the document.
(1) `xy-plane` does not look right to me.
(2) `$xy-$plane` looks bad.
(3) `$xy$-plane` looks ok, but I feel uneasy.
What is the accepted convention for typing "xy-plane" in a (La)TeX document? | 2011/12/02 | [
"https://tex.stackexchange.com/questions/36912",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7764/"
] | Here "x" and "y" are variables, so they have to go in math mode; the hyphen must go outside math mode. So
```
$xy$\nobreakdash-plane
```
Note that `\nobreakdash` is provided by the **amsmath** package; it disallows a break after the hyphen. Possible variation:
```
$x\,y$\nobreakdash-plane
```
where the two letters are slightly separated. Be consistent. You can define
```
\newcommand{\plane}[2]{$#1#2$\nobreakdash-plane}
```
and use it as `\plane{x}{y}`, if it appears with different letters. Or
```
\newcommand{\xyplane}{$x\,y$\nobreakdash-plane}
```
and use it as `\xyplane{}`. (I've used both variations, take your pick.) | Here's a different suggestion: I wouldn't place a hyphen before the word "plane" but, instead, an unbreakable space. Second, I'd insert an (unbreakable) en-dash between $x$ and $y$:
```
\newcommand\xyplane{$x$\nobreakdash--$y$~plane}
```

The en-dash is, typographically speaking, the most frequently used "connector" symbol, as in "pages 40--52", "Einstein--Bose condensates", "categories A--Z", etc. The notation implies, so to say, that we're talking about the plane formed by (linear combinations of) points on the $x$ and $y$ axes.
I'd note, separately, that I wouldn't foresee much of a chance for confusion between $x$--$y$ and $x-y$, because TeX inserts whitespace (of width `\medmuskip`) around binary operators (such as the minus sign):

Note also that the endash is *thinner* than the math-minus sign. |
2,353,902 | I'm struggling in finding a closed form for,
>
> $$ \int\_0^\infty Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right) \,dx $$
>
>
>
*My Attempt:* Let $H = \int Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx$. First I integrate by parts, splitting $f=e^{-bx}$ and $dg=\sin\left(\frac{2\pi}{T}x\right)\,dx$. Then another IBP using $u=e^{-bx}$ and $dv = \cos\left(\frac{2\pi}{T}x\right)\,dx$ and simplify,
\begin{align}
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \int \cos\left(\frac{2\pi}{T}x\right)e^{-bx}\,dx \\
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \left[ e^{-bx}\frac{T}{2\pi}\sin\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\int e^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx \right] \\
\left(\frac{2\pi}{A\cdot T} - \frac{T}{2\pi b^2}\right)H &= e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac{T}{2\pi b} e^{-bx} \sin\left(\frac{2\pi}{T}x\right) \\
H &= -e^{-bx} \left(\cos\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\sin\left(\frac{2\pi}{T}x\right) \right) \cdot \left( \frac{A\cdot T 2\pi b^2}{(2\pi b)^2 - A\cdot T^2}\right) + c\\
\end{align}
First off, is this horrid looking expression correct? If so, can it be simplified further?
Now I come to evaluate $H|\_0^\infty$. $H$ appears to be defined at $x=0$, so I really just need to find $\lim\_{x\to \infty^+} H$. Here is where I'm stuck. The denominator grows exponentially for $b\ge 1$, and $T$ and $A$ don't seem to have any effect on the limit. How should I evaluate this limit? | 2017/07/10 | [
"https://math.stackexchange.com/questions/2353902",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/274085/"
] | If you differentiate $f(x)$, you should end up with $f'(x) = 4x^3 - 12x^2-4x+12$ which you can factor as $f'(x) = 4\cdot[x^2(x-3) -(x-3)]=4(x^2-1)(x-3)$. Assess whether each of the roots of $f'(x)$ corresponds to a minimum or a maximum of $f$, or neither. Deduce that $f$ has two global minima which are positive at $x = 3$ and $x=-1$. Since $f(x)\to+\infty$ as $|x|\to+\infty$, conclude that $f$ has no real roots.
---
**Edit:** The factorization of $f'(x)$:
\begin{align\*}
4x^3-12x^2-4x+12 &= (4x-12)x^2-4(x-3) \\
&= 4(x-3)x^2-4(x-3) \\
&= 4\cdot[x^2(x-3)-(x-3)].
\end{align\*} | First thing you have to do for yourself is trying to image this graph, and the line $y = 0$, what does it mean for these two functions to have no solution when they are put in an equation together? If you can answer this, then it should be rather straightforward. |
2,353,902 | I'm struggling in finding a closed form for,
>
> $$ \int\_0^\infty Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right) \,dx $$
>
>
>
*My Attempt:* Let $H = \int Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx$. First I integrate by parts, splitting $f=e^{-bx}$ and $dg=\sin\left(\frac{2\pi}{T}x\right)\,dx$. Then another IBP using $u=e^{-bx}$ and $dv = \cos\left(\frac{2\pi}{T}x\right)\,dx$ and simplify,
\begin{align}
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \int \cos\left(\frac{2\pi}{T}x\right)e^{-bx}\,dx \\
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \left[ e^{-bx}\frac{T}{2\pi}\sin\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\int e^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx \right] \\
\left(\frac{2\pi}{A\cdot T} - \frac{T}{2\pi b^2}\right)H &= e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac{T}{2\pi b} e^{-bx} \sin\left(\frac{2\pi}{T}x\right) \\
H &= -e^{-bx} \left(\cos\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\sin\left(\frac{2\pi}{T}x\right) \right) \cdot \left( \frac{A\cdot T 2\pi b^2}{(2\pi b)^2 - A\cdot T^2}\right) + c\\
\end{align}
First off, is this horrid looking expression correct? If so, can it be simplified further?
Now I come to evaluate $H|\_0^\infty$. $H$ appears to be defined at $x=0$, so I really just need to find $\lim\_{x\to \infty^+} H$. Here is where I'm stuck. The denominator grows exponentially for $b\ge 1$, and $T$ and $A$ don't seem to have any effect on the limit. How should I evaluate this limit? | 2017/07/10 | [
"https://math.stackexchange.com/questions/2353902",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/274085/"
] | If you differentiate $f(x)$, you should end up with $f'(x) = 4x^3 - 12x^2-4x+12$ which you can factor as $f'(x) = 4\cdot[x^2(x-3) -(x-3)]=4(x^2-1)(x-3)$. Assess whether each of the roots of $f'(x)$ corresponds to a minimum or a maximum of $f$, or neither. Deduce that $f$ has two global minima which are positive at $x = 3$ and $x=-1$. Since $f(x)\to+\infty$ as $|x|\to+\infty$, conclude that $f$ has no real roots.
---
**Edit:** The factorization of $f'(x)$:
\begin{align\*}
4x^3-12x^2-4x+12 &= (4x-12)x^2-4(x-3) \\
&= 4(x-3)x^2-4(x-3) \\
&= 4\cdot[x^2(x-3)-(x-3)].
\end{align\*} | Usually the way to do this kind of question is to show $(\forall x)\,\,f(x)>0$ or $(\forall x)\,\,f(x)<0$.
Showing this usually involves finding the solutions to $f'(x)=0$ for the turning points. $f''(x)$ will tell you the nature of these turning points, and you may be able to conclude from there.
In addition, showing $(\forall x)\,\,f''(x)>0$ or $(\forall x)\,\,f''(x)<0$ shows $f$ is convex or concave respectively which is sometimes helpful.
---
In your example,
$$f(x)=x^4−4x^3−2x^2+12x+12$$
$$f'(x)=4x^3−12x^2−4x+12=4(x^3-3x^2-x+3)$$
$$f''(x)=12x^2−24x−4=4(3x^2-6x-1)$$
Note $f'(1)=0$, so using the factor theorem (and polynomial long division),
$$f'(x)=4(x-1)(x^2-2x-3)$$
$$=4(x-1)(x+1)(x-3)$$
Now $f''(-1)=8>0, f''(1)=-4<0, f''(3)=8>0$ so the points are a minimum, maximum, minimum respectively. The curve has no more turning points, and so $\lim\_{x\rightarrow\pm\infty}f(x)=\infty$
Finally, $f(-1)=3, f(3)=3$, and hence $(\forall x\in \mathbb{R})\,\,f(x)\ge3\gt0$. |
2,353,902 | I'm struggling in finding a closed form for,
>
> $$ \int\_0^\infty Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right) \,dx $$
>
>
>
*My Attempt:* Let $H = \int Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx$. First I integrate by parts, splitting $f=e^{-bx}$ and $dg=\sin\left(\frac{2\pi}{T}x\right)\,dx$. Then another IBP using $u=e^{-bx}$ and $dv = \cos\left(\frac{2\pi}{T}x\right)\,dx$ and simplify,
\begin{align}
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \int \cos\left(\frac{2\pi}{T}x\right)e^{-bx}\,dx \\
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \left[ e^{-bx}\frac{T}{2\pi}\sin\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\int e^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx \right] \\
\left(\frac{2\pi}{A\cdot T} - \frac{T}{2\pi b^2}\right)H &= e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac{T}{2\pi b} e^{-bx} \sin\left(\frac{2\pi}{T}x\right) \\
H &= -e^{-bx} \left(\cos\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\sin\left(\frac{2\pi}{T}x\right) \right) \cdot \left( \frac{A\cdot T 2\pi b^2}{(2\pi b)^2 - A\cdot T^2}\right) + c\\
\end{align}
First off, is this horrid looking expression correct? If so, can it be simplified further?
Now I come to evaluate $H|\_0^\infty$. $H$ appears to be defined at $x=0$, so I really just need to find $\lim\_{x\to \infty^+} H$. Here is where I'm stuck. The denominator grows exponentially for $b\ge 1$, and $T$ and $A$ don't seem to have any effect on the limit. How should I evaluate this limit? | 2017/07/10 | [
"https://math.stackexchange.com/questions/2353902",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/274085/"
] | If you differentiate $f(x)$, you should end up with $f'(x) = 4x^3 - 12x^2-4x+12$ which you can factor as $f'(x) = 4\cdot[x^2(x-3) -(x-3)]=4(x^2-1)(x-3)$. Assess whether each of the roots of $f'(x)$ corresponds to a minimum or a maximum of $f$, or neither. Deduce that $f$ has two global minima which are positive at $x = 3$ and $x=-1$. Since $f(x)\to+\infty$ as $|x|\to+\infty$, conclude that $f$ has no real roots.
---
**Edit:** The factorization of $f'(x)$:
\begin{align\*}
4x^3-12x^2-4x+12 &= (4x-12)x^2-4(x-3) \\
&= 4(x-3)x^2-4(x-3) \\
&= 4\cdot[x^2(x-3)-(x-3)].
\end{align\*} | The polynomial can be written as
$$f(x)=\left(x^2-2 x-3\right)^2+3$$
therefore it is strictly greater than zero for all $x\in\mathbb{R}$ |
2,353,902 | I'm struggling in finding a closed form for,
>
> $$ \int\_0^\infty Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right) \,dx $$
>
>
>
*My Attempt:* Let $H = \int Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx$. First I integrate by parts, splitting $f=e^{-bx}$ and $dg=\sin\left(\frac{2\pi}{T}x\right)\,dx$. Then another IBP using $u=e^{-bx}$ and $dv = \cos\left(\frac{2\pi}{T}x\right)\,dx$ and simplify,
\begin{align}
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \int \cos\left(\frac{2\pi}{T}x\right)e^{-bx}\,dx \\
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \left[ e^{-bx}\frac{T}{2\pi}\sin\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\int e^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx \right] \\
\left(\frac{2\pi}{A\cdot T} - \frac{T}{2\pi b^2}\right)H &= e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac{T}{2\pi b} e^{-bx} \sin\left(\frac{2\pi}{T}x\right) \\
H &= -e^{-bx} \left(\cos\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\sin\left(\frac{2\pi}{T}x\right) \right) \cdot \left( \frac{A\cdot T 2\pi b^2}{(2\pi b)^2 - A\cdot T^2}\right) + c\\
\end{align}
First off, is this horrid looking expression correct? If so, can it be simplified further?
Now I come to evaluate $H|\_0^\infty$. $H$ appears to be defined at $x=0$, so I really just need to find $\lim\_{x\to \infty^+} H$. Here is where I'm stuck. The denominator grows exponentially for $b\ge 1$, and $T$ and $A$ don't seem to have any effect on the limit. How should I evaluate this limit? | 2017/07/10 | [
"https://math.stackexchange.com/questions/2353902",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/274085/"
] | First thing you have to do for yourself is trying to image this graph, and the line $y = 0$, what does it mean for these two functions to have no solution when they are put in an equation together? If you can answer this, then it should be rather straightforward. | Usually the way to do this kind of question is to show $(\forall x)\,\,f(x)>0$ or $(\forall x)\,\,f(x)<0$.
Showing this usually involves finding the solutions to $f'(x)=0$ for the turning points. $f''(x)$ will tell you the nature of these turning points, and you may be able to conclude from there.
In addition, showing $(\forall x)\,\,f''(x)>0$ or $(\forall x)\,\,f''(x)<0$ shows $f$ is convex or concave respectively which is sometimes helpful.
---
In your example,
$$f(x)=x^4−4x^3−2x^2+12x+12$$
$$f'(x)=4x^3−12x^2−4x+12=4(x^3-3x^2-x+3)$$
$$f''(x)=12x^2−24x−4=4(3x^2-6x-1)$$
Note $f'(1)=0$, so using the factor theorem (and polynomial long division),
$$f'(x)=4(x-1)(x^2-2x-3)$$
$$=4(x-1)(x+1)(x-3)$$
Now $f''(-1)=8>0, f''(1)=-4<0, f''(3)=8>0$ so the points are a minimum, maximum, minimum respectively. The curve has no more turning points, and so $\lim\_{x\rightarrow\pm\infty}f(x)=\infty$
Finally, $f(-1)=3, f(3)=3$, and hence $(\forall x\in \mathbb{R})\,\,f(x)\ge3\gt0$. |
2,353,902 | I'm struggling in finding a closed form for,
>
> $$ \int\_0^\infty Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right) \,dx $$
>
>
>
*My Attempt:* Let $H = \int Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx$. First I integrate by parts, splitting $f=e^{-bx}$ and $dg=\sin\left(\frac{2\pi}{T}x\right)\,dx$. Then another IBP using $u=e^{-bx}$ and $dv = \cos\left(\frac{2\pi}{T}x\right)\,dx$ and simplify,
\begin{align}
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \int \cos\left(\frac{2\pi}{T}x\right)e^{-bx}\,dx \\
\frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \left[ e^{-bx}\frac{T}{2\pi}\sin\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\int e^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx \right] \\
\left(\frac{2\pi}{A\cdot T} - \frac{T}{2\pi b^2}\right)H &= e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac{T}{2\pi b} e^{-bx} \sin\left(\frac{2\pi}{T}x\right) \\
H &= -e^{-bx} \left(\cos\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\sin\left(\frac{2\pi}{T}x\right) \right) \cdot \left( \frac{A\cdot T 2\pi b^2}{(2\pi b)^2 - A\cdot T^2}\right) + c\\
\end{align}
First off, is this horrid looking expression correct? If so, can it be simplified further?
Now I come to evaluate $H|\_0^\infty$. $H$ appears to be defined at $x=0$, so I really just need to find $\lim\_{x\to \infty^+} H$. Here is where I'm stuck. The denominator grows exponentially for $b\ge 1$, and $T$ and $A$ don't seem to have any effect on the limit. How should I evaluate this limit? | 2017/07/10 | [
"https://math.stackexchange.com/questions/2353902",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/274085/"
] | First thing you have to do for yourself is trying to image this graph, and the line $y = 0$, what does it mean for these two functions to have no solution when they are put in an equation together? If you can answer this, then it should be rather straightforward. | The polynomial can be written as
$$f(x)=\left(x^2-2 x-3\right)^2+3$$
therefore it is strictly greater than zero for all $x\in\mathbb{R}$ |
8,871,253 | In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code:

file.h
```
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
```
file.m
```
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
```
I don't know why the code doesn't work. | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021610/"
] | JMS provides a mechanism for you to set expiry on messages. Look at the below two references
1. [setJMSExpiration(long expiration)](https://docs.oracle.com/javaee/1.3/api/javax/jms/Message.html#setJMSExpiration%28long%29): per message
2. [ActiveMQ: How do I set the message expiration](https://activemq.apache.org/how-do-i-set-the-message-expiration.html): per destionation/per message | Well the
setJMSExpiration(long expiration):
is something you MUST not call when you are the client. See my talk on this a bit on the ActiveMQ forum.
<https://apache-qpid-developers.2158895.n2.nabble.com/MRG-Java-JMS-Expiration-td7171854.html> |
8,871,253 | In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code:

file.h
```
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
```
file.m
```
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
```
I don't know why the code doesn't work. | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021610/"
] | JMS provides a mechanism for you to set expiry on messages. Look at the below two references
1. [setJMSExpiration(long expiration)](https://docs.oracle.com/javaee/1.3/api/javax/jms/Message.html#setJMSExpiration%28long%29): per message
2. [ActiveMQ: How do I set the message expiration](https://activemq.apache.org/how-do-i-set-the-message-expiration.html): per destionation/per message | Also mind that clocks between client - broker need to be in sync, for the expiry to work properly. If the clocks is not in sync, then the expiry set from the client, may already be expired when the message is received on the broker. Or the client time is ahead of the broker, so the expiry is longer than the 10 secs.
It kinda beats me why the expiry is client time based. So AMQ offers a plugin, to fix this by realigning the time, to be broker based only. See <https://activemq.apache.org/timestampplugin.html> |
8,871,253 | In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code:

file.h
```
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
```
file.m
```
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
```
I don't know why the code doesn't work. | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021610/"
] | JMS provides a mechanism for you to set expiry on messages. Look at the below two references
1. [setJMSExpiration(long expiration)](https://docs.oracle.com/javaee/1.3/api/javax/jms/Message.html#setJMSExpiration%28long%29): per message
2. [ActiveMQ: How do I set the message expiration](https://activemq.apache.org/how-do-i-set-the-message-expiration.html): per destionation/per message | On our side we choose to add expiration time to specific destinations by using a camel route deployed in the ActiveMQ service itself.
The only thing to do is creating a XML file like the following with name e.g. `setJMSExpiration.xml`:
```
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<camelContext id="camel-set-expiration" xmlns="http://camel.apache.org/schema/spring">
<!-- Copy route for each destination to expire -->
<route id="setJMSExpiration.my.queue.dlq">
<from uri="broker:queue:MY.QUEUE.DLQ"/>
<setHeader headerName="JMSExpiration">
<!-- Message will expire after 1 day -->
<spel>#{T(java.lang.System).currentTimeMillis() + 86400000}</spel>
</setHeader>
<to uri="broker:queue:MY.QUEUE.DLQ"/>
</route>
<route id="setJMSExpiration.another.queue">
<from uri="broker:queue:ANOTHER.QUEUE"/>
<setHeader headerName="JMSExpiration">
<!-- Message will expire after 5 days -->
<spel>#{T(java.lang.System).currentTimeMillis() + 432000000}</spel>
</setHeader>
<to uri="broker:queue:ANOTHER.QUEUE"/>
</route>
</camelContext>
</beans>
```
and import it in your `activemq.xml` config with:
```
<!-- Add default Expiration (file in the same directory) -->
<import resource="setJMSExpiration.xml"/>
```
Alternatively you can also provide specific [per destination policies](https://activemq.apache.org/per-destination-policies.html) if you don't want the expired messages to reach the ActiveMQ.DLQ queue.
```
<policyEntry queue="MY.QUEUE.DLQ">
<deadLetterStrategy>
<sharedDeadLetterStrategy processExpired="false" />
</deadLetterStrategy>
</policyEntry>
<policyEntry queue="ANOTHER.QUEUE">
<deadLetterStrategy>
<sharedDeadLetterStrategy processExpired="false" />
</deadLetterStrategy>
</policyEntry>
```
The only limitation of this way is that you cannot easily use wildcards as it is coded here (you can, but it'll need some adaptations by using JMS destination header in the camel route).
We try to let the producers to define the timeToLive (and force them as much as possible) but it is not always possible to force them to change their code, this to minimize the number of such routes. |
8,871,253 | In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code:

file.h
```
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
```
file.m
```
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
```
I don't know why the code doesn't work. | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021610/"
] | JMS provides a mechanism for you to set expiry on messages. Look at the below two references
1. [setJMSExpiration(long expiration)](https://docs.oracle.com/javaee/1.3/api/javax/jms/Message.html#setJMSExpiration%28long%29): per message
2. [ActiveMQ: How do I set the message expiration](https://activemq.apache.org/how-do-i-set-the-message-expiration.html): per destionation/per message | Endpoint option **timeToLive** (<http://camel.apache.org/jms.html>) worked for me as a solution for the described problem, messages are removed from a queue after 300000 miliseconds.
e.g. "activemq:Q.QUEUE?disableReplyTo=true&**timeToLive**=300000"
Setting header JMSExpiration, didn't cause removing message from a queue automatically in my case.
But this doc <https://www.ibm.com/support/knowledgecenter/en/SSAW57_9.0.0/com.ibm.websphere.nd.multiplatform.doc/ae/rwsf_prjms_timetolive.html> gave me a hint. |
8,871,253 | In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code:

file.h
```
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
```
file.m
```
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
```
I don't know why the code doesn't work. | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021610/"
] | Well the
setJMSExpiration(long expiration):
is something you MUST not call when you are the client. See my talk on this a bit on the ActiveMQ forum.
<https://apache-qpid-developers.2158895.n2.nabble.com/MRG-Java-JMS-Expiration-td7171854.html> | Endpoint option **timeToLive** (<http://camel.apache.org/jms.html>) worked for me as a solution for the described problem, messages are removed from a queue after 300000 miliseconds.
e.g. "activemq:Q.QUEUE?disableReplyTo=true&**timeToLive**=300000"
Setting header JMSExpiration, didn't cause removing message from a queue automatically in my case.
But this doc <https://www.ibm.com/support/knowledgecenter/en/SSAW57_9.0.0/com.ibm.websphere.nd.multiplatform.doc/ae/rwsf_prjms_timetolive.html> gave me a hint. |
8,871,253 | In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code:

file.h
```
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
```
file.m
```
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
```
I don't know why the code doesn't work. | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021610/"
] | Also mind that clocks between client - broker need to be in sync, for the expiry to work properly. If the clocks is not in sync, then the expiry set from the client, may already be expired when the message is received on the broker. Or the client time is ahead of the broker, so the expiry is longer than the 10 secs.
It kinda beats me why the expiry is client time based. So AMQ offers a plugin, to fix this by realigning the time, to be broker based only. See <https://activemq.apache.org/timestampplugin.html> | Endpoint option **timeToLive** (<http://camel.apache.org/jms.html>) worked for me as a solution for the described problem, messages are removed from a queue after 300000 miliseconds.
e.g. "activemq:Q.QUEUE?disableReplyTo=true&**timeToLive**=300000"
Setting header JMSExpiration, didn't cause removing message from a queue automatically in my case.
But this doc <https://www.ibm.com/support/knowledgecenter/en/SSAW57_9.0.0/com.ibm.websphere.nd.multiplatform.doc/ae/rwsf_prjms_timetolive.html> gave me a hint. |
8,871,253 | In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code:

file.h
```
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
```
file.m
```
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
```
I don't know why the code doesn't work. | 2012/01/15 | [
"https://Stackoverflow.com/questions/8871253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021610/"
] | On our side we choose to add expiration time to specific destinations by using a camel route deployed in the ActiveMQ service itself.
The only thing to do is creating a XML file like the following with name e.g. `setJMSExpiration.xml`:
```
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<camelContext id="camel-set-expiration" xmlns="http://camel.apache.org/schema/spring">
<!-- Copy route for each destination to expire -->
<route id="setJMSExpiration.my.queue.dlq">
<from uri="broker:queue:MY.QUEUE.DLQ"/>
<setHeader headerName="JMSExpiration">
<!-- Message will expire after 1 day -->
<spel>#{T(java.lang.System).currentTimeMillis() + 86400000}</spel>
</setHeader>
<to uri="broker:queue:MY.QUEUE.DLQ"/>
</route>
<route id="setJMSExpiration.another.queue">
<from uri="broker:queue:ANOTHER.QUEUE"/>
<setHeader headerName="JMSExpiration">
<!-- Message will expire after 5 days -->
<spel>#{T(java.lang.System).currentTimeMillis() + 432000000}</spel>
</setHeader>
<to uri="broker:queue:ANOTHER.QUEUE"/>
</route>
</camelContext>
</beans>
```
and import it in your `activemq.xml` config with:
```
<!-- Add default Expiration (file in the same directory) -->
<import resource="setJMSExpiration.xml"/>
```
Alternatively you can also provide specific [per destination policies](https://activemq.apache.org/per-destination-policies.html) if you don't want the expired messages to reach the ActiveMQ.DLQ queue.
```
<policyEntry queue="MY.QUEUE.DLQ">
<deadLetterStrategy>
<sharedDeadLetterStrategy processExpired="false" />
</deadLetterStrategy>
</policyEntry>
<policyEntry queue="ANOTHER.QUEUE">
<deadLetterStrategy>
<sharedDeadLetterStrategy processExpired="false" />
</deadLetterStrategy>
</policyEntry>
```
The only limitation of this way is that you cannot easily use wildcards as it is coded here (you can, but it'll need some adaptations by using JMS destination header in the camel route).
We try to let the producers to define the timeToLive (and force them as much as possible) but it is not always possible to force them to change their code, this to minimize the number of such routes. | Endpoint option **timeToLive** (<http://camel.apache.org/jms.html>) worked for me as a solution for the described problem, messages are removed from a queue after 300000 miliseconds.
e.g. "activemq:Q.QUEUE?disableReplyTo=true&**timeToLive**=300000"
Setting header JMSExpiration, didn't cause removing message from a queue automatically in my case.
But this doc <https://www.ibm.com/support/knowledgecenter/en/SSAW57_9.0.0/com.ibm.websphere.nd.multiplatform.doc/ae/rwsf_prjms_timetolive.html> gave me a hint. |
1,167,966 | >
> Evaluate the integral $\int\_0^1 nx(1-x^2)^n \, dx$ ($n$ is constant here)
>
>
>
I actually have the solution which is:
$$\int\_0^1 nx(1-x^2)^n = \left( \frac{-n}{2(n+1)} (1-x^2)^{n+1}\right)|\_0^1 = \frac{n}{2(n+1)}$$
It's unclear to me this was calculated. I'd be glad for reasoning.
Thanks. | 2015/02/27 | [
"https://math.stackexchange.com/questions/1167966",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/188391/"
] | if you write $f(x) = 1-x^2$, your integral can be rewriten as
$$\int\_0^1 nx(1-x^2)^n = \int\_0^1 -\frac{n}{2} f'(x)f(x)^n dx $$
$$ = \int\_0^1 -\frac{n}{2(n+1)} \left( f(x)^{n+1} \right)' dx$$
$$ = \left[-\frac{n}{2(n+1)} f^{n+1}(x)\right]\_0^1$$ | Hint: change of variable $x^2=t$. |
1,167,966 | >
> Evaluate the integral $\int\_0^1 nx(1-x^2)^n \, dx$ ($n$ is constant here)
>
>
>
I actually have the solution which is:
$$\int\_0^1 nx(1-x^2)^n = \left( \frac{-n}{2(n+1)} (1-x^2)^{n+1}\right)|\_0^1 = \frac{n}{2(n+1)}$$
It's unclear to me this was calculated. I'd be glad for reasoning.
Thanks. | 2015/02/27 | [
"https://math.stackexchange.com/questions/1167966",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/188391/"
] | We want to integrate $f(x)=nx(1-x^2)^n$
Let $u=1-x^2$ and thus $du=-2xdx$
$\int{f(x)dx}=\frac{-1}{2}\int{n\cdot u^n (-2x)dx}=\frac{-1}{2}\int{nu^ndu}=-\frac{nu^{n+1}}{2(n+1)}+c=-\frac{n(1-x^2)^{n+1}}{2(n+1)}+c$
Integrating from 0 to 1, we get $\frac{n}{2(n+1)}$ | Hint: change of variable $x^2=t$. |
1,167,966 | >
> Evaluate the integral $\int\_0^1 nx(1-x^2)^n \, dx$ ($n$ is constant here)
>
>
>
I actually have the solution which is:
$$\int\_0^1 nx(1-x^2)^n = \left( \frac{-n}{2(n+1)} (1-x^2)^{n+1}\right)|\_0^1 = \frac{n}{2(n+1)}$$
It's unclear to me this was calculated. I'd be glad for reasoning.
Thanks. | 2015/02/27 | [
"https://math.stackexchange.com/questions/1167966",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/188391/"
] | if you write $f(x) = 1-x^2$, your integral can be rewriten as
$$\int\_0^1 nx(1-x^2)^n = \int\_0^1 -\frac{n}{2} f'(x)f(x)^n dx $$
$$ = \int\_0^1 -\frac{n}{2(n+1)} \left( f(x)^{n+1} \right)' dx$$
$$ = \left[-\frac{n}{2(n+1)} f^{n+1}(x)\right]\_0^1$$ | Hint:
$$\text{If } u = (1 - x^2)^k,\ du = k(1-x^2)^{k-1}(-2x) dx= -2kx(1-x^2)^{k-1}dx$$
Then
$$\int nx(1-x^2)^n dx = -\frac{n}{2(n+1)}\int (n+1)(-2x)(1-x^2)^n dx$$
$$= -\frac{n}{2(n+1)}\int (1-x^2)^n\left((n+1)(-2x)\ dx\right)$$ |
1,167,966 | >
> Evaluate the integral $\int\_0^1 nx(1-x^2)^n \, dx$ ($n$ is constant here)
>
>
>
I actually have the solution which is:
$$\int\_0^1 nx(1-x^2)^n = \left( \frac{-n}{2(n+1)} (1-x^2)^{n+1}\right)|\_0^1 = \frac{n}{2(n+1)}$$
It's unclear to me this was calculated. I'd be glad for reasoning.
Thanks. | 2015/02/27 | [
"https://math.stackexchange.com/questions/1167966",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/188391/"
] | We want to integrate $f(x)=nx(1-x^2)^n$
Let $u=1-x^2$ and thus $du=-2xdx$
$\int{f(x)dx}=\frac{-1}{2}\int{n\cdot u^n (-2x)dx}=\frac{-1}{2}\int{nu^ndu}=-\frac{nu^{n+1}}{2(n+1)}+c=-\frac{n(1-x^2)^{n+1}}{2(n+1)}+c$
Integrating from 0 to 1, we get $\frac{n}{2(n+1)}$ | Hint:
$$\text{If } u = (1 - x^2)^k,\ du = k(1-x^2)^{k-1}(-2x) dx= -2kx(1-x^2)^{k-1}dx$$
Then
$$\int nx(1-x^2)^n dx = -\frac{n}{2(n+1)}\int (n+1)(-2x)(1-x^2)^n dx$$
$$= -\frac{n}{2(n+1)}\int (1-x^2)^n\left((n+1)(-2x)\ dx\right)$$ |
1,167,966 | >
> Evaluate the integral $\int\_0^1 nx(1-x^2)^n \, dx$ ($n$ is constant here)
>
>
>
I actually have the solution which is:
$$\int\_0^1 nx(1-x^2)^n = \left( \frac{-n}{2(n+1)} (1-x^2)^{n+1}\right)|\_0^1 = \frac{n}{2(n+1)}$$
It's unclear to me this was calculated. I'd be glad for reasoning.
Thanks. | 2015/02/27 | [
"https://math.stackexchange.com/questions/1167966",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/188391/"
] | if you write $f(x) = 1-x^2$, your integral can be rewriten as
$$\int\_0^1 nx(1-x^2)^n = \int\_0^1 -\frac{n}{2} f'(x)f(x)^n dx $$
$$ = \int\_0^1 -\frac{n}{2(n+1)} \left( f(x)^{n+1} \right)' dx$$
$$ = \left[-\frac{n}{2(n+1)} f^{n+1}(x)\right]\_0^1$$ | We want to integrate $f(x)=nx(1-x^2)^n$
Let $u=1-x^2$ and thus $du=-2xdx$
$\int{f(x)dx}=\frac{-1}{2}\int{n\cdot u^n (-2x)dx}=\frac{-1}{2}\int{nu^ndu}=-\frac{nu^{n+1}}{2(n+1)}+c=-\frac{n(1-x^2)^{n+1}}{2(n+1)}+c$
Integrating from 0 to 1, we get $\frac{n}{2(n+1)}$ |
66,140,459 | I have the React class below that shows a list of users(zoomers).
Each `zoomer` has a property called `isHidden`.
When the page first loads, I want it to just show zoomers who have the `isHidden = false`.
I made a checkbox control that, when checked, should show all zoomers, including even the hidden ones.
When it's not checked, I don't want it to show any zoomer with `isHidden = true`.
So when I run the web app, and load this React component, it initially shows me no users at all...hidden or not hidden.
And when I click the checkbox, it reloads and just shows me the hidden users.
So it's not really doing what I am want it to do and I'm not sure why.
I was hoping someone could please show me the way.
Here is my code:
```
export default class ZoomerGrid extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
zoomers: List(),
showHidden: false
};
}
toggleShowHidden = e => {
const { value } = e.target;
this.setState({ showHidden: true });
}
render() {
let zoomersShowHidden = this.state.zoomers.toJS();
zoomersShowHidden = zoomersShowHidden.filter(x => x.isHidden = this.state.showHidden);
return (
<div>
Show Hidden Zoomers? <input type="checkbox" name="test" onChange={this.toggleShowHidden} value="false" />
{zoomersShowHidden.map((zoomer) => <ZoomerTile key={zoomer.id} zoomer={zoomer} />)}
</div>
);
}
}
Thanks!
``` | 2021/02/10 | [
"https://Stackoverflow.com/questions/66140459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/880874/"
] | UPDATED FOR TS4.5+
------------------
Now that TypeScript supports [tail recursion elimination on conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#tail-recursion-elimination-on-conditional-types) we can write `Kebab<T>` in a straightforward way that should handle strings up to ~1000 characters:
```
type Kebab<T extends string, A extends string = ""> =
T extends `${infer F}${infer R}` ?
Kebab<R, `${A}${F extends Lowercase<F> ? "" : "-"}${Lowercase<F>}`> :
A
```
This works by iterating character-by-character, and inserting a `"-"` before each character which is not already lowercase (so caseless characters like numbers will not get a dash before them), and then lowercasing each character.
Non-tail-recursive character-by-character iteration in TypeScript 4.5+, or any recursive type in TypeScript 4.4 and below hits recursion limits for modestly long strings, sometimes even strings of only twenty or so characters, and weird workarounds were required to handle longer strings. But now we can handle string literals longer than I imagine anyone would reasonably need:
```
type Testing = Kebab<"itWasTheBestOfTimesItWasTheWorstOfTimesItWasTheAgeOfWisdomItWasTheAgeOfFoolishnessItWasTheEpochOfBeliefItWasTheEpochOfIncredulityItWasTheSeasonOfLightItWasTheSeasonOfDarknessItWasTheSpringOfHopeItWasTheWinterOfDespair">
// type Testing = "it-was-the-best-of-times-it-was-the-worst-of-times-it-was-the-age-of-wisdom-it-was-the-age-of-foolishness-it-was-the-epoch-of-belief-it-was-the-epoch-of-incredulity-it-was-the-season-of-light-it-was-the-season-of-darkness-it-was-the-spring-of-hope-it-was-the-winter-of-despair"
```
---
Now we can use [key remapping](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#key-remapping-in-mapped-types) (also a TS4.1 feature) to easily convert from an object with camelCase keys to one with kebab-case keys:
```
type KebabKeys<T> = { [K in keyof T as K extends string ? Kebab<K> : K]: T[K] };
```
---
Finally, let's try it out on your example:
```
export interface CssPropertiesCamel {
alignContent: number | string | null;
alignItems: number | string | null;
alignSelf: number | string | null;
alignmentBaseline: number | string | null;
}
type CssPropertiesKebab = KebabKeys<CssPropertiesCamel>;
/* type CssPropertiesKebab = {
"align-content": number | string | null;
"align-items": number | string | null;
"align-self": number | string | null;
"alignment-baseline": number | string | null;
} */
export interface CssProperties extends CssPropertiesCamel, CssPropertiesKebab { }
```
Looks good! We've turned `CssPropertiesCamel` into `CssPropertiesKebab`, and then `CssProperties` can just be a merged version of those two types.
[Playground link to code](https://www.typescriptlang.org/play?#code/C4TwDgpgBA0hBGBDeAeAKlCAPYEB2AJgM5RHABOAlngOYA0UAgpjvsaRdTVALxQBE-AHy8AUFAlQM2XIRIADACQBvagDMI5KADEAvivWaoAJV3yoAfnGS4SVMYZLljfcu0tZ7ADIB7AO6aAMaIRBAo2iIWAvxQAFwCALT8rr4B5MGh4UJmIrHWEoyioqCQUhBkXLywCMgo-JTAAOohaAAWEABC5cAA8mpolAC25QCSTS3tjT7kZH0Dw0RjzURtEIw0EH2NlEQEPoNLE2sbfdo+PgA2O6145YvjK+0AomA+ga19XVcQaoePEC83h9fnhAuQIAQAK5XUB-VYAZQgIR8eD6XkoNFawDh7URyNRagAIohyABrW5Ee7LBFgKi0PoACR8kBxEG2eFw5D6hPKYEQlHIwlEAHphVAStA0N1Knx6sAEn4QglgO0EvBugkfGplUNygkGgqlSqIArpmRNdrgLqiPr5YqbcaEogNhaFTs9oNbYaHarnSatQk1OcrkQbncvfblaqIK93q71d9tQbI46Y0DXdQwRDoQ0QBGjarQvjXVdMfLkwWTUWiCjXQQSeTwxWfVXaVxXa1mSbm1GTX5qJy67z+YKihLqnY4CAiOgRHxlFAANowKDUKCkiAgLVSKAhWAeNgkMh07hRWy1GC5WAAXXiaGX16gugA3EVsK9yMBVxzNGpEIFoAAYUpAAFcgu0-ShykAxBhguKBlHyXdSzwQCUVkYB4jwSFBnVLQAB8OBPKBCOwi4LlfSRkIxPAxggQYiCwnC8JIojKlI6EKKQxAUMRC41CY3CjEI492KgMiuKoniaOGDkOhCCArluQSWJEzhaFYiTX10IpinAIDQPAyBIPKc94CqMypxnYCiDAiCrWg2DFKEV9hQAKnFfSoBsuzjIcogzKqRCqP4aSaDwBJAnQ-BgH4FThLYjSOPIyjJFClDbXoog4vE5iEtEpLcpSpD0pohJQn4nLsKEgjEu4ZLJLSsK8Fk+UkAq6gICqvLaoK+qiq43QoDc4U3ywD8vwHX9-wM2yjM0fyDzkbzDPsqCiBguCGB8+aTICmpzIXHSiiAA) | Here you have another approach:
```js
export interface CssProperties {
alignContent: number | string | null;
alignItems: number | string | null;
alignSelf: number | string | null;
alignmentBaseline: number | string | null;
}
type ToCebab<T extends string> =
T extends `align${infer Prefix}`
? `aling-${Uncapitalize<Prefix>}`
: never;
type Result = {
[P in keyof CssProperties as ToCebab<P>]: CssProperties[P]
} & CssProperties
```
[Playground link](https://www.typescriptlang.org/play?ssl=15&ssc=18&pln=1&pc=1#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgYQGdCAFKCMNGBYQuAbwCg4W5MAbBAcyXwhWAoAXHCQBXALYAjNHAA%20cQjCjIu80WPbsA3M1YduSAJKoJhEeOmyFSlUjULxW3azaceAZWDt0FyTKh1W1V1Jx09FgMeCUEYACFMQm9kYD8rQJtlEMdNcIBfRkYYAE9KOAAVCHxgKUwpAB5yuFBUJAATOmD7AD44AF4IiuaQVo64AAMopAASemR0WTJgdAQQPPHBgH4Jg3sAWlmAVSRsTDAEGAMAL2B6pZWQbvXBi2AANzRdItK8ACVaTTwPoMQYAbRIiCQcAA1sBihB0ARiGQKFQaHREhUqjU6ndugBdEREUjkSiwdHg-GMPJwABkSJJqPJtEKjCAA)
[Template literal strings - Uncapitalize](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#uncapitalizestringtype) |
66,140,459 | I have the React class below that shows a list of users(zoomers).
Each `zoomer` has a property called `isHidden`.
When the page first loads, I want it to just show zoomers who have the `isHidden = false`.
I made a checkbox control that, when checked, should show all zoomers, including even the hidden ones.
When it's not checked, I don't want it to show any zoomer with `isHidden = true`.
So when I run the web app, and load this React component, it initially shows me no users at all...hidden or not hidden.
And when I click the checkbox, it reloads and just shows me the hidden users.
So it's not really doing what I am want it to do and I'm not sure why.
I was hoping someone could please show me the way.
Here is my code:
```
export default class ZoomerGrid extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
zoomers: List(),
showHidden: false
};
}
toggleShowHidden = e => {
const { value } = e.target;
this.setState({ showHidden: true });
}
render() {
let zoomersShowHidden = this.state.zoomers.toJS();
zoomersShowHidden = zoomersShowHidden.filter(x => x.isHidden = this.state.showHidden);
return (
<div>
Show Hidden Zoomers? <input type="checkbox" name="test" onChange={this.toggleShowHidden} value="false" />
{zoomersShowHidden.map((zoomer) => <ZoomerTile key={zoomer.id} zoomer={zoomer} />)}
</div>
);
}
}
Thanks!
``` | 2021/02/10 | [
"https://Stackoverflow.com/questions/66140459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/880874/"
] | UPDATED FOR TS4.5+
------------------
Now that TypeScript supports [tail recursion elimination on conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#tail-recursion-elimination-on-conditional-types) we can write `Kebab<T>` in a straightforward way that should handle strings up to ~1000 characters:
```
type Kebab<T extends string, A extends string = ""> =
T extends `${infer F}${infer R}` ?
Kebab<R, `${A}${F extends Lowercase<F> ? "" : "-"}${Lowercase<F>}`> :
A
```
This works by iterating character-by-character, and inserting a `"-"` before each character which is not already lowercase (so caseless characters like numbers will not get a dash before them), and then lowercasing each character.
Non-tail-recursive character-by-character iteration in TypeScript 4.5+, or any recursive type in TypeScript 4.4 and below hits recursion limits for modestly long strings, sometimes even strings of only twenty or so characters, and weird workarounds were required to handle longer strings. But now we can handle string literals longer than I imagine anyone would reasonably need:
```
type Testing = Kebab<"itWasTheBestOfTimesItWasTheWorstOfTimesItWasTheAgeOfWisdomItWasTheAgeOfFoolishnessItWasTheEpochOfBeliefItWasTheEpochOfIncredulityItWasTheSeasonOfLightItWasTheSeasonOfDarknessItWasTheSpringOfHopeItWasTheWinterOfDespair">
// type Testing = "it-was-the-best-of-times-it-was-the-worst-of-times-it-was-the-age-of-wisdom-it-was-the-age-of-foolishness-it-was-the-epoch-of-belief-it-was-the-epoch-of-incredulity-it-was-the-season-of-light-it-was-the-season-of-darkness-it-was-the-spring-of-hope-it-was-the-winter-of-despair"
```
---
Now we can use [key remapping](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#key-remapping-in-mapped-types) (also a TS4.1 feature) to easily convert from an object with camelCase keys to one with kebab-case keys:
```
type KebabKeys<T> = { [K in keyof T as K extends string ? Kebab<K> : K]: T[K] };
```
---
Finally, let's try it out on your example:
```
export interface CssPropertiesCamel {
alignContent: number | string | null;
alignItems: number | string | null;
alignSelf: number | string | null;
alignmentBaseline: number | string | null;
}
type CssPropertiesKebab = KebabKeys<CssPropertiesCamel>;
/* type CssPropertiesKebab = {
"align-content": number | string | null;
"align-items": number | string | null;
"align-self": number | string | null;
"alignment-baseline": number | string | null;
} */
export interface CssProperties extends CssPropertiesCamel, CssPropertiesKebab { }
```
Looks good! We've turned `CssPropertiesCamel` into `CssPropertiesKebab`, and then `CssProperties` can just be a merged version of those two types.
[Playground link to code](https://www.typescriptlang.org/play?#code/C4TwDgpgBA0hBGBDeAeAKlCAPYEB2AJgM5RHABOAlngOYA0UAgpjvsaRdTVALxQBE-AHy8AUFAlQM2XIRIADACQBvagDMI5KADEAvivWaoAJV3yoAfnGS4SVMYZLljfcu0tZ7ADIB7AO6aAMaIRBAo2iIWAvxQAFwCALT8rr4B5MGh4UJmIrHWEoyioqCQUhBkXLywCMgo-JTAAOohaAAWEABC5cAA8mpolAC25QCSTS3tjT7kZH0Dw0RjzURtEIw0EH2NlEQEPoNLE2sbfdo+PgA2O6145YvjK+0AomA+ga19XVcQaoePEC83h9fnhAuQIAQAK5XUB-VYAZQgIR8eD6XkoNFawDh7URyNRagAIohyABrW5Ee7LBFgKi0PoACR8kBxEG2eFw5D6hPKYEQlHIwlEAHphVAStA0N1Knx6sAEn4QglgO0EvBugkfGplUNygkGgqlSqIArpmRNdrgLqiPr5YqbcaEogNhaFTs9oNbYaHarnSatQk1OcrkQbncvfblaqIK93q71d9tQbI46Y0DXdQwRDoQ0QBGjarQvjXVdMfLkwWTUWiCjXQQSeTwxWfVXaVxXa1mSbm1GTX5qJy67z+YKihLqnY4CAiOgRHxlFAANowKDUKCkiAgLVSKAhWAeNgkMh07hRWy1GC5WAAXXiaGX16gugA3EVsK9yMBVxzNGpEIFoAAYUpAAFcgu0-ShykAxBhguKBlHyXdSzwQCUVkYB4jwSFBnVLQAB8OBPKBCOwi4LlfSRkIxPAxggQYiCwnC8JIojKlI6EKKQxAUMRC41CY3CjEI492KgMiuKoniaOGDkOhCCArluQSWJEzhaFYiTX10IpinAIDQPAyBIPKc94CqMypxnYCiDAiCrWg2DFKEV9hQAKnFfSoBsuzjIcogzKqRCqP4aSaDwBJAnQ-BgH4FThLYjSOPIyjJFClDbXoog4vE5iEtEpLcpSpD0pohJQn4nLsKEgjEu4ZLJLSsK8Fk+UkAq6gICqvLaoK+qiq43QoDc4U3ywD8vwHX9-wM2yjM0fyDzkbzDPsqCiBguCGB8+aTICmpzIXHSiiAA) | Here's a solution I came to that uses a trampolining technique to defer the typescript type so it doesn't throw recursive type errors.
```js
export type KebabCase<S> = S extends `${infer C}${infer T}`
? KebabCase<T> extends infer U
? U extends string
? T extends Uncapitalize<T>
? `${Uncapitalize<C>}${U}`
: `${Uncapitalize<C>}-${U}`
: never
: never
: S
``` |
66,140,459 | I have the React class below that shows a list of users(zoomers).
Each `zoomer` has a property called `isHidden`.
When the page first loads, I want it to just show zoomers who have the `isHidden = false`.
I made a checkbox control that, when checked, should show all zoomers, including even the hidden ones.
When it's not checked, I don't want it to show any zoomer with `isHidden = true`.
So when I run the web app, and load this React component, it initially shows me no users at all...hidden or not hidden.
And when I click the checkbox, it reloads and just shows me the hidden users.
So it's not really doing what I am want it to do and I'm not sure why.
I was hoping someone could please show me the way.
Here is my code:
```
export default class ZoomerGrid extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
zoomers: List(),
showHidden: false
};
}
toggleShowHidden = e => {
const { value } = e.target;
this.setState({ showHidden: true });
}
render() {
let zoomersShowHidden = this.state.zoomers.toJS();
zoomersShowHidden = zoomersShowHidden.filter(x => x.isHidden = this.state.showHidden);
return (
<div>
Show Hidden Zoomers? <input type="checkbox" name="test" onChange={this.toggleShowHidden} value="false" />
{zoomersShowHidden.map((zoomer) => <ZoomerTile key={zoomer.id} zoomer={zoomer} />)}
</div>
);
}
}
Thanks!
``` | 2021/02/10 | [
"https://Stackoverflow.com/questions/66140459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/880874/"
] | UPDATED FOR TS4.5+
------------------
Now that TypeScript supports [tail recursion elimination on conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#tail-recursion-elimination-on-conditional-types) we can write `Kebab<T>` in a straightforward way that should handle strings up to ~1000 characters:
```
type Kebab<T extends string, A extends string = ""> =
T extends `${infer F}${infer R}` ?
Kebab<R, `${A}${F extends Lowercase<F> ? "" : "-"}${Lowercase<F>}`> :
A
```
This works by iterating character-by-character, and inserting a `"-"` before each character which is not already lowercase (so caseless characters like numbers will not get a dash before them), and then lowercasing each character.
Non-tail-recursive character-by-character iteration in TypeScript 4.5+, or any recursive type in TypeScript 4.4 and below hits recursion limits for modestly long strings, sometimes even strings of only twenty or so characters, and weird workarounds were required to handle longer strings. But now we can handle string literals longer than I imagine anyone would reasonably need:
```
type Testing = Kebab<"itWasTheBestOfTimesItWasTheWorstOfTimesItWasTheAgeOfWisdomItWasTheAgeOfFoolishnessItWasTheEpochOfBeliefItWasTheEpochOfIncredulityItWasTheSeasonOfLightItWasTheSeasonOfDarknessItWasTheSpringOfHopeItWasTheWinterOfDespair">
// type Testing = "it-was-the-best-of-times-it-was-the-worst-of-times-it-was-the-age-of-wisdom-it-was-the-age-of-foolishness-it-was-the-epoch-of-belief-it-was-the-epoch-of-incredulity-it-was-the-season-of-light-it-was-the-season-of-darkness-it-was-the-spring-of-hope-it-was-the-winter-of-despair"
```
---
Now we can use [key remapping](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#key-remapping-in-mapped-types) (also a TS4.1 feature) to easily convert from an object with camelCase keys to one with kebab-case keys:
```
type KebabKeys<T> = { [K in keyof T as K extends string ? Kebab<K> : K]: T[K] };
```
---
Finally, let's try it out on your example:
```
export interface CssPropertiesCamel {
alignContent: number | string | null;
alignItems: number | string | null;
alignSelf: number | string | null;
alignmentBaseline: number | string | null;
}
type CssPropertiesKebab = KebabKeys<CssPropertiesCamel>;
/* type CssPropertiesKebab = {
"align-content": number | string | null;
"align-items": number | string | null;
"align-self": number | string | null;
"alignment-baseline": number | string | null;
} */
export interface CssProperties extends CssPropertiesCamel, CssPropertiesKebab { }
```
Looks good! We've turned `CssPropertiesCamel` into `CssPropertiesKebab`, and then `CssProperties` can just be a merged version of those two types.
[Playground link to code](https://www.typescriptlang.org/play?#code/C4TwDgpgBA0hBGBDeAeAKlCAPYEB2AJgM5RHABOAlngOYA0UAgpjvsaRdTVALxQBE-AHy8AUFAlQM2XIRIADACQBvagDMI5KADEAvivWaoAJV3yoAfnGS4SVMYZLljfcu0tZ7ADIB7AO6aAMaIRBAo2iIWAvxQAFwCALT8rr4B5MGh4UJmIrHWEoyioqCQUhBkXLywCMgo-JTAAOohaAAWEABC5cAA8mpolAC25QCSTS3tjT7kZH0Dw0RjzURtEIw0EH2NlEQEPoNLE2sbfdo+PgA2O6145YvjK+0AomA+ga19XVcQaoePEC83h9fnhAuQIAQAK5XUB-VYAZQgIR8eD6XkoNFawDh7URyNRagAIohyABrW5Ee7LBFgKi0PoACR8kBxEG2eFw5D6hPKYEQlHIwlEAHphVAStA0N1Knx6sAEn4QglgO0EvBugkfGplUNygkGgqlSqIArpmRNdrgLqiPr5YqbcaEogNhaFTs9oNbYaHarnSatQk1OcrkQbncvfblaqIK93q71d9tQbI46Y0DXdQwRDoQ0QBGjarQvjXVdMfLkwWTUWiCjXQQSeTwxWfVXaVxXa1mSbm1GTX5qJy67z+YKihLqnY4CAiOgRHxlFAANowKDUKCkiAgLVSKAhWAeNgkMh07hRWy1GC5WAAXXiaGX16gugA3EVsK9yMBVxzNGpEIFoAAYUpAAFcgu0-ShykAxBhguKBlHyXdSzwQCUVkYB4jwSFBnVLQAB8OBPKBCOwi4LlfSRkIxPAxggQYiCwnC8JIojKlI6EKKQxAUMRC41CY3CjEI492KgMiuKoniaOGDkOhCCArluQSWJEzhaFYiTX10IpinAIDQPAyBIPKc94CqMypxnYCiDAiCrWg2DFKEV9hQAKnFfSoBsuzjIcogzKqRCqP4aSaDwBJAnQ-BgH4FThLYjSOPIyjJFClDbXoog4vE5iEtEpLcpSpD0pohJQn4nLsKEgjEu4ZLJLSsK8Fk+UkAq6gICqvLaoK+qiq43QoDc4U3ywD8vwHX9-wM2yjM0fyDzkbzDPsqCiBguCGB8+aTICmpzIXHSiiAA) | Inspired by the great answer of @jcalz, I made a modified version to make snake\_case into kebab-case:
```
type KebabCase<
T extends string,
A extends string = ''
> = T extends `${infer P1}_${infer P2}${infer R}`
? KebabCase<R, `${A}${P1}-${P2}`>
: `${A}${T}`;
``` |
66,140,459 | I have the React class below that shows a list of users(zoomers).
Each `zoomer` has a property called `isHidden`.
When the page first loads, I want it to just show zoomers who have the `isHidden = false`.
I made a checkbox control that, when checked, should show all zoomers, including even the hidden ones.
When it's not checked, I don't want it to show any zoomer with `isHidden = true`.
So when I run the web app, and load this React component, it initially shows me no users at all...hidden or not hidden.
And when I click the checkbox, it reloads and just shows me the hidden users.
So it's not really doing what I am want it to do and I'm not sure why.
I was hoping someone could please show me the way.
Here is my code:
```
export default class ZoomerGrid extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
zoomers: List(),
showHidden: false
};
}
toggleShowHidden = e => {
const { value } = e.target;
this.setState({ showHidden: true });
}
render() {
let zoomersShowHidden = this.state.zoomers.toJS();
zoomersShowHidden = zoomersShowHidden.filter(x => x.isHidden = this.state.showHidden);
return (
<div>
Show Hidden Zoomers? <input type="checkbox" name="test" onChange={this.toggleShowHidden} value="false" />
{zoomersShowHidden.map((zoomer) => <ZoomerTile key={zoomer.id} zoomer={zoomer} />)}
</div>
);
}
}
Thanks!
``` | 2021/02/10 | [
"https://Stackoverflow.com/questions/66140459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/880874/"
] | Here's a solution I came to that uses a trampolining technique to defer the typescript type so it doesn't throw recursive type errors.
```js
export type KebabCase<S> = S extends `${infer C}${infer T}`
? KebabCase<T> extends infer U
? U extends string
? T extends Uncapitalize<T>
? `${Uncapitalize<C>}${U}`
: `${Uncapitalize<C>}-${U}`
: never
: never
: S
``` | Here you have another approach:
```js
export interface CssProperties {
alignContent: number | string | null;
alignItems: number | string | null;
alignSelf: number | string | null;
alignmentBaseline: number | string | null;
}
type ToCebab<T extends string> =
T extends `align${infer Prefix}`
? `aling-${Uncapitalize<Prefix>}`
: never;
type Result = {
[P in keyof CssProperties as ToCebab<P>]: CssProperties[P]
} & CssProperties
```
[Playground link](https://www.typescriptlang.org/play?ssl=15&ssc=18&pln=1&pc=1#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgYQGdCAFKCMNGBYQuAbwCg4W5MAbBAcyXwhWAoAXHCQBXALYAjNHAA%20cQjCjIu80WPbsA3M1YduSAJKoJhEeOmyFSlUjULxW3azaceAZWDt0FyTKh1W1V1Jx09FgMeCUEYACFMQm9kYD8rQJtlEMdNcIBfRkYYAE9KOAAVCHxgKUwpAB5yuFBUJAATOmD7AD44AF4IiuaQVo64AAMopAASemR0WTJgdAQQPPHBgH4Jg3sAWlmAVSRsTDAEGAMAL2B6pZWQbvXBi2AANzRdItK8ACVaTTwPoMQYAbRIiCQcAA1sBihB0ARiGQKFQaHREhUqjU6ndugBdEREUjkSiwdHg-GMPJwABkSJJqPJtEKjCAA)
[Template literal strings - Uncapitalize](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#uncapitalizestringtype) |
66,140,459 | I have the React class below that shows a list of users(zoomers).
Each `zoomer` has a property called `isHidden`.
When the page first loads, I want it to just show zoomers who have the `isHidden = false`.
I made a checkbox control that, when checked, should show all zoomers, including even the hidden ones.
When it's not checked, I don't want it to show any zoomer with `isHidden = true`.
So when I run the web app, and load this React component, it initially shows me no users at all...hidden or not hidden.
And when I click the checkbox, it reloads and just shows me the hidden users.
So it's not really doing what I am want it to do and I'm not sure why.
I was hoping someone could please show me the way.
Here is my code:
```
export default class ZoomerGrid extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
zoomers: List(),
showHidden: false
};
}
toggleShowHidden = e => {
const { value } = e.target;
this.setState({ showHidden: true });
}
render() {
let zoomersShowHidden = this.state.zoomers.toJS();
zoomersShowHidden = zoomersShowHidden.filter(x => x.isHidden = this.state.showHidden);
return (
<div>
Show Hidden Zoomers? <input type="checkbox" name="test" onChange={this.toggleShowHidden} value="false" />
{zoomersShowHidden.map((zoomer) => <ZoomerTile key={zoomer.id} zoomer={zoomer} />)}
</div>
);
}
}
Thanks!
``` | 2021/02/10 | [
"https://Stackoverflow.com/questions/66140459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/880874/"
] | Here's a solution I came to that uses a trampolining technique to defer the typescript type so it doesn't throw recursive type errors.
```js
export type KebabCase<S> = S extends `${infer C}${infer T}`
? KebabCase<T> extends infer U
? U extends string
? T extends Uncapitalize<T>
? `${Uncapitalize<C>}${U}`
: `${Uncapitalize<C>}-${U}`
: never
: never
: S
``` | Inspired by the great answer of @jcalz, I made a modified version to make snake\_case into kebab-case:
```
type KebabCase<
T extends string,
A extends string = ''
> = T extends `${infer P1}_${infer P2}${infer R}`
? KebabCase<R, `${A}${P1}-${P2}`>
: `${A}${T}`;
``` |
59,101,674 | So I was having issues with flutter http package when it came to making a post request so I used dart HttpClient. I made a post request according to what was described somewhere but I am having issues getting response. Here is my code
```
Future<HttpClientResponse> submit() async {
print('start');
Map<String, dynamic> data = { 'title' : 'My first post' };
String jsonString = json.encode(data); // encode map to json
String paramName = 'param'; // give the post param a name
String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
HttpClientRequest request =
await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
// it's polite to send the body length to the server
request.headers.set('Content-Length', bodyBytes.length.toString());
request.headers.set('Content-Type', 'application/json');
request.add(bodyBytes);
print('done');
return await (request.close());
}
```
How do I get the response from this request? | 2019/11/29 | [
"https://Stackoverflow.com/questions/59101674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8390502/"
] | The way you do it above is correct. You should, in principle, never use `fit` on test data, only on the train data. The fact that you get "better" results using `fit_transform` on the test data is not indicative of any real performance gains. In other words, by using `fit` on the test data, you lose the ability to say something meaningful about the predictive power of your model on unseen data.
The main lesson here is that any gains in test performance are meaningless once the methodological constraints (i.e. train-test separation) are violated. You may obtain higher scores using `fit_transform`, but these don't mean anything anymore. | when you want to transform a data you should declare that.
like:
```
data["afs"]=data["afs"].transform()
``` |
59,101,674 | So I was having issues with flutter http package when it came to making a post request so I used dart HttpClient. I made a post request according to what was described somewhere but I am having issues getting response. Here is my code
```
Future<HttpClientResponse> submit() async {
print('start');
Map<String, dynamic> data = { 'title' : 'My first post' };
String jsonString = json.encode(data); // encode map to json
String paramName = 'param'; // give the post param a name
String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
HttpClientRequest request =
await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
// it's polite to send the body length to the server
request.headers.set('Content-Length', bodyBytes.length.toString());
request.headers.set('Content-Type', 'application/json');
request.add(bodyBytes);
print('done');
return await (request.close());
}
```
How do I get the response from this request? | 2019/11/29 | [
"https://Stackoverflow.com/questions/59101674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8390502/"
] | >
> Should I follow the documentation of StandardScaler such that the test dataset MUST be transformed only using ".transform()" without fit() function? Or it depends on the dataset such that I can use the "fit\_transform()" function for both training and testing datasets?
>
>
>
The moment you are re-training your scaler for the testing set you will have a different dependincy of your input features. The original algorithm will be fitted based on the fitting of your training sacling. And if you re-train it this will be overwritten, and you are faking your input of the test data for the algorithm.
So the answer is **MUST** only be transformed. | when you want to transform a data you should declare that.
like:
```
data["afs"]=data["afs"].transform()
``` |
59,101,674 | So I was having issues with flutter http package when it came to making a post request so I used dart HttpClient. I made a post request according to what was described somewhere but I am having issues getting response. Here is my code
```
Future<HttpClientResponse> submit() async {
print('start');
Map<String, dynamic> data = { 'title' : 'My first post' };
String jsonString = json.encode(data); // encode map to json
String paramName = 'param'; // give the post param a name
String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
HttpClientRequest request =
await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
// it's polite to send the body length to the server
request.headers.set('Content-Length', bodyBytes.length.toString());
request.headers.set('Content-Type', 'application/json');
request.add(bodyBytes);
print('done');
return await (request.close());
}
```
How do I get the response from this request? | 2019/11/29 | [
"https://Stackoverflow.com/questions/59101674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8390502/"
] | >
> Should I follow the documentation of StandardScaler such that the test dataset MUST be transformed only using ".transform()" without fit() function? Or it depends on the dataset such that I can use the "fit\_transform()" function for both training and testing datasets?
>
>
>
The moment you are re-training your scaler for the testing set you will have a different dependincy of your input features. The original algorithm will be fitted based on the fitting of your training sacling. And if you re-train it this will be overwritten, and you are faking your input of the test data for the algorithm.
So the answer is **MUST** only be transformed. | The way you do it above is correct. You should, in principle, never use `fit` on test data, only on the train data. The fact that you get "better" results using `fit_transform` on the test data is not indicative of any real performance gains. In other words, by using `fit` on the test data, you lose the ability to say something meaningful about the predictive power of your model on unseen data.
The main lesson here is that any gains in test performance are meaningless once the methodological constraints (i.e. train-test separation) are violated. You may obtain higher scores using `fit_transform`, but these don't mean anything anymore. |
56,082,728 | I'm writing automated test cases using Javascript to perform GUI actions. I'm writing a function to handle some basic "initialization" operations on the software under test but I wanted to have the option to not necessarily put every argument into the parameters.
So I had a function that basically did this:
```
function initializeApp(arg1,arg2,arg3,arg4)
{
action1(arg1);
action2(arg2);
action3(arg3);
action4(arg4);
}
```
But lets say that I didn't want to perform action 4, right now the code contained inside the "action4" block would not be able to handle there not being input for arg4 and would crash. So the hamfisted way I thought about getting around this issue was to create a bunch of `if` and `else if` statements that would essentially skip over different code blocks if that argument was undefined. Here's an example:
```
function testIES(configFile, recordFile, overwrite, scriptFile)
{
if (arg1 == undefined)
{
action2(arg2);
action3(arg3);
action4(arg4);
} else if (arg2 == undefined)
{
action1(arg1);
action3(arg3);
action4(arg4);
} else if (arg3 == undefined)
{
action1(arg1);
action2(arg2);
action4(arg4);
} else if (arg4 == undefined)
{
action1(arg1);
action2(arg2);
action3(arg3);
}
}
```
However, this approach has an obvious flaw in that I'd need to come up with every combination of "actions" if I wanted to be able to leave out more than 1 argument. It would also not be very user friendly if anyone else wanted to do it because they'd have to know not to leave out more than one argument. So is my best option simply coming up with all the different combinations? Or is there a better way? Surely there's a better way. | 2019/05/10 | [
"https://Stackoverflow.com/questions/56082728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227893/"
] | There was an error in the code: the encoding declared was not actually used when opening the file. I created an issue in the module, and [this pull request to fix it](https://github.com/Tux/CSV/pull/15) | It looks like the documentation for `Text::CSV` requires that [the value passed to `encoding` must be the same as that accepted by the `open` function's `encoding` parameter](https://modules.perl6.org/dist/Text::CSV:cpan:HMBRAND/lib/Text/CSV.pod6#L1856).
The list of possible values is listed in the [`IO::Handle::encoding` method documentation](https://docs.perl6.org/type/IO::Handle#method_encoding):
>
> The accepted values for encoding are case-insensitive. The available encodings vary by implementation and backend. On Rakudo MoarVM the following are supported:
>
>
> * `utf8`
> * `utf16`
> * `utf16le`
> * `utf16be`
> * `utf8-c8`
> * `iso-8859-1`
> * `windows-1251`
> * `windows-1252`
> * `windows-932`
> * `ascii`
>
>
> The default encoding is `utf8`, which undergoes normalization into Unicode NFC (normalization form canonical). In some cases you may want to ensure no normalization is done; for this you can use `utf8-c8`. Before using `utf8-c8` please read Unicode: Filehandles and I/O for more information on `utf8-c8` and NFC.
>
>
> As of Rakudo 2018.04 `windows-932` is also supported which is a variant of ShiftJIS.
>
>
> Implementation may choose to also provide support for aliases, e.g. Rakudo allows aliases `latin-1` for `iso-8859-1` encoding and dashed utf versions: `utf-8` and `utf-16`.
>
>
> |
3,380,694 | I need some help understanding the correct way to mix variables with strings like this. I have tried every configuration I can think of and I keep getting an error.
```
<?php
include('connect.php');
foreach($_GET['item'] as $key=>$value) {
mysql_query("UPDATE userprojectlist SET category_display_order = '$key' WHERE category_id = '$value' ");
}
?>
Notice: Undefined index: item in updatedb.php on line 3
Warning: Invalid argument supplied for foreach() in pdatedb.php on line 3
``` | 2010/08/01 | [
"https://Stackoverflow.com/questions/3380694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340688/"
] | Is `item` an array in the url like `item[]`? If it's not that's the reason you get that error, you cannot iterate through a non-iterator object!
Also get rid of the single quotes around the values if they are numeric and use string concatenation,
```
"UPDATE userprojectlist SET category_display_order = " . $key . " WHERE category_id = " . $value . ";"
``` | ```
mysql_query('UPDATE userprojectlist SET category_display_order = ' . $key . ' WHERE category_id = ' . $value );
```
or
```
mysql_query("UPDATE userprojectlist SET category_display_order = $key WHERE category_id = $value" );
```
This is assuming both variables are integers. |
3,380,694 | I need some help understanding the correct way to mix variables with strings like this. I have tried every configuration I can think of and I keep getting an error.
```
<?php
include('connect.php');
foreach($_GET['item'] as $key=>$value) {
mysql_query("UPDATE userprojectlist SET category_display_order = '$key' WHERE category_id = '$value' ");
}
?>
Notice: Undefined index: item in updatedb.php on line 3
Warning: Invalid argument supplied for foreach() in pdatedb.php on line 3
``` | 2010/08/01 | [
"https://Stackoverflow.com/questions/3380694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340688/"
] | ```
Notice: Undefined index: item in updatedb.php on line 3
```
This error is saying that there's no such variable as `$_GET['item']` defined. You probably did not pass `$_GET['item']` to this page.
```
Warning: Invalid argument supplied for foreach() in pdatedb.php on line 3
```
Thus because of the previous error, you get this, as `$_GET['item']` is not an array.
The error has nothing to do with the SQL code. | ```
mysql_query('UPDATE userprojectlist SET category_display_order = ' . $key . ' WHERE category_id = ' . $value );
```
or
```
mysql_query("UPDATE userprojectlist SET category_display_order = $key WHERE category_id = $value" );
```
This is assuming both variables are integers. |
3,380,694 | I need some help understanding the correct way to mix variables with strings like this. I have tried every configuration I can think of and I keep getting an error.
```
<?php
include('connect.php');
foreach($_GET['item'] as $key=>$value) {
mysql_query("UPDATE userprojectlist SET category_display_order = '$key' WHERE category_id = '$value' ");
}
?>
Notice: Undefined index: item in updatedb.php on line 3
Warning: Invalid argument supplied for foreach() in pdatedb.php on line 3
``` | 2010/08/01 | [
"https://Stackoverflow.com/questions/3380694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340688/"
] | Is `item` an array in the url like `item[]`? If it's not that's the reason you get that error, you cannot iterate through a non-iterator object!
Also get rid of the single quotes around the values if they are numeric and use string concatenation,
```
"UPDATE userprojectlist SET category_display_order = " . $key . " WHERE category_id = " . $value . ";"
``` | ```
Notice: Undefined index: item in updatedb.php on line 3
```
This error is saying that there's no such variable as `$_GET['item']` defined. You probably did not pass `$_GET['item']` to this page.
```
Warning: Invalid argument supplied for foreach() in pdatedb.php on line 3
```
Thus because of the previous error, you get this, as `$_GET['item']` is not an array.
The error has nothing to do with the SQL code. |
2,377,603 | There is a question having several parts. I solved the part (a) but I have problems with other parts.
Let
$f\in L^{1}(\mathbb{R}^{n}),$
with
$f\geq 0\;$ a.e.
in
$\mathbb{R}^{n}$
and let
$g:\mathbb{R}^{n}\to [0,+\infty)$
be the function defined by
$$ g(x):=\int\_{B(x,\vert x\vert/2)}f(y)dy,$$
where
$\vert \cdot\vert$
denotes the Euclidean norm and
$B(x,r)=\{y\in \mathbb{R}^{n}:\vert y-x\vert <r\}$
for every
$x\in \mathbb{R}^{n}$
and every
$r\geq 0.$
(a) Prove that
$g$
is continuous.
(b) Prove that $g(x)\to 0$
as
$\vert x\vert\to \infty. $
(c) Prove that
$g$
has a maximum point in
$\mathbb{R}^{n}.$
Please write only hint and not a whole solution, I have to be accustomed to solve the mathematics problems. A small useful hint will be accepted. Also, if you have seen this problem in other books, please let me know. | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377603",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/277958/"
] | Note that the zero element of $\mathbb{Z}\oplus \mathbb{Z} / I $ is $I=0+I.$
Let $$((x\_1,y\_1)+I)((x\_2,y\_2)+I)=0+I$$
Then $$(x\_1x\_2,y\_1y\_2)\in I$$
Thus $$7\mid y\_1y\_2$$
As $7$ is prime, therefore $7 \mid y\_1$ or $7 \mid y\_2$. Hence, $(x\_1,y\_1) \in I$ or $(x\_2,y\_2)\in I$.
So, $(x\_1,y\_1)+I = 0 + I$ or $(x\_2,y\_2)+I=0+I$.
So, $\mathbb{Z}\oplus \mathbb{Z} / I $ is an integral domain. | It would be a good exercise to prove the following results.
>
> **Result-1:** In $\Bbb Z \times \Bbb Z$ the prime ideals are of the form, $\Bbb Z/p\Bbb Z\times \Bbb Z$ or $\Bbb Z\times\Bbb Z/p\Bbb Z $ where $p$ is prime.
>
>
>
In fact you can generalize the above result as follows.
>
> **Result-2:** Let $R\_i$ be a comutative ring with unity for each $i=1,...,n$. The prime ideals of $R\_1\times ...\times R\_n$ are of the form $P\_1\times...\times P\_n$ where for some $j$, $P\_j$ is a prime ideal of $R\_j$ and $ P\_i=R\_i$ for $i\not=j$.
>
>
>
In your case, $I=\Bbb Z \times \Bbb Z/7\Bbb Z$. Hence it follows that $I$ is a prime ideal. |
67,273,304 | I'm creating a bunch of emails using Word 2013 mail merge (not sure about the English term; I'm working with German version). Outlook is set to *offline mode*, so that I can modify the mails before sending out. So far, everything is working.
I want to add an attachment to each of the emails and am trying to write some Outlook VBA script to do so. The following code is failing with code 80070005 (insufficient permission) at the `.Attachment.Add...` statement **but** only if the mail does not have an attachement yet. If there is an attachment, it will add the attachment to this **and** the next mail, then fails again with 80070005. I repeated running the script and it adds the attachment to one more mail at each run.
What might cause the 80070005?
```
Sub addAttachmentsToMailsInOutbox()
Dim olNs As Outlook.NameSpace
Dim olOutbox As Outlook.MAPIFolder
Dim olItem As Object
Dim olEmail As Outlook.MailItem
Set olNs = GetNamespace("MAPI")
Set olOutbox = olNs.GetDefaultFolder(olFolderOutbox)
For Each olItem In olOutbox.Items
If olItem.Class = olMail Then
Set olEmail = olItem
With olEmail
.Attachments.Add ("d:\temp\test.txt")
.Save
End With
End If
Next
MsgBox ("done")
End Sub
```
*Note* that this is the smallest working -- well failing -- example. I tried other code I found on the internet, but all show that strange behaviour. | 2021/04/26 | [
"https://Stackoverflow.com/questions/67273304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3220554/"
] | The suggestion from @HackSlash didn't work either, but it prompted another idea: Separate the modifications into two loops, and voilà, this works:
```
Sub addAttachmentsToMailsInOutbox()
Dim olNs As Outlook.NameSpace
Dim olOutbox As Outlook.MAPIFolder
Dim olItem As Object
Set olNs = GetNamespace("MAPI")
Set olOutbox = olNs.GetDefaultFolder(olFolderOutbox)
For Each olItem In olOutbox.Items
If olItem.Class = olMail Then
With olItem
.BodyFormat = olFormatHTML
.Save
End With
End If
Next
For Each olItem In olOutbox.Items
If olItem.Class = olMail Then
With olItem
.Attachments.Add ("d:\temp\test.txt")
.Save
End With
End If
Next
MsgBox ("done")
End Sub
```
If more than one file needs to be attached, simply repeat the line `.Attachments.Add(....)` for each file. | I was unable to reproduce your problem using a newly created email. This suggests that it comes down to the properties of the mail item you are editing. For example, if the `BodyFormat` is not `olFormatHTML` then you might not be able to add attachments as expected.
If the code I supply here works then that was your problem. Please let me know if this works for you.
```
Public Sub addAttachmentsToMailsInOutbox()
Dim olNs As Outlook.NameSpace
Set olNs = GetNamespace("MAPI")
Dim olOutbox As Outlook.MAPIFolder
Set olOutbox = olNs.GetDefaultFolder(olFolderOutbox)
Dim olItem As Object
For Each olItem In olOutbox.Items
If olItem.Class = olMail Then
With olItem
.BodyFormat = olFormatHTML
.Save
.Attachments.Add ("d:\temp\test.txt")
.Save
End With
End If
Next
MsgBox ("done")
End Sub
```
NOTE: The [documentation](https://learn.microsoft.com/en-us/office/vba/api/outlook.attachments.add) states
>
> To ensure consistent results, always save an item before adding or removing objects in the Attachments collection.
>
>
> |
73,368,464 | i git yolov7(<https://github.com/WongKinYiu>) with `yolov7.pt` and try to run
`detect.py`(i just want to run the example). it seems to be normal. but the output image has no mask.Why?
here is my code and log:
```
(PyTorch) E:\yolov7>python detect.py --weights yolov7.pt --source inference\images\bus.jpg
Namespace(weights=['yolov7.pt'], source='inference\\images\\bus.jpg', img_size=640, conf_thres=0.25, iou_thres=0.45, device='', view_img=False, save_txt=False, save_conf=False, nosave=False, classes=None, agnostic_nms=False, augment=False, update=False, project='runs/detect', name='exp', exist_ok=False, no_trace=False)
YOLOR v0.1-103-g6ded32c torch 1.11.0 CUDA:0 (NVIDIA GeForce GTX 1650, 4095.6875MB)
Fusing layers...
RepConv.fuse_repvgg_block
RepConv.fuse_repvgg_block
RepConv.fuse_repvgg_block
Model Summary: 306 layers, 36905341 parameters, 6652669 gradients
Convert model to Traced-model...
traced_script_module saved!
model is traced!
E:\anaconda\envs\PyTorch\lib\site-packages\torch\functional.py:568: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at C:\cb\pytorch_1000000000000\work\aten\src\ATen\native\TensorShape.cpp:2228.)
return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]
Done. (151.6ms) Inference, (9.3ms) NMS
The image with the result is saved in: runs\detect\exp4\bus.jpg
Done. (3.713s)
```
and here is my result:[output image](https://i.stack.imgur.com/OrM6E.jpg) | 2022/08/16 | [
"https://Stackoverflow.com/questions/73368464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19570683/"
] | Your code should be throwing errors I think? You're trying to declare result twice, but as the second time is within the forEach loop, it's actually a different variable, and is created and destroyed for each loop.
Assuming your fetch works, this *should* work:
```
const data = ['item1','item2','item3']
let result = []
data.forEach(async (item)=>{
const res = await fetch(`https://websitename.com/${item}`)
result = [...result,...res]
}
console.log(result)
``` | May this could help you :)
```
async function doRequest(data) {
// process here
}
const requests = ['item1', 'item2', 'item3'];
const results = requests.map(async (val) => {
const response = await doRequest();
return response;
});
await Promise.all(requests);
``` |
73,368,464 | i git yolov7(<https://github.com/WongKinYiu>) with `yolov7.pt` and try to run
`detect.py`(i just want to run the example). it seems to be normal. but the output image has no mask.Why?
here is my code and log:
```
(PyTorch) E:\yolov7>python detect.py --weights yolov7.pt --source inference\images\bus.jpg
Namespace(weights=['yolov7.pt'], source='inference\\images\\bus.jpg', img_size=640, conf_thres=0.25, iou_thres=0.45, device='', view_img=False, save_txt=False, save_conf=False, nosave=False, classes=None, agnostic_nms=False, augment=False, update=False, project='runs/detect', name='exp', exist_ok=False, no_trace=False)
YOLOR v0.1-103-g6ded32c torch 1.11.0 CUDA:0 (NVIDIA GeForce GTX 1650, 4095.6875MB)
Fusing layers...
RepConv.fuse_repvgg_block
RepConv.fuse_repvgg_block
RepConv.fuse_repvgg_block
Model Summary: 306 layers, 36905341 parameters, 6652669 gradients
Convert model to Traced-model...
traced_script_module saved!
model is traced!
E:\anaconda\envs\PyTorch\lib\site-packages\torch\functional.py:568: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at C:\cb\pytorch_1000000000000\work\aten\src\ATen\native\TensorShape.cpp:2228.)
return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]
Done. (151.6ms) Inference, (9.3ms) NMS
The image with the result is saved in: runs\detect\exp4\bus.jpg
Done. (3.713s)
```
and here is my result:[output image](https://i.stack.imgur.com/OrM6E.jpg) | 2022/08/16 | [
"https://Stackoverflow.com/questions/73368464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19570683/"
] | Your code should be throwing errors I think? You're trying to declare result twice, but as the second time is within the forEach loop, it's actually a different variable, and is created and destroyed for each loop.
Assuming your fetch works, this *should* work:
```
const data = ['item1','item2','item3']
let result = []
data.forEach(async (item)=>{
const res = await fetch(`https://websitename.com/${item}`)
result = [...result,...res]
}
console.log(result)
``` | Change:
```
const res = await fetch(`https://websitename.com/${item}`)
const result = [...result,...res]
```
To:
```
const response = await fetch(`https://websitename.com/${item}`);
const data = response.json(); // if your response is Json
result.push(data);
```
* result should be `const` instead of `let` |
73,368,464 | i git yolov7(<https://github.com/WongKinYiu>) with `yolov7.pt` and try to run
`detect.py`(i just want to run the example). it seems to be normal. but the output image has no mask.Why?
here is my code and log:
```
(PyTorch) E:\yolov7>python detect.py --weights yolov7.pt --source inference\images\bus.jpg
Namespace(weights=['yolov7.pt'], source='inference\\images\\bus.jpg', img_size=640, conf_thres=0.25, iou_thres=0.45, device='', view_img=False, save_txt=False, save_conf=False, nosave=False, classes=None, agnostic_nms=False, augment=False, update=False, project='runs/detect', name='exp', exist_ok=False, no_trace=False)
YOLOR v0.1-103-g6ded32c torch 1.11.0 CUDA:0 (NVIDIA GeForce GTX 1650, 4095.6875MB)
Fusing layers...
RepConv.fuse_repvgg_block
RepConv.fuse_repvgg_block
RepConv.fuse_repvgg_block
Model Summary: 306 layers, 36905341 parameters, 6652669 gradients
Convert model to Traced-model...
traced_script_module saved!
model is traced!
E:\anaconda\envs\PyTorch\lib\site-packages\torch\functional.py:568: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at C:\cb\pytorch_1000000000000\work\aten\src\ATen\native\TensorShape.cpp:2228.)
return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]
Done. (151.6ms) Inference, (9.3ms) NMS
The image with the result is saved in: runs\detect\exp4\bus.jpg
Done. (3.713s)
```
and here is my result:[output image](https://i.stack.imgur.com/OrM6E.jpg) | 2022/08/16 | [
"https://Stackoverflow.com/questions/73368464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19570683/"
] | Your code should be throwing errors I think? You're trying to declare result twice, but as the second time is within the forEach loop, it's actually a different variable, and is created and destroyed for each loop.
Assuming your fetch works, this *should* work:
```
const data = ['item1','item2','item3']
let result = []
data.forEach(async (item)=>{
const res = await fetch(`https://websitename.com/${item}`)
result = [...result,...res]
}
console.log(result)
``` | Method .forEach() makes sync iteration. It means that an iteration does not wait resolving of your async callback, but just starts it. As a result forEach starts all requests and jumps to line with console.log(result). But at the moment none of the requests are done and array is still empty. If you wrap like that s*etTimeout(()=>console.log(result),3000)* you will see that the array is filled with data.
If you want to make sequential calls:
```
(async function() {
const data = ['item1','item2','item3']
let result = []
for await (const item of data) {
const res = await fetch(`https://websitename.com/${item}`)
console.log(item);
result.push(item)
}
console.log(result)
})();
```
If you want to make parallel calls:
```
(async function() {
const data = ['item1','item2','item3']
let result = await Promise.all(data.map(async (item)=>{
return await await fetch(`https://websitename.com/${item}`)
}))
console.log(result)
})();
``` |
49,427,419 | I'm using $mdDialog to show popup alerts. I want to refresh the the page whenever I close the Pop up container.
```
$scope.updateCustomer = function(){
HomeService.updateCustomer($scope.update)
.then (function success(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Username has been changed successfully!")
.ariaLabel('')
.ok('Ok')
);
},
function error(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Something is wrong!")
.ariaLabel('')
.ok('Ok')
);
});
}
```
How to refresh the page when I close the pop up container? | 2018/03/22 | [
"https://Stackoverflow.com/questions/49427419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9048829/"
] | This was the working answer for my problem...
```
$scope.updateCustomer = function(){
HomeService.updateCustomer($scope.update)
.then (function success(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Username has been changed successfully!")
.ariaLabel('')
.ok('Ok')
.onRemoving(window.location.reload())
);
},
function error(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Something is wrong!")
.ariaLabel('')
.ok('Ok')
);
});
}
``` | Page reloading is not quite the angularjs pattern but you can use:
```
$mdDialog
.show({
...
onRemoving: function() {
window.location.reload();
}
});
```
Ref.: [$mdDialog Service](https://material.angularjs.org/latest/api/service/$mdDialog#mddialog-show-optionsorpreset) |
84,684 | Do we need to make changes for Salesforce Fast deploy to deploy our code via ANT migration tool ? OR does Salesforce take care of it automatically ?
I would like to find some documentation which states that we don't have to make any changes for fast deploy. | 2015/07/23 | [
"https://salesforce.stackexchange.com/questions/84684",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/13059/"
] | If you will go through [this](http://releasenotes.docs.salesforce.com/en-us/winter15/release-notes/rn_quick_deployment.htm) article, it is clearly written :
When deploying to non-production environments (sandbox), Apex tests aren’t required and aren’t run automatically. ***When using Metadata API (including the Force.com Migration Tool), Quick Deploy is supported in sandbox only for validations that explicitly enable the execution of tests (for example, via the runAllTests parameter for the Migration Tool)***. For change sets, Quick Deploy is not supported in sandbox because there is no option to enable test runs for change sets.
So it seems like, using Metadata API(ANT), it is supported only in sandbox(with runAllTests paramater enabled) | I may be wrong here. But thought its worth to put my thoughts.
Once you validate using ANT, you can go to salesforce and use the quick deploy feature. Guess as of now, through ANT quick deploy is not supported into prod instance. |
84,684 | Do we need to make changes for Salesforce Fast deploy to deploy our code via ANT migration tool ? OR does Salesforce take care of it automatically ?
I would like to find some documentation which states that we don't have to make any changes for fast deploy. | 2015/07/23 | [
"https://salesforce.stackexchange.com/questions/84684",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/13059/"
] | If you will go through [this](http://releasenotes.docs.salesforce.com/en-us/winter15/release-notes/rn_quick_deployment.htm) article, it is clearly written :
When deploying to non-production environments (sandbox), Apex tests aren’t required and aren’t run automatically. ***When using Metadata API (including the Force.com Migration Tool), Quick Deploy is supported in sandbox only for validations that explicitly enable the execution of tests (for example, via the runAllTests parameter for the Migration Tool)***. For change sets, Quick Deploy is not supported in sandbox because there is no option to enable test runs for change sets.
So it seems like, using Metadata API(ANT), it is supported only in sandbox(with runAllTests paramater enabled) | ```
<target name="quickdeployprod">
<sf:deployRecentValidation username="${sf.username}" password="${sf.password}" serverurl="${sf.sandboxurl}" recentValidationId = "recently validated id" deployroot="Retrieve"/>
</target>
``` |
73,720,590 | It appears that starting with Android 11, you are now required to include a `AndroidWindowSplashScreenAnimatedIcon` preference in your Cordova `config.xml` that includes a path to a path to a png/xml file and the `<splash>` tags are no longer supported.
This appears to mean that we are now required to use an icon for the Splash loading in the app.
Do we have the ability to still use a full-screen image that we had done with previous versions of Android?
When using `cordova-res` it would generate some individual files for different screen sizes/densities, so I wasn't sure if there was a similar tool to help create an individual screen image for the project. | 2022/09/14 | [
"https://Stackoverflow.com/questions/73720590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1278584/"
] | Gmail does not support svg image format, so for displaying it you should host somewhere png version of appstore badge to display it inside of the email. The easiest way to host this image is Amazon s3 bucket. | **Please apply this code**
```html
<a href="https://apps.apple.com/us/app/symphony-secure-communications/id1098963705?itsct=apps_box_badge&itscg=30200"
style="display: inline-block; overflow: hidden; border-radius: 13px; width: 250px; height: 83px;">
<img src="https://apple-resources.s3.amazonaws.com/media-badges/download-on-the-app-store/black/en-us.svg"
alt="Download on the App Store" style="border-radius: 13px; width: 250px; height: 83px;">
</a>
``` |
845,593 | How to I extract a subdirectory in a tarball into the current directory?
Example, the tarball from [wordpress](http://wordpress.org/download/):
```
wordpress/
wordpress/wp-trackback.php
wordpress/wp-config-sample.php
wordpress/wp-settings.php
wordpress/wp-rss2.php
wordpress/readme.html
wordpress/index.php
...
```
How do I extract everything under `wordpress/` into the current directory? In otherwords, it will not create a `wordpress` directory.
I've tried this with no luck:
```
tar xvfz latest.tar.gz wordpress -C ./
```
I know I can extract it normally and move it back, but I figure there has to be a way to do it in one shot. | 2009/05/10 | [
"https://Stackoverflow.com/questions/845593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16742/"
] | Why don't you untar normally, then just:
```
mv wordpress/.* .
mv wordpress/* .
rmdir wordpress
```
But alas, there's:
```
tar --strip-components=1 -zxvf wordpress.tgz
``` | Surprisingly, my `tar` (GNU tar v1.16) doesn't have an option to strip initial pathname elements.
However, it seems that more recent versions sport a `--strip-components=number` parameter, which will strip that many compononents from the start of the path.
If like me you are using an older `tar`, and you are certain that the archive does not contain a directory or file named `wordpress/wordpress`, you could always just make a symlink from `wordpress` to `.`, then extract as usual:
```
ln -s . wordpress
tar xvfz latest.tar.gz wordpress
rm wordpress
``` |
31,081,750 | I created this xslt mapping using Contivo but it's not working for the XML below.
Would someone be able to identify what is wrong, please?
I spent some time already working on it but was not able to figure out what is wrong.
Here is the XSLT:
```
<?xml version="1.0" encoding="UTF-8"?>
<!-- IMPORTANT: If this transform will be run using Xalan, then version 2.5.1 or higher is required. -->
<!-- Copyright (c) 2008 Contivo, Inc. All Rights Reserved.-->
<!-- NOTE: DataPower supports the Xalan:nodeset() function. -->
<!-- This transform was created by Analyst version 3.11.2.2. -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xalan="http://xml.apache.org/xalan"
xmlns:func="http://exslt.org/functions"
xmlns:ctvf="http://www.contivo.com/xslt/extensions"
xmlns:date="http://exslt.org/dates-and-times"
xmlns:dp="http://www.datapower.com/extensions"
xmlns:tns="http://schemas.datacontract.org/2004/07/Inventory.Data.Models"
xmlns:xs2="http://integration.com/interfaces/queryDirectInventory/v1/queryDirectInventory.xsd"
extension-element-prefixes="func ctvf date dp"
exclude-result-prefixes="xalan tns s">
<xsl:variable name='_root' select='/'/>
<xsl:template match='/'>
<xsl:variable name="__MappingResults">
<xsl:value-of select="ctvf:trim($_root//tns:InventoryInquiryApiResponse[1]/tns:InventoryInquiryApiResult[1]/tns:SkuAvailabilities[1]/tns:SkuAvailabilityResponse[1]/tns:AvailabilityIndicator[1])"/>
<e>
<xsl:attribute name="n">xs2:queryDirectInventoryResponse</xsl:attribute>
<xsl:attribute name="m">t</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<e>
<xsl:attribute name="n">xs2:availabilityList</xsl:attribute>
<xsl:attribute name="m">t</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<e>
<xsl:attribute name="n">xs2:availabilityList</xsl:attribute>
<xsl:attribute name="m">t</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:attribute name="m">l</xsl:attribute>
<xsl:for-each select="$_root//tns:InventoryInquiryApiResponse[1]/tns:InventoryInquiryApiResult[1]/tns:SkuAvailabilities[1]/tns:SkuAvailabilityResponse">
<e>
<xsl:attribute name="n">xs2:availabilityList</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<e>
<xsl:attribute name="n">xs2:availabilityInd</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:value-of select="ctvf:trim(string(./tns:AvailabilityIndicator[1]))"/>
</e>
<e>
<xsl:attribute name="n">xs2:availableQuantity</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:value-of select="ctvf:testForNullNumber(./tns:AvailableQuantity[1], "")"/>
</e>
<e>
<xsl:attribute name="n">xs2:zipCode</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:value-of select="ctvf:trim(./tns:PostalCode[1])"/>
</e>
<e>
<xsl:attribute name="n">xs2:itemId</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:value-of select="ctvf:trim(./tns:Sku[1])"/>
</e>
<e>
<xsl:attribute name="n">xs2:statusMessageInfo</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<e>
<xsl:attribute name="n">xs2:statusMessageCode</xsl:attribute>
<xsl:attribute name="m">t</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:value-of select="ctvf:trim(./tns:StatusMessage[1])"/>
</e>
<e>
<xsl:attribute name="n">xs2:statusMessageText</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:value-of select="ctvf:convertNumber(ctvf:trim(string(./tns:StatusMessageCode[1])))"/>
</e>
</e>
</e>
</xsl:for-each>
<e>
<xsl:attribute name="n">xs2:availabilityList</xsl:attribute>
<xsl:attribute name="m">t</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:attribute name="m">e</xsl:attribute>
<e>
<xsl:attribute name="n">xs2:statusMessageInfo</xsl:attribute>
<xsl:attribute name="m">f</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
<xsl:attribute name="m">e</xsl:attribute>
<e>
<xsl:attribute name="n">xs2:statusMessageCode</xsl:attribute>
<xsl:attribute name="m">t</xsl:attribute>
<xsl:attribute name="d">f</xsl:attribute>
</e>
</e>
</e>
</e>
</e>
</e>
</xsl:variable>
<xsl:apply-templates select='xalan:nodeset($__MappingResults)' mode="eliminateEmptyTags"/>
</xsl:template>
<xsl:template match="a" mode="eliminateEmptyTags">
<xsl:if test='@v != "" or @m = "t"'>
<xsl:attribute name="{@n}">
<xsl:value-of select='@v' />
</xsl:attribute>
</xsl:if>
</xsl:template>
<xsl:template match="e" mode="eliminateEmptyTags">
<xsl:choose>
<xsl:when test='@m = "f"'>
<xsl:if test='descendant-or-self::*[text() != ""][@d = "f"][1]/text() != "" or descendant-or-self::a[@v != ""][@d = "f"][1]/@v != ""'>
<xsl:choose>
<xsl:when test='@n !=""'>
<xsl:element name="{@n}">
<xsl:apply-templates select='a' mode="eliminateEmptyTags"/>
<xsl:value-of select='text()' />
<xsl:for-each select='./namespace::*'>
<xsl:copy/>
</xsl:for-each>
<xsl:apply-templates select='e' mode="eliminateEmptyTags"/>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select='e' mode="eliminateEmptyTags"/>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:when>
<xsl:when test='@m = "l"'>
<xsl:choose>
<xsl:when test='child::e[@m != "e"]/descendant-or-self::*[text() != ""][@d = "f"][1]/text() != "" or child::e[@m != "e"]/descendant-or-self::a[@v != ""][@d = "f"][1]/@v != ""'>
<xsl:apply-templates select='e[@m != "e"]' mode="eliminateEmptyTags"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select='e[@m = "e"]' mode="eliminateEmptyTags"/>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test='@n !=""'>
<xsl:element name="{@n}">
<xsl:apply-templates select='a' mode="eliminateEmptyTags"/>
<xsl:value-of select='text()' />
<xsl:for-each select='./namespace::*'>
<xsl:copy/>
</xsl:for-each>
<xsl:apply-templates select='e' mode="eliminateEmptyTags"/>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select='e' mode="eliminateEmptyTags"/>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!--=========================================================================-->
<xsl:template name="trimAll">
<xsl:param name="trimMe"/>
<xsl:choose>
<xsl:when test="contains($trimMe, ' ')">
<xsl:call-template name="trimAll">
<xsl:with-param name="trimMe">
<xsl:value-of select='concat(substring-before($trimMe, " "), substring-after($trimMe, " "))'/>
</xsl:with-param>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select='$trimMe'/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="trimLeft">
<xsl:param name="trimMe"/>
<xsl:choose>
<xsl:when test="starts-with($trimMe, ' ')">
<xsl:call-template name="trimLeft">
<xsl:with-param name="trimMe" select='substring-after($trimMe, " ")'/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select='$trimMe'/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="trimRight">
<xsl:param name="trimMe"/>
<xsl:choose>
<xsl:when test="substring($trimMe, string-length($trimMe), 1) = ' '">
<xsl:call-template name="trimRight">
<xsl:with-param name="trimMe" select='substring($trimMe, 1, string-length($trimMe) - 1)'/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select='$trimMe'/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="trimBoth">
<xsl:param name="trimMe"/>
<xsl:variable name="result">
<xsl:call-template name="trimRight">
<xsl:with-param name="trimMe" select='$trimMe'/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="resultb">
<xsl:call-template name="trimLeft">
<xsl:with-param name="trimMe" select='$result'/>
</xsl:call-template>
</xsl:variable>
<xsl:value-of select='$resultb'/>
</xsl:template>
<!--=========================================================================-->
<func:function name="ctvf:testForNullNumber">
<xsl:param name="node"/>
<xsl:param name="defaultValue"/>
<xsl:choose>
<xsl:when test="local-name($node) = ''">
<func:result select="$defaultValue"/>
</xsl:when>
<xsl:when test="string-length(normalize-space(string($node))) = 0">
<func:result select="$defaultValue"/>
</xsl:when>
<xsl:otherwise>
<func:result select="number($node)"/>
</xsl:otherwise>
</xsl:choose>
</func:function>
<!--=========================================================================-->
<func:function name="ctvf:convertNumber">
<xsl:param name="val"/>
<xsl:variable name="strVal" select="string($val)"/>
<xsl:choose>
<xsl:when test="$strVal = 'NaN'">
<func:result select="''"/>
</xsl:when>
<xsl:otherwise>
<func:result select="$strVal"/>
</xsl:otherwise>
</xsl:choose>
</func:function>
<!--=========================================================================-->
<func:function name="ctvf:trim">
<xsl:param name="param" select="''"/>
<xsl:variable name="in" select="string($param)"/>
<xsl:variable name="len" select="string-length($in)"/>
<xsl:choose>
<xsl:when test="$len > 0 and (ctvf:isWhitespace(substring($in, 1, 1)) or ctvf:isWhitespace(substring($in, $len)))">
<xsl:variable name="first" select="ctvf:doTrimGetFirst($in, 1, $len)"/>
<func:result select="substring($in, $first, ctvf:doTrimGetLast($in, $len, $len) - $first + 1)"/>
</xsl:when>
<xsl:otherwise>
<func:result select="$in"/>
</xsl:otherwise>
</xsl:choose>
</func:function>
<func:function name="ctvf:isWhitespace">
<xsl:param name="char"/>
<func:result select="$char = ' ' or $char = '	' or $char = '
' or $char = '
'"/>
</func:function>
<func:function name="ctvf:doTrimGetFirst">
<xsl:param name="in"/>
<xsl:param name="index"/>
<xsl:param name="len"/>
<xsl:choose>
<xsl:when test="($index <= $len) and ($index <= 350) and ctvf:isWhitespace(substring($in, $index, 1))">
<func:result select="ctvf:doTrimGetFirst($in, $index + 1, $len)"/>
</xsl:when>
<xsl:otherwise>
<func:result select="$index"/>
</xsl:otherwise>
</xsl:choose>
</func:function>
<func:function name="ctvf:doTrimGetLast">
<xsl:param name="in"/>
<xsl:param name="index"/>
<xsl:param name="len"/>
<xsl:choose>
<xsl:when test="($index >= 1) and ($len - $index <= 350) and ctvf:isWhitespace(substring($in, $index, 1))">
<func:result select="ctvf:doTrimGetLast($in, $index - 1, $len)"/>
</xsl:when>
<xsl:otherwise>
<func:result select="$index"/>
</xsl:otherwise>
</xsl:choose>
</func:function>
</xsl:stylesheet>
```
Here is XML:
```
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header />
<s:Body>
<InventoryInquiryApiResponse xmlns="http://tempuri.org/">
<InventoryInquiryApiResult xmlns:a="http://schemas.datacontract.org/2004/07/Inventory.Data.Models" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:SkuAvailabilities>
<a:SkuAvailabilityResponse>
<a:AvailabilityIndicator>true</a:AvailabilityIndicator>
<a:AvailableQuantity>1</a:AvailableQuantity>
<a:PostalCode>12065</a:PostalCode>
<a:Sku>sku</a:Sku>
<a:StatusMessage>OK</a:StatusMessage>
<a:StatusMessageCode>200</a:StatusMessageCode>
</a:SkuAvailabilityResponse>
</a:SkuAvailabilities>
</InventoryInquiryApiResult>
</InventoryInquiryApiResponse>
</s:Body>
</s:Envelope>
``` | 2015/06/26 | [
"https://Stackoverflow.com/questions/31081750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2929206/"
] | There could be (and probably are) various things wrong with your XSL. The first thing that jumps to the eye (**after** removing the undeclared `s` prefix from the `exclude-result-prefixes` list) is that you're not using the correct namespaces of the source XML.
For example, in your very first selection:
```
<xsl:value-of select="ctvf:trim($_root//tns:InventoryInquiryApiResponse[1]/tns:InventoryInquiryApiResult[1]/tns:SkuAvailabilities[1]/tns:SkuAvailabilityResponse[1]/tns:AvailabilityIndicator[1])"/>
```
you are using the same `tns:` prefix for all your location steps - but in your XML, both `InventoryInquiryApiResponse` and `InventoryInquiryApiResult` are in the `xmlns="http://tempuri.org/"` namespace, which isn't even declared in your stylesheet. So you are starting off with your `$__MappingResults` variable being empty.
AFAICS, this mistake is repeated throughout your stylesheet, so that none of your instructions are selecting anything. | You have not declared the namespace "s" in the XSL. THat is already an error if you open the XSL in an editor and you have exclude-result-prefixes="xalan tns s". |
50,823,950 | So, I wanted to move a dataframe to a database into a table but I am encountering a few problems. I made the dataframe using the pandas library and wanted to upload the data into a table in my database.
Relevant snippets of my Code and the error details are as follows:
```
#CONNECTION TO SQL DATABASE
db=sql.connect(host="localhost",user="root",passwd="password",db="database_name")
cur=db.cursor()
#CONVERTING DATAFRAME(df_final) INTO TABLE
df_final.to_sql(con=db, name='finaltable', if_exists='replace', chunksize=5000)
```
Error details:
```
Traceback (most recent call last):
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M
ySQLdb\cursors.py", line 238, in execute
query = query % args
TypeError: not all arguments converted during string formatting
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 1400, in execute
cur.execute(*args)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M
ySQLdb\cursors.py", line 240, in execute
self.errorhandler(self, ProgrammingError, str(m))
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M
ySQLdb\connections.py", line 52, in defaulterrorhandler
raise errorclass(errorvalue)
_mysql_exceptions.ProgrammingError: not all arguments converted during string fo
rmatting
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pt.py", line 77, in <module>
df_final.to_sql(con=db, name='finaltable', if_exists='replace', chunksize=50
00)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\core\generic.py", line 2127, in to_sql
dtype=dtype)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 450, in to_sql
chunksize=chunksize, dtype=dtype)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 1502, in to_sql
table.create()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 561, in create
if self.exists():
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 549, in exists
return self.pd_sql.has_table(self.name, self.schema)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 1514, in has_table
return len(self.execute(query, [name, ]).fetchall()) > 0
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 1412, in execute
raise_with_traceback(ex)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\compat\__init__.py", line 403, in raise_with_traceback
raise exc.with_traceback(traceback)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p
andas\io\sql.py", line 1400, in execute
cur.execute(*args)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M
ySQLdb\cursors.py", line 240, in execute
self.errorhandler(self, ProgrammingError, str(m))
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M
ySQLdb\connections.py", line 52, in defaulterrorhandler
raise errorclass(errorvalue)
pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM
sqlite_ma
ster WHERE type='table' AND name=?;': not all arguments converted during string
formatting
``` | 2018/06/12 | [
"https://Stackoverflow.com/questions/50823950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9071346/"
] | So apparently my approach has gone obsolete due to updates and therefore for the connection bit, I used 'create\_engine' from 'sqlalchemy' library instead of 'mysqldb.connect()' to access the database:
```
#relevant import:
from sqlalchemy import create_engine
#accessing database:
engine = create_engine("mysql://root:PASSWORD@host/database_name")
con = engine.connect()
#uploading dataframe to database:
df.to_sql(con=con, name='final_table', if_exists='replace', chunksize=10000)
``` | For me, it seems that you have nulls in the data. Try to fill the nulls in the dataframe before calling .to\_sql()
```
df_final.fillna('default string')
```
Or to remove the null rows
```
df_final.dropna(inplace=True)
``` |
39,070,962 | I have learning Image Slider Using ViewPager. For that, I want the images to be dynamic. Glide is easy but I think I am not using it properly.
Here's what I am trying to do.
```
//Initialize by default Images
private static final Integer[] IMAGES = {R.drawable.image1,R.drawable.image2};
// Load images into Drawables using Glide
Glide.with(this)
.load("https://google.com/someImage1.jpg")
.error(R.drawable.image1)
.into(R.drawable.image1);
Glide.with(this)
.load("https://google.com/someImage2.jpg")
.error(R.drawable.image2)
.into(R.drawable.image2);
// Set Again
IMAGES[0]= R.drawable.image1;
IMAGES[1]= R.drawable.image2;
```
But `.into(java.lang.Integer`) is not defined and I know that. But I want something that would solve my problem. I have slider view. In that I need to pass the Images as drawables or something like that. Image loading would be carried by Adapter. I can't load directly as far as I know. Is there any way to load glide images in `drawable`.
Also what is the best way to catch or store the images locally, so that if there is no internet connection, still the slider works smoothly.
Here is my Adapater
```
public class MainPageSlideImageAdapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public MainPageSlideImageAdapter(Context context,ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return IMAGES.size();
}
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
}
``` | 2016/08/22 | [
"https://Stackoverflow.com/questions/39070962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2254802/"
] | you must provide the view in `.into()` please view the sample
sample layout
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/myImage"
android:layout_width="100dp"
android:layout_height="100dp"/>
</LinearLayout>
```
**Update**
```
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
Glide.with(this)
.load(IMAGES.get(position))
.error(R.drawable.image2)
.into(imageView);
//imageView.setImageResource();
view.addView(imageLayout, 0);
return imageLayout;
}
``` | Instead of storing the image in memory, store the address instead.
```
private static final String[] IMAGES = {"https://google.com/someImage1.jpg", "https://google.com/someImage2.jpg"};
```
Then load the image when you `instantiateItem`
```
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
Glide.with(context)
.load(IMAGES.get(position))
.error(R.drawable.image1)
.into(imageView);
view.addView(imageLayout, 0);
return imageLayout;
}
```
Also, glide provides memory and disk caching. This means it should be able to show images even if there is no internet. |
39,070,962 | I have learning Image Slider Using ViewPager. For that, I want the images to be dynamic. Glide is easy but I think I am not using it properly.
Here's what I am trying to do.
```
//Initialize by default Images
private static final Integer[] IMAGES = {R.drawable.image1,R.drawable.image2};
// Load images into Drawables using Glide
Glide.with(this)
.load("https://google.com/someImage1.jpg")
.error(R.drawable.image1)
.into(R.drawable.image1);
Glide.with(this)
.load("https://google.com/someImage2.jpg")
.error(R.drawable.image2)
.into(R.drawable.image2);
// Set Again
IMAGES[0]= R.drawable.image1;
IMAGES[1]= R.drawable.image2;
```
But `.into(java.lang.Integer`) is not defined and I know that. But I want something that would solve my problem. I have slider view. In that I need to pass the Images as drawables or something like that. Image loading would be carried by Adapter. I can't load directly as far as I know. Is there any way to load glide images in `drawable`.
Also what is the best way to catch or store the images locally, so that if there is no internet connection, still the slider works smoothly.
Here is my Adapater
```
public class MainPageSlideImageAdapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public MainPageSlideImageAdapter(Context context,ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return IMAGES.size();
}
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
}
``` | 2016/08/22 | [
"https://Stackoverflow.com/questions/39070962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2254802/"
] | you must provide the view in `.into()` please view the sample
sample layout
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/myImage"
android:layout_width="100dp"
android:layout_height="100dp"/>
</LinearLayout>
```
**Update**
```
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
Glide.with(this)
.load(IMAGES.get(position))
.error(R.drawable.image2)
.into(imageView);
//imageView.setImageResource();
view.addView(imageLayout, 0);
return imageLayout;
}
``` | `imageView.setImageResource` simply needs replaced with a Glide call.
Or use an ArrayAdapter of Strings for Urls that you want to download. I don't think you can "overwrite" a drawable from Glide |
39,070,962 | I have learning Image Slider Using ViewPager. For that, I want the images to be dynamic. Glide is easy but I think I am not using it properly.
Here's what I am trying to do.
```
//Initialize by default Images
private static final Integer[] IMAGES = {R.drawable.image1,R.drawable.image2};
// Load images into Drawables using Glide
Glide.with(this)
.load("https://google.com/someImage1.jpg")
.error(R.drawable.image1)
.into(R.drawable.image1);
Glide.with(this)
.load("https://google.com/someImage2.jpg")
.error(R.drawable.image2)
.into(R.drawable.image2);
// Set Again
IMAGES[0]= R.drawable.image1;
IMAGES[1]= R.drawable.image2;
```
But `.into(java.lang.Integer`) is not defined and I know that. But I want something that would solve my problem. I have slider view. In that I need to pass the Images as drawables or something like that. Image loading would be carried by Adapter. I can't load directly as far as I know. Is there any way to load glide images in `drawable`.
Also what is the best way to catch or store the images locally, so that if there is no internet connection, still the slider works smoothly.
Here is my Adapater
```
public class MainPageSlideImageAdapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public MainPageSlideImageAdapter(Context context,ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return IMAGES.size();
}
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
}
``` | 2016/08/22 | [
"https://Stackoverflow.com/questions/39070962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2254802/"
] | `imageView.setImageResource` simply needs replaced with a Glide call.
Or use an ArrayAdapter of Strings for Urls that you want to download. I don't think you can "overwrite" a drawable from Glide | Instead of storing the image in memory, store the address instead.
```
private static final String[] IMAGES = {"https://google.com/someImage1.jpg", "https://google.com/someImage2.jpg"};
```
Then load the image when you `instantiateItem`
```
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
Glide.with(context)
.load(IMAGES.get(position))
.error(R.drawable.image1)
.into(imageView);
view.addView(imageLayout, 0);
return imageLayout;
}
```
Also, glide provides memory and disk caching. This means it should be able to show images even if there is no internet. |
155,607 | >
> Let a small pressure-sensing device be suspended inside a fluid-filled vessel. ... We find by experiment that at a given point in a fluid at rest, the **pressure has the same value no matter how the pressure sensor is placed.**
>
>
>
Why is it so? | 2014/12/29 | [
"https://physics.stackexchange.com/questions/155607",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/-1/"
] | Suppose we had a fluid where the pressure depended on direction:

For the sake of argument let's suppose that $P\_1 > P\_2$. In that case we could take a tube with one end normal to direction $1$ and the other normal to direction $2$:

Because the pressure at the ends is different, fluid will flow round the tube and we have a perpetual motion device. Or rather, the fluid would flow until the pressures equalised and $P\_1 = P\_2$. But the tube is just a conceptual aid, and we can take it away:

In this case fluid would simply flow in the cycle shown until the pressures equalised. So in any fluid that can flow freely the pressure $P\_1$ must equal $P\_2$. The argument applies to any directions, and the conclusion is that the pressure must be independant of direction.
There are possible exceptions. For example some [structured fluids](https://www.google.co.uk/search?q=structured%20fluid) are anisotropic and may have different viscosity in different directions, or may have an anisotropic yield stress. In these cases it could be the case that the pressure would not be the same in all directions. But then, as Sofia says in a comment, the equations of motion for such a fluid would not be spherically symmetric. | In some circumstances, like that of homogeneous and isotropic fluids, the pressure can be described by a tensor which, by the said symmetries, becomes a scalar multiple of the "identity tensor". Such scalar is precisely $p$, the pressure (the tensor is more generally known as *stress tensor*, and the pressures are its "diagonal components"). |
73,402,356 | ```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for line in lines:
if 'Food' in line:
print(f.next())
openFood()
```
I want it where when it sees a certain header like 'Food' It will print the line below it. I cant seem to make it work. The text file will be like
```
Food
Apple
Cal 120
Protein 12
Fat 13
Carb 23
``` | 2022/08/18 | [
"https://Stackoverflow.com/questions/73402356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19730199/"
] | Just use the index.
```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for i in range(len(lines)-1):
if 'Food' in lines[i]:
print(lines[i+1])
openFood()
``` | Can you try the following:
```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for ind, line in enumerate(lines):
if 'Food' in line:
try:
print(lines[ind + 1])
except:
print('No line after "Food"')
openFood()
``` |
73,402,356 | ```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for line in lines:
if 'Food' in line:
print(f.next())
openFood()
```
I want it where when it sees a certain header like 'Food' It will print the line below it. I cant seem to make it work. The text file will be like
```
Food
Apple
Cal 120
Protein 12
Fat 13
Carb 23
``` | 2022/08/18 | [
"https://Stackoverflow.com/questions/73402356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19730199/"
] | Just use the index.
```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for i in range(len(lines)-1):
if 'Food' in lines[i]:
print(lines[i+1])
openFood()
``` | Since `readlines()` returns a list of the lines in the file that you can iterate over, you can simply access the subsequent line via its index:
```
l = len(lines)-1
for i in range(l):
if 'Food' in lines[i]:
print(lines[i+1])
``` |
73,402,356 | ```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for line in lines:
if 'Food' in line:
print(f.next())
openFood()
```
I want it where when it sees a certain header like 'Food' It will print the line below it. I cant seem to make it work. The text file will be like
```
Food
Apple
Cal 120
Protein 12
Fat 13
Carb 23
``` | 2022/08/18 | [
"https://Stackoverflow.com/questions/73402356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19730199/"
] | Just use the index.
```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for i in range(len(lines)-1):
if 'Food' in lines[i]:
print(lines[i+1])
openFood()
``` | Method `readlines()` returns list object, you can convert it to an iterator and then use `next` function:
```
def openFood():
with open("FoodList.txt") as f:
lines = iter(f.readlines())
for line in lines:
if 'Food' in line:
print(next(lines))
openFood()
``` |
73,402,356 | ```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for line in lines:
if 'Food' in line:
print(f.next())
openFood()
```
I want it where when it sees a certain header like 'Food' It will print the line below it. I cant seem to make it work. The text file will be like
```
Food
Apple
Cal 120
Protein 12
Fat 13
Carb 23
``` | 2022/08/18 | [
"https://Stackoverflow.com/questions/73402356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19730199/"
] | Just use the index.
```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for i in range(len(lines)-1):
if 'Food' in lines[i]:
print(lines[i+1])
openFood()
``` | Reading a file one line at a time can be beneficial if the file is very large. This code will not load the full file into memory, but only one line at a time:
```
def openFood():
with open("FoodList.txt") as f:
line = f.readline()
while line:
if 'Food' in line:
print(f.readline())
line = f.readline()
openFood()
```
Result:
```
Apple
```
**Note**: This method will be a lot slower for smaller files, than reading the contents into memory using the `readlines()` method. |
73,402,356 | ```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for line in lines:
if 'Food' in line:
print(f.next())
openFood()
```
I want it where when it sees a certain header like 'Food' It will print the line below it. I cant seem to make it work. The text file will be like
```
Food
Apple
Cal 120
Protein 12
Fat 13
Carb 23
``` | 2022/08/18 | [
"https://Stackoverflow.com/questions/73402356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19730199/"
] | Just use the index.
```
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
for i in range(len(lines)-1):
if 'Food' in lines[i]:
print(lines[i+1])
openFood()
``` | `readlines()` reads all the lines in a file and returns a list. You could either read and iterate one line at a time (using `readline()`), or read all the lines and use the list for iteration (using `readlines()`).
Apart from the ways mentioned, you could also use a `bool` like below (I've used `readlines()` here):
```py
def openFood():
with open("FoodList.txt") as f:
lines = f.readlines()
trigger = "Food"
triggerfound = False
for line in lines:
if triggerfound:
print(line)
triggerfound = False
if trigger in line:
triggerfound = True
openFood()
``` |
66,781,577 | I need to print input from the user in reverse order using a function. As a condition, just words (no floats/ int) should be allowed & at least **four** words need to be entered.
e.g.:
How can I help you
--> you help I can How
It should'nt be possible to input: "4 5 6 7" or "There are 2 dogs"
Here's my current code, however I didn't integrate that only strings are allowed so far:
```
def phrase():
while True:
user_input = input("Please insert a phrase: ")
words = user_input.split(" ")
n = len(words)
if n >= 4:
words = words[-1::-1]
phrase_reverse = " ".join(words)
print(phrase_reverse)
else:
print("Please only insert words and at least 4 ")
continue
break
phrase()
```
I tried with `if n<4 and words == str:`, `if n<4 and words != string` etc.. However, that didn't work. Could you please help me solving this issue? Maybe my code is wrong in general. | 2021/03/24 | [
"https://Stackoverflow.com/questions/66781577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15469758/"
] | try to do this
```r
df <- structure(list(animals = c("E1", "E1", "E1",
"E2", "E2", "E2"), period = structure(c(18690,
18697, 18704, 18690, 18697, 18704), class = "Date"), weight1 = c(704,
734, 653, 851, 911, 829), weight2 = c(0, 235, 325, 0, 148,
200)), row.names = c(NA, -6L), class = c("data.table", "data.frame"))
library(dplyr)
df %>%
group_by(animals) %>%
mutate(across(starts_with("weight"), cumsum))
#> # A tibble: 6 x 4
#> # Groups: animals [2]
#> animals period weight1 weight2
#> <chr> <date> <dbl> <dbl>
#> 1 E1 2021-03-04 704 0
#> 2 E1 2021-03-11 1438 235
#> 3 E1 2021-03-18 2091 560
#> 4 E2 2021-03-04 851 0
#> 5 E2 2021-03-11 1762 148
#> 6 E2 2021-03-18 2591 348
```
Created on 2021-03-24 by the [reprex package](https://reprex.tidyverse.org) (v1.0.0)
**or**
`vars <- names(df)[3:4]`
`df %>% group_by(animals) %>% mutate(across(all_of(vars), cumsum))` | You will get an error with what you are trying to do. Once you `group_by(animals)`, there are only three columns that `mutate` can operate on. So you could use:
```
cat %>%
group_by(animals) %>%
mutate(across(2:3, cumsum))
# A tibble: 6 x 4
# Groups: animals [2]
animals period weight1 weight2
<chr> <date> <dbl> <dbl>
1 E1 2021-03-04 704 0
2 E1 2021-03-11 1438 235
3 E1 2021-03-18 2091 560
4 E2 2021-03-04 851 0
5 E2 2021-03-11 1762 148
6 E2 2021-03-18 2591 348
```
But this approach requires you to know what the new indices would be. Better to try something programmatically. If all the columns are weights, you could use:
```
cat %>%
group_by(animals) %>%
mutate(across(starts_with("weight"), cumsum))
```
Or if you just want to operate on all numeric columns:
```
cat %>%
group_by(animals) %>%
mutate(across(where(is.numeric), cumsum))
```
Both of the latter two approaches give your desired output. |
66,781,577 | I need to print input from the user in reverse order using a function. As a condition, just words (no floats/ int) should be allowed & at least **four** words need to be entered.
e.g.:
How can I help you
--> you help I can How
It should'nt be possible to input: "4 5 6 7" or "There are 2 dogs"
Here's my current code, however I didn't integrate that only strings are allowed so far:
```
def phrase():
while True:
user_input = input("Please insert a phrase: ")
words = user_input.split(" ")
n = len(words)
if n >= 4:
words = words[-1::-1]
phrase_reverse = " ".join(words)
print(phrase_reverse)
else:
print("Please only insert words and at least 4 ")
continue
break
phrase()
```
I tried with `if n<4 and words == str:`, `if n<4 and words != string` etc.. However, that didn't work. Could you please help me solving this issue? Maybe my code is wrong in general. | 2021/03/24 | [
"https://Stackoverflow.com/questions/66781577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15469758/"
] | try to do this
```r
df <- structure(list(animals = c("E1", "E1", "E1",
"E2", "E2", "E2"), period = structure(c(18690,
18697, 18704, 18690, 18697, 18704), class = "Date"), weight1 = c(704,
734, 653, 851, 911, 829), weight2 = c(0, 235, 325, 0, 148,
200)), row.names = c(NA, -6L), class = c("data.table", "data.frame"))
library(dplyr)
df %>%
group_by(animals) %>%
mutate(across(starts_with("weight"), cumsum))
#> # A tibble: 6 x 4
#> # Groups: animals [2]
#> animals period weight1 weight2
#> <chr> <date> <dbl> <dbl>
#> 1 E1 2021-03-04 704 0
#> 2 E1 2021-03-11 1438 235
#> 3 E1 2021-03-18 2091 560
#> 4 E2 2021-03-04 851 0
#> 5 E2 2021-03-11 1762 148
#> 6 E2 2021-03-18 2591 348
```
Created on 2021-03-24 by the [reprex package](https://reprex.tidyverse.org) (v1.0.0)
**or**
`vars <- names(df)[3:4]`
`df %>% group_by(animals) %>% mutate(across(all_of(vars), cumsum))` | Base R solution:
```
num_col_idx <- vapply(df, is.numeric, logical(1))
cbind(df[,!num_col_idx],
data.frame(do.call(rbind, lapply(
split(df[, num_col_idx], df$animals), cumsum)), row.names = NULL))
``` |
66,781,577 | I need to print input from the user in reverse order using a function. As a condition, just words (no floats/ int) should be allowed & at least **four** words need to be entered.
e.g.:
How can I help you
--> you help I can How
It should'nt be possible to input: "4 5 6 7" or "There are 2 dogs"
Here's my current code, however I didn't integrate that only strings are allowed so far:
```
def phrase():
while True:
user_input = input("Please insert a phrase: ")
words = user_input.split(" ")
n = len(words)
if n >= 4:
words = words[-1::-1]
phrase_reverse = " ".join(words)
print(phrase_reverse)
else:
print("Please only insert words and at least 4 ")
continue
break
phrase()
```
I tried with `if n<4 and words == str:`, `if n<4 and words != string` etc.. However, that didn't work. Could you please help me solving this issue? Maybe my code is wrong in general. | 2021/03/24 | [
"https://Stackoverflow.com/questions/66781577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15469758/"
] | You will get an error with what you are trying to do. Once you `group_by(animals)`, there are only three columns that `mutate` can operate on. So you could use:
```
cat %>%
group_by(animals) %>%
mutate(across(2:3, cumsum))
# A tibble: 6 x 4
# Groups: animals [2]
animals period weight1 weight2
<chr> <date> <dbl> <dbl>
1 E1 2021-03-04 704 0
2 E1 2021-03-11 1438 235
3 E1 2021-03-18 2091 560
4 E2 2021-03-04 851 0
5 E2 2021-03-11 1762 148
6 E2 2021-03-18 2591 348
```
But this approach requires you to know what the new indices would be. Better to try something programmatically. If all the columns are weights, you could use:
```
cat %>%
group_by(animals) %>%
mutate(across(starts_with("weight"), cumsum))
```
Or if you just want to operate on all numeric columns:
```
cat %>%
group_by(animals) %>%
mutate(across(where(is.numeric), cumsum))
```
Both of the latter two approaches give your desired output. | Base R solution:
```
num_col_idx <- vapply(df, is.numeric, logical(1))
cbind(df[,!num_col_idx],
data.frame(do.call(rbind, lapply(
split(df[, num_col_idx], df$animals), cumsum)), row.names = NULL))
``` |
2,915,307 | I am working on the design and implementation of an iPhone application ( a newbie, but I am getting the hang of it) where a person can download specific contact information about teachers based on their majors.
The information is currently on different edu websites. And I have exported the information into SQLite databases. Is it possible to develop the application that when it is first initiated, it can give the user the option of which particular SQLite database they want for their application?
Or if not, would it be better to merge all the DBs into one DB, and allow the user the option of downloading specific information from the SQLite db.
I see that the db's can be downloaded into an app, but have yet to find a solution where there can be an option to download from different SQLite dbs. Thanks! | 2010/05/26 | [
"https://Stackoverflow.com/questions/2915307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351199/"
] | Mark,
By setting some variable to the database name via an NSString, you should be able to open up any database you want that is bundled with the app when it's submitted. For instance,
declare variable:
`NSString *databaseName;`
set database name:
`databaseName = @"teachersDBNumber1.sql";`
and then when you open it up using the file path, you get the file path for whatever `databaseName` is set to.
If you want to open a different one, just set databaseName to a new string like `databaseName = @"teachersDBNumber2.sql";` find the path for it and then open it up.
You should be able to find a number of good SQLite db tutorials out there for how to open it, read the data, etc. | I would put all the databases on a web server; that way you can update them anytime you want, without redistributing the app. (I do this for fringegenie.com)
Use NSMutableURLRequest to download the file you want and save it. The reason I suggest NSMutableURLRequest is so that you can add the If-Modified-Since header. That way, you can make the request with the date of the last download and the server will respond "304 not modified" if you have not updated it on the server. If there is a new version, the server would give a "200 OK" and send the file.
That said: how big would a single large database be? Likely not very large, so you might as well make one database. Either way: the above is still valid for updates to the big one.
Hope that helps!
PS: Use <http://gusmueller.com/blog/archives/2008/03/fmdb_for_iphone.html> to access you SQLite database. |
15,116,283 | Is it possible to setup WebAPI to Self Host like Nancy.
Such that it hosts an
>
> /api/...
>
>
>
section serving up json and xml responses and hosts a
>
> /content/...
>
>
>
section serving up \*.jpg and \*.html and \*.js
I'm trying to create a self hosting Single Page Application with WebAPI as the backend, and the only thing I have seen that comes close is Nancy.
Is this possible with WebAPI self hosting? | 2013/02/27 | [
"https://Stackoverflow.com/questions/15116283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51841/"
] | Try this:
```
#if __has_feature(objc_arc)
/* ARC is used */
#endif
``` | Try to
```
[player release];
```
It should give you "ARC Restrictions" Errors |
15,116,283 | Is it possible to setup WebAPI to Self Host like Nancy.
Such that it hosts an
>
> /api/...
>
>
>
section serving up json and xml responses and hosts a
>
> /content/...
>
>
>
section serving up \*.jpg and \*.html and \*.js
I'm trying to create a self hosting Single Page Application with WebAPI as the backend, and the only thing I have seen that comes close is Nancy.
Is this possible with WebAPI self hosting? | 2013/02/27 | [
"https://Stackoverflow.com/questions/15116283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51841/"
] | Try this:
```
#if __has_feature(objc_arc)
/* ARC is used */
#endif
``` | You can already tell you're building without ARC: were it enabled, your call to `autorelease` would result in a compiler error. This suggests that your actual problem has nothing to do with ARC, of course -- removing the `autorelease` call may be preventing an object from getting over-released, but it's also quite possibly causing a leak.
Besides that, though: in addition to the other methods that have been suggested so far, you can also find the place in Xcode where one normally controls ARC at the project- or target-wide level. Select your project in the navigator, and in the Build Settings tab, look for "Objective-C Automatic Reference Counting" under "Apple LLVM Compiler 4.2 - Language" (or use the search box at the top to look for "Automatic Reference Counting" or "ARC". If you're using a project somebody else originally set up, you may also wish to check for whether the `-fobjc-arc` or `-fno-objc-arc` flags are set at a per-file level. That's under Build Phases -> Compile Sources when your project and target are selected in Xcode. |
13,707,879 | I have an Internet Explorer Add-On that generates some files in LocalAppDataFolder\Microsoft\Windows\Temporary Internet Files\CompanyName\AddOnName\
I have a WIX installer for the application that I would like to have delete the CompanyName\AddOnName\ folders on both install and uninstall.
I have never used WIX before, and I'm more of a MacOS guy, so all of this stuff is a bit foreign to me. Here is a portion of what I have right now (in my Product.wxs file):
```
<Feature Id="ProductFeature" Title="Company IE Add-On" Level="1" ConfigurableDirectory="INSTALLFOLDER">
<ComponentRef Id="INSTALLFOLDER" />
<ComponentGroupRef Id="ProductComponents" />
<ComponentRef Id="dataDirectory"/>
</Feature>
<Fragment>
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFilesFolder">
<Directory Id="INSTALLFOLDER" Name="Company IE Add-On" >
<Component Id="INSTALLFOLDER" Guid="THERE IS A GUID HERE">
<RemoveFolder On="both" Id="INSTALLFOLDER"/>
<RegistryValue Root="HKLM" Key="Software\[Manufacturer]\[ProductName]" Type="string" Value="Company IE Add-On" />
</Component>
</Directory>
</Directory>
<Directory Id="LocalAppDataFolder">
<Directory Id="Microsoft">
<Directory Id="Windows">
<Directory Id="TempInetFiles" Name="Temporary Internet Files">
<Directory Id="CompanyName">
<Directory Id="AddOnName">
<Component Id="dataDirectory" Guid="E5938D44-5315-43D4-94EC-313F6CDB290B" NeverOverwrite="no" Permanent="no">
<RemoveFolder Id="AddOnName" On="both"/>
</Component>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Fragment>
```
But this is giving me errors like "Component dataDirectory installs to user profile. It must use a registry key under HKCU as its KeyPath, not a file."
And "The directory CompanyName is in the user profile but is not listed in the RemoveFile table."
Any help would be greatly appreciated.
Thanks. | 2012/12/04 | [
"https://Stackoverflow.com/questions/13707879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1506949/"
] | You need to manually initialize the whole array and all levels if multi-leveled:
```
point[] p1 = new point[5];
// Now the whole array contains only null elements
for (int i = 0; i < 5; i++)
p1[i] = new point();
p1[0].x = 1; // Will be okay
``` | ```
point p = new point();
```
It is the `point` object.
```
point[] p1 = new point[5];
```
This `point` object is an 1D array. It holds `point` object references. You should create a `point` object and keep into the array like -
```
for (int i = 0; i < 5; i++)
p1[i] = new point();
p1[0].x = 1;
```
And for a 2D array -
```
point[][] p2 = new point[5][5];
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++)
p1[i][j] = new point();
}
p[0][0].x = 5;
``` |
13,707,879 | I have an Internet Explorer Add-On that generates some files in LocalAppDataFolder\Microsoft\Windows\Temporary Internet Files\CompanyName\AddOnName\
I have a WIX installer for the application that I would like to have delete the CompanyName\AddOnName\ folders on both install and uninstall.
I have never used WIX before, and I'm more of a MacOS guy, so all of this stuff is a bit foreign to me. Here is a portion of what I have right now (in my Product.wxs file):
```
<Feature Id="ProductFeature" Title="Company IE Add-On" Level="1" ConfigurableDirectory="INSTALLFOLDER">
<ComponentRef Id="INSTALLFOLDER" />
<ComponentGroupRef Id="ProductComponents" />
<ComponentRef Id="dataDirectory"/>
</Feature>
<Fragment>
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFilesFolder">
<Directory Id="INSTALLFOLDER" Name="Company IE Add-On" >
<Component Id="INSTALLFOLDER" Guid="THERE IS A GUID HERE">
<RemoveFolder On="both" Id="INSTALLFOLDER"/>
<RegistryValue Root="HKLM" Key="Software\[Manufacturer]\[ProductName]" Type="string" Value="Company IE Add-On" />
</Component>
</Directory>
</Directory>
<Directory Id="LocalAppDataFolder">
<Directory Id="Microsoft">
<Directory Id="Windows">
<Directory Id="TempInetFiles" Name="Temporary Internet Files">
<Directory Id="CompanyName">
<Directory Id="AddOnName">
<Component Id="dataDirectory" Guid="E5938D44-5315-43D4-94EC-313F6CDB290B" NeverOverwrite="no" Permanent="no">
<RemoveFolder Id="AddOnName" On="both"/>
</Component>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Fragment>
```
But this is giving me errors like "Component dataDirectory installs to user profile. It must use a registry key under HKCU as its KeyPath, not a file."
And "The directory CompanyName is in the user profile but is not listed in the RemoveFile table."
Any help would be greatly appreciated.
Thanks. | 2012/12/04 | [
"https://Stackoverflow.com/questions/13707879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1506949/"
] | You need to manually initialize the whole array and all levels if multi-leveled:
```
point[] p1 = new point[5];
// Now the whole array contains only null elements
for (int i = 0; i < 5; i++)
p1[i] = new point();
p1[0].x = 1; // Will be okay
``` | When you construct an array of objects, the array itself is constructed, but the individual elements are initialized to null. So, assuming `Point()` is the constructor you want,
```
Point[] p1 = new Point[5];
for (int i = 0; i < p1.length; ++i) {
p1[i] = new Point();
}
``` |
13,707,879 | I have an Internet Explorer Add-On that generates some files in LocalAppDataFolder\Microsoft\Windows\Temporary Internet Files\CompanyName\AddOnName\
I have a WIX installer for the application that I would like to have delete the CompanyName\AddOnName\ folders on both install and uninstall.
I have never used WIX before, and I'm more of a MacOS guy, so all of this stuff is a bit foreign to me. Here is a portion of what I have right now (in my Product.wxs file):
```
<Feature Id="ProductFeature" Title="Company IE Add-On" Level="1" ConfigurableDirectory="INSTALLFOLDER">
<ComponentRef Id="INSTALLFOLDER" />
<ComponentGroupRef Id="ProductComponents" />
<ComponentRef Id="dataDirectory"/>
</Feature>
<Fragment>
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFilesFolder">
<Directory Id="INSTALLFOLDER" Name="Company IE Add-On" >
<Component Id="INSTALLFOLDER" Guid="THERE IS A GUID HERE">
<RemoveFolder On="both" Id="INSTALLFOLDER"/>
<RegistryValue Root="HKLM" Key="Software\[Manufacturer]\[ProductName]" Type="string" Value="Company IE Add-On" />
</Component>
</Directory>
</Directory>
<Directory Id="LocalAppDataFolder">
<Directory Id="Microsoft">
<Directory Id="Windows">
<Directory Id="TempInetFiles" Name="Temporary Internet Files">
<Directory Id="CompanyName">
<Directory Id="AddOnName">
<Component Id="dataDirectory" Guid="E5938D44-5315-43D4-94EC-313F6CDB290B" NeverOverwrite="no" Permanent="no">
<RemoveFolder Id="AddOnName" On="both"/>
</Component>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Fragment>
```
But this is giving me errors like "Component dataDirectory installs to user profile. It must use a registry key under HKCU as its KeyPath, not a file."
And "The directory CompanyName is in the user profile but is not listed in the RemoveFile table."
Any help would be greatly appreciated.
Thanks. | 2012/12/04 | [
"https://Stackoverflow.com/questions/13707879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1506949/"
] | You need to manually initialize the whole array and all levels if multi-leveled:
```
point[] p1 = new point[5];
// Now the whole array contains only null elements
for (int i = 0; i < 5; i++)
p1[i] = new point();
p1[0].x = 1; // Will be okay
``` | Think of it this way; when you do `new point[5]` (you should follow coding standards and name your classes with an upper case first letter btw.), you get an array with *every element being the default value for that type* (in this case null). The array is initialised, but if you want individual elements of the array to be initialised, you have to do that as well, either in the initial line like this:
```
point[] p1 = new point[] { new point(), new point() };
```
(The above method will create an array with each element already initialised of the minimum size that will accommodate those elements - in this case 2.)
Or by looping through the array and adding the points manually:
```
point[] p1 = new point[5];
for (int i = 0; i < p1.length; i++) {
point[i] = new point();
}
```
Both these concepts can be extended to multi-dimensional arrays:
```
point[] p2 = new point[][] {
new point[] { new point(), new point() }
new point[] { new point(), new point() }
};
```
Or
```
point[] p2 = new point[5][5];
for (int i = 0; i < p2.length; i++) {
for (int j = 0; j < p2[i].length; j++) {
p2[i][j] = new point();
}
}
``` |
13,707,879 | I have an Internet Explorer Add-On that generates some files in LocalAppDataFolder\Microsoft\Windows\Temporary Internet Files\CompanyName\AddOnName\
I have a WIX installer for the application that I would like to have delete the CompanyName\AddOnName\ folders on both install and uninstall.
I have never used WIX before, and I'm more of a MacOS guy, so all of this stuff is a bit foreign to me. Here is a portion of what I have right now (in my Product.wxs file):
```
<Feature Id="ProductFeature" Title="Company IE Add-On" Level="1" ConfigurableDirectory="INSTALLFOLDER">
<ComponentRef Id="INSTALLFOLDER" />
<ComponentGroupRef Id="ProductComponents" />
<ComponentRef Id="dataDirectory"/>
</Feature>
<Fragment>
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFilesFolder">
<Directory Id="INSTALLFOLDER" Name="Company IE Add-On" >
<Component Id="INSTALLFOLDER" Guid="THERE IS A GUID HERE">
<RemoveFolder On="both" Id="INSTALLFOLDER"/>
<RegistryValue Root="HKLM" Key="Software\[Manufacturer]\[ProductName]" Type="string" Value="Company IE Add-On" />
</Component>
</Directory>
</Directory>
<Directory Id="LocalAppDataFolder">
<Directory Id="Microsoft">
<Directory Id="Windows">
<Directory Id="TempInetFiles" Name="Temporary Internet Files">
<Directory Id="CompanyName">
<Directory Id="AddOnName">
<Component Id="dataDirectory" Guid="E5938D44-5315-43D4-94EC-313F6CDB290B" NeverOverwrite="no" Permanent="no">
<RemoveFolder Id="AddOnName" On="both"/>
</Component>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Fragment>
```
But this is giving me errors like "Component dataDirectory installs to user profile. It must use a registry key under HKCU as its KeyPath, not a file."
And "The directory CompanyName is in the user profile but is not listed in the RemoveFile table."
Any help would be greatly appreciated.
Thanks. | 2012/12/04 | [
"https://Stackoverflow.com/questions/13707879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1506949/"
] | Think of it this way; when you do `new point[5]` (you should follow coding standards and name your classes with an upper case first letter btw.), you get an array with *every element being the default value for that type* (in this case null). The array is initialised, but if you want individual elements of the array to be initialised, you have to do that as well, either in the initial line like this:
```
point[] p1 = new point[] { new point(), new point() };
```
(The above method will create an array with each element already initialised of the minimum size that will accommodate those elements - in this case 2.)
Or by looping through the array and adding the points manually:
```
point[] p1 = new point[5];
for (int i = 0; i < p1.length; i++) {
point[i] = new point();
}
```
Both these concepts can be extended to multi-dimensional arrays:
```
point[] p2 = new point[][] {
new point[] { new point(), new point() }
new point[] { new point(), new point() }
};
```
Or
```
point[] p2 = new point[5][5];
for (int i = 0; i < p2.length; i++) {
for (int j = 0; j < p2[i].length; j++) {
p2[i][j] = new point();
}
}
``` | ```
point p = new point();
```
It is the `point` object.
```
point[] p1 = new point[5];
```
This `point` object is an 1D array. It holds `point` object references. You should create a `point` object and keep into the array like -
```
for (int i = 0; i < 5; i++)
p1[i] = new point();
p1[0].x = 1;
```
And for a 2D array -
```
point[][] p2 = new point[5][5];
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++)
p1[i][j] = new point();
}
p[0][0].x = 5;
``` |
13,707,879 | I have an Internet Explorer Add-On that generates some files in LocalAppDataFolder\Microsoft\Windows\Temporary Internet Files\CompanyName\AddOnName\
I have a WIX installer for the application that I would like to have delete the CompanyName\AddOnName\ folders on both install and uninstall.
I have never used WIX before, and I'm more of a MacOS guy, so all of this stuff is a bit foreign to me. Here is a portion of what I have right now (in my Product.wxs file):
```
<Feature Id="ProductFeature" Title="Company IE Add-On" Level="1" ConfigurableDirectory="INSTALLFOLDER">
<ComponentRef Id="INSTALLFOLDER" />
<ComponentGroupRef Id="ProductComponents" />
<ComponentRef Id="dataDirectory"/>
</Feature>
<Fragment>
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="ProgramFilesFolder">
<Directory Id="INSTALLFOLDER" Name="Company IE Add-On" >
<Component Id="INSTALLFOLDER" Guid="THERE IS A GUID HERE">
<RemoveFolder On="both" Id="INSTALLFOLDER"/>
<RegistryValue Root="HKLM" Key="Software\[Manufacturer]\[ProductName]" Type="string" Value="Company IE Add-On" />
</Component>
</Directory>
</Directory>
<Directory Id="LocalAppDataFolder">
<Directory Id="Microsoft">
<Directory Id="Windows">
<Directory Id="TempInetFiles" Name="Temporary Internet Files">
<Directory Id="CompanyName">
<Directory Id="AddOnName">
<Component Id="dataDirectory" Guid="E5938D44-5315-43D4-94EC-313F6CDB290B" NeverOverwrite="no" Permanent="no">
<RemoveFolder Id="AddOnName" On="both"/>
</Component>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Directory>
</Fragment>
```
But this is giving me errors like "Component dataDirectory installs to user profile. It must use a registry key under HKCU as its KeyPath, not a file."
And "The directory CompanyName is in the user profile but is not listed in the RemoveFile table."
Any help would be greatly appreciated.
Thanks. | 2012/12/04 | [
"https://Stackoverflow.com/questions/13707879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1506949/"
] | Think of it this way; when you do `new point[5]` (you should follow coding standards and name your classes with an upper case first letter btw.), you get an array with *every element being the default value for that type* (in this case null). The array is initialised, but if you want individual elements of the array to be initialised, you have to do that as well, either in the initial line like this:
```
point[] p1 = new point[] { new point(), new point() };
```
(The above method will create an array with each element already initialised of the minimum size that will accommodate those elements - in this case 2.)
Or by looping through the array and adding the points manually:
```
point[] p1 = new point[5];
for (int i = 0; i < p1.length; i++) {
point[i] = new point();
}
```
Both these concepts can be extended to multi-dimensional arrays:
```
point[] p2 = new point[][] {
new point[] { new point(), new point() }
new point[] { new point(), new point() }
};
```
Or
```
point[] p2 = new point[5][5];
for (int i = 0; i < p2.length; i++) {
for (int j = 0; j < p2[i].length; j++) {
p2[i][j] = new point();
}
}
``` | When you construct an array of objects, the array itself is constructed, but the individual elements are initialized to null. So, assuming `Point()` is the constructor you want,
```
Point[] p1 = new Point[5];
for (int i = 0; i < p1.length; ++i) {
p1[i] = new Point();
}
``` |
965,610 | I have converted a GWT Eclipse based project to GWT-Maven but when I run the command
```
mvn clean gwt:compile
```
I get an awful lot of errors that specify:
```
[class name].java' is removed due to invalid reference(s):
```
My pom.xml dependencies are:
* dom4j-1.6.1
* commons-httpclient-3.1
* gwt-servlet-1.6.4
* gwt-user-1.6.4
* junit-4.3.1
* gwtext-2.0.5
* GWTx-20070605
What do these errors mean and how do I go about diagnosing the source of the problem? | 2009/06/08 | [
"https://Stackoverflow.com/questions/965610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71561/"
] | That's because the removed class refers to a method that is implemented as part of the GWT
JRE emulation library :
<http://library.igcar.gov.in/readit2007/tutori/tools/gwt-windows-1.4.10/doc/html/jre.html>
If your software makes use of reflection it is very probably the cause. | Typically this means that something higher up in the calling chain was invalid, either because of a compile error, or because it was, or was using, a class that can't be 'compiled' by the GWT compiler. So, if you have class A which references class B, and class B cannot be compiled, class A will be removed due to an invalid reference. |
19,801,679 | I have been working on this issue for several days now and have been unable to find a solution. I will try to be as specific as I can, so that you understand the problem, and include code where necessary.
I have a normal view with a Html.BeginForm (as seen in the first code example) with different controls inside, as well as ValidationMessageFors for some of them. In the model (the second example) we have a couple validation attributes for some of the properties, just like any other MVC setup. The issue is that locally when the page is run, the data-val-required attribute, as well as others, are all added to the html, but when deployed to the production server, these attributes are never added, and so the validation doesn't work. Examples 3 and 4 show this. Example 5 shows the script file declarations.
---
Example 1:
```
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.DocumentID);
@Html.HiddenFor(model => model.TempFilePath);
@Html.HiddenFor(model => model.FileName);
<div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;">
<span style="font-size: 11.5pt; font-weight: bold; float: left;">@ViewBag.Title</span>
</div>
<br />
<div style="margin-left: 15px; margin-right: 15px;">
@Html.ValidationSummary(true)
<h4>Document Name</h4>
@Html.TextBoxFor(model => model.Name, new { id = "DocumentNameEdit" })
@Html.ValidationMessageFor(model => model.Name, "*", new { @style = "font-size:16pt;" })
<br />
<h4>Description</h4>
@Html.TextAreaFor(model => model.Description, new { id = "DocumentDescriptionEdit" })
@Html.ValidationMessageFor(model => model.Description, "*", new { @style = "font-size:16pt;" })
<br />
<input type="button" id="btnSaveDocument" value="Save" />
<input type="button" id="btnClose" value="Close" />
</div>
}
```
Example 2:
```
public class DocumentModel
{
public DocumentModel()
{
Statuses = new List<SelectListItem>()
{
new SelectListItem() {Text="Visible", Value="3"},
new SelectListItem() {Text="Hidden", Value="4"}
};
}
public string DocumentID { get; set; }
[StringLength(255, ErrorMessage = "Please enter no more than 255 characters for the Name.")]
[Required(ErrorMessage="Name is Required") ]
public string Name { get; set; }
[StringLength(2000, ErrorMessage = "Please enter no more than 2000 characters for the Description.")]
[Required(ErrorMessage = "Description is Required")]
public string Description { get; set; }
public string FileName { get; set; }
public int? Status { get; set; }
public string FolderID { get; set; }
public string TempFilePath { get; set; }
public List<dm_LIST_Folders_Result> FolderList { get; set; }
public List<SelectListItem> Statuses { get; set; }
}
```
Example 3 (local):
```
<form method="post" action="/DPS/Documents/CreateEdit" novalidate="novalidate">
<input type="hidden" value="TheCode" name="__RequestVerificationToken">
<input type="hidden" value="" name="DocumentID" id="DocumentID">
<input type="hidden" value="" name="TempFilePath" id="TempFilePath">
<input type="hidden" value="" name="FileName" id="FileName">
<div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;">
<span style="font-size: 11.5pt; font-weight: bold; float: left;">Add New Document</span>
</div>
<br>
<div style="margin-left: 15px; margin-right: 15px;">
<h4>Document Name</h4>
<input type="text" value="" name="Name" id="DocumentNameEdit" data-val-required="Name is Required" data-val-length-max="255" data-val-length="Please enter no more than 255 characters for the Name." data-val="true">
<span style="font-size:16pt;" data-valmsg-replace="false" data-valmsg-for="Name" class="field-validation-valid">*</span>
<br>
<h4>Description</h4>
<textarea rows="2" name="Description" id="DocumentDescriptionEdit" data-val-required="Description is Required" data-val-length-max="2000" data-val-length="Please enter no more than 2000 characters for the Description." data-val="true" cols="20"></textarea>
<span style="font-size:16pt;" data-valmsg-replace="false" data-valmsg-for="Description" class="field-validation-valid">*</span>
<br>
<input type="button" value="Save" id="btnSaveDocument">
<input type="button" value="Close" id="btnClose">
</div>
</form>
```
Example 4 (Production)
```
<form method="post" action="/DM/DPS/Documents/CreateEdit" novalidate="novalidate">
<input type="hidden" value="TheCode" name="__RequestVerificationToken">
<input type="hidden" value="" name="DocumentID" id="DocumentID">
<input type="hidden" value="" name="TempFilePath" id="TempFilePath">
<input type="hidden" value="" name="FileName" id="FileName">
<div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;">
<span style="font-size: 11.5pt; font-weight: bold; float: left;">Add New Document</span>
</div>
<br>
<div style="margin-left: 15px; margin-right: 15px;">
<h4>Document Name</h4>
<input type="text" value="" name="Name" id="Name">
<br>
<h4>Description</h4>
<textarea rows="2" name="Description" id="Description" cols="20"></textarea>
<br>
<input type="button" value="Save" id="btnSaveDocument">
<input type="button" value="Close" id="btnClose">
</div>
</form>
```
Example 5:
```
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
```
---
Just to save on time, here is what I have tried:
1. Adding requestValidationMode="2.0" to the web.config.
2. Adding HtmlHelper.ClientValidationEnabled = true; to the view.
3. Adding HtmlHelper.UnobtrusiveJavaScriptEnabled = true; to the view.
4. Getting the most recent version of jquery and the validate plugin. When it comes to jquery, the most recent is 1.\* series, since we have to support ie8 and can't use 2.\*.
5. Checking if the FormContext is null and creating a new one if it is.
6. Checking if the scripts are being loaded. The answer is yes.
7. Including unobtrusive.ajax. Doesn't help.
8. Setting ClientValidationEnabled to true and UnobtrusiveJavaScriptEnabled to true.
A final note: this is on a Server 2012 machine running IIS 8. This is not a partial view.
Hopefully one of you have run into this. Everywhere I look online says to do one of those 7 options, and none have helped.
Edit:
After looking into things for quite a bit more (couple days since original posting) I have found that the window.mvcClientValidationMetadata property is being set to the correct rullings in the javascript, but the hookups are missing, so when validation is run, the fields aren't actually validated. | 2013/11/06 | [
"https://Stackoverflow.com/questions/19801679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679383/"
] | ```
> df[ sapply(df$Col1,function(x) any(2:3 %in% x)) , ]
Col1 Col2
1 1, 2, 3 1
2 2, 3 2
3 3 3
``` | ```
dfss <- df[ grepl("2" , df[ ,1])| grepl("3" , df[ ,1]) , ]
``` |
19,801,679 | I have been working on this issue for several days now and have been unable to find a solution. I will try to be as specific as I can, so that you understand the problem, and include code where necessary.
I have a normal view with a Html.BeginForm (as seen in the first code example) with different controls inside, as well as ValidationMessageFors for some of them. In the model (the second example) we have a couple validation attributes for some of the properties, just like any other MVC setup. The issue is that locally when the page is run, the data-val-required attribute, as well as others, are all added to the html, but when deployed to the production server, these attributes are never added, and so the validation doesn't work. Examples 3 and 4 show this. Example 5 shows the script file declarations.
---
Example 1:
```
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.DocumentID);
@Html.HiddenFor(model => model.TempFilePath);
@Html.HiddenFor(model => model.FileName);
<div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;">
<span style="font-size: 11.5pt; font-weight: bold; float: left;">@ViewBag.Title</span>
</div>
<br />
<div style="margin-left: 15px; margin-right: 15px;">
@Html.ValidationSummary(true)
<h4>Document Name</h4>
@Html.TextBoxFor(model => model.Name, new { id = "DocumentNameEdit" })
@Html.ValidationMessageFor(model => model.Name, "*", new { @style = "font-size:16pt;" })
<br />
<h4>Description</h4>
@Html.TextAreaFor(model => model.Description, new { id = "DocumentDescriptionEdit" })
@Html.ValidationMessageFor(model => model.Description, "*", new { @style = "font-size:16pt;" })
<br />
<input type="button" id="btnSaveDocument" value="Save" />
<input type="button" id="btnClose" value="Close" />
</div>
}
```
Example 2:
```
public class DocumentModel
{
public DocumentModel()
{
Statuses = new List<SelectListItem>()
{
new SelectListItem() {Text="Visible", Value="3"},
new SelectListItem() {Text="Hidden", Value="4"}
};
}
public string DocumentID { get; set; }
[StringLength(255, ErrorMessage = "Please enter no more than 255 characters for the Name.")]
[Required(ErrorMessage="Name is Required") ]
public string Name { get; set; }
[StringLength(2000, ErrorMessage = "Please enter no more than 2000 characters for the Description.")]
[Required(ErrorMessage = "Description is Required")]
public string Description { get; set; }
public string FileName { get; set; }
public int? Status { get; set; }
public string FolderID { get; set; }
public string TempFilePath { get; set; }
public List<dm_LIST_Folders_Result> FolderList { get; set; }
public List<SelectListItem> Statuses { get; set; }
}
```
Example 3 (local):
```
<form method="post" action="/DPS/Documents/CreateEdit" novalidate="novalidate">
<input type="hidden" value="TheCode" name="__RequestVerificationToken">
<input type="hidden" value="" name="DocumentID" id="DocumentID">
<input type="hidden" value="" name="TempFilePath" id="TempFilePath">
<input type="hidden" value="" name="FileName" id="FileName">
<div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;">
<span style="font-size: 11.5pt; font-weight: bold; float: left;">Add New Document</span>
</div>
<br>
<div style="margin-left: 15px; margin-right: 15px;">
<h4>Document Name</h4>
<input type="text" value="" name="Name" id="DocumentNameEdit" data-val-required="Name is Required" data-val-length-max="255" data-val-length="Please enter no more than 255 characters for the Name." data-val="true">
<span style="font-size:16pt;" data-valmsg-replace="false" data-valmsg-for="Name" class="field-validation-valid">*</span>
<br>
<h4>Description</h4>
<textarea rows="2" name="Description" id="DocumentDescriptionEdit" data-val-required="Description is Required" data-val-length-max="2000" data-val-length="Please enter no more than 2000 characters for the Description." data-val="true" cols="20"></textarea>
<span style="font-size:16pt;" data-valmsg-replace="false" data-valmsg-for="Description" class="field-validation-valid">*</span>
<br>
<input type="button" value="Save" id="btnSaveDocument">
<input type="button" value="Close" id="btnClose">
</div>
</form>
```
Example 4 (Production)
```
<form method="post" action="/DM/DPS/Documents/CreateEdit" novalidate="novalidate">
<input type="hidden" value="TheCode" name="__RequestVerificationToken">
<input type="hidden" value="" name="DocumentID" id="DocumentID">
<input type="hidden" value="" name="TempFilePath" id="TempFilePath">
<input type="hidden" value="" name="FileName" id="FileName">
<div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;">
<span style="font-size: 11.5pt; font-weight: bold; float: left;">Add New Document</span>
</div>
<br>
<div style="margin-left: 15px; margin-right: 15px;">
<h4>Document Name</h4>
<input type="text" value="" name="Name" id="Name">
<br>
<h4>Description</h4>
<textarea rows="2" name="Description" id="Description" cols="20"></textarea>
<br>
<input type="button" value="Save" id="btnSaveDocument">
<input type="button" value="Close" id="btnClose">
</div>
</form>
```
Example 5:
```
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
```
---
Just to save on time, here is what I have tried:
1. Adding requestValidationMode="2.0" to the web.config.
2. Adding HtmlHelper.ClientValidationEnabled = true; to the view.
3. Adding HtmlHelper.UnobtrusiveJavaScriptEnabled = true; to the view.
4. Getting the most recent version of jquery and the validate plugin. When it comes to jquery, the most recent is 1.\* series, since we have to support ie8 and can't use 2.\*.
5. Checking if the FormContext is null and creating a new one if it is.
6. Checking if the scripts are being loaded. The answer is yes.
7. Including unobtrusive.ajax. Doesn't help.
8. Setting ClientValidationEnabled to true and UnobtrusiveJavaScriptEnabled to true.
A final note: this is on a Server 2012 machine running IIS 8. This is not a partial view.
Hopefully one of you have run into this. Everywhere I look online says to do one of those 7 options, and none have helped.
Edit:
After looking into things for quite a bit more (couple days since original posting) I have found that the window.mvcClientValidationMetadata property is being set to the correct rullings in the javascript, but the hookups are missing, so when validation is run, the fields aren't actually validated. | 2013/11/06 | [
"https://Stackoverflow.com/questions/19801679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679383/"
] | ```
> df[ sapply(df$Col1,function(x) any(2:3 %in% x)) , ]
Col1 Col2
1 1, 2, 3 1
2 2, 3 2
3 3 3
``` | In short words: check out `subset` and `grepl` if you are dealing with string.
Here is how I read your data and assume the value type is string, otherwise you can remove the stringsAsFactors and coerce it to whatever type you want.
```
> df <- read.table(text="
+ 1,2,3 1
+ 2,3 2
+ 3 3
+ 4 3
+ 4,5 123", col.names = c("Col1", "Col2"), stringsAsFactors=FALSE)
> # This is the key
> result <- subset(df, grepl("2", Col1) | grepl("3", Col1))
> df
Col1 Col2
1 1,2,3 1
2 2,3 2
3 3 3
4 4 3
5 4,5 123
> result
Col1 Col2
1 1,2,3 1
2 2,3 2
3 3 3
``` |
17,214,150 | I have been trying to test my controllers as per this tutorial -> [Zend Framework 2.1 Unit testing](http://framework.zend.com/manual/2.1/en/tutorials/unittesting.html#testing-actions-with-post)
I have tried every possible variation of the code to send POST or GET data along with the dispatch but the only thing I get back from running the test is "Undefined Index" when I try to access that data from the $\_POST array in the controller.
I am using PHPUnit 3.7.17, Everything else works perfectly except for POST and GET data, I have tried the following code:
```
public function testIndexActionCanBeAccessed() {
$this->getRequest()
->setMethod("POST")
->setPost(new \Zend\Stdlib\Parameters(array('argument' => 'value')));
$response = $this->dispatch('/app/api/index');
$this->assertResponseStatusCode(200);
}
```
AND
```
public function testIndexActionCanBeAccessed() {
$post_data = array("argument" => "value");
$response = $this->dispatch("/app/api/index", "POST", $post_data);
$this->assertResponseStatusCode(200);
}
```
I can't find any help on the web how to fix this issue. Can anyone help out? Any ideas? | 2013/06/20 | [
"https://Stackoverflow.com/questions/17214150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393897/"
] | ```
$p = new Parameters();
$p->set('username','foo');
$p->set('password','bar');
$this->getRequest()->setMethod('POST');
$this->getRequest()->setPost($p);
$this->dispatch('/login');
```
This works for me. The Parameters() constructor doesn't seem to be what you're expecting it to be.
The docs say it takes an array, but I could only get it to work this way. The Stdlib\Parameters() constructor doesn't seem to do anything with the array passed in. | Get/Post data not sending, this issue is related to server, can you check the function use for fetching data from server. |
18,983,906 | Why is time taken to access an element in a non-homogeneous list considered as constant or How is a non-homogeneous list stored in memory in case of python?
In case of a homogeneous list, knowing the type and position, the memory location can be determined but how is it done in case of a non homogeneous list so fast as to consider it as a function of constant time?
Going through this page [Does Python use linked lists for lists? Why is inserting slow?](https://stackoverflow.com/questions/12274060/does-python-use-linked-lists-for-lists-why-is-inserting-slow) I assume it stores elements in contiguous memory locations. | 2013/09/24 | [
"https://Stackoverflow.com/questions/18983906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2216108/"
] | Expand your controller action with a new parameter:
```
public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model, bool newtransferee = false)
```
and check it inside the action. | You could use:
```
if (Request.Form["newtransferee"].ToLower() == "true")
```
or does it work if you write this instead of the manual html?
```
@Html.HiddenFor(model => model.NewTransferee)
``` |
18,983,906 | Why is time taken to access an element in a non-homogeneous list considered as constant or How is a non-homogeneous list stored in memory in case of python?
In case of a homogeneous list, knowing the type and position, the memory location can be determined but how is it done in case of a non homogeneous list so fast as to consider it as a function of constant time?
Going through this page [Does Python use linked lists for lists? Why is inserting slow?](https://stackoverflow.com/questions/12274060/does-python-use-linked-lists-for-lists-why-is-inserting-slow) I assume it stores elements in contiguous memory locations. | 2013/09/24 | [
"https://Stackoverflow.com/questions/18983906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2216108/"
] | If all you need to do is check the value of a boolean, that's just a conditional statement:
```
public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model)
{
if (model.NewTransferee)
{
// do something
}
else
{
// do something else
}
}
```
It's not entirely clear what your goal is though, since your current `return` statement depends on the output of the method that you only want to call conditionally. All code paths will need to return *something*. Maybe like this?:
```
public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model)
{
if (model.NewTransferee)
{
var resolved = SqlDataProvider.ResolveProfileSelectionRequiredJobException(model);
return resolved ? Json("Success") : Json("Failed");
}
else
{
return Json("Success");
}
}
```
Again, I can't know without knowing more about your intended behavior for this action.
It's worth noting that this isn't really an "MVC" thing. At its simplest, this action method is just a method which receives an argument of type `ResolveProfileSelectionRequiredModel`. The conditional statement is just plain C#. All code paths returning a value is plain C#. The only thing "MVC" about this method is that it's returning a `JsonResult`.
---
**Edit:** I just noticed... The value you're looking for is on the `CreateTransferee` model, but your controller is receiving a `ResolveProfileSelectionRequiredModel`? Is that value on the `ResolveProfileSelectionRequiredModel`? They seem to be very similar. If it's not on that model, you can either add it to that model or use @Raidri's approach to add it as an explicit parameter to the controller action. | Expand your controller action with a new parameter:
```
public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model, bool newtransferee = false)
```
and check it inside the action. |
18,983,906 | Why is time taken to access an element in a non-homogeneous list considered as constant or How is a non-homogeneous list stored in memory in case of python?
In case of a homogeneous list, knowing the type and position, the memory location can be determined but how is it done in case of a non homogeneous list so fast as to consider it as a function of constant time?
Going through this page [Does Python use linked lists for lists? Why is inserting slow?](https://stackoverflow.com/questions/12274060/does-python-use-linked-lists-for-lists-why-is-inserting-slow) I assume it stores elements in contiguous memory locations. | 2013/09/24 | [
"https://Stackoverflow.com/questions/18983906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2216108/"
] | If all you need to do is check the value of a boolean, that's just a conditional statement:
```
public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model)
{
if (model.NewTransferee)
{
// do something
}
else
{
// do something else
}
}
```
It's not entirely clear what your goal is though, since your current `return` statement depends on the output of the method that you only want to call conditionally. All code paths will need to return *something*. Maybe like this?:
```
public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model)
{
if (model.NewTransferee)
{
var resolved = SqlDataProvider.ResolveProfileSelectionRequiredJobException(model);
return resolved ? Json("Success") : Json("Failed");
}
else
{
return Json("Success");
}
}
```
Again, I can't know without knowing more about your intended behavior for this action.
It's worth noting that this isn't really an "MVC" thing. At its simplest, this action method is just a method which receives an argument of type `ResolveProfileSelectionRequiredModel`. The conditional statement is just plain C#. All code paths returning a value is plain C#. The only thing "MVC" about this method is that it's returning a `JsonResult`.
---
**Edit:** I just noticed... The value you're looking for is on the `CreateTransferee` model, but your controller is receiving a `ResolveProfileSelectionRequiredModel`? Is that value on the `ResolveProfileSelectionRequiredModel`? They seem to be very similar. If it's not on that model, you can either add it to that model or use @Raidri's approach to add it as an explicit parameter to the controller action. | You could use:
```
if (Request.Form["newtransferee"].ToLower() == "true")
```
or does it work if you write this instead of the manual html?
```
@Html.HiddenFor(model => model.NewTransferee)
``` |
84,410 | In the second theme of the recapitulation of Beethoven's Pathetique Sonata where the bass line goes into the treble clef and the bass register becomes part of the melody, I see the marking ***ben tenuto il basso***. I tried looking it up last night and couldn't find an answer. Google translate said that this means "well held down", but that wouldn't be the musical definition, I know it wouldn't.
From finding out that ben in Italian means well and my knowledge of Italian musical terms, here is the best that I could translate it to:
>
> Well held in the bass
>
>
>
So from that translation, here is what I think Beethoven is trying to get across with that marking:
>
> Hold the bass notes as though there was a fermata in the bass, in other words, longer than your normal tenuto, while the melody is an accented staccato.
>
>
>
**Is that what Beethoven is trying to get across with the marking?**
EDIT: Here is what I see in the Schirmer edition, or whenever I look at Sonata Album Book II published by the same people. I use the Schirmer edition, partly because it makes it so easy to see where the recapitulation starts. But here is what I see in that edition:
[](https://i.stack.imgur.com/klol4.png)
As you can see, ***ben tenuto il basso*** is clearly marked here under the same measure that has the poco crescendo marking. | 2019/04/30 | [
"https://music.stackexchange.com/questions/84410",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/9749/"
] | Finding the edition the OP referred to (<https://imslp.org/wiki/Special:ImagefromIndex/11070/torat>) didn't take long.
It's the sort of marking that always reminds me of a John Cleese joke in *Fawlty Towers*: "You should be on *Mastermind*. Specialist subject, the bleedin' obvious."
Looking through the editors of editions on IMSPL to find somebody full of their own self importance who might write such a thing, my first guess was correct: Godowsky - the guy who rewrote 57 variations on the Chopin Etudes, because he didn't understand *why* the originals were so already so difficult, being unable to see past the mere technical problem of pressing down the piano keys in the right order.
So, it means absolutely nothing. As pidgin-Italian, it translates as something like "that bass line should be well held down, man!!"
The only logic for it that I can see is that Godowsky (not Beethoven!) decided the four notes in question ought to be slurred in two pairs, but playing the slurs that he invented for no reason is hard, so he decided to add some words saying "yes I really do mean this".
Throw that edition away, and look at what *Beethoven* wrote. When *he* adds some textual instructions, they are always both practical and important.
While I was writing this the OP posted an picture which confirms the source as the Godowsky edition. Schirmer just republish anything that is out of copyright, without bothering to say where they got it from. Before the internet, Schirmer editions were cheap, but mostly garbage. Now you can get better sources from the internet for free in sites like IMSLP, they are just garbage. | It simply means you need to play the bass tenuto.
In this case I'd say he means the bass line in the treble clef, but it would help to see the relevant passage.
(To me tenuto and fermata are quite different, i.e. I wouldn't describe it like that. Tenuto means you should hold the note to the maximum full value, but definitely not exceed it. While fermata *does* give you that liberty - or rather even implores you to do so) |
20,834,941 | My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20834941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910583/"
] | You can see an example of something similar in the Routing guide:
<http://guides.rubyonrails.org/routing.html#naming-routes>
`get 'exit', to: 'sessions#destroy', as: :logout`
You could use:
`get 'about_us', to: 'main#about_us'` | you can use "path": option
```
resources :main, path: "/", only: [] do
get :about_us
end
```
Now, all actions in main controller will be accessed directly without controller name in url
eg: localhost:3000/about\_us |
20,834,941 | My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20834941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910583/"
] | you can use "path": option
```
resources :main, path: "/", only: [] do
get :about_us
end
```
Now, all actions in main controller will be accessed directly without controller name in url
eg: localhost:3000/about\_us | I settled on this...
```
MainController.action_methods.each{ |a| a = a.to_s; match a => 'main#'+a}
```
Private actions are not accessible, but all others are |
20,834,941 | My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20834941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910583/"
] | You can see an example of something similar in the Routing guide:
<http://guides.rubyonrails.org/routing.html#naming-routes>
`get 'exit', to: 'sessions#destroy', as: :logout`
You could use:
`get 'about_us', to: 'main#about_us'` | Try:
```
resources :main,:path => '',:only => []
```
Now all actions of MainController can be accessed without controller name main in the url. |
20,834,941 | My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20834941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910583/"
] | You can see an example of something similar in the Routing guide:
<http://guides.rubyonrails.org/routing.html#naming-routes>
`get 'exit', to: 'sessions#destroy', as: :logout`
You could use:
`get 'about_us', to: 'main#about_us'` | I settled on this...
```
MainController.action_methods.each{ |a| a = a.to_s; match a => 'main#'+a}
```
Private actions are not accessible, but all others are |
20,834,941 | My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20834941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910583/"
] | You can see an example of something similar in the Routing guide:
<http://guides.rubyonrails.org/routing.html#naming-routes>
`get 'exit', to: 'sessions#destroy', as: :logout`
You could use:
`get 'about_us', to: 'main#about_us'` | match 'about\_us', :to => 'MainController#about\_us' |
20,834,941 | My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20834941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910583/"
] | Try:
```
resources :main,:path => '',:only => []
```
Now all actions of MainController can be accessed without controller name main in the url. | I settled on this...
```
MainController.action_methods.each{ |a| a = a.to_s; match a => 'main#'+a}
```
Private actions are not accessible, but all others are |
20,834,941 | My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it? | 2013/12/30 | [
"https://Stackoverflow.com/questions/20834941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910583/"
] | match 'about\_us', :to => 'MainController#about\_us' | I settled on this...
```
MainController.action_methods.each{ |a| a = a.to_s; match a => 'main#'+a}
```
Private actions are not accessible, but all others are |
3,900,172 | >
> $\textbf{Problem}$: An athletic facility has $5$ tennis courts. Pairs of players arrive at the
> courts and use a court for an exponentially distributed time with mean $40$ minutes.
> Suppose a pair of players arrives and finds all courts busy and k other pairs waiting in
> queue. What is the expected waiting time to get a court?
>
>
>
>
> $\textbf{Answer}$: As long as the pair of players are waiting, all five courts are occupied by other players. When all five courts are occupied, the time until a court is freed up is exponentially distributed with mean $40/5=8 $ minutes. For our pair of players to get a court, a court must be freed up $k+1$ times. Thus, the expected waiting time is $8(k + 1)$.
>
>
>
The issue that I'm having in understanding is why does "The time until a court is freed up is exponentially distributed with mean $40/5=8$ minutes" rather than simply $40$ minutes. Since every court is independent and using the memoryless property.
On the contrary, if I look at $$Z=min(X\_{1}, X\_{2}, X\_{3}, X\_{4}, X\_{5})$$. where $X\_{i}$ is time taken by a pair to play in court $i$ and is exponentially distributed time with mean $40$ minutes.
Then $Z$ itself becomes and exponentially distributed with mean $40\*5 = 200$ minutes.
I am unable to understand it intuitively. Any help is appreciated. | 2020/11/09 | [
"https://math.stackexchange.com/questions/3900172",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/792588/"
] | Each $X\_i$ has rate $\lambda=\frac1{40}$ (with minutes as the time unit), so $Z$ has $\lambda=\frac5{40}=\frac18$ for a mean of $8$ minutes. You have applied the formula incorrectly: the rates add, not the means. | Let $Z=\min(X\_1,...,X\_5)$.
We have $X\_1=Z$ with probability ${\large{\frac{1}{5}}}$, and by the memoryless property we have
$$
E[X\_1-Z{\,\mid\,}X\_1 > Z]=40
$$
hence
\begin{align\*}
&
E[X\_1-Z]
=
\left({\small{\frac{1}{5}}}\right)\!(0)
+
\left({\small{\frac{4}{5}}}\right)\!(40)
\\[4pt]
\implies\;&
E[X\_1-Z]=32
\\[4pt]
\implies\;&
E[X\_1]-E[Z]=32
\\[4pt]
\implies\;&
40-E[Z]=32
\\[4pt]
\implies\;&
E[Z]=8
\\[4pt]
\end{align\*} |
379,117 | I just set up nginx as a http/https reverse proxy and it worked well.
After that, I realized that for some domains ftp services are available. I was able to install ftp.proxy and it also works well, although it just handles one single domain.
My question is: Is there any possibility to reverse proxy ftp services based on hostnames/domains like I do with nginx for http? | 2012/04/13 | [
"https://serverfault.com/questions/379117",
"https://serverfault.com",
"https://serverfault.com/users/81551/"
] | There's a G-WAN [rewrite example here](http://gwan.com/developers#handler) (look at the second handler source code, the first handler example illustrates FLV pseudo-streaming). | You can Use a virtual host, or even an alias, see the [G-WAN FAQs](http://gwan.com/faq#listener).
For more elaborate rewrites, you can use a handler, some examples are provided in the download archive. |
46,565,928 | I am new to Matlab and i ran into this problem:
I have a function that takes 3 doubles as arguments and outputs a single double e.g.:
```
function l = myFunct(a,b,c)
l = a^2*b^2 + (2*(c^2 - b) / (a - sqrt(c)))
end
```
Now, I need to plot the result of this function for intervals:
a = b = [0.1,3], while keeping c = 2.
I managed to do this for 2d plot of a single variable, but not for 3d...
```
R = 0:0.01:2;
fun = @(x) myFunct(0.2, x, 3);
B = arrayfun(fun,R);
plot(R, B);
```
Could you please help and explain? | 2017/10/04 | [
"https://Stackoverflow.com/questions/46565928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8720210/"
] | Add `ml-auto` class to `navbar-nav` along with `mr-auto` | You can add **margin-left: auto** by adding *mr-auto* to *navbar* to center the searchbar in the navbar. **But** it won't be at the center of the header, since there is another component beside the navbar.
```
<ul class="navbar-nav mr-auto ml-auto">
```
```html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-expand-lg navbar-light bg-light navbar-custom">
<a class="navbar-brand" href="#">ICT-Hulp(Waarschijnelijk logo)</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto ml-auto">
<li class="nav-item">
<div class="justify-content-md-center">
<form class="form-inline my-2 my-lg-0 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Zoeken..." aria-label="Search" style="width: 600px;">
<button class="btn btn-info my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</li>
</ul>
</div>
</nav>
``` |
12,739,297 | In Global Config in joomla have 2 caching is conservative and progressive, what is difference both ? | 2012/10/05 | [
"https://Stackoverflow.com/questions/12739297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/840461/"
] | >
> **Conservative caching** is the standard type of caching. Here’s how it works:
>
>
> * A visitor visits a page on your website.
> * Joomla checks if there is a non-expired version of that page in its cache directory.
> * If the cached page exists (and it’s not expired), then Joomla will serve it to the visitor – otherwise, a cached version of the page is created, and that cached version will be served to the visitor, and to every other consequent visitor, as long as it’s (by “it” we mean the page) not expired.
>
>
> The above scenario is typical and is how most developers implement
> caching.
>
>
> **Progressive caching** works the following way:
>
>
> * A visitor visits a page on your website.
> * Joomla checks if a cached version of that page exists for that visitor and it’s not yet expired.
> * If that cached page exists, then it’ll be served to the visitor, otherwise, Joomla will create the cached page for that specific visitor and then will serve it to him.
> * If another visitor (who has never been on that page) visits that page, then Joomla will not serve the cached page of the previous visitor, instead, it will create a cached version of that page
>
> specifically for that user, and then serves it to him.
>
>
> As you can see, progressive caching only offers a performance
> improvement if the same visitor visits the same page within the
> lifetime of the cached version of the page. In most scenarios,
> progressive caching results in a huge performance hit that is far
> worse than disabling cache, simply because for nearly every visit,
> Joomla has to process the request, create the cached version of the
> page, and then serve the page to the visitor (instead of just
> processing the request and serving the page in the scenario where
> cache is disabled). Oh, and don’t forget about all the cache files
> generated by Joomla – you can only imagine how many of these files you
> will have in your cache folder if you have a high traffic news website
> (that has many pages).
>
>
> Now you might wonder, under which circumstances is progressive caching
> useful? Well, imagine that you have a video website (similar to
> youtube). You want to show each visitor customized pages based on his
> location and/or browser settings and/or plugins installed. So, for
> every page that the visitors loads, you use this information to
> generate a customized version of that page and you cache it. If the
> visitor visits that same page again, then Joomla doesn’t need to redo
> the work to generate the customized page.
>
>
> Of course, there are many scenarios under which progressive caching is
> really useful, but in our opinion, progressive caching should only be
> considered if the website receives many visitors and if those visitors
> are mostly repeat visitors. Using it in other cases will cause a
> significant hit on the website’s performance.
>
>
>
Extracted from [here](http://www.itoctopus.com/why-progressive-caching-in-joomla-should-be-avoided-in-most-cases). | For **Unique cache per visitor**
* **Conservative cache** shows all visitors to your site the same exact cached content.
* **Progressive caching** however caches the content for each user uniquely.
From the [link](http://www.inmotionhosting.com/support/edu/joomla-25/caching/global-module-caching) Provided by @Tornado's comment |
12,739,297 | In Global Config in joomla have 2 caching is conservative and progressive, what is difference both ? | 2012/10/05 | [
"https://Stackoverflow.com/questions/12739297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/840461/"
] | For **Unique cache per visitor**
* **Conservative cache** shows all visitors to your site the same exact cached content.
* **Progressive caching** however caches the content for each user uniquely.
From the [link](http://www.inmotionhosting.com/support/edu/joomla-25/caching/global-module-caching) Provided by @Tornado's comment | Progressive caching works just like conservative caching with a difference that buffers are updated progressively.
If you look at the render function in JApplicationCMS (where progressive caching is set), you will find that its not applicable to logged in users.
<https://github.com/joomla/joomla-cms/blob/staging/libraries/cms/application/cms.php>
```
if ($this->isSite() && $this->get('caching') && $this->get('caching', 2) == 2 && !JFactory::getUser()->get('id'))
{
$caching = true;
}
```
Further if you dump the cache id's for the same page across browsers or ips you will get the same cache id's.
The typical work of progressive caching happens in JCache's getWorkarounds and setWorkarounds. However beware, the cbuffers can get unwieldy large at times causing issues. |
12,739,297 | In Global Config in joomla have 2 caching is conservative and progressive, what is difference both ? | 2012/10/05 | [
"https://Stackoverflow.com/questions/12739297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/840461/"
] | >
> **Conservative caching** is the standard type of caching. Here’s how it works:
>
>
> * A visitor visits a page on your website.
> * Joomla checks if there is a non-expired version of that page in its cache directory.
> * If the cached page exists (and it’s not expired), then Joomla will serve it to the visitor – otherwise, a cached version of the page is created, and that cached version will be served to the visitor, and to every other consequent visitor, as long as it’s (by “it” we mean the page) not expired.
>
>
> The above scenario is typical and is how most developers implement
> caching.
>
>
> **Progressive caching** works the following way:
>
>
> * A visitor visits a page on your website.
> * Joomla checks if a cached version of that page exists for that visitor and it’s not yet expired.
> * If that cached page exists, then it’ll be served to the visitor, otherwise, Joomla will create the cached page for that specific visitor and then will serve it to him.
> * If another visitor (who has never been on that page) visits that page, then Joomla will not serve the cached page of the previous visitor, instead, it will create a cached version of that page
>
> specifically for that user, and then serves it to him.
>
>
> As you can see, progressive caching only offers a performance
> improvement if the same visitor visits the same page within the
> lifetime of the cached version of the page. In most scenarios,
> progressive caching results in a huge performance hit that is far
> worse than disabling cache, simply because for nearly every visit,
> Joomla has to process the request, create the cached version of the
> page, and then serve the page to the visitor (instead of just
> processing the request and serving the page in the scenario where
> cache is disabled). Oh, and don’t forget about all the cache files
> generated by Joomla – you can only imagine how many of these files you
> will have in your cache folder if you have a high traffic news website
> (that has many pages).
>
>
> Now you might wonder, under which circumstances is progressive caching
> useful? Well, imagine that you have a video website (similar to
> youtube). You want to show each visitor customized pages based on his
> location and/or browser settings and/or plugins installed. So, for
> every page that the visitors loads, you use this information to
> generate a customized version of that page and you cache it. If the
> visitor visits that same page again, then Joomla doesn’t need to redo
> the work to generate the customized page.
>
>
> Of course, there are many scenarios under which progressive caching is
> really useful, but in our opinion, progressive caching should only be
> considered if the website receives many visitors and if those visitors
> are mostly repeat visitors. Using it in other cases will cause a
> significant hit on the website’s performance.
>
>
>
Extracted from [here](http://www.itoctopus.com/why-progressive-caching-in-joomla-should-be-avoided-in-most-cases). | Progressive caching works just like conservative caching with a difference that buffers are updated progressively.
If you look at the render function in JApplicationCMS (where progressive caching is set), you will find that its not applicable to logged in users.
<https://github.com/joomla/joomla-cms/blob/staging/libraries/cms/application/cms.php>
```
if ($this->isSite() && $this->get('caching') && $this->get('caching', 2) == 2 && !JFactory::getUser()->get('id'))
{
$caching = true;
}
```
Further if you dump the cache id's for the same page across browsers or ips you will get the same cache id's.
The typical work of progressive caching happens in JCache's getWorkarounds and setWorkarounds. However beware, the cbuffers can get unwieldy large at times causing issues. |
16,701,666 | Please note this is not the same question as mentioned above since XML escaping to preserve codepoints is possible.
I have a UTF-8 XML file which I can send via HTTP to some other system which I have no control over. For whatever crazy reason it decides to convert it to ISO-8859-1 loosing many Unicode characters and replacing them with '?'. This system then sends someone else this converted XML document.
How in Java on the sending side can I escape any arbitrary XML with non ASCII codepoints so that they survive this intermediary system and can still be decoded correctly by the endpoint?
A --(UTF-8)--> B --(ISO-8859-1)--> C (Decodes to internal Unicode representation).
```
import java.text.Normalizer;
import java.text.Normalizer.Form;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.apache.commons.lang3.text.translate.NumericEntityEscaper;
public class Test {
private static CharSequenceTranslator translator = StringEscapeUtils.ESCAPE_XML
.with(NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE));
public static void main(String[] args) {
String s = "<note>\n<to>Tove</to>\n<from>Jani</from>\n<heading>Reminder</heading>\n<body>Don't forget me this weekend!test☠ä</body>\n</note>";
String xmlEscapedS = xmlToRobustXml(s);
System.out.println(xmlEscapedS);
}
/**
* @param s
* @return
*/
public static String xmlToRobustXml(String s) {
s = Normalizer.normalize(s, Form.NFC);
String xmlEscapedS = translator.translate(s);
return xmlEscapedS;
}
}
```
I tried this but it escapes everything.
```
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!test☠ä</body>
</note>
``` | 2013/05/22 | [
"https://Stackoverflow.com/questions/16701666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1482815/"
] | Here are three standard API methods to produce ISO-8859-1 encoded documents.
Using the [StAX API](http://docs.oracle.com/javase/7/docs/api/javax/xml/stream/package-summary.html):
```
// output stream
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// transcode
StringReader xml = new StringReader("<x>pi: \u03A0</x>");
XMLEventReader reader = XMLInputFactory.newFactory().createXMLEventReader(
xml);
XMLEventWriter writer = XMLOutputFactory.newFactory().createXMLEventWriter(
buffer, "ISO-8859-1");
try {
writer.add(reader);
} finally {
writer.close();
}
// proof
String decoded = new String(buffer.toByteArray(),
Charset.forName("ISO-8859-1"));
System.out.println(decoded);
```
Using the [DOM API](http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/package-frame.html):
```
// output stream
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// create XML DOM
InputSource src = new InputSource(new StringReader("<x>pi: \u03A0</x>"));
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(src);
// serialize
DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation();
LSOutput out = impl.createLSOutput();
out.setEncoding("ISO-8859-1");
out.setByteStream(buffer);
impl.createLSSerializer().write(doc, out);
// proof
String decoded = new String(buffer.toByteArray(),
Charset.forName("ISO-8859-1"));
System.out.println(decoded);
```
Using the [transform package](http://docs.oracle.com/javase/7/docs/api/javax/xml/transform/package-frame.html):
```
// output stream
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// transformation
StreamSource src = new StreamSource(new StringReader("<x>pi: \u03A0</x>"));
StreamResult res = new StreamResult(buffer);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
transformer.transform(src, res);
// proof
String decoded = new String(buffer.toByteArray(),
Charset.forName("ISO-8859-1"));
System.out.println(decoded);
```
Which you would use depends on your use case; the StAX API is probably the most efficient.
All this sample code will emit documents equivalent to:
```
<?xml version="1.0"?><x>pi: Π</x>
``` | The Unicode code points above 127 can be encoded as numeric entities like `{` using the following:
From Apache commons [StringEscapeUtils](http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html#escapeXml%28java.lang.String%29). Read the javadoc, by default `escapeXML` does not convert to numeric entities.
```
StringEscapeUtils.ESCAPE_XML
.with(NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE));
```
BTW you also try sending the original XML using a header `Content-Type: application/x-xml`, so binary transfer. |
22,702 | *This question continues story of [one ESA vs NASA battle on Mars](https://worldbuilding.stackexchange.com/questions/22573/how-will-my-nerdy-mars-astronauts-do-battle-between-their-colonies). I tried to put everything important into this question. Also, being from Europe, I took ESA side as the one winning:*
* **Year:** 2100ish
* **Mars:** Two 'surface,' permanent scientific research colonies with a little over 100 scientists and engineers in each with an
additional support crew (geologist, psychologist & medical, etc.) to
about 150 people each, with the common utilities, agrarian setups,
etc.
The nerds in Colony ESA have just had it with Colony NASA, about 100km across [Elysium](http://maps.google.com/mars/#lat=0.522717&lon=534.222794&zoom=6) plains, and they went there and did burst their bubble. (Literally)
**The question: How will Earth handle this?**
It is safe to assume that both colonies are under constant surveillance from ground control. It is also safe to assume that NASA and ESA are still "friends" and the setup of having two colonies instead one is because they got great fundings - so why not build two?
It is also safe to assume, that there is some crew rotation (people and material are being exchanged on regular basis)
[](https://i.stack.imgur.com/2L6GD.jpg)
The time is Battle + 15 minutes. Ground control of both teams is getting first shocking images of whats happening on Mars. And you know that until they receive first orders, everything will be over...
What happens next?
**Edit:** Trying to make the question less opinion based: Assume there is only one NASA+ESA joint resupply mission and next one is about to launch, arriving to Mars in half a year.
Usually this resuply mission has about 7 months of food + oxygen + water supplies for all the crew + 12 people to go on rotation mission (6 NASA, 6 ESA). The resuply frequency is 6 months.
So, lets scope the question like this: Who do I send out in next resupply mission? (profession wise obviously). And how has NASA + ESA proceed is they (obviously) want Mars mission to continue? | 2015/08/16 | [
"https://worldbuilding.stackexchange.com/questions/22702",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/2071/"
] | **NASA/ESA Repsonse**
*Surprise*
The officials should be shocked. After Houston kept telling the astronauts, for example, to 'just learn to get along,' they will have decided to take things into their own hands and through a series of discussions in 'safe' spaces or on notes of paper, they planned their battles. It wasn't until T minus an-hour-or-so before they departed that NASA/ESA realized their scientists weren't going to take it any more.
*(Short-term) Attempt at Cover-up*
This is a situation with precedent. Just as whenever there's a situation (riots or whatever), there's a scramble.
I don't think it would be an attempt to cover-up permanently, because this will obviously not be successful, but governments and private companies, and even kids who broke a window with a baseball try to keep it a secret until they can think what to do. In this scenario, frantic phone calls are made between agencies internally and among the countries involved.
"Hi, Mr. President, we have a situation..."
"They what-the-WHAT?"
*Damage Control*
Heads of agencies, involved companies and government officials are scrambling to figure out what to do. It's hard to punish an employee who is a permanent colonist on a planet 140 million miles away. The press liasons are woken from bed to get onto the case and make sure that the spin is just so: the actions were unprecedented, atypical, and will be handled immediately.
*Finger Pointing*
This seems inevitable. Everyone wants to assign a cause to a situation, to help understand it, and there will be no end to this. It wouldn't be between the two agencies, rather between sub-sets of organizations and governments. The pressure put on the nerds by a rigorous schedule, or even petty things (the geologists from NASA were not allowed to study an area, because ESA claimed the area with a likelihood for astonishing discovery, for example).
The economic and political effects can be complex. However, property destruction and harm to individuals are often immediately measurable and will be assigned. In order to separate government responsibility from the actions of the nerds, I speculate that they would assign this as a 'riot,' and not politically motivated or assigned actions.
**Re-route Supplies and Relief Personnel**
The relief supplies would have to be enhanced by shifting some of the weight of long-term supplies (soils & plants for future planting, laboratory equipment, etc.) with that of equipment and personnel to either return the remaining scientists or to contain them until they can be returned.
This could include mechanisms for locating them (the nerds that won the battle know not to hang around, and have contingency for this), and then disabling their mobility.
**Aside: Public Outcry**
Phone calls will be made, statements will be made. People who already have disdain for space exploration will use this forever as an argument to defund future space exploration, manned or otherwise. Also, so much for childrens' role models. | While there would be the usual coverup/deflect/finger pointing aspect of bureaucratic and political response, I suspect that there would be another level of response, which is the sheer bloody mindedness of people.
Many people will have been invested in the project, and of course the astronauts will have been celebrities in certain social media circles (as well as real celebrities in other aspects of their lives), as well as having lots of family and influential friends. There will be a massive outcry for something to be done to avenge the loss of so many lives and so much equipment, not to mention the political capital that had been expended in setting up the expedition in the first place.
I suspect the joint resupply venture will be the first thing scuttled, as each side accuses the other of manipulating the manifest to the benefit/detriment of one group of astronauts. Certainly the astronauts themselves slated for the mission are going to have some grave doubts about the other parties aboard; if two teams of supposedly complimentary astronauts on Mars went to war, resulting in the destruction of a base and the deaths of many astronauts, then what could possibly happen aboard the resupply ship during its long transfer orbit to Mars? A secondary consideration is that one base has been destroyed, so any surviving astronauts will be busy trying to do a "Mark Watney" and need help as fast as possible. An unmanned supply vessel launched on a high energy trajectory transfer will be needed ASAP, and since you stipulate that the NASA side lost, NASA will be pulling *all* their resources and technical ability to the task and not to a joint resupply mission. (If the ESA side had lost, the same factors would apply).
The anger would also spill over on the Earth at many levels. Boycotts against products made in the EU would begin an informal trade war between the two sides, and the EU would also lose American tourism and other forms of exchange, creating economic disruptions. More formal actions against the EU would be called for by politicians and political groups eager to hitch their wagon to a popular cause (and various parties in the EU would be calling for the same against the US, leading to a situation where parties like the UKIP, Front National, Golden Dawn and other more or less radical parties whip up popular support among the European voters).
Depending on how far the agitation goes, this might provoke more robust actions between the two governments. Even if it does not by itself, nations like Russia and China will seek to inflame the situation through "Active Measures" (propaganda and other campaigns to mould public opinion in a desired direction), potentially causing the same effect. While the Americans might not want to kill the ESA astronauts in cold blood, they could make it very clear that the ESA will not be launching *anything* until the United States is satisfied that certain conditions are met (most likely the arrival of the relief ship and resupply of the American astronauts stranded on Mars).
At this point, the huge resource mismatch between the United States and the EU will begin to be felt. The US can put lots of pressure on the EU through lots of different means (political, military and economic), and as noted, NASA and the private US space industry can respond to directly support their astronauts on Mars by sending relief supplies by high energy transfer orbits. The ESA has only one supplier to build extra rockets (unless they decide to hire the Russians or Chinese to build rockets for them, which would be a nasty can of political worms to open), while the United States can hire SpaceX, Orbital, Boeing, Lockheed-Martin, Northrop-Grunmann and and entire second tier of would be rocket makers to crank out orbital vehicles and infrastructure to not only rescue the US astronauts, but establish a robust permanent presence on Mars as well (even if the US government isn't explicitly interested in doing so, Elon Musk has openly stated that this is *his* goal; he is hardly going to turn down a gilded opportunity to fulfill his life dream).
Winning the battle and losing the war is alway a risk when you take up arms, and the end results of armed conflict are rarely what either side envisioned before the start of the conflict. The only potentially "good" outcome of all this is a robust Martian colony is now possible, and the infrastructure for much larger scale space exploration is now in place. I suspect that the second order effect will be space colonies will have a robust protective service attached to prevent this sort of thing from happening again, ranging from private security forces hired by the colonists to actual contingents of national military forces brought by the colonizing nations themselves. |
22,702 | *This question continues story of [one ESA vs NASA battle on Mars](https://worldbuilding.stackexchange.com/questions/22573/how-will-my-nerdy-mars-astronauts-do-battle-between-their-colonies). I tried to put everything important into this question. Also, being from Europe, I took ESA side as the one winning:*
* **Year:** 2100ish
* **Mars:** Two 'surface,' permanent scientific research colonies with a little over 100 scientists and engineers in each with an
additional support crew (geologist, psychologist & medical, etc.) to
about 150 people each, with the common utilities, agrarian setups,
etc.
The nerds in Colony ESA have just had it with Colony NASA, about 100km across [Elysium](http://maps.google.com/mars/#lat=0.522717&lon=534.222794&zoom=6) plains, and they went there and did burst their bubble. (Literally)
**The question: How will Earth handle this?**
It is safe to assume that both colonies are under constant surveillance from ground control. It is also safe to assume that NASA and ESA are still "friends" and the setup of having two colonies instead one is because they got great fundings - so why not build two?
It is also safe to assume, that there is some crew rotation (people and material are being exchanged on regular basis)
[](https://i.stack.imgur.com/2L6GD.jpg)
The time is Battle + 15 minutes. Ground control of both teams is getting first shocking images of whats happening on Mars. And you know that until they receive first orders, everything will be over...
What happens next?
**Edit:** Trying to make the question less opinion based: Assume there is only one NASA+ESA joint resupply mission and next one is about to launch, arriving to Mars in half a year.
Usually this resuply mission has about 7 months of food + oxygen + water supplies for all the crew + 12 people to go on rotation mission (6 NASA, 6 ESA). The resuply frequency is 6 months.
So, lets scope the question like this: Who do I send out in next resupply mission? (profession wise obviously). And how has NASA + ESA proceed is they (obviously) want Mars mission to continue? | 2015/08/16 | [
"https://worldbuilding.stackexchange.com/questions/22702",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/2071/"
] | **NASA/ESA Repsonse**
*Surprise*
The officials should be shocked. After Houston kept telling the astronauts, for example, to 'just learn to get along,' they will have decided to take things into their own hands and through a series of discussions in 'safe' spaces or on notes of paper, they planned their battles. It wasn't until T minus an-hour-or-so before they departed that NASA/ESA realized their scientists weren't going to take it any more.
*(Short-term) Attempt at Cover-up*
This is a situation with precedent. Just as whenever there's a situation (riots or whatever), there's a scramble.
I don't think it would be an attempt to cover-up permanently, because this will obviously not be successful, but governments and private companies, and even kids who broke a window with a baseball try to keep it a secret until they can think what to do. In this scenario, frantic phone calls are made between agencies internally and among the countries involved.
"Hi, Mr. President, we have a situation..."
"They what-the-WHAT?"
*Damage Control*
Heads of agencies, involved companies and government officials are scrambling to figure out what to do. It's hard to punish an employee who is a permanent colonist on a planet 140 million miles away. The press liasons are woken from bed to get onto the case and make sure that the spin is just so: the actions were unprecedented, atypical, and will be handled immediately.
*Finger Pointing*
This seems inevitable. Everyone wants to assign a cause to a situation, to help understand it, and there will be no end to this. It wouldn't be between the two agencies, rather between sub-sets of organizations and governments. The pressure put on the nerds by a rigorous schedule, or even petty things (the geologists from NASA were not allowed to study an area, because ESA claimed the area with a likelihood for astonishing discovery, for example).
The economic and political effects can be complex. However, property destruction and harm to individuals are often immediately measurable and will be assigned. In order to separate government responsibility from the actions of the nerds, I speculate that they would assign this as a 'riot,' and not politically motivated or assigned actions.
**Re-route Supplies and Relief Personnel**
The relief supplies would have to be enhanced by shifting some of the weight of long-term supplies (soils & plants for future planting, laboratory equipment, etc.) with that of equipment and personnel to either return the remaining scientists or to contain them until they can be returned.
This could include mechanisms for locating them (the nerds that won the battle know not to hang around, and have contingency for this), and then disabling their mobility.
**Aside: Public Outcry**
Phone calls will be made, statements will be made. People who already have disdain for space exploration will use this forever as an argument to defund future space exploration, manned or otherwise. Also, so much for childrens' role models. | The most effective way for the US and EU to defuse any political fallout over the rogue actions of a bunch of scientists is to *call it exactly that in public*. Admit to their errors in judgement in choosing (as yet unknown) members of the Mars teams who could go on to commit murder, and state that the number one priority is now not only to rescue the innocent, but also to arrest and prosecute the guilty.
To that end, the 12 crew members who were scheduled to go out on the next resupply mission would be withdrawn, and instead a 10-strong team of military- and police- trained investigators, all with combat experience in either a civilian or military conflict, as well as experience in rescue operations, drawn equally from both the US and EU and ideally having professional experience and friendships with one-another, would be substituted. All of the new/replacement scientific gear would be removed and substituted with military and investigatory equipment for the use of the investigators to bring the perpetrators of this "unwarranted violence" to justice. The last two positions would be specially selected psychologists, again from both the US and EU, who would be working to determine what caused the build-up of tensions that led to the open conflict, and what could be done to prevent them from accumulating in future missions.
Despite both the US and the EU wanting the missions to continue, they must publically speak as if cancelling the missions entirely is a high probability - which in fact it is. Until the rogue elements in both facilities can be identified and arrested, the missions are in jeopardy. The best option from the Earth-siders point of view may be to entirely replace the existing Mars teams with entirely new teams.
It is unlikely that the perpetrators could escape justice for long once the resupply ship arrives. While they know the environment better, Mars is still a hostile environment, and environment suits have limited supplies. They would be forced to either surrender or attempt to fight off the investigators from whatever bolthole they could find, and the investigators would have vastly superior combat skills, likely backed up by armoured environment gear that the rogue scientists would have trouble dealing with.
In any event, it is one thing (as most likely happened) to pop an enemy environment dome using a drone, and entirely another thing to face multiple trained soldiers and police officers each armed with a gun selected and loaded to deal with precisely the sort of protection the scientists may be able to muster. In all likelihood, the scientists will surrender immediately rather than fight, and the probable fate of the first one who *doesn't* will encourage the rest to choose a wiser course of action.
Once the scientists have all been rounded up and placed in protective custody, and all the bodies identified, or at least accounted for, the investigators will begin the investigatory side of the operation, attempting to determine who did what.
At the very least, the suspects will be returned to Earth for trial on charges including murder and terrorism, and the investigators may conclude that the entire scientific team needs to be replaced eventually.
Regardless, the suspects will be shipped back to Earth in custody, while the investigators remain to fulfil a police role in order to keep the peace between those who remain.
Back on Earth, after debates over jurisdiction in which it is suggested that each body prosecute its own nationals, the perpetrators will appear in highly publicised trials in the Hague, which, based on the [Outer Space Treaty](https://en.wikipedia.org/wiki/Outer_Space_Treaty) has [jurisdiction over crimes committed in space](https://en.wikipedia.org/wiki/Space_jurisdiction). See also: <https://space.stackexchange.com/questions/683/jurisdiction-over-crime-in-space>.
Since the crimes in question are murder and terrorism, there will be no question as to whether the alleged actions are worthy of prosecution or not, as both the US and the EU have laws concerning the accused's actions.
As to the outcome of the trial... who can say? |
22,702 | *This question continues story of [one ESA vs NASA battle on Mars](https://worldbuilding.stackexchange.com/questions/22573/how-will-my-nerdy-mars-astronauts-do-battle-between-their-colonies). I tried to put everything important into this question. Also, being from Europe, I took ESA side as the one winning:*
* **Year:** 2100ish
* **Mars:** Two 'surface,' permanent scientific research colonies with a little over 100 scientists and engineers in each with an
additional support crew (geologist, psychologist & medical, etc.) to
about 150 people each, with the common utilities, agrarian setups,
etc.
The nerds in Colony ESA have just had it with Colony NASA, about 100km across [Elysium](http://maps.google.com/mars/#lat=0.522717&lon=534.222794&zoom=6) plains, and they went there and did burst their bubble. (Literally)
**The question: How will Earth handle this?**
It is safe to assume that both colonies are under constant surveillance from ground control. It is also safe to assume that NASA and ESA are still "friends" and the setup of having two colonies instead one is because they got great fundings - so why not build two?
It is also safe to assume, that there is some crew rotation (people and material are being exchanged on regular basis)
[](https://i.stack.imgur.com/2L6GD.jpg)
The time is Battle + 15 minutes. Ground control of both teams is getting first shocking images of whats happening on Mars. And you know that until they receive first orders, everything will be over...
What happens next?
**Edit:** Trying to make the question less opinion based: Assume there is only one NASA+ESA joint resupply mission and next one is about to launch, arriving to Mars in half a year.
Usually this resuply mission has about 7 months of food + oxygen + water supplies for all the crew + 12 people to go on rotation mission (6 NASA, 6 ESA). The resuply frequency is 6 months.
So, lets scope the question like this: Who do I send out in next resupply mission? (profession wise obviously). And how has NASA + ESA proceed is they (obviously) want Mars mission to continue? | 2015/08/16 | [
"https://worldbuilding.stackexchange.com/questions/22702",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/2071/"
] | The most effective way for the US and EU to defuse any political fallout over the rogue actions of a bunch of scientists is to *call it exactly that in public*. Admit to their errors in judgement in choosing (as yet unknown) members of the Mars teams who could go on to commit murder, and state that the number one priority is now not only to rescue the innocent, but also to arrest and prosecute the guilty.
To that end, the 12 crew members who were scheduled to go out on the next resupply mission would be withdrawn, and instead a 10-strong team of military- and police- trained investigators, all with combat experience in either a civilian or military conflict, as well as experience in rescue operations, drawn equally from both the US and EU and ideally having professional experience and friendships with one-another, would be substituted. All of the new/replacement scientific gear would be removed and substituted with military and investigatory equipment for the use of the investigators to bring the perpetrators of this "unwarranted violence" to justice. The last two positions would be specially selected psychologists, again from both the US and EU, who would be working to determine what caused the build-up of tensions that led to the open conflict, and what could be done to prevent them from accumulating in future missions.
Despite both the US and the EU wanting the missions to continue, they must publically speak as if cancelling the missions entirely is a high probability - which in fact it is. Until the rogue elements in both facilities can be identified and arrested, the missions are in jeopardy. The best option from the Earth-siders point of view may be to entirely replace the existing Mars teams with entirely new teams.
It is unlikely that the perpetrators could escape justice for long once the resupply ship arrives. While they know the environment better, Mars is still a hostile environment, and environment suits have limited supplies. They would be forced to either surrender or attempt to fight off the investigators from whatever bolthole they could find, and the investigators would have vastly superior combat skills, likely backed up by armoured environment gear that the rogue scientists would have trouble dealing with.
In any event, it is one thing (as most likely happened) to pop an enemy environment dome using a drone, and entirely another thing to face multiple trained soldiers and police officers each armed with a gun selected and loaded to deal with precisely the sort of protection the scientists may be able to muster. In all likelihood, the scientists will surrender immediately rather than fight, and the probable fate of the first one who *doesn't* will encourage the rest to choose a wiser course of action.
Once the scientists have all been rounded up and placed in protective custody, and all the bodies identified, or at least accounted for, the investigators will begin the investigatory side of the operation, attempting to determine who did what.
At the very least, the suspects will be returned to Earth for trial on charges including murder and terrorism, and the investigators may conclude that the entire scientific team needs to be replaced eventually.
Regardless, the suspects will be shipped back to Earth in custody, while the investigators remain to fulfil a police role in order to keep the peace between those who remain.
Back on Earth, after debates over jurisdiction in which it is suggested that each body prosecute its own nationals, the perpetrators will appear in highly publicised trials in the Hague, which, based on the [Outer Space Treaty](https://en.wikipedia.org/wiki/Outer_Space_Treaty) has [jurisdiction over crimes committed in space](https://en.wikipedia.org/wiki/Space_jurisdiction). See also: <https://space.stackexchange.com/questions/683/jurisdiction-over-crime-in-space>.
Since the crimes in question are murder and terrorism, there will be no question as to whether the alleged actions are worthy of prosecution or not, as both the US and the EU have laws concerning the accused's actions.
As to the outcome of the trial... who can say? | While there would be the usual coverup/deflect/finger pointing aspect of bureaucratic and political response, I suspect that there would be another level of response, which is the sheer bloody mindedness of people.
Many people will have been invested in the project, and of course the astronauts will have been celebrities in certain social media circles (as well as real celebrities in other aspects of their lives), as well as having lots of family and influential friends. There will be a massive outcry for something to be done to avenge the loss of so many lives and so much equipment, not to mention the political capital that had been expended in setting up the expedition in the first place.
I suspect the joint resupply venture will be the first thing scuttled, as each side accuses the other of manipulating the manifest to the benefit/detriment of one group of astronauts. Certainly the astronauts themselves slated for the mission are going to have some grave doubts about the other parties aboard; if two teams of supposedly complimentary astronauts on Mars went to war, resulting in the destruction of a base and the deaths of many astronauts, then what could possibly happen aboard the resupply ship during its long transfer orbit to Mars? A secondary consideration is that one base has been destroyed, so any surviving astronauts will be busy trying to do a "Mark Watney" and need help as fast as possible. An unmanned supply vessel launched on a high energy trajectory transfer will be needed ASAP, and since you stipulate that the NASA side lost, NASA will be pulling *all* their resources and technical ability to the task and not to a joint resupply mission. (If the ESA side had lost, the same factors would apply).
The anger would also spill over on the Earth at many levels. Boycotts against products made in the EU would begin an informal trade war between the two sides, and the EU would also lose American tourism and other forms of exchange, creating economic disruptions. More formal actions against the EU would be called for by politicians and political groups eager to hitch their wagon to a popular cause (and various parties in the EU would be calling for the same against the US, leading to a situation where parties like the UKIP, Front National, Golden Dawn and other more or less radical parties whip up popular support among the European voters).
Depending on how far the agitation goes, this might provoke more robust actions between the two governments. Even if it does not by itself, nations like Russia and China will seek to inflame the situation through "Active Measures" (propaganda and other campaigns to mould public opinion in a desired direction), potentially causing the same effect. While the Americans might not want to kill the ESA astronauts in cold blood, they could make it very clear that the ESA will not be launching *anything* until the United States is satisfied that certain conditions are met (most likely the arrival of the relief ship and resupply of the American astronauts stranded on Mars).
At this point, the huge resource mismatch between the United States and the EU will begin to be felt. The US can put lots of pressure on the EU through lots of different means (political, military and economic), and as noted, NASA and the private US space industry can respond to directly support their astronauts on Mars by sending relief supplies by high energy transfer orbits. The ESA has only one supplier to build extra rockets (unless they decide to hire the Russians or Chinese to build rockets for them, which would be a nasty can of political worms to open), while the United States can hire SpaceX, Orbital, Boeing, Lockheed-Martin, Northrop-Grunmann and and entire second tier of would be rocket makers to crank out orbital vehicles and infrastructure to not only rescue the US astronauts, but establish a robust permanent presence on Mars as well (even if the US government isn't explicitly interested in doing so, Elon Musk has openly stated that this is *his* goal; he is hardly going to turn down a gilded opportunity to fulfill his life dream).
Winning the battle and losing the war is alway a risk when you take up arms, and the end results of armed conflict are rarely what either side envisioned before the start of the conflict. The only potentially "good" outcome of all this is a robust Martian colony is now possible, and the infrastructure for much larger scale space exploration is now in place. I suspect that the second order effect will be space colonies will have a robust protective service attached to prevent this sort of thing from happening again, ranging from private security forces hired by the colonists to actual contingents of national military forces brought by the colonizing nations themselves. |
13,075,617 | I would like to know how to get the current week number from Rails and how do I manipulate it:
1. Translate the week number into date.
2. Make an interval based on week number.
Thanks. | 2012/10/25 | [
"https://Stackoverflow.com/questions/13075617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788357/"
] | Use [`strftime`](http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime):
>
> `%U` - Week number of the year. The week starts with Sunday. (00..53)
>
> `%W` - Week number of the year. The week starts with Monday. (00..53)
>
>
>
```
Time.now.strftime("%U").to_i # 43
# Or...
Date.today.strftime("%U").to_i # 43
```
If you want to *add* 43 weeks (or days,years,minutes, etc...) to a date, you can use [`43.weeks`](http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html#M000324), provided by ActiveSupport:
```
irb(main):001:0> 43.weeks
=> 301 days
irb(main):002:0> Date.today + 43.weeks
=> Thu, 22 Aug 2013
irb(main):003:0> Date.today + 10.days
=> Sun, 04 Nov 2012
irb(main):004:0> Date.today + 1.years # or 1.year
=> Fri, 25 Oct 2013
irb(main):005:0> Date.today + 5.months
=> Mon, 25 Mar 2013
``` | ```
date.commercial([cwyear=-4712[, cweek=1[, cwday=1[, start=Date::ITALY]]]]) → date
Creates a date object denoting the given week date.
The week and the day of week should be a negative
or a positive number (as a relative week/day from the end of year/week when negative).
They should not be zero.
```
For the interval
```
require 'date'
def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' + week_end.strftime("%m/%d/%y" )
end
puts week_dates(22)
```
>
> EG: Input (Week Number): 22
>
>
> Output: 06/12/08 - 06/19/08
>
>
>
credit: Siep Korteling <http://www.ruby-forum.com/topic/125140> |
13,075,617 | I would like to know how to get the current week number from Rails and how do I manipulate it:
1. Translate the week number into date.
2. Make an interval based on week number.
Thanks. | 2012/10/25 | [
"https://Stackoverflow.com/questions/13075617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788357/"
] | Use [`strftime`](http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime):
>
> `%U` - Week number of the year. The week starts with Sunday. (00..53)
>
> `%W` - Week number of the year. The week starts with Monday. (00..53)
>
>
>
```
Time.now.strftime("%U").to_i # 43
# Or...
Date.today.strftime("%U").to_i # 43
```
If you want to *add* 43 weeks (or days,years,minutes, etc...) to a date, you can use [`43.weeks`](http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html#M000324), provided by ActiveSupport:
```
irb(main):001:0> 43.weeks
=> 301 days
irb(main):002:0> Date.today + 43.weeks
=> Thu, 22 Aug 2013
irb(main):003:0> Date.today + 10.days
=> Sun, 04 Nov 2012
irb(main):004:0> Date.today + 1.years # or 1.year
=> Fri, 25 Oct 2013
irb(main):005:0> Date.today + 5.months
=> Mon, 25 Mar 2013
``` | [`Date#cweek`](http://ruby-doc.org/stdlib-2.2.2/libdoc/date/rdoc/Date.html#method-i-cweek) seems to get the ISO-8601 week number (a Monday-based week) like `%V` in strftime (mentioned by @Robban in a comment).
For example, the Monday and the Sunday of the week I'm writing this:
```
[ Date.new(2015, 7, 13), Date.new(2015, 7, 19) ].map { |date|
date.strftime("U: %U - W: %W - V: %V - cweek: #{date.cweek}")
}
# => ["U: 28 - W: 28 - V: 29 - cweek: 29", "U: 29 - W: 28 - V: 29 - cweek: 29"]
``` |
13,075,617 | I would like to know how to get the current week number from Rails and how do I manipulate it:
1. Translate the week number into date.
2. Make an interval based on week number.
Thanks. | 2012/10/25 | [
"https://Stackoverflow.com/questions/13075617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788357/"
] | Use [`strftime`](http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime):
>
> `%U` - Week number of the year. The week starts with Sunday. (00..53)
>
> `%W` - Week number of the year. The week starts with Monday. (00..53)
>
>
>
```
Time.now.strftime("%U").to_i # 43
# Or...
Date.today.strftime("%U").to_i # 43
```
If you want to *add* 43 weeks (or days,years,minutes, etc...) to a date, you can use [`43.weeks`](http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html#M000324), provided by ActiveSupport:
```
irb(main):001:0> 43.weeks
=> 301 days
irb(main):002:0> Date.today + 43.weeks
=> Thu, 22 Aug 2013
irb(main):003:0> Date.today + 10.days
=> Sun, 04 Nov 2012
irb(main):004:0> Date.today + 1.years # or 1.year
=> Fri, 25 Oct 2013
irb(main):005:0> Date.today + 5.months
=> Mon, 25 Mar 2013
``` | You are going to want to stay away from `strftime("%U")` and `"%W"`.
**Instead, use `Date.cweek`.**
The problem is, if you ever want to take a week number and convert it to a date, `strftime` won't give you a value that you can pass back to `Date.commercial`.
`Date.commercial` expects a range of values that are 1 based.
`Date.strftime("%U|%W")` returns a value that is 0 based. You would think you could just +1 it and it would be fine. The problem will hit you at the end of a year when there are 53 weeks. (Like what just happened...)
For example, let's look at the end of Dec 2015 and the results from your two options for getting a week number:
```
Date.parse("2015-12-31").strftime("%W") = 52
Date.parse("2015-12-31").cweek = 53
```
Now, let's look at converting that week number to a date...
```
Date.commercial(2015, 52, 1) = Mon, 21 Dec 2015
Date.commercial(2015, 53, 1) = Mon, 28 Dec 2015
```
If you blindly just +1 the value you pass to `Date.commercial`, you'll end up with an invalid date in other situations:
For example, December 2014:
```
Date.commercial(2014, 53, 1) = ArgumentError: invalid date
```
If you ever have to convert that week number back to a date, the only surefire way is to use `Date.cweek`. |
13,075,617 | I would like to know how to get the current week number from Rails and how do I manipulate it:
1. Translate the week number into date.
2. Make an interval based on week number.
Thanks. | 2012/10/25 | [
"https://Stackoverflow.com/questions/13075617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788357/"
] | ```
date.commercial([cwyear=-4712[, cweek=1[, cwday=1[, start=Date::ITALY]]]]) → date
Creates a date object denoting the given week date.
The week and the day of week should be a negative
or a positive number (as a relative week/day from the end of year/week when negative).
They should not be zero.
```
For the interval
```
require 'date'
def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' + week_end.strftime("%m/%d/%y" )
end
puts week_dates(22)
```
>
> EG: Input (Week Number): 22
>
>
> Output: 06/12/08 - 06/19/08
>
>
>
credit: Siep Korteling <http://www.ruby-forum.com/topic/125140> | [`Date#cweek`](http://ruby-doc.org/stdlib-2.2.2/libdoc/date/rdoc/Date.html#method-i-cweek) seems to get the ISO-8601 week number (a Monday-based week) like `%V` in strftime (mentioned by @Robban in a comment).
For example, the Monday and the Sunday of the week I'm writing this:
```
[ Date.new(2015, 7, 13), Date.new(2015, 7, 19) ].map { |date|
date.strftime("U: %U - W: %W - V: %V - cweek: #{date.cweek}")
}
# => ["U: 28 - W: 28 - V: 29 - cweek: 29", "U: 29 - W: 28 - V: 29 - cweek: 29"]
``` |
13,075,617 | I would like to know how to get the current week number from Rails and how do I manipulate it:
1. Translate the week number into date.
2. Make an interval based on week number.
Thanks. | 2012/10/25 | [
"https://Stackoverflow.com/questions/13075617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788357/"
] | You are going to want to stay away from `strftime("%U")` and `"%W"`.
**Instead, use `Date.cweek`.**
The problem is, if you ever want to take a week number and convert it to a date, `strftime` won't give you a value that you can pass back to `Date.commercial`.
`Date.commercial` expects a range of values that are 1 based.
`Date.strftime("%U|%W")` returns a value that is 0 based. You would think you could just +1 it and it would be fine. The problem will hit you at the end of a year when there are 53 weeks. (Like what just happened...)
For example, let's look at the end of Dec 2015 and the results from your two options for getting a week number:
```
Date.parse("2015-12-31").strftime("%W") = 52
Date.parse("2015-12-31").cweek = 53
```
Now, let's look at converting that week number to a date...
```
Date.commercial(2015, 52, 1) = Mon, 21 Dec 2015
Date.commercial(2015, 53, 1) = Mon, 28 Dec 2015
```
If you blindly just +1 the value you pass to `Date.commercial`, you'll end up with an invalid date in other situations:
For example, December 2014:
```
Date.commercial(2014, 53, 1) = ArgumentError: invalid date
```
If you ever have to convert that week number back to a date, the only surefire way is to use `Date.cweek`. | ```
date.commercial([cwyear=-4712[, cweek=1[, cwday=1[, start=Date::ITALY]]]]) → date
Creates a date object denoting the given week date.
The week and the day of week should be a negative
or a positive number (as a relative week/day from the end of year/week when negative).
They should not be zero.
```
For the interval
```
require 'date'
def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' + week_end.strftime("%m/%d/%y" )
end
puts week_dates(22)
```
>
> EG: Input (Week Number): 22
>
>
> Output: 06/12/08 - 06/19/08
>
>
>
credit: Siep Korteling <http://www.ruby-forum.com/topic/125140> |
13,075,617 | I would like to know how to get the current week number from Rails and how do I manipulate it:
1. Translate the week number into date.
2. Make an interval based on week number.
Thanks. | 2012/10/25 | [
"https://Stackoverflow.com/questions/13075617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788357/"
] | You are going to want to stay away from `strftime("%U")` and `"%W"`.
**Instead, use `Date.cweek`.**
The problem is, if you ever want to take a week number and convert it to a date, `strftime` won't give you a value that you can pass back to `Date.commercial`.
`Date.commercial` expects a range of values that are 1 based.
`Date.strftime("%U|%W")` returns a value that is 0 based. You would think you could just +1 it and it would be fine. The problem will hit you at the end of a year when there are 53 weeks. (Like what just happened...)
For example, let's look at the end of Dec 2015 and the results from your two options for getting a week number:
```
Date.parse("2015-12-31").strftime("%W") = 52
Date.parse("2015-12-31").cweek = 53
```
Now, let's look at converting that week number to a date...
```
Date.commercial(2015, 52, 1) = Mon, 21 Dec 2015
Date.commercial(2015, 53, 1) = Mon, 28 Dec 2015
```
If you blindly just +1 the value you pass to `Date.commercial`, you'll end up with an invalid date in other situations:
For example, December 2014:
```
Date.commercial(2014, 53, 1) = ArgumentError: invalid date
```
If you ever have to convert that week number back to a date, the only surefire way is to use `Date.cweek`. | [`Date#cweek`](http://ruby-doc.org/stdlib-2.2.2/libdoc/date/rdoc/Date.html#method-i-cweek) seems to get the ISO-8601 week number (a Monday-based week) like `%V` in strftime (mentioned by @Robban in a comment).
For example, the Monday and the Sunday of the week I'm writing this:
```
[ Date.new(2015, 7, 13), Date.new(2015, 7, 19) ].map { |date|
date.strftime("U: %U - W: %W - V: %V - cweek: #{date.cweek}")
}
# => ["U: 28 - W: 28 - V: 29 - cweek: 29", "U: 29 - W: 28 - V: 29 - cweek: 29"]
``` |
13,659,652 | I have found good tutorial to for Handling Screen OFF and Screen ON Intents: <http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/>
but i want that after screen is off every 5 minutes wifi is checked if is connected
```
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
wifi.isConnected()
```
i want to use `alarm manager` <http://developer.android.com/reference/android/app/AlarmManager.html> but i don't know how to check every 5 minutes if is connected or not. | 2012/12/01 | [
"https://Stackoverflow.com/questions/13659652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267679/"
] | Everything is fine. You just need to take care of little things. In this case `;` is missing after declaring 'pri\_func2'.
```
pri_func2 = function() {
//do something
};
```
This should be enough for this error. | Try this:
```
var Util = {};
Util.data = (function() {
var privar,
pri_func1 = function() {
//do something
},
pri_func2 = function() {
//do something
};
return { // JSLint error
pub_fun1: function() {
//do something
},
pub_fun2: function() {
//do something
}
};
})();
``` |
70,993 | We know through [General Relativity](http://en.wikipedia.org/wiki/General_relativity) (GR) that matter curves spacetime (ST) like a "ball curves a trampoline" but then how energy curves spacetime? Is it just like matter curvature of ST? | 2013/07/13 | [
"https://physics.stackexchange.com/questions/70993",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/25589/"
] | Matter curves the spacetime because (experimentally verified and mathematically natural) Einstein's equations that govern the spacetime curvature say that the local-curvature-encoding Einstein tensor $G\_{\mu\nu}$ is proportional to the stress-energy $T\_{\mu\nu}$. The latter contains numbers, especially the density of mass-energy and momentum and their flux (which also depends on the local pressure).
Because matter carries mass-energy, it makes spacetime warp. Any other form of mass-energy will do the same thing. I say mass-energy because in the context of relativity, mass and energy are really the same thing due to the well-known formula of special relativity, $E=mc^2$, which says that one unit (e.g. kilogram) of (relativistic) mass is equivalent to $c^2$ units (joules) of energy.
Mass or energy may be stored in various forms but they ultimately have the very same impact on the spacetime curvature (and other things). Some of the forms of mass-energy look more like mass, other looks like what we used to call energy but there's only one type of quantity that curves the spacetime and one quantity that is conserved. | The source of gravity in GR is not just mass, but the full energy-momentum tensor; this tensorial quantity is a measure of energy, momentum and stress, and applies to ALL forms of matter and all fields that are non-gravitational. Furthermore, there exists a quantity in differential geometry which is automatically conserved in a small neighbourhood on a differentiable manifold, called the Cartan moment of rotation - it turns out that this is mathematically just the dual of the Einstein tensor, and what GR does is relate these two tensorial quantities. This is what the field equations tell us - that the geometry of space-time is related to its energy-momentum content. |
70,993 | We know through [General Relativity](http://en.wikipedia.org/wiki/General_relativity) (GR) that matter curves spacetime (ST) like a "ball curves a trampoline" but then how energy curves spacetime? Is it just like matter curvature of ST? | 2013/07/13 | [
"https://physics.stackexchange.com/questions/70993",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/25589/"
] | Theoretical viewpoint:
----------------------
Einstein field equations can be written in the form: $$\color{blue}{G\_{\mu\nu}}=\color{red}{\frac{8\pi G}{c^{4}}} \color{darkgreen}{T\_{\mu\nu}}$$
We can write in simple terms: $$\rm \color{blue}{Space-time \,\,geometry}=\color{red}{const.}\,\,\color{darkgreen}{Material \,\,objects}.$$
And the $T\_{\mu\nu}$ is a mathematical object (a tensor to be precise) which describes material bodies. In that mathematical object, there are some parameters such as the density, the momentum, mass-energy... etc. So it is those parameters that determine 'how much space-time curvature' is around a body. And one of the parameters is of course *energy*. Therefore, *energy* do bend space-time.
Experiments that confirm this point:
------------------------------------
First, do photons have mass? The answer is an emphatic **'no'**. The momentum of a photon is $p=\frac{hf}c$, and from special relativity: $$\begin{align}E=\sqrt{(mc^2)^2+(pc)^2}&\iff E^2=(mc^2)^2+(pc)^2\\&\iff E^2-(pc)^2=(mc^2)^2\\ \end{align}.$$
The energy of a photon is: $E=hf$ which is an experimental fact. It can also be expressed as $E=pc$ since $E=hf=\frac{hf}{c}\cdot c=pc.$ Therefore, $E^2=(pc)^2$ and so $E^2-(pc)^2=0$. Putting this in our previous derivation we get: $E^2-(pc)^2=(mc^2)^2=0$. Since $c^2$ is a constant, then $m=0$. Therefore, photons have no rest mass.
**Claim:** Photons are not subject to gravitational attraction since they have no rest mass.
**Experimental disproof:** [Gravitational lensing](http://en.wikipedia.org/wiki/Gravitational_lens):

You could see light being bent due to the presence of a strong gravitational field.
**Conclusion:** Even if light has no rest mass, it has energy and momentum. And it is being attracted due to gravity, so the natural conclusion is that energy do curve space-time. | Matter curves the spacetime because (experimentally verified and mathematically natural) Einstein's equations that govern the spacetime curvature say that the local-curvature-encoding Einstein tensor $G\_{\mu\nu}$ is proportional to the stress-energy $T\_{\mu\nu}$. The latter contains numbers, especially the density of mass-energy and momentum and their flux (which also depends on the local pressure).
Because matter carries mass-energy, it makes spacetime warp. Any other form of mass-energy will do the same thing. I say mass-energy because in the context of relativity, mass and energy are really the same thing due to the well-known formula of special relativity, $E=mc^2$, which says that one unit (e.g. kilogram) of (relativistic) mass is equivalent to $c^2$ units (joules) of energy.
Mass or energy may be stored in various forms but they ultimately have the very same impact on the spacetime curvature (and other things). Some of the forms of mass-energy look more like mass, other looks like what we used to call energy but there's only one type of quantity that curves the spacetime and one quantity that is conserved. |
70,993 | We know through [General Relativity](http://en.wikipedia.org/wiki/General_relativity) (GR) that matter curves spacetime (ST) like a "ball curves a trampoline" but then how energy curves spacetime? Is it just like matter curvature of ST? | 2013/07/13 | [
"https://physics.stackexchange.com/questions/70993",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/25589/"
] | Matter curves the spacetime because (experimentally verified and mathematically natural) Einstein's equations that govern the spacetime curvature say that the local-curvature-encoding Einstein tensor $G\_{\mu\nu}$ is proportional to the stress-energy $T\_{\mu\nu}$. The latter contains numbers, especially the density of mass-energy and momentum and their flux (which also depends on the local pressure).
Because matter carries mass-energy, it makes spacetime warp. Any other form of mass-energy will do the same thing. I say mass-energy because in the context of relativity, mass and energy are really the same thing due to the well-known formula of special relativity, $E=mc^2$, which says that one unit (e.g. kilogram) of (relativistic) mass is equivalent to $c^2$ units (joules) of energy.
Mass or energy may be stored in various forms but they ultimately have the very same impact on the spacetime curvature (and other things). Some of the forms of mass-energy look more like mass, other looks like what we used to call energy but there's only one type of quantity that curves the spacetime and one quantity that is conserved. | According to Newtonian gravity if you made 100 million cannon balls (10kg each) and shipped them to deep space assembled them with some explosives and exploded it with enough force so none get hurt but they all went out spherically to a maximum of 2 miles (if you don't know what a mile is, just read it as a km and none of the physics will be different but the abbreviation is mi and I do use that later) from the center that only the mass of the cannon balls and the number of them matters, so it would be like a (very small) planet of mass 1000 million kg. Specifically, Newtonian gravity says you could instead send more explosives to shoot them so that they all travel spherically outwards for 10 miles and someone orbiting them would feel the same gravitational attraction as if you made a 2mi explosion of the balls, so it would be like a (very small) planet of mass 1000 million kg either way.
General Relativity disagrees. Which is good. Because that additional explosives to make it 10mi instead of 2mi had some mass and the gravitational attraction far away shouldn't change the instant you set them off. Not the exact same instant at least, since nothing should go faster than light by just setting off an explosive.
On the one hand your question looks like it has an easy answer, it is actually the energy associaited with the mass that makes curvature. The mass itself did nothing, only the energy associated with the mass did something. but that answer, while accurate, sidesteps the whole question about how curvature is caused.
The first thing to know about curvature is that it is natural. Einstein's equation $R\_{ab}-\frac{1}{2}g\_{ab}R=kT^\frac{8\pi G}{c^4}T\_{ab}$ has a version for vacuum that is $R\_{ab}-\frac{1}{2}g\_{ab}R=0$ and that equation does not say that curvature is zero. It says that certain combinations of rates of change of the metric have to balance against the existing current metric. So certain metrics have to change certain ways. The equation allows, for instance, gravitational waves to propagate through empty space with the rate of change of curvature in a region changing according to the way curvature varies nearby.
So curvature is natural, even in empty space, and curvature can cause itself, either causing curvature nearby or causing future curvature right there.
And certain kinds of curvature line up just fine in spacetime, and other do not. The kinds that do line up solve $R\_{ab}-\frac{1}{2}g\_{ab}R=0.$ The kinds that do not line up naturally, don't solve $R\_{ab}-\frac{1}{2}g\_{ab}R=0.$
The second thing to know about curvature is to note that $R\_{ab}-\frac{1}{2}g\_{ab}R$ always has the property that its (covariant) divergence vanishes. That means it is possible to have matter that equals $R\_{ab}-\frac{1}{2}g\_{ab}R$ because matter has its (covariant) divergence always vanishes. Some people go a bit extreme with this, they make spacetimes with warp bubbles and long lived wormholes and say, well you just need to put some really really really weird matter right in the right places.
But it does mean that matter can make things curve differently than it naturally would in a vacuum. Let's use that to see how matter can make spacetime curve.
Take two different natural curvatures. For the first, you can take the way the vacuum spacetime outside a planet in deep space is curved (the simplest one is called a Schwarzschild spacetime), since it is the region outside a planet where it is all vacuum, this is the kind of curvature that exists fine on its own, and even is curved just right so as to make the curvature in the future be just like the curvature now. For the second natural curvature, you can take a flat spacetime (called Minkowski spacetime). If you take a ball of radius 10 miles and take that region of flat Minkowski that can be your first region. Then you can take the Schwarzschild solution for a parameter of $M= 1000 million kg$ and cut out a spherical surface of surface area $4\pi (10mi)^2$ and glue the ball of Minkowski spacetime to the exterior of the Schwarzschild spacetime, so it is Schwarzschild on the outside and Minkowski on the inside
Anytime the surfaces line up, it is a possible spacetime. But the matter might have to be be really really weird. Do we need really really weird matter? No. Having the 100 million cannon balls of 10kg each that came to rest at 10mi from the center is exactly the right distribution of matter to sew those two solutions together.
And now as the canon balls come down we can see curvature get created. There is no curvature on the inside of the spherical shell of cannon balls. But as the canon balls fall down, the region right outside the outer shell doesn't have matter there anymore so it has to evolve in the natural (vacuum) way, but the curvature out there is the Schwarzschild curvature, which is one of the kinds of curvature that naturally evolves to itself, so the curvature right outside the shell of cannon balls will make more of itself inside if there is nothing to stop it.
And when I say more of itself, I strangely mean exactly that. A totally interesting (or mind blowing) feature is that when the cannon balls get to only being 9mi from the center the distance outside the shell of falling cannon balls is more than 1 mi away from where it started. When the cannon balls fall, the Schwarzschild solution outside creates more distance between itself and the region outside than it eats up from the inside down. It's like making a giant funnel that is deeper, to make the funnel go from a circle of circumference $2\pi(10cm)$ to a circle of circumference $2\pi(9cm)$ requires more than 1cm of distance between the two circles because the funnel surface is curved.
In out example it is like putting a flat disk of radius 10cm into your giant funnel and then taking it out and replacing it with a flat disk of radius 9cm, there will be more funnel visible because the smaller one covers up less of it. Normal geometry holds on the disk and curved geometry holds on the funnel. We are doing the same thing but in a higher dimension.
OK. So now we see how curvature gets created. Every galaxy was made in the past by matter infalling towards the center, as each shell of matter crosses over a spherical thin shelled region it ties together a region less curvature on the inside to a region of more curvature on the outside. Why? Because that is what ordinary everyday regular matter does. It's not really really weird matter, so it connects higher curvature on the outside to lower curvature (or none) on the inside. Thus leaving the outer galaxy curved so that the sun could one day orbit the galactic center. And similarly as the sun formed layer by layer, it connected a region of more curvature on the outside to a region of less curvature on the inside, leaving the solar system curved outside the sun so that we could one day orbit the sun. And similarly as the earth formed it left the region i\outside itself more curved, so that the moon could orbit the earth.
Now I said that GR gives a different curvature for the 2mi explosion and the 10mi explosion. Let's see what happens when the cannon balls get to 2mi away from the center. There are still 100 million cannon balls. And they still have a mass of 10kg each. But they have fallen 8 (or more?) mil and have been speeding up the whole way. They have more energy. And it is actually the energy, momentum, pressure, and stress of matter that allows different curvature regions to be sewn together. If you had the same number of cannon balls at 2mi radius from the center but all of them were at rest, they wouldn't have enough energy to connect up to such a highly curved spacetime. What that means is that when you brought the cannon balls and the smaller amount of explosives they didn't curve the spacetime around themselves as much when they were brought in the first time.
This makes sense, if you brought less explosives in when you made your cannon ball explosion the spacetime outside was curved less. If you brought in more explosives, then you curved space more. So when the explosives are used up (your explosives could have been matter and antimatter that exploded into pure energy, both regualr everyday matter and the antiparticles versus of regular everyday matter are have positive energy and positive mass, those really really really weird matter that you need for weird spacetimes are really really really weird). So when the explosives are used up the cannon balls take off with lots of energy but that region of spacetime outside is still curved the same way it was when you sent the explosives down to the center. This higher energy matter (more energy because moving faster) has to be enough to convert that higher curvature on the outside into (less) flat space that becomes the inside. We know the curvature on the inside has to be zero for symmetry reasons (everything is spherically symmetric and there is nothing inside the shell of matter and we assume the cannon balls are not really really really weird so they aren't lined with negative energy on one side and extra compensating positive energy on the other).
You can think of it as a certain amount of energy density leaves behind empty space of less distance than the curved surface distance it eats up as it expands. But that rate is determined by the energy and momentum and pressure and stress. And not by mass. Gravity and curvature are not created by mass, they are made by energy (and momentum and pressure and stress). Energy and momentum and pressure and stress together make $T\_{ab}$ and together they evolve in such as way as to have zero (covariant) divergence so only those can patch together a nonzero term on the left hand side of $R\_{ab}-\frac{1}{2}g\_{ab}R=kT^\frac{8\pi G}{c^4}T\_{ab}.$
Since it is energy, not mass, that evolves with zero covariant divergence it is energy, not mass, that can follow that seem of expanding and contracting space as the place where the vacuum solutions of natural curvature evolve. The sum of the rest masses of the parts does not change over time the way you need to patch up the two different natural curvatures to each other based on how the two natural (vacuum) curvatures evolve on their own.
So it is energy, not mass, that is the source of gravity, and by source, we mean something that can piece together different natural regions of curvature, energy changes as the surfaces move in such a way to allow it to continue patching them together (possibly making more space on one side than it eats up on the other, but that's really about keeping the differently flowing rates of time to line up, if time flows slower on the regions farther away from the outside of a surface, you need to make more space on the outside as you flow the surface in.
OK. I've answered your question, but there is one detail I want to be honest about. For brevity I sometimes talked about "more curvature on the outside" and "less curvature on the inside" and what I meant was like if you had two layers of thin shells then inside both it might be flat and in between the two shells it might look like a curvature similar to a star of "lower mass" and outside both of them it might look like a curvature outside a star of "higher mass". That's what I meant by higher curvature, and lower curvature. Around a star of fixed mass, the true real objective curvature gets smaller the farther out you are. So when the galaxy was forming, the curvature was small out here and as the contracting galaxy had lots of matter move in closer, it extended that curvature out here that was slight into a curvature closer in that was curved "the same" way, i.e. that natural vacuum kind of way. But that "same" way naturally has more actual curvature closer in, so there is more curvature closer in, and I didn't want to be misleading about that. But I was trying to make it clear that you have one type of natural curvature and another type of natural curvature, and they can be types that have higher or lower curvature (at the same distance from very very far away bodies). So my talk about more and less curvature was accurate when the matter was right there and the two regions where touching right there. It's just that later when the matter has moved on that natural region of curvature itself allows curvature to change from point to point. In our example, that means as the cannon balls fall in, the new additional region of more curved space created outside isn't just more space and isn't' just more curved because it is more of the type that was outside (which was more curved) it is even more curved than the stuff that used to be outside because the type of curvature that is outside is the kind that gets more curved the closer in you get (and that is also because it was made from normal not weird matter).
I hope that wasn't too confusing. But I wanted to have a real answer out here about what makes curvature and what i\t means to be a source of curvature. It means that you allow different natural curvatures to line up so you can make one transition in to the other, thus make more or less of one of them.
Potentially alowing one to build up more of a region to give it a chance to get stronger curvature in a direction if it is the kind of curvature that gets stronger in a direction. Leaving stronger curvature on the outside means the newly created region has the stronger curvature, so contracting matter (that isn't weird matter) creates more space and more curvature as it contracts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.