Basic virtualization questions

Question: Excuse me for my lack of knowledge but I am really new to the Virtual world and have a few questions.
I work for a small charity who specialise in providing basic IT training. We have recently acquired a few Dell Poweredge 2650 servers and Dell desktops and we wish to offer both XP, Windows 7, Mac and Ubuntu training. I am looking at setting up a Virtual environment so that we can have a standard image for each OS (I currently use image files but it currently takes approximately 25mins to build each machine and multi-boot is not an option as the new machines have 20Gb disks).
The servers are all dual processor and we can purchase more memory(I need to justify the cost)

What are the memory requirements for
the Host?
How many VM's can I run
    per server?
Can I run multiple instances of the same VM

Thanks in advance for your knowledge.
Darryn
Comment: I think you should post this question at ServerFault instead.
Answer: You might be able to get away with a multi-boot option with those 20 gig disks; each OS will probably take no more than ten gigs for minimal installs, two OSes per machine isn't terrible. (Incidentally, look around for a group like FreeGeek in your area -- larger hard drives ought to be cheap for small sizes like 120-500 gigs.)
That said, virtualization might be just what you need, if you have a handful of pretty powerful machines.
I think between one and two gigabytes of host memory for every guest VM that you want to run would be very useful. At least in my experience, an Ubuntu image I gave 1024 megabytes to ran very quickly, but I didn't press it very far. Running Firefox or OpenOffice inside the VM would probably dictate more memory very quickly. Chrome seemed snappy.
So, if you've got 12 gigabytes of RAM, you might be able to get between four and twenty virtual machines hosted on the machine simultaneously, depending upon what your guests are doing.
As for disk space, if you use QEMU's <code>-snapshot</code> option, you ought to be able to save disk space. Each user could boot the same underlying disk image, but their own modifications would go into the 'snapshot' file. (I have no experience trying to do long-term system maintenance with this option, so it could be that all twenty of your users need to store service pack 2 contents when they upgrade in the future; I'd be scared of trying to modify the shared disk image once you've got snapshots of it running. Perhaps having everyone store 'personal documents' and the like in CIFS shares would make a ton of sense.)
The biggest hurdle will probably be Mac; because the Apple terms of service forbid running OS X on non-Apple hardware, you'll have to have some Apple machines around to run VirtualBox.
Comment: Thanks for the info
It looks like I'll have to justify the spend on 12Gb Ram (£360-£400). Using snapshot does not look like an option, I would rather keep control of any and all upgrades to OS and applications.
And thanks for the info about OS X and have to look into this a bit further

Basic virtualization questions


Formula to increase/decrease a relative number based on a fixed number

Question: Being a fairly good math student in high school, this is humbling. But my knowledge about graphs and formulas has greatly diminished since then.
I'm trying to write a formula that calculates a percentage, depending on the total amount. My base is $15\%$ of $100$. Basically the percentage needs to go up as the total goes down, and vice versa. So some examples:
<code>10000 =>  5% (500)
 1000 =>  7% (70)
  300 => 10% (30)
  100 => 15% (15)
   80 => 20% (16)
   40 => 30% (12)
   20 => 40% (8)
    5 => 60% (3)
</code>
There would also be a limit I think, in that $0\%$ must not be possible. The upper boundary is infinite in theory, but in practice more likely to be around $100000$.
Without the deviation, the formula would be simple:
$ y = 100/x*15 $
But as far as the deviation goes, I could use some help. The numbers are just an example, I'll probably tinker with the variables a bit to get the exact formula.
Comment: Is there an upper and lower bound on the totals? Do you want a linearly relationship or a non-linear relationship between totals and percenatges?
Comment: I think the relationship is non-linear, maybe exponential. I'm not sure. The lower bound would be 1, the upper bound in theory infinite, but in practice about 100000. Thinking about it, the percentage would be 100 at a total of 1.
Answer: You seem to be looking for a function $f\colon[1,\infty)\to(0,1]$ such that $f(1)=100\%$, $f(100)=15\%$ and $\lim_{x\to\infty}f(x) = 0\%$.
A nice family of functions to try would be $f(x) = \frac{a}{bx+c}$. Your conditions then fix $f(1) = \frac{a}{b+c}=100\%$ and $f(100)=\frac{a}{100b+c}=15\%$. Some numbers that would work are $b=17$, $c=280$ and $a=297\cdot 100\%$.
Hence the formula would be $y = \frac{297}{17x+280}\cdot 100\%$.
Since you remark that this formula decreases too fast for large $x$ you might alternatively try $f(x) = \frac{a}{b\sqrt[n]{x}+c}$ for some $n\in\{1,2,\ldots\}$.
Now your conditions on $x=1$ and $x=100$ fix $f(1) = \frac{a}{b+c}=100\%$ and $f(100) = \frac{a}{\sqrt[n]{100}b+c}=15\%$. Some numbers satisfying these requirements are $a=(3\sqrt[n]{100}-3)\cdot100\%$, $b=17$ and $c=3\sqrt[n]{100}-20$.
Hence we now have
$$ y = \frac{3\sqrt[n]{100}-3}{17\sqrt[n]{x}+3\sqrt[n]{100}-20}\cdot 100\%.$$
For $n=1$ this nicely reduces to the original formula, but for $n=2$ say, we get
$$ y = \frac{27}{17\sqrt{x}+10}\cdot 100\%.$$
Comment: Wow great, thanks! It's not quite there yet, but getting close. I ran a script trying every combination of constants with $a$ and $c$ between $1$ and $700$, and $b$ between $1$ and $30$. All of them seem to diverge too much from my tests, so my tests are probably not really that accurate. However your suggested constants produce good results for numbers $100$ and below. For higher numbers though the percentage drops too quickly. How can I tweak your formula to change that?
Comment: I updated the answer, is this any help?
Comment: I'll try it out tomorrow, thank you so much. How do you come up with these formulas and constants?
Comment: Awesome, I went with $n=6$, which gave me really good results, thanks again! I'm really interested to know how you came up with this, if you have the time to explain it to me. If not, that's fine too.
Comment: I'll try to explain how I came up with it, but I did it mostly subconsciously. Experience I guess. You needed a decreasing function tending to $0$ for $x$ tending to $\infty$, so $f(x)=\frac{1}{x}$ came to mind. The natural generalisation would seem $af(bx+c)+d$, but since $f$ has to tend to $0$, $d$ has to be $0$.

Then, you needed a function that showed the same general behaviour but tending to $\infty$ slower, so I suggested $\frac{1}{\sqrt[n]{x}}$ instead with the same generalisation to $\frac{a}{b\sqrt[n]{x}+c}$.


Docker - Redirecionar DNS para outro DNS

Question: Olá,
Estou fazendo a migração de um sistema muito antigo feito em PHP 5.2, porém ele não possui 1 arquivo para configuração de banco de dados, assim, todas as conexões com o banco e feita localmente em todos os arquivos, o que seria quase impossível para mudar manualmente.
Pensei em criar um container docker com as mesmas condições da antiga máquina, mas o DNS para a conexão com o banco será modificado após a migração.
É possível fazer um bind de 1 DNS para outro? Ex: Toda vez que uma chamada for feita para o DNS dbmobile.exemplo.com ele fazer um redirecionamento para db.exemplo.com?
Answer: Sim, existem alguns parâmetros de configuração da camada de rede que tornam esse tipo de tarefa trivial. Vou tomar como base o docker run, mas tudo que disser está disponível no docker create e também no docker-compose.
--dns | lhe permite dizer para o container quais são os dns's que ele usará.
--add-host | adiciona uma linha em /etc/hosts (host:IP), acredito que esse seja a melhor alternativa para você.
Essas configurações estão disponíveis da mesma forma no docker create e docker run, e um pouquinho diferentes no docker-compose.yml.
Abaixo segue o link da documentação oficial que explica esses pontos.
docker run reference / network-settings


Field of algebraic numbers over $\mathbb{Q}$

Question: Let $F$ be the field of algebraic numbers over $\mathbb{Q}$. I do remember that this means $F$ is a field extension of rationals over $\mathbb{Q}$.
How do I show that no field extension of $F$ is algebraic? I am stuck on this and I would like a hint or two.
Comment: The field of *all* algebraic numbers definitely isn't a finite extension of $\mathbb{Q}$...
Comment: Also, what is $E$?
Comment: If $F$ is the field of all algebraic numbers, then $F$ is algebraically closed, so it has no proper algebraic extensions. So $E$ can be any proper extension of $F$.
Comment: The field of all algebraics is not a finite extension of the rationals. Note that an infinite extension can still be algebraic.
Answer: A field extension $E/F$ is algebraic if for every $\alpha \in E$, the field extension $F(\alpha)/F$ is finite. Equivalently, $\alpha$ is the root of some polynomial in $F[x]$. This says nothing about whether $E/F$ is finite or infinite. Indeed, both possibilities can occur.
As mentioned in the comments above, when $F$ is the set of all elements that are algebraic over $\mathbb{Q}$, $F/\mathbb{Q}$ is not a finite extension. Can you see why?
Keeping with $F$ the field of algebraic numbers over $\mathbb{Q}$, suppose $E/F$ is a nontrivial field extension. In other words, $F \subset E$ and $F \neq E$. Then there exists an $\alpha \in E \setminus F$. Can $\alpha$ be algebraic over $\mathbb{Q}$? Can $\alpha$ be algebraic over $F$?
Comment: I think $\alpha$ can be algebraic over $\mathbb{Q}$. I also think it can be algebraic over $F$, but I'm not 100% confident. I know obviously $\alpha$ is not going to be algebraic over $E$, if $E$ is not finite-dimensional.
Comment: If $\alpha$ is algebraic over $\mathbb{Q}$, then wouldn't $\alpha$ be an element of the field of all algebraic numbers over $\mathbb{Q}$, i.e. $F$?
Comment: Yes, $\alpha$ would be an element of $F$.
Comment: To say $\alpha \in E$ is not algebraic over $E$ is to say that the field extension $E(\alpha)/E$ is infinite. But $E(\alpha) = E$, the field extension is of degree 1.
Comment: If I could backtrack a bit: We know that $\alpha \in E$ because $\alpha \in F$, and $F \subset E$ (since $E/F$ is an field extension of $F$). Am I right on this?
Comment: I think you are missing the fact that we started by saying: "There exists an $\alpha \in E \setminus F$". In other words, we began by assuming that $\alpha$ was *not* in $F$.
Comment: So we suppose $\alpha \not\in F$ (rather, $\alpha \in E \setminus F$), based on the fact that $F \subset E$ (since $E$ is a field extension of $F$. Btw, is the term "nontrivial", in nontrivial field extension, important here?). If $\alpha \in E \setminus F$ is not algebraic over $E$, then it means the field extension of $E \setminus F$ is infinite-dimensional.
Comment: Am I left to show that $\alpha$ is not algebraic in $E \setminus F$?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13914/discussion-between-rghthndsd-and-glacier)
Comment: I'm really sorry, but I unaccepted your answer. My class presented a far different solution, in particular regarding use of the minimal polynimal $x^n-2=0$.
Comment: Feel free to post it. The question should certainly get *an* answer.


offseting date by integer

Question: I've got a content type with fields:
starting date: Date (Unix timestamp)
duration: integer
ending date: Date (Unix timestamp)
User is setting only starting date (year, month, day) and duration (in days)
end after saving the content I would like to automatically calculate ending date (=starting date + duration)
I suppose I should use rules. I tried using actions like set value or calculate value but I failed. Could you help me?
Answer: Interval module may help you. It provides an interval field type and also a rules action: "Apply an interval to a date".
Comment: For a negative interval?
Answer: For a quick fix I would recommend making a simple custom module with this function:
<code>function YOUR_MODULE_node_presave($node) {
  if($node->type === "your_content_type") { // Replace with the content type of your node.
    // Replace $node->XXX with the actual names of your fields.
    $startdate = $node->start_date[LANGUAGE_NONE][0]['value'];
    $duration = $node->duration[LANGUAGE_NONE][0]['value'];
    $enddate = &$node->end_date[LANGUAGE_NONE][0]['value'];

    $enddate = strtotime('+ ' . $duration . ' days', $startdate);
  }
}
</code>

offseting date by integer


How should this be implemented? Delegation

Question: I have many views that I want to communicate with one other view. We'll call that one other view "main view". What I want to do is have the "many other views" be able to send a method to "main view" that adds a subview. Would I create a delegate method? If so, would I create the delegate in the "main view" and then have to set it in the "many other views". I am just wrapping my mind around how delegates work.
Answer: The term 'delegate' is usually used only when an object is sufficiently general and will be reused in many situations with many possible different delegates. For example, a table view, a very generic object, has a delegate that customizes its behavior, but a custom view of your own making that is used for your own purposes might not.
It sounds like you have a very simply many-to-one relationship between your "other" views and your "main" view. You can probably simply make a property on your "other" views (e.g. mainView), or make some other method which allows your "other" views easy access to the "main" view pointer, and send your message to it.
Comment: So, I would be better off creating a class method (not an instance method) in "main view" that shows my view? Then, create a pointer to "main view" in each of the "many views" and then send "main view" class the created method from the "many views"? If this is the case, I cannot call [self.view addsubview:whateverSubviewController.view] in a class method.
Comment: Or, should I set the target of the button that invokes the action to the "main view" view controller and create an instance method in the "main view" that shows the subview?


How can I send Jenkins job queuing times into Elasticsearch?

Question: I want to record the queue lengths of our Jenkins jobs and output to Elasticsearch. For this example, I would post something like
<code>queue-duration:9.9
</code>
to elsasticsearch (among other data).

The API for the page doesn't contain this information. How can I get it, other than scraping the HTML? (jk)
Answer: It should be part of the api, but I suggest you use groovy to determine extract it:
How can I know how long a Jenkins job has been in the wait queue after the job is finished?


Query on a list of json in Mysql 5.6

Question: I am using mysql 5.6 and it will not be feasible for me to upgrade it to 5.7. I have a table which stores json as an attribute. Attaching screenshot for reference.

Here, the column policy_status contains status and values of different policies as json for each user.
How can I find the list of users, say, with appVersion' status as success and value = 1437.
I got a few references online but as I am new to stored procedures I am not able to reach a solution. I will appreciate any help. Thanks in advance.
Answer: It is not efficient at all but may can help you with ideas:
SELECT *
FROM data
WHERE
  (LOCATE('"employmentType":["status":"success"]', policy_status) > 0
   AND
   LOCATE('"value": 1', policy_status) > 0);

Using the LOCATE function you can see whether the field contains your desired appVersion and value strings. See sqlfiddle demo here.
Where the simple test data:
CREATE TABLE data (
  id INT UNSIGNED NOT NULL,
  policy_status TEXT
);

INSERT INTO data (id, policy_status) VALUES
(1,'{"employmentType":["status":"success"], "value": 1}'),
(2,'{"employmentType":["status":"no"], "value": 1}'),
(3,'{"employmentType":["status":"no"], "value": 0}'),
(4,'{"employmentType":["status":"success"], "value": 0}'),
(5,'{"employmentType":["status":"no"], "value": 1}');

gives the result:
{"employmentType":["status":"success"], "value": 1}

Where both strings are found.
UPDATE:
Also if you can add FULLTEXT index for your policy_status column than you can use fulltext search in the WHERE clause:
...
WHERE
   MATCH (policy_status) AGAINST ('+"employmentType:[status:success]" +"value: 1"' IN BOOLEAN MODE)

Note the + and " characters in AGAINST(...). They are special boolean full-text search operators. See here.

A leading or trailing plus sign indicates that this word must be
  present in each row that is returned

and

A phrase that is enclosed within double quote (") characters matches
  only rows that contain the phrase literally, as it was typed. The
  full-text engine splits the phrase into words and performs a search in
  the FULLTEXT index for the words. Nonword characters need not be
  matched exactly.

If it is not an option in your case, you can use LIKE for matching the substrings:
...
WHERE
  (policy_status LIKE '%"employmentType":["status":"success"]%'
   AND
   policy_status LIKE '%"value": 1%');

See sqlfiddle demo for both.

Query on a list of json in Mysql 5.6


Calculating Integral using Fourier's transform

Question: Let $f:\mathbb R \rightarrow \mathbb R$ given by $f(x)=0$ if $x\leq 0$ and $f(x)=e^{-x}$ if $x > 0$, I calculated Fourier's transform of $f$, i.e. $F(\omega)$ and I got $F(\omega)=\frac{1}{\sqrt{2\pi}\cdot(
1+i\omega)}$.
I am trying to find out how can I use this fact to calculate $\int_{0}^{\infty} \frac{cos(2\omega)+\omega\sin(2\omega)}{1+\omega^2}d\omega$ but it seems That I am missing something?
Comment: Confused about why you think one solves the other, can you explain why you think so? And I'm sure there are easier ways to solve this integral.
Comment: @james.nixon we were asked to do it by this way.
Answer: HINT:
$$ \frac{e^{i\omega x}}{1+i\omega}=\frac{\cos(\omega x)+\omega \sin(\omega x)}{1+\omega^2}+i\, \frac{\sin(\omega x)-\omega \cos(\omega x)}{1+\omega^2}\tag 1$$
Note that the imaginary part of the right-hand side of $(1)$ is odd.
Comment: can we also use this ? first using FT of $e^{-a|t|}$ then Duality to obtain.. $$\frac{1}{1+t^2} \Leftrightarrow \pi \cdot e^{-|\omega|} $$ After this use $$\cos \omega t=\frac{e^{-j\omega_0 t}+e^{j\omega_0 t}}{2}$$ this will shift the FT to $\pm \omega_0$ then put $\omega=0$
Comment: And how will you handle $\omega \sin(\omega x)$?
Comment: From FT of $e^{-a|t|}\mathrm{sgn}(t)$ @Mark Viola


How can I make my DNS resilient?

Question: I'm a Sysadmin and am responsible for our external DNS servers. We're trying to make our DNS more resilient.
We have our own DNS servers (Bind). We have one running on each of our two ISP's.
Their IP's are public IP's on the internet, and one is configured as a master, as one as a slave (this is all working).
The question I have.. when one of our ISP's goes down, we tend to lose DNS completely. From what we can tell, this is because our TLD DNS servers are issuing both nameserver's IP's even though one is down.
How do we get around this?
Comment: That's correct operation. Resolvers will move on to the other if one of name servers times out.
Comment: Thanks for the reply..It took approx 15 minutes before requests went to the other server. Does that sound right to you? Our TTL is 5 minutes.
Answer: Your parent domain will always keep dishing out all of your name server addresses, that's by design.
The real question is why you apparently are losing DNS when one of the ISPs goes down.  That shouldn't happen.  Whilst you should expect to see some delays resolving domain names when that happens it shouldn't actually stop working altogether.
Can you provide more information?  What do you actually mean by "losing DNS completely"?
Comment: I've been given some more information about what happened.We have two nameservers NS1 and NS2. External clients were unable to retrieve records from our nameservers for a full 15 minutes before NS2 started responding to DNS requests.
Comment: that shouldn't happen - external clients should spot the broken DNS server almost immediately (i.e. seconds, not minutes).
Answer: You have a pretty reasonable setup that should be resiliant, at least gathering from your description.
You need to collect more information (and/or give us the domain).
Do you lose "dns" immediately after your isp goes down? Do you normally see queries arriving at both nameservers?
It's just a hunch, but is only one of the two isp's critical? It could be incomplete/faulty glue records.
Comment: I suspect this is it, probably only one of the DNS servers have glue records. I made this mistake when I was young, green and keen.
Comment: I've not heard of glue records before! I'll investigate this. Thanks!
Comment: What it boils down to is the registry (com, net, us, be) always refers to nameservers, and those are always located in a domain. In a lot of domains this just refers to someone else (like your hosting provider). For people who (usually) want to be independant and run their own nameservers, there must be some extra information to bootstrap this process: the IP's of the nameservers (in this domain) to start resolving this domain. These are GLUE records.
Comment: (continuation) Both your nameservers will be handing out records as long as this information is available. If those glue-records only refer to the IP address of a nameserver on a single provider, your entire setup will fall down as soon as this provider is unreachable. Since DNS has an extensive caching mechanism (that is actually honored by the clients) not everyone will start to experience problems at the same time. Hope this -very abridged- explanation helps.
Answer: I'd approach it a different way.  Why are you going to the hassle of running your own external facing DNS servers when you can hand a DNS company $50 or so a year and just have bulletproof DNS?
There may well be good reasons don't get me wrong, but it seems like one of those that for a lot of people = spend lots and lots of time and effort, or spend $50 and it all goes away.
Comment: If you're hosting DNS for thousands of domain, like a hosting provider might, the bill would be substantially more than $50/yr. Also if this is a smaller shop, there are free secondary services out there if he needs more resiliency than the two in-house servers.
Comment: Oh of course (got that problem myself), as I said there may be really good reasons for doing it as is, but if the situation is a simple one it might just be a cheaper, more pragmatic and reliable option.
Comment: We used to have external DNS, however we found it easier to manage our own (at least initially), once we installed our BIGIP load balancers, as we had to create a subdomain used for load balacing purposes only.

How can I make my DNS resilient?


How to count the number of independent parameters in a Bayesian network?

Question: I'm currently going through Prof. Daphne Koller's probabilistic graphical models course on Coursera and had a question regarding an exercise problem.
The problem is as follows:

How many independent parameters are required to uniquely define the conditional probability distribution of $C$ in the graphical model below, if $A$, $B$, and $D$ are binary, and $C$ and $E$ have three values each?

My approach is that since $C$ is dependent on $A$ and $B$ (i.e., the CPD of $C$ is $P(C\ \vert\ A, B)$) and $A$, $B$, and $C$ each have 2, 2, and 3, values, respectively, we can write $2 \times 2 \times 3$. But we have to subtract $1$ since knowing all but the last values of $P(C\ \vert\ A, B)$ automatically determines the last. Therefore, we get $(2 \times 2 \times 3) - 1 = 11$ independent parameters.
Where am I going wrong? Any tips are appreciated, thanks.
Answer: Given the values of $A$ and $B$, there are $2\times2=4$ different conditional probability functions of $C$. For example, if $A=1,B=1$:
$$P(C=c_1|A=1,B=1)+P(C=c_2|A=1,B=1)+P(C=c_3|A=1,B=1)=1$$
So, if you happen to know any two of these probabilities, you can find the third because they sum up to $1$. For each of these four conditional probabilities, you need to know $2$ parameters, ending up with a total of $8$ parameters.


Como pegar o tamanho real do scroll?

Question: Estou querendo adquirir a porcentagem que meu scroll está, para manipular css. Porém tenho essas duas variaveis:
document.documentElement.scrollTop;
document.documentElement.scrollHeight;
A primeira me dá a posição do scroll, e a segunda me dá o tamanho do scroll. Fechou, agora eu só preciso dividir pos/height pra ter a porcentagem do scroll, porém no que percebi a variavel document.documentElement.scrollTop; quando meu scroll está no final, não dá o mesmo valor que document.documentElement.scrollHeight;, ou seja minha porcentagem nunca irá chegar a 100% se eu usar esse cálculo.
Pelo que percebi o document.documentElement.scrollTop; não chega no final de fato porque a posição é pega apenas no topo da tela. A uma maneira de eu fazer essa porcentangem de maneira melhor, tipo pegar o tamanho real do scroll?
Comment: Como `scrollTop` marca a posição do topo do viewport, nunca chegará a 100%. Para que seu cálculo funcione basta ajustar o seu valor total, ou seja, seu valor total é o tamanho do scroll menos o tamanho da página (que seria a maior posição que `scrollTop` pode ter). É um problema mais matemático do que de programação, o cálculo ficaria: `100 * scroll_atual / (scroll_total - tamanho_tela)`
Comment: Acho que isso pode te ajudar https://pt.stackoverflow.com/questions/312511/como-detectar-quando-o-scroll-de-um-elemento-chega-ao-final-sem-jquery
Answer: Transformei o comentário em resposta, dessa maneira posso postar um exemplo.

Como scrollTop marca a posição do topo do viewport, nunca chegará a 100%.
Para que seu cálculo funcione basta ajustar o seu valor total, ou seja, seu valor total é o tamanho do scroll menos o tamanho da página (que seria a maior posição que scrollTop pode ter).
É um problema mais matemático do que de programação, o cálculo ficaria:
100 * scroll_atual / (scroll_total - tamanho_tela)

Exemplo

let elem = document.getElementById('perc')
let doc = document.documentElement

window.addEventListener('scroll', function() {
    let value = parseInt(100 * doc.scrollTop / (doc.scrollHeight - doc.clientHeight))
    elem.innerHTML = value + '%'
})
body {
  height: 1000px;
  position: relative;
}

#perc {
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  background-color: tomato;
  padding: 5px;
}
0%

Performance
Lembrando que eventos como scroll e resize são disparados muitas vezes por segundo. Então você quer (ou deveria querer) controlar quantas vezes estes evento podem ser disparados.
Para entender melhor pesquise sobre throttle e debounce de eventos.
Comment: Opa, que honra! :D
Comment: Até salvei nos favoritos :D
Comment: Agora olha esse aqui, sem JS, só com CSS https://codepen.io/una/pen/bwrEpZ não é igual nem tem muito a ver com detectar posição do scroll em si, mas é muito massa!

Como pegar o tamanho real do scroll?


Excel Formula para formatar tabelas

Question: Existe alguma fórmula para encadear as cores de uma tabela?
Eu não quero o "normal" (p.e. vermelho|branco|vermelho). O que pretendo é sempre que o nome de determinada célula for igual, então o fundo é de cor A, quando o nome da célula for diferente então muda para a cor B, quando o nome voltar a mudar então a cor volta a ser a cor A e assim adiante.
Exemplo de tabela.
<code>Teste    X    B   A    T   -> cor A
Teste    f    s   f    g   -> cor A
ALPHA    f    s   f    g   -> cor B
ALPHA    g    g   h    r   -> cor B
ALPHA    f    s   f    g   -> cor B
Beta     G    A   f    g   -> cor A
.......
</code>
O valor a comparar é da primeira coluna pelo valor da primeira coluna da lina anterior.
É possível?
Comment: Sim. Você pode fazer isso com código, mas só tera efeito em sua máquina, embora permitir que seu Excel execute códigos é perigoso.
Comment: E como faço? Podes dar um exemplo do codigo?
Comment: Acesse o menu Macros -> Gravar Macro -> Ok. Faça várias mudanças de estilo, cores, preenchimentos, etc. Volte no menu Macros -> Exibir Macros e veja o código que o Excel criou para você. Crie uma nova planilha,volte em Macros -> Exibir Macros. Selecione sua Macro e clique em Executar. Agora você pode aterar o código como quiser.
Answer: Normalmente eu uso a formatação condicional, vc pode selecionar apenas as celular e depois clicar na aba formatação condicional, ou selecionar o documento inteiro.
Depois de clicar em Formatação condicional escolha Realçar Regras das Células ai é só escolher quais são as condições para trocar as cores automaticamente de acordo com a palavra, se é maior que, menor que, igual a, etc....
Simples assim
Comment: Dessa maneira já consegui fazer mas queria tentar mais dinâmico, ou seja, a formula vai ver o valor da linha anterior para ver se é igual ou não, se for igual a cor mantém-se se for diferente muda.
A tabela tens os valores a comparar ordenados de forma alfabética.
Answer: Boa tarde. Se ainda puder ajudar, e se for possível criar uma coluna extra onde terá o critério da formatação condicional, podes usar a fórmula abaixo:
<code>=SE(A2=A1;D1;-(D1))
</code>
Fiz a fórmula na coluna D. Coloca a referência para a coluna onde ficar esta fórmula.
O valor da célula D1 deve diferente de 0 (coloquei 1, pra facilitar).
Já na formatação condicional, podes selecionar para "Usar uma fórmula para determinar quais células devem ser formatadas" e usar a fórmula abaixo:
<code>=$D1=-1
</code>
Novamente, a referência à coluna "D" é conforme a coluna onde vai estar a fórmula.
O valor "-1" é por que coloquei valor 1 na célula D1.
Para não variar a referência em relação a coluna onde está a fórmula, coloca "$" antes do "D" ("$D").
E o intervalo deve começar na mesma linha da fórmula (no caso, linha 1). Se não, tem que contar a diferença entre a referência.
Espero ter ajudado.

Excel Formula para formatar tabelas


Plotting a discriminant as line on scatterplot

Question: Given a data scatterplot I can plot the data's principal components on it, as axes tiled with points which are principal components scores. You can see an example plot with the cloud (consisting of 2 clusters) and its first principle component. It is drawn easily: raw component scores are computed as data-matrix x eigenvector(s); coordinate of each score point on the original axis (V1 or V2) is score x cos-between-the-axis-and-the-component (which is the element of the eigenvector).

My question: Is it possible somehow to draw a discriminant in a similar fashion? Look at my pic please. I'd like to plot now the discriminant between two clusters, as a line tiled with discriminant scores (after discriminant analysis) as points. If yes, what could be the algo?
Answer: OK, since nobody answered I think that, after some experimentation, I can do it myself. Following discriminant analysis guidelines, let T be the whole cloud's (data X, of 2 variables) sscp matrix (of deviations from cloud's centre), and let W be the pooled within-cluster sscp matrix (of deviations from a cluster centre). B=T-W is the between-cluster sscp matrix. Singular value decomposition of inv(W)B yields us U (left eigenvectors), S (diagonal matrix of eigenvalues), V (right eigenvectors). In my example of 2 clusters only the 1st eigenvalue is nonzero (which means that there is only one discriminant), and so we use only the 1st eigenvector (column) of U: U(1). Now, XU(1) are the sought-for raw discriminant scores. To show the discriminant as a line tiled with those, multiply the scores by cos-between-the-axis-and-the-discriminant (which is the element of the eigenvector U(1)) - just as did it with principal component above. The resulting plot is below.
Comment: It might be easier to think of this as a *projection*: $U(1)$ in both cases (PCA or LDA) is a unit vector in the direction on which you want to project your data (first principle axis, or first "discriminant axis"). Orthogonal projector is [given](http://en.wikipedia.org/wiki/Projection_%28linear_algebra%29#Orthogonal_projections) by $P_U = UU^\top$. So the answer is $XUU^\top$ (which of course is exactly what you found out yourself). The same formula works for higher dimensions as well.
Comment: @amoeba, thank you for the comment. The general (for any dimensionality) formula is XV where V is the column-normalized (to SS=1) matrix of eigenvectors of the LDA extraction. These normalized eigenvectors of iris data I display here: http://stats.stackexchange.com/a/83114/3277; the algebra of LDA is here: http://stats.stackexchange.com/a/48859/3277. A plot where I used LDA's normalized eigenvectors is here: http://stats.stackexchange.com/a/22889/3277.
Comment: Yes, sure $XV$ are coordinates of the data points in the target space of lower dimensionality, but if you want to get the image of the projection in the original high-dimensional space (i.e. green dots on your scatter plots in this thread), you project these points back with $V^+$, so in the end you get $XVV^+$. I made a mistake in my previous comment: it reduces to $XVV^\top$ only when $V$ has orthonormal columns, like in the PCA case (but not LDA). Of course if you only consider 1 axis (and so $V$ has only 1 column), then it does not matter.


Epsilon-delta proof of multivariable limit [f(x+dx,y+dy)-f(x,y+dy)]/dx

Question: When can we prove that
$$\lim_{(dx,dy)\to(0,0)} \frac{f(x+dx,y+dy)-f(x,y+dy)}{dx} = f_x(x,y)$$
I'm willing to assume that $f_x$ and $f_y$ are continuous.
Here is my failed proof attempt:
By algebra,
$$\begin{align*}
&\frac{f(x+dx,y+dy)-f(x,y+dy)}{dx}\\
&=\frac{f(x+dx,y)-f(x,y)}{dx}+\frac{f(x+dx,y+dy)-f(x+dx,y)}{dx}+\frac{f(x,y)-f(x,y+dy)}{dx}\\
&=A + B + C
\end{align*}$$
By definition, $\lim_{(dx,dy)\to(0,0)} A = f_x(x,y)$.
For my conjecture to be true, I must show that $\lim_{(dx,dy)\to(0,0)} B + C = 0$.
This seems unlikely, since $\lim_{(dx,dy)\to(0,0)} C$ varies depending on the relationship between dx and dy. How can I show that $\lim_{(dx,dy)\to(0,0)} B + C = 0$?
Comment: Really $$\lim_{dx\to 0} \frac{f(x+dx,y)-f(x,y)}{dx} = f_x(x,y)$$The indeterminate form $0/0$ doesn't exclude the existence of the limit.
Comment: Can you please clarify how your comment relates to my question?
Comment: If you are trying to find a derivative, you will always get an indeterminate 0/0 form because the derivative is an instantaneous change.  That means that in the limit we are looking at an interval of width 0.  However, that limit can exist.  As a trivial  example 2h/h $\rightarrow$ 2 as h $\rightarrow$ 0.  As to how you know whether the limit exists, it very much depends on the situation, and the $\epsilon-\delta$ approach is not very helpful.  You might want to go back to calc 1 and find the derivative of f(x) = x$^2$ using the limit of differences method.
Comment: I am comfortable with formally computing limits. I've updated the question to show where my proof goes wrong.
Answer: Avoiding some detail, I prove the statement
If $f$ has partial derivative $f_x$ at every point of an open ball centered at $(x,y)$ and this is continuous at $(x,y)$, then $$\lim_{(dx,dy)\to(0,0)} \frac{f(x+dx,y+dy)-f(x,y+dy)}{dx} = f_x(x,y)$$In fact the mean value theorem (for functions of one variable) says that, if $dx \neq 0$ $$\frac{f(x+dx,y+dy)-f(x,y+dy)}{dx}=f_x(x+\theta\,dx,y+dy)$$with $0<\theta<1\,$.


Change css class on the fly with a button press (while pulling class names from an array).

Question: How to change css class on the fly with a button press (while pulling class names from an array).  If I hard code the classes into a switch statement, I can step through the classes fine.  But, when I try and pull class names from an array, it jumps to the end of switch statement. I believe that I need to have the button press halt the counter for the array, so I can step through.  The 'Switch Class' and 'array switch' buttons are the ones that I am working with here.
The switch which works (the 'Switch Class button:

The switch with the array that is giving me trouble (the 'array switch' button.

The HTML
<!DOCTYPE HTML>

<title> Order Entry  </title>
<meta charset="utf-8">
<link rel="stylesheet" href="reset.css">

 xxx

         <button id="swapStyle1">swapStyle1 </button>
        <button id="swapStyle2">swapStyle2 </button>
        <button id="swapStyle3">swapStyle3 </button>
        <button id="cyclStyls">Cycle through styles</button>
        <button id="one" value="1"
        OnClick="cyclStylsSwtch()">Select</button>
        <button id="cyclStylsSwtch">Cycle through styles</button>
        <button id="cyclStylsArrayCntr">array switch</button>
        <button id="swtchClss">swtchClss</button>

Order

 Order Form

Order

 Order Form

                <form name="contactForm" id="prdcts">

                Item

                Price

                Quantity

                Smoked Ham
                $3.00 lb

                <input type="number" name="ham"
                id="ham" value="0" size="3" maxlength="3">

                Smoked Herring
                $1.00 oz

                <input type="number" name="herring"
      id="herring" value="0" size="3" maxlength="3">

                Texas Hotlinks
                $2.00 each

                <input type="number" value="0"
   name="htlnk" id="htlnk" size="3"
                maxlength="3">

 Buttons located here clear screen data

                <input type="reset" value="Clear
                Form" onclick="clearForm()">

                </form>
                <button id="pop7">Display Form data Products sold
                 </button>
                <button id="clrSaleData">clear Sales Data Pop Up</button>

Additional scripts needed to run the HTML as is:

Comment: I would imagine that 95% of this code is not relevant to your question.  Please create a [Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) that demonstrates your issue.
Answer: But, when I try and pull class names from an array, it jumps to the end of switch statement.
you have placed your switch inside a loop and it goes for every value from 1 to 8 as far as i understand you logic when one switch operates then previous switch classes are removed and so the loop reaches at clck = 8 and executes and gets out of the for  loop and all you see is 8th switch classes
take a look for javascript below it runs for case 1 and alert 1 and also for case 8.
I think you need to update your logic

$(document).ready(function() {

    $('#cyclStylsArrayCntr').click(function(event){
    var curClass = ['ordrTabl1', 'ordrTabl2', 'ordrTabl3', 'ordrTabl4',  'ordrTabl5', 'ordrTabl6', 'ordrTabl7', 'ordrTabl8'];
 // Array of scores
    var arrayLength = curClass.length;// Items in array
    var clcks = 0;            // Current round
    var msg = '';                   // Message

    // Loop through the items in the array
    for (var i = 0; i < arrayLength; i++) {

      // Arrays are zero based (so 0 is round 1)
      // Add 1 to the current round
      clcks = (i + 1);

                                switch (true) {
            case clcks == 1:
            alert (clcks);
                $('#txtbox6').addClass(curClass[i]);
                $('#txtbox6').removeClass('ordrTabl8');
                break;
            case clcks == 2:
                alert (clcks);
                $('#txtbox6').addClass(curClass[i]);
                $('#txtbox6').removeClass('ordrTabl1');
                break;
            case clcks == 3:
                alert (clcks);
                $('#txtbox6').addClass(curClass[i]);
                $('#txtbox6').removeClass('ordrTabl2');
                break;
            case clcks == 4:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl4');
                $('#txtbox6').removeClass('ordrTabl3');
                break;
            case clcks == 5:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl5');
                $('#txtbox6').removeClass('ordrTabl4');
                break;
            case clcks == 6:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl6');
                $('#txtbox6').removeClass('ordrTabl5');
                break;
            case clcks == 7:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl7');
                $('#txtbox6').removeClass('ordrTabl6');
                break;
            case clcks == 8:
            alert (clcks);
                $('#txtbox6').addClass('ordrTabl8');
                $('#txtbox6').removeClass('ordrTabl7');
                break;
                                }
    }

 } );

    });

dfgdfgdfgdfg

I think you should remove for loop

$(document).ready(function() {
   var clcks = 0;
    $('#cyclStylsArrayCntr').click(function(event){
    var curClass = ['ordrTabl1', 'ordrTabl2', 'ordrTabl3', 'ordrTabl4',  'ordrTabl5', 'ordrTabl6', 'ordrTabl7', 'ordrTabl8'];

    var msg = '';                   // Message

      // Arrays are zero based (so 0 is round 1)
      // Add 1 to the current round
      clcks = (clcks + 1);
      if(clcks>8)clcks=1;

                                switch (true) {
            case clcks == 1:
            alert (clcks);
                $('#txtbox6').addClass(curClass[clcks]);
                $('#txtbox6').removeClass('ordrTabl8');
                break;
            case clcks == 2:
                alert (clcks);
                $('#txtbox6').addClass(curClass[clcks]);
                $('#txtbox6').removeClass('ordrTabl1');
                break;
            case clcks == 3:
                alert (clcks);
                $('#txtbox6').addClass(curClass[clcks]);
                $('#txtbox6').removeClass('ordrTabl2');
                break;
            case clcks == 4:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl4');
                $('#txtbox6').removeClass('ordrTabl3');
                break;
            case clcks == 5:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl5');
                $('#txtbox6').removeClass('ordrTabl4');
                break;
            case clcks == 6:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl6');
                $('#txtbox6').removeClass('ordrTabl5');
                break;
            case clcks == 7:
                alert (clcks);
                $('#txtbox6').addClass('ordrTabl7');
                $('#txtbox6').removeClass('ordrTabl6');
                break;
            case clcks == 8:
            alert (clcks);
                $('#txtbox6').addClass('ordrTabl8');
                $('#txtbox6').removeClass('ordrTabl7');
                break;
                                }

 } );

    });

dfgdfgdfgdfg

$(document).ready(function() {

  $("#pop7").click(function() {
    var hamPrice = 3;
    var herringPrice = 1;
    var linkPrice = 3;
    var ham = document.getElementById('ham').value;
    var herring = document.getElementById('herring').value;
    var htlnk = document.getElementById('htlnk').value;
    var divObj = document.getElementById("txtbox4");
    var hamTotal = hamPrice * ham;
    var herringTotal = herringPrice * herring;
    var linkTotal = linkPrice * htlnk;
    var grandTotal = hamTotal + herringTotal + linkTotal;
    $('.tmp9').css("background-color", "#75BDFF");
    $('.tmp9').css("height", "400px");
    $('.tmp9').css("width", "400px");
    $('.tmp9').css("box-shadow", "10px 10px 2px #333333");
    $('.tmp9').css("border", " 6px double  #660000");
    $('.tmp9').css("-webkit-border-radius", "9px");
    $('.tmp9').css("-moz-border-radius", "9px");
    $('.tmp9').css("border-radius", "9px");
    $('.tmp9').css("padding", "10px");
    $(".tmp9").toggle();
    $(".tmp9").html('

' + ham + ' hams sold at $' + hamPrice + ' for  $' + hamTotal + '

' + herring + ' herring sold at $' + herringPrice + ' for  $' + herringTotal + '

' + htlnk + ' Texas hot links sold at $' + linkPrice + ' for  $' + linkTotal + '

 For a total sale of  $' + grandTotal + '

 Thank you for your business.  Please come again.

');

  });

  $("#popup7").click(function() {
    $("#detail7").toggle();
    $(window.location.href = "#top")
  });

  $('#swapStyle1').click(function(event) {
    $('#txtbox6').addClass('ordrTabl1');
    $('#txtbox6').removeClass('ordrTabl2');
    $('#txtbox6').removeClass('ordrTabl3');
  });

  $('#swapStyle2').click(function(event) {
    $('#txtbox6').addClass('ordrTabl2');
    $('#txtbox6').removeClass('ordrTabl3');
    $('#txtbox6').removeClass('ordrTabl1');
  });

  $('#swapStyle3').click(function(event) {
    $('#txtbox6').addClass('ordrTabl3');
    $('#txtbox6').removeClass('ordrTabl2');
    $('#txtbox6').removeClass('ordrTabl1');
  });

  $("#clrSaleData").click(function() {
    $('.tmp9').css("display", "none");
  });

  $('#cyclStyls').click(function(event) {
    var curClass = ['ordrTabl1', 'ordrTabl2', 'ordrTabl3']; // Array of scores
    var arrayLength = curClass.length; // Items in array
    var count = 0; // Current round
    var msg = ''; // Message

    // Loop through the items in the array
    for (var i = 0; i < arrayLength; i++) {
      $('#txtbox6').removeClass(curClass[i]);
      // Arrays are zero based (so 0 is round 1)
      // Add 1 to the current round
      count = (i + 1);
      alert(curClass[i])
      $('#txtbox6').addClass(curClass[i]);
    }

  });

  var cliks = 1;

  function cyclStylsSwtch() {

    if (cliks < 3) {
      cliks += 1;
    } else {
      alert('else statement')
      cliks = 1;
    }
    switch (true) {
      case cliks == 1:
        $('#txtbox6').addClass('ordrTabl1');
        $('#txtbox6').removeClass('ordrTabl3');
        break;
      case cliks == 2:
        $('#txtbox6').addClass('ordrTabl2');
        $('#txtbox6').removeClass('ordrTabl1');
        break;
      case cliks == 3:
        $('#txtbox6').addClass('ordrTabl3');
        $('#txtbox6').removeClass('ordrTabl2');
        break;
      case cliks == 4:
        cliks = 1;
        alert(cliks);
        break;
      case cliks == 5:
        cliks = 1;
        alert(cliks);
        break;
    }

  };

  var clix = 1;

  $("#cyclStylsSwtch").click(function() {

    if (clix < 8) {
      clix += 1;
    } else {
      clix = 1;
    }
    switch (true) {
      case clix == 1:
        $('#txtbox6').addClass('ordrTabl1');
        $('#txtbox6').removeClass('ordrTabl8');
        break;
      case clix == 2:
        $('#txtbox6').removeClass('ordrTabl1');
        $('#txtbox6').addClass('ordrTabl2');

        break;
      case clix == 3:
        $('#txtbox6').addClass('ordrTabl3');
        $('#txtbox6').removeClass('ordrTabl2');
        break;
      case clix == 4:
        $('#txtbox6').addClass('ordrTabl4');
        $('#txtbox6').removeClass('ordrTabl3');
        break;
      case clix == 5:
        $('#txtbox6').addClass('ordrTabl5');
        $('#txtbox6').removeClass('ordrTabl4');
        break;
      case clix == 6:
        $('#txtbox6').addClass('ordrTabl6');
        $('#txtbox6').removeClass('ordrTabl5');
        break;
      case clix == 7:
        $('#txtbox6').addClass('ordrTabl7');
        $('#txtbox6').removeClass('ordrTabl6');
        break;
      case clix == 8:
        $('#txtbox6').addClass('ordrTabl8');
        $('#txtbox6').removeClass('ordrTabl7');
        break;
    }

  });
});

Comment: Thank you.  Removing the for loop worked.    I dropped this code in and it steps through relatively cleanly.  I'll need to fiddle with the logic a bit  to get a clean first and last entry (need to click twice now).
Comment: here is a copy of the working file on one of my sites To be fiddled with in Perpetuity:                   http://etherealdoorways.com/ordrEntryFrmFlxStyling.html
Comment: try the above script and your double click problem will be solved
Comment: and don't use too many `$(document).ready(function() {` and also do marked the answer as accepted if you problem is solved
Answer: Please remove the for loop and use the clcks to get the classes.
Check if this works (pardon any missing brackets):
 $('#cyclStylsArrayCntr').click(function(event){
    var curClass = ['ordrTabl1', 'ordrTabl2', 'ordrTabl3', 'ordrTabl4',  'ordrTabl5', 'ordrTabl6', 'ordrTabl7', 'ordrTabl8'];
 // Array of scores
    var arrayLength = curClass.length;// Items in array
    var clcks = 0;            // Current round
    var msg = '';                   // Message

  if (clcks < 8){

                    clcks+=1;

                        }
                            else{

                            clcks = 1;

                        };

      // Arrays are zero based (so 0 is round 1)
      // Add 1 to the current round

                                switch (true) {
            case clcks == 1:
            alert (clcks);
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[7]);
                break;
            case clcks == 2:
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[clcks-2]);
                break;
            case clcks == 3:
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[clcks-2]);
                break;
            case clcks == 4:
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[clcks-2]);
                break;
            case clcks == 5:
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[clcks-2]);
                break;
            case clcks == 6:
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[clcks-2]);
                break;
            case clcks == 7:
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[clcks-2]);
                break;
            case clcks == 8:
            alert (clcks);
                $('#txtbox6').addClass(curClass[clcks-1]);
                $('#txtbox6').removeClass(curClass[clcks-2]);
                break;
                                }

 } );

    });

 </script>


Does Closure exist in a Nested function without variables

Question: Can we say a closure exist in this code
<code>function foo(){
        return function foo2(){
                   console.log("Inner Function");
          }
}

let x = foo();
x();
</code>
Answer: No the inner function is not a closure here. It is not accessing any variable which is outside the scope.
Here is the snapshot from chrome console.

But when the inner function access a variable defined outside its scope the whole environment that is function with references to its surrounding becomes a closure. You can see scope closure in the console
Comment: That's wrong closure is created regardless of the variables


Which Axiom does this definition fail?

Question:
Consider the set of vectors $\renewcommand{\vec}[1]{\mathbf{#1}}\vec{u}=(x,y,z)$ in $\mathbb{R}^3$ with standard addition, but scalar multiplication defined by $r\vec{u}=(r^2x,r^2y,r^2z)$. This is not a vector space. Determine which vector space axiom fails and exhibit a counterexample to demonstrate the failure of that axiom.

I have attempted this and have come to believe it is the $r(s\vec{v}) = (rs)\vec{v}$ axiom that it fails.
I am new to this subject and am hoping for some guidance/confirmation.
Comment: @KerryFishcer No, $(r+s)v = ((r+s)^2 x, (r+s)^2 y, (r+s)^2 v)$.
Comment: ooooooooohhhhhhhh THANK YOU ALL SO MUCH!

Now I feel stupid hah.
Comment: [1]: https://i.stack.imgur.com/OqwTO.png
Comment: It would have been much better to use MathJax to quote the problem in your post rather than as an image (I think you also may need some reputation points to post images). ....
Comment: ... the axiom you cite does not fail. Your list of axioms should include one about  $(r + s) \mathbf{v}$. Have a look at that axiom and consider some specific examples for $r$ and $s$.
Comment: @fleablood: I agree about the ordering of the vector space axioms. But in the OP's defence, he stated what the axiom was and included a link in his comment to an image of the problem he's trying to solve.
Comment: Yeah, I realized that when I reread her post.  That axiom works as if $u = (x,y,z)$ the $r(su) = r(s^2x, s^2y,s^2z)=(r^2s^2x, r^2s^2y, r^2s^2z)$ and $(rs)u = ((rs)^2x, (rs)^2y, (rs)^z)$ so that is good.
Comment: Oops! Apologies to Kerry if I was wrong in reading Kerry as a male name.
Comment: oh so r(sv) = (rs)v doesn't fail?

And thanks Rob I'll look into (r+s)v.

I wish I was able to post a photo of my attempts...
Comment: Have a look at https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference too.
Comment: (r + s)v = $(r^2x,r^2y,r^2z) + (s^2x,s^2y,s^2z)$ right? and isnt that equal to rv + sv? it looks like a vector space to me and that why im so lost...
Answer: (r+s)u = ${(r+s)^2x,(r+s)^2y,(r+s)^2z)}$ = {$(r^2+2rs+s^2)x,(r^2+2rs+s^2)y,(r^2+2rs+s^2)z$} $\ne$ ru+su = $(r^2x,r^2y,r^2z)+(s^2x,s^2y,s^2z)$
Therefor,
(r+s)u $\ne$ ru+su
Comment: It's correct except, for completeness, you should give values for $r$ and $s$ that demonstrate that $(r + s)^2 \ne r^2 + s^2$. Here it matters that the field is $\mathbf{R}$, if you were working in a field where $2  = 0$, then this proof doesn't work (and actually, I think, it will form a vector space).
Comment: this look right?
Comment: @TrevorGunn: yes, in a field $k$ of characteristic 2, $x \mapsto x^2$ is a field automorphism and if you permute the usual view of $k^n$ as a vector space via this automorphism you will still get a vector space.
Answer: Your initial question has been answered already, so let me explain how to think about this problem—at least, how I thought about the problem.
You can see that $r\pmb{v}$ is never going to be a negative multiple of $\pmb{v}$, but we know that for vector spaces, $(-1) \cdot \pmb{v} = - \pmb{v}$. So now you need to either look up or try your best to remember the proof that $(-1) \cdot \pmb{v} = - \pmb{v}$ to see what the key axioms that are used in that proof.
Because you have the standard addition on $\mathbf{R}^3$, all the axioms that refer just to the vector addition and not the scalar multiplication will always be satisfied. So what you are left with is:

$r(s\pmb{v}) = (rs)\pmb v$
$(r + s)\pmb v = r \pmb v + s \pmb v$
$r(\pmb v + \pmb w) = r\pmb v + r \pmb w$
$1 \pmb v = \pmb v$

The essential property of the number $(-1)$ is the equation $1 + (-1) = 0$ which involves both $1$ and $+$ (scalar addition). Of the 4 axioms, the fourth mentions $1$ and you can check that easily, and the second uses the scalar addition. So because the essential equation $1 + (-1) = 0$ uses scalar addition, that tells us to look at the second axiom.

Which Axiom does this definition fail?


Tratamento de variaveis em HTML

Question: Olá... O mundo HTLM / JAVASSCRIPT / PHP é totalmente novo para mim. Como iniciante, conto com a ajuda de vocês para desenvolver um pequeno projeto.
Vamos lá...
Tenho uma página INDEX.HTML que recebe um valor via URL. Consegui ler esse valor usando uma função chamada CAPTURAPARAMETROURL() que peguei neste forum. Agora preciso abrir uma página chamada CADASTRO.HTML quando o usuário clicar em INSCRIÇÃO passando esse valor obtido pela função.
Quem pode me ajudar?
O código do INDEX.HTML é este:

<!DOCTYPE html>

 <title>MEU SITE</title>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">

 <link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
 <link rel="stylesheet" type="text/css" href="css/util.css">
 <link rel="stylesheet" type="text/css" href="css/main.css">

                                <button class="meusite-form-btn">
                                        Inscrição

                                </button>

                            <button class="meusite-form-btn" >

                                                    Termos de uso

                                </button>

Answer: Você pode ir concatenando os parâmetros e depois alterar o href do link adicionando os parâmetros.
Primeiro, retire o ? do link, deixando apenas href="cadastro.html":
Inscrição

Em seguida use o código abaixo alterado (veja explicações no código):
window.onload = CapturaParametrosUrl();

/* Captura parametros da URL com JS*/
function CapturaParametrosUrl() {
   var url = window.location.href; //retorna a url da página

   var res = url.split('?'); //tenta localizar o ?

   var params = ''; // cria uma variável para os parâmetros

   if (res[1] !== undefined) {

      var parametros = res[1].split('&'); //tenta localizar os & (pode haver mais de 1)

      if (parametros[0] !== undefined) {
         parametro0 = parametros[0].split('=');
         parametro0 = parametro0[1];
         var promocional = parametros[0]
         //document.getElementById('resultado').innerHTML = parametro0;

         params += "?param1="+parametro0; // adiciona o 1º parâmetro
      }

      if (parametros[1] !== undefined) {
         parametro1 = parametros[1].split('=');
         parametro1 = parametro1[1];
         //document.getElementById('resultado').innerHTML += ', ' + parametro1;
         params += "&param2="+parametro1; // adiciona o 2º parâmetro
      }

      if (parametros[2] !== undefined) {
         parametro2 = parametros[2].split('=');
         parametro2 = parametro2[1];
         //document.getElementById('resultado').innerHTML += ', ' + parametro2;
         params += "&param3="+parametro2; // adiciona o 3º parâmetro
      }
   }

   if(params != ""){ // se houve parâmetros, atualizo o href do link com eles
      document.querySelector("a[href='cadastro.html']").href = "cadastro.html"+params;
   }
}

No exemplo acima, eu utilizei os nomes dos parâmetros como param1, param2 e param3. Esses nomes você pode alterar com os que desejar, é só altera-los no código.
Comment: Deu certinho! Passou corretamente o parâmetro. Agora, acho que eu deveria abrir outro tópico de pergunta mas não custa perguntar: Posso usar esse mesmo método para pegar o parâmetro passado para página CADASTRO.HTML e inserir esse valor num INPUT? Como ficaria essa linha neste caso?

 document.querySelector("a[href='cadastro.html']").href
Comment: Pode usar a mesma função. Para incluir no input teria que mudar o seletor para `document.querySelector("input").value = params`... no lugar de `input` você teria que colocar uma id ou classe, ou pegar pelo name etc.
Comment: Show de bola! Deu tudo certo. Muito obrigado!
Comment: Onde marco isso? Estou procurando aqui e não acho... rsrsrsrsrs
Comment: achei! valeu....

Tratamento de variaveis em HTML


How to replace letters in lines in fasta file using bash loops?

Question: I want to change all n in the sequence into -, but I don't know how to make my bash script not change the n that show up in sequence names. I'm not experienced with sed or regex to make sure my bash script reads only the lines that do not start with >, as that indicates the header.
Example file:
>Name_with_nnn
nnnatgcnnnatttg
>Name2_with_nnn
atgggnnnnGGtnnn

At the same time I want to convert all lowercase letters into uppercase, only in the sequence lines. I don't even know how to begin using sed, I find it really tricky to understand.
Expected output:
>Name_with_nnn
---ATGC---ATTTG
>Name2_with_nnn
ATGGG----GGT---

So after I created my sequence files I tried to continue my script with:
while IFS= read -r line
do
     if [[ $line == ">"* ]]
     then
          echo "Ignoring header line: $line"
     else
          echo "Converting to uppercase and then N-to-gaps"
          # sed or tr?? do call $line or do I call $OUTFILE? so confused..
     fi
done

Answer: You can resolve this with sed with below line:
sed -i "/^>/! {s/n/-/g; s/\(.*\)/\U\1/g}" text.txt

And your output would be:
>Name_with_nnn
---ATGC---ATTTG
>Name2_with_nnn
ATGGG----GGT---

Comment: @CedricZoppolo  Not only uppercase, you updated `start with` `>` too, might be worth mentioning.
Comment: @DNAngel be aware I updated the script as converting to uppercase was missing.
Comment: @Tiw is correct. I also updated to ensure only lines not starting with `>` will be converted. I was missing `^` character in order to get the lines starting with `>` and not lines containing such character in any part of line.
Answer: You may use this simple gnu sed:
sed '/^>/!{s/n/-/g; s/.*/\U&/;}' file

>Name_with_nnn
---ATGC---ATTTG
>Name2_with_nnn
ATGGG----GGT---

Answer: In pure Bash, likely quite slow for larger inputs:
while IFS= read -r line; do
    case $line in
        '>'*)
            printf '%s\n' "$line"
            ;;
        *)
            line=${line//n/-}
            printf '%s\n' "${line^^}"
            ;;
    esac
done < infile

This uses a case statement with pattern matching to test if a line starts with > or not; to modify the lines, parameter expansions are used. The ${parameter^^} expansion requires Bash 4.0 or newer.
Answer: How about awk ?
awk '/^[^>]/{gsub("n","-");print toupper($0);next;}1' data

Output:
>Name_with_nnn
---ATGC---ATTTG
>Name2_with_nnn
ATGGG----GGT---

However, sed can do it too (GNU sed):
sed -E '/^[^>]/{s/n/-/g;s/(.*)/\U\1/g;}' data

It's the same as:
sed -E '/^>/!{s/n/-/g;s/(.*)/\U\1/g;}' data

If you want to change in place, you can add -i switch to sed.


What does $\beta$ mean when describing effect sizes?

Question: I'm reading a paper which includes a number of lines like the following:
"positive emotions in the emotional design treatment had a direct effect on transfer $(\beta=3.34,p>.001)$"
The paper itself doesn't explicitly define how $\beta$ is calculated, or what its unit is. Am I reasonable to assume that in the above example, members of the treatment group outperformed the control by 3.34 Standard Deviations?
If so, is this number meaningfully different from measures like Cohen's $d$ or Hedges $g$?
Answer: Without any other information, my assumption would be that it is a coefficient from a regression. This assumption would be strengthened if the paper relied on multiple regression.
However, even if the paper doesn't explicitly state what $\beta$ is, it must offer some context for it. What statistics were done?
It seems very unlikely to me that it means a number of standard deviations, but, in some contexts, I suppose it is possible.
Comment: I am afraid that you are right, it is a coefficient. But wouldn't that be a bad case to state it following the typical format of (parameter = ., p-value = .)? I always see this parameter as a calculated statistic that can be directly compared to a p-value in tables (e.g. chi-squared value, t-score, F-score, etc.). If it would be the coefficient value then it is a very bad (at least unorthodox) way of reporting.
Comment: Indeed, more information is necessary to be able to do more with this question than just guessing. Sadly, there are many articles that don't really tell so much more, and this question gives the minimum information just like some articles do. It is so familiar (the lack of information).
Comment: I looked it up. There was no explanation how the p-values were calculated. See here: after  "we ran a series of regression analyses" from Um, Eunjoon, et al. "Emotional design in multimedia learning." *Journal of educational psychology* 104.2 (2012): 485.


Informix: How to pass, use and execute multiple values in a single parameter to a stored procedure

Question: How I Can pass multiple values in a single parameter to a stored procedure in Informix?.
This is a frequent question but I have seen noyhing about informix.
I found a post, but it is not working for me, should be the version of the DB or am I missing something?
I'm trying this to perform a WHERE X IN (SELECT Y FROM TABLE(PARAM))
Edit:
This is an example of what Im trying to do.
CREATE PROCEDURE test_hector
(
    C LIST( SET (CHAR(10) NOT NULL ) NOT NULL)
)
RETURNING CHAR(10) AS C, CHAR(10) AS CVE, CHAR(50) AS DESC;

DEFINE vColumna like tclaves.columna;
DEFINE vClave like tclaves.clave;
DEFINE vdescve like tclaves.descve;

FOREACH
select columna, clave, descve
INTO vColumna, vClave,vdescve
from tclaves
where columna in (SELECT * FROM TABLE(C))
RETURN vColumna, vClave,vdescve WITH RESUME;
END FOREACH
END PROCEDURE;

I'm trying to execute it but I think I'm having sintax problems
EXECUTE PROCEDURE test_hector( '{stspols,stsrepo}');

I'm getting the error message  [Informix][Informix ODBC Driver][Informix]Invalid collection literal value.
I executed this function execute function se_release() to obtain the informix version this is what I got.
column1
Spatial DataBlade Release 8.21.FC4R1 (Build 238)                 Compiled on Thu Aug 26 19:42:55 CDT 2010 with:                      IBM Informix Dynamic Server Version 10.00.FC7                    glslib-4.00.UC10

I'm using Aqua Data Studio 8.0.22 to create and execute the procedure. Runinng on Windows 7 Ultimate 32-Bits
Thanks in advance. For any help
Comment: Same sollution http://stackoverflow.com/questions/11038298/how-to-pass-an-informix-collection-parameter-list-set-multiset-in-c-sharp-th
Answer: Define the parameter type as an appropriate collection type: LIST, SET, MULTISET (which is what I said in the answer to the cross-referenced question).

What isn't working for you?
What did you try?
What is the error message you get?
Which version of Informix server are you using?
Which tool or API are you using to create the stored procedure?
Which tool or API are you using to execute the stored procedure?
Which platform are you running on?
How are you invoking the procedure?

Thanks for amplifying the question.  You say:

EXECUTE PROCEDURE test_hector('{stspols,stsrepo}');

I'm getting the error message [Informix][Informix ODBC Driver][Informix]Invalid collection literal value.

This may be a simpler problem to fix than it appears on the surface.  The input type for the procedure is supposed to be a collection — in fact, a LIST of SET values — where each value is a character string.  You can write that as:
EXECUTE PROCEDURE test_hector(LIST{SET{'stspols','stsrepo'}});

I created myself a dummy procedure to test this syntax:
CREATE PROCEDURE test_hector(c LIST(SET (CHAR(10) NOT NULL ) NOT NULL))
    RETURNING CHAR(10) AS C, CHAR(10) AS CVE, CHAR(50) AS DESC;
    return "abc", "def", "ghi";
END PROCEDURE;

And the output from it was as expected:
abc   def   ghi

Note that Informix supports a comment style started by { and ended by the first following }.  However, that comment style is suppressed when the keyword before the { is one of SET, MULTISET or LIST (and yes, that does make it really hard to parse!).  You can have immense (if perverted) fun with "where can you add the {} in the SQL above" without changing its meaning.  There's an outside chance that an API might recognize Informix {} comments but not recognize the collection-exception.  In that case, you'd probably get back a syntax error (because the second } is not expected if you interpret the first { as a start comment symbol).  In that case, use one of the notations below.
The notation for collection (SET, MULTISET, LIST) literals evolved over time.  This alternative notation also works (and is more closely related to what you tried originally, and is what was documented originally):
EXECUTE PROCEDURE test_hector('LIST{SET{''stspols'',''stsrepo''}}');

The strings within the SET must be enclosed in quotes, but the whole literal is itself a string, so you need to double the embedded quotes.  You could also 'cheat' and use double quotes and single quotes:
EXECUTE PROCEDURE test_hector('LIST{SET{"stspols","stsrepo"}}');
EXECUTE PROCEDURE test_hector("LIST{SET{'stspols','stsrepo'}}");

From the discussion below, and as described in the alternative answer, the problem now seems to be related to the nested collections.  A LIST{SET{"str1", "str2"}} is an ordered list (with one entry in it); that entry is itself a set of (distinct) strings, which has no particular order. You'd use a MULTISET if you needed to be able to repeat strings (but the order isn't important).  You use a LIST is order is important (and duplicates are allowed in a list).
It sounds as if you really only need to choose the argument type so that it is simpler.  You should be able to use any one collection type effectively; I'd probably nominate SET so that you don't have to deal with repeated strings in the list, but MULTISET or LIST are also valid options.  With a procedure renamed to test_3():
CREATE PROCEDURE test_3(c SET(CHAR(10) NOT NULL))
    RETURNING CHAR(10) AS r;
    DEFINE r CHAR(10);
    FOREACH SELECT * INTO r FROM TABLE(c)
        RETURN r WITH RESUME;
    END FOREACH;
END PROCEDURE;

I was able to execute both the statements following, with the results shown:
+ EXECUTE PROCEDURE test_3(SET{'stspols','stsrepo'});
stspols
stsrepo
+ EXECUTE PROCEDURE test_3('SET{''stspols'',''stsrepo''}');
stspols
stsrepo

This was using an ESQL/C interface.  You should be able to get the second to work with ODBC; the first may cause a -201 syntax error.
If you prefer LIST to SET, then change SET to LIST in the code above:
+ CREATE PROCEDURE test_3(c LIST(CHAR(10) NOT NULL))
    RETURNING CHAR(10) AS r;
    DEFINE r CHAR(10);
    FOREACH SELECT * INTO r FROM TABLE(c)
        RETURN r WITH RESUME;
    END FOREACH;
END PROCEDURE;
+ EXECUTE PROCEDURE test_3(LIST{'stspols','stsrepo'});
stspols
stsrepo
+ EXECUTE PROCEDURE test_3('LIST{''stspols'',''stsrepo''}');
stspols
stsrepo

Comment: I edited my question to answer yours. Thanks in advance for your help!
Comment: I suspect the first failure is due to the ODBC driver mis-parsing the SQL and trying to treat the `{` as start of comment.  The second failure looks like the syntax got through, but something went wrong processing it.  At this stage, I'm not sure whether that's an ODBC problem or a server problem.  I suspect I'd need to upgrade my surrogate for your stored procedure so it tries to access data from the list of sets of strings, and see what happens.  Did you try my super-simple procedure?  Did it throw errors?
Comment: written like this way `EXECUTE PROCEDURE test_hector(LIST{SET{'stspols','stsrepo'}});` throws  `[Informix][Informix ODBC Driver][Informix]A syntax error has occurred. `. Wriitten like this `EXECUTE PROCEDURE test_hector('LIST{SET{''stspols'',''stsrepo''}}');` throws  ` [Informix][Informix ODBC Driver][Informix]Not implemented yet. sqlerrm(=any, !=any, =all, or !=all for Collections) ` and this way 'EXECUTE PROCEDURE test_hector('LIST{SET{"stspols","stsrepo"}}');' throws `[Informix][Informix ODBC Driver][Informix]Not implemented yet. sqlerrm(=any, !=any, =all, or !=all for Collections) `   :(
Comment: +1 btw for the full explanation. Almost working, i think we are missing something
Comment: Yours works like a charm!, maybe the problem is in the `where columna in (SELECT * FROM TABLE(C))`, thanks again for your valuable help!
Comment: yup is that, I commented up that line, and it works. There is a problem with the `where columna in (SELECT * FROM TABLE(C))`
Comment: That's important information (that the super-simple SPL works OK); we're past the ODBC driver and into SPL issues (and stuff down in the server, generally).  I'm not going to be able to look into it further for a while; not until later this evening (where it is late morning now) at the earliest.
Comment: Ok, I will try it out in the meantime, I really appreciate your help!
Comment: I tried to this alone `SELECT * FROM TABLE(LIST{SET{'stspols','stsrepo'}})` and it returns `unnamed_col_1
(null)` :/
Comment: but this way it works, `SELECT * FROM TABLE(LIST{'stspols','stsrepo'})` `unnamed_col_1
stspols
stsrepo`, should I try another way to pass the multiple values in the parameter or declare them differently  or something?
Comment: Thanks @Jonathan Leffler for your help, Edit your question with my answer if you wish, or if it could be made with the ...LIST{SET with that answer, and I will mark yours with the reward of the bounty.
Comment: btw i dont know the difference between `List and List{SET`
Comment: thank you, both of them work excellent! Thanks for your support
Comment: @JonathanLeffler is there a way to pass a map to the stored proc or is it just list, set and multilist? I looked around but couldn't find an answer.
Comment: I'm not sure what you mean by MAP; it isn't a type I recognize.  You could create one — it could be a row type with two elements, the key and the mapped value.  And yes, you'd be able to pass such a row type (or a list, set or multiset of such a row type) to a procedure.
Answer: I tried it out in a different way and found a solution.
I modified the procedure to accept a parameter just as a List, not a List{SET...
CREATE PROCEDURE test_hector
(
    C LIST( CHAR(10) NOT NULL )
)
RETURNING CHAR(10) AS C, CHAR(10) AS CVE, CHAR(50) AS DESC;

DEFINE vColumna like tclaves.columna;
DEFINE vClave like tclaves.clave;
DEFINE vdescve like tclaves.descve;

FOREACH
select columna, clave, descve
INTO vColumna, vClave,vdescve
from tclaves
where columna in (SELECT * FROM TABLE(C))
RETURN vColumna, vClave,vdescve WITH RESUME;
END FOREACH
END PROCEDURE;

And executing it like this way.
EXECUTE PROCEDURE test_hector('LIST{''stspols'',''stsrepo''}');

Or this way
EXECUTE PROCEDURE test_hector3('LIST{"stspols","stsrepo"}');

And it worked like a charm.


Sums of digits of prime numbers: reference request

Question: I wonder if someone could point out to me a paper on the following problem, if it has been considered at all. If not, it would still be nice to have some good references to good papers related to the following problem:
Fix $q \geq 2$ and consider $q$-adic expansions of prime numbers $p$:
$$
p = \sum_{i=0}^\infty a_i q^i
$$
for integers $a_i$ with $0 \leq a_i \leq q-1$.
Problem: Given a finite set $I \subseteq \mathbb{N}_0$ and a positive integer $s$ (with both $s, I$ reasonable enough to avoid trivial non-existence cases), does there exist a prime number $p = (a_0, a_1, \ldots)_q$ such that
$$
\sum_{i \in I}a_i = s?
$$
Thanks very much.
Update: A.P. has given a nice answer to the problem. His proof follows partly from the fact that $I$ is fixed and so one can invoke Dirichlet's theorem after a trick. I think one could make this harder by making some restrictions, although I can imagine one walks into conjecture territory, such as the Mersenne prime conjecture.
New problem: Fix an integer $q \geq 2$ and a positive real number $x$. Let $\mathcal{P}_x$ be the set of prime numbers up to $x$. There exists an index $N := N_q(x)$ such that for all $j > N$, we have $a_j(p) = 0$ for all $p \in \mathcal{P}_x$, where $a_j(p)$ is the $j$-th digit of $p$ in its $q$-adic representation.
Assume $N$ is the smallest such index (for all $p \in \mathcal{P}_x$).
For what sets $I \subseteq [0,N] = \{0, 1, \ldots, N\}$ and positive integers $s$ can we prove there exists a prime $p \in \mathcal{P}_x$ such that
$$
\sum_{j \in I} a_j(p) = s?
$$
Again, if you know nice papers on the topic don't be shy to point them out! Thanks again.
Comment: @BillCook Actually, $0 \in I$ isn't necessary. In the question (even before the edit) $p$ is the number corresponding to the sequence of digits $\{a_n\}_{n \in \Bbb{N}_0}$, while $I$ is only used to index the last sum.
Comment: Are we looking for a pair $(p,q)$ in your conjecture? Since, clearly, the sum is bounded by $(q-1)|I|$ so if $q$ were fixed, there'd be easy counterexamples. (And presumably, $I$ is non-empty as well)
Comment: I presume one could fabricate counterexamples by picking $s, I$ large/small enough. $q = 2$ would suffice for me. Nevertheless, consider the cases when $s, I, q$ are reasonable enough to expect a non-trivial result. Oh and $q$ is fixed.
Comment: If you choose your index set $I$ such that $0 \not\in I$, then the number would necessarily be divisible by $q$. For example: $i=\{1,2,3\}$. Then $p=a_1q+a_2q^2=a_3q^3=q(a_1+a_2q+a_3q^2)$. So for any $s >1$, we get a non-trivial multiple of $q$ and $p$ cannot be prime.
Comment: Nope. i in I indexes the i-th digit. Without digit a_0 you have divisibility by q
Comment: @BillCook Please read the question more carefully: $p$ is given by $(a_0,a_1,\dotsc)_q$ and $I$ only appears in the last equation. That sum forces a constraint on the digits indexed by $I$, but it says nothing about the *other* digits. For example, $31$ is a solution to the problem with $q = 10$, $I = \{1\}$, and $s=3$.
Answer: Actually, we can solve a harder problem, namely:
Proposition. Fix an integer $q \geq 2$. Furthermore, let $I \subset \Bbb{N}_0$ be a finite set and consider integers $0 \leq \alpha_i < q$ for $i \in I$. If either $0 \notin I$ or $\gcd(\alpha_0,q)=1$, then there are infinitely many primes
$$
p = \sum_{k=0}^\infty a_k q^k
$$
such that $a_i = \alpha_i$ for every $i \in I$.
Proof: Let $m$ be the maximum of $I$, and for every $0 \leq j < m$ not in $I$ define $\alpha_j = \delta_{0j}$, where $\delta$ is the Kronecker delta. Then the hypothesis on $\alpha_0$ implies that
$$
\alpha := \sum_{i = 0}^m \alpha_i q^i
$$
is comprime with $q$, hence $\alpha$ is coprime with $d := q^{m+1}$, too. Then the proposition follows from Dirichlet's theorem on arithmetic progressions, which states that the sequence
$$
\{\alpha + n d\}_{n=0}^\infty
$$
contains infinitely many primes. $\square$
Corollary. In the same setting of the above proposition, there is an effectively computable constant $c > 0$ such that the smallest prime $p$ with $a_i = \alpha_i$ for every $i \in I$ satisfies
$$
p \leq c q^{5\max I}.
$$
Proof: This follows immediately from Xylouris's refinement of Linnik's theorem (cfr. Xylouris's PhD thesis, theorem 2.1, page 12). $\square$
Corollary. Fix an integer $q \geq 2$. Let $I \subset \Bbb{N}_0$ be a finite set and consider an integer $0 \leq s \leq r(q-1)$, where $r := \#I$. Furthermore, if $0 \in I$ assume $s > 0$. If either $I \neq \{0\}$ or $\gcd(s,q)=1$, then there are infinitely many primes
$$
p = \sum_{k=0}^\infty a_k q^k
$$
such that
$$
\sum_{i \in I} a_i = s.
$$
Proof: Since $s \leq r(q-1)$ we can find integers $0 \leq \alpha_i < q$ such that $s = \sum_{i \in I} \alpha_i$. Moreover, observe that whenever $0 \in I$ we can choose $\alpha_0$ such that $\gcd(\alpha_0,q) = 1$. Indeed, if $I = \{0\}$ this is by hypothesis, otherwise let
$$
\alpha_0 =
\begin{cases}
q-1 & \text{if } s > q\\
1 & \text{otherwise}.
\end{cases}
$$
Now apply the proposition. $\square$


Why does an open subset of reals with finite measure is bounded?

Question: I am trying to prove the following:
Let $A \subset \mathbb{ R}$ be open and have finite Lebesgue measure then it is bounded.
First, since $A$ is open in $\mathbb{R}$, it can be written as a countable union of disjoint open intervals. Let us write
$$ A = \cup_{i \geq 1} (a_i, b_i) $$
Where each $(a_i,b_i) $ is the said open interval. Clearly, none of these intervals can be infinite, otherwise it is contained in this union, hence $A$ and so $m(A)$ becomes infinite, which is not possible.
Now let us define $a:= \inf\{a_i : I \geq 1\}$ and $b := \sup\{b_i: i\geq 1\}$. We will be done if we have $ -\infty < a < b < \infty$. But I am not sure how to show that.
I will appreciate it if anyone has any suggestions on how to go on about showing this or have any other ways to show this result.
Thank you.
An idea: since none of these intervals can be unbounded on the left so maybe that's why $a > -\infty$?
Edit: I feel so foolish for not looking for an example beforehand. Thank you everyone who commented, this problem is resolved now.
Comment: I would advise against trying to prove that.
Comment: What about $(0,1)\cup(1,\frac32)\cup(2,\frac94)\cup...$ ?  The measure is $2$ and the set is unbounded.
Comment: try to construct a counterexample by taking balls centered around $1,2,3,\dots$ with rapidly decreasing radii
Comment: You mean there's a counter example?
Answer: HINT.- It is easy to build a counterexample.
►Take an strictly increasing non bounded sequence $\{a_n\}$ and a sequence convergent to zero $\{\delta_n\}$.
►With the open set $\cup(a_n,a_n+\delta_n)$ you are done.
Comment: It takes more than for the $\delta_n$ to converge to zero. For example, if you take $\delta_n=\frac{1}{n}$, and $a_n=2n$, then the set has measure $\sum\frac{1}{n}=\infty$.  And you did not preclude negative or $0$ values for $\delta_n$. You need a sequence $\{\delta_n\}$ of *positive* numbers such that $\sum\delta_n\lt\infty$.


Creating Geo points in Kibana

Question: how i can create geo points in Kibana after i already imported my data from SQL into Elastic, as i want to add new field called location for latitude and longitude so i can be able to use the maps visualizations or modify the index i have created. thank
sample of my index
<code> {
        "_index": "test1",
        "_type": "pre-test",
        "_id": "AVk1OzrXZxCtOaXERUPg",
        "_score": 1,
        "_source": {
          "tagno": "L116E11079                ",
          "status": "04 ",
          "cdesc": "STRINGING                                         ",
          "statusdt": "2016-08-27T00:00:00",
          "weightdone": 12.35,
          "cchiange": "0067+172.750   ",
          "kp_no": "067",
          "latitude": 29.55592659,
          "longitude": 47.69675638,
          "pIPELINE": " FUEL ",
          "pIPELINE_DESCRIPTION": "From A ",
          "pOINT_DESCRIPTION": "KILOMETER POINT (KP)",
          "cATEGORY": "MAIN "
        }
      }
</code>
Answer: You need to map the field as Geo point and than index the documents, look at geopoint documentation

Creating Geo points in Kibana


MkDocs: using a variable to construct external URLs

Question: Using AsciiDoc, I can define a base URL property and reference it to define links:
:external-url: https://www.example.com/docs

:Foo: {external-url}/foo[Foo,role=external-doc]
:Bar: {external-url}/bar[Bar,role=external-doc]
:Baz: {external-url}/baz[Baz,role=external-doc]

I can then use {Foo} syntax to inject links into my documentation pages.
What would be the best way to achieve this with MkDocs? I'd like to avoid duplicating the base URL if possible.
Comment: I have the same problem. were you able to find a good solution for this?
Comment: @AugustusCaesar unfortunately no. I ended up duplicating the base URL in  [my `mkdocs.yml`](https://github.com/instancio/instancio/blob/main/website/mkdocs.yml).
Answer: MkDocs is using Markdown, and therefore there are no available off-the-shelf variables you could use. So instead, you need to use something to preprocess your markdown files.
You should decide two things:

Which preprocessor to use
How to integrate into your processing.

With the first one, my answer is Jamal, available from https://github.com/verhas/jamal
I have created Jamal to solve issues like this and to include programmable semantic information into your documentation. You should take this recommendation with a pinch of salt; since Jamal is my love child, I created it.
The other question is how to integrate it into Mkdocs. Here I see three different possibilities:

Use the preprocessor manually to maintain .md.jam files and convert them to .md files before building your documentation site. It is the most straightforward approach because it only needs that you execute a command before starting your build. But, on the other hand, it is the easiest to forget to do that and end up having outdated markdown files.

You can mend this solution using ANT, make, or other build tools.

Create a MkDocs plugin that starts the conversion and converts all md.jam files to .md files. You need to write a short Python module that initiates Jamal as an external process. It needs some Python programming but has the advantage that you will not forget to execute the Jamal processing since all the builds will do that for you.

Both of these approaches have the advantage that you can get rid of the introduced Jamal processing. You have your .md files created in your source structure. If you decide, you can delete the Jamal files and go on editing the Markdown files directly, bearing all the consequences of maintaining redundant-information infested documentation sources.

Finally, you can develop a Python Markdown plugin to process the Jamal macros in the .md files. Since Jamal is written in Java, this plugin has to execute an external process. This is probably the most complex approach and, in my opinion, the least practical. In this case, your Markdown files contain the Jamal macros, and you do not have the converted, macro-free Markdown files in your source set. These come in handy many times. The plugin starts Jamal as a separate process for every Markdown file separately, while the earlier approaches can convert all the files in a single process.

What I recommend is that
have a look at the features of Jamal, if you like it, and understand if this is really what you need
start using it as a separate preprocessor
when you really want it, you may consider writing a MkDocs plugin to execute the conversions automatically.
Comment: Thanks for you answer, @Peter. I will check it out.
Answer: In essence, you wish to add a mechanism of wikilinks.
I created mkdocs-macros for that kind of applications. Just install it and add the following in your config files (mkdocs.yml):
plugins:
  - search
  - macros

Then add the hyperlink in the extra section of this file, e.g:
extra:
  external-url: https://www.example.com/docs

Then, your markdown page:
The following [page]({{ external-url}}/foo), as well as this [other page]({{ external-url}}/foo)...

The variable {{ external-url}} will be translated into its equivalent.
In general, you can use mkdocs-macros in that way for any type of recurring string that you wish to keep centralized.

For completeness, see also the answer on MKDOCS - How to enable hyperlinks based on keywords found in the content? where solutions with markdown extensions are presented.


Somas valores JS

Question: Duas coisas.
Uma preciso somar os 3 valores, mas está retornando NaN.
$('#valor').blur(function(){
   var valor = $("input[name=valor]").val();
   var descontos = $("input[name=descontos]").val();
   var juros = $("input[name=juros]").val();

   valor_cobrado = (parseFloat(valor) - parseFloat(descontos)) + parseFloat(juros);
   $("#valor_cobrado").val(parseFloat(valor_cobrado));

Nem sempre descontos ou juros estão preenchidos no form.
E outra pergunta é, como declaro declaro mais campos no blur?
Answer: Está retornando NaN porque se algum dos campos estiver vazio o parseFloat não consegue converter null em número, causando erro na soma dos valores, já que o JavaScript não irá conseguir somar um número com null.
Você pode colocar um operador || para que se um dos campos estiver vazio, o valor do campo assuma 0, evitando o NaN:

$('#valor').blur(function(){
   var valor = $("input[name=valor]").val() || 0;
   var descontos = $("input[name=descontos]").val() || 0;
   var juros = $("input[name=juros]").val() || 0;

   valor_cobrado = (parseFloat(valor) - parseFloat(descontos)) + parseFloat(juros);
   $("#valor_cobrado").val(parseFloat(valor_cobrado));
});

<input type="text" name="descontos" placeholder="descontos">

<input type="text" name="juros" placeholder="juros">

<input type="text" id="valor" name="valor" placeholder="valor">

<input type="text" id="valor_cobrado" disabled placeholder="valor cobrado">
Comment: Funcionou, mas como eu coloco mais de um campo chamando o blur?
Comment: De várias formas... coloca uma classe nos inputs e faz `$(".nome_da_classe").blur(...`

Somas valores JS


Problemas com url usando thymeleaf

Question: Tenho uma pagina que mostra todos os posts de um blog. Essa pagina possui um objeto postagem que por sua vez possui o atributo  que é uma lista de categorias.
Essa lista de categorias é mostrada na pagina na  forma  links para cada post inserido na pagina para o usuário final. O usuário final pode clicar em um link e então ele é direcionado para uma pagina que contem todos os posts relacioandos com aquele tema do link da categoria.
Quero usar o th:each  para montar os links.
Os links são montados, mas de maneira incorreta!!
Eis como ele fica:
http://localhost:8084/spring-thymeleaf/categoria/?jpa

supondo que o usuário clicou no link "jpa" gerado pelo codigo abaixo:

Quero colocar como valor o conteúdo de ${categoria.permalink} mas sem ter aquela interrogação famigerada!
Para chegar a esse meu codigo me basei em um exemplo do site proprio Thymeleaf:

          Onions
          2.41
         ...
            2 comment/s
            view

Que gera o seguinte url:
http://localhost:8084/gtvg/product/comments?prodId=9

Queria que fosse possível usar o seguinte código

Mas ele tem a seguinte saida,  quando eu clico no link "jpa":
http://localhost:8084/spring-thymeleaf-jsp/categoria/$%7Bcategoria.permalink%7D

Aqui esta o trecho do meu controller que trata a requisição:
@RequestMapping(value = "/categoria/{link}", method = RequestMethod.GET)
public ModelAndView postsByCategoria(@PathVariable("link") String link, ModelMap model) {

    List<Postagem> postagens = postagemService.findByCategoria(link);

    model.addAttribute("postagens", postagens);

    return new ModelAndView("posts.html", model);
}

O que devo fazer? Já procurei em varios lugares e nada!!
Comment: Tenta utilizar ``, tem mais na [documentação](https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#link-urls)
Comment: Aparentemente o `?` está vindo direto do valor de `${categoria.permalink}`. Como esse valor é gerado?
Comment: @AndersonCarlosWoss  Ate que enfim! Ufa! Muito obrigado!!Coloque como resposta compadre!! Ai  fica explicito para quem passar pelo mesmo probleminha!!
Answer: Por padrão, conforme a documentação, a ferramenta adiciona as variáveis à query string da URL. Se desejas incorporar o valor da mesma na URL, utilize a sintaxe {nomeDaVariavel}, conforme o terceiro exemplo da documentação supracitada.
Para o seu exemplo, ficaria:

Onde {link} é a incorporação da variável na URL.

Problemas com url usando thymeleaf


Sympa install on CentOS/Fedora

Question: Has anyone installed the Sympa mailing list software on Fedora or CentOS? I am not a huge fan of their instructions on sympa.org. I have installed the program and emails are working, but I can't seem to get the web site to work. Any help or links to a better install guide would be greatly appreciated.
Answer: On my debian site, I have to configure CGI (and fastCGI). Debian provide me a file /etc/apache2/conf.d/sympa with the redirection
ScriptAlias /wws /usr/lib/cgi-bin/sympa/wwsympa.fcgi

Then I can access to the webinterface by http://server/wws
I configure the virtualhost with
DirectoryIndex wws

And I can access directly to http://server/ and see the site.
Use FastCGI : it REALLY much faster than cgi !
Answer: I think You can follow this steps:
http://marksallee.wordpress.com/2010/01/21/sympa-listserv-install-how-to-for-centos/
Before starting those steps, please read following url
http://www.sympa.org/manual/installing-sympa
Best wishes

Sympa install on CentOS/Fedora


How to sync slideToggle() elements so they expand/collapse all together regardless of current state?

Question: I'm trying to show/hide sections using triggers based on classes. So it's easy to throw the trigger class on any element and it will slideToggle the next show/hide element class in the DOM.
The first part works fine. Now I'm adding a trigger to expand/collapse ALL elements. Trouble is, I can't figure out how to sync their states.
For example: I click on 3 of 8 elements so they slide open and become visible, the other 5 are still closed... Now when I click my expand/collapse all trigger, using slideToggle just switches their states so I end up with 3 closed and 5 open.
How do I get their states to sync regardless of what their current state is?
I've been trying to figure out the conditionals to check if the trigger has the opened or close class on it, then toggle the next element, but I've only made a mess so far.
Here's my code:
jQuery( document ).ready( function( $ ) {

    // The element to hide/reveal
    $( '.bodhi-hide-reveal' ).hide();

    // The trigger to hide/reveal
    $( '.bodhi-reveal-trigger' ).click( function( e ) {

        e.preventDefault();

        // Target only the next element to hide/reveal and toggle it
        $( this ).next( '.bodhi-hide-reveal' ).slideToggle();

        // Toggle the trigger class
        $( '.bodhi-reveal-trigger' ).toggleClass( 'opened closed' );

    });

    // Expand/collapse all button
    $( '.expand-collapse-all' ).click( function( e ) {

        e.preventDefault();

        // Find all hide/reveal elements and toggle them all together
        $( 'body' ).find( '.bodhi-hide-reveal' ).slideToggle();

    });

});

Answer: Just a class named "opened" is enough to detect if the next div is open or close. So I write an IF/ELSE block to decide whether to slideUp or SlideDown. Also you have to decide what would you do when some of divs are expanded? Do you want to collapse all or expand all? I prefer to collapse all first. So I search to find an opened one (using array length)  and if I find it, I collapse all divs, elsewhere I expand all:
Also there are some inefficient selectors like $( 'body' ).find(). I also replace those selectors with efficient ones:
jQuery( document ).ready( function( $ ) {

// The element to hide/reveal
$('.bodhi-hide-reveal').hide();
$('.bodhi-reveal-trigger').removeClass("opened");

// The trigger to hide/reveal
$('.bodhi-reveal-trigger').click( function( e ) {

    e.preventDefault();

    // Target only the next element to hide/reveal and toggle it
    $(this).next('.bodhi-hide-reveal').slideToggle();

    // Toggle the trigger class
    $(this).toggleClass('opened');

});

// Expand/collapse all button
$('.expand-collapse-all').click( function( e ) {

    e.preventDefault();

    //Check if there is at least one open div:

    if ($('.bodhi-reveal-trigger.opened').length){
        $('.bodhi-reveal-trigger').removeClass("opened")
        $('.bodhi-hide-reveal').stop().slideUp();
    }

    else {
        $('.bodhi-reveal-trigger').addClass("opened")
        $('.bodhi-hide-reveal').stop().slideDown();
    }

});

});

Comment: Thanks so much, perfect explanation :)
Comment: Hi Ali Sheikhpour, if I was to set a cookie to retain the states on page reload just in the session. Where abouts would I add that? Just on the slideToggle, slideUp & slideDown?
Comment: On all of them. I suggest to preserve the opened class of each `bodhi-reveal-trigger`using a number which shows the order of element in this class and the state of its `opened` class
Comment: Thanks Ali, that sounds like a good idea, but I don't understand how I would do it.
Comment: use jquery `index()` to find the index of element in selector. for every change call a function which runs something like this `$('.bodhi-reveal-trigger').each(function(){})` and inside this function set `index` and `state` of elements in cookies. Documentation of index: https://www.w3schools.com/jquery/misc_index.asp
Comment: Thanks so much! I'll have a look into using this. I really appreciate your help!


Create a matrix with headers and inserting values by calling the headers

Question: Is it in python possible to create a zero-matrix with headers and insert values by calling column-header and row-headers? For example:
# A B C
d 0 0 0
e 0 0 0
f 0 0 0

the I write for example matrix('A', 'd') = 1 and matrix('B', 'e') = 3 and get
# A B C
d 1 0 0
e 0 3 0
f 0 0 0

And when I am done I want to be able to save it to csv.
Hope someone can help me, because I have not idea if this is possible.
Answer: this would come close to your need:
rows = dict((x,y) for y,x in enumerate('ABC')) # rows' headers
cols = dict((x,y) for y,x in enumerate('def')) # cols' headers

len_cols = 3
len_rows = 3
matrix = [[0 for i in range(len_cols)] for j in range(len_rows)]

def update(row, col, val):
    matrix[rows[row]][cols[col]] = val

examples:
>>> cols = dict((x,y) for y,x in enumerate('de'))
>>> rows = dict((x,y) for y,x in enumerate('ABCD'))
>>> len_cols = 2
>>> len_rows = 4
>>> matrix = [[0 for i in range(len_cols)] for j in range(len_rows)]

>>> update('B','e',1)
>>> update('D','d',3)
>>> matrix
[[0, 0], [0, 1], [0, 0], [3, 0]]

Comment: Thank you Ayush Shanker. Very intresstig solution. I found numpy, it also should work with numpy or am I mistaken?
Comment: while it will work with numpy perfectly, numpy might have its own solution to this (which you would have to find yourself from the docs). Also you may mark this answer as accepted if it solved your problem.