qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
364,304
I am interested in Fourier Analysis. But I don't get why the coefficients are choosen that way and why the Fourier series will converge to a given function? Can someone provide me simple information or do you know an easy source for a beginner? Regards, Kevin
2013/04/17
[ "https://math.stackexchange.com/questions/364304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73030/" ]
You can try to read something in Rudin's book (pg 185). <http://www.scribd.com/doc/9654478/Principles-of-Mathematical-Analysis-Third-Edition-Walter-Rudin> In my opinion Stein and Shakarchi Fourier Analysis is a clear and perfectly written textbook. <http://press.princeton.edu/titles/7562.html>
The Fourier series converges given that the $f\in L^2(-l,l)$ for the given interval. That is $f$ is a function that satisfies $\int\_{-l}^{l}f^2 \, dx<+\infty$. There is a proof that shows that the series converges with this condition. The way to understant why coefficients are calculated as they are is to think that you are using a vector space of infinite dimension. That is $\{1,\sin({k\frac{\pi}{x}}),\cos({k\frac{\pi}{x}})\}$ (if you use a different basis is equivalent) is a basis of $L^2(-l,l)$, and any function that belongs to this space can be generated as an infinite linear combination of elements of the base. When you calculate the coefficients you are just calculating the projections of the function over each 'direction' given but each element of the basis. Of course the projection is donde using the dot product of the metric space we are using $L^2(-l,l)$, which is: $$\langle u,v\rangle=\int\_{-l}^{l}u\cdot v\,dx$$ where $u,v\in L^2(-l,l)$. You can find some notes about the topic [here](http://ocw.mit.edu/courses/mathematics/18-03sc-differential-equations-fall-2011/unit-iii-fourier-series-and-laplace-transform/fourier-series-basics/). This notes are from MIT and quite nice for the beginner.
364,304
I am interested in Fourier Analysis. But I don't get why the coefficients are choosen that way and why the Fourier series will converge to a given function? Can someone provide me simple information or do you know an easy source for a beginner? Regards, Kevin
2013/04/17
[ "https://math.stackexchange.com/questions/364304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73030/" ]
You ask some pretty profound questions. I will answer them as simply as I can. Before I do that, (and by now I seem like a shill for my old professor), I recommend the book from which I learned all of this, [Applied Analysis by the Hilbert Space Method](http://rads.stackoverflow.com/amzn/click/0486458016) by Samuel S. Holland. Despite the lumbering title, it really is an excellent book for undergraduates who have never heard of a Fourier series. When people speak of a Fourier series, they might speak of something like this $$f(x) = \frac{a\_0}{2} + \sum\_{n=1}^{\infty} (a\_n \cos{n x} + b\_n \sin{n x})$$ Behind this equation, though, buried inside, are some really profound things and assumptions about the very function we have chosen to write this way. There are even profound assumptions behind what the equals sign means! First of all, what can we say about $f$? Well, because we have chosen to set it equal to a bunch of sines and cosines of increasing frequencies, and those frequencies are just integers, we can say that $f$ must be periodic with frequency $2 \pi$. That is $$f(x+2 \pi) = f(x)$$ I hope you can see that. To do so, plug in $x+2 \pi$ into the right hand side (RHS). And then plug in something else, like $x+\pi$, and see what happens. OK, so you can see that not all functions may be written like that; they have to be periodic with period of $2 \pi$. What about the series itself? It is an infinite series, which means that we have to worry about whether it converges. And this is a very sticky point, because Fourier series do not converge to a single point $x$ like Taylor series. I'll talk about why that is in a minute. But, rather, allow me to state mathematically the meaning of the equal sign in the representation of $f$ as a Fourier series: $$\lim\_{N \rightarrow \infty} \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 = 0$$ The integral itself is what we call a mean square error - the average of the square of the error between $f$ and a partial sum. We define convergence not by convergence at a point, but by convergence in an average sense over the interval $[0,2 \pi]$. We do this so that we may speak of representing piecewise continuous objects like square waves, sawtooths, and the like. It turns out that near points of discontinuity, the series may not converge to those points - you may have heard of Gibbs phenomena. Now, the most important question: how do we determine the coefficients? We go back to the error definition. Define $$E(a\_0,a\_1,\ldots,a\_N,b\_1,\ldots,b\_N) = \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 $$ We naturally choose the $a\_k$ and $b\_k$ so that the error $E$ is a minimum. We simply demand that $$\frac{\partial E}{\partial a\_k} = 0$$ $$\frac{\partial E}{\partial b\_k} = 0$$ for all $k \in \{0,1,2,\ldots,N\}$. Let's work with the $b\_k$, as the operations on the $a\_k$ are nearly identical. We use the fact that we can take the derivative inside the integral (remember, the sum is finite and everything is well-behaved), and we get $$\frac{\partial E}{\partial b\_k} =2\int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ] (-\sin{k x}) = 0$$ Rearranging this a bit, we get $$\int\_0^{2 \pi} dx \: f(x) \sin{k x} = \sum\_{n=1}^{N} \int\_0^{2 \pi} dx \:(a\_n \cos{n x} + b\_n \sin{n x}) \sin{k x}$$ This normally would require us to solve $2N+1$ equations in the $2 N+1$ unknowns, which would make for a terrifying representation. But, we do have one trick up our sleeve: the sines and cosines of integer frequencies are very special in that they satisfy this really cool sifting property: $$\int\_0^{2 \pi} dx \: \sin{n x} \, \sin{k x} = \begin{cases} \\ \pi & n=k \\ 0 & n \ne k\end{cases}$$ $$\int\_0^{2 \pi} dx \: \cos{n x} \, \sin{k x} = 0$$ You can prove this to yourself using the sine and cosine addition formulae: $$2 \sin{a x} \, \sin{b x} = \cos{(a-b) x} - \cos{(a+b) x}$$ $$2 \sin{a x} \, \cos{b x} = \sin{(a+b) x} - \sin{(a-b) x}$$ and noting that the integral of a sine or cosine of a nonzero integer frequency over $[0,2 \pi]$ is zero. Therefore, the coefficients of the series are given by $$a\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \cos{n x}$$ $$b\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \sin{n x}$$ Further details and explanations may be found in the book I cited, Chapter 3.
The Fourier series converges given that the $f\in L^2(-l,l)$ for the given interval. That is $f$ is a function that satisfies $\int\_{-l}^{l}f^2 \, dx<+\infty$. There is a proof that shows that the series converges with this condition. The way to understant why coefficients are calculated as they are is to think that you are using a vector space of infinite dimension. That is $\{1,\sin({k\frac{\pi}{x}}),\cos({k\frac{\pi}{x}})\}$ (if you use a different basis is equivalent) is a basis of $L^2(-l,l)$, and any function that belongs to this space can be generated as an infinite linear combination of elements of the base. When you calculate the coefficients you are just calculating the projections of the function over each 'direction' given but each element of the basis. Of course the projection is donde using the dot product of the metric space we are using $L^2(-l,l)$, which is: $$\langle u,v\rangle=\int\_{-l}^{l}u\cdot v\,dx$$ where $u,v\in L^2(-l,l)$. You can find some notes about the topic [here](http://ocw.mit.edu/courses/mathematics/18-03sc-differential-equations-fall-2011/unit-iii-fourier-series-and-laplace-transform/fourier-series-basics/). This notes are from MIT and quite nice for the beginner.
364,304
I am interested in Fourier Analysis. But I don't get why the coefficients are choosen that way and why the Fourier series will converge to a given function? Can someone provide me simple information or do you know an easy source for a beginner? Regards, Kevin
2013/04/17
[ "https://math.stackexchange.com/questions/364304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73030/" ]
The best way I've found to think about Fourier analysis is: as the linear algebra of the vector space $L^2(S^1)$ in the basis $e\_k(x) = e^{2\pi ikx}$. In this perspective, as Myke Arya points out, you have an inner product $$\langle f,g\rangle = \int\_{S^1} f(x)g(x)dx$$ and Fourier series are just an orthonormal basis decomposition: $$f(x) = \sum\_k \langle f,e\_k\rangle e\_k(x).$$ This subject is not only interesting in its own right, it is deeply related to, for example, representation theory (the functions $e\_k$ are unitary representations of $\mathbb{R}$ on $\mathbb{C}$) and spectral analysis ($\Delta e\_k = 2\pi ke\_k$, where $\Delta$ is the Laplacian operator). I have found the book [*Fourier Series and Integrals*](http://rads.stackoverflow.com/amzn/click/0122264517), by Dym and McKean, to be very helpful as I have learned the subject.
The Fourier series converges given that the $f\in L^2(-l,l)$ for the given interval. That is $f$ is a function that satisfies $\int\_{-l}^{l}f^2 \, dx<+\infty$. There is a proof that shows that the series converges with this condition. The way to understant why coefficients are calculated as they are is to think that you are using a vector space of infinite dimension. That is $\{1,\sin({k\frac{\pi}{x}}),\cos({k\frac{\pi}{x}})\}$ (if you use a different basis is equivalent) is a basis of $L^2(-l,l)$, and any function that belongs to this space can be generated as an infinite linear combination of elements of the base. When you calculate the coefficients you are just calculating the projections of the function over each 'direction' given but each element of the basis. Of course the projection is donde using the dot product of the metric space we are using $L^2(-l,l)$, which is: $$\langle u,v\rangle=\int\_{-l}^{l}u\cdot v\,dx$$ where $u,v\in L^2(-l,l)$. You can find some notes about the topic [here](http://ocw.mit.edu/courses/mathematics/18-03sc-differential-equations-fall-2011/unit-iii-fourier-series-and-laplace-transform/fourier-series-basics/). This notes are from MIT and quite nice for the beginner.
364,304
I am interested in Fourier Analysis. But I don't get why the coefficients are choosen that way and why the Fourier series will converge to a given function? Can someone provide me simple information or do you know an easy source for a beginner? Regards, Kevin
2013/04/17
[ "https://math.stackexchange.com/questions/364304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73030/" ]
It seems to me, that you are interested in the identity \begin{equation} f(x) = \sum\_{k=-\infty}^\infty \frac{1}{2\pi} \int\_{-\pi}^\pi f(t) e^{-ikt} dt e^{ikx} \ , \end{equation} that is true for example if $f$ is $2\pi$-periodic and piecewise differentiable with finite number of pieces on the interval $[-\pi,\pi]$ and satisfies \begin{equation} f(x) = \frac{1}{2} (\lim\_{t \rightarrow x^+} f(t) + \lim\_{t \rightarrow x^-} f(t)) \end{equation} for every $x \in \mathbb{R}$. To see this, we define \begin{eqnarray} f(x+) & = & \lim\_{t \rightarrow x^+} f(t) \ , \\ f(x-) & = & \lim\_{t \rightarrow x^-} f(t) \ . \end{eqnarray} We calculate for $x \neq 2\pi k$ \begin{eqnarray} \sin(1/2 \ x) \sum\_{k=-n}^n e^{ikx} & = & \sin(1/2 \ x) (e^{-ix})^n \frac{1-(e^{ix})^{2n+1}}{1-e^{ix}} = \sin((n+1/2)x) \ . \end{eqnarray} The left hand side of the first equation equals to the right hand side of the second equation also for $x = 2\pi k$. We define \begin{eqnarray} h\_1(t) & = & \frac{f(x-t+)-f(x+)}{\sin(1/2 \ t)} \ , t \in (-\pi,0) \ , \\ h\_2(t) & = & \frac{f(x-t-)-f(x-)}{\sin(1/2 \ t)} \ , t \in (0,\pi) \ . \end{eqnarray} Then \begin{eqnarray} \sin(1/2 \ t) h\_1(t-) & = & f(x-t+)-f(x+) \ , t \in (-\pi,0] \ , \\ \sin(1/2 \ t) h\_2(t+) & = & f(x-t-)-f(x-) \ , t \in [0,\pi) \ . \end{eqnarray} Note that $h\_1(0-)$ equals to $-2$ times right derivative of $f(t+)$ at $x$ and $h\_2(0+)$ $-2$ times left derivative of $f(t-)$ at $x$. This is obtained by dividing and multiplying the expression of $h\_k$ by $1/2 \ t$ and taking limits when argument approaches to $0$ from left and right respectively. We calculate using the Riemann-Lebesgue lemma and obtain \begin{eqnarray} \sum\_{k=-\infty}^\infty & \frac{1}{2\pi} & \int\_{-\pi}^\pi f(t) e^{-ikt} dt e^{ikx} = \sum\_{k=-\infty}^\infty \frac{1}{2\pi} \int\_{x-\pi}^{x+\pi} f(t) e^{-ikt} dt e^{ikx} \\ & = & \lim\_{n \rightarrow \infty} \sum\_{k=-n}^n \frac{1}{2\pi} \int\_{x-\pi}^{x+\pi} f(t) e^{-ikt} dt e^{ikx} = \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{x-\pi}^{x+\pi} f(t) \sum\_{k=-n}^n e^{ik(x-t)} dt \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^\pi f(x-t) \sum\_{k=-n}^n e^{ikt} dt \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 f(x-t+) \sum\_{k=-n}^n e^{ikt} dt + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi f(x-t-) \sum\_{k=-n}^n e^{ikt} dt \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 (f(x-t+) - f(x+)) \sum\_{k=-n}^n e^{ikt} dt + \frac{1}{2} f(x+) \\ & & + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi (f(x-t-) - f(x-)) \sum\_{k=-n}^n e^{ikt} dt +\frac{1}{2} f(x-) \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 \sin(1/2 \ t) h\_1(t-) \sum\_{k=-n}^n e^{ikt} dt + \frac{1}{2} f(x+) \\ & & + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi \sin(1/2) h\_2(t+) \sum\_{k=-n}^n e^{ikt} dt +\frac{1}{2} f(x-) \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 h\_1(t-) \sin((n+1/2)t) dt + \frac{1}{2} f(x+) \\ & & + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi h\_2(t+) \sin((n+1/2)t) dt +\frac{1}{2} f(x-) \\ & = & \frac{1}{2} (f(x+) + f(x-)) = f(x) \ . \end{eqnarray} In the fifth equation integrands on the right hand side are changed to their right and left limits respectively. This doesn't influence to the value of the integral because the difference is nonzero on a finite set only. The function $h\_1(t-)$ has a limit as $t \rightarrow 0^-$. Hence it is bounded in a boundary of $0$. The expression of $h\_1$ is also bounded elsewhere. Similar reasoning shows that also $h\_2$ is bounded. Hence they are absolutely integrable and we may apply the Riemann-Lebesgue lemma. This shows that Fourier series converges to the function, from which the coefficients were calculated. Consider now two Fourier serieses of the same function $f$, \begin{eqnarray} f(x) & = & \sum\_{k=-\infty}^\infty c\_k^1 e^{ikx} \\ f(x) & = & \sum\_{k=-\infty}^\infty c\_k^2 e^{ikx} \ . \end{eqnarray} Sidewise substraction implies \begin{equation} 0 = \sum\_{k=0}^\infty (c\_k^1-c\_k^2) e^{ikx} \ . \end{equation} We also have \begin{equation} e^{inx} = \sum\_{k=-\infty}^\infty \delta\_{n,k} e^{ikx} \ . \end{equation} Parseval's theorem now implies \begin{eqnarray} \frac{1}{2\pi} \int\_{-\pi}^\pi 0 \overline{e^{inx}} dx & = & \sum\_{k=-\infty}^\infty (c\_k^1-c\_k^2)\overline{\delta\_{n,k}} \\ 0 & = & c\_n^1-c\_n^2 \ . \end{eqnarray} Hence $c\_n^1=c\_n^2$ for every $n \in \mathbb{Z}$. This shows that Fourier series is unique, that is there is only one way to choose the coefficients. It is \begin{equation} c\_k = \frac{1}{2\pi} \int\_{-\pi}^\pi f(t) e^{-ikt} dt \ . \end{equation} Fourier inversion theorem is more difficult to prove.
The Fourier series converges given that the $f\in L^2(-l,l)$ for the given interval. That is $f$ is a function that satisfies $\int\_{-l}^{l}f^2 \, dx<+\infty$. There is a proof that shows that the series converges with this condition. The way to understant why coefficients are calculated as they are is to think that you are using a vector space of infinite dimension. That is $\{1,\sin({k\frac{\pi}{x}}),\cos({k\frac{\pi}{x}})\}$ (if you use a different basis is equivalent) is a basis of $L^2(-l,l)$, and any function that belongs to this space can be generated as an infinite linear combination of elements of the base. When you calculate the coefficients you are just calculating the projections of the function over each 'direction' given but each element of the basis. Of course the projection is donde using the dot product of the metric space we are using $L^2(-l,l)$, which is: $$\langle u,v\rangle=\int\_{-l}^{l}u\cdot v\,dx$$ where $u,v\in L^2(-l,l)$. You can find some notes about the topic [here](http://ocw.mit.edu/courses/mathematics/18-03sc-differential-equations-fall-2011/unit-iii-fourier-series-and-laplace-transform/fourier-series-basics/). This notes are from MIT and quite nice for the beginner.
364,304
I am interested in Fourier Analysis. But I don't get why the coefficients are choosen that way and why the Fourier series will converge to a given function? Can someone provide me simple information or do you know an easy source for a beginner? Regards, Kevin
2013/04/17
[ "https://math.stackexchange.com/questions/364304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73030/" ]
You ask some pretty profound questions. I will answer them as simply as I can. Before I do that, (and by now I seem like a shill for my old professor), I recommend the book from which I learned all of this, [Applied Analysis by the Hilbert Space Method](http://rads.stackoverflow.com/amzn/click/0486458016) by Samuel S. Holland. Despite the lumbering title, it really is an excellent book for undergraduates who have never heard of a Fourier series. When people speak of a Fourier series, they might speak of something like this $$f(x) = \frac{a\_0}{2} + \sum\_{n=1}^{\infty} (a\_n \cos{n x} + b\_n \sin{n x})$$ Behind this equation, though, buried inside, are some really profound things and assumptions about the very function we have chosen to write this way. There are even profound assumptions behind what the equals sign means! First of all, what can we say about $f$? Well, because we have chosen to set it equal to a bunch of sines and cosines of increasing frequencies, and those frequencies are just integers, we can say that $f$ must be periodic with frequency $2 \pi$. That is $$f(x+2 \pi) = f(x)$$ I hope you can see that. To do so, plug in $x+2 \pi$ into the right hand side (RHS). And then plug in something else, like $x+\pi$, and see what happens. OK, so you can see that not all functions may be written like that; they have to be periodic with period of $2 \pi$. What about the series itself? It is an infinite series, which means that we have to worry about whether it converges. And this is a very sticky point, because Fourier series do not converge to a single point $x$ like Taylor series. I'll talk about why that is in a minute. But, rather, allow me to state mathematically the meaning of the equal sign in the representation of $f$ as a Fourier series: $$\lim\_{N \rightarrow \infty} \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 = 0$$ The integral itself is what we call a mean square error - the average of the square of the error between $f$ and a partial sum. We define convergence not by convergence at a point, but by convergence in an average sense over the interval $[0,2 \pi]$. We do this so that we may speak of representing piecewise continuous objects like square waves, sawtooths, and the like. It turns out that near points of discontinuity, the series may not converge to those points - you may have heard of Gibbs phenomena. Now, the most important question: how do we determine the coefficients? We go back to the error definition. Define $$E(a\_0,a\_1,\ldots,a\_N,b\_1,\ldots,b\_N) = \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 $$ We naturally choose the $a\_k$ and $b\_k$ so that the error $E$ is a minimum. We simply demand that $$\frac{\partial E}{\partial a\_k} = 0$$ $$\frac{\partial E}{\partial b\_k} = 0$$ for all $k \in \{0,1,2,\ldots,N\}$. Let's work with the $b\_k$, as the operations on the $a\_k$ are nearly identical. We use the fact that we can take the derivative inside the integral (remember, the sum is finite and everything is well-behaved), and we get $$\frac{\partial E}{\partial b\_k} =2\int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ] (-\sin{k x}) = 0$$ Rearranging this a bit, we get $$\int\_0^{2 \pi} dx \: f(x) \sin{k x} = \sum\_{n=1}^{N} \int\_0^{2 \pi} dx \:(a\_n \cos{n x} + b\_n \sin{n x}) \sin{k x}$$ This normally would require us to solve $2N+1$ equations in the $2 N+1$ unknowns, which would make for a terrifying representation. But, we do have one trick up our sleeve: the sines and cosines of integer frequencies are very special in that they satisfy this really cool sifting property: $$\int\_0^{2 \pi} dx \: \sin{n x} \, \sin{k x} = \begin{cases} \\ \pi & n=k \\ 0 & n \ne k\end{cases}$$ $$\int\_0^{2 \pi} dx \: \cos{n x} \, \sin{k x} = 0$$ You can prove this to yourself using the sine and cosine addition formulae: $$2 \sin{a x} \, \sin{b x} = \cos{(a-b) x} - \cos{(a+b) x}$$ $$2 \sin{a x} \, \cos{b x} = \sin{(a+b) x} - \sin{(a-b) x}$$ and noting that the integral of a sine or cosine of a nonzero integer frequency over $[0,2 \pi]$ is zero. Therefore, the coefficients of the series are given by $$a\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \cos{n x}$$ $$b\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \sin{n x}$$ Further details and explanations may be found in the book I cited, Chapter 3.
You can try to read something in Rudin's book (pg 185). <http://www.scribd.com/doc/9654478/Principles-of-Mathematical-Analysis-Third-Edition-Walter-Rudin> In my opinion Stein and Shakarchi Fourier Analysis is a clear and perfectly written textbook. <http://press.princeton.edu/titles/7562.html>
364,304
I am interested in Fourier Analysis. But I don't get why the coefficients are choosen that way and why the Fourier series will converge to a given function? Can someone provide me simple information or do you know an easy source for a beginner? Regards, Kevin
2013/04/17
[ "https://math.stackexchange.com/questions/364304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73030/" ]
You ask some pretty profound questions. I will answer them as simply as I can. Before I do that, (and by now I seem like a shill for my old professor), I recommend the book from which I learned all of this, [Applied Analysis by the Hilbert Space Method](http://rads.stackoverflow.com/amzn/click/0486458016) by Samuel S. Holland. Despite the lumbering title, it really is an excellent book for undergraduates who have never heard of a Fourier series. When people speak of a Fourier series, they might speak of something like this $$f(x) = \frac{a\_0}{2} + \sum\_{n=1}^{\infty} (a\_n \cos{n x} + b\_n \sin{n x})$$ Behind this equation, though, buried inside, are some really profound things and assumptions about the very function we have chosen to write this way. There are even profound assumptions behind what the equals sign means! First of all, what can we say about $f$? Well, because we have chosen to set it equal to a bunch of sines and cosines of increasing frequencies, and those frequencies are just integers, we can say that $f$ must be periodic with frequency $2 \pi$. That is $$f(x+2 \pi) = f(x)$$ I hope you can see that. To do so, plug in $x+2 \pi$ into the right hand side (RHS). And then plug in something else, like $x+\pi$, and see what happens. OK, so you can see that not all functions may be written like that; they have to be periodic with period of $2 \pi$. What about the series itself? It is an infinite series, which means that we have to worry about whether it converges. And this is a very sticky point, because Fourier series do not converge to a single point $x$ like Taylor series. I'll talk about why that is in a minute. But, rather, allow me to state mathematically the meaning of the equal sign in the representation of $f$ as a Fourier series: $$\lim\_{N \rightarrow \infty} \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 = 0$$ The integral itself is what we call a mean square error - the average of the square of the error between $f$ and a partial sum. We define convergence not by convergence at a point, but by convergence in an average sense over the interval $[0,2 \pi]$. We do this so that we may speak of representing piecewise continuous objects like square waves, sawtooths, and the like. It turns out that near points of discontinuity, the series may not converge to those points - you may have heard of Gibbs phenomena. Now, the most important question: how do we determine the coefficients? We go back to the error definition. Define $$E(a\_0,a\_1,\ldots,a\_N,b\_1,\ldots,b\_N) = \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 $$ We naturally choose the $a\_k$ and $b\_k$ so that the error $E$ is a minimum. We simply demand that $$\frac{\partial E}{\partial a\_k} = 0$$ $$\frac{\partial E}{\partial b\_k} = 0$$ for all $k \in \{0,1,2,\ldots,N\}$. Let's work with the $b\_k$, as the operations on the $a\_k$ are nearly identical. We use the fact that we can take the derivative inside the integral (remember, the sum is finite and everything is well-behaved), and we get $$\frac{\partial E}{\partial b\_k} =2\int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ] (-\sin{k x}) = 0$$ Rearranging this a bit, we get $$\int\_0^{2 \pi} dx \: f(x) \sin{k x} = \sum\_{n=1}^{N} \int\_0^{2 \pi} dx \:(a\_n \cos{n x} + b\_n \sin{n x}) \sin{k x}$$ This normally would require us to solve $2N+1$ equations in the $2 N+1$ unknowns, which would make for a terrifying representation. But, we do have one trick up our sleeve: the sines and cosines of integer frequencies are very special in that they satisfy this really cool sifting property: $$\int\_0^{2 \pi} dx \: \sin{n x} \, \sin{k x} = \begin{cases} \\ \pi & n=k \\ 0 & n \ne k\end{cases}$$ $$\int\_0^{2 \pi} dx \: \cos{n x} \, \sin{k x} = 0$$ You can prove this to yourself using the sine and cosine addition formulae: $$2 \sin{a x} \, \sin{b x} = \cos{(a-b) x} - \cos{(a+b) x}$$ $$2 \sin{a x} \, \cos{b x} = \sin{(a+b) x} - \sin{(a-b) x}$$ and noting that the integral of a sine or cosine of a nonzero integer frequency over $[0,2 \pi]$ is zero. Therefore, the coefficients of the series are given by $$a\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \cos{n x}$$ $$b\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \sin{n x}$$ Further details and explanations may be found in the book I cited, Chapter 3.
The best way I've found to think about Fourier analysis is: as the linear algebra of the vector space $L^2(S^1)$ in the basis $e\_k(x) = e^{2\pi ikx}$. In this perspective, as Myke Arya points out, you have an inner product $$\langle f,g\rangle = \int\_{S^1} f(x)g(x)dx$$ and Fourier series are just an orthonormal basis decomposition: $$f(x) = \sum\_k \langle f,e\_k\rangle e\_k(x).$$ This subject is not only interesting in its own right, it is deeply related to, for example, representation theory (the functions $e\_k$ are unitary representations of $\mathbb{R}$ on $\mathbb{C}$) and spectral analysis ($\Delta e\_k = 2\pi ke\_k$, where $\Delta$ is the Laplacian operator). I have found the book [*Fourier Series and Integrals*](http://rads.stackoverflow.com/amzn/click/0122264517), by Dym and McKean, to be very helpful as I have learned the subject.
364,304
I am interested in Fourier Analysis. But I don't get why the coefficients are choosen that way and why the Fourier series will converge to a given function? Can someone provide me simple information or do you know an easy source for a beginner? Regards, Kevin
2013/04/17
[ "https://math.stackexchange.com/questions/364304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73030/" ]
You ask some pretty profound questions. I will answer them as simply as I can. Before I do that, (and by now I seem like a shill for my old professor), I recommend the book from which I learned all of this, [Applied Analysis by the Hilbert Space Method](http://rads.stackoverflow.com/amzn/click/0486458016) by Samuel S. Holland. Despite the lumbering title, it really is an excellent book for undergraduates who have never heard of a Fourier series. When people speak of a Fourier series, they might speak of something like this $$f(x) = \frac{a\_0}{2} + \sum\_{n=1}^{\infty} (a\_n \cos{n x} + b\_n \sin{n x})$$ Behind this equation, though, buried inside, are some really profound things and assumptions about the very function we have chosen to write this way. There are even profound assumptions behind what the equals sign means! First of all, what can we say about $f$? Well, because we have chosen to set it equal to a bunch of sines and cosines of increasing frequencies, and those frequencies are just integers, we can say that $f$ must be periodic with frequency $2 \pi$. That is $$f(x+2 \pi) = f(x)$$ I hope you can see that. To do so, plug in $x+2 \pi$ into the right hand side (RHS). And then plug in something else, like $x+\pi$, and see what happens. OK, so you can see that not all functions may be written like that; they have to be periodic with period of $2 \pi$. What about the series itself? It is an infinite series, which means that we have to worry about whether it converges. And this is a very sticky point, because Fourier series do not converge to a single point $x$ like Taylor series. I'll talk about why that is in a minute. But, rather, allow me to state mathematically the meaning of the equal sign in the representation of $f$ as a Fourier series: $$\lim\_{N \rightarrow \infty} \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 = 0$$ The integral itself is what we call a mean square error - the average of the square of the error between $f$ and a partial sum. We define convergence not by convergence at a point, but by convergence in an average sense over the interval $[0,2 \pi]$. We do this so that we may speak of representing piecewise continuous objects like square waves, sawtooths, and the like. It turns out that near points of discontinuity, the series may not converge to those points - you may have heard of Gibbs phenomena. Now, the most important question: how do we determine the coefficients? We go back to the error definition. Define $$E(a\_0,a\_1,\ldots,a\_N,b\_1,\ldots,b\_N) = \int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ]^2 $$ We naturally choose the $a\_k$ and $b\_k$ so that the error $E$ is a minimum. We simply demand that $$\frac{\partial E}{\partial a\_k} = 0$$ $$\frac{\partial E}{\partial b\_k} = 0$$ for all $k \in \{0,1,2,\ldots,N\}$. Let's work with the $b\_k$, as the operations on the $a\_k$ are nearly identical. We use the fact that we can take the derivative inside the integral (remember, the sum is finite and everything is well-behaved), and we get $$\frac{\partial E}{\partial b\_k} =2\int\_0^{2 \pi} dx \left [ f(x) - \frac{a\_0}{2}- \sum\_{n=1}^{N} (a\_n \cos{n x} + b\_n \sin{n x}) \right ] (-\sin{k x}) = 0$$ Rearranging this a bit, we get $$\int\_0^{2 \pi} dx \: f(x) \sin{k x} = \sum\_{n=1}^{N} \int\_0^{2 \pi} dx \:(a\_n \cos{n x} + b\_n \sin{n x}) \sin{k x}$$ This normally would require us to solve $2N+1$ equations in the $2 N+1$ unknowns, which would make for a terrifying representation. But, we do have one trick up our sleeve: the sines and cosines of integer frequencies are very special in that they satisfy this really cool sifting property: $$\int\_0^{2 \pi} dx \: \sin{n x} \, \sin{k x} = \begin{cases} \\ \pi & n=k \\ 0 & n \ne k\end{cases}$$ $$\int\_0^{2 \pi} dx \: \cos{n x} \, \sin{k x} = 0$$ You can prove this to yourself using the sine and cosine addition formulae: $$2 \sin{a x} \, \sin{b x} = \cos{(a-b) x} - \cos{(a+b) x}$$ $$2 \sin{a x} \, \cos{b x} = \sin{(a+b) x} - \sin{(a-b) x}$$ and noting that the integral of a sine or cosine of a nonzero integer frequency over $[0,2 \pi]$ is zero. Therefore, the coefficients of the series are given by $$a\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \cos{n x}$$ $$b\_n = \frac{1}{\pi} \int\_0^{2 \pi} dx \: f(x) \sin{n x}$$ Further details and explanations may be found in the book I cited, Chapter 3.
It seems to me, that you are interested in the identity \begin{equation} f(x) = \sum\_{k=-\infty}^\infty \frac{1}{2\pi} \int\_{-\pi}^\pi f(t) e^{-ikt} dt e^{ikx} \ , \end{equation} that is true for example if $f$ is $2\pi$-periodic and piecewise differentiable with finite number of pieces on the interval $[-\pi,\pi]$ and satisfies \begin{equation} f(x) = \frac{1}{2} (\lim\_{t \rightarrow x^+} f(t) + \lim\_{t \rightarrow x^-} f(t)) \end{equation} for every $x \in \mathbb{R}$. To see this, we define \begin{eqnarray} f(x+) & = & \lim\_{t \rightarrow x^+} f(t) \ , \\ f(x-) & = & \lim\_{t \rightarrow x^-} f(t) \ . \end{eqnarray} We calculate for $x \neq 2\pi k$ \begin{eqnarray} \sin(1/2 \ x) \sum\_{k=-n}^n e^{ikx} & = & \sin(1/2 \ x) (e^{-ix})^n \frac{1-(e^{ix})^{2n+1}}{1-e^{ix}} = \sin((n+1/2)x) \ . \end{eqnarray} The left hand side of the first equation equals to the right hand side of the second equation also for $x = 2\pi k$. We define \begin{eqnarray} h\_1(t) & = & \frac{f(x-t+)-f(x+)}{\sin(1/2 \ t)} \ , t \in (-\pi,0) \ , \\ h\_2(t) & = & \frac{f(x-t-)-f(x-)}{\sin(1/2 \ t)} \ , t \in (0,\pi) \ . \end{eqnarray} Then \begin{eqnarray} \sin(1/2 \ t) h\_1(t-) & = & f(x-t+)-f(x+) \ , t \in (-\pi,0] \ , \\ \sin(1/2 \ t) h\_2(t+) & = & f(x-t-)-f(x-) \ , t \in [0,\pi) \ . \end{eqnarray} Note that $h\_1(0-)$ equals to $-2$ times right derivative of $f(t+)$ at $x$ and $h\_2(0+)$ $-2$ times left derivative of $f(t-)$ at $x$. This is obtained by dividing and multiplying the expression of $h\_k$ by $1/2 \ t$ and taking limits when argument approaches to $0$ from left and right respectively. We calculate using the Riemann-Lebesgue lemma and obtain \begin{eqnarray} \sum\_{k=-\infty}^\infty & \frac{1}{2\pi} & \int\_{-\pi}^\pi f(t) e^{-ikt} dt e^{ikx} = \sum\_{k=-\infty}^\infty \frac{1}{2\pi} \int\_{x-\pi}^{x+\pi} f(t) e^{-ikt} dt e^{ikx} \\ & = & \lim\_{n \rightarrow \infty} \sum\_{k=-n}^n \frac{1}{2\pi} \int\_{x-\pi}^{x+\pi} f(t) e^{-ikt} dt e^{ikx} = \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{x-\pi}^{x+\pi} f(t) \sum\_{k=-n}^n e^{ik(x-t)} dt \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^\pi f(x-t) \sum\_{k=-n}^n e^{ikt} dt \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 f(x-t+) \sum\_{k=-n}^n e^{ikt} dt + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi f(x-t-) \sum\_{k=-n}^n e^{ikt} dt \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 (f(x-t+) - f(x+)) \sum\_{k=-n}^n e^{ikt} dt + \frac{1}{2} f(x+) \\ & & + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi (f(x-t-) - f(x-)) \sum\_{k=-n}^n e^{ikt} dt +\frac{1}{2} f(x-) \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 \sin(1/2 \ t) h\_1(t-) \sum\_{k=-n}^n e^{ikt} dt + \frac{1}{2} f(x+) \\ & & + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi \sin(1/2) h\_2(t+) \sum\_{k=-n}^n e^{ikt} dt +\frac{1}{2} f(x-) \\ & = & \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_{-\pi}^0 h\_1(t-) \sin((n+1/2)t) dt + \frac{1}{2} f(x+) \\ & & + \lim\_{n \rightarrow \infty} \frac{1}{2\pi} \int\_0^\pi h\_2(t+) \sin((n+1/2)t) dt +\frac{1}{2} f(x-) \\ & = & \frac{1}{2} (f(x+) + f(x-)) = f(x) \ . \end{eqnarray} In the fifth equation integrands on the right hand side are changed to their right and left limits respectively. This doesn't influence to the value of the integral because the difference is nonzero on a finite set only. The function $h\_1(t-)$ has a limit as $t \rightarrow 0^-$. Hence it is bounded in a boundary of $0$. The expression of $h\_1$ is also bounded elsewhere. Similar reasoning shows that also $h\_2$ is bounded. Hence they are absolutely integrable and we may apply the Riemann-Lebesgue lemma. This shows that Fourier series converges to the function, from which the coefficients were calculated. Consider now two Fourier serieses of the same function $f$, \begin{eqnarray} f(x) & = & \sum\_{k=-\infty}^\infty c\_k^1 e^{ikx} \\ f(x) & = & \sum\_{k=-\infty}^\infty c\_k^2 e^{ikx} \ . \end{eqnarray} Sidewise substraction implies \begin{equation} 0 = \sum\_{k=0}^\infty (c\_k^1-c\_k^2) e^{ikx} \ . \end{equation} We also have \begin{equation} e^{inx} = \sum\_{k=-\infty}^\infty \delta\_{n,k} e^{ikx} \ . \end{equation} Parseval's theorem now implies \begin{eqnarray} \frac{1}{2\pi} \int\_{-\pi}^\pi 0 \overline{e^{inx}} dx & = & \sum\_{k=-\infty}^\infty (c\_k^1-c\_k^2)\overline{\delta\_{n,k}} \\ 0 & = & c\_n^1-c\_n^2 \ . \end{eqnarray} Hence $c\_n^1=c\_n^2$ for every $n \in \mathbb{Z}$. This shows that Fourier series is unique, that is there is only one way to choose the coefficients. It is \begin{equation} c\_k = \frac{1}{2\pi} \int\_{-\pi}^\pi f(t) e^{-ikt} dt \ . \end{equation} Fourier inversion theorem is more difficult to prove.
61,997,720
I know the recomended way to know in Android if a location is a fake point is something like this: ``` boolean isMock = false; if (android.os.Build.VERSION.SDK_INT >= 18) { isMock = location.isFromMockProvider(); } else { // Old Android versions (<6) isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"); } ``` So, for current Androids I have to request location permission to know if this is a mock location. But I think it is not necessary if I can read "select mock location app". [![hunk of Android developer options huk](https://i.stack.imgur.com/hdgpK.jpg)](https://i.stack.imgur.com/hdgpK.jpg) Also, if you want to show an alert message you can custom this message. e.g.: You could say something like this: "Please remove com.lexa.fakegps app". And when user clicks on "Accept", you could redirect to next link: <https://play.google.com/store/apps/details?id=com.lexa.fakegps> Also, there are fake gps apps that return false in the isFromMockProvider method. Also, you can do stats with apps more use for yours users. And finally, I don't understood why you can read every setting of developer settings except "select mock location app": <https://developer.android.com/reference/android/provider/Settings> Is there any solution? Or simply is it a stupid impossible thing?
2020/05/25
[ "https://Stackoverflow.com/questions/61997720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073310/" ]
I haven't tested this but this looks legit. I spent an hour or so trying to come up with my own solution and it was right there on GitHub. <https://github.com/GantMan/jail-monkey/blob/master/android/src/main/java/com/gantix/JailMonkey/MockLocation/MockLocationCheck.java>
So first of all... by using the following code ``` boolean isMock = false; if (android.os.Build.VERSION.SDK_INT >= 18) { isMock = location.isFromMockProvider(); } else { // Old Android versions (<6) isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"); } ``` you can't ensure the device location is faked all the time. For older versions of android ``` isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"); ``` is being used but what it does basically it just gives whether the user turned on the settings for allowing mock location... so it just acts as a filter to check So if I am using an old phone and turn this setting on even if I am not using fake location it still returns true For latest versions of android ``` isMock = location.isFromMockProvider(); ``` it is buggy ... may not always return correct answer i.e even if you set the location using mock location app sometimes it may return false. **Conclusion:** To conclude reading the "select mock location app" setting and making a decision on its value is just a stupid thing. and you can't write software that is always bug-free. I personally tried and tested with some of the fake GPS apps like [Lexa Fake GPS Location](https://play.google.com/store/apps/details?id=com.lexa.fakegps) [Fake GPS](https://play.google.com/store/apps/details?id=com.blogspot.newapphorizons.fakegps) for me during my tests **isFromMockProvider()** always returned me the correct output So I found it the probability of finding the bug is rare. And in order to make sure it's a buggy value I found this remedy on this post : [Location on Android: Stop Mocking Me!](https://www.klaasnotfound.com/2016/05/27/location-on-android-stop-mocking-me//) I quote remedy from this article > > Since most location readings are correctly labeled, it’s not too > difficult to identify and reject the false negatives. I chose the > following strategy: > > > * Remember the most recent location labeled as a mock * If a new “non-mock” reading is within 1km of the last mock, reject it. * Only clear the last mock location after 20 consecutive “non-mock” readings. And I also recommend you to go through [FauChristian Answer for Detect or prevent if the user uses fake location](https://stackoverflow.com/a/42756106/9365212) Thank you...
5,817,080
what's wrong with this code? ``` module Main where import System.Environment main :: IO () main = do args <- getArgs putStrLn ("Hello, " ++ args !! 0 ++ ", " ++ args !! 1) putStrLn(add (read args !! 0) (read args !! 1)) add x y = x + y ``` Here are the error messages: ``` main.hs:8:15: No instance for (Num String) arising from a use of `add' Possible fix: add an instance declaration for (Num String) In the first argument of `putStrLn', namely `(add (read args !! 0) (read args !! 1))' In the expression: putStrLn (add (read args !! 0) (read args !! 1)) In the expression: do { args <- getArgs; putStrLn ("Hello, " ++ args !! 0 ++ ", " ++ args !! 1); putStrLn (add (read args !! 0) (read args !! 1)) } main.hs:8:25: Couldn't match expected type `Char' with actual type `[Char]' Expected type: String Actual type: [String] In the first argument of `read', namely `args' In the first argument of `(!!)', namely `read args' ```
2011/04/28
[ "https://Stackoverflow.com/questions/5817080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457261/" ]
`read args !! 0` should be `read (args !! 0)` and `add x y = x +` should be `add x y = x + y`. Also `putStrLn` takes a string only, so use `print` instead which also prints numbers. --- However, seeing you are new to haskell. I rewrote part of your program to demonstrate a more haskellish way. ``` main = do (arg0:arg1:restArgs) <- getArgs putStrLn $ "Hello, " ++ arg0 ++ ", " ++ arg1 print $ add (read arg0) (read arg1) add = (+) ``` I think it looks a bit cleaner now. Note that it's most often considered bad practice to use `!!`.
Just to add a little elaboration on the error messages and the solution given. Looking at the first error: ``` No instance for (Num String) ... In the first argument of `putStrLn' ``` This might be a bit unclear. Have a look at the type signature for putStrLn: ``` putStrLn :: String -> IO () ``` So, putStrLn is a function that takes a String and evaluates to an IO action. However you have directly **tried to pass putStrLn some expression like (x + y), which is a number**, and Strings are not numbers (in Haskell terms, its type signature is (Num t) => t). The solution given above suggests using the print function instead: ``` print :: (Show a) => a -> IO () ``` The difference between 'print' and 'putStrLn' is that **print can take anything showable**, which includes numbers. Next up: ``` Couldn't match expected type `Char' with actual type `[Char]' Expected type: String Actual type: [String] In the first argument of `read', namely `args' ``` This says **the compiler expected a String as the first argument to read, but saw a list of Strings**. Looking at the original code: ``` read args !! 0 ``` In Haskell, function application has highest precedence, so the compiler basically reads your code like so: ``` (read args) !! 0 ``` (note in particular that the application of read binds higher than the use of the !! operator). Hopefully it should be clear now that **read has been applied to all of args**. As your intention seemed to be to read the first element of args, you need to use parentheses like so: ``` read (args !! 0) ``` Hope this makes the error messages a little more understandable!
61,800,783
I am having a CSV file like this: ``` Adult literacy rate, population 15+ years, female (%),United Republic of Tanzania,2015,76.08978 Adult literacy rate, population 15+ years, female (%),Zimbabwe,2015,85.28513 Adult literacy rate, population 15+ years, male (%),Honduras,2014,87.39595 Adult literacy rate, population 15+ years, male (%),Honduras,2015,88.32135 Adult literacy rate, population 15+ years, male (%),Angola,2014,82.15105 ``` And a class for saving a line from it: ``` public class Line { //Adult literacy rate, population 15+ years, male (%),Angola,2014,82.15105 private final String gender; private final String country; private final int year; private final Float prosent; public Line(String gender, String country, String year, String prosent) { this.gender = gender; this.country = country; this.year = Integer.valueOf(year); this.prosent = Float.valueOf(prosent); } public String getGender() { return gender; } public String getCountry() { return country; } public int getYear() { return year; } public Float getProsent() { return prosent; } @Override public String toString() { return String.format("%.5s",country) + ", " + year + ", " + String.format("%.2f",prosent); } } ``` And I am grouping like this with `stream.collect(Collectors.groupBy....` ``` Stream<String> file = Stream.empty(); try { file = Files.lines(Paths.get("lukutaito_lyh.txt")); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } Map<String, List<Line>> lista = file .map(r -> r.split(",")) .map(r -> new Line(r[2], r[3], r[4], r[5])) .collect(Collectors.groupingBy(r -> r.getGender())); System.out.println(lista); ``` And I get this as expected: ``` { female (%)=[Unite, 2015, 76,09, Zimba, 2015, 85,29], male (%)=[Hondu, 2014, 87,40, Hondu, 2015, 88,32, Angol, 2014, 82,15]} ``` Could I do something like this? Without the trouble of writing class. ``` .map(r -> r.split(",")) .collect(Collectors.groupingBy(r -> r[2])); ```
2020/05/14
[ "https://Stackoverflow.com/questions/61800783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5639775/" ]
You can double-check like this : ``` if (props.data && props.data.length) ```
Check to see if the data exists ``` if (props?.data) ```
29,898,105
So I've tried to custom make a navbar that is set right below a border around a page. I've made an illustration to help explain: ![enter image description here](https://i.stack.imgur.com/Kpica.png) On the page, I have a border (blue) around the whole page, then the navbar (red) which scrolls with the page until it hits the top of the navbar and sticks until the user scrolls back up. My problem is that it seems like something is shoving my navbar and its contents to the right once the js kicks (when the user scrolls past the top border) making an obvious jerk movement. ![enter image description here](https://i.stack.imgur.com/zp5Od.png) Here is my html: ``` <html> <head> <title>Title</title> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> </head> <body> <%= yield :scss %> <div class="container-main <%= layout %>"> <nav class="main-nav"> <a class="navbar-brand" href="#"> <i class="fa fa-bars menu-icon"></i> </a> </nav> <div class="container"> <%= yield %> </div> </div> <%= yield :js %> </body> </html> ``` Would anyone know how to fix this? I'm not sure if its a bootstrap thing that needs to be overridden or what...I've tried to set the navbar's margin-left to equate the movement but it ends up messing up the bootstrap columns I have set up...any advice appreciated! Here is my CSS: ``` .main-nav { text-align: center; margin-top: 50px; background: transparent; height: 50px; z-index: 150; margin-bottom: -50px; } .main-nav-scrolled { position: fixed; width: 100%; top: 0; // margin-left: -35px; not working } .main-nav, .container { position: relative; } .container { background: transparent; padding: 100px } .layout-with-border { background: #eaeae8; //fixed for all product pages border: 35px solid #dad4c9; //theme color light } .layout-without-order { } ``` Here is my JS: ``` var mn = $(".main-nav"); mns = "main-nav-scrolled"; var BorderWidth = 35; $(window).scroll(function() { if( $(this).scrollTop() > BorderWidth ) { mn.addClass(mns); } else { mn.removeClass(mns); } }); ``` Sorry, it's a little confusing how to post so many parts since I'm so new. I created a helper for the border layout: ``` module ApplicationHelper def layout if params[:controller] == 'products' && params[:action] == 'show' 'layout-with-border' elsif params[:controller] == 'volumes' && params[:action] == 'show' 'layout-with-border' else 'layout-without-border' end end end ```
2015/04/27
[ "https://Stackoverflow.com/questions/29898105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4795788/" ]
Your code is very close to what you need. The glitch is due to changing from `position: relative` to `position: fixed` in `.main-nav`. Fixed elements widths are computed with respect to the viewport, not the parent container. First, zero-out the margin on `body` (if needed, depends on your design). For illustration, I added the 35px blue border on `.main-container`. Then, for `.main-nav-scrolled`, set both the left and right offsets to 35px to set the correct width of the `nav` block, you don't need to set the width value. **Note:** The content in `.container` jumps upward by 50px when the scroll hits the trigger point. To stop this, you would need to add 50px padding to `.container-main` or a 50px top margin to `.container` when you fix the `nav` element. I chose to add padding, see changes in the jQuery below. ```js var mn = $(".container-main"); mns = "main-nav-scrolled"; var BorderWidth = 35; $(window).scroll(function() { if ($(this).scrollTop() > BorderWidth) { mn.addClass(mns); } else { mn.removeClass(mns); } }); ``` ```css body { margin: 0; } .container-main { border: 35px solid lightblue; } .main-nav { text-align: center; margin-top: 0px; background: yellow; height: 50px; } .main-nav-scrolled .main-nav { position: fixed; top: 0; left: 35px; right: 35px; z-index: 1; } .main-nav-scrolled.container-main { padding-top: 50px; } .container { position: relative; background: beige; padding: 100px; height: 400px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container-main"> <nav class="main-nav"> <a class="navbar-brand" href="#"> <i class="fa fa-bars menu-icon">Icon</i> </a> </nav> <div class="container">container content...</div> </div> ```
define a `max-width:` to your nav element itself or parent wrapper. You should have a div wrapper around the middle of the page outside of the full width wrapper - that I am seeing. *Eg something like below.* ``` #middle_page_wrap { width: 960px; max-width: 960px; margin: 0 auto; position: relative; } ``` And like: ``` <div class="container-main"> <div id="middle_page_wrap"><!-- nest --> <nav class="main-nav"> <a class="navbar-brand" href="#"> <i class="fa fa-bars menu-icon"></i> </a> </nav> <!-- etc --> ``` *Also, yeah I agree with the comments; not sure what JS or dynamic tool or other languages are at play here. But* **sounds like a pure CSS thing** If this doesn't work then its because of code you are not showing, you'll have to create a demo / jsfiddle.
396,044
Need move files with multiple, defined patterns, like: ``` Z_*ana_bwk_na_N*.png Z_*ana_bwk_dwda*.png Z_*ana_bwkman_dwdna* Z_*ana_bwkman_dwdc* Z_*EDZW*_nwv01*_p00_na_N*WV11.png Z_*EDZW*_nwv01*_p00_nh_N*WV11.png Z_*nwv01*_hsy_NA*.png Z_*EDZW_*_htp_na_N_*_WV11SW.png Z_*_rft_na_*.png Z_*_r12* ``` from one defined folder, to another. How it can be done in best economic way? In a script, running from cron? Can this patterns be defined better in same script, or get from separate textfile, containing them?
2017/10/04
[ "https://unix.stackexchange.com/questions/396044", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/254067/" ]
It's simple: ``` mv Z_*ana_bwk_na_N*.png Z_*ana_bwk_dwda*.png Z_*ana_bwkman_dwdna* -t /your/directory/ ``` If you want it more elegant with input from file: ``` PATTERNS=`cat input.txt | paste -sd " " - ` && mv $PATTERNS -t /your/directory/ ```
The most efficient, but possibly the least legible, approach is to just enumerate everything in one big happy `mv` command. ``` mv Z_*ana_bwk_na_N*.png \ Z_*ana_bwk_dwda*.png \ Z_*ana_bwkman_dwdna* \ Z_*ana_bwkman_dwdc* \ Z_*EDZW*_nwv01*_p00_na_N*WV11.png \ Z_*EDZW*_nwv01*_p00_nh_N*WV11.png \ Z_*nwv01*_hsy_NA*.png \ Z_*EDZW_*_htp_na_N_*_WV11SW.png \ Z_*_rft_na_*.png \ Z_*_r12* \ destination ``` If you want to split this up (perhaps because you get "command line too long") you can use a here document. ``` while read files; do mv $files dest done <<____ Z_*ana_bwk_na_N*.png Z_*ana_bwk_dwda*.png Z_*ana_bwkman_dwdna* Z_*ana_bwkman_dwdc* Z_*EDZW*_nwv01*_p00_na_N*WV11.png Z_*EDZW*_nwv01*_p00_nh_N*WV11.png Z_*nwv01*_hsy_NA*.png Z_*EDZW_*_htp_na_N_*_WV11SW.png Z_*_rft_na_*.png Z_*_r12* ____ ``` If you want to parametrize the destination, you can do that too. ``` while read destination files; do mv $files "$destination" done <<____ here Z_*ana_bwk_na_N*.png here Z_*ana_bwk_dwda*.png here Z_*ana_bwkman_dwdna* there Z_*ana_bwkman_dwdc* there Z_*EDZW*_nwv01*_p00_na_N*WV11.png everywhere Z_*EDZW*_nwv01*_p00_nh_N*WV11.png here Z_*nwv01*_hsy_NA*.png elsewhere Z_*EDZW_*_htp_na_N_*_WV11SW.png there Z_*_rft_na_*.png anywhere Z_*_r12* ____ ``` Somewhat confusingly, the wildcards in the here document will be expanded by the shell *before the loop runs.* Because we need the inner loop to be unquoted, the expanded file names cannot contain any shell metacharacters (which do not match exactly only themselves -- typically irregular whitespace or wildcard expressions).
396,044
Need move files with multiple, defined patterns, like: ``` Z_*ana_bwk_na_N*.png Z_*ana_bwk_dwda*.png Z_*ana_bwkman_dwdna* Z_*ana_bwkman_dwdc* Z_*EDZW*_nwv01*_p00_na_N*WV11.png Z_*EDZW*_nwv01*_p00_nh_N*WV11.png Z_*nwv01*_hsy_NA*.png Z_*EDZW_*_htp_na_N_*_WV11SW.png Z_*_rft_na_*.png Z_*_r12* ``` from one defined folder, to another. How it can be done in best economic way? In a script, running from cron? Can this patterns be defined better in same script, or get from separate textfile, containing them?
2017/10/04
[ "https://unix.stackexchange.com/questions/396044", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/254067/" ]
It's simple: ``` mv Z_*ana_bwk_na_N*.png Z_*ana_bwk_dwda*.png Z_*ana_bwkman_dwdna* -t /your/directory/ ``` If you want it more elegant with input from file: ``` PATTERNS=`cat input.txt | paste -sd " " - ` && mv $PATTERNS -t /your/directory/ ```
assume your patterns in a file called patterns ``` mapfile -t arr < patterns && mv -t destination "${arr[@]}" ```
396,044
Need move files with multiple, defined patterns, like: ``` Z_*ana_bwk_na_N*.png Z_*ana_bwk_dwda*.png Z_*ana_bwkman_dwdna* Z_*ana_bwkman_dwdc* Z_*EDZW*_nwv01*_p00_na_N*WV11.png Z_*EDZW*_nwv01*_p00_nh_N*WV11.png Z_*nwv01*_hsy_NA*.png Z_*EDZW_*_htp_na_N_*_WV11SW.png Z_*_rft_na_*.png Z_*_r12* ``` from one defined folder, to another. How it can be done in best economic way? In a script, running from cron? Can this patterns be defined better in same script, or get from separate textfile, containing them?
2017/10/04
[ "https://unix.stackexchange.com/questions/396044", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/254067/" ]
assume your patterns in a file called patterns ``` mapfile -t arr < patterns && mv -t destination "${arr[@]}" ```
The most efficient, but possibly the least legible, approach is to just enumerate everything in one big happy `mv` command. ``` mv Z_*ana_bwk_na_N*.png \ Z_*ana_bwk_dwda*.png \ Z_*ana_bwkman_dwdna* \ Z_*ana_bwkman_dwdc* \ Z_*EDZW*_nwv01*_p00_na_N*WV11.png \ Z_*EDZW*_nwv01*_p00_nh_N*WV11.png \ Z_*nwv01*_hsy_NA*.png \ Z_*EDZW_*_htp_na_N_*_WV11SW.png \ Z_*_rft_na_*.png \ Z_*_r12* \ destination ``` If you want to split this up (perhaps because you get "command line too long") you can use a here document. ``` while read files; do mv $files dest done <<____ Z_*ana_bwk_na_N*.png Z_*ana_bwk_dwda*.png Z_*ana_bwkman_dwdna* Z_*ana_bwkman_dwdc* Z_*EDZW*_nwv01*_p00_na_N*WV11.png Z_*EDZW*_nwv01*_p00_nh_N*WV11.png Z_*nwv01*_hsy_NA*.png Z_*EDZW_*_htp_na_N_*_WV11SW.png Z_*_rft_na_*.png Z_*_r12* ____ ``` If you want to parametrize the destination, you can do that too. ``` while read destination files; do mv $files "$destination" done <<____ here Z_*ana_bwk_na_N*.png here Z_*ana_bwk_dwda*.png here Z_*ana_bwkman_dwdna* there Z_*ana_bwkman_dwdc* there Z_*EDZW*_nwv01*_p00_na_N*WV11.png everywhere Z_*EDZW*_nwv01*_p00_nh_N*WV11.png here Z_*nwv01*_hsy_NA*.png elsewhere Z_*EDZW_*_htp_na_N_*_WV11SW.png there Z_*_rft_na_*.png anywhere Z_*_r12* ____ ``` Somewhat confusingly, the wildcards in the here document will be expanded by the shell *before the loop runs.* Because we need the inner loop to be unquoted, the expanded file names cannot contain any shell metacharacters (which do not match exactly only themselves -- typically irregular whitespace or wildcard expressions).
39,748,327
I wrote a batch file which should find and copy the latest build file bigger than a 3.5 GB. ``` set source=D:\src set tmp_dir="D:\tmp" set "file=" for /f "delims=|" %%a in (' dir /b /o-d "%source%\*.zip" 2^>nul ^| cmd /q /v /c"set /p .=&if defined . (echo(!.!)" ') do set "file=%%a" echo %file% robocopy %source% %tmp_dir% %file% /MT:16 /X /MIN:3500000000 /XO /V /TS /FFT /R:3 /W:10 /ETA ``` My problem is what happening when the latest file is smaller than 3.5 GB. In this case is need to copy the next file larger than 3.5 GB.
2016/09/28
[ "https://Stackoverflow.com/questions/39748327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6649535/" ]
You almost have it. Instead of using the `dir` command to retrieve the initial list of files, we can use `robocopy` to get a list (`/l`) of files in the source folder with the required minimum size (`/min`). This list should not include job header, job footer, nor directory list (`/njh`, `/njf`, `/ndl`). For each file we don't need the class of the file (`/nc`) or the size of the file (`/ns`), but we want the time stamp (`/ts`) of the files to sort the list on this field. This will leave a sorted list of files with the newer file matching the conditions as the first in the list. ```dos @echo off setlocal enableextensions disabledelayedexpansion set "source=D:\src" set "tmp_dir=D:\tmp" set "file=" for /f "tokens=2,*" %%a in (' robocopy "%source%" . *.zip /l /xx /is /njh /njs /ndl /nc /ns /ts /min:350000000000 ^| sort /r ^| cmd /q /v /c"set /p .=&if defined . (echo(!.!)" ') do set "file=%%~nxb" echo(%file% if defined file ( robocopy "%source%" "%tmp_dir%" "%file%" /MT:16 /X /XO /V /TS /FFT /R:3 /W:10 /ETA ) ```
You can get the size of a file in bit using the following line ``` for /f "usebackq" %%a in ('%file%') d set filesize=%%~za ``` Add ``` set /a filesize+=0 ``` to make sure it is treated like a numeric variable. Then use an `if`-statement to check if filesize exceeds 3500000000 byte -> 3.5 GB. ``` if filesize LSS 3500000000 ( echo not 3.5 GB ) ELSE ( echo bigger than 3.5 GB ) ``` Adding other `echo`es is up to you.
18,659,279
I am trying to remove certain functionality when the screen is at certain widths. I was wondering if you could tell me why this doesn't work? <http://jsbin.com/ALAYOru/1/edit> I remove the 'has-sub-menu' class when the screen goes below 700px but it still executes the mouseover event. Thanks!
2013/09/06
[ "https://Stackoverflow.com/questions/18659279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1160811/" ]
Or this. ``` function isWindowSmall() { if(window.innerWidth < 700px) return true; else return false; } $(".some-btn").on('click',function() { if(isWindowSmall()){ //do something for small windows } else{ //do something else for big windows } }); ```
try this. ``` window.onresize = function () { if(window.innerWidth < 700) { // your code here } } ```
18,659,279
I am trying to remove certain functionality when the screen is at certain widths. I was wondering if you could tell me why this doesn't work? <http://jsbin.com/ALAYOru/1/edit> I remove the 'has-sub-menu' class when the screen goes below 700px but it still executes the mouseover event. Thanks!
2013/09/06
[ "https://Stackoverflow.com/questions/18659279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1160811/" ]
That is becauase what this is doing is. ``` $(".has-sub-menu").mouseenter(function(){ $(this).css('background-color','red'); }).mouseleave(function(){ $(this).css('background-color','transparent'); }); ``` This goes and finds all of the elements with the class of `.has-sub-menu` and then it attaches the event listener, so this listener will be applied forever, what you could do is something like this. ``` $("body").on({ mouseenter: function(){ $(this).css('background-color','red'); }, mouseleave: function(){ $(this).css('background-color','transparent'); } }, '.has-sub-menu'); ``` This will check to see if the element has the class every time it is clicked **Demo: <http://jsbin.com/ALAYOru/6/edit>** > > Note: in the demo, you might have to make the output window bigger than 720px and then refresh to see the proper effect. > > >
try this. ``` window.onresize = function () { if(window.innerWidth < 700) { // your code here } } ```
18,659,279
I am trying to remove certain functionality when the screen is at certain widths. I was wondering if you could tell me why this doesn't work? <http://jsbin.com/ALAYOru/1/edit> I remove the 'has-sub-menu' class when the screen goes below 700px but it still executes the mouseover event. Thanks!
2013/09/06
[ "https://Stackoverflow.com/questions/18659279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1160811/" ]
Or this. ``` function isWindowSmall() { if(window.innerWidth < 700px) return true; else return false; } $(".some-btn").on('click',function() { if(isWindowSmall()){ //do something for small windows } else{ //do something else for big windows } }); ```
You can add a function to check the screen size and remove the onmouseover event listener. ``` function check_screen() { if(window.innerWidth < 700px) { whateveryourelementiscalled.removeEventListner('onmouseover', //whatever your mouseover function was); } } ```
18,659,279
I am trying to remove certain functionality when the screen is at certain widths. I was wondering if you could tell me why this doesn't work? <http://jsbin.com/ALAYOru/1/edit> I remove the 'has-sub-menu' class when the screen goes below 700px but it still executes the mouseover event. Thanks!
2013/09/06
[ "https://Stackoverflow.com/questions/18659279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1160811/" ]
That is becauase what this is doing is. ``` $(".has-sub-menu").mouseenter(function(){ $(this).css('background-color','red'); }).mouseleave(function(){ $(this).css('background-color','transparent'); }); ``` This goes and finds all of the elements with the class of `.has-sub-menu` and then it attaches the event listener, so this listener will be applied forever, what you could do is something like this. ``` $("body").on({ mouseenter: function(){ $(this).css('background-color','red'); }, mouseleave: function(){ $(this).css('background-color','transparent'); } }, '.has-sub-menu'); ``` This will check to see if the element has the class every time it is clicked **Demo: <http://jsbin.com/ALAYOru/6/edit>** > > Note: in the demo, you might have to make the output window bigger than 720px and then refresh to see the proper effect. > > >
You can add a function to check the screen size and remove the onmouseover event listener. ``` function check_screen() { if(window.innerWidth < 700px) { whateveryourelementiscalled.removeEventListner('onmouseover', //whatever your mouseover function was); } } ```
39,561,806
I have a list of lists and I want to merge them to sum the inner `index[1]` values where the `index[0]` values match. My list looks like this: ``` lists = [ ['Gifts', [4]], ['Gifts', [4]], ['Politics', [3]], ['Supply', [4]], ['Supply', [4]], ['Prints', [1]], ['Prints', [1]], ['Prints', [1]], ['Politics', [3]], ['Politics', [3]], ['Accounts', [2]], ['Accounts', [2]], ['Accounts', [2]], ['Features', [3]], ['Features', [2]] ] ``` I would therefore like the new structure to be: ``` new_lists = [ ['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5] ] ``` How do I achieve this in Python?
2016/09/18
[ "https://Stackoverflow.com/questions/39561806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5652029/" ]
You can use [`defaultdict(int)`](https://docs.python.org/3/library/collections.html#collections.defaultdict) from `collections` module: ``` >>> from collections import defaultdict >>> d = defaultdict(int) >>> for key, value in lists: ... d[key] += value[0] ... >>> dict(d) {'Gifts': 8, 'Prints': 3, 'Accounts': 6, 'Features': 5, 'Supply': 8, 'Politics': 9} >>> list(d.items()) [('Prints', 3), ('Features', 5), ('Supply', 8), ('Gifts', 8), ('Accounts', 6), ('Politics', 9)] ```
Use a `defaultdict`: ``` In [52]: from collections import defaultdict In [53]: d = defaultdict(int) In [54]: for name, (val,) in lists: ....: d[name] += val ....: In [55]: d.items() Out[55]: dict_items([('Politics', 9), ('Supply', 8), ('Prints', 3), ('Features', 5), ('Gifts', 8), ('Accounts', 6)]) ```
39,561,806
I have a list of lists and I want to merge them to sum the inner `index[1]` values where the `index[0]` values match. My list looks like this: ``` lists = [ ['Gifts', [4]], ['Gifts', [4]], ['Politics', [3]], ['Supply', [4]], ['Supply', [4]], ['Prints', [1]], ['Prints', [1]], ['Prints', [1]], ['Politics', [3]], ['Politics', [3]], ['Accounts', [2]], ['Accounts', [2]], ['Accounts', [2]], ['Features', [3]], ['Features', [2]] ] ``` I would therefore like the new structure to be: ``` new_lists = [ ['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5] ] ``` How do I achieve this in Python?
2016/09/18
[ "https://Stackoverflow.com/questions/39561806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5652029/" ]
Or, use a [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) from [`collections`](https://docs.python.org/3/library/collections.html). You can initialize it either manually by incrementing the values for every key: ``` from collections import Counter c = Counter() for i, j in lists: c[i] += l[j] ``` Or, by providing a flat list of the expanded contents, `Counter` will then do the counting for you: ``` c = Counter(sum([[i] * j[0] for i,j in lists], [])) ``` In both cases, create the result list by using a list comprehension grabbing the contents of the counter with `c.items()`: ``` r = [[i, j] for i, j in c.items()] ``` Result being: ``` print(r) [['Supply', 8], ['Features', 5], ['Prints', 3], ['Gifts', 8], ['Accounts', 6], ['Politics', 9]] ```
Use a `defaultdict`: ``` In [52]: from collections import defaultdict In [53]: d = defaultdict(int) In [54]: for name, (val,) in lists: ....: d[name] += val ....: In [55]: d.items() Out[55]: dict_items([('Politics', 9), ('Supply', 8), ('Prints', 3), ('Features', 5), ('Gifts', 8), ('Accounts', 6)]) ```
39,561,806
I have a list of lists and I want to merge them to sum the inner `index[1]` values where the `index[0]` values match. My list looks like this: ``` lists = [ ['Gifts', [4]], ['Gifts', [4]], ['Politics', [3]], ['Supply', [4]], ['Supply', [4]], ['Prints', [1]], ['Prints', [1]], ['Prints', [1]], ['Politics', [3]], ['Politics', [3]], ['Accounts', [2]], ['Accounts', [2]], ['Accounts', [2]], ['Features', [3]], ['Features', [2]] ] ``` I would therefore like the new structure to be: ``` new_lists = [ ['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5] ] ``` How do I achieve this in Python?
2016/09/18
[ "https://Stackoverflow.com/questions/39561806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5652029/" ]
You can use [`defaultdict(int)`](https://docs.python.org/3/library/collections.html#collections.defaultdict) from `collections` module: ``` >>> from collections import defaultdict >>> d = defaultdict(int) >>> for key, value in lists: ... d[key] += value[0] ... >>> dict(d) {'Gifts': 8, 'Prints': 3, 'Accounts': 6, 'Features': 5, 'Supply': 8, 'Politics': 9} >>> list(d.items()) [('Prints', 3), ('Features', 5), ('Supply', 8), ('Gifts', 8), ('Accounts', 6), ('Politics', 9)] ```
Or, use a [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) from [`collections`](https://docs.python.org/3/library/collections.html). You can initialize it either manually by incrementing the values for every key: ``` from collections import Counter c = Counter() for i, j in lists: c[i] += l[j] ``` Or, by providing a flat list of the expanded contents, `Counter` will then do the counting for you: ``` c = Counter(sum([[i] * j[0] for i,j in lists], [])) ``` In both cases, create the result list by using a list comprehension grabbing the contents of the counter with `c.items()`: ``` r = [[i, j] for i, j in c.items()] ``` Result being: ``` print(r) [['Supply', 8], ['Features', 5], ['Prints', 3], ['Gifts', 8], ['Accounts', 6], ['Politics', 9]] ```
11,244,235
I am building this C# windows application. On a certain Form, I am using maskedtextbox to enter upto 3 numerical digits, then I convert it into int as I have to send all these data to database with an insert query, but the problem is that these maskedtextboxes give error when left empty: ``` int scd_user_comm = Convert.ToInt32(maskedTextBox1.Text); ``` and the error is : > > Input string was not in a correct format. > > > The corresponding field in database allows null, so if left empty, it must not give an error. Can anyone help please? One side question:: Can I use a textbox or maskedtextbox to ensure that user only enters numeric value b/w 0 to 100? Thanks in advance.
2012/06/28
[ "https://Stackoverflow.com/questions/11244235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479153/" ]
You could try the Int32.TryParse() method ``` int scd_user_comm; if(Int32.TryParse(maskedTextBox1.Text, out scd_user_comm) == false) scd_user_comm = 0; ``` this will give you all the flexiblity required to work with your integer var and your maschedTextBox- To force your maskTextBox to accept only numeric values set ``` maskTextBox1.Mask = "999"; maskTextBox1.TextMaskFormat = MaskFormat.ExludePromptAndLiterals; ``` However this is not enough to ensure the enterd number is between 0 and 100. To get this result you need to use the Validating event and reject the input if is outside your limits ``` private void maskedTextBox1_Validating(object sender, CancelEventArgs e) { int num; if (Int32.TryParse(maskedTextBox1.Text, out num) == true) { if (num < 0 || num > 100) { MessageBox.Show("Insert number between 0 and 100"); e.Cancel = true; } } } ```
You could use the TryParse instead: ``` int scd_user_comm; if(!Int32.TryParse(maskedTextBox1.Text, out scd_user_comm)) { // Do something to notify the user that the text isn't a number. } ```
2,132,440
I have a set of python scripts that I run frequently on different machines that depend on a few external libraries as well as some other applications spawned via `subprocess.Popen`. As expected depending on the version of the installed modules and applications the output varies. To address this I would like to keep track of which versions were in use at runtime. In order to do this I've considered the following steps: 1. Using [modulefinder](http://docs.python.org/library/modulefinder.html) to collect dependencies. 2. Try to call `module.__version__`, `module.get_version()` or other common ways to store version information on each collected module. 3. Collect all calls to `subprocess.Popen` and try to get a version number by parsing the output with different arguments such as -version, -v, -?, -h, ... Steps 2 and 3 could be greatly improved by the use of distribution specific ([Debian](http://www.debian.org) in my case) tools such as [dpkg](http://www.debian.org/doc/FAQ/ch-pkgtools.en.html) to get versions of installed packages. The downside is that it becomes not only OS but also distribution specific, however I do realize that the initial approach is extremely inefficient and error-prone, if functional at all. So my question is if there is any package out there to address this or if anyone has a better suggestion on how to implement it?
2010/01/25
[ "https://Stackoverflow.com/questions/2132440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125801/" ]
Two years passed and some new tools came into play. To take care of point 1 and 2 there is now `pip freeze` specially when coupled with `virtualenv`. For external applications I had to resource to the package manager (apt-file, dpkg, qlist, emerge,... depending on the system) on the system which included all the expected pitfalls. I would still like to make a reference to Ross' answer as it produced the desired result. The disadvantage (from my point of view) is that it collected a lot more dependencies than strictly required.
Instead of directly investigating your dependencies in python, and if you are running in Linux/Unix, you can wrapper your program with `[memoize.py](http://benno.id.au/blog/2008/06/06/memoize-build-framework)`. `memoize.py` uses `[strace](http://en.wikipedia.org/wiki/Strace)`, or "system trace", to watch all system read and write commands that your program generates and then stores these dependencies to a file. `memoize.py` may also be use as a library, so you can use its functions internally within your program and get the dependencies in a python data structure.
168,221
In my testing (in Bash and Z Shell), I saw no problems with defining functions or aliases or executable shell scripts which have hyphens in the name, but I'm not confident that this will be okay in all shells and in all use cases. The reason I would like to do this is that a hyphen is easier to type than an underscore, and therefore faster and smoother. One reason I'm hesitant to trust that it's not a problem is that in some languages (Ruby for example) the hyphen would be interpreted as a minus sign even without spaces around it. It wouldn't surprise me if something like this might happen in some shells, where the hyphen is interpreted as signaling an option even without a space. Another reason I'm a little suspicious is that my text editor screws up the syntax highlighting for functions with hyphens. (But of course it's entirely possible that that's just a bug in its syntax highlighting configuration for shell scripts.) Is there any reason to avoid hyphens?
2014/11/16
[ "https://unix.stackexchange.com/questions/168221", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/3358/" ]
### POSIX and Hyphens: No Guarantee According to the POSIX standard, [a function name](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_05) must be a valid name and [a name](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_231) can consist of: > > **3.231 Name** > > In the shell command language, a word consisting solely of > underscores, digits, and alphabetics from the portable character set. > The first character of a name is not a digit. > > > Additionally, [an alias](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_03_01) must be a valid [alias name](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_10), which can consist of: > > **3.10 Alias Name** > > In the shell command language, a word consisting solely of underscores, > digits, and alphabetics from the portable character set and any of the > following characters: '!', '%', ',', '@'. > > > **Implementations may allow other characters within alias names as an > extension.** *(Emphasis mine.)* > > > A hyphen is *not* listed among the characters that must be allowed in either case. So, if they are used, portability is not guaranteed. ### Examples of Shells That Do Not Support Hyphens `dash` is the default shell (`/bin/sh`) on the debian-ubuntu family and it does not support hyphens in function names: ``` $ a-b() { date; } dash: 1: Syntax error: Bad function name ``` Interestingly enough, it *does* support hyphens in aliases, though, as noted above, this is an *implementation characteristic*, not a requirement: ``` $ a_b() { printf "hello %s\n" "$1"; } $ alias a-b='a_b' $ a-b world hello world ``` The busybox shell (only the ash based one) also does not support hyphens in function names: ``` $ a-b() { date; } -sh: Syntax error: Bad function name ``` ### Summary of Hyphen Support by Shell The following shells are known to support hyphens in function names: * pdksh and derivatives, bash, zsh * some ash derivatives such as the sh of FreeBSD ([since 2010](https://svnweb.freebsd.org/base?view=revision&revision=214291)) or NetBSD (since 2016. * busybox sh when the selected shell at compile time is `hush` instead of `ash`. * csh and tcsh (in their aliases, those shells have no function support). Those shells have a radically different syntax anyway, so there's no hope to have cross shell compatibility with those. * rc and derivatives (again with a radically different syntax) * fish (again with a radically different syntax) The following shells are known *not* to support hyphens in function names: * the Bourne shell and derivatives such as ksh88 and bosh (in the Bourne shell, functions and variables shared the same namespace, you couldn't have a variable and a function by the same name). * ksh93, yash, the original ash and some of its derivatives (busybox ash (the default choice for sh), dash) ### Conclusions * Hyphens are non-standard. Stay away from them if you want cross-shell compatibility. * Use underscores instead of hyphens: underscores are accepted everywhere.
I know this is really late, but perhaps you can work around your issue of making the underscore more accessible. ``` xmodmap -e "keycode 20 = underscore minus" ``` This will switch underscore with hyphen (minus). So now, you hold shift for hyphen, but an underscore is typed without shift. Your keycode may be different, however, I think it depends on your keyboard; mine happens to be 20. Just let me know if you need help finding what keycode you need to use.
13,504,814
Does an operator, when I overload it, lose its ability to operator for types it was defined for before, or does the new definition only apply when I call ``` cout << that_specific_class_type_variable ``` If I write `cout << that_specific_class_type_variabe->Left()` will it be overloaded function or normal cout statement? ``` ostream& operator<< (ostream& out, TreeNode* tptr) { if(tptr!=NULL) { operator<<(out,tptr->Left()); out<<(*(tptr->Entry())); operator<<(out,t->Right()); } return out; } ```
2012/11/22
[ "https://Stackoverflow.com/questions/13504814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1722022/" ]
It will only change the behaviour for the specific type it's overloaded for, in your case, `TreeNode *`. Existing versions of the operator will continue to function as normal. For the recursive calls: It will use your new definition of the operator if `Left` and `Right` are of type `TreeNode *` (or pointer to a class derived from `TreeNode`). If they are of a different type, the default version of the operator will be used. I suspect that `Entry()` returns an object of a type different from `TreeNode *`. In that case, the standard definition of `operator<<` will be applied to it.
Operator Overloading does not mean changing the function and behavior of that particular operator forever or for the built in data types. It only facilitates you to perform operations on your user defined data types similar to the ones you do on integral types. For example if you have two integer variables, you can assign one the value of the other like this. ``` int a = 5 ; int b = 7 ; b = a ; ``` Similarly you may also want your own data types to behave like that for efficieny and easy of use. ``` //Hypothetical class myClass obj1 (5, "abc") ; myClass obj2 (109, "xyz") ; ......... ...... obj2 = obj1 ; ``` As for the output, you overload `cout` with `<<` operator to output the data of your object like this. ``` cout << obj1 ; ``` If you want to output the variables inside your class of integral types, you can do that like this if they are public members. ``` cout << myVar << endl ; ``` or like this if they are private members. ``` cout << getmyVar() << endl ; ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Both of your `if` statements are getting executed one after each other, as you change the value and then immediately read it again and change it back: ``` function toggle(button) { if(document.getElementById("1").value=="OFF"){ document.getElementById("1").value="ON";} else if(document.getElementById("1").value=="ON"){ document.getElementById("1").value="OFF";} } ``` Adding the `else` in there should stop this happening.
Another method to do this is: ``` var button = document.querySelector("button"); var body = document.querySelector("body"); var isOrange = true; button.addEventListener("click", function() { if(isOrange) { body.style.background = "orange"; }else { body.style.background = "none"; } isOrange = !isOrange; }); ``` In the `JavaScript` file. /\*\*\*\*\* NOTE! Another way is applying a class to the element that we want to change. The `CSS` file must have the class with the format we want: ``` .orange { background: orange; } ``` By last in our `js` file we only need to make the application of the class: ``` var button = document.querySelector("button"); button.addEventListener("click", function() { document.body.classList.toggle("orange"); }); ``` *Regards :)*
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Both of your `if` statements are getting executed one after each other, as you change the value and then immediately read it again and change it back: ``` function toggle(button) { if(document.getElementById("1").value=="OFF"){ document.getElementById("1").value="ON";} else if(document.getElementById("1").value=="ON"){ document.getElementById("1").value="OFF";} } ``` Adding the `else` in there should stop this happening.
``` <html> <head> <script type="text/javascript"> function toggle(button) { if(document.getElementById("1").value=="OFF") { document.getElementById("1").value="ON"; } else { document.getElementById("1").value="OFF"; } } </script> </head> <body> <form action=""> <input type="button" id="1" value="ON" style="color:blue" onclick="toggle(this);"> </form> </body> </html> ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Another method to do this is: ``` var button = document.querySelector("button"); var body = document.querySelector("body"); var isOrange = true; button.addEventListener("click", function() { if(isOrange) { body.style.background = "orange"; }else { body.style.background = "none"; } isOrange = !isOrange; }); ``` In the `JavaScript` file. /\*\*\*\*\* NOTE! Another way is applying a class to the element that we want to change. The `CSS` file must have the class with the format we want: ``` .orange { background: orange; } ``` By last in our `js` file we only need to make the application of the class: ``` var button = document.querySelector("button"); button.addEventListener("click", function() { document.body.classList.toggle("orange"); }); ``` *Regards :)*
This will resolve your issue. ``` let isOn = true; function toggle(button) { isOn = !isOn; if (isOn) { document.getElementById("1").value = "ON"; } else { document.getElementById("1").value = "OFF"; } } ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Both of your `if` statements are getting executed one after each other, as you change the value and then immediately read it again and change it back: ``` function toggle(button) { if(document.getElementById("1").value=="OFF"){ document.getElementById("1").value="ON";} else if(document.getElementById("1").value=="ON"){ document.getElementById("1").value="OFF";} } ``` Adding the `else` in there should stop this happening.
Why are you passing the button if you're going to look it up? Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's ON. ``` // Toggles the passed button from OFF to ON and vice-versa. function toggle(button) { if (button.value == "OFF") { button.value = "ON"; } else { button.value = "OFF"; } } ``` If you wanna get fancy and save a couple of bytes you can use the ternary operator: ``` function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";} ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Both of your `if` statements are getting executed one after each other, as you change the value and then immediately read it again and change it back: ``` function toggle(button) { if(document.getElementById("1").value=="OFF"){ document.getElementById("1").value="ON";} else if(document.getElementById("1").value=="ON"){ document.getElementById("1").value="OFF";} } ``` Adding the `else` in there should stop this happening.
This will resolve your issue. ``` let isOn = true; function toggle(button) { isOn = !isOn; if (isOn) { document.getElementById("1").value = "ON"; } else { document.getElementById("1").value = "OFF"; } } ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Another method to do this is: ``` var button = document.querySelector("button"); var body = document.querySelector("body"); var isOrange = true; button.addEventListener("click", function() { if(isOrange) { body.style.background = "orange"; }else { body.style.background = "none"; } isOrange = !isOrange; }); ``` In the `JavaScript` file. /\*\*\*\*\* NOTE! Another way is applying a class to the element that we want to change. The `CSS` file must have the class with the format we want: ``` .orange { background: orange; } ``` By last in our `js` file we only need to make the application of the class: ``` var button = document.querySelector("button"); button.addEventListener("click", function() { document.body.classList.toggle("orange"); }); ``` *Regards :)*
Why not use a switch? ``` function toggle(button) { switch(button.value) { case "ON": button.value = "OFF"; break; case "OFF": button.value = "ON"; break; } } ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Why are you passing the button if you're going to look it up? Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's ON. ``` // Toggles the passed button from OFF to ON and vice-versa. function toggle(button) { if (button.value == "OFF") { button.value = "ON"; } else { button.value = "OFF"; } } ``` If you wanna get fancy and save a couple of bytes you can use the ternary operator: ``` function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";} ```
This will resolve your issue. ``` let isOn = true; function toggle(button) { isOn = !isOn; if (isOn) { document.getElementById("1").value = "ON"; } else { document.getElementById("1").value = "OFF"; } } ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Both of your `if` statements are getting executed one after each other, as you change the value and then immediately read it again and change it back: ``` function toggle(button) { if(document.getElementById("1").value=="OFF"){ document.getElementById("1").value="ON";} else if(document.getElementById("1").value=="ON"){ document.getElementById("1").value="OFF";} } ``` Adding the `else` in there should stop this happening.
Why not use a switch? ``` function toggle(button) { switch(button.value) { case "ON": button.value = "OFF"; break; case "OFF": button.value = "ON"; break; } } ```
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Why are you passing the button if you're going to look it up? Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's ON. ``` // Toggles the passed button from OFF to ON and vice-versa. function toggle(button) { if (button.value == "OFF") { button.value = "ON"; } else { button.value = "OFF"; } } ``` If you wanna get fancy and save a couple of bytes you can use the ternary operator: ``` function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";} ```
Another method to do this is: ``` var button = document.querySelector("button"); var body = document.querySelector("body"); var isOrange = true; button.addEventListener("click", function() { if(isOrange) { body.style.background = "orange"; }else { body.style.background = "none"; } isOrange = !isOrange; }); ``` In the `JavaScript` file. /\*\*\*\*\* NOTE! Another way is applying a class to the element that we want to change. The `CSS` file must have the class with the format we want: ``` .orange { background: orange; } ``` By last in our `js` file we only need to make the application of the class: ``` var button = document.querySelector("button"); button.addEventListener("click", function() { document.body.classList.toggle("orange"); }); ``` *Regards :)*
3,047,756
I'm just preparing the release of a library site builded in asp.net: <http://213.133.103.5/gramma_prod/Site/Index.aspx> All it's working great on FF and Chrome but on IE the asp button click event is not working. Please notice the most important buttons: "Adauga in cos" (Add to basket)... I'm just struggling to find out the problem... I've checked the forms to not have nested ones but they seems ok. Could you provide any other ideea? ps: I did not post any code because this problem occurs on all pages... Thanks in advance. **Edit:** Code for "Add to basket"(Adauga in cos) button from the index: ``` <asp:ImageButton ID="imgBtnCosBooksFeatured" runat="server" OnCommand="addProductToBasket_Click" CommandName="Click" CommandArgument='<%# Eval("Carti_id").ToString()+","+Eval("Titlu").ToString()+","+Eval("Autor").ToString()%>' ImageUrl="../Site/images/featured-cos.jpg" ToolTip="Adauga in cos" /> ``` * works ok on ff and chrome. Fails on IE :(
2010/06/15
[ "https://Stackoverflow.com/questions/3047756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174349/" ]
Why are you passing the button if you're going to look it up? Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's ON. ``` // Toggles the passed button from OFF to ON and vice-versa. function toggle(button) { if (button.value == "OFF") { button.value = "ON"; } else { button.value = "OFF"; } } ``` If you wanna get fancy and save a couple of bytes you can use the ternary operator: ``` function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";} ```
Why not use a switch? ``` function toggle(button) { switch(button.value) { case "ON": button.value = "OFF"; break; case "OFF": button.value = "ON"; break; } } ```
325,031
I have been studying software architecture and design patterns for the past weeks, and for a week now I can't stop thinking about the performance problems that come with the flexibility of the data mapper pattern. In the book written by Martin Fowler, he gives an example of the pattern with some find methods and just one delete method, one update method and one insert method. So, when he has to update multiple objects, he takes multiple "trips" to the database. I started reading about the Unit Of Work pattern in the same book, but it looks like by its implementation that it doesn't solve this problem either. Is there a solution that solves this issues without losing too much flexibility?
2016/07/17
[ "https://softwareengineering.stackexchange.com/questions/325031", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/237117/" ]
[Eugene Philipov ran a benchmark](https://www.simple-talk.com/sql/performance/comparing-multiple-rows-insert-vs-single-row-insert-with-three-data-load-methods/) on multiple `INSERT`s in one query and found out that they are really faster than running many sequential inserts after each other. This really did not come as a surprise because `INSERT` is a very simple operation. For updates the reason why you'd be taking multiple trips to a database is because the code is simply easier to understand by the programmer. Unless deemed completely necessary the performance drop will not be substantional. The situation of updates behaving differently from inserts is caused by the `CASE/WHEN` clause that must be present when you want to update attributes of multiple rows with different values. Because of that, the database not only performs search and update but also needs to decide which value should be actually used as a replacement for the current one. You as a programmer always have the option to write a method which would update an attribute of multiple rows with the same value. On a database level this is very simple to do, you provide a constrait which rows should be affected (most likely using the `IN` clause), you then provide the replacement and it's done. No deciding on the database level what so ever, just a simple search and replace procedure. I said that updating multiple rows with different values is not as performant as multiple `INSERT`, but still, it will be slightly faster than taking multiple trips to the database, because that costs resources (mostly time - to connect to database and to execute each query). But unless you are talking about bulk-updating milions of rows, I don't think you need to care. You mentioned Martin Fowler in his example specifically takes multiple trips to the database. In the book he shows an example of the insert action, where each record is processed individually. Even so, Martin Fowler himself says the following: > > To avoid multiple database calls, you can leave all your updates to > the end. To do this you need to keep track of all the objects that > have changed. You can use variables in your code for this, but they > soon become unmanageable once you have more than a few. Variables > often work fine with a Transaction Script (110), but they can be very > difficult with a Domain Model (116). > > > Rather than keep objects in variables you can give each object a dirty > flag that you set when the object changes. Then you need to find all > the dirty objects at the end of your transaction and write them out. > > > > > --- > > > Source: Martin Fowler, P of EAA > > > The important part from the quote is: *you **can** leave all your updates to the end*. Note how he does not say you must do so, because in most cases it's simply not necessary. From my experience, the bulk-operation (operation meaning `INSERT`, `UPDATE` and/or `DELETE`) hack will not completely solve your performance issue. If you have one, you are more likely to fix it by improving your architecture, introducing caching, maybe using different technologies and whatnot. I think what you are concerned with is [premature optimization](http://c2.com/cgi/wiki?PrematureOptimization). Yes, it is amazing to have a vision of a system which is blazing fast, but it's even better having a system done, so you can actually use it. So while Mr. Fowler does not supply an actual example of bulk updates, it is completely possible if/when needed. He most likely chose not to show an example of that, because the regular sequential approach usually works. That's my assumption. His reason behind not putting it into the book might be different, but for that you need to ask him directly.
Keep in mind if the is a network between your program and the database, it is very easy to write code that becomes IO bound. Also, if you are processing transactions you may have to take several trips to the database depending on the mechanism used to track transactions.
59,335,936
I have a function component which uses two states and both are changed based on event triggered. I've read on react [docs](https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level) that is a bad idea to change states in nested function or condition. I also seen some examples using useEffects, but I have no clear idea how to properly refactor this. here is my entire component: ``` import React, { useState, useEffect } from 'react' import './App.css' import AppHeader from '../app-header' import AppFooter from '../app-footer' import SearchInput from '../search-input' import Stats from '../stats' import Chart from '../chart' import { getBundleInfoAPI } from '../../services/hostApi' import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css' import Loader from 'react-loader-spinner' function App() { const [isSpinnerVisible, setSpinnerVisible] = useState(false) const [bundleData, setBundleData] = useState({}) const _handleOnItemSelected = (item) => { if (item && item.package && item.package.name && item.package.version) { setSpinnerVisible(true) getBundleInfoAPI(item.package.name, item.package.version) .then(resposeData => setBundleData(resposeData)) .finally(() => setSpinnerVisible(false)) } else { // TODO - implement an error handler component? console.warn('WARNING: The selected bundle does not have name or version!') } } return ( <div className="app"> <AppHeader /> <main> <SearchInput onItemSelected={_handleOnItemSelected} /> <div className="app-main-inner-container"> <Loader type="Triangle" color="#00BFFF" height={200} width={200} visible={isSpinnerVisible} /> {!isSpinnerVisible && <div className="app-stats-chart-container"> <section className="app-stats-container"><Stats size={bundleData.stats} /></section> <section className="app-chart-container"><Chart bundleChartData={bundleData.chart} /></section> </div> } </div> </main> <AppFooter /> </div> ) } export default App ```
2019/12/14
[ "https://Stackoverflow.com/questions/59335936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6242613/" ]
> > Are there any tools (or a description of a workflow) that would allow me to have two differently formatted versions of source-code? > > > As commented, using a common convention is easier. For example, any program written in **[Go](https://golang.org)** would use [`go fmt`](https://golang.org/pkg/fmt/), [included with the language itself](https://blog.golang.org/go-fmt-your-code). But yes, you can locally define a [Git content filter driver](https://stackoverflow.com/a/10571580/6309) which will: [![enter image description here](https://i.stack.imgur.com/tumAc.png)](https://i.stack.imgur.com/tumAc.png) (image from "[Customizing Git - Git Attributes](https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#filters_a)", from "[Pro Git book](http://git-scm.com/book/en/v2/)") * automatically apply your format to your code on checkout * automatically apply the company format to your code on commit The diff will be preserved. The content filter driver will only apply to files with a certain extension, as define in a [`.gitattributes` file](https://stackoverflow.com/a/2316728/6309). But it will be activated in a *local* Git configuration --- You can find an example of that approach in the project [prettier/prettier](https://github.com/prettier/prettier), in issue [issue 129](https://github.com/prettier/prettier/issues/129#issuecomment-297587908): > > For projects that use `prettier`, developers who prefer a [different prettier config](https://prettier.io/docs/en/configuration.html) could configure git smudge/clean filters to do this for them, without having to involve editors. > > For example, putting this into `.git/config`: > > > > ``` > [filter "prettier"] > clean = prettier --stdin --no-semi --single-quote > smudge = prettier --stdin > > ``` > > and putting this into `.git/info/attributes`: > > > > ``` > *.js filter=prettier > > ``` > > makes it so that files are checked into the repository with single quotes and without semicolons, but are checked out onto the disk with double quotes and semicolons. > > >
Thank you @VonC, Here I just wanted to post a quick and ready to use implementation of your idea with Git content filter driver. ### In `.git/config` add ``` [filter "clangformat"] smudge = .git/clang-formatter.sh .clang-format-my clean = .git/clang-formatter.sh .clang-format-company ``` Explanation: * `smudge` - the command that is called when you **pull** something (more precisely when git checks sources out onto your disk) * `clean` - the command that is called when you **push** something (more precisely when you add files in the git's staging area). * `.clang-format-my` and `.clang-format-company` - self-explanatory clang-format files. `.git/clang-formatter.sh` is a small script that invokes `clang-format`. The main purpose of the script is to "prepare" value for `-style` option (via awk): ``` #!/bin/bash clang-format-8 -style "{$(awk '{if ($0 !~ /#/) {if (NR>1) {printf ", "} printf $0; }}' $1)}" -assume-filename=main.cpp ``` * `clang-format-8` - clang-format itself, remove the version or verify it is correct * awk script converts contents of `.clang-format-my` (or `.clang-format-company`) into inline format: `-style "{Option1: Value, ...}"`, because there is no way to specify filename with config to `clang-format` * do not forget to make the script executable: `chmod +x .git/clang-formatter.sh` ### In `.git/info/` add `attributes` file: ``` *.c filter=clangformat *.h filter=clangformat *.cpp filter=clangformat *.hpp filter=clangformat ``` Note, that `clangformat` in the `attributes` must match to `[filter "clangformat"]` in in `.git/config`.
2,214
First i hope that my question isn't off topic here, i'm sorry if it's the case but i don't know where i should ask if it's not here. I'm asking a question about security risks and what i should do when adding a particular fonctionnality, yet my post has been moved to SO without any comments of why it should belong to SO. But cleary it doesn't belong to SO, i'm not asking for any code. Maybe my question wasn't well explained. Can you take a look at it and explained me why wouldn't it belong to security SE ? <https://stackoverflow.com/questions/35713409/security-risk-of-a-service-that-test-connection-from-server-for-a-printer-from-c>
2016/03/01
[ "https://security.meta.stackexchange.com/questions/2214", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/98400/" ]
I understand why it was closed - the question seems very unclear. I read it a number of times and am not sure what you are asking. But I'm not sure why it was moved to SO. It's still unclear there... One thing to remember is that the system takes the majority view on closing, so there may have been 4 different Vote to Close reasons, or all the same - impossible to tell.
I'm one of the folks who voted to move it to SO. In in initial version of the question, it appeared to me that your primary question was about adding a button to your application to test a printer. It was somewhat unclear, but the security component appeared to me to be peripheral, and I thought I understood the question well enough to determine that the core was about making the button work, a programming question. In hindsight, I didn't understand correctly, and I should have let you clarify the question first, rather than voting to move. Mea culpa.
11,732,977
Can you count the results of a query and make part of the query dynamic if it doesn't meet a count threshold? Maybe using a case? As you can see below I have a big silly sql query that has a lot going on (ignore the date adjust part, sorry). Sometimes it returns less than 12 results out of a database of over 10k items, because of it requiring items within 17 hours of closing. **So the question is, can I check (count?) the results of the entire query inside itself, and open up that 17 hour parameter to a larger number to return at least 12 results?** Thanks in advance. ``` SELECT 100 - round((current_price / item.estimated_price)*100) as percent, item.cached_thumbnail_url, item.item_id, current_price, close_date, catalog_item_id FROM catalog_item AS ci JOIN item on item.item_id = ci.item_id JOIN item_translations it ON (it.item_id = item.item_id) WHERE ((100 - round((current_price / item.estimated_price)*100)) > 49 AND item.estimated_price > 0 AND current_price > 0 AND ci.close_date > DATE_ADD(NOW(), interval 14400 second) AND item.active = 1 AND ci.active = 1 AND (current_price / estimated_price) < 1 AND (ci.close_date < DATE_ADD(DATE_ADD(NOW(), interval 14400 second), INTERVAL 17 HOUR))) ORDER BY (item.estimated_price - current_price) DESC LIMIT 12 ```
2012/07/31
[ "https://Stackoverflow.com/questions/11732977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/541164/" ]
The suspect code apparently needs to be nested inside the inside the previous describe ``` describe "after saving the user" do before { click_button submit } let(:user) { User.find_by_email('user@example.com') } it { should have_selector('title', text: user.name) } it { should have_selector('div.alert.alert-success', text: 'Welcome') } it { should have_link('Sign out') } describe "followed by signout" do before { click_link "Sign out" } it { should have_link('Sign in') } end end ```
The `before` block in the last describe hasn't yet created the user. This is why the user (which doesn't exist yet) isn't currently signed in, thus no "sign out" link. One possible solution is to `click_button 'submit'` in the before block. Another is to skip the sign out in the `before` block altogether, since there is no user signed in at that point.
11,732,977
Can you count the results of a query and make part of the query dynamic if it doesn't meet a count threshold? Maybe using a case? As you can see below I have a big silly sql query that has a lot going on (ignore the date adjust part, sorry). Sometimes it returns less than 12 results out of a database of over 10k items, because of it requiring items within 17 hours of closing. **So the question is, can I check (count?) the results of the entire query inside itself, and open up that 17 hour parameter to a larger number to return at least 12 results?** Thanks in advance. ``` SELECT 100 - round((current_price / item.estimated_price)*100) as percent, item.cached_thumbnail_url, item.item_id, current_price, close_date, catalog_item_id FROM catalog_item AS ci JOIN item on item.item_id = ci.item_id JOIN item_translations it ON (it.item_id = item.item_id) WHERE ((100 - round((current_price / item.estimated_price)*100)) > 49 AND item.estimated_price > 0 AND current_price > 0 AND ci.close_date > DATE_ADD(NOW(), interval 14400 second) AND item.active = 1 AND ci.active = 1 AND (current_price / estimated_price) < 1 AND (ci.close_date < DATE_ADD(DATE_ADD(NOW(), interval 14400 second), INTERVAL 17 HOUR))) ORDER BY (item.estimated_price - current_price) DESC LIMIT 12 ```
2012/07/31
[ "https://Stackoverflow.com/questions/11732977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/541164/" ]
The `before` block in the last describe hasn't yet created the user. This is why the user (which doesn't exist yet) isn't currently signed in, thus no "sign out" link. One possible solution is to `click_button 'submit'` in the before block. Another is to skip the sign out in the `before` block altogether, since there is no user signed in at that point.
Yes, it should be nested inside the previous describe. I can confirm this also works for the Rails 4 version of the tutorial.
11,732,977
Can you count the results of a query and make part of the query dynamic if it doesn't meet a count threshold? Maybe using a case? As you can see below I have a big silly sql query that has a lot going on (ignore the date adjust part, sorry). Sometimes it returns less than 12 results out of a database of over 10k items, because of it requiring items within 17 hours of closing. **So the question is, can I check (count?) the results of the entire query inside itself, and open up that 17 hour parameter to a larger number to return at least 12 results?** Thanks in advance. ``` SELECT 100 - round((current_price / item.estimated_price)*100) as percent, item.cached_thumbnail_url, item.item_id, current_price, close_date, catalog_item_id FROM catalog_item AS ci JOIN item on item.item_id = ci.item_id JOIN item_translations it ON (it.item_id = item.item_id) WHERE ((100 - round((current_price / item.estimated_price)*100)) > 49 AND item.estimated_price > 0 AND current_price > 0 AND ci.close_date > DATE_ADD(NOW(), interval 14400 second) AND item.active = 1 AND ci.active = 1 AND (current_price / estimated_price) < 1 AND (ci.close_date < DATE_ADD(DATE_ADD(NOW(), interval 14400 second), INTERVAL 17 HOUR))) ORDER BY (item.estimated_price - current_price) DESC LIMIT 12 ```
2012/07/31
[ "https://Stackoverflow.com/questions/11732977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/541164/" ]
The suspect code apparently needs to be nested inside the inside the previous describe ``` describe "after saving the user" do before { click_button submit } let(:user) { User.find_by_email('user@example.com') } it { should have_selector('title', text: user.name) } it { should have_selector('div.alert.alert-success', text: 'Welcome') } it { should have_link('Sign out') } describe "followed by signout" do before { click_link "Sign out" } it { should have_link('Sign in') } end end ```
Yes, it should be nested inside the previous describe. I can confirm this also works for the Rails 4 version of the tutorial.
34,846,900
I am very new to this whole world of "big data" tech, and recently started reading about Spark. One thing that keeps coming up is SparkSQL, yet I consistently fail to comprehend was exactly it is. Is it supposed to convert SQL queries to MapReduce that do operations on the data you give it? But aren't dataframes already essentially SQL tables in terms of functionality? Or is it some tech that allows you to connect to an SQL database and use Spark to query it? In this case, what's the point of Spark in here at all - why not use SQL directly? Or is the point that you can use your structured SQL data in combination with the flat data? Again, I am emphasizing that I am very new to all of this and may or may not talking out of my butt :). So please do correct me and be forgiving if you see that I'm clearly misunderstanding something.
2016/01/18
[ "https://Stackoverflow.com/questions/34846900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your first answer is essentially correct, it's a API in Spark where you can write queries in SQL and they will be converted to a parallelised Spark job (Spark can do more complex types of operations than just map and reduce). Spark Data frames actually are just a wrapper around this API, it's just an alternative way of accessing the API, depending on whether you're more comfortable coding in SQL or in Python/Scala.
**Spark** ========= **Spark** is a Framework or very big set of components using for Scalable, efficient analysis of Big Data. **For example**: People are uploading a petabyte of video to YouTube every day. Now the time it takes to read one terabyte from a disk is about three hours at 100 megabytes per second. That's actually quite a long time(inexpensive of disk cannot helps us here). So the challenge we face is that one machine cannot process, or even store, all of the data. So our solution is **distributed data over cluster of machines**. > > **DataFrames** are the primary abstraction in Spark. > > > We can construct a data frame from text files, Json files, Hadoop Distributed File System, Apache Parquet or Hypertable or Amazon S3 file, Apache HBase and then perform some operations, transformation on it regardless where the data come from. **Spark Sql** ============= **Spark SQL** is a Spark module for structured data processing. as describing on the documentation page [here](https://spark.apache.org/docs/latest/sql-programming-guide.html#overview). So one of the interests of Spark SQL is that it allows us to query structured data from many data sources with an SQL syntax and offering many others possibilities. I think it is for this reason we don't use SQL directly.
47,410,340
I am using the [tablesorter](https://github.com/Mottie/tablesorter) from motti for sorting the html table.I am unable to find way to sort a certain column depend on another column value. In my case ,wanna sort the FULLNAME column depend on the LASTNAME column value which is basically hidden.Is this possible ? Thanks :-) ``` <table id="tblDetails"> <thead> <tr> <th>FULL NAME</th> <th style="display:none;">LAST NAME</th> <th>GENDER</th> <th>ADDRESS</th> </tr> </thead> <tbody> <tr> <td>James</td> <td style="display:none;">Peter</td> <td>male</td> <td>washington dc</td> </tr> <tr> <td>jennifer</td> <td style="display:none;">lopez</td> <td>female</td> <td>New york</td> </tr> <tr> <td>Harrison</td> <td style="display:none;">Ford</td> <td>male</td> <td>washington dc</td> </tr> </tbody> ```
2017/11/21
[ "https://Stackoverflow.com/questions/47410340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928461/" ]
You can use a fixed size array and up count appropriate index each time: It is hour[item-1] since list indexing starts at 0. ``` hour = [0] * 24 for i in range(0,24): item = int(input("please enter login hour: ")) if item == -1: break else: hour[item] += 1 ```
I have added a while loop to count the number of elements in the list. Hope you do not want to add -1 to the list. Included if statement to not append `-1` and break when user inputs `-1` Before the second loop, I have created another list which will contain unique values from `hour` to print number of attempts for only those numbers for whom attempt has actually been made(this is slightly different from what you have mentioned in question, You can get that be changing `sorted(unique_hrs)` in second loop to `range(1,25)`). ``` hour = [] while len(hour) < 24: item = int(input("please enter login hour: ")) if item != -1: hour.append(item) else: break unique_hrs = list(set(hour)) for i in sorted(unique_hrs): print('There were ' + str(hour.count(i)) + ' logins In hour ' + str(i)) ```
47,410,340
I am using the [tablesorter](https://github.com/Mottie/tablesorter) from motti for sorting the html table.I am unable to find way to sort a certain column depend on another column value. In my case ,wanna sort the FULLNAME column depend on the LASTNAME column value which is basically hidden.Is this possible ? Thanks :-) ``` <table id="tblDetails"> <thead> <tr> <th>FULL NAME</th> <th style="display:none;">LAST NAME</th> <th>GENDER</th> <th>ADDRESS</th> </tr> </thead> <tbody> <tr> <td>James</td> <td style="display:none;">Peter</td> <td>male</td> <td>washington dc</td> </tr> <tr> <td>jennifer</td> <td style="display:none;">lopez</td> <td>female</td> <td>New york</td> </tr> <tr> <td>Harrison</td> <td style="display:none;">Ford</td> <td>male</td> <td>washington dc</td> </tr> </tbody> ```
2017/11/21
[ "https://Stackoverflow.com/questions/47410340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928461/" ]
You can use a fixed size array and up count appropriate index each time: It is hour[item-1] since list indexing starts at 0. ``` hour = [0] * 24 for i in range(0,24): item = int(input("please enter login hour: ")) if item == -1: break else: hour[item] += 1 ```
``` # We will maintain a list with 24 entries # Each entry in the list will maintain a count for the number # of logins in that hour. Finally, we will print all the entries # from the list that will output number of logins for each hour # Creating a list with one entry for each hour records = [0] * 24 # Asking user 24 times for j in range(0, 24): i = int(input("please enter login hour:")) # Since lists are mutable, we can increment the count # at the corresponding position of the input hour if i != -1: records[i - 1] = records[i - 1] + 1 else: break # Print all the entries from the records for i in range(len(records)): print("There were " + str(records[i]) + " logins in hour " + str(i+1)) ```
18,247
When I add some lisp program in the init.el. I don't want to restart emacs in order to make effect. Then how can I do that?
2015/11/20
[ "https://emacs.stackexchange.com/questions/18247", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/9923/" ]
In addition to Drew's answer, if you add more than one expression, and don't want to have to evaluate them all individually, there's `eval-region`. Its docstring: > > Execute the region as Lisp code. > > > Select the region (move point to before the first expression, press `C-space`, move point to after the expression), then run `M-x eval-region`.
Evaluate it: call it with its arguments, using, for example `C-x C-e`. If the function `foo` takes arguments `arg1` and `arg2`, type `(foo arg1 arg2)`, put the cursor after `)`, and hit `C-x C-e`. But if you are going to use some Emacs Lisp you really should start to read the Intro to Emacs Lisp manual - use `C-h i` then choose `Emacs Lisp Intro`.
18,247
When I add some lisp program in the init.el. I don't want to restart emacs in order to make effect. Then how can I do that?
2015/11/20
[ "https://emacs.stackexchange.com/questions/18247", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/9923/" ]
Evaluate it: call it with its arguments, using, for example `C-x C-e`. If the function `foo` takes arguments `arg1` and `arg2`, type `(foo arg1 arg2)`, put the cursor after `)`, and hit `C-x C-e`. But if you are going to use some Emacs Lisp you really should start to read the Intro to Emacs Lisp manual - use `C-h i` then choose `Emacs Lisp Intro`.
If your function has defvar or defcustom and you want those reset as part of the eval, then consider C-M-x (eval-defun). A plain eval will not reset previous values of the defvars, if any.
18,247
When I add some lisp program in the init.el. I don't want to restart emacs in order to make effect. Then how can I do that?
2015/11/20
[ "https://emacs.stackexchange.com/questions/18247", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/9923/" ]
In addition to Drew's answer, if you add more than one expression, and don't want to have to evaluate them all individually, there's `eval-region`. Its docstring: > > Execute the region as Lisp code. > > > Select the region (move point to before the first expression, press `C-space`, move point to after the expression), then run `M-x eval-region`.
If your function has defvar or defcustom and you want those reset as part of the eval, then consider C-M-x (eval-defun). A plain eval will not reset previous values of the defvars, if any.
47,418,881
I'm new to the java language and have just learned basic stuff as of yet. I have to write an application that asks a user to enter an integer, and then display a statement that indicates whether an integer is even or odd. This is what I have done: ``` import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); double divisibleByTwo = num % 2; if(divisibleByTwo == 0) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } } ``` The above code works fine, but the software that grades my code requires my code to be in this format: ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd } public static boolean isEven(int number) { // check if number is even } } ``` The following is my setup, but I have several mistakes in it, and am not really sure how to get going and have it work right. Any help would be appreciated. ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); isEven(num); boolean divisible; isDivisibleByTwo = divisible; if(divisible == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { // check if number is even int remainderByTwo = number % 2; boolean isDivisbleByTwo = (remainderByTwo == 0); return isDivisibleByTwo; } } ```
2017/11/21
[ "https://Stackoverflow.com/questions/47418881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8981016/" ]
In your first example you are assigning the variable correctly when you do ``` double divisibleByTwo = num % 2; ``` and then using that value that was returned you check ``` if(divisibleByTwo == 0)... ``` which returns true or false. However in the next sample of code you do ``` isEven(num); //NO asignment!!!! boolean divisible; //defaults to false isDivisibleByTwo = divisible; if(divisible == true) //divisble will always be false ``` Since you never assign divisible to the value returned by isEven your if statement will always return false because the default value of boolean variables are false. You need to assign the value returned by your isEven method call and then use that value like this ``` boolean isDivisibleByTwo = isEven(num); if(isDivisibleByTwo) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); ``` Or you can use the returned value of the isEven method without having to assign it to a variable like this ``` if(isEven(num)) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); ```
Your goal is to do all the calculation in the `isEven` method, your main method will only be used to get the number from the user and call the other method. No need to do calculations there. In other words something like the following : ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // Get the user input Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); // Check if the input is correct ? // Call your method and check the return value if(isEven(num)) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } // And then your method is good public static boolean isEven(int number) { // check if number is even return (number % 2) == 0; } } ```
47,418,881
I'm new to the java language and have just learned basic stuff as of yet. I have to write an application that asks a user to enter an integer, and then display a statement that indicates whether an integer is even or odd. This is what I have done: ``` import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); double divisibleByTwo = num % 2; if(divisibleByTwo == 0) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } } ``` The above code works fine, but the software that grades my code requires my code to be in this format: ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd } public static boolean isEven(int number) { // check if number is even } } ``` The following is my setup, but I have several mistakes in it, and am not really sure how to get going and have it work right. Any help would be appreciated. ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); isEven(num); boolean divisible; isDivisibleByTwo = divisible; if(divisible == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { // check if number is even int remainderByTwo = number % 2; boolean isDivisbleByTwo = (remainderByTwo == 0); return isDivisibleByTwo; } } ```
2017/11/21
[ "https://Stackoverflow.com/questions/47418881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8981016/" ]
In your first example you are assigning the variable correctly when you do ``` double divisibleByTwo = num % 2; ``` and then using that value that was returned you check ``` if(divisibleByTwo == 0)... ``` which returns true or false. However in the next sample of code you do ``` isEven(num); //NO asignment!!!! boolean divisible; //defaults to false isDivisibleByTwo = divisible; if(divisible == true) //divisble will always be false ``` Since you never assign divisible to the value returned by isEven your if statement will always return false because the default value of boolean variables are false. You need to assign the value returned by your isEven method call and then use that value like this ``` boolean isDivisibleByTwo = isEven(num); if(isDivisibleByTwo) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); ``` Or you can use the returned value of the isEven method without having to assign it to a variable like this ``` if(isEven(num)) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); ```
You don't need to overcomplicate things. You just need cleaner and simple code: ``` public class OddEven { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); boolean remainder = isEven(num); if (remainder == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { if (number % 2 == 0) return true; else return false; } } ```
47,418,881
I'm new to the java language and have just learned basic stuff as of yet. I have to write an application that asks a user to enter an integer, and then display a statement that indicates whether an integer is even or odd. This is what I have done: ``` import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); double divisibleByTwo = num % 2; if(divisibleByTwo == 0) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } } ``` The above code works fine, but the software that grades my code requires my code to be in this format: ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd } public static boolean isEven(int number) { // check if number is even } } ``` The following is my setup, but I have several mistakes in it, and am not really sure how to get going and have it work right. Any help would be appreciated. ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); isEven(num); boolean divisible; isDivisibleByTwo = divisible; if(divisible == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { // check if number is even int remainderByTwo = number % 2; boolean isDivisbleByTwo = (remainderByTwo == 0); return isDivisibleByTwo; } } ```
2017/11/21
[ "https://Stackoverflow.com/questions/47418881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8981016/" ]
In your first example you are assigning the variable correctly when you do ``` double divisibleByTwo = num % 2; ``` and then using that value that was returned you check ``` if(divisibleByTwo == 0)... ``` which returns true or false. However in the next sample of code you do ``` isEven(num); //NO asignment!!!! boolean divisible; //defaults to false isDivisibleByTwo = divisible; if(divisible == true) //divisble will always be false ``` Since you never assign divisible to the value returned by isEven your if statement will always return false because the default value of boolean variables are false. You need to assign the value returned by your isEven method call and then use that value like this ``` boolean isDivisibleByTwo = isEven(num); if(isDivisibleByTwo) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); ``` Or you can use the returned value of the isEven method without having to assign it to a variable like this ``` if(isEven(num)) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); ```
Write an application that reads in two integers and determines and prints whether the first is a multiple of the second. For example, if the user inputs 15 and 3, the first number is a multiple of the second. If the user inputs 2 and 4, the first number is not a multiple of the second.
47,418,881
I'm new to the java language and have just learned basic stuff as of yet. I have to write an application that asks a user to enter an integer, and then display a statement that indicates whether an integer is even or odd. This is what I have done: ``` import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); double divisibleByTwo = num % 2; if(divisibleByTwo == 0) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } } ``` The above code works fine, but the software that grades my code requires my code to be in this format: ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd } public static boolean isEven(int number) { // check if number is even } } ``` The following is my setup, but I have several mistakes in it, and am not really sure how to get going and have it work right. Any help would be appreciated. ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); isEven(num); boolean divisible; isDivisibleByTwo = divisible; if(divisible == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { // check if number is even int remainderByTwo = number % 2; boolean isDivisbleByTwo = (remainderByTwo == 0); return isDivisibleByTwo; } } ```
2017/11/21
[ "https://Stackoverflow.com/questions/47418881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8981016/" ]
You don't need to overcomplicate things. You just need cleaner and simple code: ``` public class OddEven { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); boolean remainder = isEven(num); if (remainder == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { if (number % 2 == 0) return true; else return false; } } ```
Your goal is to do all the calculation in the `isEven` method, your main method will only be used to get the number from the user and call the other method. No need to do calculations there. In other words something like the following : ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // Get the user input Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); // Check if the input is correct ? // Call your method and check the return value if(isEven(num)) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } // And then your method is good public static boolean isEven(int number) { // check if number is even return (number % 2) == 0; } } ```
47,418,881
I'm new to the java language and have just learned basic stuff as of yet. I have to write an application that asks a user to enter an integer, and then display a statement that indicates whether an integer is even or odd. This is what I have done: ``` import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); double divisibleByTwo = num % 2; if(divisibleByTwo == 0) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } } ``` The above code works fine, but the software that grades my code requires my code to be in this format: ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd } public static boolean isEven(int number) { // check if number is even } } ``` The following is my setup, but I have several mistakes in it, and am not really sure how to get going and have it work right. Any help would be appreciated. ``` import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); isEven(num); boolean divisible; isDivisibleByTwo = divisible; if(divisible == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { // check if number is even int remainderByTwo = number % 2; boolean isDivisbleByTwo = (remainderByTwo == 0); return isDivisibleByTwo; } } ```
2017/11/21
[ "https://Stackoverflow.com/questions/47418881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8981016/" ]
You don't need to overcomplicate things. You just need cleaner and simple code: ``` public class OddEven { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); boolean remainder = isEven(num); if (remainder == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { if (number % 2 == 0) return true; else return false; } } ```
Write an application that reads in two integers and determines and prints whether the first is a multiple of the second. For example, if the user inputs 15 and 3, the first number is a multiple of the second. If the user inputs 2 and 4, the first number is not a multiple of the second.
13,088,993
I wanted to select all of the elements in the DOM that have a border-radius !== 0. Do you guys know a way of doing that?
2012/10/26
[ "https://Stackoverflow.com/questions/13088993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462403/" ]
Yes. Use the [.filter()](http://api.jquery.com/filter/) function. ``` $(elements).filter(function(){ return parseInt($(this).css("border-radius"),10) != 0; }); ```
Use a CSS class to define your border radius, then use jQuery to select them. CSS: ``` .border-radius { border-radius: 4px; } ``` JS: ``` $('.border-radius') ```
13,088,993
I wanted to select all of the elements in the DOM that have a border-radius !== 0. Do you guys know a way of doing that?
2012/10/26
[ "https://Stackoverflow.com/questions/13088993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462403/" ]
Yes. Use the [.filter()](http://api.jquery.com/filter/) function. ``` $(elements).filter(function(){ return parseInt($(this).css("border-radius"),10) != 0; }); ```
Because I like to be thorough, we ought to consider the fact that `border-radius` can accept multiple values to describe all four corners individually: ``` $('*').filter(function() { var br = $(this).css("border-radius").split(' '), test = false; for (var i = 0, j = br.length; i < j; i++) { test = test || parseInt(br[i], 10); }; return test; }) ``` <http://jsfiddle.net/mblase75/SLUcb/> That said, filtering EVERY element on the page is outrageously inefficient. The better approach is just to assign the `border-radius` to a class and test for the existence of objects with that class.
37,222,895
I'm new to the forms, so excuse me. For some odd reason, it may just be because it's 1 AM I just can't link CSS properly!They are in the same folder, no sub-folders or anything (on mac btw) and it's just not linking up. Any help would be appreciated. Thanks. ``` <html> <head> <title></title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="container"> <div class="nav"> <nav> <ul> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> </ul> </nav> </div> </div> </body> ```
2016/05/14
[ "https://Stackoverflow.com/questions/37222895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6333258/" ]
The most efficient way to improve performance in your case is to a add a **INDEX** to your **sort** column in this case message\_id for better performance. In this way , your query will perform an **index scan instead of a full table** scan which hampers the performance. You can create an index by using following statement: ``` CREATE INDEX index_name ON table_name (column_name) ```
Yes. If message\_id is not the leading column in the primary key or a secondary index, then create an index: ``` ... ON MESSAGES (message_id) ``` And eliminate the inline view: ``` SELECT m.* FROM MESSAGES m WHERE m.message_id > ? ORDER BY m.message_id ```
37,222,895
I'm new to the forms, so excuse me. For some odd reason, it may just be because it's 1 AM I just can't link CSS properly!They are in the same folder, no sub-folders or anything (on mac btw) and it's just not linking up. Any help would be appreciated. Thanks. ``` <html> <head> <title></title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="container"> <div class="nav"> <nav> <ul> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> </ul> </nav> </div> </div> </body> ```
2016/05/14
[ "https://Stackoverflow.com/questions/37222895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6333258/" ]
The most efficient way to improve performance in your case is to a add a **INDEX** to your **sort** column in this case message\_id for better performance. In this way , your query will perform an **index scan instead of a full table** scan which hampers the performance. You can create an index by using following statement: ``` CREATE INDEX index_name ON table_name (column_name) ```
Create a B-Tree Index : You can adjust the ordering of a B-tree index by including the options ASC, DESC, NULLS FIRST, and/or NULLS LAST when creating the index; for example: CREATE INDEX test2\_info\_nulls\_low ON test2 (info NULLS FIRST); CREATE INDEX test3\_desc\_index ON test3 (id DESC NULLS LAST);
16,297,485
i have an index page that contain div content. i load contents from other divs in other pages via ajax inside index page content div. the content successfully loaded but without its css and scripts. How can i load the content with its css and scripts to work inside content div. ``` $(document).ready(function () { $(".menuAnchor").click(function (event) { event.preventDefault(); var url = $(this).attr('href'); var title = $(this).attr('title '); window.history.pushState("",title,url); $.get(url, {}, function (data) { $(".contn_btm_mid_bg").html($(data).find('.contn_btm_mid_bg').html()); //$.validator.unobtrusive.parse(".contn_btm_mid_bg"); }); }); }); ```
2013/04/30
[ "https://Stackoverflow.com/questions/16297485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331047/" ]
ok do one thing load your css and js externally using code ``` $("<link/>", { rel: "stylesheet", type: "text/css", href: "/styles/yourcss.css" }).appendTo("head"); ``` same for js
either declare css on index page or declare css within div on other page(ajax page)
16,297,485
i have an index page that contain div content. i load contents from other divs in other pages via ajax inside index page content div. the content successfully loaded but without its css and scripts. How can i load the content with its css and scripts to work inside content div. ``` $(document).ready(function () { $(".menuAnchor").click(function (event) { event.preventDefault(); var url = $(this).attr('href'); var title = $(this).attr('title '); window.history.pushState("",title,url); $.get(url, {}, function (data) { $(".contn_btm_mid_bg").html($(data).find('.contn_btm_mid_bg').html()); //$.validator.unobtrusive.parse(".contn_btm_mid_bg"); }); }); }); ```
2013/04/30
[ "https://Stackoverflow.com/questions/16297485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331047/" ]
ok do one thing load your css and js externally using code ``` $("<link/>", { rel: "stylesheet", type: "text/css", href: "/styles/yourcss.css" }).appendTo("head"); ``` same for js
Put Css and Js inside target `div` which you want to load.
42,987,199
Node Class As part of the tree implementation you should implement a Node class. Each node should contain a Customer object, pointers to left and right children and (optionally) the parent. So, currently I have a customer class such that: ``` class Customer { public: Customer(void); Customer(string,char,int); }; ``` In my node class how can I create a customer object while linking the two files? Do I just include the following in my node header file? ``` #include "Customer.h" class Node { public: //Customer class class Customer { public: Customer(void); Customer(string,char,int); } Node(void); //default constructor Node(string,char,int); //Node constructor with customer details Node* left; Node* right; Node* parent; }; ``` In the node.cpp file to pass in the values to the node: ``` //Constructor Node::Node(string x, char y, int z) { lastName = x; firstInitial = y; balance = z; } ``` How do I pass the values of the customer object to the node construct?
2017/03/23
[ "https://Stackoverflow.com/questions/42987199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7537349/" ]
> > Do I just include the following in my node header file? > > > No. You just use an object of type `Customer` in `Node`. ``` #include "Customer.h" class Node { public: Node(void); //default constructor Node(string,char,int); //Node constructor with customer details Node* left; Node* right; Node* parent; Customer customer; }; ``` Implement the constructors as: ``` Node::Node() : left(nullptr), right(nullptr), parent(nullptr), customer() {} Node::Node(string x, char y, int z) : left(nullptr), right(nullptr), parent(nullptr), customer(x, y, z) {} ```
You simply include the header as you did and then declare a Customer object in your Node class (private / protected / public, as you wish). When you'll declare a Node object, the first thing that is constructed are the objects inside your class, and only then the class itself. So, if you would have a `cout`in both constructors with the class name, when you'll be declaring a Node object, you'll see: Customer's constructor Node's constructor Also, if you want to specify how to construct the Customer object inside the Node constructor, you can use the list of initialization ``` class Node { public: Customer obj; Node(string,char,int); } ``` and then define the Node constructor like this in your .cpp file: ``` Node :: Node(string x,char y,int z) : obj(x, y, z) { } ``` this is just an example. You can use static values when initializing `obj` or you could also get more parameters for Node constructor and so on.
276,493
anyone knows how to change the default width for shell window in Linux(Ubuntu), so that I don't have to re-size it every time I open it up? Thanks
2011/04/28
[ "https://superuser.com/questions/276493", "https://superuser.com", "https://superuser.com/users/-1/" ]
Run `gconf-editor`, navigate to `/apps/gnome-terminal/profiles/Default` and set the `default_size_columns` and `default_size_rows` keys. The columns & rows are measured in characters, not in pixels.
If you are on gnome: ``` gnome-terminal --geometry 120x60 ``` Will explicitly state the window size. `konsole` sounds like KDE's variant. The same argument should work there.
4,870,828
i have published android app but not appearing in android market.i m using android 2.2 and i have tried in samsung galaxy that is not showing my application so just give me some idea to fix this problem. this is my manifest.xml file: ``` <activity android:name=".Full" android:screenOrientation="landscape" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.SAMPLE_CODE" /> </intent-filter> </activity> <activity android:name=".Short" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.SAMPLE_CODE" /> </intent-filter> </activity> </application> ``` Please help me..
2011/02/02
[ "https://Stackoverflow.com/questions/4870828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/591790/" ]
If I understand you correctly you just want to get the most recent transaction for all users. ``` SELECT user_id, trans_date, trans_credit FROM `table` GROUP BY user_id ORDER BY trans_date DESC; ```
How about something like ``` SELECT t.* FROM table t INNER JOIN ( SELECT user_id, MAX(trans_date) max_trans_date FROM table GROUP BY user_id ) MaxDates ON t.user_id = MaxDates.max_trans_date ```
743,792
I'm setting up Email Authentication and I'm seeing conflicting info on the format. [Some say](http://help.campaignmonitor.com/topic.aspx?t=100) that the value should be surrounded in `"` `"` But other services have told me to leave out the surrounding `"` Does it just vary by ESP (email service provider)?
2015/12/17
[ "https://serverfault.com/questions/743792", "https://serverfault.com", "https://serverfault.com/users/2181/" ]
The formatting of `TXT` record data doesn't really have to do with Email. Ie, it doesn't have to do with the Email Service Provider, rather the DNS server software / DNS Service provider if anything. `TXT` records [can have multiple string values](https://www.rfc-editor.org/rfc/rfc1035#section-3.3.14). In the standardized master file format, [if you put quotation marks around something that becomes a single string](https://www.rfc-editor.org/rfc/rfc1035#page-35) even if there are spaces. If you leave out the quotation marks each "word" is a string of its own. For DKIM `TXT` records, if there are multiple string values [these are simply concatenated](https://www.rfc-editor.org/rfc/rfc6376#section-3.6.2.2). This means that: `"foo bar"` means *foo bar* `foo bar` is the same as `"foo" "bar"` and means *foobar* For a DKIM record specifically there isn't really significant whitespace, so either is ok in that respect but be careful with `;` as semicolon is the comment character in the master file format. Now, this is all regarding the standardized master file format, if you instead talk about something like a form field in a web UI of a DNS service provider, then you'll really have to consult their documentation as their UI may or may not accept its input based on the above.
Yes surround the whole shabang in quotes! Fun fact, dig returns results in bind-ok format, so you can always try digging someone else's dkim record: ``` [d...@o... ~]$ dig @sjc-dns1.ebaydns.com -t TXT dkim1k._domainkey.ebay.com ``` [snip] ``` dkim1k._domainkey.ebay.com. 3600 IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+mihCTvPRr46AskdAcAP0FLp+PwmRwxUjWXSaQiT0u+iqOaDj8wi9/kRfTJyvkPVAnEa3d9l1hSiVmK7VMTptUldvitfg/T2AVMi5s/B9gJoj30eOujBJHFvCd6Imu4BDCMjZSDWEcbHXH+jsYuNxCG5aeguZwGzaFtsK0iLhDQIDAQAB;" ``` [snip]
82,730
I'm trying to compare two diagrams in pdf format side by side. I have this post - [Two figures side by side](https://tex.stackexchange.com/questions/5769/two-figures-side-by-side) to get some hint. This is the code that I'm coming up with. ``` \begin{figure} \begin{minipage}[t]{0.45\linewidth} \includegraphics[scale=0.30]{before.pdf} \caption{(a) Before} \end{minipage}% \hfill\vrule\hfill \begin{minipage}[t]{0.45\linewidth} \includegraphics[scale=0.3]{after.pdf} \caption{(b) After} \end{minipage}% \caption{Hello} \end{figure} ``` And this is the result, which is not exactly what I expected. ![enter image description here](https://i.stack.imgur.com/ulR0r.png) * What modifications are needed to make the pictures sit side by side? * I just want the caption (a) Before and (b) After without any `Figure` prepended. What should I do?
2012/11/14
[ "https://tex.stackexchange.com/questions/82730", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/379/" ]
Although you can solve perfectly the problem with `minipages`, for sub-figures with captions enumerated with letters (a,b,..) you can use also the package `subcaption` to simplify a little your code, as you do not need write "(a)" and "(b)", but mainly because the flexibility that you have with this package, as listing the subfigures. Note that neither is it necessary in the MWE the use of `\centering` nor include file extension (.pdf). Note: Remove the `demo` option in `graphicx` package to use your diagrams instead of the black boxes: ``` \documentclass{article} \usepackage[demo]{graphicx} % remove option for real images \usepackage[list=true]{subcaption} \begin{document} \listoffigures \vspace{3cm} \begin{figure}[h]% \begin{subfigure}[h]{0.4\textwidth} \includegraphics[width=\textwidth]{before} \caption{Before} \end{subfigure} \hfill\vrule\hfill \begin{subfigure}[h]{0.4\textwidth} \includegraphics[width=\textwidth]{after} \caption{After} \end{subfigure}% \caption[Hello]{Hello, this a minimal working example} \end{figure} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/gpAlO.png) Alternatively you can use also `subfig` or `subfigure` packages for the same reasons. See [Setting default distance between subfigures](https://tex.stackexchange.com/questions/68025/setting-default-distance-between-subfigures) for examples with these packages.
Thanks to egreg and Vincent, I could make the correction. The problem was the empty line that caused the wrong alignment, and I replaced `caption` with `centering` to remove the `Figure` ![enter image description here](https://i.stack.imgur.com/PGKf9.png) ``` \begin{figure} \begin{minipage}[t]{0.49\linewidth} \centering \includegraphics[width=\linewidth]{before.pdf} (a) Before \end{minipage}% \hfill\vrule\hfill \begin{minipage}[t]{0.49\linewidth} \centering \includegraphics[width=\linewidth]{after.pdf} (b) After \end{minipage} \caption{Hello} \end{figure} ``` ---
14,184,802
I have encountered an example of HTML5 that has an absence of a number in the heading tag unlike the normal `<h1>` to `<h6>` tags. Is this an incorrect use of HTML? I believe that this use of the heading tag is incorrect, I did want to verify though. ``` <article> <h>Subheading</h> This is some content </article> ```
2013/01/06
[ "https://Stackoverflow.com/questions/14184802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1554264/" ]
There is no `<h>` element in HTML. There was one proposed for XHTML 2, but that never took off.
He can "create" new tags in HTML and then put as selector in CSS. But this is not a header though.
43,818,109
I am appending output to a `ul` element using `li` elements. I am able to generate the output as desired but I have no idea on how to use transitions and transform, as Javascript is creating those `li` elements. I want to transform `li` elements as they appear from Javascript in the DOM. Vanilla Javascript is preferred. What I have, HTML: ``` <div class="add"> <input type="text" id="addTodoTextInput" placeholder="Add Task Here" onkeydown="handlers.addTodo()" > <!-- input text field to add <li> --> <button onclick="search()"> <img src="add.png" height="20" width="20" alt=""> </button> <!-- button to add li --> </div> <ul class="result"> <!-- output generated with JavaScript will be appended here --> </ul> ``` CSS: ``` li{ margin: 0 5px 0 5px; padding: 5px; font-family: cursive; color: #006cff; font-size: 1.3em; background: rgba(43, 229, 43, 0.28); transition: 2s; } li:hover{ transform: translateX(50px); } ``` JavaScript: ``` var handlers = { addTodo: function(){ var addToDoInput = document.getElementById('addTodoTextInput'); todoList.addToDo(addToDoInput.value); addToDoInput.value = ""; view.displayTodo(); } } var view = { displayTodo: function() { var todosUl = document.querySelector('ul'); todosUl.innerHTML = ''; todoList.itemList.forEach(function(todo,position) { var todosLi = document.createElement('li'); var todoTextWithCompletion = ""; if(todo.completed === true) { todosLi.style.textDecoration = "line-through"; } todosLi.id = position; todosLi.textContent = todo.todoText; todosLi.appendChild(this.createDeleteButton()); todosLi.appendChild(this.createToggleButton()); todosUl.appendChild(todosLi); }, this); } } ```
2017/05/06
[ "https://Stackoverflow.com/questions/43818109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7897366/" ]
You need convert to `str` first and select first `2` values which are compared with [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) and filter with [`boolean indexing`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing): ``` print (df.B.astype(str).str[:2]) 0 15 1 15 2 15 3 16 4 16 5 16 6 17 7 17 8 17 9 60 10 60 11 60 12 90 13 90 14 90 Name: B, dtype: object print (df[df.B.astype(str).str[:2].isin(['15','16','60'])]) A B D 0 d 151 M 1 d 152 a 2 d 153 M 3 d 161 z 4 d 164 M 5 d 169 g 9 d 605 j 10 d 603 d 11 d 607 e ``` Another solution is use [`contains`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html) with custom regex - `^` means start of string and `|` or: ``` L = [15,16,90] val = '|'.join(['^' + str(x) for x in L]) print (val) ^15|^16|^90 print (df[df.B.astype(str).str.contains(val)]) A B D 0 d 151 M 1 d 152 a 2 d 153 M 3 d 161 z 4 d 164 M 5 d 169 g 12 d 905 j 13 d 903 d 14 d 907 e ```
``` >>> df[df['B'].map(lambda x: str(x[:2]) in ['15', '16', '60'])] A B D 0 d 151 M 1 d 152 a 2 d 153 M 3 d 161 z 4 d 164 M 5 d 169 g 9 d 605 j 10 d 603 d 11 d 607 e ```
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
This is now [in Atom core](https://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition), you don't need that file-types package any more. Where I work, we use .phl for a certain kind of PHP file. To tell Atom about this, first [find the language's Scope Name](https://flight-manual.atom.io/using-atom/sections/basic-customization/#finding-a-languages-scope-name) (e.g. `text.html.php` ), then edit `config.cson` like so: ``` core: customFileTypes: "text.html.php": [ "phl" ] themes: [ // snip ``` You can find this file at `~/.atom/config.cson`, or from the Settings window click the "Open Config Folder" button. It's easy to get wrong, as evidenced by the many errors people made on the [GitHub issue](https://github.com/atom/atom/issues/1718) for the feature.
*Edit:* since the time I wrote this answer, this functionality has been added to Atom core, see [this answer](https://stackoverflow.com/a/32508353/2315334) for details. ### file-types Atom package (<https://atom.io/packages/file-types>) It does exactly what the title question asks for: you can define new file extensions for existing languages with a simple edit of the `config.cson` file.
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
For individual files you can use the Grammar Selector; `Ctrl`+`Shift`+`L` to set which language you're using on that file. Not the same as auto-detect but useful for those times when you're using a file that you don't want to set a default for.
For example if you want to open all `.jsx` files with javascript syntax, you need to add this to your `config.cson` ``` "*": core: customFileTypes: "source.js": [ "jsx" ] ``` This maps all .jsx files to open with js syntax.
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
*Edit:* since the time I wrote this answer, this functionality has been added to Atom core, see [this answer](https://stackoverflow.com/a/32508353/2315334) for details. ### file-types Atom package (<https://atom.io/packages/file-types>) It does exactly what the title question asks for: you can define new file extensions for existing languages with a simple edit of the `config.cson` file.
As Dave Andersen mentions in a buried comment, it is now possible to do this without any extra packages and it's documented [here](http://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition).
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
This is now [in Atom core](https://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition), you don't need that file-types package any more. Where I work, we use .phl for a certain kind of PHP file. To tell Atom about this, first [find the language's Scope Name](https://flight-manual.atom.io/using-atom/sections/basic-customization/#finding-a-languages-scope-name) (e.g. `text.html.php` ), then edit `config.cson` like so: ``` core: customFileTypes: "text.html.php": [ "phl" ] themes: [ // snip ``` You can find this file at `~/.atom/config.cson`, or from the Settings window click the "Open Config Folder" button. It's easy to get wrong, as evidenced by the many errors people made on the [GitHub issue](https://github.com/atom/atom/issues/1718) for the feature.
As Dave Andersen mentions in a buried comment, it is now possible to do this without any extra packages and it's documented [here](http://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition).
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
For individual files you can use the Grammar Selector; `Ctrl`+`Shift`+`L` to set which language you're using on that file. Not the same as auto-detect but useful for those times when you're using a file that you don't want to set a default for.
As Dave Andersen mentions in a buried comment, it is now possible to do this without any extra packages and it's documented [here](http://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition).
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
Easy mode: include ================== If your language really is just HTML, you can set up a simple package to handle this. Create a package called `langugage-ejs` and in `grammars/ejs.cson` you can include HTML as having the patterns you care about: ``` 'fileTypes': [ 'ejs' ] 'name': 'Embedded JavaScript' 'patterns': [ { 'include': 'source.html' } ] 'scopeName': 'source.ejs' ``` [language-ipynb](https://github.com/rgbkrk/language-ipynb) certainly does this by extending JSON. What about my template tags? ============================ In reality though, you have template tags on top of HTML that you would want to make the editor recognize. The best example I can find is for [erb (Embedded Ruby templates)](https://github.com/atom/language-ruby-on-rails/blob/master/grammars/html%20(rails).cson). It sources from HTML but also adds on other tags as shown in this snippet: ``` ... 'patterns': [ { 'begin': '<%+#' 'captures': '0': 'name': 'punctuation.definition.comment.erb' 'end': '%>' 'name': 'comment.block.erb' } { 'begin': '<%+(?!>)[-=]?' 'captures': '0': 'name': 'punctuation.section.embedded.ruby' 'end': '-?%>' 'name': 'source.ruby.rails.embedded.html' 'patterns': [ { 'captures': '1': 'name': 'punctuation.definition.comment.ruby' 'match': '(#).*?(?=-?%>)' 'name': 'comment.line.number-sign.ruby' } { 'include': 'source.ruby.rails' } ] } { 'include': 'text.html.basic' } ] ... ```
It looks likes there's a brand new package has been released for this. <https://atom.io/packages/language-ejs>.
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
This is now [in Atom core](https://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition), you don't need that file-types package any more. Where I work, we use .phl for a certain kind of PHP file. To tell Atom about this, first [find the language's Scope Name](https://flight-manual.atom.io/using-atom/sections/basic-customization/#finding-a-languages-scope-name) (e.g. `text.html.php` ), then edit `config.cson` like so: ``` core: customFileTypes: "text.html.php": [ "phl" ] themes: [ // snip ``` You can find this file at `~/.atom/config.cson`, or from the Settings window click the "Open Config Folder" button. It's easy to get wrong, as evidenced by the many errors people made on the [GitHub issue](https://github.com/atom/atom/issues/1718) for the feature.
It looks likes there's a brand new package has been released for this. <https://atom.io/packages/language-ejs>.
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
*Edit:* since the time I wrote this answer, this functionality has been added to Atom core, see [this answer](https://stackoverflow.com/a/32508353/2315334) for details. ### file-types Atom package (<https://atom.io/packages/file-types>) It does exactly what the title question asks for: you can define new file extensions for existing languages with a simple edit of the `config.cson` file.
It looks likes there's a brand new package has been released for this. <https://atom.io/packages/language-ejs>.
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
For individual files you can use the Grammar Selector; `Ctrl`+`Shift`+`L` to set which language you're using on that file. Not the same as auto-detect but useful for those times when you're using a file that you don't want to set a default for.
It looks likes there's a brand new package has been released for this. <https://atom.io/packages/language-ejs>.
22,363,070
I want my .ejs files to have html syntax, however, it always opens the files as Plain Text. In sublime you can choose "Open all with current extension as..." then choose your syntax. ![sublime text3 syntax](https://i.stack.imgur.com/T5zBq.png) I see that you can change the syntax in the left bottom corner![syntax change](https://i.stack.imgur.com/k5FJW.png) How do you open files with a certain type with a specific syntax?
2014/03/12
[ "https://Stackoverflow.com/questions/22363070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1258121/" ]
This is now [in Atom core](https://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition), you don't need that file-types package any more. Where I work, we use .phl for a certain kind of PHP file. To tell Atom about this, first [find the language's Scope Name](https://flight-manual.atom.io/using-atom/sections/basic-customization/#finding-a-languages-scope-name) (e.g. `text.html.php` ), then edit `config.cson` like so: ``` core: customFileTypes: "text.html.php": [ "phl" ] themes: [ // snip ``` You can find this file at `~/.atom/config.cson`, or from the Settings window click the "Open Config Folder" button. It's easy to get wrong, as evidenced by the many errors people made on the [GitHub issue](https://github.com/atom/atom/issues/1718) for the feature.
For individual files you can use the Grammar Selector; `Ctrl`+`Shift`+`L` to set which language you're using on that file. Not the same as auto-detect but useful for those times when you're using a file that you don't want to set a default for.
67,237,574
m beginner at react i have a little problem i want to change a bool value which is isApproved so the admin click a button and approve the post so it can be displayed here is my code . can anyone help me this is the function that change the value of isApproved ``` //@route put api/posts/approve/:id //@desc approve post //@access Private router.post('/:id/approve', auth, async(req, res) => { console.log("action base de donne begin"); Post.findById(req.params.id, (err, post) => { console.log(post.isApproved); if (err) { console.log(err); } else if (post.isApproved == false) { post.update({$set: {isApproved: true}}); } else { post.update({$set: {isApproved: false}}); } }); }); ``` the post model : ``` const mongoose = require('mongoose'); const Schema = mongoose.Schema; // Create Schema const PostSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'users' }, text: { type: String, required: true }, name: { type: String }, avatar: { type: String }, isApproved: { type: Boolean, default: false }, likes: [ { user: { type: Schema.Types.ObjectId, ref: 'users' } } ], comments: [ { user: { type: Schema.Types.ObjectId, ref: 'users' }, text: { type: String, required: true }, name: { type: String }, avatar: { type: String }, date: { type: Date, default: Date.now } } ], date: { type: Date, default: Date.now } }); module.exports = Post = mongoose.model('post', PostSchema); ``` approve action : ``` // Approve Approve export const approve = id => async dispatch => { try { console.log('action is begin'); console.log(id); const res = await axios.post(`/api/posts/${id}/approve`); console.log('la valeur dans action est',res) dispatch({ type: APPROVE_POST, payload: { id, isApproved: res.data } }); } catch (err) { dispatch({ type: POST_ERROR, payload: { msg: err.response.statusText, status: err.response.status } }); } }; ``` post reducers ``` import { GET_POSTS, POST_ERROR, UPDATE_LIKES, DELETE_POST, ADD_POST, GET_POST, ADD_COMMENT, REMOVE_COMMENT, APPROVE_POST } from '../actions/types'; const initialState = { posts: [], post: null, loading: true, error: {} }; export default function(state = initialState, action) { const { type, payload } = action; switch (type) { case GET_POSTS: return { ...state, posts: payload, loading: false }; case GET_POST: return { ...state, post: payload, loading: false }; case ADD_POST: return { ...state, posts: [payload, ...state.posts], loading: false }; case DELETE_POST: return { ...state, posts: state.posts.filter(post => post._id !== payload), loading: false }; case POST_ERROR: return { ...state, error: payload, loading: false }; case UPDATE_LIKES: return { ...state, posts: state.posts.map(post => post._id === payload.id ? { ...post, likes: payload.likes } : post ), loading: false }; case APPROVE_POST: return { ...state, posts: state.posts.map(post => post._id === payload.id ? { ...post, isApproved: payload.isApproved } : post ), loading: false }; case ADD_COMMENT: return { ...state, post: { ...state.post, comments: payload }, loading: false }; case REMOVE_COMMENT: return { ...state, post: { ...state.post, comments: state.post.comments.filter( comment => comment._id !== payload ) }, loading: false }; default: return state; } } ``` ``` case APPROVE_POST: return { ...state, posts: state.posts.map(post => post._id === payload.id ? { ...post, isApproved: payload.isApproved } : post ), loading: false }; ```
2021/04/23
[ "https://Stackoverflow.com/questions/67237574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15221448/" ]
The [`std::filesystem`](https://en.cppreference.com/w/cpp/filesystem/exists) library evolved out directly from the corresponding [Boost library](https://www.boost.org/doc/libs/1_75_0/libs/filesystem/doc/index.htm). As several functions in the Boost libraries (such as Boost ASIO) it offers [two interfaces](https://subscription.packtpub.com/book/application_development/9781782163268/1/ch01lvl1sec10/exceptions-versus-error-codes) that use a different type of error handling ``` bool exists(std::filesystem::path const& p); bool exists(std::filesystem::path const& p, std::error_code& ec) noexcept; ``` The first version uses *exceptions* (that have to be caught with a `try... catch` construct) while the second one does not but instead one has to evaluate the error codes. This **error code** might then contain **additional information about the precise reason of the failure** and help with debugging if the function returns `false`. > > The overload that does not take a std::error\_code& parameter throws > filesystem\_error on underlying OS API errors, constructed with p as > the first path argument and the OS error code as the error code > argument. The overload taking a std::error\_code& parameter sets it to > the OS API error code if an OS API call fails, and executes ec.clear() > if no errors occur. Any overload not marked noexcept may throw > std::bad\_alloc if memory allocation fails. > > > If the function returns **`true`** on the other hand it is **safe to assume that the path exists**. Error codes are more lightweight and in particular convenient for real-time performant code, numerical simulations and high-performance applications. In these cases one might turn off exception handling entirely for the compilation process just to have better performance. On the other hand error codes are often harder to maintain as for nested code - if a routine fails in some subfunction - you will have to pass the error code through several layers to where the error should be handled. Exceptions in this regard are easier maintainable.
From cppreference: > > The overload taking a `std::error_code&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. > > > No, you don't *need* to. It's better to only use it if the call fails. Any other time `ec` will not have any useful information in it. You can enforce this using `if-initializer` statements so the error code is only declared inside the smallest scope possible: ```cpp std::filesystem::path fpath{"fname"}; if(std::error_code ec{}; !std::filesystem::exists(fpath, ec)) { std::cerr << "File system returned the following for \"" << fpath.string() << "\":\nError: " << ec.value() << "\nMessage: " << ec.message(); } ```
43,477,483
I'm working with a lot of Option and I need to use pattern match/case almost every call to check if object is None or not. Is possible to write cleaner code when you use a lot of match cases? ``` def process(schema: Option[String], body: String, token:String, queueInfo: Map[String, String]) = { jsonSchemaService.findByDescriptionFromCache(schema) match { case Some(jsonSchema) => jsonSchema.schema match { case Some(s) => val ku = buildKinesisUtils(token, queueInfo) validateAndPublish(body, s, ku) case None => Future(Left(SchemaNotDefinedException(s"O Json schema [$schema] não possui um schema definido"))) } case None => Future(Left(SchemaNotFoundException("Não foi possível encontrar o JsonSchema informado"))) } } ```
2017/04/18
[ "https://Stackoverflow.com/questions/43477483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
use `.map` and `.flatMap` to avoid pattern matching on Options: ``` jsonSchemaService .findByDescriptionFromCache(schema) .map { jsonSchema => jsonSchema.schema.map { s => val ku = buildKinesisUtils(token, queueInfo) validateAndPublish(body, s, ku) }.getOrElse(Future(Left(SchemaNotDefinedException(s"O Json schema [$schema] não possui um schema definido")))) }.getOrElse(Future(Left(SchemaNotFoundException("Não foi possível encontrar o JsonSchema informado")))) ``` > > Note: it's a bit hard to produce a correct answer without knowing the signature of all methods used...but it should be somehow close to what you'd want > > >
What you're doing is actually a `fold`. ``` option.fold(noneCase)(s => someCase(s)) ```
43,477,483
I'm working with a lot of Option and I need to use pattern match/case almost every call to check if object is None or not. Is possible to write cleaner code when you use a lot of match cases? ``` def process(schema: Option[String], body: String, token:String, queueInfo: Map[String, String]) = { jsonSchemaService.findByDescriptionFromCache(schema) match { case Some(jsonSchema) => jsonSchema.schema match { case Some(s) => val ku = buildKinesisUtils(token, queueInfo) validateAndPublish(body, s, ku) case None => Future(Left(SchemaNotDefinedException(s"O Json schema [$schema] não possui um schema definido"))) } case None => Future(Left(SchemaNotFoundException("Não foi possível encontrar o JsonSchema informado"))) } } ```
2017/04/18
[ "https://Stackoverflow.com/questions/43477483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using pattern matching isn't really an idiomatic way of dealing with options. It's better to use the methods like map and flatmap and take advantage of for comprehensions to work with options. If you are checking everytime if an option is None, it's not much better than a null check. Since your methods are returning Options but you actually want Eithers you can convert these options to Eithers using the `toRight` method. ``` def process(schema: Option[String], body: String, token:String, queueInfo: Map[String, String]) = { val res = for { jsonSchema <- jsonSchemaService.findByDescriptionFromCache(schema).toRight(SchemaNotFoundException("Não foi possível encontrar o JsonSchema informado")).right s <- jsonSchema.schema.toRight(SchemaNotDefinedException(s"O Json schema [$schema] não possui um schema definido")).right } yield s res.fold(e => Future(Left(e)), s => validateAndPublish(body, s, buildKinesisUtils(token, queueInfo))) } ``` As of scala 2.12, Either is Right-Biased by default so the `.right` calls are no longer needed.
What you're doing is actually a `fold`. ``` option.fold(noneCase)(s => someCase(s)) ```
55,942,990
Semantic's Transition.Group example shown here <https://react.semantic-ui.com/modules/transition/#types-group> only animates the bottom most element. How would I change it so the top most element gets animated instead. If I press the add or subtract button in the example above the animation only applies to the last element in the list, how would I make it only animate the top most element. Or essentially make the selector opposite of default so it goes from top to bottom
2019/05/01
[ "https://Stackoverflow.com/questions/55942990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021627/" ]
If you read the sample code you realize all it does is to display a slice of the array based on the current length in the state. It appears to be appending / removing from the bottom because it's taking elements starting from the index 0. If you want to show it as if it's animating at the top, you just need to take the elements starting from the last element. For example, you can do this with `reverse`: ``` #8 state = { items: users.slice(0, 3).reverse() } #10 handleAdd = () => this.setState({ items: users.slice(0, this.state.items.length + 1).reverse() }) #12 handleRemove = () => this.setState({ items: this.state.items.slice(1) }) ```
An easier solution using `reverse` would be to just reverse the array when you map through it and create the children. ``` render() { const { items } = this.state; return (<div> {items.clone().reverse().map((item, index) => <div key={item}> { /* Stuff */ } </div>)} </div>); } ``` Yes, it would create a new array on each call to `render`, but the `key` prop identifies an element and prevents unnecessary re-renders of the child elements, because though it is a new array, object references will still be the same. But I would recommend to use a more identifiable and unique value for the `key` prop, e.g. IDs' or slugs. Also this way you wouldn't have to recalculate the array using `reverse` everywhere you use it, just at one point in your code.
2,464,661
I was wondering how can I factor this equation: $x^3-2x+1$ by grouping, I have this doubt because the solution is $(x-1)(x^2+x-1)$ and this seems clearly obtain by factoring by grouping but I have always thought that this method was possible only for 4 terms equations. So I tried to do my best and I factored it in this way: $$(x^3-2x)+1 \\ x(x^2-2)+1 $$ But I'm stuck here and I can't find the way to get to the right solution, I would really appreciate your attention and a clarification of this doubt of my mine. Thanks for your attention and have a good day!
2017/10/09
[ "https://math.stackexchange.com/questions/2464661", "https://math.stackexchange.com", "https://math.stackexchange.com/users/486458/" ]
Note that $$\frac{\sqrt{n+1}-\sqrt n}{n}=\frac{1}{n(\sqrt{n+1}+\sqrt n)}\le \frac{1}{2n^{3/2}}$$
$\sum\_{n=1}^{\infty}\frac{\sqrt{n+1}-\sqrt{n}}{n} = \sum\_{n=1}^{\infty}\frac{\sqrt{n+1}-\sqrt{n}}{n} \frac{\sqrt{n+1}+\sqrt{n}}{\sqrt{n+1}+\sqrt{n}} = \sum\_{n=1}^{\infty}\frac{1}{n(\sqrt{n+1}+\sqrt{n})} < \sum\_{n=1}^{\infty}\frac{1}{2n(\sqrt{n})} \\ and \\ \sum\_{n=1}^{\infty}\frac{1}{n(\sqrt{n+1}+\sqrt{n})} > \sum\_{n=1}^{\infty}\frac{1}{2n(\sqrt{n+1})} \\now \ use \ comparison \ test... $
2,464,661
I was wondering how can I factor this equation: $x^3-2x+1$ by grouping, I have this doubt because the solution is $(x-1)(x^2+x-1)$ and this seems clearly obtain by factoring by grouping but I have always thought that this method was possible only for 4 terms equations. So I tried to do my best and I factored it in this way: $$(x^3-2x)+1 \\ x(x^2-2)+1 $$ But I'm stuck here and I can't find the way to get to the right solution, I would really appreciate your attention and a clarification of this doubt of my mine. Thanks for your attention and have a good day!
2017/10/09
[ "https://math.stackexchange.com/questions/2464661", "https://math.stackexchange.com", "https://math.stackexchange.com/users/486458/" ]
Note that $$\frac{\sqrt{n+1}-\sqrt n}{n}=\frac{1}{n(\sqrt{n+1}+\sqrt n)}\le \frac{1}{2n^{3/2}}$$
More generally, consider $\sum\_{n=1}^{\infty}\frac{(n+1)^a-n^a}{n} $ where $1 >a > 0$. This problem is the case $a = \frac12$. Since $x^a$ is monotonic, and $(x^a)' = a x^{a-1} $, $(n+1)^a-n^a =\int\_n^{n+1} (x^a)' dx =\int\_n^{n+1} ax^{a-1} dx \lt a n^{a-1} $ so $\frac{(n+1)^a-n^a}{n} \lt \frac{a n^{a-1}}{n} = \frac{a }{n^{2-a}} $ and the sum of these converges.
2,464,661
I was wondering how can I factor this equation: $x^3-2x+1$ by grouping, I have this doubt because the solution is $(x-1)(x^2+x-1)$ and this seems clearly obtain by factoring by grouping but I have always thought that this method was possible only for 4 terms equations. So I tried to do my best and I factored it in this way: $$(x^3-2x)+1 \\ x(x^2-2)+1 $$ But I'm stuck here and I can't find the way to get to the right solution, I would really appreciate your attention and a clarification of this doubt of my mine. Thanks for your attention and have a good day!
2017/10/09
[ "https://math.stackexchange.com/questions/2464661", "https://math.stackexchange.com", "https://math.stackexchange.com/users/486458/" ]
$\sum\_{n=1}^{\infty}\frac{\sqrt{n+1}-\sqrt{n}}{n} = \sum\_{n=1}^{\infty}\frac{\sqrt{n+1}-\sqrt{n}}{n} \frac{\sqrt{n+1}+\sqrt{n}}{\sqrt{n+1}+\sqrt{n}} = \sum\_{n=1}^{\infty}\frac{1}{n(\sqrt{n+1}+\sqrt{n})} < \sum\_{n=1}^{\infty}\frac{1}{2n(\sqrt{n})} \\ and \\ \sum\_{n=1}^{\infty}\frac{1}{n(\sqrt{n+1}+\sqrt{n})} > \sum\_{n=1}^{\infty}\frac{1}{2n(\sqrt{n+1})} \\now \ use \ comparison \ test... $
More generally, consider $\sum\_{n=1}^{\infty}\frac{(n+1)^a-n^a}{n} $ where $1 >a > 0$. This problem is the case $a = \frac12$. Since $x^a$ is monotonic, and $(x^a)' = a x^{a-1} $, $(n+1)^a-n^a =\int\_n^{n+1} (x^a)' dx =\int\_n^{n+1} ax^{a-1} dx \lt a n^{a-1} $ so $\frac{(n+1)^a-n^a}{n} \lt \frac{a n^{a-1}}{n} = \frac{a }{n^{2-a}} $ and the sum of these converges.
29,550,723
I have the use case, where I need to allow for processing an arbitrary array of strings, by an arbitrary regex, which is created either by a regex literal, or through the `new RegExp()` constructor. It all works fine, until the global `g` flag is used with capturing groups. I read a few answers on SO, and the proposed solution is to use regex.exec(string) in a while loop, e.g. [How do you access the matched groups in a JavaScript regular expression?](https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression), [JavaScript regular expressions and sub-matches](https://stackoverflow.com/questions/844001/javascript-regex-and-submatches) I also talked about it on IRC, and was advised against the implementation all together: > > but there's regexes that will segfault your engine, unless you're > using spidermonkey. > > > So here is a corner case, try pasting it into a fiddle or plunker, or even the console, it just breaks: ```js var regexString = '([^-]*)'; var flags = 'ig'; var regex = new RegExp(regexString, flags); var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp']; var result = []; arr.forEach(function(item) { var match; var inter = []; while (match = regex.exec(item)) { inter.push(match[0]); } }); console.log(result); ``` I did tried it on regex101.com <https://regex101.com/r/xG0cL4/1> It breaks even if I do it without the quantifier, i.e. `/([^-])/g` <https://regex101.com/r/yT7sQ2/1> My question: what is the `(correct|safe)` way to process arbitrary regexes against arbitrary strings?
2015/04/09
[ "https://Stackoverflow.com/questions/29550723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2445063/" ]
It's not working because when '-' is reached, exec() fails to match the '-' character, but does match 0 characters (because of \*), so it doesn't skip it, and thus it gets stuck. If you use `-|([^-]*)`, then it will skip the '-' character. You will need to then check the 'match.index' property to see if you've reach the end. Also, you should be adding `match[1]` not `match[0]` if your intent is to save the matched text. This works: ``` var regexString = '-|([^-]*)'; // or better yet: '([^-]+)' will work also var flags = 'ig'; var regex = new RegExp(regexString, flags); var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp']; var result = []; arr.forEach(function(item) { var match; var inter = []; while (match = regex.exec(item)) { if (match.index >= item.length) break; else if (match[1] !== void 0) inter.push(match[1]); } }); console.log(result); ``` but why not use 'match()' instead? ``` var regexString = '[^-]+'; var flags = 'gi'; var regex = new RegExp(regexString, flags); var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp']; var result = []; arr.forEach(function(item) { var inter = item.match(regex); }); console.log(result); ```
The `match` object has an `index` property that contains the position of the current match. If that stays the same between two calls in the loop, it means you're stuck. ```js var regexString = '([^-]*)'; var flags = 'ig'; var regex = new RegExp(regexString, flags); var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp']; var result = []; arr.forEach(function(item) { var match; var inter = []; var lastIndex = -1; while (match = regex.exec(item)) { if (match.index == lastIndex) { break; } lastIndex = match.index; inter.push(match[0]); } result.push(inter); }); console.log(result); ```
29,550,723
I have the use case, where I need to allow for processing an arbitrary array of strings, by an arbitrary regex, which is created either by a regex literal, or through the `new RegExp()` constructor. It all works fine, until the global `g` flag is used with capturing groups. I read a few answers on SO, and the proposed solution is to use regex.exec(string) in a while loop, e.g. [How do you access the matched groups in a JavaScript regular expression?](https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression), [JavaScript regular expressions and sub-matches](https://stackoverflow.com/questions/844001/javascript-regex-and-submatches) I also talked about it on IRC, and was advised against the implementation all together: > > but there's regexes that will segfault your engine, unless you're > using spidermonkey. > > > So here is a corner case, try pasting it into a fiddle or plunker, or even the console, it just breaks: ```js var regexString = '([^-]*)'; var flags = 'ig'; var regex = new RegExp(regexString, flags); var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp']; var result = []; arr.forEach(function(item) { var match; var inter = []; while (match = regex.exec(item)) { inter.push(match[0]); } }); console.log(result); ``` I did tried it on regex101.com <https://regex101.com/r/xG0cL4/1> It breaks even if I do it without the quantifier, i.e. `/([^-])/g` <https://regex101.com/r/yT7sQ2/1> My question: what is the `(correct|safe)` way to process arbitrary regexes against arbitrary strings?
2015/04/09
[ "https://Stackoverflow.com/questions/29550723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2445063/" ]
It's not working because when '-' is reached, exec() fails to match the '-' character, but does match 0 characters (because of \*), so it doesn't skip it, and thus it gets stuck. If you use `-|([^-]*)`, then it will skip the '-' character. You will need to then check the 'match.index' property to see if you've reach the end. Also, you should be adding `match[1]` not `match[0]` if your intent is to save the matched text. This works: ``` var regexString = '-|([^-]*)'; // or better yet: '([^-]+)' will work also var flags = 'ig'; var regex = new RegExp(regexString, flags); var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp']; var result = []; arr.forEach(function(item) { var match; var inter = []; while (match = regex.exec(item)) { if (match.index >= item.length) break; else if (match[1] !== void 0) inter.push(match[1]); } }); console.log(result); ``` but why not use 'match()' instead? ``` var regexString = '[^-]+'; var flags = 'gi'; var regex = new RegExp(regexString, flags); var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp']; var result = []; arr.forEach(function(item) { var inter = item.match(regex); }); console.log(result); ```
Why it's crashing: an infinite loop was created by using a RegExp object with a global flag and [`exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) in a loop with a zero-width match. The loop hits the first '-' but doesn't match that character because of the negated character class. It then reverts back to the zero-length match and so doesn't advance the index value for `exec`. This means on the next loop it starts back at the same spot and does the exact same thing...infinitely. That said, it's hard to tell what exactly you want but why not try [`match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)? It looks like you only care about the matching string so `exec` seems to be a bit of overkill. If the desired output is a one-to-one array of results with the input array: ``` function foo(regexp, strings) { return strings.reduce(function(matches, str) { matches.push(str.match(regexp)); return matches; }, []); } foo(/([^-]+)/ig, arr); // outputs: [["some","property","image.png"],["another","prop","video.png"],["y","no","work.bmp"]] foo(new RegExp('([^-]+)', 'ig'), arr); // outputs: [["some","property","image.png"],["another","prop","video.png"],["y","no","work.bmp"]] ``` Even with the zero-width matching it won't go into an infinite loop: ``` foo(/([^-]*)/ig, arr)); // outputs: [["some","","property","","image.png",""],["another","","prop","","video.png",""],["y","","no","","work.bmp",""]] ``` If the desired output really is one array of all the matches: ``` function foo(regexp, strings) { return strings.reduce(function(matches, str) { return matches.concat(str.match(regexp)); }, []); } foo(/([^-]+)/ig, arr); // outputs: ["some","property","image.png","another","prop","video.png","y","no","work.bmp"] foo(new RegExp('([^-]+)', 'ig'), arr); // outputs: ["some","property","image.png","another","prop","video.png","y","no","work.bmp"] foo(/([^-]*)/ig, arr)); // outputs: ["some","","property","","image.png","","another","","prop","","video.png","","y","","no","","work.bmp",""] ```
42,485,605
I was programming in Android Studio, on MAC OS X macOS Sierra. I was debugging code on one emulator, then I started next emulator with different phone. Then accidentally laptop restarted (with the grey screen <https://i.kinja-img.com/gawker-media/image/upload/s--HPvl05ih--/c_scale,f_auto,fl_progressive,q_80,w_800/18mfougmh04injpg.jpg>). After boot everything come back, Android Studio too. But I can't debug my apps. I have ``` Error:java.lang.NullPointerException (no error message) ``` This happening everytime I try to run my app. It is on my company project, from git. I tried different versions of code. I tried also (with chronology): * reinstall Android Studio * reinstall SDK, Virtual Devices * reinstall Android Studio after completly delete it from Mac, using terminal ([How to completely uninstall Android Studio?](https://stackoverflow.com/questions/17625622/how-to-completely-uninstall-android-studio)) * reinstall Java (uninstall with the tip from Java webpage (<https://www.java.com/en/download/help/mac_uninstall_java.xml>) I don't know what I can do next besides reinstalling OS. Thanks
2017/02/27
[ "https://Stackoverflow.com/questions/42485605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6314640/" ]
Okay. After that post I also tried cleaning cache, logs and again reinstall Java JDK. Nothing helped. Unfortunately the only solution which helped - format and reinstall system.
Try File -> Invalidate caches / Restart... in android studio.
42,485,605
I was programming in Android Studio, on MAC OS X macOS Sierra. I was debugging code on one emulator, then I started next emulator with different phone. Then accidentally laptop restarted (with the grey screen <https://i.kinja-img.com/gawker-media/image/upload/s--HPvl05ih--/c_scale,f_auto,fl_progressive,q_80,w_800/18mfougmh04injpg.jpg>). After boot everything come back, Android Studio too. But I can't debug my apps. I have ``` Error:java.lang.NullPointerException (no error message) ``` This happening everytime I try to run my app. It is on my company project, from git. I tried different versions of code. I tried also (with chronology): * reinstall Android Studio * reinstall SDK, Virtual Devices * reinstall Android Studio after completly delete it from Mac, using terminal ([How to completely uninstall Android Studio?](https://stackoverflow.com/questions/17625622/how-to-completely-uninstall-android-studio)) * reinstall Java (uninstall with the tip from Java webpage (<https://www.java.com/en/download/help/mac_uninstall_java.xml>) I don't know what I can do next besides reinstalling OS. Thanks
2017/02/27
[ "https://Stackoverflow.com/questions/42485605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6314640/" ]
Okay. After that post I also tried cleaning cache, logs and again reinstall Java JDK. Nothing helped. Unfortunately the only solution which helped - format and reinstall system.
you must remove ".gradle" folder into your root project and restart your android studio.
35,934,583
The title says it all. Just to irritate DRY purists, I'll say it again. Is it possible to get a list of instances my application is running on via **gcloud**?
2016/03/11
[ "https://Stackoverflow.com/questions/35934583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339838/" ]
App Engine can mean traditional App Engine or Managed VMs, depending on the context. There is only one App Engine app per project, but you can have multiple modules (although only one of those module will serve web traffic, the rest are backend only) and multiple versions of each module. As pgiecek mention, ``` gcloud preview app modules list ``` will show all the modules. What you might be looking for is all your App Engine versions, for which you will still have to use appcfg ``` appcfg.py -A <your-project-id> [-M <module>] list_versions ``` If you are using Managed VMs, it will spin up your app on GCE instances, in which case ``` gcloud compute instances list ``` does in fact show your App Engine (MVM) instances.
It seems that currently it is not possible. At the moment gcloud tool supports App Engine (via Preview CLI command groups) but provides only limited number of operations and furthermore they are in BETA. You can check documentation [here](https://cloud.google.com/sdk/gcloud/reference/preview/app/). You can only list your existing deployed modules and versions as follows. ``` gcloud preview app modules list ```
35,934,583
The title says it all. Just to irritate DRY purists, I'll say it again. Is it possible to get a list of instances my application is running on via **gcloud**?
2016/03/11
[ "https://Stackoverflow.com/questions/35934583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339838/" ]
In 2019, You can check the newest document : [gcloud app services list - list your existing services](https://cloud.google.com/sdk/gcloud/reference/app/services/list) The newest command is: ``` gcloud app services list ``` The result will be something like this. ``` SERVICE NUM_VERSIONS default 7 ```
It seems that currently it is not possible. At the moment gcloud tool supports App Engine (via Preview CLI command groups) but provides only limited number of operations and furthermore they are in BETA. You can check documentation [here](https://cloud.google.com/sdk/gcloud/reference/preview/app/). You can only list your existing deployed modules and versions as follows. ``` gcloud preview app modules list ```
35,934,583
The title says it all. Just to irritate DRY purists, I'll say it again. Is it possible to get a list of instances my application is running on via **gcloud**?
2016/03/11
[ "https://Stackoverflow.com/questions/35934583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339838/" ]
App Engine can mean traditional App Engine or Managed VMs, depending on the context. There is only one App Engine app per project, but you can have multiple modules (although only one of those module will serve web traffic, the rest are backend only) and multiple versions of each module. As pgiecek mention, ``` gcloud preview app modules list ``` will show all the modules. What you might be looking for is all your App Engine versions, for which you will still have to use appcfg ``` appcfg.py -A <your-project-id> [-M <module>] list_versions ``` If you are using Managed VMs, it will spin up your app on GCE instances, in which case ``` gcloud compute instances list ``` does in fact show your App Engine (MVM) instances.
In 2019, You can check the newest document : [gcloud app services list - list your existing services](https://cloud.google.com/sdk/gcloud/reference/app/services/list) The newest command is: ``` gcloud app services list ``` The result will be something like this. ``` SERVICE NUM_VERSIONS default 7 ```
35,934,583
The title says it all. Just to irritate DRY purists, I'll say it again. Is it possible to get a list of instances my application is running on via **gcloud**?
2016/03/11
[ "https://Stackoverflow.com/questions/35934583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339838/" ]
App Engine can mean traditional App Engine or Managed VMs, depending on the context. There is only one App Engine app per project, but you can have multiple modules (although only one of those module will serve web traffic, the rest are backend only) and multiple versions of each module. As pgiecek mention, ``` gcloud preview app modules list ``` will show all the modules. What you might be looking for is all your App Engine versions, for which you will still have to use appcfg ``` appcfg.py -A <your-project-id> [-M <module>] list_versions ``` If you are using Managed VMs, it will spin up your app on GCE instances, in which case ``` gcloud compute instances list ``` does in fact show your App Engine (MVM) instances.
As of Sep 2019 (Google Cloud SDK 237.0.0): `gcloud app instances list` [![enter image description here](https://i.stack.imgur.com/J9CAH.png)](https://i.stack.imgur.com/J9CAH.png)
35,934,583
The title says it all. Just to irritate DRY purists, I'll say it again. Is it possible to get a list of instances my application is running on via **gcloud**?
2016/03/11
[ "https://Stackoverflow.com/questions/35934583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339838/" ]
In 2019, You can check the newest document : [gcloud app services list - list your existing services](https://cloud.google.com/sdk/gcloud/reference/app/services/list) The newest command is: ``` gcloud app services list ``` The result will be something like this. ``` SERVICE NUM_VERSIONS default 7 ```
As of Sep 2019 (Google Cloud SDK 237.0.0): `gcloud app instances list` [![enter image description here](https://i.stack.imgur.com/J9CAH.png)](https://i.stack.imgur.com/J9CAH.png)
124,697
I was confused about the difference between a commit operation and a checkpoint. I referred to some of the articles like [This Article](https://community.oracle.com/thread/463791?start=0&tstart=0) But they are advanced for my understanding. I mean both appear to be same i.e. saving data like a "Save" action. If we rollback, we can rollback only to the most recent checkpoint/commit. Am I right in my statements? Can someone explain?
2015/12/28
[ "https://dba.stackexchange.com/questions/124697", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/34059/" ]
A [commit](https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_4010.htm) is a user initiated action that tells the database (Oracle in this case) that the transaction is completed and that the changes may be committed and any locks/resources released. Normally the changes are committed to in memory data buffers and to the redo log buffer. A checkpoint though is a database initiated action that writes all of the data to the actual physical disk file based on the changes recorded in the redo log buffer. Some good articles can be found [here](http://oracleinaction.com/checkpoints/) and [here](http://www.orafaq.com/wiki/Checkpoint).
Commit: its an **action performed by user** to let database instance know that transaction is completed and correct, and it can not be rolled back. Checkpoint: after performing a commit, instance will perform action to change system change number (SCN) that already committed to store it (data ) in a block(s) and datafile(s), and SCN in control file(s). and it can be used in rollback. Note: checkpoint may happened anytime
124,697
I was confused about the difference between a commit operation and a checkpoint. I referred to some of the articles like [This Article](https://community.oracle.com/thread/463791?start=0&tstart=0) But they are advanced for my understanding. I mean both appear to be same i.e. saving data like a "Save" action. If we rollback, we can rollback only to the most recent checkpoint/commit. Am I right in my statements? Can someone explain?
2015/12/28
[ "https://dba.stackexchange.com/questions/124697", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/34059/" ]
Commit: its an **action performed by user** to let database instance know that transaction is completed and correct, and it can not be rolled back. Checkpoint: after performing a commit, instance will perform action to change system change number (SCN) that already committed to store it (data ) in a block(s) and datafile(s), and SCN in control file(s). and it can be used in rollback. Note: checkpoint may happened anytime
To complete some of the previous answers: A commit will end the current transaction in the current section. It will guarantee the consistency of the data that was "touched" during the transaction. A checkpoint writes all commited changes to disk up to some SCN that willl be kept in the control file and datafile headers. It guarantees the consistency of the database. --- **EDIT 1** As some of the comments point out that the concepts aren't completely clear I will provide some more information here. We have 3 major structures involved in the **commit** and **checkpoint** concepts. * Memory (Database Buffer Cache & Redo Log Buffer) * Redo Logs (Redo log files) * Database (Datafiles) So changes are made to blocks kept in the Database Buffer Cache (DBCache). Once commited, the changes are pushed to the Redo Log Buffer (RLB) which is dumped on a regular basis to the Redo Log Files (RLF) and, eventually to the database storage files (DF). Also on a regular basis and not completely unrelated to commit, the checkpoint process dumps the dirty blocks from the DBCache to permanent storage DF. During the **checkpoint** process the SCN associated with the latest DB block written to storage is written on the DF headers and the control file. That will be from that moment on the latest consistent estate of the database.
124,697
I was confused about the difference between a commit operation and a checkpoint. I referred to some of the articles like [This Article](https://community.oracle.com/thread/463791?start=0&tstart=0) But they are advanced for my understanding. I mean both appear to be same i.e. saving data like a "Save" action. If we rollback, we can rollback only to the most recent checkpoint/commit. Am I right in my statements? Can someone explain?
2015/12/28
[ "https://dba.stackexchange.com/questions/124697", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/34059/" ]
A [commit](https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_4010.htm) is a user initiated action that tells the database (Oracle in this case) that the transaction is completed and that the changes may be committed and any locks/resources released. Normally the changes are committed to in memory data buffers and to the redo log buffer. A checkpoint though is a database initiated action that writes all of the data to the actual physical disk file based on the changes recorded in the redo log buffer. Some good articles can be found [here](http://oracleinaction.com/checkpoints/) and [here](http://www.orafaq.com/wiki/Checkpoint).
To complete some of the previous answers: A commit will end the current transaction in the current section. It will guarantee the consistency of the data that was "touched" during the transaction. A checkpoint writes all commited changes to disk up to some SCN that willl be kept in the control file and datafile headers. It guarantees the consistency of the database. --- **EDIT 1** As some of the comments point out that the concepts aren't completely clear I will provide some more information here. We have 3 major structures involved in the **commit** and **checkpoint** concepts. * Memory (Database Buffer Cache & Redo Log Buffer) * Redo Logs (Redo log files) * Database (Datafiles) So changes are made to blocks kept in the Database Buffer Cache (DBCache). Once commited, the changes are pushed to the Redo Log Buffer (RLB) which is dumped on a regular basis to the Redo Log Files (RLF) and, eventually to the database storage files (DF). Also on a regular basis and not completely unrelated to commit, the checkpoint process dumps the dirty blocks from the DBCache to permanent storage DF. During the **checkpoint** process the SCN associated with the latest DB block written to storage is written on the DF headers and the control file. That will be from that moment on the latest consistent estate of the database.
45,179
I understand how those tree's work separately, but i can't imagine how to put it in one structure. From ethereum's wiki: > > All substantial quantities of data in Ethereum are stored in a data structure known as the Patricia Merkle tree, a tree structure where each node in the tree is the hash of its children. Each set of key/value pairs maps to a unique root hash, and only a small subset of nodes is needed to prove that a particular key/value combination is in the tree corresponding to a particular root hash. > > > Also, inspecting [this](https://i.stack.imgur.com/YZGxe.) diagram, can't see where each node is a hash of it's childs. From official specification, can't understand below part. What means <> in current example? ``` <64 6f> : 'verb' <64 6f 67> : 'puppy' <64 6f 67 65> : 'coin' <68 6f 72 73 65> : 'stallion' Now, we build such a trie with the following key/value pairs in the underlying DB: rootHash: [ <16>, hashA ] hashA: [ <>, <>, <>, <>, hashB, <>, <>, <>, hashC, <>, <>, <>, <>, <>, <>, <>, <> ] hashC: [ <20 6f 72 73 65>, 'stallion' ] hashB: [ <00 6f>, hashD ] hashD: [ <>, <>, <>, <>, <>, <>, hashE, <>, <>, <>, <>, <>, <>, <>, <>, <>, 'verb' ] hashE: [ <17>, hashF ] hashF: [ <>, <>, <>, <>, <>, <>, hashG, <>, <>, <>, <>, <>, <>, <>, <>, <>, 'puppy' ] hashG: [ <35>, 'coin' ] ``` **EDIT:** Ok so i understood that hashA empty brackets '<>' is empty slots in branch node.
2018/04/09
[ "https://ethereum.stackexchange.com/questions/45179", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/37559/" ]
In Ethereum, the data structure is a Modified Merkle Patricia Trie **Merkle**: =========== The merkle part of the tree means that the hash of the children used by the parent to ensure the entire tree is cryptographically proven to be immutable. In the above example, 1. the rootHash points to hashA 2. hashA, in turn, points to hashB & hashC **Patricia Trie** : =================== These are [radix trees where r=2, as noted here](https://en.wikipedia.org/wiki/Radix_tree#PATRICIA) [![enter image description here](https://i.stack.imgur.com/ZFS2B.png)](https://i.stack.imgur.com/ZFS2B.png) In a Patricia ("Practical Algorithm To Retrieve Information Coded In Alphanumeric") Trie (NOTE: "trie" comes from re-***trie***-val: * edges contain the content * nodes indicate branching, or leaf (i.e. trie termination). **Modified \_\_\_\_** : ======================= In the Ethereum version of the data structure, the nodes in the tree are either: * a combination of a Patricia edge & and a leaf node (such as hashC above) * Patricia branching node (such as hashA above) * a Patricia edge (such as hashB above)
All nodes from modified patricia tree are stored in flat key value LevelDB like so sha3(rlp(node)). Then extension node store hash from levelDB in value as reference to other node. Very good explanation [here](https://easythereentropy.wordpress.com/2014/06/04/understanding-the-ethereum-trie/)
20,668,496
I am following [this](http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/) tutorial. Here are all my related files: activity\_main.xml ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> ``` MainActivity.java ``` package org.barisakkurt.googlemapsv2; import android.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.Toast; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; public class MainActivity extends FragmentActivity { // Google Map private GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // Loading map initilizeMap(); } catch (Exception e) { } } /** * function to load map. If map is not created it will create it for you * */ private void initilizeMap() { if (googleMap == null) { googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } } } @Override protected void onResume() { super.onResume(); initilizeMap(); } } ``` AndroidManifest.xml ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.barisakkurt.googlemapsv2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Required to show current location --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="org.barisakkurt.googlemapsv2.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyAC7y4bP-MjeJljm6Fr9Og1FKxNe9ZiFkY" /> </application> </manifest> ``` I completed the tutorial until the title *Placing a Marker*. However I am getting the following error. ``` Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value. Expected 4030500 but found 0. You must have the following declaration within the <application> element: <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ``` If I write my manifest file the following lines: ``` <meta-data android:name="com.google.android.gms.version" android:value="4030500" /> ``` this time I am getting this error: ``` Caused by: java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml ``` Is android kidding me? Why is that code crashes? What do i have to do to run that damn simple code? Why it is working in the tutorial and not on my machine. It annoyed me. (By the way, I am using Windows 7 with a real device Nexus 7 and I copied a version.xml tried also the following meta-data ``` <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ``` and again didn't work. Lastly, of course I searched SO and google looked at the popular tutorials) Please help me.
2013/12/18
[ "https://Stackoverflow.com/questions/20668496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1662800/" ]
You need to have two `meta-data` fields. One is required for google play services in general, the second one on top for using maps. Example snippet from the sample application you should have in `[android-sdk]/extras/google/google_play_services/samples/maps/AndroidManifest.xml` ``` <application android:icon="@drawable/ic_launcher" android:label="@string/demo_title" android:hardwareAccelerated="true"> <!-- ** You need to replace the key below with your own key. ** The example key below will not be accepted because it is not linked to the certificate which you will use to sign this application. See: https://developers.google.com/maps/documentation/android/start for instructions on how to get your own key. --> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCvGBr5in13NK2yYBR7lhXTtnxj3mrXQy4" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ```
you need ``` <application..> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="KEY" /> ... </application> ```
20,668,496
I am following [this](http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/) tutorial. Here are all my related files: activity\_main.xml ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> ``` MainActivity.java ``` package org.barisakkurt.googlemapsv2; import android.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.Toast; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; public class MainActivity extends FragmentActivity { // Google Map private GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // Loading map initilizeMap(); } catch (Exception e) { } } /** * function to load map. If map is not created it will create it for you * */ private void initilizeMap() { if (googleMap == null) { googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } } } @Override protected void onResume() { super.onResume(); initilizeMap(); } } ``` AndroidManifest.xml ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.barisakkurt.googlemapsv2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Required to show current location --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="org.barisakkurt.googlemapsv2.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyAC7y4bP-MjeJljm6Fr9Og1FKxNe9ZiFkY" /> </application> </manifest> ``` I completed the tutorial until the title *Placing a Marker*. However I am getting the following error. ``` Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value. Expected 4030500 but found 0. You must have the following declaration within the <application> element: <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ``` If I write my manifest file the following lines: ``` <meta-data android:name="com.google.android.gms.version" android:value="4030500" /> ``` this time I am getting this error: ``` Caused by: java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml ``` Is android kidding me? Why is that code crashes? What do i have to do to run that damn simple code? Why it is working in the tutorial and not on my machine. It annoyed me. (By the way, I am using Windows 7 with a real device Nexus 7 and I copied a version.xml tried also the following meta-data ``` <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ``` and again didn't work. Lastly, of course I searched SO and google looked at the popular tutorials) Please help me.
2013/12/18
[ "https://Stackoverflow.com/questions/20668496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1662800/" ]
you need ``` <application..> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="KEY" /> ... </application> ```
You need do give External Storage permission with both meta-data: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCm5xJy0AwN4TfXM6ccpfj2GhqZneFCyiM" /> </application> ```
20,668,496
I am following [this](http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/) tutorial. Here are all my related files: activity\_main.xml ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> ``` MainActivity.java ``` package org.barisakkurt.googlemapsv2; import android.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.Toast; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; public class MainActivity extends FragmentActivity { // Google Map private GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // Loading map initilizeMap(); } catch (Exception e) { } } /** * function to load map. If map is not created it will create it for you * */ private void initilizeMap() { if (googleMap == null) { googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } } } @Override protected void onResume() { super.onResume(); initilizeMap(); } } ``` AndroidManifest.xml ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.barisakkurt.googlemapsv2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Required to show current location --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="org.barisakkurt.googlemapsv2.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyAC7y4bP-MjeJljm6Fr9Og1FKxNe9ZiFkY" /> </application> </manifest> ``` I completed the tutorial until the title *Placing a Marker*. However I am getting the following error. ``` Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value. Expected 4030500 but found 0. You must have the following declaration within the <application> element: <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ``` If I write my manifest file the following lines: ``` <meta-data android:name="com.google.android.gms.version" android:value="4030500" /> ``` this time I am getting this error: ``` Caused by: java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml ``` Is android kidding me? Why is that code crashes? What do i have to do to run that damn simple code? Why it is working in the tutorial and not on my machine. It annoyed me. (By the way, I am using Windows 7 with a real device Nexus 7 and I copied a version.xml tried also the following meta-data ``` <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ``` and again didn't work. Lastly, of course I searched SO and google looked at the popular tutorials) Please help me.
2013/12/18
[ "https://Stackoverflow.com/questions/20668496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1662800/" ]
You need to have two `meta-data` fields. One is required for google play services in general, the second one on top for using maps. Example snippet from the sample application you should have in `[android-sdk]/extras/google/google_play_services/samples/maps/AndroidManifest.xml` ``` <application android:icon="@drawable/ic_launcher" android:label="@string/demo_title" android:hardwareAccelerated="true"> <!-- ** You need to replace the key below with your own key. ** The example key below will not be accepted because it is not linked to the certificate which you will use to sign this application. See: https://developers.google.com/maps/documentation/android/start for instructions on how to get your own key. --> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCvGBr5in13NK2yYBR7lhXTtnxj3mrXQy4" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> ```
You need do give External Storage permission with both meta-data: ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCm5xJy0AwN4TfXM6ccpfj2GhqZneFCyiM" /> </application> ```
72,291,901
I am trying to change a column's datatype. The column of type VARCHAR has thousands of GUID values like look those shown below: ``` b1f4ff32-48d4-494e-a32c-044014cea9 bc5a1158-b310-49ff-a1f3-09d4f8707f69 4b7ebc9d-9fa1-42d9-811e-0b7b4b7297a fc7ba848-98ea-4bc6-add7-11f0ee9c6917a21 485741ff-2ab2-4705-91b3-136389948b7c ``` I need to convert the column type to `unqiqueidentifier` using the script below. Can I do that safely without corrupting the column data? ``` alter table MyTable alter column guidColumn uniqueidentifier not null ```
2022/05/18
[ "https://Stackoverflow.com/questions/72291901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19026985/" ]
If you change the data type SQL Server will first check if *all* the values in the columns can be implicitly converted to the new data type; if they cannot then the `ALTER` will fail. If they can, then they will be implicitly converted and the `ALTER` will be successful (assuming no dependencies of course). For a `uniqueidentifier` then either it's a valid value or it's not, so either the data will all convert or the `ALTER` won't take place. For something like a date and time data type, however, you could very easily end up with incorrect data if the data is stored in an ambiguous format like `dd/MM/yyyy`. This could mean a value like `'12/05/2022'` ends up being stored as the `date` value `2022-12-05` rather than `2022-05-12`. For such scenarios you would therefore want to `UPDATE` the data to an unambiguous format first, and then `ALTER` the data type of the column.
The **uniqueidentifier** type is considered a character type for the purposes of conversion from a character expression, and therefore is subject to the truncation rules for converting to a character type. **Also there are limitations, uniqueidentifier type is limited to 36 char** So if you decide to truncate the table like in this example: ``` DECLARE @ID NVARCHAR(max) = N'0E984725-C51C-4BF4-9960-E1C80E27ABA0wrong'; SELECT @ID, CONVERT(uniqueidentifier, @ID) AS TruncatedValue; ``` This will be the result: | String | Truncated Value | | --- | --- | | 0E984725-C51C-4BF4-9960-E1C80E27ABA0wrong | 0E984725-C51C-4BF4-9960-E1C80E27ABA0 | So, if your string is more or less than 36 it will not truncate correctly. For more information check Microsoft documentation: <https://learn.microsoft.com/en-us/sql/t-sql/data-types/uniqueidentifier-transact-sql?view=sql-server-ver15>