How to use I18n.locale with Hash#dig

Question: I have the following Hash:
h = {
      forms: {
        version1: {
          href: {
            en: 'https://form1_en.example.org',
            de: 'https://form1_de.example.org'
          }
        },
        version2: {
          href: {
            en: 'https://form2_en.example.org',
            de: 'https://form2_de.example.org'
          }
        }
      }
    }

I am trying to access verion1 href for the user's current locale. So what I do is:
Proj.config.forms.dig('version1', 'href', I18n.locale)

However, this results in nil even though I18n.locale returns en.
This, however, works perfectly fine and returns the correct href.
Proj.config.forms.dig('version1', 'href', 'en')

What am I doing wrong here? Can I not use I18n.locale in connection with hash#dig?
Comment: I edited the presentation of the hash in your example to make it a valid Ruby object. Doing so makes its structure more clear and avoids the need for each reader who wishes to cut and paste your code to do what I did: convert it into a valid Rufy object. I also assigned a variable (`h`) to the hash, allowing readers to refer to the hash in comments and answers as simply `h`, without having to define it. I suggest that whenever you give an example you ensure all inputs are valid objects and assign a variable to each. You could of course use a different format for writing the hash.
Comment: Just a comment about the use of [Hash#dig](https://ruby-doc.org/core-2.7.0/Hash.html#method-i-dig) (and its close cousins [Array#dig](https://ruby-doc.org/core-2.7.0/Array.html#method-i-dig) and [Struct#dig](https://ruby-doc.org/core-2.7.0/Struct.html#method-i-dig), all of which made their debut in Ruby v2.3.). This method is for use where a key of a nested hash may or may not be present. For example, instead `h.key?(:a) && h[:a].key?(:b) && h[:a][:b].key?(:c) ? h[:a][:b][:c] : nil`, it allowed one to write `h.dig(:a,:b,:c)`. `dig` should *not* be used, however, when...
Comment: ...all the keys in the chain should be present. In the above example, suppose `h` should have a key `:a`, `h[:a]` should have a key `:b`, `h[:a][:b]` should have a key `:c` and `h = {a: {t: {c: 'cat'}}}`, meaning that we have a bug in our code (because `h[:a]` does not have a key `:b`). Then `x = h.dig(:a,:b,:c) #=> nil`. You might raise an exception if `x` is not `nil`, in which case you have to track down the bug. If you don't test if `x` is not `nil` the bug will be buried more deeply. On the other hand, suppose `h[:a][:b][:c] #=> nil` were valid when all the nested keys were present?...
Comment: ...That would present a potentially nasty problem. By contrast,`h[:a][:b][:c] #=> NoMethodError (undefined method '[]' for nil:NilClass)`, which is *exactly what we want*. We still have to find the bug, but no extra code is needed to indicate that we have one.
Answer: I think that possible problem might be if I18n.locale returns :en instead of 'en'. In this case you can solve it in a few ways:
Proj.config.forms.dig('version1', 'href', I18n.locale.to_s)

or
Proj.config.forms.with_indifferent_access.dig('version1', 'href', I18n.locale)

Comment: Thank you for that quick response! That works perfectly fine. Will mark this as correct answer as soon as I am able to :)

How to use I18n.locale with Hash#dig


Unable to change the html of views field using theming preprocess function

Question: Basically
1. I am trying to edit a view.
  --> For that I have copied the views-view.tpl.php file from the views module's theme folder and placed it into my custom templates  folder present inside theme folder.
--> Also I have renamed the file views-view.tpl.php file to views-view-[VIEW_NAME].tpl.php where [VIEW_NAME] is just placeholder for actual view name.
--> After this I have cleared the caches.
--> Now In my custom theme function I have a template.php file.
--> In that template.php file, I am using [THEME_NAME]preprocess[VIEW_NAME] function that is my_theme_preprocess_view_name(&$vars) function
When I check the vars object I have found the following place where I need to put the html for the field's html to change which is as follows :
<code>$vars['view']->result[$key]->field_name[0]['rendered']['#markup']
</code>
which contains the html of the field I want to alter .So Using this vars variable I inserted the html as follows :
 <code>$vars['view']->result[$key]->field_name[0]['rendered']['#markup'] = $html;</code>
Where html is the variable which contains the altered html value for the field .
 --> After this  I again clear the caches.
-->But the still the html value of the field does not change.
Can you please help me out on this ...
I tried doing this using hook_views_pre_render(&$vars) inside a custom module. It works there but I wanted all the code inside the template.php file as I have read that hook_views_pre_render() is not the proper way to alter the field value.
Answer: Views are complex in the way they render.
The best thing to do is override things at the right level.
If you want to override things at the view level, for example the title of your view, you would use views-view.tpl.php; if you want to override something at the row level, you might use views-view-fields.tpl.php; if you want to override an individual field, you would likely use views-view-field.tpl.php.
Basically, if you look in the views-view.tpl.php file, you will see that individual fields are not being printed, which indicates that this is probably not the place to override that.
In your case try using views-view-field.tpl.php.
Check out the "Theme: Information" section of your view edit screen for suggestions on what to name your file along the lines of views-view-field--view-name--field-name.tpl.php
As for whether or not it should be in the theme or in a module, a good question to ask is: If I change themes, would I want this same change in the new theme? If so, it is more functional and probably should go in a module; if the answer is no, it probably should go in the theme as it is specific to that theme.
That's good as a basic guide, anyway; sometimes there are exceptions to rules.
Comment: That's it: If you need that functionality independently from the theme currently used, the code should go in a module. That is well said.


Imagem proporcional ao sistema utilizado. Posso continuar fazendo assim?

Question: tentei muitas formas e não obtive êxito. Então fui por conta própria e achei uma solução.
Gostaria de saber se posso continuar usando assim ou se terei problemas com isso...
Bem, no browser do notebook a imagem fica perfeitamente normal assim:, em um código HTML:

Mas quando acesso do celular a página, fica muito grande. Tentei fazer CSS com width = 100% e auto e não funcionou (quando ficava boa no celular, não ficava no browser do notebook e vice-versa).
Aí fiz uma funçãozinha PHP que identifica se a página está sendo acessada pelo notebook ou pelo celular.
Dessa forma está funcionando perfeitamente, mas quero saber se terei problemas.
Código em PHP na página:
<?php
  if ($utilizador == "celular") {
   echo "";
}
  else {
   echo "";
}
?>

Dessa forma fica perfeito tanto no celular (com o width) tanto no browser do navegador, sem o width.
Posso continuar fazendo assim?
Função para verificar:
<?php
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$ipad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
$symbian =  strpos($_SERVER['HTTP_USER_AGENT'],"Symbian");

if ($iphone || $ipad || $android || $palmpre || $ipod || $berry || $symbian == true) {
    $utilizador = "celular";
}
else {
 $utilizador = "pc";
}
?>

Answer: Acho desnecessário quando o CSS já oferece propriedades para isso.
Além de width, CSS também oferece max-width e min-width, ou seja, largura máxima e largura mínima. Combinando essas propriedades da seguinte forma:

Você terá uma imagem que ocupa 100% da largura de seu elemento pai, porém se essa largura for extrapolar 500px, a imagem permanece com o máximo de 500px de largura.
Dessa forma você tem a imagem ocupando a largura máximo no seu celular, mas em telas maiores a largura é limitada para não ficar com proporções exageradas.
Comment: Funcionou perfeitamente. Irei substituir a função PHP por essa! Muitíssimo obrigado!
Comment: @Felipe, esqueci de mencionar, mas você também pode usar `auto` como `max-width`. Acredito que isso seria mais parecido o seu layout inicial.


"Perfecting" an endomorphism in a category

Question: Let $\mathcal{C}$ be a complete category and suppose $f: X \to X$ is an endomorphism in $\mathcal{C}$. Associated to $f$ is an inverse system,
$$X_\bullet: \dots \to X \to X \to X \to X,$$
where every arrow is $f$, and we can form a map of inverse systems $f_\bullet: X_\bullet \to X_\bullet$, again just via $f$. Taking inverse limits, we arrive at $\hat{f}: \hat{X} \to \hat{X}$.
In any concrete category where inverse limits can be represented as sets of coherent sequences, it's easy to see that $\hat{f}$ is an epimorphism. Indeed, given a coherent sequence $(x_0, x_1, \dots)$, we have that
$$\hat{f}(x_1,x_2,\dots) = (f(x_1),f(x_2),\dots) = (x_0,x_1,\dots).$$

Is it always true that $\hat{f}$ is an epi? If not, what counter-examples exist? What kind of conditions could be imposed on $\mathcal{C}$ to ensure $\hat{f}$ is an epi?

It seems like this holds for a large class of categories (e.g. all complete abelian categories, by Freyd–Mitchell), so I'm curious to see just how general it really is.
Answer: In fact, you can prove that in the category of sets this $\hat{f}$ is even an isomorphism : indeed, in that category $\hat{X}$ can be represented as the set of coherent sequences you mention, and you have a map
$$\gamma:\hat{X}\to \hat{X}:(x_0,x_1,x_2,\dots)\mapsto (x_1,x_2,\dots).$$
You have proved already that $\hat{f}\gamma=id_{\hat{X}}$, and it's easy to see that $\gamma \hat{f}=id_{\hat{X}}$ as well.
Now using this fact, you can prove that in fact $\hat{f}$ must be an isomorphism in any complete category. Indeed, by the Yoneda lemma it is enough to prove that $\hat{f}^* : Hom_\mathcal{C}(\_, \hat{X})\to Hom_\mathcal{C}(\_, \hat{X})$ is a natural isomorphism; but for this it is enough to prove that $\hat{f}^* : Hom_\mathcal{C}(Z, \hat{X})\to Hom_\mathcal{C}(Z, \hat{X})$ is an isomorphism for all $Z$.
But the universal property of the limit tells you that for all $Z$, $Hom_\mathcal{C}(Z, \hat{X})$ must be (naturally isomorphic to) the limit of
$$\dots Hom_\mathcal{C}(Z, X)\to Hom_\mathcal{C}(Z, X)\to Hom_\mathcal{C}(Z, X)$$
(where every map is $f^*$) in the category of sets, and you can prove that $\hat{f}^*=\widehat{f^*}$ which is thus an isomorphism.
Comment: Here is a fun example: let $X = S^1$ in the category of compact Hausdorff abelian groups, and let $f : X \to X$ be given by $z \mapsto z^p$. Then $\hat{X}$ is a group called the $p$-adic solenoid; it can be thought of as the Pontryagin dual of $\mathbb{Z}[1/p]$ (which arises via the dual construction of a colimit rather than a limit in abelian groups). The identification of the Pontryagin dual gives some indication of what this process has to do with attempting to invert $f$.
Comment: I presume in your final indented line you should write $X$ not $\hat{X}$ in the homs? But thanks for the enlightening answer.
Comment: The map $x \mapsto x^p$ (and the process of "perfecting" an $\mathbb{F}_p$-algebra it's defined on) was indeed what inspired this question!


24 bit audio processing

Question: I have written some code that read data from a audio buffer based on bit depth, processes it and writes it back to same buffer. I have to handle 16 and 24 bit depths. code for 16 bit works fine but for 24 bit it does not.
Here is what I am doing for each sample for 24 bit data:
int data = 0;

//read data from buffer
RtlCopyMemory (&data, ((char*)Source) + head, 3);

//scale data for integer

data = data << 8;

//data processing

data = data * m_CurOutVolLevel;

//scaling down the data
data = (data >> 8);

RtlCopyMemory (((char*)Source) + head, &data, 3);

but the output is not proper. Can someone point what's wrong here??
Thanks
Thanks for the suggestions. I implemented what you guys suggested but still there is some flaw:
unsigned __int64 newData;
unsigned char* s = ((unsigned char*)Source) + head;
unsigned int data = ((unsigned int)s[0] << 8) | ((unsigned int)s[1] << 16) |((unsigned int)s[2] << 24);

// data processing
newData = (unsigned __int64)(data * m_pMiniport->m_CurOutVolLevel);
//divide this by 2 to the power 16
newData = (newData >> 16);

// store back
s[0] = (unsigned char)((newData >> 32)  & 0xff);
s[1] = (unsigned char)((newData >> 40) & 0xff);
s[2] = (unsigned char)((newData >> 48) & 0xff);

does anyone see problem with above code?
Thanks, Annie
Comment: The multiplication will cause overflow.  Don't scale the data.
Comment: Are you compiling in C or C++?
Answer: Well, you use an int, if it is on a 32-bit machine this will typically be 32 bits. If data is 24 bits, shifting it will mean you can even use the highest order bit. This results in two things:

A first possible overload from the shift, as your int is signed, if bit "24" (highest order bit in your data) is 1, bit 32 in the result will be 1 and it will become a negative number.
A second possible overflow from the multiplication, suppose the above doesn't happen, it is very likely that you now will overgrow the boundaries of a 32 bit number. Suppose bit 23 is set, so your number stays possitive, if m_curOutVolLevel is even only as low as 2, this is equal to an exta bit shift and again you're overflowing. Much more likely you'll even lose bits because the number can't be stored in 32 bits anymore.

Edit: possible solution, if this is the problem: use uint64_t from stdint.h
Edit2: Also note that your code can give problem with endianness as you simply encode the int into a byte stream (unless RtlCopyMemory handles this, which I doubt).
Answer: You can't modify parts of an int and just expect the code to work (let alone be portable).
Assuming the data is stored in unsigned little-endian order you can access it like this:
unsigned char* s = ((unsigned char*)Source) + head;
uint32_t data = ((uint32_t)s[0] << 8) | ((uint32_t)s[1] << 16) | ((uint32_t)s[2] << 24);
// use data
// store back
s[0] = (unsigned char)((data >> 8) & 0xff);
s[1] = (unsigned char)((data >> 16) & 0xff);
s[2] = (unsigned char)((data >> 24) & 0xff);

But this will depend on how the data is stored.
Answer: You need to be very careful about endianness issues with code like this, byte-copying into a multi-byte single variable is not safe.
It's better to read one byte at a time, so that you can express in endianness-proof way where in the value you expect each byte to land. This, of course, requires you to think about the byte-ordering of the multi-byte 24-bit values in the source data, instead.
Answer: Generalizing @user786653 answer for multiple bit depths.
uint32_t sample = 0;
for (int i = 0; i < bit_depth / 8; i++) {
    sample = ((uint32_t)source[i] << (i * 8)) | sample;
}

24 bit audio processing


Prove the coefficients of $\prod_{k=2}^{n+1}(1-x^{a_k})$ are $0$, $1$, or $-1$ where $(a_k)$ are Fibonacci numbers.

Question: Given $a_1 =1,a_2=1, a_{n+2}=a_{n+1}+a_n$, prove that for $n\geq 2$, all coefficients of polynomial $$A(x)=\prod_{k=2}^{n+1}(1-x^{a_{k}})$$ are $0$, $1$, or $-1$.
I tried induction. I don't think it works. The hypothesis will be too weak. I think if we want to prove it by induction, we need to prove a stronger proposition, but I can't find it.
Comment: I have a hunch Zeckendorf's theorem could be useful. https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem
Comment: Check https://www.fq.math.ca/Scanned/34-4/robbins.pdf Effectiveley in notation used in the paper, we seek $a(n)$ when $\{u_n\}=\{F_{n+1}\}$
Comment: @user2661923 When it is true for n=N, the hypothesis will be "n=N, all coefficients are 0,1, or -1", it is not enough. There is some "structure" for these coefficients 0,1,or -1. The hypothesis will be too weak.
Comment: @Aryabhata any proof
Comment: What do you mean by "coefficients of $\prod_{k=2}^{n+1}(1-x^{a_{k}})$"?
Comment: @user I mean all coefficients of the polynomial.
Comment: Have you tried induction? If you have, where did you get stuck?
Comment: @EricSun please show your work.  In particular, show an attempt to verify that the conjecture is true for n=3, n=4, and n=5.  Then show an attempt to verify that if the conjecture is true for n=N, then it will be true for n=N+1.
Comment: OK, let us expand the given polynomial. We get $1\pm$ products of the shape $$\displaystyle x^{a_{k_1}}\cdot x^{a_{k_2}}\cdot \dots$$ and then we have to collect the terms with signs. Let us solve a simple combinatorial problem. Let $n+1$ be $10$, so we have the factors $(1-x^1)$, $(1-x^2)$, ... , $(1-x^{55})$. Which monomials contribute in the product to $x^{77}$?
Comment: @EricSun I agree that the actual proof may or may not involve induction.  However, the procedure detailed in my previous comment is **exactly** what my **first attack** of the problem would be.  If the conjecture is true, there must be a reason that it is true.  Exploring simple cases is the **tried and true** method of developing intuition around the problem and looking for a **pattern** that is **causing the conjecture to be true**.
Comment: So, what is your actual question? You want an induction proof? Or any proof will do?
Comment: I think the most interesting part in this question would be the use of the Fibonacci sequence and it's properties because the powers of x are very closely related to it
Comment: @Macavity: Interesting find! However, I don't think we are quite looking for $a(n)$, which are what happen when we look at the infinite product. $a(n)$ will of course form the initial coefficients of each finite product, so are a special case of the original post.
Answer: Yufei Zhao, The coefficients of a truncated Fibonacci power series, Fibonacci Quarterly, $\mathbf{46/47}\,(2008/2009)$, no. $1$, $53$-$55$, has the following clever inductive proof, which does indeed use a stronger hypothesis.
Say that a polynomial is timid if each of its coefficients is $-1,0$, or $1$; we want to show that $A_n(x)$ is timid for each $n\ge 1$, where
$$A_n(x)=\prod_{k=2}^{n+1}\left(1-x^{F_k}\right)\,.$$
We will use auxiliary polynomials $B_n(x)$ and $C_n(x)$ for $n\ge 1$:
$$\begin{align*}
B_1(x)&=1-x^{F_2}-x^{F_3}=1-x-x^2\\
C_1(x)&=1+x^{F_1}-x^{F_3}=1+x-x^2\\
B_n(x)&=A_{n-1}(x)\left(1-x^{F_{n+1}}-x^{F_{n+2}}\right)\text{ for }n\ge 2\\
C_n(x)&=A_{n-1}(x)\left(1+x^{F_n}-x^{F_{n+2}}\right)\text{ for }n\ge 2\,.
\end{align*}$$
Clearly $A_1(x)=1-x$, $B_1(x)$, $C_1(x)$, $A_2(x)=1-x-x^2+x^3$, $B_2(x)=1-x-x^2+x^4$, and $C_2(x)=1-x^2-x^3+x^4$ are timid. Suppose that $n\ge 3$, and $A_k(x),B_k(x)$, and $C_k(x)$ are timid for $1\le k<n$; we want to show that $A_n(x),B_n(x)$, and $C_n(x)$ are timid.
$$\begin{align*}
A_n(x)&=A_{n-3}(x)\left(1-x^{F_{n-1}}\right)\left(1-x^{F_n}\right)\left(1-x^{F_{n+1}}\right)\\
&=A_{n-3}(x)\left(1-x^{F_{n-1}}-x^{F_n}\color{red}{-x^{F_{n+1}}+x^{F_{n-1}+F_n}}+x^{F_{n-1}+F_{n+1}}+x^{\color{blue}{F_n}+F_{n+1}}-x^{F_{n-1}+F_n+F_{n+1}}\right)\\
&=A_{n-3}(x)\left(1-x^{F_{n-1}}-x^{F_n}+x^{F_{n-1}+F_{n+1}}+x^{\color{blue}{F_{n-2}+F_{n-1}}+F_{n+1}}-x^{F_{n-1}+F_n+F_{n+1}}\right)\\
&=A_{n-3}(x)\left(1-x^{F_{n-1}}-x^{F_n}\right)+x^{F_{n-1}+F_{n+1}}A_{n-3}(x)\left(1+x^{F_{n-2}}-x^{F_n}\right)\\
&=B_{n-2}(x)+x^{F_{n-1}+F_{n+1}}C_{n-2}(x)\,.
\end{align*}$$
Now
$$\deg B_{n-2}(x)=\sum\limits_{k=2}^{n-2}F_k+F_n=(F_n-F_1-1)+F_n=2F_n-2\,,$$
and
$$\begin{align*}
(F_{n-1}+F_{n+1})-(2F_n-2)&=(F_{n-1}-F_n)+(F_{n+1}-F_n)+2\\
&=-F_{n-2}+F_{n-1}+2\\
&=F_{n-3}+2\\
&>0\,,
\end{align*}$$
i.e., $F_{n-1}+F_{n+1}>\deg B_{n-2}(x)$, so $B_{n-2}(x)$ and $x^{F_{n-1}+F_{n+1}}C_{n-2}(x)$ have no powers of $x$ in common. Since $B_{n-2}(x)$ and $x^{F_{n-1}+F_{n+1}}C_{n-2}(x)$ are both timid, this implies that $A_n(x)$ is timid as well.
We can use a similar argument to show that $B_n(x)$ is timid:
$$\begin{align*}
B_n(x)&=A_{n-2}(x)\left(1-x^{F_n}\right)\left(1-x^{F_{n+1}}-x^{F_{n+2}}\right)\\
&=A_{n-2}(x)\left(1-x^{F_{n+1}}\color{red}{-x^{F_{n+2}}}-x^{F_n}\color{red}{+x^{F_n+F_{n+1}}}+x^{F_n+F_{n+2}}\right)\\
&=A_{n-2}(x)\left(1-x^{F_n}-x^{F_{n+1}}\right)+x^{F_n+F_{n+2}}A_{n-2}(x)\\
&=B_{n-1}(x)+x^{F_n+F_{n+2}}A_{n-2}(x)\,,
\end{align*}$$
where $\deg B_{n-1}(x)=2F_{n+1}-2<F_n+F_{n+2}$, so $B_{n-1}(x)$ and $x^{F_n+F_{n+2}}A_{n-2}(x)$ have no powers of $x$ in common. Since both are timid, so is their sum, $B_n(x)$.
Finally,
$$\begin{align*}
C_n(x)&=A_{n-2}(x)\left(1-x^{F_n}\right)\left(1+x^{F_n}-x^{F_{n+2}}\right)\\
&=A_{n-2}(x)\left(1\color{red}{+x^{F_n}}-x^{\color{green}{F_{n+2}}}\color{red}{-x^{F_n}}-x^{2F_n}+x^{\color{brown}{F_n+F_{n+2}}}\right)\\
&=A_{n-2}(x)\left(1-x^{\color{green}{2F_n+F_{n-1}}}-x^{2F_n}+x^{\color{brown}{2F_n+F_{n+1}}}\right)\\
&=A_{n-2}(x)-x^{2F_n}A_{n-2}(x)\left(1+x^{F_{n-1}}-x^{F_{n+1}}\right)\\
&=A_{n-2}(x)-x^{2F_n}C_{n-1}(x)\,,
\end{align*}$$
where $\deg A_{n-2}(x)=\sum\limits_{k=2}^{n-1}F_k=F_{n+1}-2$, and
$$\begin{align*}
2F_n-(F_{n+1}-2)&=F_n+(F_n-F_{n+1})+2\\
&=F_n-F_{n-1}+2\\
&=F_{n-2}+2\\
&>0\,.
\end{align*}$$
Thus, $\deg A_{n-2}(x)<2F_n$, $A_{n-2}(x)$ and $x^{2F_n}C_{n-1}(x)$ are timid and have no powers of $x$ in common, so $C_n(x)$ is timid. This completes the induction, and we conclude that $A_n(x)$ is timid for each $n\ge 1$.
Note that we get for free the result that when
$$\begin{align*}
\prod_{n\ge 2}\left(1-x^{F_n}\right)&=(1-x)\left(1-x^2\right)\left(1-x^3\right)\left(1-x^5\right)\left(1-x^8\right)\ldots\\
&=1-x-x^2+x^5+x^7-x^8+x^{11}-x^{12}-x^{13}+x^{14}+\ldots
\end{align*}$$
is expanded as a formal power series $\sum\limits_{n\ge 0}a_nx^n$, $a_n\in\{-1,0,1\}$ for each $n\ge 0$: the coefficient $a_n$ of $x^n$ depends only on the factors $1-x^{F_k}$ with $F_k\le n$, so it is equal to the coefficient of $x^n$ in $A_k(x)$ for all $k$ such that $F_{k+1}\ge n$.
By the way, the coefficients $a_n$ have a nice combinatorial interpretation. Let $r_E(n)$ ($r_O(n)$, respectively) be the number of partitions of $n$ into an even (odd, respectively) number of distinct parts drawn from the set $\{F_k:k\ge 2\}$; then $a_n=r_E(n)-r_O(n)$, since each partition of $n$ into an even number of parts contributes a term $x^n$, and each partition into an odd number of parts contributes a term $-x^n$. (The coefficient of $x^n$ in $A_m(x)$ has a similar interpretation with the sizes of the parts limited to the set $\{F_2,\ldots,F_{m+1}\}$.)
Federico Ardila, The coefficients of a Fibonacci power series, Fibonacci Quarterly, $\mathbf{42}\,(2004)$, no. $3$, $202$-$204$, makes use of this interpretation to prove a recurrence that allows the $a_n$ to be computed quickly and easily in blocks of the form $[F_m\le n<F_{m+1}]$.
Two final observations:

The sequence $\langle 0,1,2,4,7,8,11,\ldots\rangle$ of exponents of non-zero terms of the power series $\sum_{n\ge 0}a_nx^n$ is OEIS A151661.

For $n\ge 1$ let $t_n$ be the number of non-zero terms in $A_n(x)$ then $t_n=2a(n)$, where $a(n)$ is given by OEIS A104767. (This follows from the comment there by Michael Somos.) Thus, $t_1=2$, $t_2=4$, $t_3=6$, and $t_n=2t_{n-1}-2t_{n-2}+2t_{n-3}$ for $n\ge 4$.


How to split on two string delimters

Question: How would I split a string based on two string delimiters like " of " and " in ".
For example, the string:
"dogs in Toronto of Canada"

would transform into the array:
["dogs", "Toronto", "Canada"]

Comment: Welcome to SO; here you find something on [ask]. It would be a good starting point to post what you tried so far, showing us that you did some research and attempts before posting.
Comment: Besides "[ask]", please read https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ and http://catb.org/esr/faqs/smart-questions.html
Answer: You can use String#split with regex:
"dogs in Toronto of Canada".split(/\sof\s|\sin\s/)
=> ["dogs", "Toronto", "Canada"]

Comment: Also: `/\b(of|in)\b/`
Comment: @tadman, I've just transformed into regex original delimiters with spaces (" or ", " in ").
Comment: `"of dogs in Toronto".split(/\sof\s|\sin\s/) #=> ["of dogs", "Toronto"]` vs `"of dogs in Toronto".split(/\b(?:of|in)\b/) #=> ["", " dogs ", " Toronto"]`.
Comment: @tadman, as you know well, you need a non-capture group: `/\b(?:of|in)\b/`.
Comment: @CarySwoveland I put in the non-capturing part by habit, then removed it thinking it'd be more concise and require less explanation. It is necessary, you're right.
Comment: Speaking of Toronto, "Go Raptors!".
Answer: Here's a more general-purpose one:
dogs.split(/\b\s*(?:of|in)\s*\b/)

There's a lot of cruft in there, but it handles irregular spacing, of appearing at the start or end of the phrase, and so on.
You can also try this which is even more adaptable at the expense of legibility:
splits = %w[ of in at on ]
pattern = Regexp.new('\b\s*%s\s*\b' % Regexp.union(splits))

dogs.split(pattern).reject(&:empty?)

How to split on two string delimters


Add files to git when directory already added

Question: I know this is strange, because git shouldn't keep empty directories. This is what I did:
git add directory
git commit

In directory there are files, which I also want to add, but only some of them. However, none files were added, and I can't add any now.
When I clone repository to different location, I can clearly see that directory is empty.
When I try to add file in directory to git like this:
git add directory/file

I get an error fatal: Path 'directory/file' is in submodule 'directory'
How can I add this files?
Answer: This is not an empty directory, this is a submodule. Read ProGit: Submodules and man git-submoule on how to handle them.
Especially: If you clone a repository with submodules, you should init the submodules too
# git clone ...
git submodule init
git submodule update

Answer: As mentioned, this is a submodule. The empty directory needs to be in the containing (parent) repo. The submodule has it's own clone url.
On the clone, issue
git submodule update --init

And you're good to go (provided you have access to the clone url of the submodule)
Comment: I think it's confusing to refer to a repository as "master", given its standard use for your main branch in git :)  Also, in the cloned repository you need to do `git submodule update --init` or you'll get an error saying the submodule hasn't been initialized.
Comment: Ah, I do this not often enough to remember the init; I bet it's something that the `update` will tell me everytime :)


dynamic memory allocation in c throws an error for a certain size

Question: I'm trying to create an array (dynamically) and populate it with random numbers.
I'm on Linux. The program compiles without errors. This is the C code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void create_array(int **, int);
void populate_array(int *X, int size, int low, int high);
void display_array(int *X, int size);

int main()
{
    int *A = NULL;
    int size = 7;
    int low = 10;
    int high = 1000;
    create_array(&A, size);
    populate_array(A, size, low, high);
    display_array(A, size);
    return 0;
}

void create_array(int **X, int size)
{
    *X = (int *)(malloc(size));
}

void populate_array(int *X, int size, int low, int high)
{
    srand(time(0));
    for (int i = 0; i < size; ++i)
    {
        *(X + i) = low + rand() % (high + 1 - low);
    }
}

void display_array(int *X, int size)
{
    for (int i = 0; i < size; ++i)
    {
        if (i % 10 == 0)
            printf("\n");
        printf("%d\t", *(X + i));
    }
    printf("\n");
}

However, when I run it, I get the following error:
malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
This error is only produced for size = 7. For lower values it's all good. But for higher values, it's another story! Output for size = 20:

455     526     335     719     907     695     1041    0       154481972       154546741
154481459       154743095       154482992       875836721       960049720       926419250       909326389       154219063       808465977       842479924

In contrast, the same program (almost) in C++ gives me the expected output. Here's the code:
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void create_array(int *&, int);
void populate_array(int *X, int size, int low, int high);
void display_array(int *X, int size);

int main()
{
    int *A;
    int size = 100;
    int low = 10;
    int high = 1000;
    create_array(A, size);
    populate_array(A, size, low, high);
    display_array(A, size);
    return 0;
}

void create_array(int *&X, int size)
{
    X = new int[size];
}

void populate_array(int *X, int size, int low, int high)
{
    srand(time(0));
    for (int i = 0; i < size; ++i)
    {
        X[i] = low + rand() % (high + 1 - low);
    }
}

void display_array(int *X, int size)
{
    for (int i = 0; i < size; ++i)
    {
        if (i % 10 == 0)
            cout << endl;
        cout << X[i] << "\t";
    }
    cout << endl;
}

What am I doing wrong?
Comment: @ryyker: I used gcc for C and g++ for C++.
Answer: *X = (int *)(malloc(size));

You are allocating size number of bytes perhaps what you want is
*X = malloc(sizeof(int)*size);

Note: malloc takes number of bytes to be allocated as argument.
   Also for for c implementation you  might want to read Why not to cast malloc return.


How to make a field required using JavaScript injector

Question: I have a field that is part of a content type that I need to make required by using a JavaScript injector.  The reason that I can't just make it required while setting the rules for that field is because I have to parse a string that will display on the same page whether or not I need to make it required.  Any thoughts?
Comment: How sensitive is the form? If you absolutely need to make sure that the field is completed, you need the logic to run server-side. A determined user could easily remove any required attribute you set by javascript, and get through the form submission. I guess you could theoretically send an AJAX request whose callback loads the cached form and updates the `#required` status based on the client-side data, but it'd be quite messy. What's a javascript injector by the way, is that a module?
Comment: Thanks @user1527576. Matt, the bible is [here](https://www.drupal.org/module-development), but there is a bit of a learning curve. If you're new to PHP too that's going to make it tricky, I don't remember coming across any articles on learning both at the same time. You kinda need to know PHP before most of module development stuff will make enough sense to use it effectively. Because it's so complex it's difficult to just copy/paste code snippets and have them work without tweaking too. Maybe someone else will be able to point you to a good resource, sorry I don't really have anything
Comment: @Clive yes, it seems that it's a [module](https://www.drupal.org/project/js_injector)
Comment: @Clive Yes, it is a module.  I am willing to do everything server side with PHP, but I am rather new to Drupal, do you have any recommendations for how to get going with PHP and module development?
Comment: @Clive, learning PHP is not an issue, I've been programming in PHP for almost a year now.  I'm just not sure how to access fields and everything before a page loads.
Comment: @Matt I think that the JS injector is unnecessary, you just need to create a custom validator for your field. Check if the accepted answer [here](http://drupal.stackexchange.com/questions/82849/validate-all-instances-of-a-field-programmatically) could fit your needs
Comment: In what situation do you need field to be required?
Answer: Matt -
I would recommend looking into hook_node_validate(). This is a function hook provided by Drupal core that allows you to add custom validation into the form. While you cannot select "required" from the field UI, perhaps you can validate it here and then return an error if the form doesn't provide the correct information for that specific field.
Other things to investigate: hook_form_alter() and hook_validate - where you can add custom validation functions into the Drupal form array itself.
Helpful links:
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_validate/7
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7


How to annotate violin bowing over a triplet

Question: I am new (6 months) to both violin and music; forgive the simple question. My understanding of general bowing is:

Without a slur, bow direction alternates with each note
With a slur, maintain the same bow direction

I'm composing a simple melody (common time) and I have a triplet where I want the first two notes down bow, but the last note up bow. A few options I've considered:

Slur the first two notes of the triplet only
Slur the whole triplet, but mark the final note as up bow
No slur, mark down bow for second note

I'm sure there's no "right way" to do this, and as long as the idea is conveyed to the reader then whatever works, but since I'm new to music I'm curious about the general convention. I could not find any examples of what I'm looking for either online or in my beginner books.
Thanks for the help!
Answer: Your confusion is understandable, since there are multiple ways to indicate both triplets and bow directions! But some are better than others.
Sometimes triplets have been indicated with a "3" and nothing else, like in this second bar:

The problem with this is that the "3" might be mistaken for a fingering, or in some more complex tuplets it might be harder to see which notes are included. It's more common, especially today, to use square brackets like this:

Occasionally you see slur marks substituted for these brackets, like this:

You can see an example at this question, or find people arguing about the practice on the Musescore forum. As that thread shows, it has been done plenty in the past, and perhaps today when someone's engraving abilities lack square brackets. But the disadvantage of this is obvious, it can be mistaken for an actual slur. Modern practice strongly discourages this.
Meanwhile, when engraving violin music, there's a difference between this:

... and this:

A true slur mark means that the bow keeps moving in a downbow direction without any interruption. The two down bows without a slur can be heard as two separate notes that just happen to both be in the same direction, but the player might stop the bow in between them, or even lift it and replace it to start again at the same point, causing an even bigger gap.
(Note, sometimes orchestra players in a hurry might pencil in something like the second example when they mean the first, but if you want a true slur, the best engraving practice is to print one.)
Answer: As a violinist, what would probably be easiest to read and most valid is the first solution you suggested.
The second solution doesn't make sense to my knowledge, and I don't think I've seen any other music do similar bow changes in a slur.
For the third solution, this could also be valid if you don't want the first two notes to flow smoothly into each other, but in this case it'd be much easier to understand if you put a down bow on both the first and second note to indicate you want them in the same direction.


arrange numbers or alphabets in following matrix form

Question: for n = 3:

1 3 6
2 5 8
4 7 9

this is diffrent from diagonal printing.

If we are given n then we have to print in 2d matrix from upto n.
Comment: Language? What have you tried?
Comment: Any language, I just want solution not exact code. I am not able to start yet.
Answer: public static int[][] zigzag(final int size)
 {
   int[][] data = new int[size][size];
    int i = 1;
     int j = 1;
     for (int element = 0; element < size * size; element++)
{
data[i - 1][j - 1] = element;
if ((i + j) % 2 == 0)
{
// Even stripes
if (j < size)
j++;
else
i+= 2;
if (i > 1)
i--;
}
else
{
 // Odd stripes
 if (i < size)
 i++;
 else
 j+= 2;
 if (j > 1)
 j--;
 }
 }
  return data;
  }


Appverifier and Visual Studio for leak detection

Question: I'm running Appverifier in an application. When it detects a memory leaks the logs saids
"Address of the leaked allocation. Run !heap -p -a  to get additional information about the allocation."
I guess that's when you are running in Windbg, is there any way to access the allocation stack trace from inside Visual Studio ?
Comment: Have you seen [this](http://msdn.microsoft.com/en-us/library/ms220948.aspx)?
Answer: Not that I know of. You will have to use WinDbg to track those down.
http://www.winprogger.com


Solving $\log_2(x^2) = x$ explicitly?

Question: I'm having problems getting a proper step-by-step solution to this equation.
$$
\log_2(x^2) = x
$$
I know the results are 2 and 4, but so far I can get only solutions like these:
$$
2^x = x^2 \qquad \text{or} \qquad \frac{\log(x)}{x} = \frac{\log(2)}{2}.
$$
I'd like something along the lines of $x = \dotsb$.
Is it possible with some basic knowledge?
Comment: The real solutions include the product-log function according to WA. You can't solve it in terms of elementary algebra.
Comment: See how [this](http://math.stackexchange.com/questions/965836/how-to-solve-this-equation-x2-2x/965899#965899) helps.
Comment: we get $x=2$ or $x=4$ and after this you need the Lambert function
Answer: No. There is in fact a third solution, $x\approx -0.77$, but you cannot find it using elementary algebraic methods. The best you can do is to "guess" these solutions (by inspection in the case of the positive ones, or by using a numerical method) and then prove using Calculus that there can be no others (by comparing the growth rates of the two functions).

Solving $\log_2(x^2) = x$ explicitly?


How to Use Usercontrol more than once inside one Control

Question: I created WPF UserControl which enables to enter some information now I have Main entry form where I want to use tow instances of that UserControl When I add my YserControl as Resource and than try to use it as ContrntControl's Content exception is thrown informing that control is already a logical child. Can anyone provide with sollution?
Answer: You can use the x:Shared attribute so that whenever something references the resource, a new instance is created instead of it being shared.
Thus you might have something like this:
<Window.Resources>
    <MyUserControl x:Key="MyControlKey" x:Shared="False" .... />
    ....
</Window.Resources>

http://msdn.microsoft.com/en-us/library/aa970778.aspx
http://www.wpfmentor.com/2009/01/how-to-ensure-new-instance-of-resource.html
Answer: I just found out way to not throw exception but I want to know if this is right sollution
            <TaicoControl:WizardPage Title="Title1"
                                 BackButtonVisibility="Collapsed"
                                 CancelButtonVisibility="Collapsed"
                                 Description="Desctiption1"
                                 PageType="Interior">
            <ContentPresenter ContentTemplate="{StaticResource PersonEntryFormTemplate}" DataContext="{Binding Person}" />
        </TaicoControl:WizardPage>
        <TaicoControl:WizardPage Title="Title2"
                                 BackButtonVisibility="Collapsed"
                                 CancelButtonVisibility="Collapsed"
                                 Description="Description2"
                                 NextButtonVisibility="Collapsed"
                                 PageType="Interior">
            <ContentPresenter ContentTemplate="{StaticResource PersonEntryFormTemplate}" DataContext="{Binding Person.ContactPerson}" />
        </TaicoControl:WizardPage>


NVD3.js | php | unix time stamp not working

Question: For some reason the timestamps i am using are not translating to the graph correctly.  the graph says they are 01/16/1970 [ time stamp: 1389429242].  I am using strtotime (php function) to generate the time stamps.  How do i generate the correct time stamp for this to work, using php?
Code:
<code><script>
    nv.addGraph(function() {
        var chart = nv.models.lineWithFocusChart();

        chart.xAxis
            .tickFormat(function(d) { return d3.time.format('%x')(new Date(d)) });
        chart.x2Axis
            .tickFormat(function(d) { return d3.time.format('%x')(new Date(d)) });

        chart.yAxis
            .tickFormat(d3.format(',f'));
        chart.y2Axis
            .tickFormat(d3.format(',f'));

        d3.select('#chart svg')
                .datum(
                    [
                        {
                            key : 'Current' ,
                            color : '#2ca02c',
                            values : [
                                { x: 1389429242 , y:15 },
                                ...
                            ]
                        },
                        {
                            key : 'Backlog' ,
                            color : '#ff7f0e',
                            values : [
                                { x: 1389429242 , y:50 },
                                ...
                            ]
                        }
                    ]
                )
                .call(chart);

        nv.utils.windowResize(chart.update);

        return chart;
    });
</script>
</code>
Answer: So apparently, JS time stamps are in milliseconds.  So i had to multiply my php time stamp my 1000 and it works.
SOLVED


Selecting of students under restraints

Question:
A delegation of $4$ students is to be selected from $12$ students. In how many ways can the delegation be selected if $2$ particular students wish to be together and other $2$ wish not to be together in the delegation?

A B wish to be together C D not together.

My attempt:

CASE$1$

A B are included (remaining $10$, $2$ to choose), C is included D excluded: $\binom11\times\binom81$

CASE$2$

A B are included (remaining $10, 2$ to choose), D is included C excluded:$\binom11\times\binom81$

CASE$3$

A B are both excluded(remaining $10, 4$ to choose), C is included D excluded: $\binom11\times\binom94$

CASE$4$

A B are both excluded (remaining $10, 4$ to choose), D is included C excluded: $\binom11\times\binom93$

Edit

CASE$5$

A B are both excluded(remaining $10, 4$ to choose), D is excluded C excluded: $\binom11\times\binom84$

CASE$6$

A B are both included(remaining $10, 2$ to choose), D is excluded C excluded: $\binom11\times\binom82$

Total: $324$

This apparently gave the wrong answer and I feel I've done a mistake in selecting. I don't know which case is extra.
Comment: You haven't counted the case in which none of the four people are selected for the delegation.
Comment: Nor have you counted the case in which AB are included but CD both are excluded. Look at it like this -- for CD, we have three cases: C incl, D excl; C excl, D incl; C excl, D excl. For AB, we have two cases: AB incl, AB excl. This makes a total of $2\times3=6$ cases.
Comment: @ShubhamJohri now extra cases are being included answer is 216
Comment: @Anusha Look at the last part of [this question](https://www.toppr.com/ask/question/a-delegation-of-4-students-is-to-be-selected-from-a-total-12-students-in/). The correct answer is indeed $226$ and not $216$
Answer: In addition to the cases you were missing, your answers for case $3$ and $4$ are wrong. AB are excluded and either one of CD is included. So out of the remaining $8$ students, you want to select $3$. This will give you the correct answer of $226$.

Selecting of students under restraints


JQuery Ajax Request: Change User-Agent

Question: I'm using JQuery to issue an AJAX request to my own Webservice. I need to set or modify the User-Agent HTTP-Header for the HTTP-AJAX-Request, how can I do this the easiest way?
I tried the hint provided by some users to use the setRequestHeader Method to set the User-Agent, but this does not work. It does in fact work for other newly created headers (like X-Test-Header) but it does not work for User-Agent.
Comment: see this discussion http://forum.jquery.com/topic/jquery-specifying-user-agent-with-ajax
Comment: See my comment below, does not work for me.
Answer: It is simply impossible, you are not allowed to change the user-agent for XMLHttpRequests. I'm not sure if this is valid for Internet-Explorer, but the w3c specifies here:

The setRequestHeader() method
[...]
When the setRequestHeader(header, value) method is invoked, the user agent must run these steps:
  [...]
Terminate these steps if header is a case-insensitive match for one of the following headers:
[...]

User-Agent
Comment: 2017 update: the W3C TR spec you linked has moved to [this whatwg spec](https://xhr.spec.whatwg.org/#the-setrequestheader()-method), which refers to [this list of forbidden header names in the fetch spec](https://fetch.spec.whatwg.org/#forbidden-header-name), which doesn't include `User-Agent`. MDN [explicitly confirms](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) that `User-Agent` is no longer forbidden. Chrome still refuses it, though, so I don't think your advice is invalid quite yet.
Answer: If you are using jQuery, set the request header in the ajaxSetup.
$.ajaxSetup({
  beforeSend: function(request) {
    request.setRequestHeader("User-Agent","InsertUserAgentStringHere");
  }
});

Comment: Works for me inside my node.js application where I can care less about w3c's rules.. You're awesome - thanks.
Comment: Modifying the header does not work at all, however this code works if you are trying to add a new header.
Comment: Have you tried this? It does not work using JQuery 1.5.2 and Firefox 4, the user-agent is still the default one. I call the ajaxSetup after the document has loaded completely (document.ready) before issuing the calls. It is a simple json-request (not jsonp)
Comment: This does not work in Chrome with a Mac.  I would say in general this doesn't work at all if it's "simply impossible".
Comment: It seems the code works but Chrome doesn't want to set it. Refused to set unsafe header "User-Agent"
Answer: Well, you could always use jQuery to post to a server-side page which then in turn is able to modify the User-Agent header, and also make a request to the page which would have been directly accessed by jQuery.
Answer: A way to do this is to overwrite the native code in the __defineGetter__ method of the window.navigator object.
Check this out:
window.navigator.__defineGetter__('userAgent', function () {
    return "___I'M A GHOST___";
});

Run navigator.userAgent in the console before and after to check.
Works in Chrome. I haven't checked other browsers.
You can read more about it here: https://www.codeproject.com/Tips/1036762/Mocking-userAgent-with-JavaScript
Comment: Anyone seeing this: please do not use this solution (it's not the solution's fault, but it is deprecated): "Warning: This feature is deprecated in favor of defining getters using the object initializer syntax or the Object.defineProperty() API. While this feature is widely implemented, it is only described in the ECMAScript specification because of legacy usage. This method should not be used since better alternatives exist." (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__)).
Answer: I have done it like this:
I send the ajax request to a seperate php script that acts just like a forwarder, in this php script you will then make the original request and change the user-agent as you want.
You can set the user-agent in file_get_contents like this:
https://gist.github.com/vyspiansky/82f4b1ef6fcff160047d

JQuery Ajax Request: Change User-Agent


Views filter on field being either empty or equal to uid

Question: I have a views filter on a particular field being empty (Is empty (NULL)).
However, I would like to have it check on the field being either empty or equal to the current user's uid. I would like to do this programmatically in a custom module, so without installing a contributed module.
The field in question is $node->field_quality_personal[LANGUAGE_NONE][0]['value']. So this field can be either empty, or it can contain a uid.
Answer: I found the way to fix this. The answer is twofold:
First create two filters: one for the field being empty and one for the field being equal to the string "uid". Then as a Filter Criteria option, choose And/Or, Rearrange and add the Or condition:

This is the result:

Second implement hook_views_query_alter() to replace the "uid" string we added earlier with the actual user uid:
/**
 * Implements hook_views_query_alter().
 *
 * Search for 'personal' field to be empty or equal to uid.
 */
function example_views_query_alter(&$view, &$query) {
  if ($view->name == 'myview') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'table.field_quality_personal' && $condition['value'] == 'uid') {
          global $user;
          $condition['value'] = $user->uid;
        }
      }
    }
  }
}

That's it!


Evitar a duplicidade de data e hora para o mesmo profissional em agendamento

Question: Amigos estou tentando criar uma agenda para uma clinica odontológica, mas estou tendo dificuldade para evitar de que o cliente agende uma data e hora que já tenha sido agendada para aquele profissional selecionado.
Por exemplo, alguém já agendou o atendimento com o profissional João a data 01/06/2015 as 12:00Hs, eu gostaria de que outra pessoa não tenha condições de agendar para o mesmo profissional a mesma data e hora, que o sistema avisasse para escolher outra data e hora para esse profissional ou agendar para outro profissional disponível para a data e hora desejada.
Eu estou usando esse código abaixo que cadastra, mas não impede a duplicidade de cadastro do agendamento.
<?php if(isset($_POST['enter'])){

$nome = $_POST['nome'];
$tel = $_POST['tel'];
$cel = $_POST['cel'];
$email = $_POST['email'];
$plano = $_POST['plano'];
$horas = $_POST['horas'];
$prof = $_POST['prof'];
$data = $_POST['data'];
$tempo = date("dd/mm/YY His",time());

$pdo = new PDO('mysql:host=localhost;dbname=site', "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT * FROM agendar WHERE data LIKE = '{$data}' AND horas ='{$horas}' AND prof = '{$prof}'");
if($stmt->rowCount()>=1){

echo "<meta http-equiv='refresh' content='0; URL= agenda.php'>
      ";

 return die;

 }else{

 $stmt = $pdo->prepare ('INSERT INTO agendar (nome, tel, cel, email, plano, prof, data, horas)
                        VALUES (:nome, :tel, :cel, :email, :plano, :prof, :data, :horas)');

 $stmt->execute(array(':nome' => $nome,
                     ':tel' => $tel,
                     ':cel' => $cel,
                     ':email' => $email,
                     ':plano' => $plano,
                     ':prof' => $prof,
                     ':horas' => $horas,
                     ':data' => $data,
                     ':data' => $data,
                     ));

  if($stmt == ''){
    echo "";
  }else{
    echo "";

}}}
?>

Uso essa linha de código $sql = mysql_query("SELECT * FROM agendar WHERE data LIKE '".$data."' AND horas ='".$horas."' AND prof = '".$prof."'");
if(mysql_num_rows($sql)>=1){ no Mysql para evitar a duplicidade, e funciona legal, impedindo o agendamento.
Adaptei para o PDO ficando assim $stmt = $pdo->prepare("SELECT * FROM agendar WHERE data LIKE = '{$data}' AND horas ='{$horas}' AND prof = '{$prof}'");
    if($stmt->rowCount()>=1){ mas não sei se fiz a adaptação corretamente, e acho que pode ser ai que eu esteja errando!!!
Conforme solicitado estou inserindo o código do FORM abaixo:
<form name="enter" method="post" action="" enctype="multipart/form-data">

AGENDE HOJE MESMO SUA AVALIAÇÃO

Nome:<input style="width:250px" type="text" name="nome" value=''>

Telefone Residêncial:<input style="width:166px" type="text" name="tel" value='(21) '>

Telefone Celular:<input style="width:188px" type="text" name="cel" value='(21) '>

E-mail:<input style="width:247px" type="text" name="email" value=''>

<?php
$conn = new PDO('mysql:host=localhost;dbname=site', 'root', '');
$stmt = $conn->prepare('SELECT plano FROM planos');
$stmt-> execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(isset($_POST['enter'])){

$plano = $_POST['plano'];
$pdo = new PDO('mysql:host=localhost;dbname=site', "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare('UPDATE agendar SET plano = :plano');
$stmt->execute(array( ':plano' => $plano));
}
?>
<select name="plano">
<?php foreach($result as $row){ ?>
    <option value="<?php echo $row['plano'];?>"><?php echo $row['plano'];?></option>
    <?php } ?>
</select>

<?php
$conn = new PDO('mysql:host=localhost;dbname=site', 'root', '');
$stmt = $conn->prepare('SELECT prof FROM profissionais');
$stmt-> execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(isset($_POST['enter'])){

$prof = $_POST['prof'];
$pdo = new PDO('mysql:host=localhost;dbname=site', "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare('UPDATE agendar SET prof = :prof');
$stmt->execute(array( ':prof' => $prof));
}
?>
<select name="prof">
 <?php foreach($result as $row){ ?>
    <option value="<?php echo $row['prof'];?>"><?php echo $row['prof'];?></option>
    <?php } ?>
 </select>

 <input width="10" type="text" name="data" value="Data" id="data" />

<?php
$conn = new PDO('mysql:host=localhost;dbname=site', 'root', '');
$stmt = $conn->prepare('SELECT horas FROM horarios');
$stmt-> execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(isset($_POST['enter'])){

$horas = $_POST['horas'];
$pdo = new PDO('mysql:host=localhost;dbname=site', "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare('UPDATE agendar SET horas = :horas');
$stmt->execute(array( ':horas' => $horas));
}
?>
<select name="horas">
<?php foreach($result as $row){ ?>
    <option value="<?php echo $row['horas'];?>"><?php echo $row['horas'];?></option>
    <?php } ?>
</select>

<input class="input" type="submit" name="enter" value="Agendar" />  Se preferir, ligue para: (21)2290.3702

</form>

Se os amigos puderem me ajudar, ficarei grato.
Abraços à todos!!!
Comment: Acho mais facil você  liberar apenas os horarios disponiveis para a pessoa postar.. da mesma forma como funciona um check-in de voo... o usuario so pode escolher as cadeiras disponíveis.  seria isso?
Comment: vc poderia colocar o formulario que o usuario cadastra o horario tambem?
Comment: OK  Andrei, acabei de inserir o código do **FORM** que estou usando.
Acho que foi isso que vc. pediu, estou correto?
Agradeço a atenção, valeu!!!
Answer: Analisei seus códigos, e acho que você poderia fazer em etapas para não ter problema com duplicidade...
Antes do usuário cadastrar nome, endereço, etc... ele tem que escolher 1 dia que é melhor para ele fazer a consulta na clínica. Depois ele escolhe os horários que estão disponíveis naquela data selecionada. E depois ele cadastra os dados pessoais...
Formatei seu código assim
agendar.php
      // aqui o codigo verifica se existe na url a data e a hora, se não existir ele executa baixo...
     <?php if(!isset($_GET['data']) && !isset($_GET['hora'])){ ?>

    <form method="get" action="agendar.php">
     <input width="10" type="text" name="data" value="Data" id="data" />

    <input width="10" type="submit" name="envia" value="Selecionar" />
     </form>
    // aqui o codigo verifica se existe na url a data e a hora, se não existir a hora ele executa baixo...
   <?php  } elseif(isset($_GET['data']) && !isset($_GET['hora']) { ?>

     <form method="get" action="agendar.php">

    <?php

    //***** alterado ***** > a variável que estava escrita era a $pdo
    $conn= new PDO('mysql:host=localhost;dbname=site', "root", "");

    $data = $_GET['data'];
    //MUITO IMPORTATE: aqui estou selecionando apenas os horários vazios da tabela horário conforma a tabela agendar daquela data selecionada.
    $stmt = $conn->prepare("SELECT horas FROM horarios LEFT JOIN agendar ON agendar.horas = horarios.horas WHERE horarios.horas IS NULL AND agendar.data = $data");
    $stmt-> execute();
    //repare que eu alterei esta linha de código pois não estava funcionando com ASSOC, afinal oque você precisa é de um array
    $result = $stmt->fetchAll();
    if(isset($_POST['enter'])){

    $horas = $_POST['horas'];
    $pdo = new PDO('mysql:host=localhost;dbname=site', "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare('UPDATE agendar SET horas = :horas');
    $stmt->execute(array( ':horas' => $horas));
    }
    ?>
    <select name="horas">
    <?php foreach($result as $row){ ?>
        <option value="<?php echo $row['horas'];?>"><?php echo $row['horas'];?></option>
        <?php } ?>
    </select>

     <input width="10" type="submit" name="envia" value="Selecionar" />
   </form>
         // aqui o codigo verifica se existe na url a data e a hora, se existir a hora e a data ele executa baixo..
        <?php  } elseif(isset($_GET['data']) && isset($_GET['hora']) { ?>

       <form name="enter" method="post" action="" enctype="multipart/form-data">

        AGENDE HOJE MESMO SUA AVALIAÇÃO

         Data selecionada: <input name="data" value="<?php echo $_GET['data'] ?>"/>

        Hora selecionada:  <input name="hora" value="<?php echo $_GET['hora'] ?>"/>

        Nome:<input style="width:250px" type="text" name="nome" value=''>

        Telefone Residêncial:<input style="width:166px" type="text" name="tel" value='(21) '>

        Telefone Celular:<input style="width:188px" type="text" name="cel" value='(21) '>

        E-mail:<input style="width:247px" type="text" name="email" value=''>

        </form>
        <?php  }  ?>

agora é só inserir no banco de dados
Fiz com o method get só para você ter uma idéia.
Mas aquela seleção da hora do dia que estão disponíveis vai evitar duplicidade para voce, pois ele só vai selecionar os campos hora da tabela horario que estão disponíveis.
Espero ter ajudado.
Comment: Valeu Andrei, vou dar uma analisada no seu código, pois assim aprendo um pouco mais...rsrsrsrs...
Mais uma vez BRIGADÃO pela sua atenção.
Abraços!!!
Comment: Tranquilo Murilo, abraço
Comment: Andrei, inseri as suas alterações, porém ele esta se referindo ao seguinte erro quando seleciono uma data e clico em selecionar: **Notice: Undefined variable: conn in C:\wamp\www\site\agenda\agendar.php on line 46**, e a linha 46 esta assim: `$stmt = $conn->prepare("SELECT horas FROM horarios LEFT JOIN agendar ON agendar.horas = horarios.horas WHERE horarios.horas IS NULL AND agendar.data = $data");`. Se puderes me ajudar com esse erro, ficarei grato. Abraços amigo!!!
Comment: achei o erro... digitei um comentário lá com ***** para você visualizar.. Mas veja, este código é apenas um modelo de como você deve agir...
Comment: Talvez ele não funcione da forma correta pois não estou fazendo testes e tal...


Insert into DB from ASP.Net form

Question: I have an issue when I want to insert an object into the database.
My model is Colis class which has a foreign key to ZoneReserve (ZoneReserveId), which has a foreign key on Reserve (ReserveId).
In my form I choose an existing ZoneReserve and Reserve, but when I post my form, new lines are created in DB, in table ZoneReserve and Reserve. Entity framework do not retrieve the existing line or I don't know...
I don't know if I'm clear enough, sorry for my english ;)
Do you have any advice ? I'm stuck et I tried everything :(
Thank you guys
Colis Model Class :
   public class Colis
    {
        public int ColisId { get; set; }

        [Display(Name = "Code barre du colis")]
        public string CodeBarreColis { get; set; }

        public bool IndAVendreColis { get; set; }

        public virtual TypeColis TypeColis  { get; set; }

        [Display(Name = "Type de colis")]
        public int TypeColisId { get; set; }

        public ZoneReserve ZoneReserve { get; set; }

        [Display(Name = "Emplacement du colis")]
        public int ZoneReserveId { get; set;
    }

ZoneReserve Model Class :
public class ZoneReserve
    {
        public int Id { get; set; }
        public string NomZoneReserve { get; set; }

        public Reserve Reserve { get; set; }
        public int ReserveId { get; set; }
    }

Reserve Model Class :
    public class Reserve
    {
        [Display(Name = "Réserve")]
        public int Id { get; set; }
        public string NomReserve { get; set; }

    }

My Action in ColisController :
        [HttpPost]
        public ActionResult CreerColis(Colis colis)
        {
            _context.Colis.Add(colis);
            _context.SaveChanges();

            return RedirectToAction("ListeColis");
        }

My Form in the view :
@using (Html.BeginForm("CreerColis", "Colis"))
{

        @Html.LabelFor(m => m.Colis.CodeBarreColis)
        @Html.TextBoxFor(m => m.Colis.CodeBarreColis, new { @class = "form-control" })

            @Html.CheckBoxFor(m => m.Colis.IndAVendreColis) A vendre ?

        @Html.LabelFor(m => m.Colis.TypeColisId)
        @Html.DropDownListFor(m => m.Colis.TypeColisId, new SelectList(Model.TypeColis, "Id", "NomTypeColis"), "Selectionner un type", new { @class = "form -control" })

        @Html.LabelFor(m => m.Colis.ZoneReserve.Reserve.Id)
        @Html.DropDownListFor(m => m.Colis.ZoneReserve.Reserve.Id, new SelectList(Model.Reserve, "Id", "NomReserve"), "Selectionner une zone", new { @class = "form -control" })

        @Html.LabelFor(m => m.Colis.ZoneReserveId)
        @Html.DropDownListFor(m => m.Colis.ZoneReserve.Id, new SelectList(Model.ZoneReserve, "Id", "NomZoneReserve"), "Selectionner une zone", new { @class = "form -control" })

    <button type="submit" class="bt, btn-primary">Enregistrer</button>

}

Answer: It looks like your razor page is posting info about navigation properties of the Colis object to the controller and creating the full objects instead of creating a new Colis object with just the int foreign key specified.
As is, when posted, '''colis.ZoneReserve''' is not null nor is '''colis.ZoneReserve.Reserve''' reference which tells entity framework to create those related object as well when you .Add(colis) to the context.
[HttpPost]
public ActionResult CreerColis(Colis colis)
{
    _context.Colis.Add(colis);
    _context.SaveChanges();

    return RedirectToAction("ListeColis");
}

You are POSTing unintended parameters to your controller, specifically '''Colis.ZoneReserve.Id''' and '''Colis.ZoneReserve.Reserve.Id''' as you BOUND TO in your razor page (see comments in code):

    @Html.LabelFor(m => m.Colis.ZoneReserve.Reserve.Id)

    @Html.DropDownListFor(m => m.Colis.ZoneReserve.Reserve.Id, new SelectList(Model.Reserve, "Id", "NomReserve"), "Selectionner une zone", new { @class = "form -control" })

    @Html.LabelFor(m => m.Colis.ZoneReserveId)

    @Html.DropDownListFor(m => m.Colis.ZoneReserve.Id, new SelectList(Model.ZoneReserve, "Id", "NomZoneReserve"), "Selectionner une zone", new { @class = "form -control" })

To fix your razor page (and not send unintended values to the server)

change the first drop down list for Reserve to NOT be for anything it'll bind to on the server (you don't even need to POST it's value if you can strip it before submit), one way is to change it's name to something meaningless such as "UnnecessaryData" that won't map in the controller when posted (pseudo-code, not tested)

    @Html.LabelFor(m => m.Colis.ZoneReserve.Reserve.Id)
    @Html.DropDownList(new SelectList(Model.Reserve, "Id", "NomReserve"),
        "Selectionner une zone",
        new { @class = "form-control", name = "UnnecessaryData" })

Change the second drop-down-list to map to the correct property on the Colis object, notice all I did was change m => m.Colis.ZoneReserve.Id to the FK property of Colis m => m.Colis.ZoneReserveId:

    @Html.LabelFor(m => m.Colis.ZoneReserveId)
    @Html.DropDownListFor(m => m.Colis.ZoneReserveId, new SelectList(Model.ZoneReserve, "Id", "NomZoneReserve"), "Selectionner une zone", new { @class = "form -control" })

When you POST the form, your Colis object in the controller should have a NULL ZoneReserve property and a non-zero ZoneReserveId property - this will prevent the other data records from being created by entity framework.
Note: You can also simply strip the data from the Colis in the POST controller - but that doesn't correct your implementation on the client razor page that's sending unintended structure to the server in the POST method.
Also note: Because you don't validate that the navigation properties of Colis are NULL in the controller, a malicious user COULD create a lot of crap data on the server by POSTing full object tree data that'll be added with the controller method as implemented.

Insert into DB from ASP.Net form


Calling class operator directly

Question: I'd like to ask you why do I need to call class operator directly in this situation:
void __fastcall TForm2::statusDrawPanel(TStatusBar *StatusBar, TStatusPanel *Panel,
                                        const TRect &Rect)
{
  //if (Panel == StatusBar->Panels[1]) This doesn't work for me, compiler throws E2096 Illegal structure operation
    if (Panel == StatusBar->Panels->operator [](1)) // but this is working
    {
      int i  = 0;
    }
}

I'm using Borland's C++ Builder XE2. I would also like to ask you in which situations do I need to call class operator directly.
Answer: Panels is apparently a pointer, and when you use [] on a pointer, it treats it like a pointer to an array and tries to add the offset to the pointer to get a Panels object at the given offset, which isn't want you want.
You need to dereference the pointer, either with Panels->operator[](1) or (*StatusBar->Panels)[1] to get to the object and call operator[] on it, which is probably your desired behaviour.
Comment: This bites quite often with `Items` properties, where often you need to write `Foo->Items->Items[n]` where the equivalent Delphi code would be simply `Foo.Items[n]`.

Calling class operator directly


How can I use EntityForm ::save() in a custom module?

Question: How can i call public function ContactFormEditForm::save. My goal
is refer to return value, do something like email, custom logged
message, etc.
Refer to api."Return value int Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed."
Un myCustom.module file how to do:
if contact Form == specific Form, and if the form submitted.
$value = $form->save():
how do custom module know when user submitted ? hook for entity Form saved ?
Must use Event ? i check some docs, but for dispatched to
entity Form save(). same question, how Event know the form saved ?
pls give some direction,  my concept is not clear.
thks
Comment: IMHO this is a valid question. It's somewhat counterintuitive that the form class method save() is called by the submit element in the form array and it could use an explanation.
Comment: Welcome to Drupal Answers! Since this is a question about code, we need to see the code you wrote so far. If you are asking the question before writing code, you are asking the question too early. If the question is asked because you do not understand what the documentation says, the question must be explicit about that. From the question is not clear what exactly you do not understand in achieving the described task.
Comment: Sorry for late reply, this is also 22:00 in my side.
There are no code at all,  because don't know where to start,
nothing to hide, this is OOP concept problem, So far my Drupal life is only hook function,  i just want to  know how to get return value form entityForm:save(), someone has ans me, again   use hook_form_alter.  my programming skill is poor,  but will keep studying, next time make sure post here only for coding problem,  thanks.
Comment: The question in the question body is *How can I call `ContactFormEditForm::save()`?* The question does not make clear where `ContactFormEditForm::save()` would be called nor does it show the code that would call `ContactFormEditForm::save()`.
Comment: Except in the case of a class that extends `ContactFormEditForm`, I cannot think of code that would need to call `ContactFormEditForm::save()`. It seems that calling `ContactFormEditForm::save()` is what the OP thinks to be the solution; if the question shows the used code, answers can at least say what is wrong in the code and what the correct solution is.
Comment: The post is not clear nor does it contain enough details; if the answer is that `ContactFormEditForm::save()` should be listed in the form submission handlers, then the question is too broad. Furthermore, there are more than a question asked in a single post; posts need to be focused on one problem only; that is why we have the *Needs more focus* closing reason.
Answer: This is a submission handler. Use a form alter hook and inspect the existing #submit array, you probably see the ::save() method already registered:
<code>$form['actions']['submit']['#submit']
</code>
How do custom module know when user submitted?
Add your own submit handler to this array. See Add a custom submission handler to a form
Comment: Thanks your very much !!! will try.....


Prove that the limit exist

Question: Let  $T : H \rightarrow H$ is a linear continuous unitary ($T^*=T^{-1}$) operator, $H$ is a Hilbert space (not necessary). Suppose that

$\forall h \in H \Rightarrow Th=h$
$T_n$ - a sequence of linear operators $T_n \underset{n\rightarrow \infty}{\longrightarrow}  T$, $|| T_n - T||\rightarrow 0$. So the sequence $T_n$ tends to $T$ in the norm and we have $\forall h \in H \ \ || T_n h - T h|| \leq || T_n - T|| \ ||h||\rightarrow 0$.

Can we prove that there exists a limit of the sum $S_n= \frac{1}{n}\left( T_1 h + T_1 T_2 h + \dots + T_1 \dots T_n h \right)$ where $n \rightarrow \infty$?
Comment: Just to understand... your $T$ is the identity map, right?
Comment: Yes, T is the identity map
Answer: There are several cases:

the limit exists and is $0$ (when $T_j=\left(1-\frac 1{j+1}\right)I$);
the limit exists and is the identity (when $T_j=I)$;
the limit doesn't exist (when $T_j=\left(1+\frac 1{\log(j+1)}\right)I$).
Comment: Thank you for this examples. But I have now a new question here http://math.stackexchange.com/questions/415754/prove-that-the-limit-exist-ii

Prove that the limit exist


Determine if TCP socket is in kernel-space

Question: I have no problem finding out if a socket belongs to user space - I simply scan /proc/ to see which PID owns the [socket]. But with TCP sockets open in the kernel space there is no entry in /proc/ (since kernel has no PID).
I assume that it is not safe to suppose that just because socket wasn't found in /proc, it was initiated by the kernel.
I though about /proc/net/tcp's undocumented 7 columns at the end. Maybe one of them can give hints as too socket's origin? I couldn't decipher kernel's source code to figure out what those 7 fields represent.
Could someone lend me some assistance, please.
Comment: Try seeing whether `rpcinfo -p` reports information regarding those ports.
Comment: Thanks for the suggestion:
I ran rpcinfo -p while in-kernel socket was sending packets and clearly hitting my iptables rule for outgoing TCP.
Unfortunately rpcinfo didn't show it's port number.
Comment: Can you clarify what you are trying to do?  Or what the motivation is here to hopefully clarify what the question is?  What information are you trying to gather?  What do you mean by 'TCP socket is in kernel-space'?
Answer: Try netstat with additional args:
sudo netstat -wtpeav

The sudo is there to make sure you run it as root, otherwise it won't show you everything.
The options are:
-w, --raw
    Show raw sockets.

-t, --tcp
    Show TCP protocol sockets.

-p, --program
    Show the PID and name of the program to which each socket
    belongs.

-e, --extend
    Display additional information. Use this option twice for
    maximum detail.

-a, --all
    Show both listening and non-listening sockets. With the
    --interfaces option, show interfaces that are not up

--verbose , -v
   Tell the user what is going on by being verbose. Especially
   print some useful informa‐ tion about unconfigured address
   families.

Also, the columns at the end of /proc/net/tcp are documented in the kernel source tree in Documentation/networking/proc_net_tcp.txt. The end fields are:
1000        0 54165785 4 cd1e6040 25 4 27 3 -1
 |          |    |     |    |     |  | |  | |--> slow start size threshold,
 |          |    |     |    |     |  | |  |      or -1 if the threshold
 |          |    |     |    |     |  | |  |      is >= 0xFFFF
 |          |    |     |    |     |  | |  |----> sending congestion window
 |          |    |     |    |     |  | |-------> (ack.quick<<1)|ack.pingpong
 |          |    |     |    |     |  |---------> Predicted tick of soft clock
 |          |    |     |    |     |              (delayed ACK control data)
 |          |    |     |    |     |------------> retransmit timeout
 |          |    |     |    |------------------> location of socket in memory
 |          |    |     |-----------------------> socket reference count
 |          |    |-----------------------------> inode
 |          |----------------------------------> unanswered 0-window probes
 |---------------------------------------------> uid

Comment: netstat -lptvw usually does the trick for me.
Comment: I added `-w` to my answer since it doesn't hurt to display raw sockets, even though the question specifically mentioned TCP sockets. And `-v` also doesn't hurt. I'm not sure that `-l` is helpful in this case, though since `-a` covers both listening and non-listening sockets.
Comment: And speaking of raw sockets the page [SOCK_RAW Demystified](http://sock-raw.org/papers/sock_raw) is interesting reading.


Centos 6 Timezone Wrong

Question: I am trying to set my Centos 6 VPS to GMT timezone.
I tried a sudo ln -s /usr/share/zoneinfo/GMT /etc/localtime
Which works fine.
However when I run date it returns:

Tue Oct  4 05:09:32 GMT 2016

Which indicates there is something that is much more of a problem.
Googling GMT time returns 16:57...
How come this is happening?
Comment: how can I fix the clock time? @yoonix
Answer: This was fixed by contacting my host and asking them to fix and set the clock time on their node.
If your on a dedicated server you can do this yourself by issuing:
# date -s "4 OCT 2016 18:00:00"

as root

Centos 6 Timezone Wrong


Verificando conexão com a internet com o phonegap

Question: Peguei este modelo do site do Phonegap e mesmo assim ele não emite um alerta mostrando o estado da conexão.
Quero que ao abrir o InAppBrowser que estou criando ele mostre se esta conectado na internet via 3g ou wifi e se não estiver ele emita um alerta avisando o usuário.
Exemplo: Exemplo retirado do site do Phonegap
Ele não emite o alerta avisando o estado da conexão, como fazer isso?
<!DOCTYPE html>

    <title>navigator.connection.type Example</title>

A dialog box will report the network state.

Comment: como está seu código?
Comment: Math, esta do jeitinho que esta no site mesmo, nest elink ai...Eu só copiei e colei na aplicação, rodei ele no Eclipse emulando no smartphone conetado na internet e enão emite alerta algum.
Comment: Ajudaria se você colocasse ele aqui direto no corpo da sua pergunta, nem sempre as pessoas clicam no link para ver ou o link possui muito mais informação do que o necessário.
Comment: Eu sou novato aqui Math, não coloquei o código, por não saber colocar mesmo...Você me ajuda? Como faço para colocar um código HTML aqui na questão?
Comment: Clica em editar, copia e cola ele na sua pergunta, em seguida você seleciona seu código e clica no ícone `{}` (amostra de código), se estiver com dificuldades a gente conserta, mas tenta ae.
Comment: Pronto, esta ai o código.
Comment: Para verificar conexão internet, pode-se usar um Ping.
Comment: Na documentação diz que antes da versão 2.2.0, o objeto `connection` estava em `navigator.network.connection`... talvez seja isso.
Comment: Miguel, este exemplo ja foi retirado da versão 3.0, o site é bem organizado e contem um exemplo para cada versão...Estou usando a versão 3.0 e peguei o exemplo da versão 3.0, não teria porque não funcionar, esse site da Phonegap é muito zuado!
Answer: Verifiquei seu código e tudo funciona de forma normal, faça o seguinte altere a função onDeviceReady para a seguinte
    function onDeviceReady() {
        alert("Device Ready");
        checkConnection();
    }

E verifique se alguma mensagem aparece na tela, caso não aparecer nada o problema deve estar ocorrendo antes mesmo do função de verificar a conexão.
Caso for o caso utilize o adb  para verificar os logs do Cordova.
Para isso abra o terminal e digite o seguite comando.
 adb logcat ":S CordovaLog: Cordova:*"


Pandas set new value based in if statement

Question: I am trying to create a new field in a Pandas dataframe which is the concatenated strings of selected other fields, separated by a comma, but only where a value exists in those other fields.
Name City   Food1  Food2  Food3
Dave London cheese ham
Stan Boston eggs   cheese fish
Jean Paris  fish

Name City   Food1  Food2  Food3  concat
Dave London cheese ham           cheese,ham
Stan Boston eggs   cheese fish   eggs,cheese,fish
Jean Paris  fish                 fish

I could concatenate all fields with
df[concat'] = df['Food1'] + ',' + df['Food2'] + ',' +  df['Food3'] + ',' +  df['Food4']
but this does not limit to fields with values.
Pseudo code is something like:
columns = [df['Food1'],df['Food2'],df['Food3'],df['Food4']]
mylist = []
for column in columns:
    if column:
        mylist.append(column)
df['concat'] = mylist

But to use the df['new field'] =  format, Pandas seems to need this on one line. I use Pandas in a simple way but not so much list comprehensions or numpy. Are those where the solution lies?
Comment: Why does `fish` comes with `eggs` and `cheese`? What is the logic?
Comment: `for column in columns: if column`, what does that mean in your pseudo code?
Comment: @harvpan - apols, type, have corrected
Comment: @Erfan - for each column in my list of columns, if a value exists in that column
Answer: agg with strip and replace
(df.filter(like='Food')     # extract Food columns (same as df[['Food1', ...]])
   .fillna('')              # fill NaNs with empty string ''
   .agg(','.join, axis=1)   # join strings by comma
   .str.strip(',')          # remove leading and trailing commas
   .str.replace(',+', ',')) # remove repeated commas

0          cheese,ham
1    eggs,cheese,fish
2                fish
dtype: object

This will work for 1, 3, or 100 columns that need to be joined. You just have to be smart with how you select them.
Answer: Note this solution is not expandable if you have many columns, in comparison with cs95's answer.

But that said,  for your convenience we can build on your tried solution, by adding an str.replace and removing all trailing commas:
df['concat'] = (df['Food1'] + ',' + df['Food2'] + ',' + df['Food3']).str.replace('(,+$)', '')

   Name    City   Food1   Food2 Food3            concat
0  Dave  London  cheese     ham              cheese,ham
1  Stan  Boston    eggs  cheese  fish  eggs,cheese,fish
2  Jean   Paris    fish                            fish


Connect to VPN only when outside office LAN

Question: I'm trying to figure out a way to make domain clients connect to office LAN using VPN only when it's physically disconnected to the said LAN.
I've found this and this detailed official guides. As far as I understand, it will only make domain members connect to the specified VPN; even if the domain member is already within the LAN the VPN is meant to connect to, essentially a redundant exercise.

How do I make it so that it ensures it's outside the LAN before connecting to VPN? How can a PC identify a specific network (i.e. what can it use to identify networks so that I may prepare it)?
Must the log in script always be obtained from the DC? Can I make it so that a copy permanently copies to all members when I create the GPO?

PS Can anyone familiar with using the above GPO provide an example L2TP/IPSec XML?
Comment: A VPN connection is usually initiated and established by a user action. Are you saying that these computers are automatically connecting to the VPN?
Comment: @joeqwerty It is not currently (nothing configured yet), but it sure can. Domain GPO enforcement would basically make it's members do so.
Comment: I don't understand what you're saying. GPO enforcement would make `what` so? I'm asking you if the VPN connection is initiated by the user. Yes or No?
Comment: @joeqwerty To be accurate, a domain user logging in triggers the VPN connection.
Answer: DirectAccess will do exactly what you're asking for and handles the bits you're asking about (network location awareness, GPO.)
Comment: Some guidance and references, please?
Comment: I looked it up myself. Ultimate/Enterprise restriction makes it pretty much unfeasible. Further, the domain is to be created using Samba, there's actually no Windows Server on the network to actually provide that service.
Comment: Requiring Windows Enterprise doesn't make it infeasible for the general case. And yes, it does require Windows servers and a Windows domain, which is generally implied when you're talking about Windows workstations and GPOs. If you have a serious budget restriction and don't have a Windows domain, that would have been worth mentioning. As is, you don't even tell us what VPN technology you're using today.
Comment: True, however, I only had enforcement using GPO in mind, so did not feel it necessary to mention the Samba situation. I'm looking at implementing IPSec/L2TP using SoftEther.


Connecting to user email with oauth2

Question: I am trying to send emails via user account (with out him having to insert user, password) using Oauth2 for connection.
This is my code for getting an access token:
String SCOPES =  "https://mail.google.com/";
token = GoogleAuthUtil.getToken(m_context,SystemUtills.getUsername(m_context)+"@gmail.com","oauth2:" + SCOPES);

This works well and gives me a token.
Now I am trying to connect to imap and smtp like this:
public class OAuth2Authenticator   extends AsyncTask<String, Void, String> {
private static final Logger logger =Logger.getLogger(OAuth2Authenticator.class.getName());
private static String user_email;
public static final class OAuth2Provider extends Provider {
private static final long serialVersionUID = 1L;

public OAuth2Provider() {
  super("Google OAuth2 Provider", 1.0,
        "Provides the XOAUTH2 SASL Mechanism");
  put("SaslClientFactory.XOAUTH2",
      "com.google.code.samples.oauth2.OAuth2SaslClientFactory");

}
}

 public static void initialize() {
Security.addProvider(new OAuth2Provider());
}

public static IMAPStore connectToImap(String host,
                                    int port,
                                    String userEmail,
                                    String oauthToken,
                                    boolean debug) throws Exception {
Properties props = new Properties();
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imaps.sasl.mechanisms.oauth2.oauthToken", oauthToken);
Session session = Session.getInstance(props);
session.setDebug(debug);

final URLName unusedUrlName = null;
IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
final String emptyPassword = "";
store.connect(host, port, userEmail, emptyPassword);
return store;
}

public static SMTPTransport connectToSmtp(String host,
                                        int port,
                                        String userEmail,
                                        String oauthToken,
                                        boolean debug) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "true");
props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
props.put("mail.imaps.sasl.mechanisms.oauth2.oauthToken", oauthToken);
Session session = Session.getInstance(props);
session.setDebug(debug);

final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = "";
transport.connect(host, port, userEmail, emptyPassword);

return transport;
}

@Override
protected String doInBackground(String... arg0)
{
    try
    {
        IMAPStore imapStore = connectToImap("imap.gmail.com", 993, AppSettings.user_email,AppSettings.getAccessToken(), true);
        SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",587,AppSettings.user_email,AppSettings.getAccessToken(),true);
        return "SUC";
    }catch (Exception e) {
        e.printStackTrace();
        return "FLD";
    }
}

In my calling class I am invoking the connection using:
new AsyncGetAccessToken().execute();

    OAuth2Authenticator.initialize();
    try{

        new OAuth2Authenticator().execute();
    }catch (Exception e) {
        e.printStackTrace();
    }

For the smtp (debug negotiation:
04-01 07:57:08.770: I/System.out(31190): DEBUG: setDebug: JavaMail version 1.4.1
04-01 07:57:37.890: I/System.out(31190): DEBUG SMTP: useEhlo true, useAuth false
04-01 07:57:37.900: I/System.out(31190): DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587,  isSSL false
04-01 07:57:38.150: I/System.out(31190): 220 mx.google.com ESMTP q41sm37770244eez.7 - gsmtp
04-01 07:57:38.150: I/System.out(31190): DEBUG SMTP: connected to host "smtp.gmail.com", port: 587
04-01 07:57:38.155: I/System.out(31190): EHLO localhost
04-01 07:57:38.310: I/System.out(31190): 250-mx.google.com at your service, [18.104.22.168]
04-01 07:57:38.310: I/System.out(31190): 250-SIZE 35882577
04-01 07:57:38.320: I/System.out(31190): 250-8BITMIME
04-01 07:57:38.320: I/System.out(31190): 250-STARTTLS
04-01 07:57:38.320: I/System.out(31190): 250-ENHANCEDSTATUSCODES
04-01 07:57:38.320: I/System.out(31190): 250 CHUNKING
04-01 07:57:38.330: I/System.out(31190): DEBUG SMTP: Found extension "SIZE", arg "35882577"
04-01 07:57:38.330: I/System.out(31190): DEBUG SMTP: Found extension "8BITMIME", arg ""
04-01 07:57:38.330: I/System.out(31190): DEBUG SMTP: Found extension "STARTTLS", arg ""
04-01 07:57:38.335: I/System.out(31190): DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
04-01 07:57:38.335: I/System.out(31190): DEBUG SMTP: Found extension "CHUNKING", arg ""
04-01 07:57:38.345: I/System.out(31190): STARTTLS
04-01 07:57:38.440: I/System.out(31190): 220 2.0.0 Ready to start TLS
04-01 07:57:39.115: I/System.out(31190): EHLO localhost
04-01 07:57:39.220: I/System.out(31190): 250-mx.google.com at your service, [18.104.22.168]
04-01 07:57:39.220: I/System.out(31190): 250-SIZE 35882577
04-01 07:57:39.220: I/System.out(31190): 250-8BITMIME
04-01 07:57:39.225: I/System.out(31190): 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
04-01 07:57:39.225: I/System.out(31190): 250-ENHANCEDSTATUSCODES
04-01 07:57:39.225: I/System.out(31190): 250 CHUNKING
04-01 07:57:39.235: I/System.out(31190): DEBUG SMTP: Found extension "SIZE", arg "35882577"
04-01 07:57:39.235: I/System.out(31190): DEBUG SMTP: Found extension "8BITMIME", arg ""
04-01 07:57:39.240: I/System.out(31190): DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN"
04-01 07:57:39.240: I/System.out(31190): DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
04-01 07:57:39.245: I/System.out(31190): DEBUG SMTP: Found extension "CHUNKING", arg ""
04-01 07:57:39.245: I/System.out(31190): DEBUG SMTP: Attempt to authenticate
04-01 07:57:39.250: I/System.out(31190): AUTH LOGIN
04-01 07:57:39.350: I/System.out(31190): 334 VXNlcm5hbWU6
04-01 07:57:39.355: I/System.out(31190): bWljaGFlbC5hc2FyYWZAZ21haWwuY29t
04-01 07:57:39.460: I/System.out(31190): 334 UGFzc3dvcmQ6
04-01 07:57:39.470: I/System.out(31190):
04-01 07:57:39.990: I/System.out(31190): 535-5.7.8 Username and Password not accepted. Learn more at
04-01 07:57:39.990: I/System.out(31190): 535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257    q41sm37770244eez.7 - gsmtp

And an exception:
04-01 08:00:57.860: W/System.err(31190): javax.mail.AuthenticationFailedException
04-01 08:00:57.880: W/System.err(31190):        at javax.mail.Service.connect(Service.java:319)
04-01 08:00:57.885: W/System.err(31190):        at com.my_android_assistant.OAUTH.OAuth2Authenticator.connectToSmtp(OAuth2Authenticator.java:128)

Answer: It's not using the OAuth2 provider because the server advertises LOGIN so JavaMail chooses that first.  You need to disable the LOGIN and PLAIN mechanisms to force it to use SASL and choose XOAUTH2.  Set "mail.imaps.auth.login.disable" and "mail.imaps.auth.plain.disable" to "true".
Also, you might want to try the OAuth2 support built into JavaMail 1.5.2.  A SNAPSHOT release is available.
Comment: That sounds good thanks (ill try it later). One more thing in prior version of my code i used java mail to send mail using the user pass (askingg him for credentials). if i understant correct you are saying that i can use the java.mail 1.5.2 with the OAUTH token insteat of the password and just use my prior code?

Connecting to user email with oauth2


Parameter estimation in log linear models

Question: Can anyone explain to me how parameter estimation is computed in log linear models? I followed this paper which is quite good, however I'm a bit confused in the parameter estimation part which is computed by this equation:
$$
\sum_{i=1}^{n} \log\,p(y^{(i)}| x^{(i)};v)
$$
Comment: What's your question?
Comment: a short explanation maybe, as we might have millions of features and for each feature we have to estimate the weight. Does this equation estimates all the parameters at once or you have to maximize the function for each parameter??
Comment: That equation is the log-loss.   We want to find $v$ to minimize the loss, which is the same as maximizing the log-loss.  They minimize the loss function by gradient descent.  The calculation of derivatives is a bit silly since these results are all known for the general case of exponential families.
Comment: It would probably be better to find a machine learning textbook and read about "loss functions", and "gradient descent".
Answer: This is done with maximum likelihood. The formula you showed is the log likelihood: the logarithm of the probability of observing the data given the parameters $v$. You try to find those parameters that maximize the probability of observing the data you have observed. Pragmatically, you can estimate many log-linear models using just Poisson regression after you have appropriately prepared the data.
Comment: I know that we maximize the equation using maximum likelihood to find v, however my question is: v here is just one parameter or a vector of parameters?
Comment: That depends on what kind of log-linear model you want to estimate. The simplest log-linear model will try to summarize the entire table with just 1 parameter. Needless to say, it often does not fit very well...


Distance to shop long/lat

Question: I want to create a filter where companies are able to find users within eg. 10 kilometers using users added long/lat and the company's long/lat they have added.
I am using geolocation but how am I going to go about this?
Comment: the Location module ( http://drupal.org/project/location ) has Views integration that supports this.
Comment: great thank you for your help. Just what I was looking for
Answer: As Jimajamma pointed out, the Location module along with Views will allow you to filter by distance. I am currently using zipcodes to filter by, but one could do geocoordinates as well.
Here is a step by step article on how to achieve filtering.  Although the article is a tad old, it is still relevant and can easily be adapted for drupal 7.
http://drupal.org/node/359463

Distance to shop long/lat