How to get output in Real Number instead of complex number?

Question: I made the following code to solve any quadratic polynomial but I want the final output to be a Real Number (Either a whole number or a fraction) but I get Complex numbers like (3+0j). How to convert them?
Here is the Code:-
import cmath
a = float(raw_input("Enter the Coefficient of x^2 :- "))
b = float(raw_input("Enter the coefficient of x :- "))
c = float(raw_input("Enter the value of constant term or c :- "))

d = ((b*b) - (4*a*c))
if d < 0:
    print "There are no Real Roots of this equation"
else:
    x1 = (((-b) + cmath.sqrt(float(d))) // 2*a)
    x2 = (((-b) - cmath.sqrt(float(d))) // 2*a)

    if x1 == x2:
        print "x = ", x1
    else:
        print "x = ", x1, "or", x2

Desired Result:- I want the final result to be a Real Number(both Rational and irrational is allowed including fractions)(Like: 4, 4/3 or something like that).
Comment: https://docs.python.org/3.6/library/fractions.html
Comment: Do you want *rational* numbers or *real* numbers?
Comment: What do you want to see for the root of x^2 + 2 = 0?
Comment: I have added the desired Output in the question itself
Comment: @Lucifer Your question (and its title)  starts off stating that you want rational answers but then ends stating that you want real ones.
Comment: I edited my question but forgot to edit that part. Sorry
Answer: Simply only print the real part, besides you have to devide by 2a
x1 = (((-b) + cmath.sqrt(float(d))) / (2*a))
x2 = (((-b) - cmath.sqrt(float(d))) / (2*a))

if x1 == x2:
    print "x = ", x1.real
else:
    print "x = ", x1.real, "or", x2.real

Comment: He controls that only real solutions are accepted `if d < 0:`
Comment: Using python 2.7 I get the correct result using only one `/` for devision and brackets around (2a)
Comment: No. I tried the above input again and got the output 24 which is totally not correct.
Comment: Thank You. Your suggestion worked but I also used fraction lib which gave an exact fraction. `Fraction(Decimal(x1.real))`
Answer: You can use a class like Complex and support imaginary solutions as well.
 Code taken from http://hplgit.github.io/primer.html/doc/pub/class/._class-solarized005.html
class Complex(object):
    def __init__(self, real, imag=0.0):
        self.real = real
        self.imag = imag

    def __add__(self, other):
        return Complex(self.real + other.real,
                   self.imag + other.imag)

    def __sub__(self, other):
        return Complex(self.real - other.real,
                   self.imag - other.imag)

    def __mul__(self, other):
        return Complex(self.real*other.real - self.imag*other.imag,
                   self.imag*other.real + self.real*other.imag)

    def __div__(self, other):
        sr, si, or, oi = self.real, self.imag, \
                     other.real, other.imag # short forms
        r = float(or**2 + oi**2)
        return Complex((sr*or+si*oi)/r, (si*or-sr*oi)/r)

    def __abs__(self):
        return sqrt(self.real**2 + self.imag**2)

    def __neg__(self):   # defines -c (c is Complex)
        return Complex(-self.real, -self.imag)

    def __eq__(self, other):
        return self.real == other.real and self.imag == other.imag

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        return '(%g, %g)' % (self.real, self.imag)

    def __repr__(self):
        return 'Complex' + str(self)

    def __pow__(self, power):
        raise NotImplementedError\
          ('self**power is not yet impl. for Complex')

Comment: Sorry, but I recently started coding, hence I am not able to use the code you provided. Can you by any means tell me how to incorporate the above code in my code?


Tautology, Contradiction, or a satisfiable equation? Confusion about implication.

Question: I'm having some trouble with a homework question. I have the following
$ P \rightarrow \neg P$
This looks like a contradiction to me. This should never be true! Yet, if I transform it using $p \rightarrow q := \neg p \vee q$, I get $\neg P \vee \neg P$, which is $\neg P$, which is satisfiable!
$ P \rightarrow (\neg P \rightarrow P)$
Similarly, the same thing happens here. I look at this, and I see the part inside parentheses and say "so this is basically just $P \rightarrow (false)$- that's true half of the time"
But no, if I use that equation, I get $P \rightarrow (P \vee P) = P \rightarrow P$, which is a tautology.
Where am I going wrong?
Comment: You say it "should never be true". Have you actually drawn up a truth table to discover when it is true?
Comment: $p \rightarrow q$ 'says nothing' about $q$ when $p$ is false.
Answer: As Berci noted, implications in propositional logic are fraught with problems when interpreted in ordinary speech. Some people find it helpful to think of an implication $p\rightarrow q$ as a promise that whenever $p$ is true, $q$ will be guaranteed to be true. For instance, let $p$ = "It is sunny" and $q$ = "I'll ride my bike to work". When it's sunny, you're keeping your promise by riding your bike, so the implication will be true. On the other hand, if it's sunny and you drive to work, you've broken your promise and so the implication will be false. Notice, though, that if it's not sunny, you haven't broken your promise whether you ride your bike or not: in other words, if $p$ is false, then $p\rightarrow q$ will be true no matter what value $q$ has.
Now consider the implication $p\rightarrow\neg p$. It may seem to be contradictory ("If it's sunny, then it's not") at first glance, but it's not in the case where $p$ is false, since, recall, you're not breaking any promises. In other words, you've correctly observed that $p\rightarrow \neg p$ is false in case $p$ is true, but is true when $p$ is false, so actually isn't a contradiction.
Answer: Note that $P \rightarrow \lnot P$ is equivalent to $\lnot P \lor \lnot P$ which essentially is an assertion that $\lnot P$.
$\lnot P$ is true whenever $P$ is false. So the implication $P\rightarrow \lnot P$ is "satisfiable" whenever the truth value of $P$ is false.
Likewise, given $$P \rightarrow (P \rightarrow \lnot P),\tag{1}$$ then $(1)$ is true when $P$ is false; this is because, as we've seen, the conclusion of implication $(1)$ is equivalent to $\lnot P$. So again, we have $P \rightarrow \lnot P$, and thus $\lnot P$, true when $P$ is false.
Now we'll address the non-equivalent (to $(1)$) statement:
$$ P \rightarrow (\lnot P \rightarrow P)\tag{2}$$ $$\iff P \rightarrow (\lnot\lnot P \lor P)$$
$$\iff P \rightarrow (P \lor P)$$
$$\iff P \rightarrow P$$
$P \rightarrow P$ can be read as $(\lnot P \lor P)$ which, as you observed, is a tautology.
Note that this can readily be seen as a tautology without deducing ($P \lor \lnot P$) from $P \rightarrow P$ because...

$\ast$ An implication is false if and only if its premise is true and its conclusion is false.

So given the implication $P \rightarrow P$, either P is true or else P is false: i.e. either true $\rightarrow $ true, or else false $\rightarrow$ false. And so, knowing $(\ast)$ the implication $P \rightarrow P$ cannot ever be false: Whatever the truth-value of $P$, it will never be true that the premise P will be true, while the conclusion P is false. When the premise $P$ is true, then the conclusion, $P$, is true.
As others here have pointed out, material implication ($\rightarrow$), as used in logic, does not correlate well with our intuitive, informal (and sometimes formal) understanding(s) of implication.
John Corcoran wrote a great paper on this problem, surveying the various meanings of implication, both classifying those meanings/uses, and pointing out the differences between them in an effort to better capture what implication means in various contexts. (For anyone interested, I highly recommend that you read Corcoran's "Meanings of Implication," Dialogos 9 (1973) 59–76. Reprinted in R. Hughes, Ed., Philosophical companion to first order logic. Indianapolis: Hackett. 1993.) Here is a link: http://philpapers.org/rec/CORMOI and http://philpapers.org/archive/CORMOI.pdf
Comment: @Brian Thanks for your edit...I was editing while you edited! It seems that I sometimes need to see my post before recognizing a missed $...especially when writing comments!
Comment: You're welcome. I actually hesitated, since you had just done an edit and were likely to catch the problem yourself, but the temptation to make such an easy quick fix was too great. :-) I often don't catch little things like that until I see it, especially in comments.
Comment: See also [this post](http://math.stackexchange.com/questions/38713/help-to-understand-material-implication), and many others like it, which all address the meaning of material implication and how to better understand it.
Comment: @amWhy In fact, the weird [suggested edit](http://math.stackexchange.com/review/suggested-edits/656366) was [pointed out in chat](http://chat.stackexchange.com/transcript/message/31033762#31033762). I guess free link is better than academia.edu link.
Answer: Observe that $ P \rightarrow \neg P$ is not a contradiction. When $P$ is false, it is true.
Answer: Using the equivalence of $p\rightarrow q$ and $\neg p\vee q$ is the right idea here. Saying $P\rightarrow\neg P$, is then precisely the statement $\neg P$, as you observed. On the other hand, $\neg P\rightarrow P$ becomes $P$ by this reasoning, so $P\rightarrow(\neg P\rightarrow P)$ becomes $P\rightarrow P$ becomes $\neg P\vee P$, a tautology
Answer: As you just learned, the logical implication $P\to Q$ is not the best for expressing implication in the most intuitive sense.
There are a lot approach to help this, for example in intuitionistic logic, modal logic $\Box(P\to Q)$, etc.
Comment: Note that in Heyting Arithmetic, $0 = 1 \to \neg 0 = 1$. So the fact that you can have truths of the form $\varphi \to \neg\varphi$ doesn't distinguish the classical truth-functional from the intuitionist conditional.
Answer: The schema in question is the following.
If P then –P.
To see that this is not contradictory notice that it is implied by its own consequent –P, which of course is not contradictory. No non-contradictory sentence implies a contradictory sentence.
It is useful to be aware of the fact that every conditional follows from its own consequent.
Moreover it implies its own consequent: assume the conditional, to see that the consequent follows assume its negation, which implies the antecedent [double negation elimination], and using that with the original conditional gives the consequent[modus ponens], contradiction. QED
Comment: Welcome to Math.SE. This is an old question which already has a well-accepted answer. You have contributed nothing new. Please refrain from answering old answered questions if you are not contributing anything new


Soccer Standings

Question: consider a league of 10 teams
Each play each other two time
No Home/Away
3 team, A, B & C have same number of points
A vs B  2 - 0 2 - 1
B vs C 2- 1  2 - 0
C vs A  6 - 2  1 -2
Rules apply
Rule 1
if two teams or more, end the championship with the same number of points the following shall
apply in the order of priority as given below:
a) Higher number of points.
b. Direct confrontation between two tying teams
C.superior g.differerence between the team in question.
Rule 2
if two teams or more, end the championship with the same number of points the following shall
apply in the order of priority as given below:
a) Higher number of points obtained in matches among the team in questions.
b. Same as rule 1b
C. Same as rule 1c
what is the difference between these two rules and the standing in each case???
Answer: Just like already mentioned in your other question there is no difference.
Let's use two teams first...
Now for example A and B are tied for points and played 1-1 and 0-3:

direct confrontation:

A has a draw and loss = 1 point and 1-4 goals
B has a draw and win = 4 points and 4-1 goals
B wins

Points to win:

A still has 1 point and 1-4 goals
B still has 4 points and 4-1 goals
B wins

With 3 teams:
In both cases the winner of the tie will be the one with the most points.
If you want to compare more than two team's results for the direct confrontation rule it is necessary to add up all results between the tied teams. It does not work to just compare A with B and B with C and A with C. Yes, they would have won one duel each, but the results count, not the comparisons.
You try to do this:

A wins against B -> 1 for A
B wins against C -> 1 for B
C wins against A -> 1 for C

While that is technically true you would ignore the actual results, which is all the league table is about. Even in direct confrontation only the results matter.
So you have to accumulate all results:
A played against B and C -> take all matches against B and C into account. A won 3 out of 4 matches against B and C. That is what matters.
Do the same for the other teams and you can create a table from the results:

A won both matches against B and one against C = 3 wins = 9 points
B won both matches against C = 2 wins = 6 points
C won only one match against A = 1 win = 3 points

Soccer Standings


No macro for Power Query in Excel 2013

Question: I installed "Power Query" in Excel 2013. Works fine. However it doesn't support VBA. No code is generated when I try to make a macro with the macro recorder. What I am doing wrong?
Comment: The fact that the macro recorder doesn't create any code doesn't mean that it is not possible.
Comment: In excel 2016 creation is fine.
Comment: And have you tried to run the code that the recorder created on a computer with 2016 on a computer that runs 2013?
Comment: It doesn't work either
Answer:
What I am doing wrong?

Using Excel 2013 in 2022. You should upgrade already.
It will work if you upgrade to 2016.
https://learn.microsoft.com/en-us/office/vba/api/excel.workbookquery

WorkbookQuery object (Excel)
An object that represents a query that was created by Power Query. Introduced in Office 2016.
Comment: You can install "power query" in excel 2013. However vba2013 is not quite compatible.
Comment: That is exactly it.

No macro for Power Query in Excel 2013


Did I make a mistake or is the question wrong? How do I calculate the magnitude $r'(t)$?

Question:
I took the derivative of each term, then added their squares together and took the square root. I get $$\sqrt{t^2 + 6t + 10}$$ which is very close to choice A but it's off by 1 underneath the square root. If it was $\sqrt{t^2 + 6t + 9}$ then it would be the same as $|t+3|$, but it's not.
Did I make a mistake, or is the question wrong?
Comment: Wolfram confirms that what you did is fine.
Comment: I agree with your result.
Comment: OK. thank you - then it means the question is wrong
Answer: You are correct.
Since $$r'(t)=<\cos (t)-t\sin(t), \sin(t)+t\cos(t),(6t+9)^{\frac{1}{2}}>$$
We have that $$|r'(t)|=\sqrt{(\cos (t)-t\sin(t))^2+(\sin(t)+t\cos(t))^2+6t+9}$$
$$=\sqrt{(\cos^2(t)+\sin^2(t))(t^2+1)+6t+9}$$
$$=\sqrt{t^2+6t+10}$$
In part $D)$, they've added the $2t\cos(t)\sin(t)$ terms instead of subtracting.


Será que qualquer projeto pode ser adequado aos princípios pregados pelo SOLID? Quais os passos para isso?

Question: Estou tentando adequar um dos meus projetos aos padrões do SOLID, porém, não estou conseguindo sair do marco zero. O projeto em questão pode ser encontrado em: https://github.com/crphp/webservice
Após algumas tentativas surgiram as seguintes dúvidas:

Todo projeto é passivo de adequação a todos os 5 princípios preconizados pelos padrões do SOLID?
Estes princípios possuem alguma dependência hierárquica de implementação?
Acredito que o princípio SRP possa ser considerado um ponto de partida, mas e depois, qual seria o próximo principio a ser atendido, existe uma ordem lógica (não obrigatória em si, mas sim lógica)?
Em uma de minhas investidas, tentei atender ao princípio ISP, entretanto, não consegui determinar interfaces + assinatura comum. Até cheguei a uma interface comum, entretanto a assinatura dessa interface divergia entre as classes do projeto (Crphp\src\Soap.php e Crphp\src\ClienteGenerico.php). O que fazer nestes casos? Será que um projeto (módulo) tão pequeno requer a criação de mais de uma interface para tentar transpor essa barreira?

Os 5 princípio mencionados acima são:

SRP - Single responsibility principle
OCP - Open/closed principle
LSP - Liskov substitution principle
ISP - Interface segregation principle
DIP - Dependency inversion principle

Fonte: https://medium.com/thiago-aragao/solid-princ%C3%ADpios-da-programação-orientada-a-objetos-ba7e31d8fb25
Comment: E por que quer "adequear"  seus projetos ao SOLID?
Comment: Relacionado: [O que é SRP?](https://pt.stackoverflow.com/questions/100516/o-que-%C3%A9-e-como-se-usa-o-srp)
Comment: Relacionado: [Quais as diferenças entre Injeção de Dependência e Inversão de Controle?](https://pt.stackoverflow.com/questions/21319)
Comment: Relacionado: [Quais são os tipos de IoC?](https://pt.stackoverflow.com/questions/73160/quais-s%C3%A3o-os-tipos-de-ioc)
Comment: Relacionado: [O que é Dependency Injection?](https://pt.stackoverflow.com/questions/20770/o-que-%C3%A9-inje%C3%A7%C3%A3o-de-depend%C3%AAncia)
Comment: Relacionado: [O que é DIP?](https://pt.stackoverflow.com/questions/101552/o-que-%C3%A9-princ%C3%ADpio-da-invers%C3%A3o-de-depend%C3%AAncia-dip)
Comment: Tem material aí pra estudar um dia inteiro, kkkkkk
Answer: Não existe um sequencia para "adequar" um projeto ao SOLID!
O acrônimo diz repeito a princípios de desenvolvimento que devem, sempre que possível, ser seguidos para evitar problemas no software com o passar do tempo, principalmente se você trabalhar em equipe.
Haverá momentos em que será necessário não seguir algum princípio. Desde que essa decisão seja tomada com consciência do que se está fazendo, não há problema algum. O importante é saber o porquê do SOLID.
O SOLID existe para ajudar os desenvolvedores a corrigir uma série de problemas que podem acontecer dentro da Orientação a Objetos. No paper do Robert Martin, responsável pela difusão dos princípios (Design Principles and Design Patterns), é falado muito sobre mudanças e refatoração, uma característica importantíssima para qualquer software passível de evolução.
Sistemas muito rígidos (resistentes à mudanças) dão muito trabalho na hora de evoluir. O contrário também é preocupante, em sistemas muito frágeis a simples alteração de uma parte pode quebrar outras dez em todo o sistema.
Os princípios SOLID objetivam tornar o software mais manutenível e fácil de entender. Em outras palavras, o SOLID tornará o software:

Mais organizado;
Aberto para receber melhorias;
Evolutivo: ao ser atualizado não terá efeitos colaterais indesejados;
Fácil de ser testado;
Menos propenso a repetição de código;
Fácil de ter seus módulos reaproveitados.

O contrário também deve ser considerado, ou seja, sistemas onde os princípios SOLID não são observados tendem a:

Possuir código sem padrão, desorganizado e macarrônico;
Possuir classes inchadas, com explosão de métodos e difíceis de entender;
Ser muito rígidos em algumas partes, dificultando as mudanças;
Ser muito frágeis, quebrando outras partes do sistema com facilidade;
Ter muito código repetido ao longo do sistema;
Ser muito difíceis de testar.

O assunto é vasto e muito interessante. Para mais informações, sugiro que leia Os princípios SOLID.


Solving Right Triangle Given Two Sides

Question: I have a right triangle whose base has length 40 cm and whose hypotenuse has length 43 cm.
How can I determine the height and the measures of the remaining two angles?
Answer: The lengths of the sides of a right triangle are related by the Pythagorean Theorem, which states $a^2 + b^2 = c^2$, where $a$ and $b$ are the lengths the two legs and $c$ is the length of the hypotenuse. Using the information you have, you want to solve
$$
40^2 + b^2 = 43^2
$$
to get $b = \sqrt{249} \approx 15.78$.
Once you have the lengths of all three sides, you can use the Law of Cosines to figure out the missing angles, which states
$$
x^2 = y^2 + z^2 - 2yz\cos \alpha,
$$
where $x,y,z$ are the lengths of the legs of the triangle and $\alpha$ is the angle opposite $x$. You'll need to plug in all the side lengths (making sure that $x$ is the length of the side opposite the angle you want to find) and solve for $\alpha$ (using $\arccos$ at the final step).
EDIT: As pointed out in Marty's answer, the Law of Cosines is not needed for a right triangle. Let's call the angle between the base and the hypotenuse $\alpha$. We can use the simpler relationship $\cos \alpha = \frac{40}{43}$, which rearranges to $\alpha = \arccos \frac{40}{43} \approx 21.53^\circ$. Since a triangle has $180^\circ$ in total, the remaining angle must have approximate measure $180^\circ - 90^\circ - 21.53^\circ = 68.47^\circ$.
Comment: Ok thanks the height is now 15.779.... lets say 15.78.
Comment: @david One of your equations will be $15.78^2 = 40^2 + 43^2 - 2 \cdot 40 \cdot 43 \cos \alpha$ and one will be $40^2 = 15.78^2 + 43^2 - 2 \cdot 15.78 \cdot 43 \cos \beta$, where $\alpha$ is the angle opposite the side of length $15.78$ and $\beta$ is the angle opposite the side of length $40$.
Comment: @david The typical way to state the Law of Cosines uses $a,b,c$. I switched to $x,y,z$ because I didn't want to imply that the $c$ in Law of Cosines had to represent the hypotenuse.
Comment: @mohr Dont you think the sine rule would be better in this case?
Comment: @Sawarnik Simple trigonometry would be even better. See my edit.
Comment: @mohr Oh, yes! As simple as it can be! Although sine rules directly and quite simply leads to the same thing.
Answer: Once you have the three sides
(a, b, and hypotenuse c),
the angle opposite side a
has sine of a/c and cosine b/c and the angle opposite side b
has sine of b/c and cosine of a/c.
Use of the cosine formula for a right triangle
seems like overkill.
Comment: I'm not entirely sure why I went to Law of Cosines first. Your approach is certainly much cleaner.

Solving Right Triangle Given Two Sides


Torch squeeze and the batch dimension

Question: does anyone here know if the torch.squeeze function respects the batch (e.g. first) dimension? From some inline code it seems it does not.. but maybe someone else knows the inner workings better than I do.
Btw, the underlying problem is that I have tensor of shape (n_batch, channel, x, y, 1). I want to remove the last dimension with a simple function, so that I end up with a shape of (n_batch, channel, x, y).
A reshape is of course possible, or even selecting the last axis. But I want to embed this functionality in a layer so that I can easily add it to a ModuleList or Sequence object.
EDIT: just found out that for Tensorflow (2.5.0) the function tf.linalg.diag DOES respect batch dimension. Just a FYI that it might differ per function you are using
Answer: No! squeeze doesn't respect the batch dimension. It's a potential source of error if you use squeeze when the batch dimension may be 1. Rule of thumb is that only classes and functions in torch.nn respect batch dimensions by default.
This has caused me headaches in the past. I recommend using reshape or only using squeeze with the optional input dimension argument. In your case you could use .squeeze(4) to only remove the last dimension. That way nothing unexpected happens. Squeeze without the input dimension has led me to unexpected results, specifically when

the input shape to the model may vary
batch size may vary
nn.DataParallel is being used (in which case batch size for a particular instance may be reduced to 1)
Answer: Accepted answer is sufficient for the problem - to squeeze last dimension. However, I had tensor of dimension (batch, 1280, 1, 1) and wanted (batch, 1280). Squeeze function didn't allow for that - squeeze(tensor, 1).shape -> (batch, 1280, 1, 1) and squeeze(tensor, 2).shape -> (batch, 1280, 1). I could have used squeeze two times, but you know, aesthetics :).
What helped me was torch.flatten(tensor, start_dim = 1) -> (batch, 1280). Trivial, but I forgot about it. Warning though, this function my create a copy instead view, so be careful.
https://pytorch.org/docs/stable/generated/torch.flatten.html

Torch squeeze and the batch dimension


How can I prevent compound component from re-rendering?

Question: I am using react context, and all it contains at the moment are 3 items: contacts and editingContact, and editContact:
interface ContactsContextProps {
  contacts: Contact[];
  editingContact: Contact;
  editContact: (contact: Contact) => () => void // being lazy and this is from an onClick
}

const ContactsContext = React.createContext<Partial<ContactsContextProps>>({
  editContact: (contact: Contact) => () => {}
})

const ContactsProvider: React.FunctionComponent = props => {
  const [contacts, setContacts] = useState<Contact[]>();
  const [editingContact, setEditingContact] = useState<Contact>();

  React.useEffect(() => {
   // fetch contacts, and setContacts(contacts)
  }, [])

  const editContact = React.useCallback((contact: Contact) => {
    return function() {
      setEditingContact(contact);
    }
  })

  return (
    <ContactsContext.Provider
      value={{
        editingContact,
        editContact,
        contacts
      }}
    >
      {props.children}
    </ContactsContext.Provider>
  )
}

Here's how it is being used:
const ContactsList: React.FunctionComponent<{
  contacts: Contact[];
}> = React.memo(props => {
  return (
    <>
      {props.contacts.map(contact => (
        <Card key={contact.id} contact={contact} />
      ))}
    </>
  );
});

const Wrapper: React.FunctionComponent = () => {
  const contactsCtx = React.useContext(ContactsContext);

  return (
    <>
      <Box className={styles.main}>

        {contactsCtx.contacts && <ContactsList contacts={contactsCtx.contacts} />}
      </Box>
      {contactsCtx.editingContact && <EditContactModal />}
    </>
  );
};

The <Card /> only has an edit button right now, which calls contactsContext.editContact().  However, each time this is called, all the Cards re-render.  I placed a console.log('card') in each Card, and it logs card 10 times (I have 10 contacts right now).
What am I doing wrong?
Comment: You can't avoid that, that's the way react works, every change will render everything again, but relax it will render only in memory and the changes won't reflect on your DOM tree. Search about "react virtual dom"
Comment: Thanks.  what happens if I have 5000 contacts?  I don't want the contacts to re-render just because a modal has opened up.  Is there a way to do that?
Comment: It will render in memory first on "virtual dom" and after that It will do a diff operation with the real dom and only change what it's need :D
Answer: There has been a discussion in a React Github issue, basically there is 3 possible solutions for this:

Option 1 (Preferred): Split contexts that don't change together
Option 2: Split your component in two, put memo in between
Option 3: One component with useMemo inside

You should check the link for examples about it.


Migrations Laravel 5.8

Question: Está acontecendo um erro quando vou fazer a migration um para muitos.
O objetivo é fazer com que um cliente vai ter muitos telefones e um telefone vai pertencer apenas a um cliente.
No código abaixo podem observar que o cliente_id referencia o campo id da tabela clientes.
    Schema::create('telefones', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('cliente_id')->unsigned();
        $table->timestamps();
    });

    Schema::create('telefones', function (Blueprint $table) {
        $table->foreign('cliente_id')->references('id')->on('clientes');
    });
}

Mas quando vou executar o comando php artisan migrate ele cria a tabela só que não tem o foreign key e dá o seguinte erro:
PS C:\projetos\appteste> php artisan migrate
Migrating: 2019_07_28_221050_cria__tabela__telefones

   Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') default character set utf8mb4 collate 'utf8mb4_unicode_ci'' at line 1 (SQL: create table `telefones` () default character set utf8mb4 collate 'utf8mb4_unicode_ci')

  at C:\projetos\appteste\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') default character
set utf8mb4 collate 'utf8mb4_unicode_ci'' at line 1")
      C:\projetos\appteste\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOConnection.php:63

  2   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') default character set utf8mb4 collate 'utf8mb4_unicode_ci'' at line 1")
      C:\projetos\appteste\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOConnection.php:61

Answer: Não pode utilizar o Schema::create duas vezes para mesma tabela. Para adicionar a chave estrangeira você pode utilizar o mesmo escopo do primeiro create ou utilizar o Schema::table para fazer as alterações.
Schema::create('telefones', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('cliente_id');
    $table->timestamps();
});

Schema::table('telefones', function (Blueprint $table) {
    $table->foreign('cliente_id')->references('id')->on('clientes');
});

Você pode trocar os dois métodos integer e unsigned - que funcionam perfeitamente - para unsignedInteger que tem o mesmo resultado.
Comment: Erra isso mesmo. Muito obrigado!
Comment: Não precisa fazer 2 schema para relaciona poderia fazer o foreign abaixo do unsigned
Comment: @LucasAntonio, exatamente isso que descrevi no início da resposta. Prefiro sugerir a criação dos relacionamentos desta forma - separado - pois assim fica mais fácil a manutenção.
Comment: Não acho, eu faço junto pra agilizar bateu o olho já sabe onde ta o relacionamento assim, dessa forma ai tenho que ler um schema e depois ler outro, processos atoas e ficará mais lento a migration.

Migrations Laravel 5.8


java attempting to assign weaker access privilege error

Question: [javac] U:\dms-webui-testing\test-java\dmswebui\CR\TestLogin.java:16: until() in  cannot override until() in com.thoughtworks.selenium.Wait; attempting to assign weaker access privileges; was public

I am getting above error for a fairly simple code:
package dmswebui.CR;

import org.infineta.webui.selenium4j.MainTestCase;

public class TestLogin extends MainTestCase {

  @Override
  public void setUp() throws Exception {
    super.setUp();
    startSeleniumSession("ChromeDriver", "somesite");
  }

  public void testMethod() throws Exception {

        new Wait("") {boolean until() {return false;}};session().open("/");
        new Wait("") {boolean until() {return false;}};session().click("id=btnLogin-button");       session().waitForPageToLoad("30000");
        for (int second = 0;; second++) {
            if (second >= 60) fail("timeout 'waitForTextPresent:Logoff' ");
            try { if (session().isTextPresent("Logoff")) break; } catch (Exception e) {}
            Thread.sleep(1000);
        }
        new Wait("") {boolean until() {return false;}};session().click("id=btnUserLogout-button");
        new Wait("") {boolean until() {return false;}};session().click("id=yui-gen0-button");       session().waitForPageToLoad("30000");
  }
  public void tearDown() throws Exception {
    super.tearDown();
    closeSeleniumSession();
  }

}

here is how I use Wait class. Please help me to understand this error.
Comment: Looks like they provide a wrong example in their own javadoc ;)
Answer: The lines with the problem are the two below
new Wait("") {boolean until() {return false;}};session().open("/");
new Wait("") {boolean until() {return false;}};session().click("id=btnLogin-button");

You try to override the until method which has public access in the com.thoughtworks.selenium.Wait class by a until method which is only package visible.
You cannot override a method and reduce visibility. You can only increase the visibility (e.g. overriding a protected method and making it public)
So the fix would be to add the public keyword to these methods
new Wait("") {public boolean until() {return false;}};session().open("/");
new Wait("") {public boolean until() {return false;}};session().click("id=btnLogin-button");

Comment: @Richard no that is not correct. Protected methods are visible for all subclasses, also subclasses outside the package. So making it package visible would increase visibility for some cases (another class in the same package), but reduce visibility as well in other cases (subclass in another package).
Comment: one second early than Keppil. Thanks both of you. :)
Comment: Yes, you mean I can only increase the visibility. overriding a protected method and making it public, but not package. I think package modifier can increase the visibility of protected one, am I right for this understanding?
Comment: Easily said, javac won't compile it, so it is not totally an expansion of visibility.


500 internal server error in Laravel 4

Question: I am trying to migrate my laravel web app to hosting server, uploaded contents and changed the database configuration.
Then I pointed to my web browser like : www.mywebsite.com it will shows 500 internal server error
Is there any problem in my htaccess file. ?
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
   Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

or I am working with BITBUCKET GIT.is there any problem with GIT Usage. ?
Thanks & regards
Comment: did you change permissions on the `storage` folder?
Comment: Try after changing RewriteRule ^ index.php [L] to RewriteRule ^ /index.php [L]
Comment: no I dont give any permission to storage.
Comment: you have to add /public path in your url or else write code in htacess to remove public path from site
Comment: I am removed public from URL In starting of development. also make the changing of htaccess and files.
Comment: Ask your provider and check Apache error.log to see why 500 is showing up
Comment: Is there any problem with GIT ?
Answer: Posting my own answer. Make sure your folders have 755 permission. I cleared this issue with permission. This is first thing do any others. You can get successful output.
No Issues with .htaccess and GIT.

500 internal server error in Laravel 4


Cannot connect via remote JMX

Question: I tried to enable JMX remoting on a Java app running on a server by adding the JVM args -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9001 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=xxx.xxx.xxx.xxx, but I was unable to connect to the application. Not knowing if the application was messing it up somehow, I wrote a simple test app:
public class Main {
    public static void main(String[] args) {
        while (true) {
            try {
                System.out.println("Sleeping for 5 seconds...");
                Thread.sleep(5000);
            }
           catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

However, I could not connect to this application, either. iptables shows an open port on 9001, and netstat confirms that a connection was established, but Jconsole (and a simple Groovy script) fails due to timeout.
Because my troubleshooting has failed thus far, I've been looking into alternative ways of getting Jconsole to connect. Solutions include installing a new webserver and routing JMX through that, but that is probably not feasible for me. There is a webserver on the box but it is Hiawatha and I can't change that or install another one. What have I missed?
Comment: What is `netstat -tln` telling you, is the port open on the right interface?
Answer: Try these steps to troubleshoot and report back:

Can you use telnet xxx.xxx.xxx.xxx 9001 from where you run the jconsole. You should see:
Connected to xxx.xxx.xxx.xxx
Escape character is '^]'.

If you do see that then that means you have a TCP connection so firewalls are not the problem.

Run the following command on the server and post the output:
$ netstat -an | grep LISTEN | grep 9001
tcp6       0      0 :::9001                 :::*                    LISTEN

Your class and your command line:
-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9001 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false Main

work ok for me, I can connect to jconsole.

Can you check what version of Java the host you want to monitor is running? java -version

Cannot connect via remote JMX


returning multiple values in python

Question: I am trying to analyze and understand a python program the implements a simple map-reduce idea.  I have some difficulty in understanding some code.
Person = namedtuple('Person', ['name', 'gender', 'age', 'height'])

persons = [
    Person('mary', 'fem', 21, 60.2),
    Person('suzy', 'fem', 32, 70.1),
    Person('jane', 'fem', 27, 58.1),
    Person('jill', 'fem', 24, 69.1),
    Person('bess', 'fem', 43, 66.6),
    Person('john', 'mal', 25, 70.8),
    Person('jack', 'mal', 40, 59.1),
    Person('mike', 'mal', 42, 60.3),
    Person('zack', 'mal', 45, 63.7),
    Person('alma', 'fem', 34, 67.0),
    Person('bill', 'mal', 20, 62.1),
]

def height_by_gender_and_agegroup(p):
    key = p.gender, p.age //10
    val = p.height
    return key, val

The function height_by_gender_and_agegroup(p) seems to return two values for each p.  It seems to return
<key,val> where key is p.gender and val is p.height
<key,val> where key is p.age and val is p.height

I have been programming in C and C++ but am quite new to python.  My question is how does returning multiples  pairs by value work in Python.  i.e assuming that that is what this code is doing.  If yes how do I process the return values?
the answers below seem to convey the fact that returning a key-value pair in python is similar to returning a struct with two members.I understand that part.
 key = p.gender, p.age //10

My question is on the above line.Key seems to take two values p.gender and p.age.If that is the case there need to be two sets of <key,value> returned for every value of P.
How does this work?
Comment: I'd suggest you start by reading [the relevant bit of the python tutorial](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences).
Answer: What it is returning is a tuple of two items. (It is basically equivalent to returning a struct with two fields in C). You can unpack the returned tuple like this:
key, val = height_by_gender_and_agegroup(person)

It might help to think of it in this way:
def height_by_gender_and_agegroup(p):
    key = p.gender, p.age //10
    val = p.height
    return (key, val)  # note the optional parentheses to denote a tuple

ret = height_by_gender_and_agegroup(person)
key = ret[0]
val = ret[1]  # "key, val =" is just a shortcut for this

Since the key in your case contains two values, you can unpack it further:
(gender, age), val = height_by_gender_and_agegroup(person)

Or if you prefer:
key, val = height_by_gender_and_agegroup(person)
gender, age = key

Answer: The function is actually returning a tuple.
>>> def f(): return 1, 2
...
>>> type(f())
<type 'tuple'>

Like any tuple, you can access its values by subscript or by assigning the members in order:
>>> first, second = f()
>>> second
2

Answer: You can say:
 k,v = height_by_gender_and_agegroup(p)

returning multiple values in python


Tuning Mesh drumheads

Question: I fitted my drumset with Remo Silent Stroke heads for home practice convenience. However I cannot seem to be able to 'tune' the heads appropriately.
I can't get enough sound out of them when tuning them by feel -- like when tunning 'regular" heads -- to be able to make up if they are tune right. And if they are  very, very tight, the volume gets just a tiny louder and they become very bouncy and
I try using tune bot, but I cannot register any frequencies.
Does any one has advice or tuning tricks?
Answer: They are called "silent" for a reason! You should not expect to hear much more than the sticking when using these heads.
Tuning, in my experience, will only serve two purposes: adjusting the bounce (feel/responsiveness), and helping triggers accurately register.
It has been suggested that the best way to affect the pitch (faint though be) is to adjust the resonant head.
Comment: +1 I tuned my mesh heads entirely for feel. You could add that to change the tone you want to tune the resonator head.
Answer: I found that to get "more" sound out of the mesh head, is to "trap" the sound by covering areas of the head with painters tape, and you can control the level of volume and tone: The more of the head that is covered the more volume and tone the emit.
Comment: I think what you mean by "trap" the sound is, you give the head some way to actually move a bit of air and thus emit acoustic energy. Makes sense physically. (Though I find it a bit strange to use mesh heads designed to be silent, and then deliberately hack them to be loud...)
Comment: The reason why I wanted to "add" some volume to the silent heads is so that volume and tones are balanced out when playing along with low volume cymbals. It might not bother anyone else, but it bother me that the low volume cymbals are louder than silent stroke heads. This way i feel the volumen and tone of both drums and cymbals is equal.

Tuning Mesh drumheads


Spring on Android without Maven

Question: I can use a Spring REST client on Android without using Maven.
Can someone tell me or point to a reference.
Thanks.
Answer: Download the distribution, which includes the jars.
Comment: Link is now invalid. Try this link instead: http://maven.springframework.org/milestone/org/springframework/android/spring-android-rest-template/
Comment: @RonE There is no version 1.0.1.RELEASE there. Is it up to date?
Answer: Download the below jar files from here and here then add them into libs folder.

spring-android-core-1.0.0.RELEASE.jar
spring-android-rest-template-1.0.0.RELEASE.jar

If you want to use MappingJacksonHttpMessageConverter message converter in your code in order to read and write JSON using Jackson JSON Processor's ObjectMapper, add it's library.
Comment: @Piotr if you mean jar file you can download it [here](http://mvnrepository.com/artifact/org.springframework.android/spring-android-auth/1.0.1.RELEASE)
Comment: @user1162647 I've changed the link but i dont now how should you download those file :(
Comment: what about spring-android-auth?

Spring on Android without Maven


Misnamed MS SQL server MSBD and Model DB log file names during move

Question: I've made an interesting problem for myself on SQL 2008R2.  I moved my MSDB and Model databases to a new drive, but in the process of doing so I transposed the log file names for each and they are now reversed.  SQL will start, and I can check database file names with the following script:
SELECT name,
physical_name AS CurrentLocation,
state_desc
FROM sys.master_files

Which confirms the flipped names.  The script that I used to cause my problem returns a "database does not exist" error, however.
ALTER DATABASE msdb
MODIFY FILE (NAME = MSDBLog, FILENAME = 'F:\SQLLogs\MSDBLog.ldf');
GO
ALTER DATABASE Model
MODIFY FILE (NAME = ModelLog, FILENAME = 'F:\SQLLogs\ModelLog.ldf');
GO

Swapping the file names to match the misconfiguration results in SQL not starting.
Any thoughts on how to fix this, without resorting to a system database rebuild?
Answer: I am happy to say that I worked out a solution to my problems.  One of the fundamental hangups that I was hitting was I was mistaking the error message "The file does not exist" to reference the database file itself, rather than the logical file name within the database.  I will provide below the inspection script that I drafted that got me over the hump.
Steps I took to ultimately solve this:

Turned off TCP/IP connections and turned on Named Pipes, to ensure only local access to the DB.
Started SQL from the command line with 3608 trace flag, to prevent any other databases other than master from being brought up.  I needed to start and stop SQL quite a few times, so I kept this CMD line up.  "NET START MSSQLSERVER /T3608" and "NET STOP MSSQLSERVER"
Ran my script to show me the naming on the databases (listed by ID, 3 and 4)
and then appropriately modified and ran the name correction scripts. See below.

The script that show me the precise problems that I had caused myself with my transpositions:
SELECT database_id, name,
physical_name AS CurrentLocation,
state_desc
FROM sys.master_files
WHERE database_id = 3 OR database_id = 4
go

database_id 3 is Model, 4 is MSDB
With that in mind, substituting the corrected information into the following scripts worked (albeit with a few service restarts)
ALTER DATABASE msdb
MODIFY FILE (NAME = MSDBLog, FILENAME = 'D:\MSSQL\DATA\MSDBLog.ldf');
GO
ALTER DATABASE msdb
MODIFY FILE (NAME = MSDBData, FILENAME = 'D:\MSSQL\DATA\MSDBData.mdf');
GO
ALTER DATABASE model
MODIFY FILE (NAME = modellog, FILENAME = 'D:\MSSQL\DATA\modellog.ldf');
GO
ALTER DATABASE model
MODIFY FILE (NAME = modeldev, FILENAME = 'D:\MSSQL\DATA\model.mdf');
GO

In some cases where the NAME was wrong, I needed to use (please note the swap below - DONT USE unless you have this exact swapping issue):
ALTER DATABASE model
MODIFY FILE (NAME = msdbdata, NEWNAME = modeldev );
GO


how to add a "preview" button to a webform submission

Question: I am using version 8x-5.2 of webform.  I cant see an option to add a preview button.  Can someone explain where to add this button, or do i have to use a later version of the webform module to get this ? thank you .
Answer: in the webform you go to "settings" "form" and at the bottom there is an option for "Form Preview Settings"


Search on multiple terms with Elastic Search

Question: I'm new to ES and want to setup a query to search on multiple terms.
My SQL looks like:
"SELECT field4 FROM tablename WHERE (field1 = 'A' OR field1 = 'AA') AND (field2 = 'B' OR fields2 = 'BB') AND (field3 = 'C' OR field3 = 'CC')"

In ES I'm trying
{
"query": {
"bool": {
  "must": [
    {
      "term": {
        "field1": {"A","AA"}
      }
    },
    {
      "term": {
        "field2": {"B","BB"}
      }
    },
    {
    "term": {
      "field3": {"C","CC"}
    }
   }
  }
 }
}

Answer: What you most likely want is a terms query. You can see the documentation for it here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
An example from that site is:
{
    "terms" : { "user" : ["kimchy", "elasticsearch"]}
}

Also, your query right now isn't valid json, you'll need to correct it.
Comment: I tried the following but still not working.:       {  "from": 0,  "size": 200,  "query": {  "bool": {  "must": {  "bool": {  "must": [  {  "bool": {  "should": [  {  "term": {  "field2": "1"  }  },  {  "term": {  "field2": "4"  }  }  ]  }  },  {  "bool": {  "should": [  {  "term": {  "field1": "1"  }  },  {  "term": {  "field1": "3"  }  }  ]  }  }  ]  }  }  }  }  }
Comment: What do you mean by "not working"? What is the result of running the query? Does it error or just return zero results? If the latter, you probably don't have any documents that match the query. Double check what documents you have in the elasticsearch cluster and try a simpler query to confirm the documents are there and you are running the query correctly.


Ordinal Logistic Regression in SPSS

Question: This is my first time conducting an ordinal logistic regression on SPSS, and I want to check for the assumptions.
Assumption 1: My dependent variable is indeed ordinal. My variable is anxiety symptom severity levels: normal, mild, moderate, severe, and extremely severe.
Assumption 2: My independent variables are either continuous or categorical.
I have 3 categorical variables: sex, educational attainment, and marital status.
I have 4 continuous variables: age, number of children, and two other variables that are scored on self-report questionnaires.
Assumption 3: I tested for multicollinearity using multiple linear regressions. To do so, I generated seven multiple linear regression each one having one predictor variable of the OLR as a dependent variable. All VIFs were less than 3. So I conclude that there are no multicollinearity among the predictors.
Assumption 4: I am testing for proportional odds. The test of parallel lines on SPSS was insignificant, p>.05.
I read that we should do a full likelihood ratio test comparing the fitted location model to a model with varying location parameters and then run separate binomial logistic regressions on cumulative dichotomous dependent variables.
Should I do this given that the test of parallel lines is insignificant? Or do we run separate binomial regressions regardless of the test of parallel lines outcome? Also, how do we conduct these? Please share with me resources that explain the procedures on SPSS.
If the test of parallel lines is violated, what to do next?
Thank you.
Answer: The test of parallel lines in PLUM (Ordinal Regression in the menus) is a likelihood-ratio test. If you're not able to assume parallel functions, you can fit a multinomial logistic model in the NOMREG (Multinomial Logistic in the menus) procedure, which fits a separate function for each of K-1 logits for a K-level response, but does them altogether, which is better than doing separate binary response models.

Ordinal Logistic Regression in SPSS


Cross-correlations in digit distributions

Question: *Update on 5/4/2023. The strictly positive integers $p$ and $q$ discussed in this post, in addition to being co-prime, must not contain any factor that is power of $2$, such $2,4,8$ and so on.
Let $B_1, B_2,\cdots$ be i.i.d. Bernouilli with mean $\frac{1}{2}$, and
$$X=\sum_{k=1}^\infty \frac{B_k}{2^k}.$$
The random variables $B_k$ are the binary digits of the random number $X \in [0,1]$. Let's $p, q$ be strictly positive co-prime integers (that is, they have no common factors other than $1$). In addition, $p,q$ are odd numbers.
Let $C_k, D_k, k=1,2\cdots$ be the binary digits respectively of $pX$ and $qX$, starting after the decimal point. We define the cross-correlation $\rho_N$ as
$$\rho_N(p,q) = \mbox{Correl}(C_1,\cdots,C_N; D_1,\cdots,D_N).$$
The purpose here is three-fold:

Establish that the limit $\rho_\infty$ exists
Prove or disprove that $\rho_\infty=\frac{1}{pq}$
Prove that the empirical correlation between the binary digits of
(say) $\sqrt{2}$ and $\sqrt{3}$, is zero.

I am by a long shot mostly interested in answering the third question, which would be a spectacular result, unproven to this day. However, answering the second question is also of great interest, and probably of bigger interest to the readers.
Some great progress (with respect to the third question) was accomplished in a previous answer to a CV question, see here. @Whuber proved that the cross-correlation between the terms in the sequences $\{kp\alpha\}$ and $\{kq\alpha\}, k=1,2,\cdots$, is $\frac{1}{pq}$. Here the brackets represent the fractional part function, and $\alpha$ is irrational.
In my question here, the relevant sequences would be  $\{2^k p\alpha\}$ and $\{2^k q\alpha\}$ as the $k$-th binary digit of $\alpha$ is $\lfloor 2\{2^k\alpha\}\rfloor$.
To answer the third question, note that $\sqrt{2}$ and $\sqrt{3}$ are linearly independent over the set of rational numbers, and $\rho_\infty$ can be approximated as close as you want using $p\alpha$ and $q\alpha$ instead of $\sqrt{2}$ and $\sqrt{3}$ for some irrational $\alpha$. But to get better and better approximations, you need $p$ and $q$ to tend to infinity, and the resulting correlation, equal to $\frac{1}{pq}$, tends to zero.
Example and code
Below is the code used for my computations, creating simulated random numbers $X$ and computing the correlations between the binary digits of $pX$ and $qX$. It shows the variability from one sample to the other.
<code>$nsimul=10;
$kmax=1000000;
$p=13;
$q=31;

open(OUT2,">correl.txt");

for ($simul=0; $simul< $nsimul; $simul++) {

$rand=107*100000*$simul;
$prod=0;
$count=0;

for ($k=0; $k<$kmax; $k++) { # digits in reverse order
  $rand=(10232193*$rand + 3701101) % 54198451371;
  $b=int(2*$rand/54198451371); # digit of X

  $c1=$p*$b;
  $old_d1=$d1;
  $old_e1=$e1;
  $d1=($c1+ $old_e1/2) %2;  # digit of pX
  $e1=($old_e1/2) + $c1 - $d1;

  $c2=$q*$b;
  $old_d2=$d2;
  $old_e2=$e2;
  $d2=($c2+ $old_e2/2) %2;  #digit of qX
  $e2=($old_e2/2) + $c2 - $d2;

  $prod+=($d1*$d2);
  $count++;
  $correl=4*$prod/$count - 1;
  $limit=1/($p*$q);

  if ($k% 1000 == 0) {
    print "$simul\t$k\t$correl\t$x\n";
    print OUT2 "$simul\t$k\t$correl\t$limit\n";
  }

}

print "correl: $correl - $x\n";

}

close(OUT2);
</code>
Below is the chart showing one simulation, with 10 million random binary digits, with $p=1$ and $q=3$. The orange line corresponds to the limit $\rho_\infty = \frac{1}{3}$. The Y-axis represents the correlation computed over the first $n$ digits, for $n=1,2,\cdots, 10^7$ on the abcissa.

Possible approach to solve the problem
Instead of $X$ being irrational, consider a rational number with a large period, much larger than $p$ or $q$ (use same source code to produce the period) and let the period tends to infinity.
Comment: The number $X$ must be random. This does not work with numbers exhibiting patterns, such as rational numbers. See also related question at https://stats.stackexchange.com/questions/422354/correlations-between-two-sequences-of-irrational-numbers
Answer: Not an easy question it seems. My answer here is still based on empirical evidence, but far easier to check. First, note that if we shift the digits of either $pX$ or $qX$ (that is by multiplying $pX$ or $qY$ by a power of two, positive or negative) any apparent cross-correlation in the two digit distributions vanishes. Only one particular shift produces a non-zero cross-correlation, and that's the shift produced when running the code posted in my question.
Here I will use the following notation:

$b_k$ represents the $k$-th binary digit of $X$
$d_k$ and $d'_k$ are the $k$-th binary digits of $pX$ and $qX$
respectively
$e_k$ and $e'_k$ are auxiliary variables used in the
computations, attached to $pX$ and $qX$ respectively

The digits satisfy the recursions
$$d_k=\mbox{mod}\Big(pb_k+ \frac{1}{2}e_{k+1},2\Big) , e_k=\frac{1}{2}e_{k+1} + pb_k - d_k$$
$$d'_k=\mbox{mod}\Big(qb_k+ \frac{1}{2}e'_{k+1},2\Big) , e'_k=\frac{1}{2}e'_{k+1} + qb_k - d'_k$$
In practice, assuming we compute the iterates in reverse order, starting with a large $k=N$ (say $N=10^6$) with $d_N=d'_N=e_N=e'_N=0$ all the way back to $k=0$, then all the digits except a couple of them at the very end (next to $k=N$) will be correct.
Based on empirical evidence, we observe that

The sequences $\{d_k\}$ and $\{e_{k-1}\}$ are independent; same with
$\{d'_k\}$ and $\{e'_{k-1}\}$
The digits $b_k$ behave as i.i.d Bernouilli of parameter
$\frac{1}{2}$, by design
The terms in the sequences $e_k$ and $e'_k$ are uniformly distributed, respectively on $\{0, 2, 4,\cdots,2(p-1)\}$ and $\{0, 2, 4,\cdots,2(q-1)\}$

Thus the cross-correlation between the binary digit sequences $\{d_k\}$ and $\{d'_k\}$ is equal to
$$\rho=-1+\lim_{N\rightarrow\infty} \frac{4}{N}\sum_{k=0}^{N-1} d_k d'_k.$$
Note that $p, q$ are assumed to be odd co-prime integers. As a result, it is easy to prove that $d_k d'_k =1$ if and only if $\frac{1}{2}e_{k-1} = \frac{1}{2}e'_{k-1} \pmod{2} $, and otherwise $d_kd'_k = 0$.
Let us consider the $p\times q$ matrix $M$ defined as follows: $M_{ij}$ is a positive integer, with

$M_{ij} = 0$ if and only if the joint event $e_{k-1} = 2i, e'_{k-1}=2j$ never occurs
regardless of $k$. Otherwise $M_{ij}$ is strictly positive.
The sum of the elements of $M$ in any row is equal to $q$
The sum of the elements of $M$ in any column is equal to $p$

These three properties define $M$ uniquely. Let's $M^* = \frac{1}{pq}M$. Now $M^*_{ij}$ is the probability that $e_{k-1} = 2i$ and $e'_{k-1}=2j$ simultaneously, measured as the asymptotic frequency of this event computed on all observed $(e_k,e'_k)$. The probability $P$ that $d_kd'_k=1$ is the sum of the terms $M^*_{ij}$ over all indices $i,j$ with $i = j \pmod{2}$. And of course, the sum of all $M^*_{ij}$ (regardless of parity) is equal to $1$. To conclude, it suffices to prove that $P=\frac{pq +1}{2pq}$  and $\rho = 2P-1 = \frac{1}{pq}$.
Example
Here $p=7, q=11$. Non-null entries in $M$ are starred below, based on empirical evidence.

The above starred entries are based on counts computed on $10^6$ values of $(e_k,e'_k)$. These counts are featured in the table below. The binary digits $b_k$ were generated as i.i.d Bernouilli with parameter $\frac{1}{2}$ using the source code posted in my question.

The resulting matrix $M$ is as follows:

Below is the matrix $M$ for $p=31, q=71$:


Need Regex to match [#URL^Url Description^#]

Question: I need regex to find this text

[#URL^Url Description^#]

in a string and replace it with

Url Description

"Url Description" can be set of characters in any language.
Any Regex Experts out there to help me?
Thanks.
Comment: It's not a question. Adding `?` to the end of sentence won't help.
Comment: That's nice. Have you tried yourself?
Comment: I tried myself with http://regexpal.com/ and with similar stackoverflow answers, but I am not able to get it exactly right. The URL description can be any language. As of now I need to test French and German. Thanks for the help.
Answer: It might be a bit confusing, but you can use the following:
string str = @"[#URL^Url Description^#]";
var regex = new Regex(@"^[^^]+\^([^^]+)\^[^^]+$");
var result = regex.Replace(str, @"$1");

The first ^ means the beginning of the string;
The [^^]+ means anything not a caret character;
The \^ is a literal caret;
The $ is the end of the string.
Basically, it captures all characters between the carets (^) and replace this in between the  tags.
See ideone demo.
You can also replace the last line with this:
var result = regex.Replace(str, @"$1");

Where link is the variable containing the link you want to replace in.
Comment: Hi, Thanks for your effort and Nice Regex. I also learned about ideone. its working for English. But I must test it for all the languages. But I agree with elmugrat, string.replace logic will work very well with out testing for all languages and it is readable as well. For My Question, your answer is correct, but I go for the other solution in real time scenario. Thanks.
Comment: @suresh2 Could you provide an example of non english description?
Comment: As of now, the url Description can be any English, German, French Characters. In the future it may be Chinese, Arabic or any language. I am not sure how the regex will work with all the unicode characters. I just used the string.replace, because I am confident that will work with all scenarios and the code is readable too. Thanks.
Comment: @suresh2 Oh if that's that, the regex works for all characters. See a japanese one I made [here](http://ideone.com/fWE35G).
Answer: Why don't you use String.Replace()?  A regex would work, but it looks like the format is well defined and regexes are harder to read.
string url = "[#URL^blah^#]";

string url_html = url.Replace("[#URL^", "")
                     .Replace("^#]", "");

Comment: I can replace the URL with variables. @elmugrat I agree with you. I used string.replace instead of regex which is simple and better solution. When ever I see a string, Brain always think about Regex. :-). Thanks for the simple and better solution.


PHP cPanel: Is there a way to change my upload_max_filesize in cPanel (without access to php.ini)?

Question: i would like to be able to upload files larger than 64M. locally, i could set my php.ini file, but it looks like cPanel does not allow that, and rightfully so. i read that ini_set does not work for upload_max_filesize, so i am here asking the pros.
any ideas? thanks.
Answer: upload_max_filesize can be rewriten by php.ini in user's directory if you have your cPanel using suphp.
It is usually under /home/domain/public_html if it is not there you can create your own in there.
Make sure you have suphp enabled on htttpd.conf aswell.
Comment: so, if i understand correctly, i need to:
1) make my own php.ini file inside /home/domain/public_html
2) enable suphp on httpd.conf

great. now my only question is:
where can i find `httpd.conf`?
Comment: if you are not the owner of the server you gona have to ask for you server provider if they use suPHP or you can simple try to put the php.ini on the public_html folder with the changes you need and then run the phpinfo from a php script to verify the server variable for a change, if it changed means you do have suPHP within your server. If you are the owner of the server, httpd.conf is usually at /etc/httpd/ or your can fun `updatedb; locate httpd.conf`
Comment: i found `php.ini` inside `/etc`! thanks for your help!
Comment: /etc of your ftp or /etc within your system ? if it is within your ftp it is probably that your host does use suPHP but with a different path for the php.ini like yours. Hope that works out for you, best regards.
Answer: In your public_html add these two files:
.htaccess (if it's already there, simply download it and add into it the following)
#Activates php.ini config located in main folder to work also recursively for all subfolders, obviously replace your_cpanel_user with your full path, you find it in cPanel home page on the left it's called 'Home Directory'
suPHP_ConfigPath /home/your_cpanel_user/public_html

php.ini
upload_max_filesize = 64M
; post_max_size 8M (this might need to be adjusted too)
; memory_limit 128M (this might need to be adjusted too)
; max_input_time -1 (this might need to be adjusted too)

Actually 64M is really huge to upload on a server without using FTP, the other variables I wrote in php.ini file might need to be set properly to bigger values (I left them commented out using ';'), you can readmore in here: http://it.php.net/manual/en/features.file-upload.common-pitfalls.php
Answer: I've found an easy way to change the upload_max_filesize through .htaccess
You onlye have to edit your .htacess (in root) an add the following lines
php_value upload_max_filesize 40M
php_value post_max_size 40M
php_value max_input_time 1000
php_value max_execution_time 1000

Notice that I chose 40MB ("40M") as upload limit, and time "1000", just to be sure that the time will be long enough to upload the file.
It worked for me.
Comment: FYI: this will only work when php is loaded as an apache module aka DSO.


GLS vs ML in Linear Mixed Model

Question: Hox's Multilevel Analysis: Techniques and Applications states,
"Generalized Least Squares(GLS) estimates can be obtained from a Maximum Likelihood procedure by restricting the number of iterations to one."
I cant figure how it is so.
First of all, he doesn't state whether it's about ML or REML.
Second, as far as I know GLS is for error-variance-covariance structure.
I know random intercept model has a equivalent model with fixed coefficients and
error variance-covariance structure but I don't think it's possible
for all Mixed model to have equivalent model with fixed coefficients and error variance-covariance structure. Is it right? or wrong?
So anyone can elaborate on them?
Comment: It's very difficult to determine what it is you are asking here.  I'd recommend rephrasing this and providing more detail.
Comment: Well, it's just that i cant understand how "Generalized Least Squares(GLS) estimates can be obtained from a Maximum Likelihood procedure by restricting the number of iterations to one." is true. As far as I know, GLS is for the model without random effect... so how is it the ML with just one iteration is GLS???
Comment: Of course we are talking about multilevel(mixed effect) model...
Comment: Got it.  See my response below.
Answer: Maximum Likelihood procedures (like those in SAS) typically use as starting values, the OLS parameter estimates, so that is why setting iteration to 1 would work here.

GLS vs ML in Linear Mixed Model


Value cannot be null (clientId) on GetConversationMembersWithHttpMessagesAsync execution

Question: The bot is getting an error "Value cannot be null. Parameter name: clientId"
while executing GetConversationMembersWithHttpMessagesAsync method to get conversation users data. The conversation is just works fine, i can send and receive messages, but when i try to get info about the current conversation i get this exception.
Is there a necessity to create Bot Channels Registration at Azure to maintain such operations?
I've tried to manually add CustomHeaders with bearer token to http-query without a result.
customHeaders.Add("Authorization", new List<string> { "Bearer " + Global.accessToken });
membersListResponse = await connector.Conversations.GetConversationMembersWithHttpMessagesAsync(convId, customHeaders);

Error and stack trace:
Value cannot be null.
Parameter name: clientId         at Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential..ctor(String clientId, String clientSecret)
   at Microsoft.Bot.Connector.Authentication.MicrosoftAppCredentials.<>c__DisplayClass8_0.<.ctor>b__0()
   at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy1.CreateValue()
   at Microsoft.Bot.Connector.Authentication.MicrosoftAppCredentials.GetTokenAsync(Boolean forceRefresh)
   at Microsoft.Bot.Connector.Authentication.MicrosoftAppCredentials.ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Bot.Connector.Conversations.GetConversationMembersWithHttpMessagesAsync(String conversationId, Dictionary2 customHeaders, CancellationToken cancellationToken)
Comment: Were you able to authenticate the user?
Comment: Possible duplicate of [ArgumentNullException in CreateDirectConversation/CreateDirectConversationAsync Bot Framework 4](https://stackoverflow.com/questions/55407725/argumentnullexception-in-createdirectconversation-createdirectconversationasync)
Comment: @GeethuSuresh I'm using MSappId and MSappPassword to sign in Bot Framework and they are applied correctly. The bot is available for communication and prompting for command execution, but that's it.
Answer: The cause of this exception was an absense of auth data in the ConnectorClient used to post async request.
I've instantiated new MicrosoftAppCredentials class, passed appId and appPassword into it and then applied new instance to ConnectorClient.
It was:
var connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl))
It became:
var connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl), BotCredentials.msAppCredentials);


auto.arima from Forecast package

Question: I am trying to fit a time series using the function auto.arima and I face some strange results.
As a first try, I use the command
auto.arima(data,d=0,D=1,max.p=2,max.q=2,max.P=2,max.Q=2,max.order=8, xreg=xreg_past,trace=TRUE,ic="aic")

The model I get is an ARIMA(2,0,2)(0,1,1)[12] with an AIC equal to -300.14.
But since I know that this command will make use of the stepwise selection algorithm, I want to make a try with the tests of all possible models using the option stepwise=FALSE.
I thus try the command
auto.arima(data,d=0,D=1,max.p=2,max.q=2,max.P=2,max.Q=2,max.order=8, xreg=xreg_past,stepwise=FALSE,trace=TRUE,ic="aic")

And now, the model I get is an ARIMA(0,0,2)(2,1,0)[12] with an AIC equal to -293.14. Since my second attempt takes all the models into account, this result is strange as the previous model had a lower AIC. Furthermore, If I take a look in the trace of the last function call, I see that the ARIMA(2,0,2)(0,1,1)[12] model has now an AIC of -245.13 which explains why it has been rejected. Why did the AIC value change ?
At least, if I use the simple command
arima(data, order=c(2,0,2), seasonal= list(order=c(2,1,2), period=12), xreg=xreg_past)

I get an AIC value of -319.15, which is better that the two models provided before.
I think I am missing something important but I am not able to see what. Can somebody help me ?
Thanks in advance,
Regards,
Ludo
Comment: Try the following code instead of the first code that you wrote: auto.arima(data,d=0,D=1,max.p=2,max.q=2,max.P=2,max.Q=2, xreg=xreg_past,trace=TRUE,ic="aic") because the max.order should not be set when stepwise is TRUE. If that does not fix the problem then try to remove the arguments d=0,D=1,max.p=2,max.q=2,max.P=2,max.Q=2 in both models as well i.e. let the function select the orders ...
Comment: Hi ! Your first suggestion didn't change the result. For the second one, I don't think it will solve the problem. Indeed, the different conditions imposed on the orders are necessary for my work and I really need to understand why auto.arima doesn't choose the best model. Thanks for your help.
Answer: arima() will return different results from auto.arima() when differencing is used. Estimation with arima() uses a diffuse prior when the model is non-stationary, whereas auto.arima() fits the model to the differenced series.
I'm not sure why the two auto.arima() calls give different AIC values for the same model. Can you please post the data so the result can be replicated.
Comment: Thank you for your reply. Unfortunately, I am not authorized to publish this data on the internet. However, if I make no mistake, I think I am able to replicate the problem using the gas time series provided in the Forecast package. Please consider the code : data <- gas xreg_past <- 1:length(data) auto.arima(data,d=0,D=1,max.p=2,max.q=2,max.P=2,max.Q=2,max.order=8, xreg=xreg_past,trace=TRUE,ic="aic") auto.arima(data,d=0,D=1,max.p=2,max.q=2,max.P=2,max.Q=2,max.order=8, xreg=xreg_past,stepwise=FALSE,trace=TRUE,ic="aic")
Comment: The first model returns an ARIMA(2,0,2)(0,1,2) model with an AIC of 8183.52. The AIC returned by trace (using an approximation) is 7996.88. The second model gives the same AIC in the trace using the same approximation. Perhaps you are comparing the AIC returned with that printed in the trace. The latter is an approximation. If you want the exact AIC, use the argument approximation=FALSE.
Comment: I was clearly comparing the AIC in the final output with the one in the trace. Thank you for the explanation.

auto.arima from Forecast package


How to determine primary network adapter in results from PdhExpandWildCardPath?

Question: My goal is to measure the average Bytes received per second using the Windows performance counter API. My problem is that, when there are multiple network adapters, I don't know which one is the "primary" one (i.e. the one used for Internet and LAN traffic).
I can pass "\Network Interface(*)\Bytes Received/sec" to PdhExpandWildCardPath() and get a list back, but that list seems to be in alphabetical order, not routing order. And the names returned by PdhExpandWildCardPath() don't seem to be the same as the ones the WMI functions use -- Pdh seems to add "Packet Scheduler Miniport" -- so even if I went that route I'm not sure how to correlate the information from the different APIs.
Answer: Which network adapter is 'Primary' is a qualitative judgment.  A computer might have both onboard wireless 802.11, and wired Ethernet adapters, either of which could be primary at any given time (or even at the same time).
You are probably going to have to use the IP Helper API to determine which you prefer and correlate that with the PerfMon ouput.  or you could just pick the one with the most activity and call it primary.  That's just the kind of value judgment that PerfMon cannot possibly make, as these stats are transparent to it.


Para que serve o índice INDEX no MySQL?

Question: Para que serve o índice INDEX no MySQL?
ALTER TABLE `tabela`
ADD INDEX `tabela_id_index` (`tabela_id` ASC);

Comment: Relacionado: http://pt.stackoverflow.com/q/35088/101, http://pt.stackoverflow.com/q/55118/101, http://pt.stackoverflow.com/q/32052/101, http://pt.stackoverflow.com/q/23348/101, http://pt.stackoverflow.com/q/27877/101
Comment: Relacionado: [Quando e em quais colunas deve-se usar índices?](http://pt.stackoverflow.com/q/76131/18246)
Comment: Só para constar, "index" = "índice" em inglês. Parece haver uma confusão no título da questão.
Comment: @DineiRockenbach não é confusão não... É que eu diria: "índice unique" ou "índice primary"... então também me expressaria falando "índice index"
Answer: Uma maneira fácil de pensar em indexes é pensar num sumário de um livro, ele existe para facilitar a localização de conteúdos do livro, assim você acha um conteúdo de maneira mais fácil do que procurar página por página, para isto depende de que os indexes sejam bem definidos.

Benefícios:

São capazes de reduzir a quantidade de dados que o servidor teria que examinar.
São capazes de ajudar o servidor a ordenar (ex. ORDER BY) e evitar criação de tabelas temporárias.

O uso de "são capazes" é porque nem todo os indexes criados vão fazer isso, até porque talvez eles nunca sejam utilizados.

Tipos de Indexes:
Esses são os tipos de indexes que existem nas engines mais comuns:

B-Tree: Mais comum de todos os tipos de indexes, basicamente com exceção do Archive Engine todos suportam ele, porém com diferenças internas.

InnoDB  Engine utiliza B+Tree não comprimido e são referenciados pela Primary Key.
MyISAM Engine utiliza B-Tree com técnicas de compreensão e são referenciados por sua localização física.
NDB Cluster Engine utiliza T-Tree.
TokuDB utiliza uma variação chamada Fractal Tree.

Hash: Próprio nome já explica, ele é util apenas para diferenciação e igualdade (IN(), = e <=>), mas não é usado para nenhuma outra funcionalidade.

MEMORY Engine é um dos únicos que tem suporte explicito para este tipo de index.
InnoDB Engine possui adaptative hash indexes, quando o InnoDB identifica que alguns valores são acessados frequentemente ele criar um hash index e utiliza antes do B-Tree, porém isto é totalmente automático e não há como desligar ou criar isto.

R-Tree: Raramente utilizado no MySQL, porém utilizado no PostgreSQL e PostGIS, ele não exige o uso do WHERE para se beneficiar.

InnoDB Engine é um dos único que tem suporte para este tipo de index.

Full-Text Index: Tenha uma característica diferente e apenas usado para operações de MATCH AGAINST.

MyISAM Engine tem suporte para este tipo de index.
InnoDB Engine tem suporte para este tipo de index nas versões mais recentes.

Para complementar, o ScaleDB utiliza Patricia-Tries. Já o InfiniDB e Infobright tem uma arquitetura própria (?).

Como o padrão é o B-Tree, é justamente nele que irei utilizar como base para tudo aqui.
Limitações:

Não servem para leituras que não comecem da esquerda, por exemplo o SELECT * FROM Tabela WHERE Nome LIKE '%A', para tentar achar todos nomes que terminam com A, porém você pode usar A% para achar o que comece com A.
A sua query deve executar a mesma ordem os index definido, criar um KEY(Nome, Sobrenome) obrigatoriamente deverá informar nesta ordem. Você pode WHERE Nome = 'Inkeliz', porém não poderá usar WHERE Sobrenome = 'Lima'. Você obrigatoriamente deve seguir a ordem, ou seja WHERE Nome = 'Inkeliz' AND Sobrenome = 'Lima', por exemplo.
Se criar um range, por exemplo, WHERE Nome LIKE 'ANA%' AND Sobrenome = 'Lima', os indexes serão utilizados para achar a Ana, porém não será utilizado para achar os sobrenomes, isto irá ainda criar uma tabela temporária. Isso indica que você preferir deve colocar X > 1, BETWEEN 1 AND 5 e LIKE como última condição, ou seja todas as igualdades devem vir antes (inclusive existem "truques"/"gambiarras" com o IN()), detalho isto depois.

Problemas:
Isolar colunas:
Considere isto:
SELECT Nome FROM Usuarios WHERE ID + 1 = 10

Viu o problema? O MySQL não é capaz de fazer essa soma. Para nós, é fácil saber que ID + 1 = 10 é o mesmo que ID = 9, porém o MySQL não faz isto, como consequência ele irá varrer todo o banco de dados e somar todos os ID, ignorando qualquer index.
Exemplo mais real:
SELECT Nome FROM Acessos WHERE TO_DAYS(CURRENT_DATE) - TO_DAYS(UltimoAcesso) <= 7

O mesmo problema, você irá executar o TO_DAYS() em tudo e depois subtrair e depois compara-lo para ver se é menor que 7. Indexes não são milagrosos nesses casos e serão ignoráveis.
Criar range:
No MySQL utilizar PODE IN() ser melhor do que BETWEEN, porém cuidado com grande número de condições, por exemplo:
SELECT Nome FROM Usuario WHERE Genero IN ('h', 'm') AND Idade IN (18, 19, 20, 21, 22, 23, 24, 25) AND UltimaAcao > DATE_SUB(NOW(), INTERVAL 7 DAY);

Isto teria 2 * 8 possibilidades e depois seria teoricamente melhor do que:
SELECT Nome FROM Usuario WHERE Genero IN ('h', 'm') AND Idade BETWEEN 18 AND 25 AND UltimaAcao > DATE_SUB(NOW(), INTERVAL 7 DAY);

Isto ocorre porque utilizando o BETWEEN você geraria dois ranges o primeiro por Idade e o segundo por UltimaAcao, enquanto no IN() é igualdade. Isto ainda levanta uma outra questão, qual dos dois possui maior relevância?! Mas, porque usar Genero IN ('h', 'm'), supondo que sejam as únicas opções.
A gambiarra do IN() vem pela necessidade de especificar todas as colunas, por isso se fizer: KEY(Genero, Pais, Idade) você sempre terá que informar o Genero, Pais e Idade. Por isso usamos o IN(), ou seja se somente existe h e m então fazemos Genero IN ('h', 'm'), dessa forma "ignoramos" o Genero e podemos filtrar por Pais, ou fazemos um novo IN() com todas as listas de países e passamos para a idade. *A idade em último, novamente, porque ela tem um poder potencial de criar um range.
Caso usássemos:
SELECT Nome FROM Usuario WHERE Idade > 18 AND Genero = 'h' AND Pais = 'BR'

Iria obrigatoriamente ignorar os indexes de Genero e Pais, porque o primeiro, Idade cria um range.
Relevância e ordem:
Agora qual tem mais relevância, considere isto:
SELECT * FROM Usuario WHERE Ativo = 0 AND id =  10;
SELECT * FROM Usuario WHERE id = 10;
SELECT * FROM Usuario WHERE Ativo IN (0, 1) AND id = 10;

O primeiro e o último poderia utilizar KEY(Ativo, id), porém seria incompatível com o segundo. Porém poderíamos também fazer:
SELECT * FROM Usuario WHERE id = 10 AND Ativo = 0;
SELECT * FROM Usuario WHERE id = 10;
SELECT * FROM Usuario WHERE id = 10 AND Ativo IN (0,1);

Assim poderíamos usar o KEY(id, Ativo), todos eles iriam utilizar indexes, neste caso ele tende a ser melhor, porque o Ativo, por ser binário irá retornar mais dados do que o id que tende a ser único, portanto o id tem maior relevância e isso tem grande impacto.
Uma outra coisa é saber se não ira fazer isso:
SELECT * FROM Usuario WHERE id > 10 AND Ativo = 0;
SELECT * FROM Usuario WHERE Ativo = 0;

Porque se essas queries forem utilizadas o KEY(Ativo, id) poderia ser melhor, mas novamente depende do caso, assim usando o Ativo IN() antes mesmo que somente fosse selecionar o id.
Um outro problema é criar vários indexes separados por cada coluna, isto é terrível e raramente são úteis.
Colunas separadas:
Criar indexes separados podem ser bons caso utilize:
SELECT * FROM tabela WHERE Nome = 'Inkeliz' OR Idade = 18

Caso crie indexes separados, Nome e Idade o MySQL fará um UNION dos dois resultados, usando cada index separado. No entanto fazer isto:
 SELECT * FROM tabela WHERE Nome = 'Inkeliz' AND Idade = 18

Não irá se beneficiar de ambos dos indexes, ele apenas irá optar por utilizar um deles, não os dois. Na maioria das vezes criar indexes dividos não é bom, em resumo.
O ORDER BY e GROUP BY também se beneficia dos indexes, porém desde que não crie um range, porque neste caso cai num filesort mesmo, não tem jeito, exceto fazer um RAID-0 de SSD.

Indexes são complexos, tem dois livros sobre isto, infelizmente não cobrem o MySQL 5.6 e MySQL 5.7, e aparentemente não há nova versão para ser lançada, são eles:
High Performance MySQL: Optimization, Backups, and Replication, tem uma versão traduzida pela Altas Books (mas é mais antigo ainda e existe várias reclamações de falhas na tradução), nele que menciona o uso da gambiarra do IN(), não é minha autoria (e deu uma boa reduzida de RAM, deletando indexes repetidos).
Relational Database Index Design and the Optimizers, praticamente um livro somente somente indexes, este ainda está na fila para ser lido, o livro acima indica este também. :)
Answer: Para se criar um índice (Os índices são utilizados para encontrar registros com um valor específico de uma coluna rapidamente. Sem um índice o MySQL tem de iniciar com o primeiro registro e depois ler através de toda a tabela até que ele encontre os registros relevantes)
Citação da Locaweb

Um dos itens mais importantes na otimização da base de dados é a
  criação de índices. Com este procedimento sua consulta ficará bem mais
  rápida. O ideal é que crie índices em todos os campos utilizados nas
  cláusulas "where" e "joins" de suas queries.

Esta resposta do SOen da uma demonstração de como se criar um índice: Link
Comparação entre CREATE INDEX e ALTER TABLEtabelaADD INDEX: Link
Index documentação Mysql: Link
Answer: Índices são estruturas de acesso auxiliares associadas às tabelas e que têm por objetivo aumentar o desempenho na execução de consultas.
existem dois tipos de index:
Clusterizado: esse ordenado sequencialmente.
Não Clusterizado:
Um índice cuja chave de busca especifica uma ordem diferente da ordem sequencial do arquivo.

Para que serve o índice INDEX no MySQL?


Graphical LASSO Interpretation

Question: I have a conceptual question about graphical LASSO interpretation. I have been using the huge package in R to estimate an association network for a matrix of node attributes. My understanding of graphical LASSO is that you are performing a penalized regression where each vector of attributes is regressed on all other vectors of attributes. A pair of vectors $i$ and $j$ then have a tie in the resulting network if $\beta_{ij}, \beta_{ji} \neq 0 $. In most of the applications I've seen, the resulting network is interpreted in terms of similarity. This paper, for example, identifies a network of senators where senators with similar voting records are in each other's neighborhood. This is intuitive and this is what I find in my own applications.
My question is: why is this the case if a pair of vectors are included in the network when $\beta_{ji} \neq 0$? Vectors $ij$ should then be included if $\beta <0$ as well as when $\beta >0$. The network of association would include ties between highly similar and highly dissimilar vectors, both positive and negative associations. So why is it that the networks this method generates are primarily networks of similarity / positive association? Why don't we also see links between perfectly dissimilar vectors? I would greatly appreciate any help with this question.
Comment: I do not have an answer, as such, but can suggest searching for more examples of graphical LASSO, e.g. see the 'adaptive lasso' network here http://www.sciencedirect.com/science/article/pii/S0092656614000701.  Connections can be negative. As I understand, graphical lasso methods take a precision matrix, or the inverse of the correlation matrix (i.e. partial correlations), and compute a penalised graph dependent on a value lambda, ranging between [0,1]. Thus, connections certainly can be negative.
Answer: Structure estimation in graphical models is a big field of statistics in it's own right. Two common methods are

Neighbourhood Selection, Meinhausen and Buhlmann, 2006
Graphical Lasso, originally proposed by Yuan and Lin and subject to various future practical extensions and theoretical analysis e.g. Mazumder and Hastie, Chandrasekaran et al.

What you are describing sounds like the Meinhausen-Buhlmann neighbourhood selection scheme.
However, I suppose the graphical lasso function inhuge implements some version of the graphical lasso algorithm - which is related to neighbourhood selection - but different.
The references above are pretty scary - I think the introduction in Statistical Learning with Sparsity will be more friendly. This mentions a nice interpretation of the graphical lasso as doing neighbourhood selection on all nodes simultaneously.
On to why networks are primarily of positive association, I believe this is just a quirk of real-world data. One would expect similar things to behave in similar ways - this might be very common; one might expect different things to behave somewhat independently; a negative correlation suggests more complicated system dynamics that one might expect to be fairly rare (and correspondingly more interesting). Does that sound reasonable?

Graphical LASSO Interpretation


Execute an sql query in umbraco at time of package Installation

Question: I have created a package in umbraco and trying to add Action Script which will create a table in umbraco database.But When I try to save the below action script it is giving error message:
Actions XML is malformed, either remove the text in the actions field or make sure it is correctly formed XML.
I am not able to identify what's the mistake I am doing here in below code.Please Help me out here. Thanks in advance.
Note: I am using Umbraco 4.8.0
<code>    <Action runat="install" undo="false" alias="ExecuteSql">
<![CDATA
        CREATE TABLE [test_nishantBlog_Comment](
            [__kp_ID] [smallint] IDENTITY(1999,1) NOT NULL,
            [__fk_postID] [smallint] NOT NULL,
            [Comment] [ntext] NOT NULL,
            [CreationTime] [timestamp] NOT NULL,
            [CommentTitle] [varchar](500) NOT NULL,
            [EmailAdd] [varchar](100) NULL,
         CONSTRAINT [PK_test_nishantBlog_Comment] PRIMARY KEY CLUSTERED
        (
            [__kp_ID] ASC
        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
        )
    ]>

</Action>
</code>
Comment: Here is link: For Execute sql action script: http://nishantwork.wordpress.com/2012/08/24/execute-sql-query-in-umbraco-during-package-installation/
Answer: You're missing the square brackets around your SQL
<code><![CDATA[-- SQL goes here --]]>
</code>
Answer: My guess is the ] characters in the SQL statement are causing issues with the CDATA close brackets: "]>"
Could you remove those and see if it works?


Falha no método SELECT da classe RANGE

Question: A intenção é que ao clicar na guia Sintese Euro, a macro imputasse na célula D1 da guia Síntese Local o caracter "L" e depois retornasse para a guia Síntese Euro. Eu consegui resolver o problema do erro imputando a macro no módulo. Dessa forma apenas inseri um comando na página Sintese Euro para chamar a macro:
Então na página Síntese Euro eu inseri o código:
Private Sub Worksheet_Activate()
Call Module1.Macro1
End Sub

No Módulo inseri o código da macro
Sub Macro1()
Sheets("SINTESE_LOCAL").Select
Range("D1").Select
ActiveCell.FormulaR1C1 = "L"
Sheets("SINTESE_EURO").Select
End Sub

O problema é que como utilizei o comando Private Sub Worksheet_Activate(), ele entende que todas as formas de acessar a guia podem acionar a macro, e como coloquei o comando Sheets("SINTESE_EURO").Select, na Macro ele acaba entrando em looping.
Existe alguma função que ative somente quando clico na guia e não em todas formas de acessá-la como é o caso da  Private Sub Worksheet_Activate()?
E essa é a linha do erro:
Range("D1").Select

Obrigada, gente.
Comment: Onde você está inserindo o código `Private Sub Worksheet_Activate()`? Num módulo? Poderia inserir um print da Árvore do Projeto VBA.
Comment: O evento está sendo acionado da maneira correta. A célula D1 possui alguma ListBox ou é uma célula comum? Pois um teste com este código foi realizado e funcionou corretamente.
Comment: Então, eu não entendo nada mesmo de VBA, mas o código está dentro do "Microsoft Excel Objetos".
Comment: Então, a célula tem uma listBox sim.
Answer: Você não precisa selecionar a Sheets("SINTESE_LOCAL") nem a célula "D1".
Troque o código da sua Macro1 por:
Sub Macro1()
    Sheets("SINTESE_LOCAL").Range("D1").Value= "L"
End Sub

Answer: Evento Worksheet_Activate
Para utilizar este evento sem entrar em loop, você não pode utilizar o .Select dentro do evento.
Na verdade, .Select/.Activate/.ActiveCell devem ser evitadas quase sempre (a não ser para ativar eventos ou outras ocasiões que é possível somente com Select).
Então você declara a planilha SINTESE_LOCAL e insere o valor na célula ou range da seguinte maneira.
Private Sub Worksheet_Activate()
    Dim SINTESE_LOCAL As Worksheet
    Set SINTESE_LOCAL = ThisWorkbook.Worksheets("SINTESE_LOCAL")
    SINTESE_LOCAL.Range("D1") = "L"
End Sub

Você ativa a Macro da seguinte maneira:
Sub Macro1()
    Sheets("SINTESE_LOCAL").Select
    Sheets("SINTESE_EURO").Select
End Sub

Answer: O erro:
plan3.range("G4").select

A  mensagem: O MÉTODO SELECT DA CLASSE RANGE FALHOU!
O que foi feito (no lugar da linha acima):
plan3.range("G4").select

Faz-se:
DIM WsA AS worksheet
SET wSA= Worksheets("nome da plan3")
WsA.select
WsA.Range("G4").Activate

Falha no método SELECT da classe RANGE


select and operate on words from an array

Question: I want to underline words from an array if a condition is met but I can only select the index as a variable, how can I make it into an element and then underline it (if that's possible). Here is some code to show what I mean.
var textArr = $(div).text().split(/\b/);

for (i = 0; i < textArr.length; i++) {

    if ($('#search').val().match(new RegExp(textArr[i], "i"))) {

     //pseudo code
      $(textArr[i]).css('text-decoration','underline');
    }
}

Comment: How about throwing a fiddle together for us so we can more easily help you?
Comment: I like this problem, definitely will work on it if there's a fiddle!
Answer: To turn your psuedo code, this might be a solution:
$(''+textArr[i]+'').css('text-decoration','underline')
.appendTo('body'); // or any selector

Basically you're creating a new element and styling it with .css() and then append it to a container using .append()
Comment: it's good, but it adds the new underlined text next to the other text instead of replacing it. Thanks +1
Comment: @user2014429 what is the text you want to replace?
Comment: inthe div from: var textArr = $(div).text().split(/\b/);
Answer: Since you haven't posted the contents of search, I'm assuming it's a single word.
This jQuery function, borrowed from here, should do exactly what you need.
jQuery.fn.underline = function (str, className) {
    var regex = new RegExp(str, "gi");
    return this.each(function () {
        $(this).contents().filter(function() {
            return this.nodeType == 3 && regex.test(this.nodeValue);
        }).replaceWith(function() {
            return (this.nodeValue || "").replace(regex, function(match) {
                return "" + match + "";
            });
        });
    });
};

$("#textDiv").underline($("#search").text(), "underlinedText");

Here's a working fiddle.
Answer: Here's a solution that doesn't involve loops. A sample solution is available  at this jsFiddle:
HTML

    Highlight:
    <input type="text" id="search"
        placeholder="Enter a regular expression"/>

 ...

CSS
em {
    text-decoration: underline;
    background-color: yellow;
}

jQuery Code
$('#search').on('change', function(e) {
    highlight('#toUnderline', $(this).val());
});

function highlight(selector, search) {
    var target = $(selector);
    var re = new RegExp(search, 'i');
    var wrapper = '';
    target.html(
        target.text()
            .match(/\w+/g)
            .map(function (word) {
            return (word.search(re) > -1
                    ? $(wrapper)
                        .text(word)
                        .wrap('
')
                        .parent()
                        .html()
                    : word);
        }).join(' ')
    );
}

[edit] Updated the code to be more modular and reusable. Unfortunately, this code will strip out double spaces...
Comment: thanks for the fiddle. I can use a lot of that code +1
Comment: Thanks! You helped me break 1000 points. ;) Good luck with your code!
Comment: If you have time, would you mind checking this fiddle: http://jsfiddle.net/JzLjd/6/. I am trying to make multiple target divs, but it's not going well. Thanks
Comment: Have a look [here](http://jsfiddle.net/MrRampage/JzLjd/7/). You need to run the `.each` function and apply that code to each of the matches.
Comment: That's great. I had tried using the each function, but I was getting the strings being copied and concatenated with each iteration. I must have had something in the wrong order. You have been a massive help. Thank you very much, glad I could help tip you over to 4 figures. ;)
Comment: Please provide feedback on down votes. I would like to improve my answers and coding. Thank you.


How to read value of Textbox which is inside table using javascript

Question:

<title>Projects</title>

Comment: Please make this into a small prototype using [jsFiddle](http://jsfiddle.net)
Answer: You're reading correctly by accessing the .value property, the problem lies elsewhere.
Here is a cleaner version: https://gist.github.com/anonymous/7331383
The problems you had:

First don't forget to declare the variables you're using.
You were adding to arrays (row/cell) which wasn't really needed.
The table wasn't being added to the body
Need to call makeTable() on load (the other function can be called from the console, or you can add a button for that).
unnecessary braces in GetCellValues(), use a good editor and don't forget to indent the code, to prevent this
Use console.log() to print to the console when testing, instead of alert()

And maybe other stuff I'm not remembering xD
Hope it helps.
Comment: I'm not familiar with the .csv format, but try to search on the internet, you'll probably find some library to do that.
Answer: Assign class to inputs then get by class name
var elements =document.getElementsByClassName('test');
for(var i=0;i<elements.length;i++)
{
    console.log(elements[i].value);
}


Maximal independent set and minimum dominating set

Question: Is it possible to build an example of a simple undirected graph that will satisfy the following claim:
Of all possible maximal independent sets of some graph $G = (V,E)$, not a single one can be also a minimum dominating set.
We know that every maximal independent set is a dominating set. In order to construct such example we should have a minimum dominating set that is not in the list of all possible maximal independent sets of some graph $G = (V,E)$ and that has a cardinality smaller than any set in the list of all possible maximal independent sets. Is it possible to find such graph?
Answer: Take the following tree:

The only minimum dominating set (of size 2) is not an independent set at all.


Problem with plotting with SAS

Question: I'm very new to SAS, so please keep that in mind with any responses.
I've been running the following code in SAS:
FILENAME fishfile URL
 "http://www.amstat.org/publications/jse/datasets/fishcatch.dat";
PROC FORMAT;
  VALUE sexfmt 0="female" 1="male";
  VALUE speciesfmt 1="common bream" 2="whitefish" 3="roach"
    4="silver bream" 5="smelt" 6="pike" 7="perch";
  INVALUE misscode "NA"=. ;
RUN;
DATA fish;
  INFILE fishfile;
  INPUT obs species weight length1 length2
        length3 hgtpct widpct sex;
  INFORMAT weight sex misscode.;
  LABEL length1="Nose to tail beginning length"
        length2="Nose to tail notch length"
        length3="Nose to tail end length";
  FORMAT species speciesfmt. sex sexfmt.;
RUN;

All of the above code runs without any errors. The following code gives me errors:
TITLE "Finnish Fish: Species distribution";
PROC SGPLOT DATA=fish;
  VBAR species;
RUN;
TITLE "Finnish Fish: Weight in grams";
PROC SGPLOT DATA=fish;
  HISTOGRAM weight;
RUN;

I can't access the data right now so I don't have the specific error, but it says something along the lines of "Insufficient authorization" when I try to view the resulting plots. I will post the actual error message when I can access the data again, but until then I'm hoping that someone has encountered this error and found a solution.
Answer: Are you trying to open the file directly in SAS?  This has caused problems for me before when working on a server.  However if I open up explorer and browse to where the png file is stored (probably where your SAS program is saved) you should be able to open it from there with a variety of programs.  From there I think you can isolate the program that is giving you trouble.
Answer: I actually figured out the issue. I'm not listed as an Administrator on my school-issued laptop. As such, I cannot save to the Program Files folder. I changed the current directory for SAS and now I can access all of my plots and other output. Thanks for all of the responses, though!
Comment: I'd suggest accepting your own answer, as you've clearly solved your problem. I'm rather pleased that my guess - "This is probably a file permissions problem on your PC, rather than SAS itself", seems correct.
Comment: @EpiGrad - It took me a few error messages to actually realize what they were telling me. Next time, I will give myself a bit more time to understand the error before coming to SE.
Comment: Believe me, its a problem I'm well familiar with. Took me an embarrassingly long time once to figure out all the errors of an analysis were coming from me failing to use the right pathname for a file. At least it wasn't a semi-colon.
Answer: I've solved this problem in the past by ensuring that either my SAS working directory is set to a disk I know I can write to (especially if SAS is running on an application server like Citrix) or by submitting
ODS LISTING GPATH = "C:\Documents";
For example, assuming that you can access the C:\Documents folder.
Answer: Which version of SAS are you running?
In v. 9.3 (the latest) this ought to open a HTML window right in your session. In 9.2, you would need "ods graphics on" before the code and "ods graphics off" afterward.  However, in either version you can save the output by, e.g.
ods rtf file = "c:\myfile.rtf";

before the code and
ods rtf close;

after the code. There are other formatting options as well, including png and html and other formats.
Comment: You never need "ods graphics on" before an SGPLOT call.  Only before statistical procs.

Problem with plotting with SAS