A finite group of order $p^n$ cannot have a center of order $p^{n-1}$

Question: I am aware that this is a relatively simple question if you use quotients, because $G/Z(G)$ has order $p$, and hence the quotient is cyclic, and therefore $G$ is abelian, so the center is the whole group, contradiction.
However, I am interested in a proof that does not use quotients, normality, Cauchy, Sylow, or similar tools. I came across one such proof, but I have a question about one particular detail. Here is the relevant part:
Suppose $|Z(G)| = p^{n-1}$. Then $G$ is not abelian. Take an element $x$ that is not in the center, and consider the elements $x, x^2, \ldots ,x^{p-1}$. The claim is now that none of these elements are in the center of $G$. For suppose one of these elements were in the center. Then $x^k \in Z(G)$ for some $k$ such that $2 \leq k \leq p - 1$. Now the center has order $p^{n-1}$, so $(x^k)^{p^{n-1}} = e$, and so $|x|$ divides $p^{n-1}k$ and $|x|$ divides $p^n$. Therefore $k$ must be a power of $\mathbf{p}$.
Why is the part in bold true? Why can't $k$ be any integer between $2$ and $p^{n-1}$?
PS: if you know of another proof that doesn't use any of the weapons mentioned above, please share.
Comment: By the way, I suspect that what it says is "Now the center has order $p^{n-1}$ so $(x^k)^{p^{n-1}}=e$..." (rather than $(x^k)^{p-1}$....)
Comment: @Mike I don't know. I did not downvote your answer. But I also didn't upvote it because 1) you wrote much more than what was necessary to answer my very particular question, and 2) what you did write wasn't clear at all (to me, anyway). Contrast your answer with Arturo Magidin's. I hope you are not offended. Also, you cannot expect that every answer you provide will be accepted, just like no one else can reasonably expect this.
Comment: @Mike: It is generally fruitless to ask for reasons for downvotes; if the person giving the downvote does not comment at the time, you'll never find out. It can be anything from "I think this is wrong" to "I can't follow this" to "I disagree with some opinion or statement written in the answer."  My second-highest-voted answer is also the most heavily downvoted.
Comment: Yes, thanks, that was a typo. Corrected.
Comment: @Junglemath may I ask why my answer was downvoted/not upvoted? My answer is correct and it was up before the other answers. I also spent a bit of time writing it out carefully too.
Comment: Thats fine @Junglemath
Answer: That's not well written; rather, $k$ cannot lie in the required range.
If $1\lt k\leq p-1$, then $\gcd(k,p)=1=\gcd(k,p^n)$, since $p$ is prime. Therefore there exist integers $\alpha$ and $\beta$ such that $1=\alpha k+\beta p^n$.
Now,
$$x = x^1 = x^{\alpha k + \beta p^n} = (x^{\alpha k})(x^{\beta p^n}) = (x^k)^{\alpha}(x^{p^n})^{\beta} = (x^k)^{\alpha}e^{\beta} = (x^k)^{\alpha}\in Z(G),$$
since $x^k\in Z(G)$. But this contradicts the choice of $x$. Thus, none of $x$, $x^2,\ldots,x^{p-1}$ lie in $Z(G)$.
From this point, you can complete the proof by noting that $\langle Z(G),x\rangle$ contains at least all elements of the form $zx^i$ with $z\in Z(G)$ and $0\leq i\leq p-1$, and all are distinct (if $zx^i=wx^j$ with $j\geq i$, then $x^{j-i}=w^{-1}z\in Z(G)$, hence $j-i=0$, so $i=j$ and $z=w$). This gives you $|Z(G)|p = p^n$ elements. Thus, $\langle Z(G),x\rangle=G$, but then $G$ is abelian: any element in the generating set commutes with every element in the generating set.

Added. In comments I mention that one can show that the smallest value of $k$ such that $x^k$ lies in $Z(G)$ must be a power of $p$ (without using quotients, of course).
To expand: let $k$ be the smallest positive integer such that $x^k\in Z(G)$. We know that the order of $x$ is a power of $p$, say $p^t$. Let $\gcd(k,p^t)=p^s$. Note that of course $s\leq t$.
Let $\alpha$ and $\beta$ be integers such that $\alpha k + \beta p^t = p^s$. Then
$$x^{p^s} = x^{\alpha k + \beta p^t} = (x^k)^{\alpha}(x^{p^t})^{\beta} = (x^k)^{\alpha}\in Z(G),$$
thus, $x^{p^s}\in Z(G)$; as $p^s| k$ and $k$ is the smallest positive integer such that $x^k\in Z(G)$, it follows that $p^s=k$, so the smallest $k\gt 0$ such that $x^k$ that lies in $Z(G)$ is a power of $p$, as claimed.
Comment: @Junglemath: I don't think you really "grokked" what the argument was doing. I've added the proof of the assertion, and you can see that it is exactly the same argument as before.
Comment: @Junglemath: I deleted some stuff that wasn't needed; it's given by the $\gcd$. Fixed.
Comment: @Junglemath: **It's the same argument!** Because $\gcd(k,|x|)$ will lie in $H$, and since $\gcd(k,|x|)\leq k$, it follows that $\gcd(k,|x|)=k$, so $k$ divides $|x|$.
Comment: (above should be "$x^{\gcd(k,|x|)}$ will lie in $H$"...)
Comment: Two things: 1) should you have $1 < k \leq p-1$? 2) So is the author simply wrong about the bolded part in my question?
Comment: @Junglemath: Yes; I originally had $1\leq k$, and when I corrected I over-corrected. Yes, the assertion given by the author does not follow from what they have, though one can show in other ways that the least $k$ such that $x^k\in Z(G)$ must be a power of $p$; just not *that* way.
Comment: How, for example? Is it related to what the other answer outlines?
Comment: @Junglemath: For the reason I gave: if you take the least such $k$, and you write $k=ap^r$ with $\gcd(a,p)=1$, then you can use the gcd to show that in fact $x^{p^r}$ lies in $Z(G)$, and hence that $a=1$.
Comment: I understand how you showed that $x \in Z(G)$ in your answer, but there you did not claim anywhere that $k$ was the smallest value for which $x^k \in Z(G)$. Thus I don't see how the method used in your answer is the same as the one you just left in the comment.
Comment: What is $s$? I don't see where it was defined.
Comment: @Junglemath: Basically, in **any** group, if $H$ is a subgroup, and both $x^r$ and $x^s$ lie in $H$, then $x^a\in H$ where $a=\gcd(r,s)$. In particular, the smallest $k$ such that $x^k\in H$ is always a divisor of the order of $x$.
Comment: I agree with the first sentence, but why does the second sentence follow?
Comment: I see now. Very good.
Answer: In general, for the centralizer of an element $x \in G$ we have $Z(G) \subseteq C_G(x) \subseteq G$. Since in your case $|G:Z(G)|=p$, we conclude $Z(G)=C_G(x)$ or $C_G(x)=G$. In both cases it follows that $x \in Z(G)$. So $G \subseteq Z(G)$, and hence $G$ must be abelian.
Comment: The result in the OP follows from a different result that says that the center cannot have prime index in a finite group, which is essentially what you are saying. But I was mainly interested in the bolded part of my OP that was asserted by the author, but which turns out to be false, as pointed out by a couple of people here (as I suspected).
Comment: Ah OK, I concentrated on using elementary methods (as you pointed out, not using quotients, normality, Cauchy, Sylow, or similar tools).


Issue with running Linux Audit System in a nested Virtual Machine inside Google Cloud Engine

Question: I am trying to run the Linux audit system in a nested Virtual machine on the google cloud engine.  The problem I am facing is that the Linux Audit System suspends after showing the following error after a few minutes when I view the auditd status.
جنوری 29 16:53:42 fuzzer-VirtualBox auditd[294]: Audit daemon has no space left on logging partition

جنوری 29 16:53:42 fuzzer-VirtualBox auditd[294]: Audit daemon is suspending logging due to no space left on logging partition

I checked using the df -h command and found out that there were around 6GB of free space on the logging partition so I did not understand why this error is occurring. Can you provide me a solution? Could this be because of nested virtualization?
Below is my auditd.conf:
#
# This file controls the configuration of the audit daemon
#

local_events = yes
write_logs = yes
log_file = /var/log/audit/audit.log
log_group = adm
log_format = RAW
flush = INCREMENTAL_ASYNC
freq = 50
max_log_file = 24
num_logs = 50
priority_boost = 4
disp_qos = lossy
dispatcher = /sbin/audispd
name_format = NONE
##name = mydomain
max_log_file_action = keep_logs
space_left = 75
space_left_action = SYSLOG
verify_email = yes
action_mail_acct = root
admin_space_left = 50
admin_space_left_action = SUSPEND
disk_full_action = SUSPEND
disk_error_action = SUSPEND
use_libwrap = yes
##tcp_listen_port = 60
tcp_listen_queue = 5
tcp_max_per_addr = 1
##tcp_client_ports = 1024-65535
tcp_client_max_idle = 0
enable_krb5 = no
krb5_principal = auditd
##krb5_key_file = /etc/audit/audit.key
distribute_network = no

Below are my parameters in audit.rules file:
## First rule - delete all
-D

## Buffer size
-b 8192

## This determine how long to wait in burst of events
--backlog_wait_time 0

## Set failure mode to syslog
-f 1

Answer: As per the error message, you should you try to:

Clear unwanted files from /var to recover free space.
Increase the size of /var file system.
The /etc/audit/auditd.conf configuration file contains the space_left option which describes numeric value in megabytes that tells the audit daemon when to perform a configurable action because the system is starting to run low on disk space. Check auditd.conf man page for more information on possible actions and their behavior.

This could be caused by:

The /var file system does not have enough free space.
The auditd daemon writes "Audit daemon is low on disk space for logging" in messages log file when the log destination file system does not have enough free space.

Reference
Answer: It's probably out of inodes, that also manifests as ENOSPC.
df -i

should be able to tell you.
Comment: Thanks for answering. I have checked and there are plenty of free inodes available.


Como criar um CardView igual ao Google Play

Question: Bom dia,
Estou querendo criar um layout igual ao da Google Play, porém não estou sabendo como fazer o design. Poderia me ajudar?
https://i.stack.imgur.com/XW2wT.jpg
Link do código XML
https://pastebin.com/sNytLsNz
Comment: Igual em que sentido?!
Answer: O  problema é que você não definiu um child principal para o cardview. Essa child, que será um viewgroup vai organizar todas as outras views dentro do cardview chegando ao resultado que você quer.
<android.support.v7.widget.CardView
       android:id="@+id/cardview"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:padding="50dp">

       <LinearLayout
           android:orientation="vertical"
           android:layout_width="match_parent"
           android:layout_height="match_parent">

                 <TextView
                     android:id="@+id/ads_title"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_margin="10dp"
                     android:text="Melhores preços" />

                 <android.support.v7.widget.RecyclerView
                        android:id="@+id/recycler_ads"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_marginRight="5dp"
                        android:layout_marginTop="40dp"
                        android:scrollbars="none" />

       </LinearLayout>
</android.support.v7.widget.CardView>

Comment: Obrigado, resolveu meu problema!


Legendre Symbol, Jacobi Symbol, and Quadratic Residues..

Question: I am looking at this problem and I am confused on how one could easily compute this. Is it just the intersection of either non-quadratic residue or quadratic residues of the respective p and q?
Comment: What is the question again?
Answer: If you want to find $x$ such that it is a QR mod p and a NR mod q for example, you can just find a QR mod p (say m), find a NR mod q(say n), then use Chinese remainder theorem to solve
$$\begin{cases}x \equiv m & (\operatorname{mod} p) \\ x \equiv n & (\operatorname{mod} q) \end{cases}$$
Comment: Hi user27126, could you please provide an example for say i=1 and j=-1. I am not sure how the CR theorem can help here. Thank you.
Comment: Let's take $m = 0$, $n = 2$. You want to find x = 0 (mod 19), x = 2 (mod 37). Just use chinese remainder theorem to solve this congruence.
Answer: Firstly the case $i=j=1$ is simple since the number $1$ will do this.
Secondly when $i = -1$ and $j=1$ we can use the number $-1$ since this is a QR mod $p'$ (prime) if and only if $p'\equiv 1$ mod $4$.
Thirdly when $i=j=-1$ we can use the number $2$ since this is a QR mod $p'$ if and only if $p\equiv 1,7$ mod $8$.
For the final case we may use $-2$ since we can see that the product of the $i,j$ values in the previous two cases match what we want (essentially we are using the homomorphism property of Legendre symbols here).
Comment: Sorry. I have problems parsing this. What are the variables $i$ and $j$? Where did they come from?
Comment: Hi fretty, why is mod 8 or mod 4 used or derived from? Thanks
Comment: These are the simple rules about when $-1$ or $2$ are QR's mod $p$
Comment: The question seems to have been edited!
Answer: The solution by user27126 is fine, but you can cut a few corners. For example, there is one kind of number $n$ that is guaranteed to be a quadratic residue mod $p$ for all $p$ not dividing $n$ - do you know what I'm referring to? Also, you should know when $-1$ is a residue, that should settle another case without any need to resort to Chinese remainders. If you know when 2 is a residue, there goes another case. And so on.


What do I need to read to understand dimensions and spacetime?

Question: The concept of dimension seems to be:

In physics and mathematics, the dimension of a space or object is
  informally defined as the minimum number of coordinates needed to
  specify any point within it.

According to wikipedia. But the fourth dimension seems to have also some kind of connection with spacetime which seems to be related to Minkowski spaces. I want to understand dimensionality and also learn about these issues about spacetime.
I'm searching for references on what I should read in order to understand this,  I'm searching for a serious way (no pop-science) to understand it, I'm searching for a list of topics and also some recomendations on textbooks for it.
I hope I'm not asking too much, but I'm very curious to grasp this subject. I'm also realistic on this, I do not think it's something easy of fast to learn.
EDIT: I've found some books on Minkowski spaces, I guess I'll be able to understand from those in the near future.
Answer: There are two different concepts of the fourth dimension in what you talk about.  Four dimensional Euclidean space, $\mathbb R^4$ has four equivalent coordinates.  To find the distance between two points, you sum the squares of the differences of coordinates and take the square root.  Many things are similar to your experience in $\mathbb R^3$
Spacetime is a different creature.  The time axis is fundamentally different from the three space axes.  Your normal experience should tell you this and it doesn't lie.  Mathematically it is because the "metric" has a minus sign on the difference in time-$d^2=\Delta x^2+\Delta y^2+\Delta z^2 -c^2\Delta t^2$  This means "distances" are not positive definite.  Anywhere a light ray goes is zero distance.  If the distance between two points is greater than zero, they can't influence each other and there is a reference frame where they happen at the same time.  If the distance is less than zero, one precedes the other and does in all reference frames.
Comment: Distance between two points less than zero? Is it possible? How? I intuitively thought that the distance between two points could always be a positive number.
Comment: Oh sorry, I guess you're saying something like: $D>0=$ something in my front and $D<0=$ something in my back. Is this it?
Comment: Actually, what can be negative is the square of the distance, this is because in Minkowski space the time axis is imaginary, so the distance itself can be an imaginary number. But Gustavo, from my point of view, it is just a math trick that extends the intuitive definition of distance in real space to other physical system. I dont think there are many physicists that think that an imaginary axis is "real" (but I might be wrong)
Comment: @julianfernandez:  In fact, there is a discussion in Wheeler's gravitation about how you can call the time axis imaginary (in that the coordinates are $ict$) in special relativity and make things work, but not in general relativity.  You have to view the minus sign as coming from the metric.  I don't remember the details.
Comment: @Ross thanks, I wasn't aware of that!!
Answer: It is easy to be confused because the different meanings often given to the "fourth dimension". In the simplest an more natural case, the fourth dimension is just another spatial dimension, and you can have as many dimensions as you want. An introductory book on linear algebra should make it easy to understand (look for metric spaces in particular). This fourth dimension has nothing to do with time. But...
In physics, relativity theory defines a relationship between space an time, in the sense that space and time can be interchanged if two observers move relative to each other. The equations for this relationship resemble those of metric spaces. The equations look as if time behaves like an "imaginary" (because in involves imaginary numbers) extra spatial dimension. In the end the mathematical structure can be described as something called Minkowsky space, although it doesnt behave like an actual spatial four dimensional spatial space. Because of this relationship between time and space, usually people  consider time as the fourth dimension, but it is not a good analogy. A fourth spatial dimension would behave very differently, and moving into a 4D space from somebody inhabiting 3D space would be equivalent to moving into 3d space for somebody living in a 2d planar surface. You can read about hypercubes to get a better intuition.
But remember, dont mix extra spatial dimensions with time as a fourth dimension, they are completely different stuff.
Answer: A big difference between 4d space and spacetime is its size. Consider the size (Cardinality) of all the sets which have a one to one mapping between the digits on my hand and their members to be 5. Define the Cardinality of the set of all integers as $\aleph_0$, said as aleph-null. Note that it is possible to produce a 1 to 1 mapping between the set of integers and the set of even integers. This is a property of infinite sets, they have 1 to 1 relationships with proper subsets of themselves, and these subsets have the same cardinality as the original set.
Note that $\aleph_0+\aleph_0=\aleph_0$. The set of Real numbers is composed of Integers + Fractions + Irrational + Transcendental numbers. The cardinality of Integers Fractions and Irrational numbers is $\aleph_0$. The cardinality of transendental numbers is $\aleph$ which is larger than $\aleph_0$ (probably $\aleph_1$ but not proven to be). $\aleph_0+\aleph_0+\aleph_0+C=C$ and this is the cardinality of the points on a line. A line is a proper subset of 2d space so the cardinality of 2d (and by extension any_d) space is C.
Spacetime may be imagined as your monitor consisting of C pixels each of which may represent any colour. Replacing the monitor with 3d space and the colour with time infers that spacetime has C points. This is F (probably $\aleph_2$ again not proven) because it is also the cardinality of the set of all single valued functions.
We have N < C < F. This makes it possible to resolve Zeno's paradoxes by having the arrow stationary in spacetime but moving in 3d.
This is called Relativity and would be the mathematical framework for a 3d universe moving through some other thing. Special Relativity and General Relativity continue the Relativity tag because it was thought that the universe would be explained based on this model. It turned out that realizing that the arrow and the observer have a different understanding of what is NOW is more fruitful.
Comment: Well, but we still have $|\mathbb{R}^n| = \mathfrak{c}$ for every $n \in \mathbb{N}$. Even though cardinality is meant to talk about the size of a set, it's something pretty different than the notion of dimension that comes from linear algebra and differential geometry.
Comment: @user1620696:  you are correct.  This answer merits a -1


O que é observabilidade e quais são seus benefícios em relação a sistemas de software?

Question: Ando lendo a respeito do termo Observabilidade em relação ao campo da computação e sistemas de softwares, e junto com esse termo me surgem outros termos que são: Sistema de Observabilidade, Telemetria e assim por diante. Não sei se isto é algum conceito novo ou antigo e que "ressurgiu das cinzas".
Ainda não está claro para mim de forma precisa o que é Observabilidade no contexto de sistemas de softwares, portanto, eu gostaria de ter as seguintes dúvidas esclarecidas:

O que é Observabilidade?
Qual a vantagem da Observabilidade e o que ela traz de benefício para sistemas de software?
O que seria um Sistema de Observabilidade?
Qual a relação da Telemetria com a Observabilidade?
Answer: Está bem na moda, né? Bem, não posso dizer que é modinha, tem uma função importante. Em alguns casos abusa-se, mas em geral é interessante.

observabilidade ( ob·ser·va·bi·li·da·de )
nome feminino Qualidade do que é observável (ex.: observabilidade da
informação; observabilidade do comportamento).
etimologiaOrigem etimológica:forma alatinada de observável + -dade.
Palavras relacionadas observável observavelmente radiante quantização
metagaláxia fenótipo fenotipicamente observável ( ob·ser·vá·vel )
adjectivo de dois géneros

Que pode ser visto ou observado.

Que merece ser observado.

Que pode ser medido de forma directa (ex.: grandeza observável).

nome masculino
4. Quantidade ou grandeza que se pode medir directamente.
etimologiaOrigem etimológica:observar + -ável.
"observabilidade", in Dicionário Priberam da Língua Portuguesa [em
linha], 2008-2023, https://dicionario.priberam.org/observabilidade.

E temos definições mais específicas, como na matemática (tem gente que ainda acha que não precisa saber matemática para programar):

Observabilidade, na teoria de controle, é uma medida do quão bem podem os
estados de um sistema ser inferidos a partir do conhecimento de suas
saídas externas. A observabilidade e a controlabilidade de um sistema
são conceitos matemáticos duais.
Formalmente, um sistema é dito ser observável se, para qualquer
possível sequência de vetores de estado e de controle, o estado atual
pode ser determinado em tempo finito usando apenas as saídas (esta
definição é voltada à representação no espaço de estados. Menos
formalmente, isto significa que a partir de saídas do sistema é
possível determinar o comportamento de todo o sistema. Se um sistema
não é observável, isto significa que os valores atuais de alguns de
seus estados não podem ser determinados através dos sensores de saída:
isso implica que o seu valor é desconhecido para o controlador e,
consequentemente, que ele não será capaz de cumprir as especificações
de controle referente a estas saídas.

Fonte. Melhor.
De uma certa forma sempre se usou isso. Mais recentemente se formalizou mais a definição, o termo entrou na boca das pessoas e passou ter inúmeras ferramentas para auxiliar, da mesma forma que tem para testes, depuração, etc.
Quanto mais você tem sistemas funcionando 24x7 (missão crítica, ou quase isso) mais se torna necessário saber se tudo está correto. Quanto mais tem usuários que você não tem contato direto para te informar de problemas no software, mais você tem que descobrir isso através de verificação pelo próprio software.
Em computação a observabilidade é a característica que algo tem para poder ser monitorado. Indica se tem meios de descobrir o que está acontecendo ou aconteceu com o software quando estava sendo executado.
Difere de testes porque é usado em produção e espera-se que nunca identifique anomalias, ainda que isso acabe sendo comum ter.
E também não é só sobre perceber erros, mas falhas que não são do software, ataques, uso fora do normal, e prover medições para tomar decisões em relação a uma série de coisas, de infraestrutura ou até mudanças de arquitetura.
Os mecanismos mais comuns para fazer isso é o logging, o tracing e profiling.
É fundamental em cenários de SRE, algo que explodiu recentemente.
Embora seja melhor em sistemas mais críticos e grandes, qualquer implantação pode se beneficiar, até mesmo como forma de auditoria, ainda que não seja o propósito principal. Claro que sistemas distribuídos serão mais beneficiados. Como esses sistemas são complexos sem isso há muitos riscos e dificuldade de traçar um mapa do que está acontecendo ou aconteceu. Mesmo com informações pode complicar, por isso sistemas distribuídos devem ser evitados até que seja absolutamente necessário.
Com algo observável é possível sanar problemas mais facilmente porque você tem dados, ou prevenir que problemas aconteçam porque dados já indicam um padrão que resultará em algo ruim.
Em geral, além do monitoramento, estabelece-se métricas do que é considerado normal e anormal, quando emitir alertas ou tomar ações proativas para mitigar algum possível problema.
O termo principal é praticamente sinônimo de telemetria e monitoramento. Em tese a telemetria seria algo remoto, mas não vejo isso como algo tão relevante, seria preciosismo determinar uma diferença, ainda que na prática quase sempre será remoto mesmo. Você precisa da observavilidade na solução para conseguir esses dois outros.
Sistema de observabilidade eu imagino ser uma solução que fornece ferramentas necessárias para coletar, armazenar, gerenciar e visualizar os dados vindos das soluções principais que estão rodando. Há toda uma indústria investindo em ferramentas deste tipo.
O termo costuma implicar que tudo é feito o tempo todo sem muita intervenção humana, diferente de outras formas de monitoramento mais simples e pontuais, com um objetivo mais específico.
Ela é fundamental para garantir alta disponibilidade.


JQuery Fade Slideshow bug

Question: I made a slideshow of images in jquery using the fadeIn functionality. Now, the slideshow works fine except for one tiny problem. When it reaches the last image, it's supposed to return back and the first image is supposed to fade in. But, instead, the first image just shows; it doesn't fade in. Here's my jquery code below:
var index = 1;

 $(document).ready(function() {
    $('.wallpaper:not(:nth-child(' + index + '))').css({ display : 'none' });
    slideShow();
});

function slideShow() {
    var $firstImg = $('.wallpaper:nth-child(' + index + ')');
    $('#para1 h3').text(index);
    if ($firstImg.next().length) {
    index ++;
    } else {
    index = 1;
}

var $nextImg = $('.wallpaper:nth-child(' + index + ')');

$nextImg.delay(6000).fadeIn(2000, function() {
    $firstImg.hide();
    $('#para1 h3').text(index); // This is just for debugging purposes
    $('#para2 h3').text($firstImg.attr('alt') + ' ' + $firstImg.css('display') + ' ' +
    $nextImg.attr('alt') + ' ' + $nextImg.css('display')); // This too
    setTimeout(slideShow());
});
}

Help would really be appreciated.
In the answer I need to know why this is happening along with the solution. (i'm new)
Thanks.
Comment: I think the problem is on the last function, `$firstImg.hide();` will just make it disappear at once. If `$nextImg` is not somehow z-indexed before $firstImg
Comment: It worked. But could you please tell me why it wasn't a problem during the first two images
Answer: Your images will fade in one by one, on top of one another, and the old image in the background will hide once the fade in has completed. The reason this works is because subsequent images are all shown on top of the previous.
With the last image, however, an image from the bottom will be faded in, but it will not be shown, as the top-most image is showing above it. The first image in the set will fade in in the background, and it will appear, suddenly, at $firstImage.hide(), when the image above it is hidden.
Answer: The problem is on the last function run, $firstImg.hide(); will just make it disappear at once, if $nextImg is not somehow z-indexed before $firstImg
On the previous runs, the pictures which are being faded in are on top of the previous picture. So the last picture is above the first one.
When you fade in the first one again at the end of this "loop", the last one is still on top, and will disappear only when you call hide().

JQuery Fade Slideshow bug


Exponential Growth, half-life time

Question: An exponential growth function has at time $t = 5$
a) the growth factor (I guess that is just the "$\lambda$") of $0.125$ - what is the half life time?
b) A growth factor of $64$ - what is the doubling time ("Verdopplungsfaktor")?
For a), as far as I know the half life time is $\displaystyle T_{1/n} = \frac{ln(n)}{\lambda}$ but how do I use the fact that we are at $t = 5$?
I don't understand the (b) part.
Thanks
Answer: The growth factor tells you the relative growth between $f(x)$ and $f(x+1)$, i.e. it's $$
  \frac{f(t+1)}{f(t)} \text{.}
$$
If $f$ grows exactly exponentially, i.e. if $$
  f(t) = \lambda\alpha^t = \lambda e^{\beta t} \quad\text{($\beta = \ln \alpha$ respectively $\alpha = e^\beta$)} \text{,}
$$
then $$
  \frac{f(t+1)}{f(t)} = \frac{\lambda\alpha^{t+1}}{\lambda\alpha^t} = \alpha = e^\beta \text{,}
$$
meaning that, as you noticed, the grow factor doesn't depend on $t$ - it's constant.
The half-life time is the time $h$ it takes to get from $f(t)$ to $f(t+h)=\frac{f(t)}{2}$. For a strictly exponential $f$, you have $$
  f(t+h) = \frac{f(t)}{2} \Rightarrow \lambda\alpha^{t+h} = \frac{\lambda}{2}\alpha^t
  \Rightarrow \alpha^h = \frac{1}{2} \Rightarrow h = \log_\alpha \frac{1}{2} = -\frac{\ln 2}{\ln \alpha} = -\frac{\ln 2}{\beta} \text{.}
$$
Similarly, the doubling-time is the time $d$ it takes to get from $f(t)$ to $f(t+d) = 2f(t)$, and you have $$
  f(t+d) = 2f(t) \Rightarrow \lambda\alpha^{t+d} = 2\lambda\alpha^t
  \Rightarrow \alpha^d = 2\Rightarrow h = \log_\alpha 2 = \frac{\ln 2}{\ln \alpha} = \frac{\ln 2}{\beta} \text{.}
$$
Thus, you always have that $d = -h$ for doubling-time $d$ and half-time $h$, which of course makes sense. If you go forward $d$ units of time to double the value, then going backwards $d$ units halves the value, similarly for going forward respectively backward $h$ units to half respectively double the value.
In your case, you get that the doubling time for (b) is $\frac{\ln 2}{\ln 64} = \frac{1}{6}$. For (a) you get that the half-life time is $-\frac{\ln 2}{\ln \frac{1}{8}} = \frac{1}{3}$.
You can also derive those by observing that a growth factor of one-eight means that going forward one unit of time means the value decreases to one-eight of the original value. Thus, after going forward one-third unit, the value decreases to one-half, since if if it decreases three times to one-half each, it overall decreases to one-eight.
Similarly, if the value increases to 64 times the original value when going forward one unit of time, you have to go forward one-sixt unit of time to have it increase to twice the value, since $2^6 = 64$.

Exponential Growth, half-life time


Passing Self-Refreshing Changing Variable

Question: I'm making a web application that lets people, with an invitation, track other people. I'm using javascript geolocation. I need a variable that passes to another page, but also needs to be refreshed every five seconds or so. All this is done only when the person who is being tracked is on the first page. A database accessed with ajax and the variable changing every five seconds seems like overkill.
Thanks in advance!
Answer: Try localStorage
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
That will store data into the browser, but associated with that particular URL.  So the page can always access it.
If that doesn't fit the bill, look into sessionStorage or indexedDB.
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
Comment: So localStorage is accessible by other browsers?
Comment: No. localStorage is not accessible by other browsers.  If you need it across browsers, then you need remote storage.
If you don't have control over a remote server, then kinvey.com (google) or parse.com (facebook) might be of use. They are like instant backends. There are other providers as well. They are simple remote key/value stores with authorization.


Is that correct about dimensionality reduction and clustering?

Question: Could you please help me to understand it because I'm not sure if I got it correctly. Let's say I have a dataset, of persons, with 100 features, various characteristics like height, weight, age, etc. I want to classify if are normal or abnormal. By abnormal I mean if a 20 years old man is 170cm and 150kg to identify it as abnormal.
Should I use Self Organising Map to reduce the dimensionality (these 100 features) and then K-means to classify them into normal and abnormal? Is that a correct approach?
And if later I'd like to find why this person has included into the abnormal class how can I find that this happened because of these two features, his weight according to his height?
Answer: This depends a lot on your method.
For above data set, decision trees and random forest may work well.
They do not need dimensionality reduction; it will likely even harm your result.
K-Means on the other hand will not work on such data very well, because data normalization is really difficult to do right.
But you appear to be interested in classification, not clustering anyway.
Comment: So, can I just use K-NN? With hundreds features? And then a decision tree in order to find somehow the features which are responsible for the abnormality?
Comment: What do you mean by K-NN here? You do not combine K-NN with decision trees.
Comment: Anony-Mouse How many features can I use with K-NN without the need of any algorithm for dimensionality reduction?
Comment: Depends on your data. With textual data and cosinen thousands. With Euclidean: a dozen or two, if you carefully weighted them. Or you use an algorithm that better fits your data & problem.


How to decouple the Router and Navbar so the Navbar component is not including components

Question: I am creating a portfolio website, where in this design, I have a background for the entire website that will stay fixed as content scrolls over it.  The Navbar is also fixed, and has the content scrolling under it.
This design looks cool, and wasn't too hard to put together, but I am having a little bit of trouble incorporating React Routing into this mix.
From what I gathered, the tutorials say to create a App-Router component, which basically looks like their way of saying "Navbar".  So I did that and got my Navbar to route to my Home, and About Me component pages.  However, since my Navbar is fixed, all the pages refuse to scroll, which means they are being included inside the Navbar component.  This is the opposite of what I want to have happen.
My Ideal setup would be to have the Navigation Bar (It's own component) send a routing request to a Routing component, which will then render that component (bellow the Navbar, still contained within the app container which contains the background).
Here is some psuedo code of my structure so far (the bad code):
App.js

        <Navigation />
        {/* <other components to render here /> */}

App.css
     background-image: url(blah);
     background-attachment: fixed;
     z-index: -1;

Navigation.js
    <Router>

            <Container>
                <Row>
                    <Link to="/">Home</Link>
                    <Link to="/About">About Me</Link>
                </Row>
            </Container>

            <Route path="/" exact component={Home} />
            <Route path="/About" component={About} />

    </Router>

Navigation.css
    .App-navigation {
        // blah blah
        position: fixed;
        z-index: 10;
    }

About.js and Home.js just having their respective page content.
With the above, even though Home has more content than the page height, obviously the containing navbar's fixed position prevents scrolling.
I'm pretty new to React, so I'm not sure on the proper procedure in setting up a app routing component, or where it's supposed to fit into the app architecture.  Any help or guidance is appreciated!
Comment: It's as simple as moving your Route components outside of the Navigation component. Basically just have Link components in your Navigation component and put your Route components into your main container component or whether you want them to actually render the contents of the views.
Comment: @AlexanderStaroselsky can you post an answer with an example of what you say above?
Comment: I've created an answer showing the basic structure to render elements outside of component `Navigation`.
Answer: You simply need to restructure things a bit to ensure that routes/views/components render outside of component Navigation. Move Router to wrap most if not all children of App. Remove the Route elements from Navigation as Route is where the contents of each route/view/component will render. Move the removed Route elements to some other component outside of Navigation and inside Router.
App:

  <Router>
    <Navigation />
     {/* component for rendered components */}
  </Router>

Navigation:

  <Container>
    <Row>
      <Link to="/">Home</Link>
      <Link to="/About">About Me</Link>
    </Row>
  </Container>

Main:

  <Container>
    <Route path="/" exact component={Home} />
    <Route path="/About" component={About} />
  </Container>

Here is an example in action.
Hopefully that helps!
Answer: Two quick solutions.
1# Create only 2 components in your Router: app/portfolio and PageNot Found. Lazy load components that you wouldn't want to load immediately. Like About component. The only downside is that url wouldn't change, if you after it.
2# Just import Navbar component in every other page/component or use HOC pattern which basically will grant the same result.
Comment: I think #2 sounds more down my alley.  Combined with Alexander's' comment, this makes sense.  Thanks for the input!


How to mirror and repeat periodic function from a .csv file

Question: I have several .csv files with a half of a symetrical periodic fuction. What's the best way to plot a file, mirror it and then repeat origial and the mirror until end of x_range?
Edit:
Now I realised how to do it, but i am still intrested if there is a more elegant way to do this.
stats "KWV [100] прод.DAT" using 1 name "A"
stats "KWV [111] прод.DAT" using 1 name "B"
stats "KWV [100] поп.DAT" using 1 name "C"
stats "KWV [111] поп.DAT" using 1 name "D"
plot for [i = 0:3] "KWV [100] прод.DAT" using (i*2*A_max+ $1):2 with lines lc "green" notitle,for [i = 0:3] "KWV [100] прод.DAT" using ((i*2+2)*A_max-$1):2 with lines lc "green" notitle, keyentry with lines lc "green" title "[100] Продольные", for [i = 0:3] "KWV [111] прод.DAT" using (i*2*B_max+$1):2 with lines lc "red" notitle,for [i = 0:3] "KWV [111] прод.DAT" using ((i*2+2)*B_max-$1):2 with lines lc "red" notitle, keyentry with lines lc "red" title "[111] Продольные", for [i = 0:3] "KWV [100] поп.DAT" using (i*2*C_max+$1):2 with lines lc "blue" notitle,for [i = 0:3] "KWV [100] поп.DAT" using ((i*2+2)*C_max-$1):2 with lines lc "blue" notitle, keyentry with lines lc "blue" title "[100] Поперечные", for [i = 0:3] "KWV [111] поп.DAT" using (i*2*D_max+$1):2 with lines lc "magenta" notitle,for [i = 0:3] "KWV [111] поп.DAT" using ((i*2+2)*D_max-$1):2 with lines lc "magenta" notitle, keyentry with lines lc "magenta" title "[111] Поперечные"

Comment: Welcome to StackOverflow! Well, you are not giving to many details. Actually, it is kind of expected to provide some code and detailed description of the problem. Can you give a minimal (non-)working example? https://stackoverflow.com/help/minimal-reproducible-example
Comment: Thanks for providing some code. However, I'm still not sure whether you just want to repeat the original data in positive direction and repeat the mirrored data in negative direction, instead of flipping the data for every repetition in both directions? A sketch would help.
Comment: in order to illustrate: if your data is axially symmetric like `A`, there will be no difference `AAAAAA`. If your data might be asymmetric to zero, like `E`, it would be `3E3E3E3`, if you see `3` as mirror data of `E`. (and plotting `333EEEE` is probably not intended).
Comment: any response would be appreciated and would be considered as kind of minimum politeness...
Answer: Well, you are not giving too many details. Depending on what exactly you want, this could be one approach.
Code:
### horizontal mirroring of data
reset session

# create some test data
# curve from here: https://mathworld.wolfram.com/HeartCurve.html
set table $Data
    plot sample [t=0:pi:0.1] '+' u (16*sin(t)**3 + 3):(13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)) w table
unset table

set size ratio -1
set xrange [-25:25]
set grid xtics, ytics
xm = 3   # mirror axis

plot $Data u 1:2 w lp pt 7 lc "red" title "Original", \
     '' u (-($1-xm)+xm):2 w lp pt 7 lc "green" title "Mirror"
### end of code

Result:
Comment: of course `(-($1-xm)+xm)` can be shortened to `(-$1+2*xm)`, but the first way is maybe easier to follow what's going on with shifting and mirroring.
Answer: Providing code in the question is always helpful, even better if possible with some data and/or illustration.
Well, at least there is a way to present your gnuplot code more readable, i.e. breaking lines by using \ as the last character in a line (no other characters allowed afterwards in the same line).
Although you are not explicitely writing it, I assume your data is axially symmetric relative to x=0 (well, example $DataD is chosen central symmetric).
It depends what you consider "more elegant", at least you can make it a bit shorter such that you don't have to double the plot commands. You can define a function Mirror(i) = i<0 ? -1 : 1 which is -1 for negative arguments and +1 otherwise. Furthermore, you can add arrows to indicate the borders A_max, etc. (I assume these are crystallographic unit cells in your case).
Edit:
In case you want to flip your data (especially $DataD) for every repetition then simply define a function Flip(i) = i%2 ? -1 : +1.
Check out the following minimal example with data and with graph.
Code:
### periodic repetition of data
reset session

# create some test data
set table $DataA
    plot sample [-pi:pi] '+' u 1:(x**2/9) w table
set table $DataB
    plot sample [-pi:pi] '+' u 1:(cos(x)+3) w table
set table $DataC
    plot sample [-pi:pi] '+' u 1:(abs(x)/2+5) w table
set table $DataD
    plot sample [-pi:pi] '+' u 1:((x**3+x**2)/40+8) w table
unset table

stats $DataA u 1 name "A" nooutput
stats $DataB u 1 name "B" nooutput
stats $DataC u 1 name "C" nooutput
stats $DataD u 1 name "D" nooutput

set key out
do for [i=-4:3] {
    set arrow i+100 from first (2*i+1)*A_max, graph 0 to first (2*i+1)*A_max, graph 1 nohead dt 2
}
Mirror(i) = i<0 ? -1 : 1
Flip(i) = i%2 ? -1 : +1

plot for [i=-3:3] $DataA u ((i*2)*A_max + Mirror(i)*$1):2 w l lc "green" notitle, \
        keyentry w l lc "green" title "DataA", \
     for [i=-3:3] $DataB u ((i*2)*B_max + Mirror(i)*$1):2 w l lc "red" notitle, \
        keyentry w l lc "red" title "DataB", \
     for [i=-3:3] $DataC u ((i*2)*C_max + Mirror(i)*$1):2 w l lc "blue" notitle, \
        keyentry w l lc "blue" title "DataC", \
     for [i=-3:3] $DataD u ((i*2)*D_max + Mirror(i)*$1):2 w l lc "magenta" notitle, \
        keyentry w l lc "magenta" title "DataD", \
     for [i=-3:3] $DataD u ((i*2)*D_max + Flip(i)*$1):($2+2) w l lc "orange" notitle, \
        keyentry w l lc "orange" title "DataD flipped"
### end of code

Result:


Why bootstrap sub-theme with sass starterkit is not working?

Question: I am trying Bootstrap 7.x-3.6 theme.
But sub-theme for some reason is not working. I did follow the same procedure as described on the Documentation page for Drupal 7.
I am describing here, what I did,
1. Installed fresh drupal 7.50 on localhost.
2. Down loaded Bootsrtap 7.x-3.6 and enabled but not make is default.
3. Sub-theme: I did copy sass folder from the starterkits. Paste in /theme folder and rename with mysubtheme. Rename the file-name sass.starterkit with mysubtheme.info. And inside that changed the 'name'.

Final image of /theme folder

4. Downloding Bootstrap: Downloaded bootstrap file from here as decribed in following image. I did select Sass option. Pasted to /mysubtheme folder, rename with bootsrtap.(even to check, I did try all three options one by one, but same result)

5. Downloaded Jquery update module also and enabled, default version was 1.50.
Now, Till this stage the site shows content but not a basic theme formatting. Comparative image below.

What could be the reason or I am missing something.
Comment: Well I could go out on a limb and say you have to compile the SASS.
Comment: You should add information about compiling SASS, and the name, number of lines in, and location of the resulting .css-file to your question. Your "Base theme" looks OK, but your "Subtheme with sass" screenshot looks like there is no css present, so *something* has gone wrong with the sub-theming - but it is impossible to pinpoint what it is without knowing more about the css generated for your sub-theme. Also, what subdirectories to you have in your subtheme (is there a css subdirectory)? Have you removed the CDN?
Comment: @JeffBurnz Hi, Well I have already compiled the SASS, as I am using other themes, i.e. Adaptive theme for other trial site which is in same `htdocs` of MAMP, that all working well with SASS. Do I have to do some special for this, recompile?
Comment: Have you set the bootstrap theme as your base theme in your .info file?
Comment: @MarkConroy Yes, it is reading like `base theme = bootstrap`.
Comment: I did find the issue, in that `.info` file of subtheme in the last, there is a code `; Disable the CDN provider so compiled source files can be used.
settings[bootstrap_cdn] = ''`, I did comment out and now it is taking the same theme as base. BUT, still I am unable to use style.scss, I will update the infor regarding that.
Comment: @FreeRadical I have updated the image in question section. The issue of `not fetchign the base theme` is solved as i posted in above message. You also looks pointing put same thing by removing CDN, I did see your updated message after posting mine last one. Thanks, Still, the `style.scss` is not working, although it is separate isuue. I am reading `README.md`, will try that and will update.
Comment: @CodeNext I have the same problem. I'm wondering what to do next after downloading sass from getbootstrap.com and extracting it under mytheme folder. How to generate bootstrap.css or bootstrap.min.css. CodeNext did you solve this problem? If yes, please share us your solution. Thanks
Comment: @jaypabs 1. I was not able to get the original bootstrap styling to my sub-theme, but as I have mentioned in the answer how to get that. Now your issue seems different, it is like you wan to know, how to make the entire sub-theme using sass starter-kit and how to enable its all CSS, so you will be able to apply your CSS changes. I would say, if you visit the bootstrap theme page on [Drupal.org](https://www.drupal.org/project/bootstrap) there you can find the [link](http://drupal-bootstrap.org/api/bootstrap) and there you can follow the steps for sub-theming.
Comment: @jaypabs 2. Unfortunately, I still not able to figure out how to set-up theme with SASS, so eventually I moved to LESS..:( might be there could be a issue of composer or some issue to local environment...
Comment: @CodeNext Can you please tell me how did you compile sass under the subtheme that you created? I have already downloaded all necessary files to my subtheme folder and don't know what to do next. I'm using Windows, btw.
Comment: @CodeNext I get it to work but don't know if I am doing it right. I just compiled the style.scss and save it under css folder and seems the theme is working fine now. However, it seems that the file bootstrap.css is also compiled within style.css. Is this the correct?
Comment: @jaypabs I am not getting why the bootstrap.css comes in picture. You do not have to touch anything except SCSS folder, which has there files, `_default-variables.scss`, `overrides.scss`, `style.scss`, You just need to use `_default-variables.scss`, `overrides.scss`, and whatever your custom CSS you have to apply, you have to use `overrides.scss`, Amd do not need to use `styles.scss`. See description [here](http://drupal-bootstrap.org/api/bootstrap/starterkits%21sass%21README.md/group/subtheme_sass/7), how to use these files. You don't have to touch anything which is inside `bootstrap` folder
Comment: @jaypabs Did you find solution for your issues?
Comment: @CodeNext Yes. What I did is simply compile style.scss. And everything works as intended.
Comment: @jaypabs, Ok, and just read the link(here) in my last comment you will come to now which file you ahve to use and which not.
Answer: Thanks to @JeffBurnz @MarkCornoy and @FreeRadical for their inputs.
The following setting needs to be disable in mysubtheme.info(sass.starterkit A original file). And may be @FreeRadical want to point out same thing by asking "Have you removed the CDN?" in the his comment.

; Disable the CDN provider so compiled source files can be used.
settings[bootstrap_cdn] = ''

After commenting out settings[bootstrap_cdn] = '' it does take the base theme setting.
Any more suggestion appreciated. For now, this solution works.


MongoDB virtual memory usage

Question: I'm testing MongoDB for archives data. We have a collection with 160M rows.
MongoDB instance takes 76.2 Gb virtual memory on a 12 Gb physical memory box ;-)
The swap in null.
I read that virtual memory = physical + swap.
What's wrong in my case ? It this a problem for mongoDB itself ?
Thanks
Answer: MongoDB uses memory mapped files - which can be much larger then the actual physical (or swap) available on your machine.  The total virtual memory used will usually be the size of all the data on disk at the time as a result.
The resident memory will be the stat that represents the actual working set used, though depending on your resources on the box and the usage pattern this will tend to grow over time and approach the total physical RAM on the host.  Basically, unless the OS sees a need to page out old data (memory pressure) it will stay in RAM.
When you restart MongoDB this basically starts again from scratch.  So if you have a known time frame for your actual working data set (say you only ever use the last 7 days), then the set size after that time period (assuming regular, predictable use) will represent your approximate working set size in terms of RAM.
More info to be found in the Docs here:
http://www.mongodb.org/display/DOCS/Caching
http://www.mongodb.org/display/DOCS/Checking+Server+Memory+Usage
Finally, MMS (which is free) does a good job of mapping this out for you over time - Mapped, Virtual, Resident and non-Mapped as well as plenty of other stats (look for "i" over each graph for an explanation).
http://mms.10gen.com
Comment: Can you please define "disk" in your statement "The total virtual memory used will usually be the size of all the data on disk at the time as a result". Is disk the entire mount / volume on a Linux where mongo is installed, or is just the physical data directory where mongo would store the datafiles? Simply putting "disk" doesnt make much sense.

MongoDB virtual memory usage


Specifying specific priors for a correlation matrix via Stan

Question: I'm trying to estimate a correlation matrix for a model where I already have a sense of the values of the off-diagonals based on existing studies. I'm quite new to Bayesian analysis so trying to learn as I go along.
The Stan package is pretty bullish on using an LKJ prior for correlation matrices (see here). There isn't a way for me to encode a specific expected value of the correlation matrix into the prior. From my understanding I could use the inverse Wishart to generate a covariance matrix instead, but that isn't guaranteed to generate a correlation matrix (i.e. diagonal of 1).
Can anyone recommend the best approach here? If it's useful at all I'm trying to recreate exactly this example, except specify my prior knowledge about the correlation matrix.
Answer: The Stan documentation and examples often use the LKJ prior in situations that are unlike the one you are describing where you are pretty sure about the off-diagonals.
In the case of a confirmatory factor analysis, I would do Wishart or inverse-Wishart on the covariance (not correlation) among the factors and fix some of the loadings to be $1.0$, rather than fixing the factor variances to be $1.0$.
Answer: Consider that your covariance matrix $\Sigma$ can be written as a correlation matrix $R$ multiplied elementwise by the tensor product of the vectors of the standard deviations.
$\Sigma = (\vec \sigma \otimes \vec \sigma) \odot R$
Provided that none of the standard deviations are zero, the elementwise product is invertible to obtain:
$(\vec \sigma \otimes \vec \sigma)^{-1} \odot \Sigma = R.$
As suggested by Ben, I would try an inverse-Wishart (or the Wishart up to an inverse) to allow putting background knowledge into the prior. Furthermore, I would try making it adaptive using the above relation so that published correlation values can be used.


AJAX Edit Node and update

Question: Im reading up on how to add AJAX functionality to nodes and am stuck. Where exactly do I place  #ajax in order to make the edit field updae via ajax? Specifically is it an existing php, js, html, css file that handles this? Do I add it to the node or block?  I've read that its fairly simple but drupal isn't my native language so i'm still learning.
I've tried using this module ajax_form_entitty
but it wont load the newly created node after submission it directs to a blank page. I've been told to point the node to a div and insert the div in the header, but I have no idea how that should look.
here is what i've done (which doesn't work)

All help is appreciated
EDIT:
Reading Material
I've tried following along with this as one possible way to go about it but have no clue how to implement anything.
Comment: General remarks: Try to include at least some of the references that you have used so far and also relevant code snippets that you came up with until now. That way it's easier for anyone here to help you.
Comment: As stated i'm not even sure where to begin. I'm not even sure what code snippets I would use at all. Everything I read does not say what specifically to edit, it's all implied and i'm still learning by trial and error.
Comment: But you say that your are "reading up"? Just give some links, so people here have something to start with. Ajax form entity is a pretty young module, so it's totally possible that you have discovered a bug in the module. The module maintainer will probably be glad if you report this as an issue in the official [issue queue](https://drupal.org/project/issues/ajax_form_entity).
Answer: To answer the question of "where" do you add the AJAX functionality in a node form, the answer is in a form_alter. That can be done in a custom module or the theme's template.php file. I recommend a module so the functionality remains even if you change your theme.
A great resource is the examples module which is a group of example modules with great comments that assist developers in implementing Drupal functionality. In fact, there's is a submodule called ajax_example that adds ajax functionality to a a field in a node (exactly what you are looking for!). Here's an excerpt from ajax_examples_node_form_alter.inc:
/**
 * Implements hook_form_FORM_ID_alter() for the node form.
 *
 * Adds two fields to the node form, second only appears after first is enabled.
 */
function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    )
  );
  $form['container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
      || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ?
                          $node->ajax_example['example_2'] :
                          $form_state['values']['ajax_example_2'],
    );
  }
}

/**
 * Returns changed part of the form.
 *
 * @return renderable array
 *
 * @see ajax_example_form_node_form_alter()
 */
function ajax_example_form_node_callback($form, $form_state) {
  return $form['container'];
}

Comment: I think we're getting there! I've played with the module some and my last question is, if I implement that in a new module or in my templates php file, could I have it submit the content and edit the content via ajax so that I don't reload the page?
Comment: I'm going to cheat here and just point you to the edit module. :) https://drupal.org/project/edit
Comment: Unfortunately the EDIT module does not work with views and mediafront.

AJAX Edit Node and update


New property in iOS Core Data model is inaccessible from controller

Question: I have a Core Data model with 3 properties and I've generated model class for that. It was working fine. Then I've added a new property(4th property) in that model and re-generated the model class file and replaced the old one. Now that new property is inaccessible from my controller. :(
Could anybody please describe whats wrong?
Note: development environment is XCode 5.
Answer: Did you do this without re-indexing the project?  If it's been open the entire time, it may not have noticed the changes.  Run Clean from the Product menu.


Voltar linha do debug

Question: No antigo Visual Basic se você estivesse em debug passa-a-passo e sem querer passasse de um linha que queria verificar, havia a opção de ir com o cursor até a linha acima e pressionar a combinação de teclas: Crtl + F9 para que debug voltasse para tal linha.
Existe essa opção (ou algo semelhante) no Visual Studio 2013 ?
Comment: Você pode arrastar com o mouse o ponto do debug no VS, tanto para frente quanto para trás...
Answer: No Visual Studio, em modo de debug, aparece uma seta amarela do lado esquerdo do codigo.
Podes arrastar essa seta para cima, para voltar a executar codigo.

Voltar linha do debug


Image Binding not showing iOS Maui

Question: Im having this issue on where Images that are using binding aren't showing up on iOS. All my images are inside a resource folder and then inside a images folder. If I don't use binding on the images they show up just fine On Android the images are showing up just fine
Here is my xaml:
 <StackLayout Spacing="0">

        <RefreshView x:DataType="local:MowersViewModel" Command="{Binding LoadItemsCommand}" IsRefreshing="{Binding IsBusy, Mode=TwoWay}">
            <CollectionView BackgroundColor="{AppThemeBinding Dark={StaticResource Accent}, Light={StaticResource Secondary}}" x:Name="ItemsListView"
                ItemsSource="{Binding Items}"
                SelectionMode="None">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Grid RowDefinitions="90" ColumnDefinitions="90,90,*" x:DataType="model:Mower" BackgroundColor="{AppThemeBinding Dark={StaticResource Accent}, Light={StaticResource Secondary}}">
                            <Image Grid.Row="0" Grid.Column="0" x:DataType="model:Mower" Source="{Binding MowersPageImage}" Aspect="AspectFill" Margin="5"/>
                            <VerticalStackLayout Grid.Row="0" Grid.Column="1" VerticalOptions="Center" Padding="0,10,0,0">

                            </VerticalStackLayout>
                            <HorizontalStackLayout Grid.Row="0" Grid.Column="2" Margin="5"  x:DataType="model:Mower" HorizontalOptions="End" BackgroundColor="{AppThemeBinding Dark={StaticResource Accent}, Light={StaticResource Secondary}}">
                                <Button x:Name="ButtonConfigure" Margin="0,0,5,0" Text="Configure" HeightRequest="45" IsVisible="{Binding CanConfigure}"
                                Command="{Binding Source={RelativeSource AncestorType={x:Type local:MowersViewModel}}, Path=ConfigurePushed}"
                                CommandParameter="{Binding .}"/>
                                <Button x:Name="ButtonConnect"  Text="{Binding ConnectButtonString}" IsVisible="{Binding Online}"  HeightRequest="45"
                                Command="{Binding Source={RelativeSource AncestorType={x:Type local:MowersViewModel}}, Path=ConnectPushed}"
                                CommandParameter="{Binding .}"/>
                            </HorizontalStackLayout>
                            <Grid.GestureRecognizers>
                                <TapGestureRecognizer
                                NumberOfTapsRequired="1"
                                Command="{Binding Source={RelativeSource AncestorType={x:Type local:MowersViewModel}}, Path=ItemTapped}"
                                CommandParameter="{Binding .}">
                                </TapGestureRecognizer>
                            </Grid.GestureRecognizers>
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </RefreshView>
    </StackLayout>

Here is the lines where the images are supposed to be bound too:
async Task ExecuteLoadItemsCommand()
    {
        IsBusy = true;

        try
        {
            Items.Clear();

            // add mowers that we are connected to
            var sorted = new List<MowerData>((IEnumerable<MowerData>)online_mowers_);
            sorted.Sort((x, y) => (int)x.serial_number - (int)y.serial_number);
            foreach (var m in sorted)
            {
                var new_item = new Mower();
                new_item.MachineSerialNumber = m.serial_number.ToString();
                new_item.CompanyName = "";// todo fill me in?
                new_item.Connected = m.connected;
                new_item.OtherUserConnected = m.other_user_connected;
                new_item.Online = true;
                new_item.AccentColor = m.GetAccentColor();
                if (new_item.AccentColor == Color.FromRgb(1, 0, 1))
                {
                    new_item.MowersPageImage = "Resources/Images/mower_active_purple.png";
                }
                else if (new_item.AccentColor == Color.FromRgb(1, 1, 1))
                {
                    new_item.MowersPageImage = "Resources/Images/mower_active_grey.png";
                }
                else
                {
                    new_item.MowersPageImage = "Resources/Images/mower_active_blue.png";
                }
                new_item.CanConfigure = App.IsTechnician || m.connected;
                Items.Add(new_item);
            }

            var items = (await DataStore.GetItemsAsync(true)).ToList();
            items.Sort((x, y) => (int)int.Parse(x.MachineSerialNumber) - (int)int.Parse(y.MachineSerialNumber));
            foreach (var i in items)
            {
                bool found = false;
                i.MowersPageImage = "Resources/Images/mower_offline.png"; //off
                for (int j = 0; j < Items.Count; j++)
                {
                    var item = Items[j];
                    if (item.MachineSerialNumber == i.MachineSerialNumber)
                    {
                        found = true;
                        item.CompanyName = i.CompanyName;
                        Items.RemoveAt(j);
                        Items.Insert(j, item);
                        break;
                    }
                }

                if (!found)
                {
                    i.CanConfigure = false;
                    Items.Add(i);
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
        finally
        {
            IsBusy = false;
        }
    }

I tried changing all the paths for the image didn't do anything. Then tried a static Image that one worked
Comment: you should not need the path, just the image name.  See https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=windows#download-images
Answer: A method is to set your images's Build Action to Embedded resource and add a new property MySource in your item.
Just as follows:
 public ImageSource MySource { get; set; }

then set value for MySource as follows:
 MySource = ImageSource.FromResource("RefreshViewDemo.Resources.Images.sleep.png",typeof(MowersViewModel).GetTypeInfo().Assembly)

And bind like this:
<Image   Source="{Binding MySource}" Aspect="AspectFill" WidthRequest="50"   HeightRequest="50" />

Note:

RefreshViewDemo is the name of my app,you can change it to yours.

Please change your images' Build Action to Embedded resource

Image Binding not showing iOS Maui


Why do so many symphonic works that are named "minor" end "major"?

Question: For example, Schumann's Symphony No. 4 in d minor has the 4th movement end in D major. There are many many other examples that I have seen of this pattern; some that end on the major version of the same key, whereas others end on a different major key.
Is the reason purely to end on a "happy note"?
The only symphony that I can think of that declares it as minor and ends on the same minor key is Brahms's Symphony No. 4 in e minor.
Comment: By the way: one of Brahms's intermezzi is the *only* work I know offhand that ends in (e flat) minor after having begun out in e flat major.
Comment: @KilianFoth wow didn't even know one such major -> minor!
Comment: One major-key symphony that ends in the minor is Mendelssohn's 4th (the Italian) in A major: its finale's in a minor. For more examples: https://en.wikipedia.org/wiki/List_of_major/minor_compositions
Answer: Tim was partway there. It's not uncommon in movements that are in the minor to end in the major, not just a tierce de Picardie, but a coda in the major, or even a good part of the recapitulation: it's a way of resolving the tension inherent in the minor mode in common practice tonality. A finale in the tonic major is taking that sense of resolution up a level of hierarchy.
A finale in the major on a different tonic than the opening movement, however, is exhibiting what is usually called progressive tonality. One might say that the emphasis is on the "journey", on transformation rather than resolution in such a case.
Comment: Great answer! I probably should have put that I wanted more of a historical reason than a stylistic one, but I'll go ahead and accept this.
Comment: @Ryan, the need for resolution was tied to history: you'll see precisely the kind of thing I'm talking about in the Viennese Classical composers (sometimes very cagily in Beethoven's case). With the Romantic generation, that need starts to disappear, and, by the time you reach Nielsen and Mahler, the need to return to the opening tonic is pretty much gone. Highly recommended, if you're interested: Charles Rosen's books, _The Classical Style: Haydn, Mozart, Beethoven_ and _The Romantic Generation_.
Comment: @Ryan In fact, Mahler's Symphony No. 2 in c# minor ends in D Major!
Answer: Mozart No. 40 in g minor, and Sibelius No. 1 in e minor, are two more examples of symphonies that begin and end on the same minor chord.
Many composers and songwriters have an aversion to ending on a minor chord. They feel it leaves the piece 'un-resolved.' There's a scientific reason for this: the major triad is composed of natural overtones of any fundamental pitch. The minor triad has no such origin. It is 'made up.'
Answer: The 'tierce de Picardy' is maybe your answer. It is known as the Picardy third, and is used to finish a minor piece , on the parallel major. Obviously, if the piece is 'xyz in D minor', the key signature is going to be one flat throughout it, unless there's a key change or modulation, but it'll probably gravitate back to D minor again.
The 'different major key' ending is often the relative major, so in my example, it would end on F major, or you could say IN F major.
Comment: The Picardy third is a single chord at the end of a minor piece, not an entire final movement.
Comment: Yes, but I think Tim is saying that the reasons for this may be parallel or at least similar, and I think he's right.  There is an aversion among many composers to ending on a minor chord, as it leaves a feeling in many ears of non-resolution.  There is a scientific reason for this-- the major triad is composed of natural harmonics of any fundamental note.  There is no similar origin of the minor triad.
Answer: The Western musical ear is very tuned into hearing a major scale and a major scale as the norm.  Maybe this has something to do with the construction of the harmonic series, maybe not.  (Other musical traditions have taken different paths.  Have they achieved a similar catalogue of art music?  It's a much-argued point.)  Anyway, in the context of tonal music, anything else feels slightly unfinished.  Hence the 'Tierce de Picardy' and its extension into a whole section in a major key, particularly in Common Practice symphonic works that use key relationships as a major structural element.


Proving exponential inequalities

Question: I'm currently revising for an upcoming exam and am stuck on the following question. I have completed a similar question that involved cos and the mean value theorem I used the triangle inequality too, so I assume this question will do the same. However I am unsure how to go about this. Any help would be appreciated.
Comment: Hint: Use the Mean-Value Theorem.
Answer: Hint: According to the MVT $$e^x-e^y=e^\xi (x-y) $$ for some $\xi \in (0,1).$
Answer: One may observe that, for $x,y \in \mathbb{R}$,
$$
e^x-e^y=\int_x^ye^tdt
$$ giving, for $x,y \in [0,1]$,
$$
\left|e^x-e^y\right|=\left|\int_x^ye^tdt\right|\leq e\left|\int_x^y1dt\right|=e|x-y|.
$$
Comment: is there a way I could do this using mean value theorem as well?? :)
Comment: @Chloe Then the user1337 answer seems fine for it. Thanks.

Proving exponential inequalities


LinkButton com Eval ListView asp.net

Question: Quero fazer isso
<%# Eval("campo1").ToString() == "nada consta" ? "nada consta" : Eval("campo1")%>

dentro do linkButton
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl= '<%#
"~/Promocao.aspx?ID="+Eval("campo2") +
Eval("campo3")%>'>...+infos</asp:LinkButton>

Ou seja, se existir dados em "campo1", exibe os dados. Senão exibe "nada consta". E, havendo dados, ao clicar em linkButton passa pra outra pagina "promocao.aspx" os campo2 e campo3. Do jeito que está,um ao lado do outro, mesmo não tendo dados em "campo1" o LinkButton fica disponível para clique. Além disso, do jeito que está, na URL o campo2 e campo3 ficam juntos.
Comment: estranho a explicação: "Ou seja, se existir campo1," : vamos lá se quer que só aparece o LinkButton se o campo1 existir? como assim, tem como explicar melhor?
Comment: @VirgilioNovic Desculpe, a explicação ficou carente de detalhes. Se não for "nada consta" campo1 mostrará os dados, senão não precisa aparecer o linkButton. Se simm, o usuário então clicará em "...+infos" indo para outra pagina, onde irei recuperar os dados do campo2 e campo3 - para montar uma requisição de pagamento - que sempre vão existir, uma vez existindo campo1. Quero também que na URL fique separado os parametros campo2 e campo3 e nao juntos sequencialmente, Um espaço entre eles seria bom.
Comment: Um espaço entre eles seria bom -> não está correto assim, o que você fazer e criar um ID1  e passar o campo3 o que acha?
Comment: Sim @VirgilioNovic
Answer: Se pode utilizar a propriedade Visible do LinkButton para criticar se o mesmo vai estar presente ou não, exemplo:
<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate>

            <asp:LinkButton ID="LinkButton1"
                PostBackUrl='<%#string.Format("~/Promocao.aspx?id={0}&id1={1}", Eval("campo2"),Eval("campo3"))%>'
                runat="server"
                Visible='<%#Eval("campo1").ToString()!="nada consta"%>'>
                    Item
            </asp:LinkButton>
            <asp:Literal
                ID="Literal1"
                runat="server"
                Text='<%#Eval("campo1").ToString()=="nada consta"?"nada consta":""%>'>
            </asp:Literal>

    </ItemTemplate>
</asp:ListView>

e no PostBackUrl criar as opções desejadas para resgatar na página da sua configuração.
Referencias LinkButton Web Server Control
Comment: @Daniel não entendi?
Comment: Amigo é um exemplo nem no seu @Daniel tem algo escrito
Comment: @Daniel é só colocar um literal e inverter a informação do visible, fiz a edição.
Comment: Quando consta, no lugar dos dados de campo1 exibe "item".' Não está certo.
Comment: Verdade. Eu estou explorando esse exemplo aqui. Quero que apareça os dados e o controle para o usuário poder clicar. Caso não haja dados para exibir, então exiba "nada consta", nesse caso, linkButton não aparece, apenas o texto "nada consta".
Comment: @Daniel está dificil de entender!
Comment: De acordo com excelente exemplo acima, quando nada consta em" campo1" o controle desaparece. Isto está correto. Porém, quero que apareça um texto para o usuário saber que nada consta no campo desse registro. E quando consta, o controle aparece. Isso está correto. Porém, quero que apareça não somente o controle, mas o dado de "campo1".

LinkButton com Eval ListView asp.net


MediaStore.Video.Thumbnails.getThumbnail

Question: I have been trying to load video thumbnails to my gridView. It is loading thumb nails very slowly if i use ThumbnailUtils.createVideoThumbnail.
So i decided to use MediaStore.Video.Thumbnails.getThumbnail. But What is origld. and how can i pass this element to this method?
I have refer MediaStore.Video.Thumbnails.getThumbnail() returns null link also. But it is not helpful for me
Comment: `But What is orgid.` What do you mean by this ? Where did you find this ?
Comment: public static Bitmap getThumbnail (ContentResolver cr, long origId, int kind, BitmapFactory.Options options) in API
Answer: <code> public static Bitmap getThumbnail (ContentResolver cr, long origId, long groupId, int kind, BitmapFactory.Options options)
</code>
This method checks if the thumbnails of the specified image (origId) has been created. It will be blocked until the thumbnails are generated.
Parameters

cr-   ContentResolver used to dispatch queries to MediaProvider.
origId -  Original image id associated with thumbnail of interest.
groupId - the id of group to which this request belongs
kind- The type of thumbnail to fetch. Should be either MINI_KIND or MICRO_KIND
options-  this is only used for MINI_KIND when decoding the Bitmap

As it defines the original image id of the video thumbnail you need to pass the image id of your video thumbnail in this parameter.
For more details Check out HERE
<code>public static Bitmap getThumbnail (ContentResolver cr, long origId, long groupId, int kind, BitmapFactory.Options options)
// origid  is the Images.ImageColumns._ID
//groupid is the Images.ImageColumns.BUCKET_ID
</code>
Comment: Hi GrlsHu.. i have tried your code. My imageview id is R.id.imageView_grid. I have passed it to getThumbNail mathod. But it returning null
Comment: Check out the link in my answer.
Comment: Thanks GrlsHu.. It is working. And it is faster than ThumbnailUtils. THanks again


Apply curve_fit on dataframe columns

Question: I have a pandas.DataFrame with with multiple columns and I would like to apply a curve_fit function to each of them. I would like the output to be a dataframe with the optimal values fitting the data in the columns (for now, I am not interested in their covariance).
The df has the following structure:
    a  b  c
0   0  0  0
1   0  0  0
2   0  0  0
3   0  0  0
4   0  0  0
5   0  0  0
6   1  0  1
7   1  1  1
8   1  1  1
9   1  1  1
10  1  1  1
11  1  1  1
12  1  1  1
13  1  1  1
14  2  1  2
15  6  2  6
16  7  2  7
17  8  2  8
18  9  2  9
19  7  2  7

I have defined a function to fit to the data as so:
def sigmoid(x, a, x0, k):
     y = a / (1 + np.exp(-k*(x-x0)))
     return y

def fitdata(dataseries):
    popt, pcov=curve_fit(sigmoid, dataseries.index, dataseries)
    return popt

I can apply the function and get an array in return:
result_a=fitdata(df['a'])
In []: result_a
Out[]: array([  8.04197008,  14.48710063,   1.51668241])

If I try to df.apply the function I get the following error:
fittings=df.apply(fitdata)
ValueError: Shape of passed values is (3, 3), indices imply (3, 20)

Ultimately I would like the output to look like:
           a          b          c
0   8.041970   2.366496   8.041970
1  14.487101  12.006009  14.487101
2   1.516682   0.282359   1.516682

Can this be done with something similar to apply?
Answer: Hope my solution work for you.
result = pd.DataFrame()
for i in df.columns:
    frames = [result, pd.DataFrame(fitdata(df[i]))]
    result = pd.concat(frames, axis=1)
result.columns = df.columns

           a           b           c
0   8.041970    2.366496    8.041970
1   14.487101   12.006009   14.487101
2   1.516682    0.282359    1.516682

Answer: I think the issue is that the apply of your fitting function returns an array of dim 3x3 (the 3 fitparameters as returned by conner). But expected is something in the shape of 20x3 as your df.
So you have to re-apply your fitfunction on these parameters to get your fitted y-values.
def fitdata(dataseries):
    # fit the data
    fitParams, fitCovariances=curve_fit(sigmoid, dataseries.index, dataseries)
    # we have to re-apply a function to the coeffs. so that we get fittet
    # data in shape of the df again.
    y_fit = sigmoid(dataseries, fitParams[0], fitParams[1], fitParams[2])
    return y_fit

Have a look here for more examples
Answer: (this post is based on both previous answers and provides a complete example including an improvement in the dataframe construction of the fit parameters)
The following function fit_to_dataframe fits an arbitrary function to each column in your data and returns the fit parameters (covariance ignored here) in a convenient format:
def fit_to_dataframe(df, function, parameter_names):
    popts = {}
    pcovs = {}

    for c in df.columns:
        popts[c], pcovs[c] = curve_fit(function, df.index, df[c])

    fit_parameters = pd.DataFrame.from_dict(popts,
                                            orient='index',
                                            columns=parameter_names)
    return fit_parameters

fit_parameters = fit_to_dataframe(df, sigmoid, parameter_names=['a', 'x0', 'k'])

The fit parameters are available in the following form:
          a         x0         k
a  8.869996  11.714575  0.844969
b  2.366496  12.006009  0.282359
c  8.041970  14.487101  1.516682

In order to inspect the fit result, you can use the following function to plot the results:
def plot_fit_results(df, function, fit_parameters):
    NUM_POINTS = 50
    t = np.linspace(df.index.values.min(), df.index.values.max(), NUM_POINTS)
    df.plot(style='.')
    for idx, column in enumerate(df.columns):
        plt.plot(t,
                 function(t, *fit_parameters.loc[column]),
                 color='C{}'.format(idx))
    plt.show()

plot_fit_results(df, sigmoid, fit_parameters)

Result: Output Graph
This answer is also available as an interactive jupyter notebook here.

Apply curve_fit on dataframe columns


how to correctly download tomcat 6 on centos 5.5

Question: i am a big confused about how to install tomcat 6 on centos 5.5 final.
this is what i am trying to do:
<code># cd /etc/yum.repos.d/
# wget http://jpackage.org/jpackage50.repo
# yum install tomcat6 tomcat6-webapps tomcat6-admin-webapps
</code>
but when i type the widget command, this is what i get:
<code>Resolving www.jpackage.org... failed: Temporary failure in name resolution.
wget: unable to resolve host address `www.jpackage.org'
</code>
could anyone kindly show me the right way please. really in trouble at the moment with this.
thanks in advance.
Comment: Your machine isn't connected or has no proper means to resolve names: try `ping 188.8.131.52` to see, whether you can reach the internets at all.
Comment: you are correct! my machine was not connected. thanks man
Answer: It seems that you have the troubles with your dns servers or local name resolver.
You can use dig to determine ip-adderss of www.jpackage.org and then add it to your local /etc/hosts file.


Finding a sum to infinity with a factorial

Question: The sequence is
$$\sum_{n=1}^{\infty} \frac{n-1}{n!}$$
I could show that it converges using the Ratio test, but evaluating it seems to be hard. I'm trying to avoid power series and Taylor series and such. Is it possible to solve this some other, simpler way?
I tried writing out the first few terms, but since it's non-geometric, it doesn't seem to help.
Comment: Finding the first few partial sums might help: $\frac{0}{1}+\frac{1}{2}+\frac{2}{6}+\frac{3}{24}+\frac{4}{120}+\cdots$ $=\frac{1}{2}+\frac{2}{6}+\frac{3}{24}+\frac{4}{120}+\cdots$ $=\frac{5}{6}+\frac{3}{24}+\frac{4}{120}+\cdots$ $=\frac{23}{24}+\frac{4}{120}+\cdots$ $=\frac{119}{120}+\cdots$
Comment: @Joanpemo: there is a pattern in the sequence $\dfrac{0}{1}, \dfrac{1}{2}, \dfrac{5}{6}, \dfrac{23}{24}, \dfrac{119}{120}, \ldots$. Can you spot what it might converge to? And what the precise pattern is?  Then use induction for proof.
Comment: "evaluating it seems to be hard": have you even tried ? This ratio test is quite easy.
Comment: @Henry Thank you. I can't see how the partial sums, expressed in that form, can possibly help. Is there some hidden easy-to-follow pattern I'm missing in those expressions?
Comment: @Henry Thank you. I can see, with some effort, that if those are really the partial sums, then the limit is one, and this is correct, yet I can't see how could this pattern be reached in general (and proved in general) without first stumbling in one of the already given answers.
Comment: @Henry thank you! This is a good method which avoids having to use Euler's constant, which was what I was hoping to do.
Answer: Hint: Note that
$$\frac{n - 1}{n!} = \frac{1}{(n - 1)!} - \frac{1}{n!}$$
A large amount of cancellations will occur between successive terms in the summation.
Comment: Probably the most elegant using elementary observations like telescoping series.
Answer: Your sum is only
$$\sum_{n=1}^\infty\frac{n-1}{n!}=\sum_{\color{red}{n=0}}^\infty\overbrace{\frac1{n!}}^{=\frac n{n!}=\frac1{(n-1)!}}-\sum_{\color{red}{n=1}}^\infty\frac1{n!}=e^1-(e^1-1)=1$$
Comment: Nice and straightforward. +1
Comment: Nice answer! Sorry I couldn't accept it as the correct answer but if I could choose two I'd have chosen this.
Comment: Avoids cleverness.
Comment: @martycohen Thank you. Yes, perhaps...but makes, in my opinion, things pretty simple using a very well known infinite series.
Comment: @SkeletonBow Thank you. Don't worry about the accepting: choose whatever you consider the best/more helpful to you.
Answer: Consider the function $$f(x)=\frac{\mathbb e^x}{x}=\sum_{n=0}^\infty \frac{x^{n-1}}{n!}$$ And use derivativetion we get that: $$\frac{x\mathbb e^x-\mathbb e^x}{x^2}=\sum_{n=0}^\infty \frac{(n-1)x^{n-2}}{n!}$$ Or: $$\frac{x\mathbb e^x-\mathbb e^x}{x^2}+\frac1{x^2}=\sum_{n=1}^\infty \frac{(n-1)x^{n-2}}{n!}$$ Finally: $$1=\sum_{n=1}^\infty \frac{n-1}{n!}$$.


Enabling "entity translation" disables term translation in Drupal (name and description)

Question: i want to translate taxonomy terms and their description text.
When I enable the module "entity-translation" and check "Taxnomie-terms" in admin/config/regional/entity_translation, the terms and descriptions get synchronized. Means: If I enter the German termname and description and switch to english and change it there, it also changes on the german translation.
The lables show:

Name (all languages)
Description (all languages)

And I don't know how to change that. Ideas for solving my problem welcome!
Answer: Ad documented on the Entity Translation project page: "Title module allows to replace entity labels with fields to make them translatable." With the Title module you are able to replace the non-Field title and description properties taxonomy terms with Fields translatable with Entity Translation.
Comment: Awesome, I never would have guessed that the Title module supports the description property too.
Answer: had the same issue, after hours of frustrating research we found the solution.

please check if you have "title" module installed.
then go to /admin/structure/taxonomy/[vocabulary_name]/fields
for title and description hit "replace"
Answer: Hours??? In my case it has been days!!! And I'm desperate (again!)
If Drupal is already counter intuitive by itself in general and even more for translations, taxonomy always has been a hundred times worse.
However, I did achieve a certain (not full) level of taxonomy translation through field (or entity) translation doing something like:

for the vocabulary ("Special") I went to: "Localize" under admin/structure/taxonomy/special/edit
Save&Translate -> NL:"Speciaal", IT:"Speciale", ES:"Especial"
for the term ("To be developed") I went to: nl/taxonomy/term/85/edit/nl or was it taxonomy/term/85/translate?? (this for each language).
On both pages it says I have this URL alias for each language, but when I use that path (eg /nl/speciaal/te-ontwikkelen) I get a "Page not found" error.
Same goes for /it/speciale/da-sviluppare, /es/especial/por-desarrollar
Only Generic (Drupal's "Default") works: special/to-be-developed

Also the translated Terms of "to-be-developed" do not appear as options in the translated version of the "Special" Vocabulary when editing content.
HOW does Taxonomy get to understand that both Vocabulary and Term already exist, have been translated and that these paths should work????

also did translation under admin/config/regional/translate/edit/9709?destination=admin/config/regional/translate/translate

What should be the next step should to get also the other languages to work (without creating additional term IDs)?
Additionally my hope was to have Taxonomy terms syncronized EVEN with entity translation (new translation of content -> tax term already selected) as is possible with menu items to have just one instance in the list.
Is this actually possible?
Also I have not been able to find the "language is in" option for the "Special" vocabulary in Views: admin/structure/views/view/special
How can I get that?
And last but not least: path is not translated either they all go to /lang/special even if "Special" already has been translated to the other languages in all possible places (although you never know)
BTW one should definitely should NOT FORGET to also activate the field-translation options for Taxonomy (Vocabulary and/or terms) in several other places, before Drupal or Taxonomy even understand you really MEAN to use entity (or field?) translation all over the site (not just in only one expceptional place) and the above can even occur. Unfortunately after days of going through the impossible Drupal-Taxonomy-FieldTranslations labyrinth, I do not remember all the steps, nor the order I have taken, nor which of these steps were actually valid.
Anyway several of these places, randomly (don't know if all) are:
- admin/structure/taxonomy/special/fields/name_field
- to keep up common sense, indeed also in the Title module: admin/config/content/title
- in the content type: admin/structure/types/manage/[content-type]/fields/field_category
- of course several additional things under the translation interface admin/config/regional/translate/translate
not forgetting string refreshment admin/config/regional/translate/i18n_string
- and I don't remember if somewhere else in Drupal's translation labyrinth (specifically having to activate entity (or field?) translations for taxonomy or vocabulary or terms...) Maybe some module configuration or special permissions...
Example at: http://europinion.is/special/to-be-developed (if it doesn't break of course) you can see:
1 - the Vocabulary menu item is translated, however linking to non translated path
2 - Term also appears, however linking to a path that gives error
3 - vocabulary/term reference appears translated in the content with "page not found" path again
Answer: The entity translation approach for taxonomy term can be a bit of a mess indeed.
I had created my vocabulary and terms before I enabled "Field translation. Term fields will be translated through the Entity translation module." in my vocabulary settings (admin/structure/taxonomy/(yourvocabulary/edit).
As a result Views wouldn't properly output the translated term name and description (it would stick with the source translation).
Solution:
Notice: the steps below are advised when enabling "Field translation", replacing the title and description field and re-saving each term isn't working out.

I deleted and recreated the vocabulary from scratch,
enabled Entity translation on it first of all this time (note: it may require a patch to obtain this Field translation option, and running update.php may be required right after that),

replaced both the title and description fields with entity fields (using the Title module),
and finally added the terms again.
Once the terms and their descriptions where all there in the source
language, I translated them one by one.

Mind you that it's possible that there's no "translate" link directly next to the term in the overview. To translate the term, click its "edit" link, and then you'll find "translate" tab.
This time Views would properly render the translated output of both the term name and description.
-> On a sidenote: taxonomy fields may be more practical than select option fields in content types, especially when it comes to URL patterns and their translation.
-> When you accidentally enabled taxonomy translation and attempted to translate a term, and now the Entity Translation approach has no longer effect: go to the database and find the table entity translation. Find the term (by its TID), and assign a language to it in the language column (instead of und). In case it's still not working: also provide this language in the language source colum. Now the translate tab to appear again on the term's edit page.
Answer: The latest version (beta6) of entity translate now supports Taxonomy term translation


Remove URL from printing page using css

Question:

Published on website name (http://localhost)

Home Reportedly Prepping

 some title

    contributor helping  report. It's the latest nightmare.some text for the url to be removed(http://url-to-be-removed) then some more text.

 some more text and another url

...

Using CSS how can remove the URL. Since the URL are in the body I tried using the class name and html tag :
div.print-content article.node .node-blog .clearfix div.item-body p a { content: "";}

update
The part i want to remove is in bold.
   contributor helping  report. It's the latest nightmare.some text for the url to be removed (http://url-to-be-removed) then some more text.
Comment: Possible duplicate of [Need to remove href values when printing in Chrome](https://stackoverflow.com/questions/7301989/need-to-remove-href-values-when-printing-in-chrome)
Answer: To remove the URL from a printed media, use:
@media print {
  div.print-content article.node .node-blog .clearfix div.item-body p a {
    display: none;
}

If what you want instead is to have it dissapear completely (from any view), just add div.print-content article.node .node-blog .clearfix div.item-body p a { display: none; }
Adding it this way will remove it completely from the view of the doc, freeing up any space occupied by the  tag.
Comment: Thanks what i did is : `div.print-content article.node div.item-body p a { display: none; }` but it remove everything: the link and the url. I update my question and bolded the part that need to be removed which is the URL after the link in parenthesis.
Answer: a[href]:after { content: none !important; }
update
The CSS :after selector inserts something after the content of each selected element(s).
Use the content property to specify the content to insert. content: none is for explicitly preventing the after selector (pseudo-element) from being generated (really only used to override another style that would have generated content).
a[href]:after { content: none !important; } will mean remove content after each link.

Remove URL from printing page using css


What is the difference between pointers to array of pointers?

Question: I came across these two terms
Int (*q)[3][4]  and. int q[ ][3][4].
What's the difference these two terms?
And one more question .
 Char a[ ]="abcd";
  Char *p="abv";
   a="ghj";
   p="ajk";
 Printf("℅s℅s",a,p);

Why this would not compile?
Comment: `Will this run or not and why?` Well, did you try to run it?
Comment: This wouldn't even compile, let alone run.
Comment: You're trying to determine the difference between pointers and arrays. This article is technical and you should read it, it's really good! http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c
Comment: You are taking too many liberties with the cases of various keywords and standard functions. I don't think any conscientious C programmer can overlook that in your question and don't at least flinch while writing an answer...
Comment: ISO C++11 does not allow conversion from string literal to `char *`
Comment: are you asking why a is not compiling while p does?
Comment: a is an array and it can be modified using subscripts a[0] ... a[size-1], not doing this directly a="whatever". p is a pointer to const string placed somewhere in memory. Since the string is constant it can't be modified directly.
Comment: @cameltoe yes I am asking the same.
Answer: It won't compile because of the line:
a = "ghi"

This assigns a const char* to a char* directly. You can use strcpy to copy the string intead:
strcpy(a, "ghi")

You will still have warnings at this point, because you have not declared p as a const. You can fix this like so:
const char* p = "abv"