std::conditional in nested template class

Question: I'm trying to implement a RingBuffer in the style of the STL. This means I'm also implementing an iterator for it that has to work as either const or non-const. This is just the iterator part:
#include <iterator>
#include <type_traits>

template <typename T> class RingBuffer {
public:
    class Iterator;
    // actual RingBuffer implementation here
};

template <typename T, bool is_const=false>
class RingBuffer<T>::Iterator {
public:
    typedef std::ptrdiff_t difference_type;
    typedef T value_type;
    typedef typename std::conditional<is_const, const value_type*, value_type*>::type pointer ;
    typedef typename std::conditional<is_const, const value_type&, value_type&>::type reference ;
    typedef std::random_access_iterator_tag iterator_category;

    // a bunch of functions here
    ...
};

GCC 4.8.0 gives errors for every line where I try to access an iterator, saying something like
no type named 'type' in 'struct std::conditional<is_const, const int*, int*>'

Substituting int for the type that RingBuffer<T> has been instantiated with. I don't get it. is_const has a default value. Why doesn't this work? And why doesn't GCC subsitute in false in the error message, like it substituted int for value_type?
The solution is probably obvious but all the googling in the world didn't get me anywhere. Templates are still kind of confusing to me.
Answer: If you want Iterator to also be templated by bool is_const, you have to declare it as such:
template <typename T> class RingBuffer {
public:
    template <bool is_const = false>
    class Iterator;
    // actual RingBuffer implementation here
};

template <typename T>
template <bool is_const>
class RingBuffer<T>::Iterator {
public:
    typedef std::ptrdiff_t difference_type;
    typedef T value_type;
    typedef typename std::conditional<is_const, const value_type*, value_type*>::type pointer ;
    typedef typename std::conditional<is_const, const value_type&, value_type&>::type reference ;
    typedef std::random_access_iterator_tag iterator_category;

    // a bunch of functions here
    ...
};

Explanation: Iterator is a member of a class template, but in your original code, Iterator itself was a non-template class. RingBuffer had one template parameter, T; Iterator was a non-template class; there just wasn't anywhere for is_const to appear. It will become clearer if we remove the outer class for a moment:
class Foo;

template <bool b = false>
class Foo
{
  // something
};

I believe it's obvious the above wouldn't work.
Comment: @sseeland Added explanation. As for why `RingBuffer::Iterator` doesn't work - it has to be `RingBuffer::Iterator<>`. Unlike for function templates, there is no deduction mechanism for class templates, which also means you always have to specify `<>` (even if empty).
Comment: I can't claim to understand _why_, but that works. Can you explain what I did wrong and what your version does right? Also: I can't seem to use `RingBuffer::Iterator` (without the is_const argument) even though it has a default value. Why is that? Can that be changed so that I only have to specify is_const when I actually want to deviate from the default?


Delete workflows / individual states

Question: Strangly I seem not to be able to delete an existing workflow as a whole, nor a state within a workflow. The admin user has all the necessary permission. No content type is assigned with the workflow. What do I not see?
Comment: Are you able to delete them if you log in as user 1?  (if you have linux command line access and drush installed you can get a login link with `sudo drush uli`). I ask because if you can, then the 'admin' user is not user 1 and does not have all of the necessary permissions meaning you would need to try some more of them.
Comment: Update: The only way I could solve this was to remove the entries from the database. This must have been a strange fluke, because after creating new workflows I am able to delete them.
Answer: In Drupal 8 (at least), there is a "Clean up" tab in the main configuration screen of the module (/admin/config/workflow/workflow), where you can delete inactive states.
In my case, I suddenly stopped seeing the "Actions" buttons, so the only thing I could do was activate/disactivate the states.
That may solve someone's problem...It solved mine
Comment: I don't see this in D8 (v8.8.8)
Answer: I was just having the same issue. But I have just noticed that deleting a state from a workflow is not done in just one step.
First, you have to disable the state.
Second, on the main page of the workflow module, click on "Clean up workflow" and you will see that you can delete the inactive workflows there.
Answer: If you want to delete a workflow at all it must not be used in any node. So delete all fields pointing to this workflow first.
But I confirm: I cannot delete single states inside of a workflow at all.

Delete workflows / individual states


Matrices, prove that if $XY=0$ and other conditions, then $\det(X+Y) =\det(X- Y) $

Question: Prove that if $XY=0$ and $\det(X) =\det (Y) =0$, and both $\det(X+Y)$ and $\det(X-Y)$ are positive, then they are equal. I noticed it is enough to prove that $YX=0$.
Thanks
Edit: i mean prove that $\det(X+Y)=\det(X-Y)$
Comment: How can $\det(X-Y)>0$ and $X=Y$?
Comment: @MichaelHoppe i mean the determinants are equal. Check the edit above. Sorry!
Comment: BTW: Some of the "other conditions" are not really needed: If you have $\det(X) \neq 0$, then $XY = 0$ implies $Y = 0$, and the claim becomes trivial. Likewise, if $\det(Y) \neq 0$, then $XY = 0$ implies $X = 0$, so that $\det(X+Y) = \det Y$ and $\det (X-Y) = \det(-Y) = (-1)^n \cdot \det(Y)$, so that the claim (if both are positive, they are equal) is also trivial. So what you really are asking is if $XY = 0$ and if $\det(X\pm Y) >0$, then $\det(X+Y) = \det(X-Y)$.
Comment: Maybe interesting for other answerers: The OP mentions that it would be enough to show $YX = 0$. While true that this would be sufficient, it is not true that this follows from the given assumptions. As a counterexample consider $
X = \left(\begin{matrix}
1 & 1 & 0& 0 \\
0 & 1 & 0 & 0\\
0 & 0 & 1 & 1 \\
0 & 0 & 0 & 1
\end{matrix}\right)
\quad
Y = \left(
\begin{matrix}
1 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 \\
0 & 0 & 1 & 1 \\
0 & 0 & 0 & 0
\end{matrix}
\right).
$
Comment: Final comment @LiviuAntohi: Could you maybe explain where you encountered this problem, or what the context is? This might give some clue as to what techniques one should use for the proof.
Answer: This looks like a contest problem and there might be some nice tricks behind it, but without knowing the tricks, the problem can still be solved in a straightforward manner.
By a change of basis, we may assume that $X$ is already in rational canonical form. Then $X$ cannot contain a non-trivial nilpotent diagonal sub-block, otherwise, if the first diagonal sub-block of $X$ is
$$
\pmatrix{\mathbf 0^T&0\\ I_k&\mathbf0},
$$
then the condition $XY=0$ would force the first $k$ rows of $Y$ to be zero, but then both the first rows of $X$ and $Y$ would be zero, contradicting the assumption that $X\pm Y$ is non-singular.
Therefore, by another change of basis, we may assume that $X=D\oplus0_{r\times r}$ for some non-singular matrix $D$. Now the condition $XY=0$ means that $Y=\pmatrix{0_{(n-r)\times(n-r)}&0\\ \ast &Z}$ for some $r\times r$ matrix $Z$. Hence $\det(X+Y)=\det(D)\det(Z)$, $\det(X-Y)=(-1)^r\det(D)\det(Z)$ and the rest is trivial.


Como adicionar 2 dropzone na mesma view

Question: Bom estou tentando adicionar dois dropzone em uma tela, um é especifico para um arquivo(pdf,doc) e ou outro está para anexo(doc,pdf,imagem etc).
Segue abaixo um exemplo da utilização do Dropzone:
@{
Layout = null;
}

@Styles.Render("~/Content/dropzonescss")
<form id="my-awesome-dropzone" class="dropzone" action="#">

                        <button type="submit" class="btn btn-primary pull-right">Submit this form!</button>
                    </form>

Segue um exemplo onde funciona com 2 dropzone, mas o css fica desorganizado pois para ficar com o css default do dropzone deve-se adicionar a class dropzone.
Ao adicionar a class dropzone, o plugin não funciona pois ele não sabe qual dropzone é, erros de url etc

@Styles.Render("~/Content/dropzonescss")
<link href="~/Scripts/dropzone/basic.css" rel="stylesheet">
<link href="~/Scripts/dropzone/dropzone.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
@section Scripts {
@Scripts.Render("~/bundles/dropzonescripts")
@Scripts.Render("~/plugins/util")

   }

                   Escolha o(s) arquivo(s)

            Envie arquivos de no máximo    30MB. Você poderá enviar arquivos das seguintes extensões: PDF, DOC e  DOCX .

 Anexos

        O anexo tem finalidade de complementar, possibilitando melhores informações não referenciados no documento.

Comment: Certo. E os erros? Quais são?
Comment: Bom o primeiro erro é **throw new Error("No URL provided.");** que ocorre com o primeiro dropzone, ele não encontra:
    $("#file-dropzone").dropzone({
        url : "@(System.Web.VirtualPathUtility.ToAbsolute("~/Documento/SaveDocumentoAjax/"))", // Set the url
});
Comment: Se você inspecionar o HTML, o que aparece ali na URL?
Comment: **url : "/Documento/SaveDocumentoAjax/**,  o segundo dropzone se consegue ver a url(obs.: esta funcionando apenas o segundo dropzone), ela aparece no console com a requisição ajax.
Answer: Para a criação de dois dropzone na mesma view tive que utilizar o seguinte código:
$(document).ready(function () {
Dropzone.autoDiscover = false;
$(".dropzone").each(function () {
    new Dropzone($(this).get(0), {
        url: "...."
    });
});
});

Fonte:https://github.com/enyo/dropzone/issues/823

Como adicionar 2 dropzone na mesma view


Como alternar entre abas dentro de um modal bootstrap?

Question: estou trabalhando com bootstrap para fazer um modal de chat. A ideia seria a seguinte: Eu abro o modal onde está localizado o chat do usuário e na primeira aba do modal estaria um conteúdo (últimas mensagens, coisa do tipo) e na outra aba dentro do mesmo modal, estariam os contatos dos quais eu poderia iniciar uma nova conversa. Eu pretendo alternar as abas por meio do botão "MENSAGENS" e "NOVA CONVERSA", localizados na parte superior (não sei nem se devo usar button ou a ou input, sei la...) Desde já agradeço a ajuda!
Comment: Seria bom você disponibilizar o código para vermos o que já tentou.
Comment: Tem de indicar que versão do bootstrap está a usar.
Answer: Não sei que versão do Bootstrap está a usar, no exemplo a versão é a 4.3.1
Tem duas tabs, uma de Upload e outra de Browse.

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Hello, world!</title>

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×

                </button>

Modal title

Upload

Browse

upload Tab

browseTab

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary save">Save changes</button>


Permutation & Combination - How many 4 digit no's are there whose decimal notation contains not more than two distinct digits?

Question: How many 4 digit no's are there whose decimal notation contains not more than two distinct digits?
Comment: Would the downvoter care to share their thoughts on how the question could be improved?
Comment: Leading Zeros not allowed.
Comment: I tried to Solve :
Comment: I tried to Solve : Here is what I got - Number can be aaaa, aaab, aabb. For aaaa - 9C1*4!/4! = 9, For case aaab (not with 0 case) 9C1*8C1*4!/3!= 288, For case aaab (with 0 case,cannot be leading) 9C1*1C1*3!/2! = 27, Now Similarly for case aabb (without zero) - 9C1*8C1*4!/2!^2= 432, with zero 9c1*1c1*3!/2! = 27...  I don't know, if I am doing it correct??? I am getting 9+288+27+432+27....?? Any Idea..
Answer: HINT:

How many $4$-digit numbers use only one digit?
How many pairs of digits are there?
If a $4$-digit number uses the digits $a$ and $b$, it must have one $a$ and three $b$'s, two of each, or three $a$'s and one $b$. How many $4$-digit numbers are there in each of those three categories?

Your answer will depend on whether leading zeros are allowed. If they are not allowed, so that you cannot count $0101$, for instance, then you'll have to split the pairs into those that contain $0$ and those that don't.
Comment: @Joy: The book is right. I didn't notice that there's a small error in your count for the $aaab$ case with $0$ case. If $a=0$, there are $9$ possibilities, and if $b=0$, there are $27$, for a total of $36$.
Comment: I tried to Solve : Here is what I got - Number can be aaaa, aaab, aabb. For aaaa - 9C1*4!/4! = 9, For case aaab (not with 0 case) 9C1*8C1*4!/3!= 288, For case aaab (with 0 case,cannot be leading) 9C1*1C1*3!/2! = 27, Now Similarly for case aabb (without zero) - 9C1*8C1*4!/2!^2= 432, with zero 9c1*1c1*3!/2! = 27...  I don't know, if I am doing it correct??? I am getting 9+288+27+432+27....?? Any Idea..
Comment: @Joy: Your $aaaa$ case is correct, as are your two $aaab$ cases. You've overcounted $aabb$. Without $0$ there are $9$ ways to choose the first digit, $3$ ways to choose where the other copy of that digit goes, and $8$ ways to choose the other digit, for a total of $9\cdot3\cdot8=216$ numbers. (You counted every one of the twice. For instance, you counted $1221$ once with $a=1$ and once with $a=2$.) With $0$ there are $9$ ways to choose the first digit and $3$ ways to place the other non-zero digit, so your $27$ is right.
Comment: @ Brian - Thanks I figured out the Error. However I get 9+27+288+216+27 = 567, but my Book show 576... :( , which is 9 more.
Comment: @Joy: That may just be a typo in the book. Let me calculate it a different way to check.
Comment: I guess, may be a typo. Thank you for the help :) I'd wait for your final call on this.. :)
Comment: Perfect, I got it. Thanks a lot for the help.
Comment: @Joy: You're very welcome.


Does adding a dataset in repeated measures change the type of test?

Question: I am trying to design a test and am confused between the types of experiment that I should be conducting. Here is the description of what I am doing:
It is a repeated measures test. So, a participant is first given an uncolored node-link graph G1 and asked some questions about the graph. The dependent variable is the time it takes for the participant to answer the questions. Next the same participant is given a colored graph G2 and asked a set of questions. This is counterbalanced by reversing the order of the groups. Next I repeat this procedure except that this time, I provide colored G1 and uncolored G2. In all, I have 4 conditions/groups that perform the test in order as specified below:

G1-uncolored G2-colored
G2-colored   G1-uncolored
G1-colored   G2-uncolored
G2-uncolored G1-colored

I measure the time for each case. The two graphs are almost equal. The only reason I am using two different graphs is because I cannot use the same graph in both the conditions for a group as if I did that, then the participant would remember his answers from the previous condition.
Now, I am not sure what should I call this method? Should I consider one independent variable (i.e. presence/abscence of color in the graph) or whether I consider two different IV (color + which graph is used (G1/G2?)). In other words, is this just a t-dependent test or a two-way ANOVA (dunno which one)?
Answer: It sounds like you counterbalanced the pictures and order only to assess colour so colour presence would be your primary variable of interest.  However, regardless of how well you controlled for picture similarity, colour could have impacted them differentially. In that case you might want to look at a colour x picture interaction because it could compromise your conclusions, point to new directions for research, or both. A picture main effect wouldn't really mean anything.
Often times, in these cases one might report the main effect of colour but not fully report the interaction unless there was something meaningful in it because it's only run to assess the design, not as an outcome you want to generalize.
Comment: Just to avoid any confusion, I will be using the same colors with the same number of colors in same proportion in both the cases. The only difference between the dataset would be the configuration and labels of the graph vertices.


Qt - Converting QString to Indices of QByteArray - Dividing device ID into 3 indices

Question: I am using QtSerialPort to send serial messages across a COM port to an INSTEON PowerLinc 2413U Modem. I can hardcode and send messages just fine, however I need to send the same message using variable device IDs. The following is the structure I used to send static messages:
QByteArray msg;
bool msgStatus;

msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg[2] = 0x1B;
msg[3] = 0xE9;
msg[4] = 0x4B;
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;
send(msg,&msgStatus);

Index positions 2,3,and 4 represent the device ID. "1BE94B" in this instance. My function accepts the device ID that the action should be executed for via QString.
How can I convert the QString to fit the needed structure of 3 indices. I successfully get each byte of the 3 byte address using the following:
devID.mid(0,2)
devID.mid(2,2)
devID.mid(4,2)

My Target implementation is for the QByteArray to look like this:
QByteArray msg;
bool msgStatus;

msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg[2] = devID.mid(0,2)
msg[3] = devID.mid(2,2)
msg[4] = devID.mid(4,2)
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;
send(msg,&msgStatus);

I have tried many different conversions schemes, but have been unable to resolve what I need. Ultimately my msg should be structured as:
    02621DE94B151300

The only way I have successfully seen the intended device action is by individually assigning each byte in the QByteArray, using msg.append() does not seem to work.
Thank you for your suggestions!
Comment: maybe you can use `QByteArray::fromHex(const QByteArray& hexString)` to append the values
Comment: I believe if anything, it would be `msg=STRINGOFCOMMANDS.toHex()`, however I tried something very similar and it did not work. I am needing to convert my three byte device address into three separate indices with a datatype that aligns with the above `msg[x]=` structure.
Or, if there is a better implementation I would love to hear!
Answer: Part of the problem here is that QString is unicode/short based and not char based. For me it works when I use toLocal8Bit
QByteArray id;
idd.resize(3);
id[0] = 0x1B;
id[1] = 0xE9;
id[2] = 0x4B;

QString devId( bytes );

QByteArray msg;
msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg.replace( 2, 3, devId.toLocal8Bit() );
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;

If your id is text, and not bytes, then the fromHex must be added:
QString devId( "1BE94B" );
msg.replace( 2, 3, QByteArray::fromHex( devId.toLocal8Bit() ) );

Comment: Thomas, thank you very much for your reply. I am still not sure how that would work for what I need exactly. I have modified my post to reflect my intended target implementation. My problem is that my device ID originates from a string that is passed to the function, opposed to being hard coded into indices as you show above.
Comment: I modified my example to match your revised question.
Comment: I added an additional example for when the id is text from and not bytes.
Comment: Thank you very much for your time! I will not be able to really check this until after work.

What we are doing here is using `QByteArray & replace ( int pos, int len, const QByteArray & after )` by saying: Starting at index 2, replace three positions (2,3,4) with the Hex formatted devID, correct? This works because each of the elements will be 1 Byte ~ 2 Hex Characters.
Comment: Yes, that's  it. `toHex` receives 6 characters because `toLocal8Bit` converts devId into bytes. `toHex` then converts the 6 characters into 3 bytes values. These three bytes values are then written into message at offset 2.


Baby Rudin Theorem 11.35

Question: Inside Principles of Mathematical Analysis, Rudin states

11.35 $\ \ $ Theorem $\ \ $ Suppose $f\in{L}^2(\mu)$ and $g\in{L}^2(\mu)$. Then $fg \in{L}^1(\mu)$, and
$$\int_{X} \left|fg\right| d\mu \leq  \|f\| \|g\|.$$
Proof: This is the Schwarz inequality, which we have already encountered
for series and for Riemann integrals. It follows from the inequality
$$0\leq \int_{X}(\left|f\right|+\lambda\left|g\right|)^2 d\mu=\|f\|^2+2\lambda\int_{X} \left|fg\right| d\mu+\lambda^2\|g\|^2$$
which holds for every real $\lambda$.

One way to interpret the last equality on the RHS is through the discriminant of a quadratic equation for $\lambda$
$$\lambda*=\frac{-b\pm\sqrt{b^2-4ac\ }}{2a},$$
where $a,b,c$ are the coefficients of $\lambda$. If $\lambda$ is real, then the discriminant $b^2-4ac$ should be positive. This means that
$$b^2-4ac \geq 0.$$
When I do the analysis on pencil and paper, I find that
$$b^2 \geq 4ac,$$
and that
$$\int_{X} \left|fg\right| d\mu \geq  \|f\| \|g\|.$$
This is clearly wrong. Why am I getting the opposite of the Schwarz inequality?
Answer: The quadratic $P(\lambda)=\|f\|^2+2\lambda\int_{X} \left|fg\right| d\mu+\lambda^2\|g\|^2$ is always positive, so there can't be two distinct roots (otherwise $P(\lambda)$ would be negative for some values of $\lambda$).  Thus the discriminant must be $\leq0$.
Comment: $P(\lambda)$ needs not be a quadratic function in $\lambda$. The case $||g||=0$ needs to be handled separately (although it is easy..).
Comment: @DannyPak-KeungChan Of course.
Comment: That makes sense. Is there a specific theorem or resource I can review to see why the discriminant is negative? I reviewed Wikipedia. I don't understand why always being positive implies that the discriminant must be $\leq$ 0.
Comment: @Axion004 It's just elementary algebra:  since the binomial is always positive, it can have at most one real root, and if the discriminant were positive it would have two real roots.
Comment: I see, http://www.biology.arizona.edu/biomath/tutorials/quadratic/roots.html.

Baby Rudin Theorem 11.35


Joint distribution of two sums of correlated variables

Question: Suppose that $(X_1, Y_1)$ and $(X_2, Y_2)$ are independent and have the same joint distribution $F_{X,Y}$, which is a known copula $C_{X,Y}(F(X), F(Y))$. Also, suppose that $V = X_1 + X_2$ and $W = Y_1 + Y_2$.
It would be great if someone could point me to a procedure for computing the copula $C_{V,W}(F(V), F(W))$.
If not, is there is some other way (beside direct simulation) to compute the joint distribution $F_{VW}$?
Thanks!
EDIT: Added independence assumption
Comment: The fact that it is a copula does not matter on principle. You have the joint distribution of $(X_1,X_2,Y_1,Y_2)$, from which you can derive the joint distribution of $(V,W)$ by a linear change of variables.
Comment: You need to specify the _joint distribution_ of $(X_1,X_2,Y_1,Y_2)$ in order to compute the joint distribution of $X_1+X_2$ and $Y_1+Y_2$.  Even the _marginal distribution_ of $X_1+X_2$ cannot be obtained without some information (or assumption) about the joint distribution of $X_1$ and $X_2$.
Comment: I assume that the two vectors are independent. Thanks for catching that.
Answer: The distribution of the sum of independent random variables/vectors can often be obtained easily using moment generating functions (MGF).
In short, the MGF of the sum is the product of the MGFs of the random variables/vectors.
Details on MGF can be found here: https://en.wikipedia.org/wiki/Moment-generating_function


evaluation order and printing in printf

Question: I've seen questions about i++ ++i etc. but I have a small, somewhat different question.
suppose I have some thing like this:
<code> printf("%d %d", P, P);
</code>
and P is a function
<code> int P(){
      printf("HEY");
      return 0;
 }
</code>
what will be printed
HEYHEY00 or HEY0HEY0 ?
Comment: I assume you mean `printf("%d %d", p(), p());`
Comment: That's all good and well, but this is not a suitable question for Stackoverflow. There are numerous online compilers/IDEs that you can use. Try http://compileonline.com/.
Comment: I don't exactly have access to a program to try it with at the moment. so I was hoping for a quick answer since google didn't help me
Answer: Just run it.
This program:
<code>#include <stdio.h>

int P(){
  printf("HEY");
  return 0;
}
int main() {
  printf("%d %d", P(), P());
  return 0;
}
</code>
Outputs:
<code>HEYHEY0 0
</code>
Why? The arguments are evaluated (P is called) before the code for printf is actually entered.
EDIT: According to @Shafik bellow, the C standard does not guarantee the order of the evaluation of arguments, so if there had been two functions with different strings, the order of those strings wouldn't be predictable.
Comment: In this case it may not matter but the order of evaluation of function arguments in unspecified. So if there had been calls to two different functions the output could vary. So it is deceptive to say that just running the program will tell you what it does.
Comment: @ShafikYaghmour: Yes, but no matter what the arguments (in whatever order), are evaluated before the function is called. Right?
Comment: Yes, they are both evaluated before but if the OP used `P1()` and `P2()` which had different output the result would no longer be predictable. Especially since the OP mentioned `i++ ++i` order of evaluation is important.
Answer: The evaluation of the arguments in printf() as per standards is undefined.  but it prints only after total evaluation of arguments.
so in above example both p()'s are evaluated first, when they evaluated they print "HEY" 2 times  first then their returned values (0 and 0) are printed so output became "HEYHEY00".
Comment: The order in which function arguments are evaluated is *unspecified*.
Comment: But printing is done only after evaluation so first hey's are printed then their returned values are printed . that's y output is HEYHEY00
Comment: i agree with u @dbush but as far as question is concerned , he asked why the output is "heyhey0 0" . as evaluation done before printing out put is "HEYHEY0 0".

evaluation order and printing in printf


What is the most efficient way to search rows in a table based on metadata stored in another table?

Question: Consider these two tables stored in a MySQL database. The first stores a list of movies and the second stores metadata about each movie. Rather than adding 'category' and 'actor' fields to the movies table, they are stored as key/value pairs in the movie_attributes table, as each movie may have more than one category or actor attributed to it.
movies
id    name
-----------
0     hot rod
1     star wars

movie_attributes
id    movie_id    key      value
----------------------------------------
0     0           genre    comedy
1     0           genre    stupid
2     0           actor    andy samberg
3     0           actor    harrison ford
4     0           actor    chester tam
5     1           genre    adventure
6     1           actor    harrison ford

What would be the most efficient way to query the movies based on a search criteria that allows the user to select multiple genres and multiple actors? If the user adds more than one category to their search, I would like the results to include movies from both categories (but only those videos that also match the actors selected.)
For example, this pseudo-query:
select * from movies where (genre = 'comedy' OR genre = 'adventure') AND (actor = 'harrison ford')

would return this:
id    name
-----------
0     hot rod
1     star wars

Currently, my solution uses a mess of subqueries and it's awfuly slow, as my database contains more than two attribute key types per movie (genres, actors, actresses, tags, etc..) and it's terribly slow. Here's the real query that's equivalent to the example pseudo-query above:
select * from movies
    WHERE (select count(*) from movie_attributes
           WHERE key='genre'
           AND (value='comedy'
                OR value='adventure'))>0
    AND
          (select count(*) from movie_attributes
           WHERE key='actor'
           AND (value='harrison ford'))>0

Is there a more efficient way to achieve the same results using joins or some other SQL voodoo magic I'm unfamiliar with? Thanks!
Answer: See if this one helps:
SELECT m.* FROM `movie_attributes` ma
JOIN `movies` m ON (ma.movie_id=m.id)
WHERE
  (`key` = 'genre' and `value` in ('comedy', 'adventure'))
OR (`key` = 'actor' and `value` in ('harrison ford'))

Secondly, make sure, there is an index on the fields key, value in movie_attributes
Comment: The key can't be 'genre' and 'actor' at the same time, so your query will never return anything. You need to join to the movies table twice. I'm also not really sure why you used a left join instead of an inner join.
Answer: SELECT *
FROM movies
WHERE EXISTS(
  SELECT NULL
  FROM movie_attributes
  WHERE movies.id = movie_attributes.movie_id AND
        key = 'genre' AND value in ('comedy', 'adventure')
) AND
EXISTS(
  SELECT NULL
  FROM movie_attributes
  WHERE movies.id = movie_attributes.movie_id AND
        key = 'actor' AND value = 'harrison ford'
)

I would however suggest against this kind of design, see @n8wrl answer.
Comment: This is a corelated query. Solution with join or plain subquery is supposed to perform better.


Meaning of residual vs. predicted quantile plots in DHARMa?

Question: I am fairly new to statistics and R and I need a bit of help to understand the results of my GLM. I am using bee species richness as the response variable and plant species richness as the predictor variable. I only have 12 data points and the data is not nd.
m2 <- glm(Bee_SR ~ Plant.species.richness, data = IOP_pan,
   family = "poisson")
summary (m2)

Can someone help me understand if my model is okay?
Comment: What does "nd" mean?  Could you edit your question to include the data summary in a text format rather than as a screenshot?  It would also be somewhat useful to know the range of your response variable ...
Answer: It's hard to say for sure without more detail. The DHARMa residual-pattern plot (right-hand plot) strongly suggests that there's a non-(log)-linear pattern in the bee/plant species richness relationship. You should look at a plot of your raw data to confirm this suspicion (plot(Bee_SR ~ Plant.species.richness, data = IOP_pan, log = "y")) and try a quadratic model (Bee_SR ~ poly(Plant.species.richness, 2) ) to see if that helps resolve the problem.


Modified K-means with unequal cluster variances

Question: I wonder how I can modify the K-means algorithm so that the cluster volumes are not equal to each other. The K-means objective is to minimize within cluster sum of squares $\sum_{i=1}^{p} {\parallel \mathit{X}_i-\mathit{L}_{\mathit{Z}_i} \parallel}_2^2$, and this objective assumes that all cluster variances are the same. If we assume that the clusters are Gaussian with mean $\mathit{L}_{\mathit{Z}_i}$ and variance $\sigma_{\mathit{Z}_i}^2$ where $\mathit{Z}_i$ stands for the cluster assignment of data point $i$, then the objective for the cluster assignments become $\sum_{i=1}^{p} \frac {{\parallel \mathit{X}_i-\mathit{L}_{\mathit{Z}_i} \parallel}_2^2} {\sigma_{\mathit{Z}_i}^2}$. So, I tried modifying K-means such that $\mathit{Z}_i$ update is performed using this new update rule, and $\sigma_{\mathit{Z}_i}^2$ are also updated in each iteration. However, when I use this new modified K-means, almost all data points are assigned to the same cluster, which is weird. What might be the problem about that approach? I know EM can be used for this unequal-volume GMM purpose, but I want a simpler approach like K-means, and I am really curious about why what I tried is not feasible. Thanks!
Comment: In fact, since K-means does not assume that the data points are generated from a Gaussian mixture model, it doesn't deal with the variances explicitly, but it actually includes equal-variance assumption implicitly. If all the denominators in the new objective function that I wrote in the question are equal, then you can just omit this denominator, and you will be left with the K-means objective.
Comment: Yes, that's what the algorithm I suggest would do. Is there a valid algorithm like that? I mean, if we also learn the cluster variances in K-means and use them while assigning the data points to clusters, does it happen to be a valid algorithm? Mathematically, when you learn univariate GGM parameters by MLE and hard assignment, what I suggested looks correct, but intuitively, this would result in a situation where one of the clusters has a high variance, so, the distance of the points to that cluster is small, and as a result, more data points are assigned to it, so on (a vicious circle).
Comment: So, I just wonder if the algorithm I suggested is a pathologic one in general, or it behaves in this way just on the dataset I am working on. ?
Comment: Interesting question. I don't see the need for a variance assumption in k-means. In fact, I thought the objective was to minimize $  \sum_{i=1}^K\sum_{x_j\in S_i} ||x_j - \mu_i ||^2$. If so, there is no equal variance assumption.
Comment: Is your algorithm assignes a case to that cluster to which centroid it is closer by the distance, inversly weighted by the variance of the cluster?
Comment: This belated comment may no longer matter but, first off, I was confused by the distinction in word usage between *volumes* and *variances*. To me, *volume* refers to cluster frequencies. That said, the question left me wondering how you were drawing the samples between each iteration update. If you weren't bootstrapping or jacknifing them and were using the same exact data from one update to the next, then I'm not at all surprised that your answer didn't change. My experience is that k-means algorithms are quite immune to minor tweaks to the alg. Evaluating k-means using k-fold cv is needed
Answer: Use Gaussian Mixture Modeling (aka: EM Clustering) instead.
It allows different variances, depending on your model. It can even allow different covariances if you use the most complex models.
Answer: While not exactly K-means (see below), I ran across several clustering approaches (in addition to the EM clustering, already mentioned by @Anony-Mousse), which might be helpful. They include:

weighted hierarchical clustering (search for WPGMA and WPGMC here);
Dirichlet distribution-based clustering (Dirichlet mixture models and Bayesian-based hierarchical Dirichlet process models);
latent class (LC) clustering (see this page and this paper; LC clustering can be viewed as K-means generalization or, using the authors' terminology, "probabilistic extension").
Answer: In a GMM, in the limit that the variance of each component goes to 0, and the mixing proportion is uniform, doing expectation maximization on GMM reduces to K-means. Basically one can see K-means as a very special case of a GMM. If you want to modify K-means to allow possibility of different variance in each component, I would say that you will end up with an EM on a GMM.


Random-walk prior with ridge-like regularizarion?

Question: I am working with a model that contains a large number of coefficients, arranged in an ordered vector $\beta_1, \dots, \,  \beta_N $. I have some prior knowledge that could be used to improve the estimation of the $\beta$, in particular:

There's autocorrelation in the vector of $\beta$, such that the
difference between contiguous values, e.g. $\beta_i$ and $\beta_{i+1}$, is more likely to be
'small', rather than 'large';
I expect most $\beta$ coefficients to be unimportant; specifically I expect only a single, relatively small (compared to $N$), cluster of contiguous coefficient to be different from zero and useful for predicting my dependent variable.

I am working in a Bayesian setting (I use Stan). My idea was to include both these information in the model using a combination of a random-walk prior (to enforce smoothness and correlation between contiguous $\beta$) with a regularizing prior, to give higher prior probability to small values of $\beta$.
More in detail, I have a random walk prior such that
$$
\beta_1 \sim \mathcal{N}(0,1), \quad \beta_i \sim \mathcal{N}(\beta_{i-1}, \tau)
$$
where $\tau$ is a smoothness hyperparameter.
At the same time I want to penalize large values of $\beta$. In ridge regression this would be achieved by adding a penalty $-\lambda \sum_{i=1}^N \beta_i^2$ to the log-likelihood. In a Bayesian setting this should be equivalent to setting a zero-centred Gaussian prior, e.g.
$$
\beta_i \sim \mathcal{N}\left(0, \frac{1}{2\lambda}\right)
$$
Putting everything together, this would give the following modified/regularized random walk prior:
$$
\beta_1 \sim \mathcal{N}\left(0, \: \frac{1}{1+2\lambda}\right), \quad \beta_i \sim \mathcal{N}\left(\frac{\frac{1}{2\lambda}}{\tau + \frac{1}{2\lambda}}\beta_{i-1}, \: \frac{1}{\frac{1}{\tau} + 2\lambda} \right)
$$
My question is: does this approach makes sense or are there shortcomings/limitations that I have missed? Is there any reference I can cite that used similar approach? Or alternatively, is there a better way to do this?
Thanks!
Comment: are you familiar with the fused lasso? Would those ideas be helpful?
Comment: I think you're on the right track but would use something else for the actual prior. See here for example: https://arxiv.org/pdf/1706.06908.pdf
Comment: i don't understand why you don't set $\beta_1 \sim N(0,\tau_1)$  and $\beta_i \sim N(\beta_{i-1},\tau)$.  your initial setup is already regularising. remember that you can pull the $\beta_{i-1}$ out of the mean. so $\beta_i= \beta_1 + \sum_{1<j<=i} N(0,\tau)$. ie you are regularising beta 1 - and the consecutive diffs.
Comment: Thanks, I did not know about the fused lasso (and Bayesian fused lasso mentioned in the link), I will look into it.
Answer: I would look into the horseshoe-type markov random fields (MRFs) described in https://projecteuclid.org/euclid.ba/1487905413. They generalize Gaussian MRFs to include horseshoe-type priors which induce the type of shrinkage of the coefficients you want, while maintaining the autoregressive properties from a random walk. They also have a Stan implementation!


How can using Logistic Regression without regularization be better?

Question: I'm using this Java machine learning library: https://sites.google.com/site/qianmingjie/home/toolkits/laml
From the library I'm using Logistic Regression: http://web.engr.illinois.edu/~mqian2/upload/projects/java/LAML/doc/ml/classification/LogisticRegression.html
This class supports 4 types of regularizations:

0:  No regularization
1:  L1 regularization
2:  L2^2 regularization
3:  L2 regularization
4:  Infinity norm regularization

You basically create an object of Regular Regression using this code:
int regularizationType = 1;
double lambda = 0.1;
Classifier logReg = new LogisticRegression(regularizationType, lambda);

When I tried it I noticed this weird thing:
As far as I know the idea of regularization is to have the weights as small as possible and so using lambda will penalize large weights. So one should use a large lambda to regularize. However, when I used L1 regularization with a lambda=1 the performance was worse than using lambda=0.0001. Actually the best performance I got is when I used lambda=0!
My questions:
1- How can logistic regression without regularization perform better than when using regularization? Isn't the idea of regularization after all is to make the performance better?!
2- Should I use large values for the regularization parameter?!
3- Is using regularization in general always good?
Comment: How can using question without grammar is better?
Comment: Not all regression is about predictive performance.
Answer:
As far as I know the idea of regularization is to have the weights as small as possible and so using lambda will penalize large weights.

Deep down, regularization is really about preventing your weights from fitting the "noise" in your problem, aka overfitting. If you have more noise (i.e. as measured by the standard deviation of the noise distribution), then you will need more regularization to prevent overfitting. It's not really about keeping weights small.

So one should use a large lambda to regularize.

With regularization, it's best to avoid such definite statements. Sometimes bigger is better, sometimes not.

However, when I used L1 regularization with a lambda=1 the performance was worse than using lambda=0.0001. Actually the best performance I got is when I used lambda=0!

By my reasoning above, it is not true that bigger lambda => better performance. It depends on the noise level, among other things. In fact, you can always set lambda = 1000000 and all your weights will be zero. Choosing lambda correctly can be somewhat of a subtle art.
To your questions:

1- How can logistic regression without regularization perform better than when using regularization? Isn't the idea of regularization after all is to make the performance better?!

More often than not, regularization will improve the performance of your model. It sounds to me like you're considering one specific application and/or dataset, in which case it is very possible that regularization doesn't help for this specific problem.
However, without knowing what you mean by "better performance", it's hard to tell. What have you done to test the generalization performance of your model? lambda = 0 is always gonna to perform better on the training data, but what you should care about is the performance on test data.

2- Should I use large values for the regularization parameter?!

See above - this is somewhat of an art and you need to balance it with the noise level in your specific problem. Are you familiar with / have you tried techniques such as cross-validation for selecting hyperparameters?

3 - Is using regularization in general always good?

See answer to 1).
Comment: Good point about $\lambda = 0$ on the training data.
Comment: I split my data into two parts: training %80 and testing %20. I trained my classifier on the training set and tested the performance on the test set.
Comment: So my trained classifier achieved the best performance on the test set when the classifier was trained with `lambda=0`.
Comment: Did you try multiple, random 80/20 splits? If so, did `lambda = 0` always perform the best? Without knowing more about your data and your code it's hard to say anything definitive.


Transformar formato de data DD/MM/AA em MM/DD/AA em Shell Script

Question: O script lê a data de um .txt no formato DD/MM/AA, e preciso convertê-la para o formato MM/DD/AA com Bash, Sed ou AWK.
Answer: Em bash, existe algo chamado "parameter expansion" que consiste em manipular os argumentos. Sabendo disso, recomendo que evite usar sed e/ou awk em pipelines. Pois, devido cada pipeline gerar um processo, isso pode deixar seu código mais lento.
Utilizar do "parameter expansion" pode ser meio confuso no inicio, mas é uma bom truque! Veja:
$ set -- "31/12/1970"
$ echo "${1:3:3}${1:0:3}${1:6:4}"
12/31/1970

A sintaxe é simples: ${variável:offset:tamanho}.
Neste caso, deixei o "31/12/1970" como um parâmetro $1 e fui formatando cada informação apenas aproveitando cada "offset" que é a localização dos caracteres -, já o tamanho, refere-se a quantidade de caracteres que será mostrado à partir do offset que você definiu. Ou seja:
$ set -- "Edition 3"
$ echo "${1:8:1}rd ${1:0:7}"
3rd Edition

Outra dica para deixar mais legível, tu pode usar como array. Assim você tem uma "referencia" do que está tratando:
$ set -- "31/12/1970"
$ txt=("${1}")
$ echo "${txt[0]:3:3}${txt[0]:0:2}${txt[0]:5:5}"
12/31/1970

ps: Certifique de que estejam com aspas duplas, caso você coloque uma sintaxe do tipo: $variavel. Pode te dar algumas confusões se essa $variavel estiver vazia. Então, para evitar, basta usar deste jeito: "$variavel".
Answer: Acabei de descobrir como.
É possível fazer utilizando AWK da seguinte maneira:
data=`echo $data | awk -F/ '{ print $2"/"$1"/"$3 }'`

Isso é bem útil para se obter a diferença entre duas datas.
Answer: Uma maneira diferente de se fazer é usando o sed:
echo "31/12/1970" | sed -r 's/(.*)\/(.*)\/(.*)/\2\/\1\/\3/g'


Calling cross-script arrays

Question: I'm calling two scripts.
The first...

Contains this code (I'm creating and appending table elements):
var td = tr.appendChild(document.createElement('td'));
var tdText = "myArray[0] = " + myArray[0];
td.innerHTML = tdText ;

But the cell text (and console text, when I output it to the console in FireFox) says:
"myArray[0] = [object Object]"

So, on the other questions which were answered here (and in other web sites), this should work, because variables (including arrays) are "global" to the window that the page is displayed in...except that it's not, and I haven't been able to find out WHY it's not.  I could just combine the two scripts, but I figured it would be best to separate them because their roles are different: one builds and populates arrays, the other does some other stuff on the page and then (should) use the data that was added to the arrays in the first script.
Am I going about this wrong, or am I missing something very simple here?  Thanks in advance, everyone.
Comment: Well, it *does* work. You're correctly accessing `myArray[0]`. However, the output format of the `myObject` instance seems to confuse you. What did you expect?
Comment: Oh, well now I feel stupid.  I'm very clearly missing the property accessor when trying to access the object's value.
Answer: Missing the property accessor for the object that I'm trying to get a property value for.  It should be:
var tdText = "myArray[0] = " + myArray[0].foo;

Calling cross-script arrays


Function evaluated in Brownian motion vanishes implies that the function itself vanishes?

Question: tl;dr, here's my question:

Question. Let $f(t,x)$ be a measurable function such that $f(t,B_t)=0$ almost everywhere on $[0,T]\times\Omega$ for a Brownian motion $B_t$. Does this imply that $f(t,x)=0$ almost everywhere on $[0,T]\times\mathbb R$?

Given that Brownian motion is recurrent and normally distributed (and hence,
the probability that $|B_t|>a$ for any $a$ is nonzero, albeit very small for large $a$), it seems intuitive enough that this should be true, but I have been unable to prove it conclusively.

For context:
I was reading the answer to this question (which can actually be found on this MO question), and there was a detail that left me unsatisfied.
If we remove any specificities related to the linked problem and look at the core of the argument, unless I'm mistaken, it goes as follows (tl;dr skip to question below):

Let $(B_t)_{t\geq0}$ be a Brownian motion (for simplicity), and let $f(t,x):\mathbb R^+\times\mathbb R\to\mathbb R$ be a measurable function.
Suppose that $\int_0^tf(s,B_s)~\text d s=0$ for all $t\leq T$.
Then, for almost every $\omega$, $f\big(t,B_t(\omega)\big)=0$ for almost every $t$ (by the Lebesgue differentiation theorem).
By Fubini's theorem, we can argue that $f\big(t,B_t(\omega)\big)=0$ almost everywhere on $[0,T]\times\Omega$.
Therefore $f(t,x)=0$ for almost all $(t,x)$.

The only part of the argument that I'm not confortable with (which is the one that is left unexplained in the linked MO answer) is part 4, which is essentially the question above.
Answer: Let $D:=\{(t,\omega):f(t,B_t(\omega)\not=0\}$ and $C=\{(t,x):f(x,t)\not=0\}$. Observe that $D=\varphi^{-1}(C)$, where $\varphi(t,\omega) =(t,B_t(\omega))$ (mapping $[0,T]\times\Omega$ into $[0,T]\times\Bbb R$). Consequently, writing $\lambda$ for Lebesgue measure on $[0,T]$,
$$
0=\lambda\otimes\Bbb P(D) =\int\int 1_{C}(t,x){1\over\sqrt{2\pi t}}e^{-x^2/2t}\,dt\,dx.
$$
Because the integrand $(t,x)\mapsto{1\over\sqrt{2\pi t}}e^{-x^2/2t}$ is strictly positive, it must be that $\int\int 1_{C}(t,x)\,dt\,dx=0$. That is, $\lambda\otimes\Bbb P(C)=0$.
Answer: For any measurable set $A \subseteq [0,T] \times \Omega$ it holds that
$$\begin{align*} \{(t,\omega); (t,B_t(\omega)) \in A\} &= \int_0^T \! \int 1_A(t,B_t) \, d\mathbb{P} \, dt \\ &= \int_0^T \! \int 1_A(t,x) \frac{1}{\sqrt{2\pi t}} e^{-x^2/2t} \, dx \, dt. \end{align*}$$
Since $e^{-x^2/2t}$ is strictly positive, this implies
$$(\lambda|_{[0,T]} \times \mathbb{P})(A) = 0 \iff (\lambda|_{[0,T]} \times \mathbb{P})(\{(t,B_t) \in A\})=0.$$
Consequently, if we set $A:= \{(t,x); f(t,x) \neq 0\}$, then we find that
$$(\lambda|_{[0,T]} \times \mathbb{P})(\{(t,\omega); f(t,B_t(\omega)) \neq 0\}) = 0$$
if, and only if,
$$(\lambda|_{[0,T]} \times \mathbb{P})(\{(t,x); f(t,x) \neq 0\})=0.$$


jQuery scroll content with navigation

Question: Can someone tell me how to scroll the content.
For example I have a link like this
content3

When the user click that link I would like to scroll the content to div content3.
Can someone tell me how to do this using jQuery?
Here is my full code.

content1

content2

content3

content4

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Comment: @Eric You can scroll the page with CSS?
Comment: @Eric How is that CSS? That's pure HTML...and default browser behavior. And there's already an answer with that explanation...
Comment: woaah, my mind went blank, CORRECTION... html. my bad
Answer: You don't need jQuery to do this - simply use href="#content3" to scroll to the element with an id of "content3".
Comment: I completely agree. Other than animating the scroll, this is how it should be done.
Answer: jQuery has scrollTop and scrollLeft methods to do this.. if it is merely vertical scrolling, then scrollTop(yVal) will do the trick
http://api.jquery.com/scrollTop/
Answer: Using scrollTop :
Example :
click me to scroll to the div "content3"

$(document).ready(function(){
    $('a').on('click',function(){
        $("#container").animate({ scrollTop: $('#'+$(this).attr('scrollTo')).offset().top }, 1000);
    });
});

Answer: Don't know what you are attempting to do, but go check out wowslider.com
Answer: Using the $('body').scrollTop atribute like so:
$('#button1').click(function(){
    var element = $('#content1'),
    elemTop = element.offset().top, // You get the element top to know where to move the window
    windowTop = elemTop + 20; // You can add some pixels so the element dont be shown on the very edge
    $("html, body").animate({
           scrollTop:  windowTop // Animate the change so it doesnt seem invasive
    }, "fast");
    }
});

Answer: Try this...
$('a').on('click', function (){
    $('html,body').animate({
        scrollTop: $('#'+$(this).text()).offset().top},
    'slow');
});

See this JsFiddle Example
Greetings...
Answer: Based on your markup it appeared you wanted to use the anchor text to determine where to scroll. If you click the content1 link it will scroll you to
.
$('.nav ul li a').click(function(){

    $('html, body').animate({
        scrollTop: $('#' + $(this).text()).offset().top
    }, 2000);

});

Heres a fiddle as an example: http://jsfiddle.net/ZG3zh/
Answer: In order to scroll with HTML you need to set the href of the anchor #+'id of element' you are scrolling to.
Example:
I want to scroll to
Hello World

using an anchor tag or a use the code, Click Me!

jQuery scroll content with navigation


onBlur event not allowing link clicks to register

Question: I have a Navigation Bar with a React-InstantSearch: <SearchBox /> in that provides me with Autocomplete, there is an onChange event that fires that shows the suggestions box. There is also an onBlur event that fires when you leave the search box and hides the box. This onBlur event is preventing a link click from firing. (Verified by removing it). Does anyone have a suggestion on how I can correct this? Code below:
Relevant Portion of App.js
render() {
    if (this.state.redirect) {
      return (

          <InstantSearch
            appId="{MY APP ID}"
            apiKey={process.env.REACT_APP_ALGOLIA_API_KEY}
            indexName="blog_posts"
          >
            <NavigationBar
              loggedIn={this.state.loggedIn}
              handleLogout={this.handleLogout}
              username={this.state.username}
            />
            <Redirect to="/" />;
          </InstantSearch>

      );
    }

    return (

        <InstantSearch
          appId="{MY APP ID}"
          apiKey={process.env.REACT_APP_ALGOLIA_API_KEY}
          indexName="blog_posts"
        >
          <NavigationBar
            loggedIn={this.state.loggedIn}
            handleLogout={this.handleLogout}
            username={this.state.username}
          />
          <Switch>
            <Route exact path="/" />
            <Route path="/posts" component={PostListView} />
            <Route
              path="/post/:postID"
              render={props => (
                <PostDetailView
                  {...props}
                  loggedIn={this.state.loggedIn}
                  username={this.state.username}
                  deleteComment={this.deleteComment}
                />
              )}
            />
            <Route
              path="/login"
              render={props => (
                <LoginForm {...props} handleLogin={this.handleLogin} />
              )}
            />
          </Switch>
        </InstantSearch>

    );
  }
}

export default App;

NavigationBar.js
import React, { Component } from "react";
import { Navbar, Nav, NavItem } from "react-bootstrap";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import { Hits, SearchBox, Highlight } from "react-instantsearch-dom";

import CompanyHeader from "../config/settings.js";

/**
 * Navigation Bar for App
 * Utilizes react-bootstrap
 * @extends Component
 */
class NavigationBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hitResultsShown: false
    };

    this.onChange = this.onChange.bind(this);
    this.onBlur = this.onBlur.bind(this);
  }

  onChange() {
    this.setState({
      hitResultsShown: true
    });
  }

  onBlur(e) {
    this.setState({
      hitResultsShown: false
    });
    e.target.value = "";
  }

  render() {
    const logged_in_nav = (
      <React.Fragment>
        <NavItem eventKey={2} href="#">
          {`Hello, ${this.props.username}`}
        </NavItem>
        <NavItem eventKey={3} onClick={this.props.handleLogout}>
          Logout
        </NavItem>
      </React.Fragment>
    );

    const logged_out_nav = (
      <React.Fragment>
        <NavItem eventKey={2} href="/login">
          Log In
        </NavItem>
        <NavItem eventKey={3} href="/signup">
          SignUp
        </NavItem>
      </React.Fragment>
    );

    return (
      // Instantiate a Navbar with:
      //   Dark Theme
      //   Full-width
      //   sticks to top of viewport
      <Navbar inverse fluid fixedTop>
        <Navbar.Header>
          <Navbar.Brand>
            {CompanyHeader}
          </Navbar.Brand>
          <Navbar.Toggle />
        </Navbar.Header>
        <Navbar.Collapse>

            <NavItem eventKey={1} href="/random">
              Random Post
            </NavItem>
            {this.props.loggedIn ? logged_in_nav : logged_out_nav}

          <Navbar.Form pullRight>
            <SearchBox onChange={this.onChange} onBlur={this.onBlur} />
            {this.state.hitResultsShown ? <Hits hitComponent={PostHits} /> : ""}
          </Navbar.Form>
        </Navbar.Collapse>
      </Navbar>
    );
  }
}

class PostHits extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const hit = this.props.hit;
    return (

          <Link to={`/post/${hit.id}`}>
            <Highlight attribute="title" hit={hit} className="font--bold" />
          </Link>

          {hit.content.length > 100 ? hit.content.slice(0, 100) : hit.content}

    );
  }
}

Answer: This is happening because your onBlur is only wrapping the Searchbox component.
When you click on the suggestions box link you are removing focus from the Searchbox and subsequently hiding the suggestions.
All you have to do is wrap both of the elements within the onBlur and your problem will be solved:

  <SearchBox />
  {this.state.hitResultsShown && <Hits hitComponent={PostHits} />}

Note: Inline conditional rendering is better like that ^ and onFocus will call it once instead of repeatedly like onChange will.
In a situation like this your suggestions box would normally be part of the Search component as it is inherently linked, pushing the blur/change functionality down into that component and making it a lot more self-contained.
Comment: unfortunately this did not solve my issue. Moving the on* methods to a container div had no effect.
Comment: Can you update your answer with what you tried? And have you attempted merging the autocomplete box into the search component? That's where it should be and will probably fix your issue :)
Answer: I had the same issue before. I solve with Hooks and a setTimeout for onBlur method with 200ms. That way, my child tab close right after i click on the link and my onChange worked fine too.
onBlur={()=>{setTimeout(() => {setSearch(false)}, "200")}}


Java - JPA @Basic and @Embedded annotations

Question: I am learning JPA from this tutorial.
I have some confusions in understanding the following annotations:

@Basic
@Embedded

Fields of an embeddable type default to persistent, as if annotated with @Embedded.

If the fields of embeddable types default to persistent, then why would we need the @Embedded annotation
Answer: The @Embeddable annotation allows to specify a class whose instances are stored as intrinsic part of the owning entity. This annotation has no attributes.
@Embeddable
public class EmploymentPeriod {
     java.util.Date startDate;
     java.util.Date endDate;
     ...
}

The @Embedded annotation is used to specify a persistent field or property of an entity whose value is an instance of an embeddable class. By default, column definitions specified in the @Embeddable class apply to the table of the owning entity but you can override them using@AttributeOverride:
@Embedded
@AttributeOverrides({
    @AttributeOverride(name="startDate", column=@Column(name="EMP_START")),
    @AttributeOverride(name="endDate", column=@Column(name="EMP_END"))
})
public EmploymentPeriod getEmploymentPeriod() { ... }

Regarding the optional @Basic annotation, you may use it to configure the fetch type to LAZY and to configure the mapping to forbid null values (for non primitive types) with the optional attribute.
@Basic(fetch=LAZY)
protected String getName() { return name; }

You can also place it on a field or property to explicitly mark it as persistent (for documentation purpose).
Comment: Q1. If the fields or properties of embeddable types are by defualt persistent then why we need to add `@Embedded` annotation ? Q2. Can I use `@AttributeOverrides` annotation without `@Embedded` annotation? Could you please also throw some light on `@Basic`?
Comment: Q1. Because @Embedded allows to override column definitions Q2. No I don't think so. There is a good example illustrating this here: http://www.redhat.com/docs/en-US/JBoss_Enterprise_Web_Platform/5.0.0/html/Hibernate_Annotations_Reference_Guide/ch02s02s02s03.html
Comment: @Pascal What if there are no overrides? What's the purpose of `@Embedded`? Can it be left out?
Comment: @HendyIrawan: I have posted this as a question here http://stackoverflow.com/q/31157700/2886891
Comment: Most usefull, concise and complete answer on this subject ! ;) got my +1
Answer: In ORM mapping, the granularity of your object model can be finer than that of your database.
For example, you can have a Person record in your database which can be further decomposed to contain a reference to an Address object  in your model. That's where the @Embedded and @Embeddable annotations come in. They simply state a relationship where one Entity can be stored as part of another.
As for the @Basic annotation, it's the simplest form of mapping which is applied by default to primitive types such as int and float and their wrappers as well as enums. More information can be had here: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html#entity-mapping-property
Answer:
@Basic
The  Basic annotation can be applied to a persistent property or
  instance variable of any of the following types:
Java primitive types,
  wrappers of the primitive types, String,  java.math.BigInteger,
  java.math.BigDecimal, java.util.Date,  java.util.Calendar,
  java.sql.Date,  java.sql.Time,  java.sql.Timestamp, byte[], Byte[],
  char[], Character[], enums, and any other type that implements
  java.io.Serializable.
The use of the Basic annotation is optional for
  persistent fields and properties of these types. If the  Basic
  annotation is not specified for such a field or property, the default
  values of the Basic annotation will apply.

Example:
@Basic
protected String name;

and
@Basic(fetch=LAZY)
protected String getName() {
    return name;
}

@Embedded
Specifies a persistent field or property of an entity whose value is
  an instance of an embeddable class. The embeddable class must be
  annotated as Embeddable.

Example 1:
@Embedded
@AttributeOverrides({
       @AttributeOverride(name="startDate", column=@Column("EMP_START")),
       @AttributeOverride(name="endDate", column=@Column("EMP_END"))
})
public EmploymentPeriod getEmploymentPeriod() { ... }

Example 2:
@Entity
public class Project {
    @EmbeddedId ProjectId id;
    //other fields
}

@Embeddable
Class ProjectId {
    int departmentId;
    long projectId;
}

JSR Persistence Specification and Source reference


string to integer in postgres

Question: i have a table of users:-
|usersname|
|  52125  |
|  John   |
|  kathy  |
|  52451  |

I need to delete entries where username is made of only numbers like 52125 and 52451. i don't want to delete john and kathy. datatype of column is varchar and I'm using PostgreSQL. can someone help.
Comment: Use a regex match?
Answer: You can use regexp to find such rows:
SELECT *
FROM t
WHERE usersname ~ '^[0-9]+$' -- user name made only of numbers

Answer: Something like this?
SELECT username
FROM users
WHERE username !~* '([a-z])';

Answer: If you want to actually remove the users from the table, use delete:
delete from t
    where username ~ '^[0-9]+$';

You can use this logic in a select to check the rows before deleting them.

string to integer in postgres


Flask Matplotlib Python

Question: Unable to dynamically update data visualization charts via user input.
make_visual takes info, creates matplotlib visuals, then saves them in the static location.
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

def make_visual(nums):
    a, b, c, d, e, f, g, h = nums
    turn_labels = "A", "B"
    turn_size = [a,b]
    goes_labels = "1", "2"
    goes_size = [c,d]
    method_labels = "Moo", "Bark", "Meow"
    method_size = [g, f, e]
    fig1, ax1 = plt.subplots()
    ax1.pie(turn_size, labels=turn_labels, autopct='%1.1f%%', startangle=90)
    ax1.axis('equal')
    plt.savefig("static/graph.png")
    fig2, ax2 = plt.subplots()
    ax2.pie(goes_size, labels=goes_labels, autopct='%1.1f%%', startangle=90)
    ax2.axis('equal')
    plt.savefig("static/goes.png")
    fig3, ax3 = plt.subplots()
    ax3.pie(method_size, labels=method_labels, autopct='%1.1f%%', startangle=90)
    ax3.axis('equal')
    plt.savefig("static/method.png")

make_visual([0.50, 0.50, 0.4, 0.6, 0.43, 0.3, 0.27, 14.511904761904763])

^
When this runs on it's own in the command line, it works.
Does not work in the Flask function.
If I remove make_visual, the info goes through to the results.html page as intended.
I am unsure as to why I am unable to dynamically create, save, then render the page with the visuals current from the static folder.
@app.route('/results', methods=['POST'])
def results():
    stats = request.form['data']
    info = get_stats(stats)
    unstr = stats.split(',')
    title = make_string(unstr[0], unstr[1])
    make_visual(info)
    return render_template('results.html', stats=title, data=info)

Below is results.html.
{% block content %}

Results

{{ stats }}

{{ data }}

{% endblock %}

Answer: For best results, show code that demonstrates the problem, with extraneous details removed and in a full enough form that it can be run. Often the exercise of doing that is sufficient to unearth the cause.
However, getting matplotlib working with Flask involves a trick. I'm guessing that after
import matplotlib

there's no
matplotlib.use('agg')

without with matplotlib will attempt to use tkinter to render, which leads to sadness when trying to work with Flask.
Comment: Good guess and idea.
I added the make_visual function to the question.

Flask Matplotlib Python


How to populate asp:LinkButton from Json data response

Question: first of all apologies for my english.
I'm a newby in json area.
My problem is that i can't parse the data recived in a json response into a asp:LinkButton or whatever asp:element, coz i can't create a correct sintax.
Especifically, What I'm trying to do, is this:

<asp:UpdatePanel runat="server" ID="CarMakersUpdatePanel" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:HiddenField runat="server" ID="CarMakersHiddenField" />
        <asp:BulletedList runat="server" ID="MakersList" DisplayMode="LinkButton">
        </asp:BulletedList>
    </ContentTemplate>
</asp:UpdatePanel>

Server code:
protected void Page_Load(object sender, EventArgs e)
{
    MakersList.Items.Clear();
    foreach (var maker in CarMakersHiddenField.Value.Split(';'))
    {
        MakersList.Items.Add(maker);
    }
}

Second approach is more siutable if you need to pass to server some complex object like array of makers objects. In that case you can serialize this object to JSON string on client and deserialize it on server. Looks like previous version with bit changes:

Markup left the same as in the first version.
Server code:
[Serializable]
public class Make
{
    public string make_id;
    public string make_display;
    public bool make_is_common;
    public string make_country;
}

protected void Page_Load(object sender, EventArgs e)
{
    MakersList.Items.Clear();
    if (!String.IsNullOrEmpty(CarMakersHiddenField.Value))
    {
        var serializer = new DataContractJsonSerializer(typeof(Make[]));
        using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(CarMakersHiddenField.Value)))
        {
            var makes = serializer.ReadObject(stream) as Make[];
            if (makes != null)
            {
                foreach (var maker in makes)
                {
                    MakersList.Items.Add(new ListItem(maker.make_display, maker.make_id));
                }
            }
        }
    }
}

Comment: Thank u so much Yuriy!!  this is exactly what i was looking for!!  thank u guys for your explications!


is $x^{1000,000,000}$ a polynomial?

Question: per wiki

A polynomial equation, also called algebraic equation, is an equation
  of the form
$a_{n}x^{n}+a_{n-1}x^{n-1}+\dotsb +a_{2}x^{2}+a_{1}x+a_{0}$

and

a polynomial can either be zero or can be written as the sum of a
  finite number of non-zero terms

so, as long as the n is a finite number, such as 2 billion, 3 trillion,
$P = x^n$
is a polynomial equation, do I understand this right?
Comment: Why did you omit Wikipedia's $=0$ from the statement of the equation?
Comment: The important thing is not how large the exponent is (it doesn't matter if its 2, 3, or a billion). The important thing is to understand what the words 'equation' and 'polynomial' mean.
Comment: "Polynomial" or "Polynomial equation"?
Comment: yes that's right. THe only thing I'd say is the term "expression" is better than "equation" in this context, because there are no $=$ signs anywhere
Comment: That is not an equation. Even wiki has the equal sign there.
Answer: A polynomial equation is of the form
$$a_{n}x^{n}+a_{n-1}x^{n-1}+\dotsb +a_{2}x^{2}+a_{1}x+a_{0} \color{red}{ \boldsymbol{=0}}$$
while what you wrote is just the general form of a polynomial.
And indeed, if you check the definition and plug in $n=100000000000$ with $a_n=1$ and $a_k=0$ for all $k \neq n$ then we see that $x^{100000000000}$ is a polynomial. (But by itself not a polynomial equation.)
Comment: ...and $x^{100000000}=0$ *is* a polynomial equation.

is $x^{1000,000,000}$ a polynomial?


Clearing cached memory of uploaded file

Question: On my system, I have a log file that is being rotated and uploaded every hour. This file is heavy on writes and only needs to be read when rotated and uploaded.
The cached memory on my system is raising until it allocates the entire RAM and then the OS clears some of it. I want to improve that process and I suspect that the cache is rising b/c of this log file I keep writing to all the time.
I need to find a way to clear the cache of that file after I upload it so I can tell the OS this is no longer needed and let it free up memory.
As far as I know, echo 3 > /proc/sys/vm/drop_caches clears all cached memory. Is that correct?
Is there any way to clear up cached memory for just one file?
Answer: In general, it's best to just leave your operating system to manage memory itself. Memory used as cache will be returned to processes when they request it.
You really only need to start taking action when your system is regularly using significant amounts of memory for processes or you have gone beyond that and are swapping. You should have monitoring in place to alert you to these issues.
The use of /proc/sys/vm/drop_caches is discouraged, unless you know what you're doing. The relevant kernel docs have this to say

Use of this file can cause performance problems.  Since it discards cached
  objects, it may cost a significant amount of I/O and CPU to recreate the
  dropped objects, especially if they were under heavy use.  Because of this,
  use outside of a testing or debugging environment is not recommended.
Comment: @lain so you're basically saying I shouldn't touch it even though I see the cached memory keeps growing until it fills the entire RAM? (I don't see any swap and my processes use constant amount of memory).
Comment: Yup - http://www.linuxatemyram.com/, there is absolutely nothing wrong with cache using up lots of memory.

Clearing cached memory of uploaded file


Identificar se o dispositivo é pc ou celular e utilizar um código diferente pra cada

Question: quero que fique automático se a pessoa estiver no computador exiba um código se estiver no celular exiba outro diferente.
Eu não quero mudar a resolução e sim todo o conteúdo apresentado na pagina.
Exemplo:
Se for mobile:
Você esta conectado por um celular!
se por computador
você esta conectado por um PC!
Alguém me da uma luz?
Comment: Eu adoraria isso se existisse, mas infelizmente os comitês que normatizam a web são tão ruins, que não existe um jeito simples. Tudo é muito cheio de detalhes, e não fica 100% como deveria ser. Mas tem essas quebrações de galho como media-queries, que não deixam de ser um remendo porco, mas é melhor do que nada. E tou dando +1 na sua pergunta, pq é uma duvida válida, apesar de não ter uma resposta que vá resolver bem atualmente.
Comment: Você tá usando algum framework CSS?
Comment: Caso não esteja, dê uma olhada em media-queries CSS que pode lhe ajudar.
Comment: Talvez esse artigo te ajude http://www.devmedia.com.br/utilizando-css-media-queries/27085 Explica bem como funciona
Comment: Tenho pouca experiência, mas ... se você der um `debug($_SERVER);` e verificar o `'HTTP_USER_AGENT'`, não conseguirá verificar o tipo de sistema em que o site está rodando?

**Exemplo de saída:** `'HTTP_USER_AGENT' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0',`, nesse caso é um sistema `Ubuntu`. _**Ressucitando Post...**_
Answer: De maneira simples, você pode usar essa função para detectar se é mobile:
function detectar_mobile() {
 if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 || navigator.userAgent.match(/Windows Phone/i)
 ){
    return true;
  }
 else {
    return false;
  }
}

Ou usar algo mais profissional:
function detectar_mobile() {
  var check = false; //wrapper no check
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
}

EDIT
Solução para Tablets usando o detectmobilebrowsers.com:

Android tablets, iPads, Kindle Fires and PlayBooks are not detected by
  design. To add support for tablets, add |android|ipad|playbook|silk to
  the first regex.

EDIT 2
Outra opção (possivelmente a melhor opção) é utilizar o WURFL:
if (WURFL.is_mobile === true && WURFL.form_factor === "Smartphone") {
    // moblie
} else {
    //nao mobile
}

Só um detalhe sobre a licença dele:

You can use these services free of charge, as long as your website is
  publicly available and does not require fees or paid subscription to
  access.
Comment: Não vou julgar os votos, mas mesmo antes da sua resposta eu já ia comentar aqui que confiar no user-agent não funciona. Quanto à solução "profissional", tem isso na página: "Regex updated: 1 August 2014". Infelizmente usar o user-agent somente daria certo se realmente houvesse algum tipo de centralizador sempre atualizado. Lembrando ainda que cada OS de mobile hoje permite o uso de uma diversidade de browsers, cada um implementando user-agent com critério próprio. (por acaso fui ver sua recomendação pra ver se tinha alguma solução boa lá, pq realmente essa do mobile é um problema)
Comment: Mas foi aí mesmo que eu vi que faz quase 2 anos que nao é atualizado. Veja no pé da página "Regex updated: 1 August 2014" - Mais uma curiosidade: seu script não tá pegando o meu celular, um Nokia N900. Vou ver se o deles pega. UPDATE: o deles inclui o maemo.
Comment: Vou testar esse cara aí do edit2. Talvez por ter alguma fonte de renda, tenha mais chance de ser mais atualizado. Tem solução server-side tambem https://www.scientiamobile.com/page/wurfl-cloud, mas não achei o link. De qq forma, o forum é bem ativo https://www.scientiamobile.com/forum/viewforum.php?f=20
Comment: Gostaria de saber o porquê do -1
Comment: Não disse que era profissional e sim mais profissional. O site http://detectmobilebrowsers.com/ é mais confiável porque ele atualiza o regex.
Comment: Creio que até então não foi mais preciso atualizar, lembrando que este regex não tem suporte para tablet.
Answer: Não tente detectar se o dispositivo é móvel ou de mesa através do navegador, isso é menos confiável do que verificação de maioridade em entrada de site pornô. O próprio Chrome mobile tem uma opção pra se passar pelo Chrome desktop, e nem é uma opção avançada. Está no menu básico do aplicativo.
Se você tentar determinar se um dispositivo é mobile pelo user agent do navegador, a única coisa que você garantirá é que novos navegadores móveis não receberão a experiência móvel ao acessar o seu site.
Se você tentar determinar se o dispositivo é um celular pelas suas capacidades (i.e.: detectar se o dispositivo oferece suporte a toque), você terá resultados bizarros. Meu laptop, por exemplo, é sensível a toque. Imagine um site com layout de celular renderizado em uma tela de 15". Isso quando eu não plugo ele na televisão...
A forma correta de desenvolver páginas é ser agnóstico com relação ao tipo de dispositivo. Sirva layout com base na resolução, mas de forma que se ajuste automaticamente à janela sem precisar recarregar a página. Isso é possível com o bootstrap, por exemplo, por isso eu o recomendo.
Com relação a Javascript, detectar se o navegador é móvel é uma prática pior ainda. Só porque determinada funcionalidade tem problemas em um modelo de celular não quer dizer que terá os mesmos problemas em outro modelo, e vice-versa. Assim, de duas uma: ou você priva todos os usuários dos navegadores móveis atuais de algo que seria interessante, ou você serve funcionalidades potencialmente quebradas para todos. O melhor é determinar quais funcionalidades javascript servir com base nas capacidades do aparelho, não com base no nome do navegador. Existem bibliotecas que auxiliam bastante nisso. Eu recomendo modernizr.
Answer: Use screen.width para pegar a largura da tela
var largura = screen.width;

if( largura <= ? ) {

       //
}

Essas informações você precisa confirmar:

tablets e telefones tem a largura de 767 para baixo
Telefones tem a largura de 480 para baixo
Comment: eu não quero mudar a resolução e sim todo o conteúdo apresentado
Comment: Cara, ainda acho que o que passei resolve. Com screen.width você pega a largura da tela de quem esta acessando, com a informação da largura, você consegue saber se é um PC, Tablete ou celular! É assim que os sistemas de grids funciona, como o bootstrap, por exemplo. No caso estou falando de javascript, mas se for mexer só com css, você pode utilizar a mesma ideia, com mediaquery
http://www.w3schools.com/cssref/css3_pr_mediaquery.asp
Comment: como falei, eu quero mudar todo o conteúdo pra cada versão
Comment: Lucas, se a largura da tela for menor ou igual a 480, então é um celular, e você chama o conteúdo para celulares, caso contrario, você chama o conteúdo para desktop. Pelo o que você disse, seria isso. Caso não, tente explicar de outra forma.
Comment: @EdCesar, se eu tiver acessando de um computador e alterar a resolução do meu navegador para a resolução de um celular, o programa vai "mudar", conforme o que o Lucas quer fazer ... _**Ressucitando post...**_
Answer: Achei isto na web, testei e funcionou:

Onde esta "http://mobile.seusite.com" e so colocar o seu site ou Directory que quiser.


Render a view in the outlet after ajax response

Question: In my home page i have an oulet watchListView i just want to replace the outlet with the view i am getting after clicking the link "/watch_lists".
This is the code for application Layout/template

  {{outlet}}

 {{outlet watchListView}}

This is the code in application route
 this.resource('watchList', { path: '/watch_lists' });

This is the code in WatchList router
 Discourse.WatchListRoute = Discourse.Route.extend({
   redirect: function() { Discourse.redirectIfLoginRequired(this); },
   renderTemplate: function() {
     this.render('watch_lists', { into: 'application', outlet: 'watchListView' });
   }
 });

I Just want to add view created after the ajax call in the application template
Can anyone point me out where i am wrong.
Comment: Could you put together a jsFiddle?
Answer: Your view is loading into the outlet as soon as you move into this route, it just has no data until populated by the ajax call. Put logging in the renderTemplate function and you'll see this.
I would make the ajax call in your route's setupController method, populating the controller with the results of that call so you can display those results in your view. See the documentation on this method for more info.
In the AJAX callback, you should be populating the controller with the results of that call and have handlebars in the template pointing to the data you want to display. It will load automatically when the Ajax call comes back and populates the controller:
setupController:function(controller){
    someObj.AjaxCall(function(data){
        controller.set('data',data);
    }
}

You can watch controller properties in your watchList template with {{controller.data.property}} or {{{controller.data.htmlProperty}}} to render html.
If this is not helpful enough, post a jsfiddle that illustrates what you're currently doing.


JDK for android app development

Question: Im trying to get started with app development. Isnt this the corrent JDK if i want to use eclipse + android plugin?
Java SE Development Kit 7u5: http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1637583.html
When i try to install the android SDK tools it tells me that i dont have the correct JDK installed.
And yes, ive tried this already: Android SDK installation doesn't find JDK
Thanks
Comment: Did you try reading the requirements for the Java JDK version at the Android SDK site? Seems like that would be a better (and quicker) place to find the answer.
Comment: Happened to me each time I've installed it on Win 7 (x86 and x64).
If you've correctly set your JAVA_HOME env var, then when it says it cannot find any JDK, press back and then next again. I know... :)
Comment: @marceln Ok, where do i set the variable?
Comment: Here's a step-by-step post here: http://stackoverflow.com/questions/2619584/how-to-set-java-home-on-windows-7. If you haven't set it yet, then it may very well be the cause of your problems.
Comment: @marceln Allright, thanks for the link
Answer: Java 7 is not officially supported by the Android SDK at this time. Please use the latest version of the Java 6 JDK.
UPDATE: Java 7 is now supported.
Comment: JDK7 can be installed, and then the SDK will just use the level 6 API.I'm running it like that.
Comment: @CommonsWare: I would appreciate it if you can update your answer. It's not entirely correct in it's current form. Thanks.
Comment: I solved it by installing the 32 bit version, based on a comment in the thread that i linked. Please update this answer. Its working with JDK7 as marceln said
Comment: @marceln: Until such time as [the official system requirements](http://developer.android.com/sdk/requirements.html) say otherwise, Java 7 is not officially supported, and I have had multiple people report problems using Java 7 with the Android SDK. I have adjusted my answer to reflect the "officially supported" nuance. If you can get it to work and want to run that way, more power to you.
Comment: @CommonsWare: I got serious problem with jdk7, first of all ADT Bundle is not working with it since eclipse.ini parameters are not customized for jdk7. meanwhile after some quick fixes, eclipse is crashing repeatedly. However I always adore you for your books and detailed answers :)
Comment: @VSB: FWIW, I have been using JDK 7 for the past few months with Eclipse 3.8.1 on Ubuntu 13.04/13.10, with no issues (other than the typical sorts of Eclipse instabilities that I have had for years). And Xav indicated that Java 7 is officially supported, though I forget if the Web site has been updated to that end. And thanks for the kind words!
Comment: @CommonsWare: since i'm using Windows, we may have different experiences. Before JDK7 everthing with eclipse was fine:) I'm just trying to install JDK6u38 to rollback to good old days! my current eclipse is 4.2.1

JDK for android app development


How to get Scanner to read next line of numbers?

Question: I am new to java and programming. I have sort of a grasp on the concept but not entirely sure. This problem uses a scanner to read from another file to get information on amount of energy produced.

import java.util.Scanner;
import java.io.File;

public class HJUnit3
{
 public static void main(String[] args) throws Exception
 {
//   Scanner stdIn = new Scanner(System.in);
   Scanner stdIn = new Scanner(new File("energyProduced.txt"));
        stdIn.nextLine();
  double energy;
  energy = stdIn.nextLine();
   int systemsCost;  //Total Systems Cost
   double ttlEnergy;  //Total energy produced in a week
   double savingsWeek;  //Total savings for one week
   double savingsDay;  //Total savings for one day
   double recoupDay;  //Days to recoup
   double recoupYear; //Years to recoup
   final double electricCost = 0.085;

   systemsCost = (savingsWeek * energy);
   System.out.println("Total System Cost = $" + systemsCost );
   System.out.println("Total Energy Produced in one week" + (energy * 7) + "Kwh");
   savingsWeek = (ttlEnergy * electricCost);
   System.out.println("Total Savings for one week =" + savingsWeek);
   savingsDay = (savingsWeek / 7);
   System.out.println("Total Savings for one day =" + savingsDay);
   recoupDay = (systemsCost / savingsDay);
   System.out.println("Days to recoup cost(truncated)" + recoupDay);
   recoupYear = (recoupDay / 365);
   System.out.println("Years to recoup cost(truncated)");
 } // end main
} // end HJUnit3 class

It gives me this error "error: incompatible types: String cannot be converted to double
                energy = stdIn.next();"
and this "error: incompatible types: possible lossy conversion from double to int
   systemsCost = (savingsWeek * energy);"
What did I do wrong, not really sure.
EDIT
So I got the program to work but in the program produces only one set of answers from the .txt file but the file has more numbers and I'm not sure what to add to make it read the next line.

import java.util.Scanner;
import java.io.File;

public class HJUnit3
{
 public static void main(String[] args) throws Exception
 {
//   Scanner stdIn = new Scanner(System.in);
   Scanner stdIn = new Scanner(new File("energyProduced.txt"));
        stdIn.nextDouble();
  double energy;
  energy = stdIn.nextDouble();
   int systemsCost;  //Total Systems Cost
   double ttlEnergy; //Total energy produced in a week
   double savingsWeek; //Total savings for one week
   double savingsDay;  //Total savings for one day
   double recoupDay;  //Days to recoup
   double recoupYear; //Years to recoup
   final double electricCost = 0.085;
//

   ttlEnergy = (energy * 7);
   savingsWeek = (ttlEnergy * electricCost);
   savingsDay = (savingsWeek / 7);
   systemsCost = (int) (savingsWeek * energy);
   recoupDay = (systemsCost / savingsDay);
   recoupYear = (recoupDay / 365);

 System.out.println("Total System Cost = $" + systemsCost );
 System.out.println("Total Energy Produced in one week" + (ttlEnergy) + "Kwh");
    System.out.println("Total Savings for one week =" + savingsWeek);
    System.out.println("Total Savings for one day =" + savingsDay);
    System.out.println("Days to recoup cost(truncated)" + recoupDay);
    System.out.println("Years to recoup cost(truncated)" + recoupYear);
 } // end main
} // end HJUnit3 class

The .txt file is like a bunch of numbers going down a column
Comment: @azurefrog: Or directly use `stdIn.nextDouble()`
Comment: stdIn.next() returns a String. You're trying to assign it to a variable of type double. That's not possible, because a String is not a double. That's what the first error message means. The second means that you're trying to assign a double, which has a decimal part and is potentially very large, to a variable of type int, which does not have any decimal part and has a more limited range of values. That's also not possible, at least not without a cast informing the compiler that you understand what you're doing and accept to lose the precision. Now, take time thinking about what you must do.
Comment: Please change your title to reflect the actual issue.
Comment: Java cannot magically convert types for you.  If you want to change a `String` into a a `Double`, use `Double.parseDouble()`.
Comment: What would I need to replace?
Comment: @Marvin Eh... I'm not a huge fan of doing it that way, since it's easy to run into [this problem](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo).  I prefer to read the line and then explicitly parse things.
Comment: @azurefrog: Agreed, I've removed the "even better" part.
Answer: The compiler says that a String cannot be converted into a Double. That's the problem. You're saying double energy = stdIn.nextLine(), but Scanner#nextLine() returns a String. Instead, you either want to convert it to a Double (Double.parseDouble(String)), or you could call stdIn.nextDouble(). http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Answer: You may need to brush up on your "datatypes" skills, because Java is a strongly typed language :-).
The error
error: incompatible types: String cannot be converted to double energy = stdIn.next();

means that the value returned by stdIn.next() has a datatype of "string", which does not match the datatype of the variable "energy", because "energy" is not a string. It is a "double".
You convert the value returned by stdIn.next() to a double by using
energy = Double.parseDouble(stdIn.next());

Beware that this will throw an exception when the string returned by stdIn.next() characters such as alphabets.
For your second error, why do you want systemsCost variable to be an integer? Do you want it to always be a rounded number? If so, then you need to round the result of the expression "savingsWeek * energy" to the nearest whole number, and then convert it into an integer. On the other hand, if you don't necessarily want systemsCost to be an integer, just declare it as a double.
Comment: "strongly typed" Do you mean statically typed?
Comment: I meant "strongly" typed. In simpler terms, it means that all variables in Java have predefined data-types, and, unlike "loosely" typed languages, you can not randomly assign a variable with one data-type to a variable with another data-type. For example, in JavaScript, you can do var x = 1.2 + " hi"; but you can't do that in Java because 1.2 is a double and " hi" is a string. adding them together makes no sense.
Comment: Okay. I thought that was called statically typed, but I may be wrong.


Find $Gal(\mathbb{Q}(e^{2\pi i/6},e^{2\pi i / 10}) / \mathbb{Q})$

Question: First I need to show that the extension $\mathbb{Q}(e^{2\pi i/6},e^{2\pi i / 10}) / \mathbb{Q}$ is actually Galois extension, and then I need to find the group itself.
Denote $\alpha = e^{2\pi i/6} $, $\beta = e^{2\pi i / 10}$.
I guess the first step is to find the minimal polynomial of $\alpha,\beta$, but I'm not really sure how to do it. I know that the following polynomials are zeroed by $\alpha, \beta$:
$$\sum_{i=0}^{29} x^i,\quad (\sum_{i=0}^5 x^i) \cdot (\sum_{i=0}^9 x^i)$$
Both are reducible, but I don't know how can I reduce them further.
Comment: **Hint:** Show: $$\mathbb Q(\alpha,\beta)=\mathbb Q\left(e^{2\pi i/30}\right)$$
Comment: Hint 1: $\alpha^3 = -1$ and $\beta^5 = -1$.\
Hint 2: Since $\alpha, \beta \notin \mathbb{R}$ the minimal polynomial of $\alpha$ is $\mu_\alpha(X) = X^2-X+1$ and the minimal polynomial of $\beta$ is $\mu_\beta(X) = X^4-X^3+X^2-X+1$. To see that $\mu_\beta$ is indeed irreducible note that $\mu_\beta(-X) = \phi_5(X)$.
Answer: Disclaimer: This answer uses cyclotomic field theory.
Let $K_n$ denote the $n$th cyclotomic field.
Then your field extension is $K_6 K_{10}$ (compositum).
Then $K_6 K_{10} = K_{\operatorname{lcm}(6,10)} = K_{30}$, so its Galois group is $(\Bbb Z/30\Bbb Z)^\times$.


How do I redirect/save the console to a file and keep it visible on the screen?

Question: I want to save a program's output (stdout) to a file but still be able to see the output on the screen in realtime.
I need a solutions for both Linux and Windows.
Answer: In Linux, you can use the tee utility.
In Windows, PowerShell contains a tee cmdlet. For cmd, you will need to download and install a separate utility.
Answer: On Linux and similar systems:
program | tee filename

The tee program sends anything that comes into its standard input to its standard output (like cat) and also writes it to the specified file.
Another way to get the same effect would be
program >filename 2>/dev/null &
tail -f filename

This runs the program in the background, redirecting its standard output to the file, then tail -f lets you follow data being written to the file in real time (or nearly so, maybe a fraction of a second delay). The 2>/dev/null makes the standard error stream disappear so that it doesn't interfere with the output of tail -f.
Answer: Linux: command | tee logfile
Windows: Install cygwin, then run: command | tee logfile
Answer: For Windows you can do this:

dir > directory.txt & type directory.txt

where you'd replace dir by your application.
If the output scrolls too fast use:

dir > c:\directory.txt & type c:\directory.txt | more

However, I don't think this would display the contents of the file in real time. You'd have to wait until the process had finished.
Answer: In Windows, you can use tee if you download the GnuWin32 version of it. It's the same as the linux app and comes from the coreutils package.
One word of caution, though: tee has its own return code, so you won't be able to notice errors from the process piped to it (unless you're in linux, then there are ways around it).