Busca por termos fora de ordem php MYSQL

Question: Ola pessoal estava dando uma pesquisada por aqui e gostaria de saber como faço para pesquisar termos fora de ordem
exemplo possuo uma tabela com o seguinte nome: nome_prod
nela esta um exemplo de nome:
CARTÃO DE VISITA - 4X0- COUCHE BRILHO 250GRS / COM CANTO ARREDONDADO
gostaria de poder fazer uma busca onde pudesse pesquisar por exemplo:
cartão 4x0 couche arredondado
e aparece o resultado, ha alguma forma de fazer isso?
segue o meu codigo:
<?php
// Incluir aquivo de conexão
include("Connections/conn2.php");

// Recebe o valor enviado
$valor = $_GET['valor'];

// Procura titulos no banco relacionados ao valor
$sql = $conn1->query("SELECT * FROM cad_produtos WHERE nome_prod LIKE '%".$valor."%' OR codigo_prod LIKE '%".$valor."' OR tipo_prod LIKE '%".$valor."' ORDER BY codigo_prod ASC");

echo "
\n";
if ($sql) {
while ($prod = $sql->fetch_object()) {

    $variavel = $prod->tipo_prod;
    $imgse = $conn1->query("SELECT `arquivo` FROM cad_prodrutos_tipo_prod WHERE tipo_prod='$variavel' ");
    if ($imgse->num_rows > 0) {
    while($imgrow = $imgse->fetch_object()) {

$variavel_limpa = strtolower( preg_replace("/[ -]+/", "-", strtr(utf8_decode(trim($variavel)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ"),"aaaaeeiooouuncAAAAEEIOOOUUNC-")) );

        $valor = $prod->valor_uni;

$Preco = number_format($valor,2,",",".");

    ?>

<?php

    echo "
\n";
echo "
\n";
echo "

\n";
echo "\n";
echo "          \n";
echo "\n";
echo "             R$ $Preco \n";
echo "\n";
echo "
$prod->nome_prod
\n";
echo "          $prod->desc_prod\n";
echo "\n";
echo "
\n";
echo "\n";
echo "
\n";
echo "          arquivo\" alt=\"Nike 19\" class=\"card_prod__image\">\n";
         }
 } else {
    echo ""."
"."Não há produtos!"."
".""."Cadastre um para visualizar!".""."
"."
"."";
 }

echo "\n";
echo "          COD:$prod->codigo_prod\n";
echo "            $prod->tamanho1_prod cm X $prod->tamanho2_prod cm\n";
echo "             $prod->tipo_prod\n";
echo "
\n";
echo "
\n";

}
}else{

    die($conn1->error);
}

?>

Answer: Para isso é necessário fazer um filtro com LIKE. Para fazer match em partes e ter mais de uma palavra no filtro vc pode usar o % onde quiser aceitar partes que não fazem match.
ex: SELECT * FROM tabela WHERE coluna LIKE %TERMO_1%TERMO_2%
Ao fazer este filtro o SQL fará match com linhas onde o conteúdo tiver TERMO_1 E TERMO_2, sendo que poderão estar no início, no meio ou no final do conteúdo.
Considerando a sua query, seria necessário substituir os espaços por %:
SELECT * FROM cad_produtos WHERE nome_prod LIKE '%".str_replace(" ", "%", $valor)."%' OR codigo_prod LIKE '%".$valor."' OR tipo_prod LIKE '%".$valor."' ORDER BY codigo_prod ASC

Conforme solicitado nos comentários, seguem alternativas para pegar os termos fora de ordem.
1a alternativa
Criar vários LIKE com AND. Funciona de forma semelhante à anterior, mas cria várias condições de busca.
ex:
$busca_termos = "nome_prod LIKE '%" . str_replace(" ", "%' AND nome_prod LIKE '%", $valor) . "%'";
SELECT * FROM cad_produtos WHERE (".$busca_termos.") OR codigo_prod LIKE '%".$valor."' OR tipo_prod LIKE '%".$valor."' ORDER BY codigo_prod ASC

2a alternativa
Essa seria a alternativa mais "elegante", mas pode exigir alterações à sua tabela e até base, para habilitar o FULL TEXT SEARCH.
SELECT *
FROM cad_produtos
WHERE
  match(nome_prod) against ('+TERMO_1 +TERMO_2' in boolean mode)
  OR codigo_prod LIKE '%".$valor."'
  OR tipo_prod LIKE '%".$valor."'
ORDER BY codigo_prod ASC

Note que em todos os exemplos, a busca foi alterada somente na coluna nome_prod.
PS: Nesta resposta não são levados em conta outros pontos que podem ser relevantes para a realização de queries com inputs dos usuários, como "como evitar SQL injection". Recomendo que pesquise no próprio SOpt sobre perguntas relacionadas ao tema.
Comment: muito obrigado era isso mesmo que eu precisava estava quebrando a cabeça pois sou iniciante
Comment: @DanielRicardo, note que ainda é NECESSÁRIO que os termos estejam em ordem. Caso seja requisito que isso seja diferente comenta aqui que passo outra alternativa. Passei essa, mais simples, por conta da descrição da pergunta.
Comment: e como seria esse de termos desordenados
Comment: blz muito obrigado estou no aguardo
Comment: muito obrigado, agora a pesquisa ficou perfeita vou da ruma pesquisada no que vc me aconselhou, muito obrigado
Comment: desculpa incomodar mas poderia me ajudar em um outra questão?
Comment: e que eu fiz uma pergunta e desde ontem ninguém respondeu para pegar campos um campo especifico quando vc clona ele com javascript
Comment: https://pt.stackoverflow.com/questions/433698/como-especificar-o-campo-input-clonado-js


Holomorphic function $f: \mathbb{C}^{\times} \to \mathbb{C}$ with essential singularities at $0$ and $\infty$

Question: Is it true that a holomorphic function $f: \mathbb{C}^{\times} \to \mathbb{C}$ can't have an essential singularity at both $0$ and $\infty$ simultaneously? And if so, why is this true?
Assuming $f$ has essential singularities at $0$ and $\infty$, then $g(z) = f(\frac{1}{z})$ also has this property. Then I tried using Laurent series of $f$ and $g$ but didn't get anything out of it. Am I going in the wrong direction?
Comment: What about $e^{z}+e^{1/z}$?
Comment: Oh my... thank you for this example. I totally didn't think about that
Answer: Any holomorphic function $f: \mathbb{C}^{\times} \to \mathbb{C}$ can be written as a Laurent series
$$
 f(z) = \sum_{n=-\infty}^{\infty} a_n z^n \, .
$$
$f$ has

an essential singularity at $\infty$ if $a_n \ne 0$ for infinitely many $n > 0$,
an essential singularity at $0$ if $a_n \ne 0$ for infinitely many $n < 0$.

Every such $f$ can be decomposed into a sum
$$
 f(z) = g(z) + h(1/z)
$$
where $g$ and $h$ are entire functions. Then $f$ has

an essential singularity at $\infty$ if $g$ is not a polynomial,
an essential singularity at $0$ if $h$ is not a polynomial.

This gives a complete characterization of all holomorphic functions  $f: \mathbb{C}^{\times} \to \mathbb{C}$ with an essential singularity at both $0$ and $\infty$.


Modulus after X concatenation

Question: Given a number $N$ we can form another number $Y$ by concatenating $N$, $X$ times towards right. How to compute $Y \mod \space M$ efficiently?
For example: if $N = 456$ and $X = 3$ then $Y = 456456456$. Now I am wondering how to efficiently compute $Y \mod M$ where $N,M \in \mathbb{N}$.
PS: The motivation of this question comes from here.
Comment: when we are taking about concatenation it's always better to return to the arithmetic expression, I think that if we rewrite $Y$ as $N(10^6+10^3+1)$ may help but still the problem what do you mean exactly by efficiently?
Answer: Given $N$ with $n$ digits and $x$ a positive integer we have (from your definition):
$$Y=N(10^{nx}+\cdots+10^x+1) $$
so the problem of computing $Y \mod M$ can be reduced to computing $m_1=N\mod M$, computing $n$, compute $m_2=10^{nx}+\cdots+10^x+1 \mod m$, and finally the result is $m_1m_2\mod M $
I hope this answers your question.

Modulus after X concatenation


How to get user info into in visualforce / salesforce

Question: I'm trying to get user email into salesforce visualforce. here is the form, I'm very new to salesforce, please forget me for any missing information.
I'd like to know if salesforce has a public class for user email, firstname and etc
<code><apex:page standardController="AcctSeed__Cash_Disbursement_Batch__c">
   <form id="MyForm" method="POST">
              <input type="hidden" id="checkbook_var"

                UserFirtname="{!XXname}"
                UserLastname="{!XXname}"
                user-email ='{!XXEmail}'
/>
              <script src="some.js" class="checkbook-button" id="api_js">
              </script>
    </form>
</apex:page>
</code>
Answer: You are looking for the built-in "User" object.
https://developer.salesforce.com/docs/atlas.en-us.200.0.pages.meta/pages/pages_variables_global_user.htm
<code> UserFirtname={!$User.FirstName}
 UserLastname={!$User.LastName}
 user-email ={!$User.Email}
</code>


Prism Login Dialog

Question: I use Prism for a appliction and need a login dialog. For the login to be verified i need to initialize some of the application data that is loaded by Prism/MEF so i cant put it in App.xmal.cs
OnStartUp so i put the login dialog in the bootstrappers InitializeShell like this
   protected override void InitializeShell()
        {

            Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

            //// Authenticate the current user and set the default principal
            LoginDialog auth = new LoginDialog();
            auth.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            bool? dialogResult = auth.ShowDialog();

            // deal with the results
            if (dialogResult.HasValue && dialogResult.Value)
            {

                base.InitializeShell();
                Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            }
            else
            {
                Application.Current.Shutdown(-1);
            }

#if SILVERLIGHT
            Application.Current.RootVisual = (Shell)this.Shell;
#else
            Application.Current.MainWindow = (Shell)this.Shell;

            Application.Current.MainWindow.Show();
#endif
        }

I have a hard time assessing if there are any traps or drawback, anyone have a comment
Answer: Yes, I had exactly same dilemma. You have only one RootVisual and yet you have to force user to login. It's a common scenario that's not really addressed.
Here is what I did:

Code like you don't have Login. Initialize shell and load first module. In my case first module contains security stuff.
When your "System" or whatever you call it module loaded - write code in Initialize() to call your login procedure, in my case this is SecurityService.
I used RegionPopupManager (example in StockTrader RI project bundled with PRISM) to show modal popup interaction.
When logged in - just hide popup and proceed loading other modules, populating regions, etc
Comment: Thanks for god comment. As im doing a desktop application i will stick to my solution for now, but i will try yours when i get time. thanks

Prism Login Dialog


Is there a significant difference between the number of lecture sessions students attend and their final grades?

Question: I have a database with number of sessions students attended and their final grades as Fail, 3, 4 and 5. Which test should I run to find out if there is a relationship between their attendance and final grade?
Answer: The grades are ordinal-data, so you need models that can deal with that. One common model for that is ordinal logistic regression, which generalizes "normal" logistic regression to more than two categories which (importantly) are ordered. This tag wiki contains pointers to resources.


Select comma separated values from single column

Question: Below is the MySQL data table in which we have 5 lookup columns and their respective names in lookup_list column separated by commas. I want to select each lookup column name separately from lookup_list column like:
Invoice_Lookup as Lookup_1 Name
Leadlist_Lookup as Lookup_2 Name
and so on.
Comment: Post the tables and data as text [READ THIS](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557)
Comment: What is the desired result? I mean after select name from Lookup list what you want to display?
Comment: It should be like, Select
Invoice_Lookup as Lookup1 Name,
Leadlist_Lookup as Lookup_2 Name,
BTNHistory_Lookup as Lookup_3 Name,

as so on
Comment: So you want to use output of query as a column name in another query?
Comment: Yes, i want them as column.
Comment: show us exactly the desire return value you want.  Show us db schema, sample data, current and expected output.
 Please read [**How-to-Ask**](http://stackoverflow.com/help/how-to-ask)

 And here is a great place to [**START**](http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/) to learn how improve your question quality and get better answers.

 [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve)

 Try create a sample in http://rextester.com
Answer: You should normalize your data.
But by using SUBSTRING_INDEX you can split your Lookup_list into columns like so
<code>SELECT
  SUBSTRING_INDEX(SUBSTRING_INDEX(Lookup_list, ',', 1), ',', -1) AS Lookup_1
, SUBSTRING_INDEX(SUBSTRING_INDEX(Lookup_list, ',', 2), ',', -1) AS Lookup_2
, SUBSTRING_INDEX(SUBSTRING_INDEX(Lookup_list, ',', 3), ',', -1) AS Lookup_3
, SUBSTRING_INDEX(SUBSTRING_INDEX(Lookup_list, ',', 4), ',', -1) AS Lookup_4
, SUBSTRING_INDEX(SUBSTRING_INDEX(Lookup_list, ',', 5), ',', -1) AS Lookup_5
FROM
 [table]
</code>
Comment: true but don't blame me @JuanCarlosOropeza but it splits Lookup_list into columns like the topic starter asked for in his comments.... his data doesn't make sense annyhow it should be normalized
Comment: This doesnt make sense. Will print the same values for all rows.
Comment: This is exactly what I wanted. Thanks. And sorry for very vague question.


Are the critical points of a vector 2 norm the same as the norm square?

Question: Is the set of critical points of $\|Ax\|_2^2$ subject to $\|Bx\|_2^2 = 1$ the same set as the set of critical points of $\|Ax\|_2$ subject to $\|Bx\|_2 = 1$? Clearly the constraint conditions are identical.
Answer: They are not quite the same. Define the norm function $f:\mathbb{R}^n\rightarrow \mathbb{R}$. $f(x)=||x||$.
$f(x)=\sqrt{x_{1}^2+x_{2}^2+...x_{n}^2}$. Note that the critical points of a $C^1$ function ($f$ and $f'$ are continuous), are when $f'=0$. We can compute the derivative and arrive at $f'=\frac{1}{2}(x_{1}^2+...+x_{n}^2)^{-1/2}(2x_{1}+...+2x_{n})$. This is not quite the same as $f^2$ which is $||x||^2=x_{1}^2+..+x_{n}^2$


insert text using grep

Question: I have bunch of java files in a directory and want to insert package declaration in them if they already don't have them. Can I accomplish it with grep? and if yes please tell me how?
thanks.
Comment: No. You need one of the other tools. sed/awk etc.
Comment: Grep can only help you identify the files that lack a package declaration (see the `-l` switch, which will list only the filenames that match your regular expression). You could perhaps use sed to modify the files, using something like `for f in $(grep -l "expression" *); do sed -i "commands to modify $f go here"; done`.
Answer: No, you cannot. grep is officially described as print lines matching a pattern.
It is a filter, it does not output anything that wasn't there already (but it may output less). In particular, it will not be able to output a missing package declaration. You can however use it to test whether a file does have a package declaration:
 <insert your favorite "for each java file" statement>
   if egrep -q "^package " $file; then
     <insert command to insert package declaration> $file
   fi
 <end loop>

You probably are looking for awk, although perl is also a popular choice.
Answer: Try:
#!/bin/tcsh

foreach a ( `ls *.java` )

    cat ${a} | awk 'BEGIN {P=0} /package/ {P=1} /import/ {if (P == 0) {P=1;print "package X;"}} {print}' > t1
    mv t1 ${a}

end

It looks for the word package and import.
If it sees import before package then it print "package X".

insert text using grep


How do I solve this problem on application of derivatives? Please help.

Question: How do I solve this?
For the curve $x^{m+n}=a^{m-n}y^{2n}$, where a is a positive constant and $m,n$ are positive integers, prove that the $m$'th power of subtangent varies as $n$'th power of subnormal.
Comment: The first step is to understand what the problem asks. "subtangent" and "subnormal" are not terms that are commonly used these days. I am taking their definitions from Wikipedia.
Answer: The first step is to understand what the problem asks. "subtangent" and "subnormal" are not terms that are commonly used these days. I am taking their definitions from Wikipedia.
Let $P = (u,v)$ be a point on the curve $C: x^{m+n} - a^{m-n}y^{2n}=0$. The curve is singular at $(0,0)$, and since the problem involves the tangent line, implicitly, it is being assume that the statement is made for points other than $(0,0)$; therefore, let's assume $P \ne (0,0)$.
The tangent line to $C$ at $P$ is
$(m+n)u^{n+m-1}(x-u)  - a^{m-n} 2n v^{2n-1}(y-v) = 0 $.
The subtangent is $T-u$ where $T$ is found by looking for the point $(T,0)$ where the tangent line intersects the $x$ axis, i.e.: $T$ solves
$(m+n)u^{n+m-1}(T-u)  - a^{m-n} 2n v^{2n-1}(0-v) = 0$.
The normal line to $C$ at $P$ is
$a^{m-n} 2n v^{2n-1}(x-u)  + (m+n)u^{n+m-1}(y-v) = 0 $.
The subnormal is $N-u$ where $N$ is found by looking for the point $(N,0)$ where the normal line intersects the $x$ axis, i.e.: $N$ solves
$a^{m-n} 2n v^{2n-1}(N-u)  + (m+n)u^{n+m-1}(0-v) = 0 $.
Solving for $(T-u)$ and $(N-u)$, after some algebra, using the fact that $u, v$ are not arbitrary, but lay on the curve $C$, on gets $(T-u)^{m} = g (N-u)^{n}$ where $g$ is a constant that depends on $n, m, a$, but not on the point $P$, which is probably what is meant by "varies as" in the statement of the problem.


Extract titles from each page of a PDF?

Question: I am working on a project, SIGGRAPH Image Wall.
My first challenge is to figure out how to extract titles of each page in a PDF, SIGGRAPH 2013 Technical Papers First Pages (44 MB PDF).
This PDF is a compilation of the first page of each papers.
Therefore, there is a paper title for each page, a little different from
the traditional scholar paper.
Does anyone have any idea for this?
Comment: @uptownnickbrown I'm testing pdf2text library but the echo $a->output() of your pdf, print something like this 唀䐀儀嘀䐀F圀䰀刀儀嘀)刀儀)
Comment: I have the same exact requirement. I used https://pypi.org/project/pdftotext/ to get the text pagewise and it's working great but it doesn't give out any API to get the title for each page. How did you achieve it?
Answer: I think you can accomplish this using any of a number of text extraction approaches, though I will caution that getting to 100% accuracy will be tricky...
Some possible tools to use:

pdftotext or pdf2txt - Simple and easy cross-platform extraction utilities.
PDFNet - Robust SDK for digging into PDFs and pulling out exactly the data you want.
Perl modules: PDF::API2, CAM::PDF - I'm a Perl guy so I'd go this route, but I'm sure similar libraries exist in Python, Ruby, etc.

Your source pages look reasonably consistent - I feel like you'll be able to make some smart guesses about where on the page your content will be and what it'll look like.  I'd try this out:

Inspect the PDF manually to figure out the title font name and size.
Extract text information for the top portion of the page (something like the top 150 pixels).  Make sure to extract font info.
This should get all of your title text and maybe some author names. Parse this data (either within the script you write, or in the XML output files from pdftotext, etc.), keeping only the words that match your title font info.

If the title font varies, you'll need to guess what the title font is for each page and differentiate it from author names (the only other content you should get from the top of the page) which you can probably do simply by comparing font sizes.

Extract titles from each page of a PDF?


How can I model flips until N successes?

Question: You and I decide to play a game where we take turns flipping a coin. The first player to flip 10 heads in total wins the game. Naturally, there is an argument about who should go first.
Simulations of this game show that the player to flips first wins 6% more than the player who flips second (the first player wins approx 53% of the time).  I'm interested in modelling this analytically.
This isn't a binomial random variable, as there are no fixed number of trials (flip until someone gets 10 heads). How can I model this?  Is it the negative binomial distribution?

So as to be able to recreate my results, here is my python code:
import numpy as np
from numba import jit

@jit
def sim(N):

    P1_wins = 0
    P2_wins = 0

    for i in range(N):

        P1_heads = 0
        P2_heads = 0
        while True:

            P1_heads += np.random.randint(0,2)

            if P1_heads == 10:
                P1_wins+=1
                break

            P2_heads+= np.random.randint(0,2)
            if P2_heads==10:
                P2_wins+=1
                break
    return P1_wins/N, P2_wins/N

a,b = sim(1000000)

Comment: When you toss a coin until $r$ failures and then look at the distribution of the number of successes that happen before finishing such experiment, then this is by definition [negative binomial distribution](https://en.wikipedia.org/wiki/Negative_binomial_distribution).
Comment: Did you get this question from the FiveThirtyEight [Riddler Express](https://fivethirtyeight.com/features/can-you-time-the-stoplight-just-right/)?
Comment: I cannot reproduce the 2% value.  I find that the first player wins $53.290977425133892\ldots\%$ of the time.
Comment: @whuber yes, I believe you are right.  I ran my simulation fewer times than I should.  My results are commensurate with yours.
Comment: If one wins 53% of the time, the other should be 47%, so shouldn't the description read "the first player wins 6% more than the second player," or "3% more than half the time" ?  Not (as it currently says) "3% more than the player who flips second"
Comment: @foutandabout I did.  Usually the express problems are easy to code, but of late I wanted to try and find analytical answers.
Comment: @JesseM Right, my mistake,
Answer: The distribution of the number of tails before achieving $10$ heads is Negative Binomial with parameters $10$ and $1/2$.  Let $f$ be the probability function and $G$ the survival function: for each $n\ge 0$, $f(n)$ is the player's chance of $n$ tails before $10$ heads and $G(n)$ is the player's chance of $n$ or more tails before $10$ heads.
Because the players roll independently, the chance the first player wins with rolling exactly $n$ tails is obtained by multiplying that chance by the chance the second player rolls $n$ or more tails, equal to $f(n)G(n)$.
Summing over all possible $n$ gives the first player's winning chances as
$$\sum_{n=0}^\infty f(n)G(n) \approx 53.290977425133892\ldots\%.$$
That is about $3\%$ more than half the time.
In general, replacing $10$ by any positive integer $m$, the answer can be given in terms of a Hypergeometric function: it is equal to
$$1/2 + 2^{-2m-1} {_2F_1}(m,m,1,1/4).$$
When using a biased coin with a chance $p$ of heads, this generalizes to
$$\frac{1}{2} + \frac{1}{2}(p^{2m})  {_2F_1}(m, m, 1, (1 - p)^2).$$

Here is an R simulation of a million such games.  It reports an estimate of $0.5325$.  A binomial hypothesis test to compare it to the theoretical result has a Z-score of $-0.843$, which is an insignificant difference.
n.sim <- 1e6
set.seed(17)
xy <- matrix(rnbinom(2*n.sim, 10, 1/2), nrow=2)
p <- mean(xy[1,] <= xy[2,])
cat("Estimate:", signif(p, 4),
    "Z-score:", signif((p - 0.532909774) / sqrt(p*(1-p)) * sqrt(n.sim), 3))

Comment: Just as a note that may not be obvious at a glance, our answers agree numerically: (.53290977425133892 - .5) * 2 is essentially exactly the probability I gave.
Comment: @Dougal Thank you for pointing that out.  I looked at your answer, saw the $6.6\%$, and knowing that it did not agree with the form of the answer requested in the question, I did not recognize that you had computed correctly.  In general it's a good idea to frame an answer to any question in the form that is requested, if possible: that makes it easy to recognize when it's correct and easy to compare answers.
Comment: @whuber I was responding to the phrase "Simulations of this game show that the player to flips first wins 2% (EDIT: 3% more after simulating more games) more than the player who flips second". I'd interpret "wins 2% more" as $\Pr(A\text{ wins}) - \Pr(B\text{ wins}) = 2\%$; the correct value is indeed 6.6%. I'm not sure of a way to interpret "wins 2% more" means "wins 52% of the time", though apparently that is what was intended.
Comment: @whuber Agreed. Unfortunately, I answered the question before the code was posted, and didn't run a simulation myself. :)
Comment: @Dougal I agree that the OP's description is confusing and even wrong.  However, the code and his result made it clear he meant "3% more than half the time" rather than "3% more than the other player."
Answer: We can model the game like this:

Player A flips a coin repeatedly, getting results $A_1, A_2, \dots$ until they get a total of 10 heads. Let the time index of the 10th heads be the random variable $X$.
Player B does the same. Let the time index of the 10th heads be the random variable $Y$, which is an iid copy of $X$.
If $X \le Y$, Player A wins; otherwise Player B wins. That is, \begin{align}
\Pr(A\text{ wins})&= \Pr(X \ge Y) = \Pr(X > Y) + \Pr(X = Y)\\
\Pr(B\text{ wins})&= \Pr(Y > X) = \Pr(X > Y).
\end{align}

The gap in the win rates is thus
$$
\Pr(X = Y) = \sum_k \Pr(X = k, Y = k) = \sum_k \Pr(X = k)^2
.$$
As you suspected, $X$ (and $Y$) are distributed essentially according to a negative binomial distribution. Notations for this vary, but in Wikipedia's parameterization, we have heads as a "failure" and tails as a "success"; we need $r = 10$ "failures" (heads) before the experiment is stopped, and success probability $p = \tfrac12$. Then the number of "successes," which is $X - 10$, has $$\Pr(X - 10 = k) = \binom{k + 9}{k} 2^{-10 - k},$$
and the collision probability is
$$
\Pr(X = Y)
= \sum_{k=0}^\infty \binom{k + 9}{k}^2 2^{-2k - 20}
,$$
which Mathematica helpfully tells us is $\frac{76\,499\,525}{1\,162\,261\,467} \approx 6.6\%$.
Thus Player B's win rate is $\Pr(Y > X) \approx 46.7\%$,
and Player A's is $\frac{619\,380\,496}{1\,162\,261\,467} \approx 53.3\%$.
Comment: (+1) I like this approach better than the one I posted because it is computationally simpler: it requires only the probability function, which has a simple expression in terms of binomial coefficients.
Comment: I've submitted an edit replacing the last paragraph questioning the difference from the other answer with an explanation of how their results are actually the same.
Comment: the heads need not be in a row, just 10 total.  I assume that is what you are fixing.
Answer: Let $E_{ij}$ be the event that the player on roll flips i heads before the other player flips j heads, and let $X$ be the first two flips having sample space $ \{ hh,ht,th,tt\}$ where h means heads and t tails, and let $p_{ij} \equiv Pr(E_{ij})$.
Then  $p_{ij}=Pr(E_{i-1j-1}|X=hh)*Pr(X=hh)+Pr(E_{i-1j}|X=ht)*Pr(X=ht)+Pr(E_{ij-1}|X=th)*Pr(X=th)+Pr(E_{ij}|X=tt)*Pr(X=tt)$
Assuming a standard coin $Pr(X=*)=1/4$ means that $p_{ij}=1/4*[p_{i-1j-1}+p_{i-1j}+p_{ij-1}+p_{ij}]$
solving for $p_{ij}$, $= 1/3*[p_{i-1j-1}+p_{i-1j}+p_{ij-1}]$
But $p_{0j}=p_{00}=1$ and $p_{i0}=0$, implying that the recursion fully terminates. However, a direct naive recursive implementation will yield poor performance because the branches intersect.
An efficient implementation will have complexity $O(i*j)$ and memory complexity $O(min(i,j))$. Here's a simple fold implemented in Haskell:
Prelude> let p i j = last. head. drop j $ iterate ((1:).(f 1)) start where
  start = 1 : replicate i 0;
  f c v = case v of (a:[]) -> [];
                    (a:b:rest) -> sum : f sum (b:rest) where
                     sum = (a+b+c)/3
Prelude> p 0 0
1.0
Prelude> p 1 0
0.0
Prelude> p 10 10
0.5329097742513388
Prelude>

UPDATE: Someone in the comments above asked whether one was suppose to roll 10 heads in a row or not. So let $E_{kl}$ be the event that the player on roll flips i heads in a row before the other player flips i heads in a row, given that they already flipped k and l consecutive heads respectively.
Proceeding as before above, but this time conditioning on the first flip only,
$p_{k,l} = 1-1/2*[p_{l,k+1}+p_{l,0}]$ where $p_{il}=p_{ii}=1, p_{ki}=0$
This is a linear system with $i^2$ unknowns and one unique solution.
To convert it into an iterative scheme, simply add an iterate number $n$ and a sensitivity factor $\epsilon$:
$p_{k,l,n+1} = 1/(1+\epsilon)*[\epsilon*p_{k,l,n} +1-1/2*(p_{l,k+1,n}+p_{l,0,n})]$
Choose $\epsilon$ and $p_{k,l,0}$ wisely and run the iteration for a few steps and monitor the correction term.


How to plot ROC curve for multiclass Xgboost using python?

Question: In my model, the classes are [0,1,2,3].
As ROC is used in binary classification or OneVsRest multiclass problems, I want to plot ROC curve for classes[0,1],[0,2],[0,3]. What should I do?
Comment: can you add some data ?
Answer: ROC curves are modelled for binary problems. OneVsAll is one method to do so where your main class in considered as positive label and others as negative.According to your problem you want to model the problem as OneVsOne which is good. Since this is another method for making binary classifers work for your multiclass classification.
Caution : OneVsOne method is computationally expensive.
See here for further reading.
For classes [0,1,2] it would return [0,1], [0,2],[1,2] i.e for 3 classes it would return 3(3-1)/2 i.e 3 classifiers. Now you have 3 binary classifier. I hope it is easy for you to follow from here on how to get your ROC curves from this point.


Multiplicação de 3 matrizes

Question: Tenho que fazer a multiplicação de 3 matrizes com a validação de que dá mesmo para fazer, em uma função. Estou tentando fazer a matriz 1 e 2 primeiro e pegar o resultado para fazer a 3. Mas está dando errado e também não consigo chamar o resultado no main.
 public static int[][] mult(int linha, int coluna, int linha2, int coluna2, int linha3, int coluna3, int[][] matriz, int[][] matriz2, int[][] matriz3) {

            if(matriz[0].length == matriz2.length){
                int[][] matrizR = new int[linha][coluna2];

                for(int i = 0; i < linha; i++){
                    for(int j = 0; j < coluna2; j++)
                        for(int k = 0; k < linha2; k++)
                            matrizR[i][j] = matriz[i][k] * matriz2[k][j];
                }
                return matrizR;
            }
            if(matrizR[0].length == matriz3.length){
               int[][] resultado = new int[linha][coluna3];

               for(int i = 0; i < linha; i++){
                   for(int j = 0; j < coluna3; j++)
                       for(int k = 0; k < linha2; k++)
                           resultado[i][j] = matrizR[i][k] * matriz3[k][j];
               }
               return resultado;
           }
      }

Answer: Para multiplicar 2 matrizes, a quantidade de colunas da primeira deve ser igual à quantidade de linhas da segunda. Ou seja, se a primeira matriz é M x N (M linhas e N colunas), a segunda deve ser N x P (N linhas e P colunas) e o resultado será uma matriz M x P (M linhas e P colunas).
De qualquer forma, eu acho mais fácil fazer um método que multiplica 2 matrizes, e aí você pode usar para multiplicar quantas quiser depois. E o algoritmo está errado, no último for você tem que somar ao valor da célula, mas você está sobrescrevendo-o (veja aqui o algoritmo).
Nos casos abaixo não estou verificando se todas as linhas da matriz possuem a mesma quantidade de colunas (estou assumindo que isso já foi verificado antes). E também não precisa passar a quantidade de linhas e colunas, pois é possível obter isso das próprias matrizes:
// multiplica apenas 2 matrizes
public static int[][] mult(int[][] m1, int[][] m2) {
    if (m1[0].length != m2.length) { // se a quantidade de coluunas de m1 é diferente da quantidade de linhas de m2
        throw new IllegalArgumentException("Não é possível multiplicar, tamanhos incompatíveis");
    }

    int[][] result = new int[m1.length][m2[0].length];
    for (int lin = 0; lin < result.length; lin++) {
        for (int col = 0; col < result[lin].length; col++) {
            int valor = 0;
            for (int i = 0; i < m2.length; i++) {
                valor += m1[lin][i] * m2[i][col]; // soma ao valor ("+=" em vez de "=")
            }
            result[lin][col] = valor;
        }
    }
    return result;
}

Então, se você quiser multiplicar 3 matrizes, basta usar o método acima, multiplicando de 2 em 2:
// multiplica 3 matrizes
public static int[][] multiplicaTrezMatrizes(int[][] m1, int[][] m2, int[][] m3) {
    // primeiro multiplica m1 e m2
    int[][] result = mult(m1, m2);

    // depois multiplica por m3
    return mult(result, m3);
}

Ou, se quiser fazer um método genérico que recebe qualquer quantidade de matrizes:
public static int[][] multiplicaVariasMatrizes(int[][]... matrizes) {
    int[][] result = matrizes[0]; // pega a primeira matriz
    for (int i = 1; i < result.length; i++) { // vai multiplicando as matrizes
        result = mult(result, matrizes[i]);
    }
    return result;
}

// e no main:
int[][] m1 = { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } };
int[][] m2 = { new int[] { 1, 2, 3, 4 }, new int[] { 5, 6, 7, 8 } };
int[][] m3 = { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 }, new int[] { 7, 8 } };

System.out.println(Arrays.deepToString(multiplicaVariasMatrizes(m1, m2, m3)));

Multiplicação de 3 matrizes


Is there some function of $n$ that is a multiply of $\phi(n^2)$?

Question: Given $n = pq$, where $p$ and $q$ are prime and $\phi(n^2) = (p^2-p)(q^2-q)$ (The Euler Totient function). Is there some combination of $n$s such that $\phi(n^2)|f(n)$
$f$ can be anything (greater than$\phi(n^2)$)given it only uses $n$ and not $p$ or $q$ separately and results in an integer for the input of $n$.
I have tried to find some such $f$ by manipulating $\phi(n^2)$ but haven't had any luck.
Anyway of showing such an $f$ doesn't exist would also be helpful
Thanks
Edit:
I am trying to adapt this answer here:
https://crypto.stackexchange.com/questions/58047/equality-check-in-homomorphic-encryption
where I am taking$\mod n^2$ rather than$\mod p$  I am looking to replace the $p-1$ in $1 - (A - B)^{p-1}$ with $f(n)$ that still returns 0 if $A \neq B \mod n^2$. to do this I am applying:
Euler's Theorem: Let $m \in N$. For any $a ∈ Z$ such that $hcf(a, m) =
1$, we have $a^
{\phi(m)} ≡ 1 \mod m$, where $φ(m)$ is the Euler totient function.
I understand that this will occasionally fail (i.e. if $A-B = p \mod n) which is ok for me
Since I will be applying this $f(n)$ to check if $A=B$ I need it to be computationally efficient (e.g. in time polynomial in $\log n$) without knowing $p$,$q$. so an $f$ requiring the decomposition of $n$ won't work as this would take too long/ completely remove the point of the encryption
Comment: does $f(n) = 0$ work?
Comment: How about $(\lfloor n/2 \rfloor )!^2$
Comment: Then also $f(n)=2\phi(n^2)$ is possible. I think you need to clarify what you really want in the end, and how you want to apply it.
Comment: You should probably specify in the question that you want $f(n)$ to be computable efficiently (e.g. in time polynomial in $\log n$) without knowing $p,q$.
Comment: $\phi(n^2)=n\phi(n).................$
Comment: Let $f(n)=f(pq)=k(p^2-p)(q^2-q)$ for some positive integer $k$.
Comment: sorry, but how is $f$ in terms of $n$. $f$ can't include $p$ or $q$ seperately
Comment: But $n=pq$ always, or not? We have $\phi(n^2)=n^2+n-(p+q)n$, and we cannot express it easily only in terms of $n$.
Comment: Yes but assuming p and q are not known. This is for cryptography where p and q are massive so finding them is hard so I am looking for a function that uses only n as this is given
Comment: Why do you think there is such a function $f(n)$, which is of any use? Why can't we take $f(n)=\phi(n^2)$. This is only in $n$.
Comment: Sorry I should have specified $f(n)>\phi(n^2)$
Comment: Yeah that's also possible I guess, I was thinking that maybe an expression that sort of didn't talk about prime factorization was sought after or something.
Comment: I will add more to the question
Comment: yeah for using $\phi(n^2)$  I was trying to avoid as the only expression for it that I know uses the prime decomposition of n which I am trying to avoid.
Comment: This requires $\phi(n)$ which relies on p and q or at least a speeding factorisation of n which I think isn't possible
Comment: [Cross-posted to crypto-SE](https://crypto.stackexchange.com/q/92266/555), where it might be more on-topic
Comment: Thanks, wasn't sure where to put it
Comment: @Daniel I figured that out too, but in my case only after looking at http://oeis.org/A002618
Answer:
Is there some combination of $n$s such that $\phi(n^2) | f(n)$

One would hope that there is no efficient way to compute a nontrivial $f(n)$ without apriori knowledge of the factorization of $n$ (or some equivalent knowledge, such as the knowledge of $\phi(n)$)
The reason is that knowledge of any (nonhuge) multiple of $\phi(n)$ allows you to efficiently factor $n$; hence you would have just broken RSA (and Paillier).
The method to factor is fairly straight-forward; if you know a value $z = k \phi(n)$ (for some unknown $k > 0$); $z$ has the property that $g^z \equiv 1 \pmod n$ for any $g$ relatively prime to $n$.
What you do is compute the odd value $w = z / 2^{\lambda}$ (where $\lambda$ is number of factors of 2 within $z$; because $\phi(n)$ is even, we have $\lambda > 0$), and then for a random $g$, we compute $g^w \bmod n$; if that is neither 1 nor -1 (aka $n-1$), we repeatedly square the result $\lambda$ times.  If one of the squarings results in a 1 but the previous value was not $-1$, then that gives the factorization, becaues if $g^2 \equiv 1 \bmod n$, and $g$ is neither $1$ nor $-1$, then $\gcd( g-1, n)$ and $\gcd( g+1, n)$ are nontrivial factors of $n$.
It is straight-forward to show that this yields nontrivial factors for at least half of the random $g$ values; this is also efficient, and so is a practical factorization method (assuming that we know $z$ in the first place)

Also, you are doing this in order to generate a Paillier based function that converts (most) nonzero values to 1 and zero values to 0.  With such a function, Paillier would become a fully homomorphic function (that is, you can compute any [1] function homomorphically.  We can see this because we could generate a two input NAND function homomorphically by, given $E_k(A)$ and $E_k(B)$ (where both $A, B \in \{0, 1\}$) by computing $E_k(2-A-B)$ (which Paillier allows us to do), and then applying your magic function to the result.  And, since NAND is complete, that means we can express any circuit as a series of NAND functions.
A Paillier-based fully homomorphic encryption would be a big deal; it doesn't look likely in practice.
[1]: Well, anything that can be described with a bounded circuit, which turns out to be just about anything we care about in practice
Answer: A bit more simplistically, for semiprime $n=pq$, $\phi(n^2)=p(p-1)q(q-1)=pq(pq-p-q+1)=n^2-n(p+q)+n$
In order to construct a function based solely on $n$, you are faced with explicitly knowing or discovering something about $p$ and $q$ based only on your knowledge of $n$. As poncho indicated in his answer, the problem devolves to factoring $n$.
Comment: However, he isn't asking for a way to compute $\phi(n^2)$, but rather $k \phi(n^2)$, for potentially a huge $k$; this large $k$ value blocks straight-forward algebraic approaches...
Comment: Actually, he's asking if there are two functions, $f(n)$ and $g(n)$, such that $f(n)=g(n)\cdot \phi(n^2)$. The possibility that $g(n)=k$ a constant can probably be dismissed. Finding a suitable $g(n)$ that is not dependent on factoring $n$ does not seem likely to me, but I have no proof that it can't be done.
Comment: I had assumed that $k$ was dependent on $n$, so we're on the same page there.  As for proof that you can't find a $g(n)$ that doesn't depend on factoring, well, see my answer...


WAMP limit log files size

Question: Is there any functionality in wamp to limit the access and error log to 20 MB? i.e. it should be truncated after 20 MB.
Answer: usually (on linux) the log are managed by another system (for example a log rotate), it's not apache which manage them itself - if you understand french someone did logrotate.bat and shared it on the wampserver forum - thus you can use a log rotate system of windows too
Hope this could help

WAMP limit log files size


Check multiple file exists or not using ANT

Question: I am using ANT to check count for set of files in two jars.
I am not able to check whether the files of same pattern exists or not.
for e.g. I have 2 files like /host/user/dir1/ABC1.txt and /host/user/dir1/ABC2.txt.
now i want to check whether the file of pattern "/host/user/dir1/ABC*" present or not ??
I can check individual file /host/user/dir1/ABC1.txt, using available tag, but not able to check the files for specific pattern.
thanks in advance.
For individual file, following works fine:
<if>
    <available file="${client.classes.src.dir}/${class_to_be_search}.class"/>
    <then>
         <echo> File ${client.classes.src.dir}/${class_to_be_search}.class FOUND in src dir

         </echo>
         <echo> Update property client.jar.packages.listOfInnerClass</echo>
    </then>
    <else>
         <echo> File ${client.classes.src.dir}/${class_to_be_search}.class NOT FOUND      in src dir.
         </echo>
    </else>
</if>

But i want to search for multiple files:
something like :  ${dir.structure}/${class_to_be_search}$*.class
Comment: Can you add code that you actually use (this one with individual file check)?
Comment: For individual file, following works fine:

 File ${dir.structure}/${class_to_be_search}.class FOUND in src dir.

 Update property client.jar.packages.listOfInnerClass

 File ${client.classes.src.dir}/${class_to_be_search}.class NOT FOUND  in src dir.

I want to search ${dir.structure}/${class_to_be_search}$*.class
Comment: Edit your question and paste it there. Don't forget to format this into readable form.
Comment: @Patryk Roszczyniała : questiion edited with example.
Answer: The if task is not part of core ANT.
The following example shows how it can be done using the ANT condition task. You can use whatever pattern you want in the fileset. The target execution is subsequently conditional on how the "file.found" property has been set:
<project name="demo" default="run">

    <fileset id="classfiles" dir="build" includes="**/*.class"/>

    <condition property="file.found">
        <resourcecount refid="classfiles" when="greater" count="0"/>
    </condition>

    <target name="run" depends="found,notfound"/>

    <target name="found" if="file.found">
        <echo message="file found"/>
    </target>

    <target name="notfound" unless="file.found">
        <echo message="file not found"/>
    </target>

</project>

Comment: You have made target="run" as default. This means it will run first by default. Right? This "run" target is depend on found/notfound targets which in-turn uses "file.found" condition.
i want to know when this condition task gets executed and set file.found=true/false ??
Comment: @MayurSharma That is the purpose of the "condition" task. It's executed when the build is initialised and sets the property. This property in turn controls whether the "found" and "notfound" targets do anything.


Override title with field label instead of key inside a views contextual filter

Question: I have a soccer team Drupal 7 site where I keep track of the players using a user role.  I have a view of the players which grids their profile pics and I'm very happy with it.  It's URL is /players
Now I want to divide the players into separate groups.  My first stab at this was to add a user_program field onto the User content type.  I added this field of type List(text), and gave it keys/values like:
youth_competitive_program|Youth Competitive Program
primary_competitive_programe|Primary Competitive Program
I then added a Contextual Filter so that I have /players/youth_competitive_program and such.  Works very well.  Except:  when I tell those views to override the title using %1 I get the key instead of the value.  What I really want is my human readable value up there, not the key.
Answer: edit your Contextual Filter check Specify validation criteria in Validator check PHP code and enter following:
if ($argument == 'youth_competitive_program') {
  $handler->options['title'] = 'Youth Competitive Program';
  return true;
} else if ($argument == 'primary_competitive_programe') {
  $handler->options['title'] = 'Primary Competitive Program';
  return true;
}
return false;

there is another similar way:
if (!empty($argument)) {
  $handler->options['title'] = t($argument);
  return true;
}

return false;

and translate them, so if you add more option to your user_program fields, this code will work better.
but there is another option yet:
$field = field_info_field('field_user_program');
if (array_key_exists($argument, $field['settings']['allowed_values'])) {
  $handler->options['title'] = $field['settings']['allowed_values'][$argument];
  return true;
}
return false;

I will select the last way
Comment: This is actually pretty good, don`t understand the downvotes. Downvoting is constructive when supported with a comment on why the post is considered less viable. Unexplained downvotes are pretty much worthless.
Comment: Well notwithstanding the downvotes this is the best answer for me for sure!  Thank you very much and enjoy the bounty!
Comment: Don't forget to check `Override title`, if not your title won't be updated. If you like to mess around you can add `$handler->options['title_enable'] = 1;` instead.
Answer: Why don't you use Human readable values for both the key and value of the list?  Views should be able to accept an argument with hyphens and substitute spaces in the title.  You may have to modify the template to get title cases in your title using something like php's ucwords().
Comment: This would be OK if you haven't already created the field but for an existing field it is not trivial to change the keys of the options.


Criar banner interativo personalizado HTML estilo hover overlay

Question: Olá, gostaria de criar um banner no estilo hover overlay semelhante ao que se encontra neste site:
http://www.gruporedservicos.com.br/

Basicamente, ao passar o mouse por cima da imagem, a camada onde está escrito "Experiencia" se move, e ao retirar o mouse de cima da imagem, ela volta ao ponto de origem.
Quebrei a cabeça tentando fazer algo semelhante. Sei que o site roda wordpress, então caso isso seja um plugin, aceito nomes.
Obrigado desde já.
Answer: Exemplo usando apenas css, ao passar o mouse em cima o tamanho da div filha será 100% da div pai

.container {
  position: relative;
  width: 25%;
}

.imagem {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 30px;
  transition: .5s ease;
}

.container:hover .overlay {
  height: 100%;
}

.texto {
  white-space: nowrap;
  color: white;
  font-size: 20px;
  position: absolute;
  overflow: hidden;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

Texto aqui

Comment: AI vai da sua criatividade, eu não posso fazer por você
Comment: Perfeito! mas como fazer pra aparecer apenas um titulo enquanto o hover nao é executado? como no site citado acima. Obrigado desde já!


fast lookup for the last element in a Django QuerySet?

Question: I've a model called Valor. Valor has a Robot. I'm querying like this:
Valor.objects.filter(robot=r).reverse()[0]

to get the last Valor the the r robot. Valor.objects.filter(robot=r).count() is about 200000 and getting the last items takes about 4 seconds in my PC.
How can I speed it up? I'm querying the wrong way?
Comment: Do you have a very ornate structure of ForeignKey, OneToOneField, or ManyToManyField relationships?
Comment: fwiw, this is slow because you're selecting everything in the `valor` table, instantiating a django model instance for each entry when you convert it to a list (via `.reverse`), and taking only the first item in the list.
Answer: The optimal mysql syntax for this problem would be something along the lines of:
SELECT * FROM table WHERE x=y ORDER BY z DESC LIMIT 1

The django equivalent of this would be:
Valor.objects.filter(robot=r).order_by('-id')[:1][0]

Notice how this solution utilizes django's slicing method to limit the queryset before compiling the list of objects.
Answer: If none of the earlier suggestions are working, I'd suggest taking Django out of the equation and run this raw sql against your database.  I'm guessing at your table names, so you may have to adjust accordingly:
SELECT * FROM valor v WHERE v.robot_id = [robot_id] ORDER BY id DESC LIMIT 1;

Is that slow?  If so, make your RDBMS (MySQL?) explain the query plan to you.  This will tell you if it's doing any full table scans, which you obviously don't want with a table that large. You might also edit your question and include the schema for the valor table for us to see.
Also, you can see the SQL that Django is generating by doing this (using the query set provided by Peter Rowell):
qs = Valor.objects.filter(robot=r).order_by('-id')[0]
print qs.query

Make sure that SQL is similar to the 'raw' query I posted above.  You can also make your RDBMS explain that query plan to you.
Comment: qs.query (or .query.as\_sql()) is definitely the way to go for anyone trying to track down this issue from the DB side.  People that are wondering about how slicing / sql limit, order_by(), and filter() are handled at a low level should play with this a bit.
Answer: It sounds like your data set is going to be big enough that you may want to denormalize things a little bit.  Have you tried keeping track of the last Valor object in the Robot object?
class Robot(models.Model):
    # ...
    last_valor = models.ForeignKey('Valor', null=True, blank=True)

And then use a post_save signal to make the update.
from django.db.models.signals import post_save

def record_last_valor(sender, **kwargs):
    if kwargs.get('created', False):
        instance = kwargs.get('instance')
        instance.robot.last_valor = instance

post_save.connect(record_last_valor, sender=Valor)

You will pay the cost of an extra db transaction when you create the Valor objects but the last_valor lookup will be blazing fast.  Play with it and see if the tradeoff is worth it for your app.
Comment: This is a good solution to the design problem, but it leaves open the question as to why his design was performing poorly even when given more appropriate queries than his original one. With proper indexing, ordering and limits, his original normalized design should have been 'blazing fast' too. I hope the OP updates the question with his findings.
Comment: Django asked me to change it to:
def record_last_valor(sender, **kwargs):
    if created:
        instance.robot.last_valor = instance
Comment: I agree Joe, this does not try to answer the underlying DB performance issues.  It seemed like there was already a fair amount of talk about checking indexes and your suggestion about qs.query looked like the best possible way to investigate the checking indexes approach.
Comment: I've tried this approach and I can't get the value saved in the DB.
Comment: Are you sure record_last_valor is being called?  Try adding a `print locals()` or `import pdb; pdb.set_trace()` to record_last_valor.  Or maybe my example code needed an instance.robot.save().
Answer: Well, there's no order_by clause so I'm wondering about what you mean by 'last'. Assuming you meant 'last added',
Valor.objects.filter(robot=r).order_by('-id')[0]

might do the job for you.
Comment: In the Valor model I have Meta: ordering = ('id',). Does this make your query the same as mine?
Comment: Do you have an appropriate index on your valor table for robot_id?
Answer: django 1.6 introduces .first() and .last():
https://docs.djangoproject.com/en/1.6/ref/models/querysets/#last
So you could simply do:
Valor.objects.filter(robot=r).last()

Answer: Quite fast should also be:
qs = Valor.objects.filter(robot=r) # <-- it doesn't hit the database
count = qs.count()                 # <-- first hit the database, compute a count
last_item = qs[ count-1 ]          # <-- second hit the database, get specified rownum

So, in practice you execute only 2 SQL queries ;)
Answer: Model_Name.objects.first()

//To get the first element
Model_name.objects.last()

//For get last()
in my case, the last is not work because there is only one row in the database
maybe help full for you too :)
Answer: Is there a limit clause in django?  This way you can have the db, simply return a single record.
mysql
 select * from table where x = y limit 1

sql server
 select top 1 * from table where x = y

oracle
 select * from table where x = y and rownum = 1

I realize this isn't translated into django, but someone can come back and clean this up.
Comment: limit and reverse, you mean. Right?
Comment: In Django you limit with Python's slicing sintax. Valor.objects.filter(robot=r).reverse()[0:1].get()
Comment: I've just tried that last query and is as slower as my original one.
Answer: The correct way of doing this, is to use the built-in QuerySet method latest() and feeding it whichever column (field name) it should sort by. The drawback is that it can only sort by a single db column.
The current implementation looks like this and is optimized in the same sense as @Aaron's suggestion.
def latest(self, field_name=None):
    """
    Returns the latest object, according to the model's 'get_latest_by'
    option or optional given field_name.
    """
    latest_by = field_name or self.model._meta.get_latest_by
    assert bool(latest_by), "latest() requires either a field_name parameter or 'get_latest_by' in the model"
    assert self.query.can_filter(), \
            "Cannot change a query once a slice has been taken."
    obj = self._clone()
    obj.query.set_limits(high=1)
    obj.query.clear_ordering()
    obj.query.add_ordering('-%s' % latest_by)
    return obj.get()


Is there a module that displays a field only when a condition is met?

Question: I am looking a module that will only display some fields if a condition is met. Basically only administrators or editors should be able to see those fields in the display. In editing mode it should be alright as only editors have the right to view those fields.
I have checked the documenation for  Conditional Fields module and Field Conditional States which enable this but they do it based on field contents, but I want run if a PHP condition is met. Are there any other similar modules which implement this?
Comment: Hi you can also do it without a module? is there any specific reason why you require module.
Comment: @DEVARAJJOHNSON I hve settled on the Field Permissions module, but can you explain how it would be done without a module?
Comment: yes, in form_alter use $form['field_name']['#access'] = FALSE;  will hide the field in the form.
Answer: Have a look at the Field permissions module. It allows for role-based conditional display.


$ \lim_{x\to 0} \left(\frac{5}{2+\sqrt{9+x}}\right)^{\operatorname{cosec} x}$

Question: I solved this question in two different ways and got two different answers to it.
Method #1:
The question is of the form $1^\infty$.
So, to solve it, I took it in the power of e and wrote the numerator in the natural logarithmic function.
Now, according to the Maclauren series, $$\lim_{x\to 0} \left(\frac{\ln (x+1)}{x}\right) = 1$$
Using this result, then rationalising the power and then using the result $$\lim_{x\to 0} \left(\frac{\sin x}{x}\right) = 1$$
we get the answer as $e^{-1/30}$
Method #2:
In this method, I decided to go by the basics instead.
I took out the left-hand limit and the right-hand limit separately.
If we want the right-hand limit, then we will have to put $x = 0^+$.
Upon doing so, the denominator becomes slightly greater than the numerator, and we can say that the part inside the parenthesis is slightly less than 1.
Now $cosec 0^+$ tends to  $\infty$
Also, a number less than 1 raised to the power of infinity tends to 0.
$\therefore$ The right-hand limit is zero.
In a similar manner when we take out the left-hand limit, that also comes out to be zero.
Hence, by this method, the answer should be 0.
Please help.
Comment: "a number less than 1 raised to the power of infinity tends to 0" This is where you go wrong. Consider that, for example, $$\lim\left(1-\frac4n\right)^n=e^{-4}$$ but $$\lim\left(1-\frac4{\sqrt n}\right)^n=0$$ and $$\lim\left(1-\frac4{n^2}\right)^n=1$$ although $$\lim\left(1-\frac4n\right)=\lim\left(1-\frac4{\sqrt n}\right)=\lim\left(1-\frac4{n^2}\right)=1$$
Comment: Welcome to Math StackExchange. While your question is good, please change your question title to describe your doubt better.
Comment: Please consider using \left( and \right) to get brackets that match the height of what's between them:
$$\left(\frac{5}{x^2}\right)$$
instead of
$$(\frac{5}{x^2})$$
Answer: You need to work out what happens to
\begin{align}
\ln(2+\sqrt{9+x})
&=\ln(2+3\sqrt{1+(x/9)}\,)\\
&=\ln(2+3(1+x/18+o(x)))\\
&=\ln(5+x/6+o(x))\\
&=\ln 5+\ln(1+x/30+o(x))\\
&=\ln 5+x/30+o(x)
\end{align}
Thus the logarithm of your function is
$$
\frac{\ln 5-\ln(2+\sqrt{9+x})}{\sin x}=
\frac{\ln 5-\ln 5-x/30+o(x)}{x+o(x)}
$$
and the limit (of the logarithm) is $-1/30$. So the given limit is $e^{-1/30}$. Good job with method #1.
Your method #2 is flawed: for instance
$$
\lim_{x\to0^+}(1-x)^{1/x}=e^{-1}
$$
and not $0$ as you claim.
Comment: Thanks for the explanation. But can you please elaborate more on why the second method is wrong. I mean that why is a number less than 1 raised to the power of infinity not equal to zero..


How to change the value of a key in dict in Python with its position?

Question: There is a dict params:
{'channel': 'DIMENSION',
 'day': 'DIMENSION',
 'subscribersGained': 'METRIC',
 'likes': 'METRIC',
 'views': 'METRIC',
 'subscribersLost': 'METRIC'}

What I want to do is if value == 'DIMENSION', change its name to 'element_n', where n is the key's position.
So my desired output is
{'element_1': 'DIMENSION',
 'element_2': 'DIMENSION',
 'subscribersGained': 'METRIC',
 'likes': 'METRIC',
 'views': 'METRIC',
 'subscribersLost': 'METRIC'}

So far I did it
for k,v in params.items():
    if v == 'DIMENSION':
        v=['element_{}'.format(i+1) for i in range(len(params.values()))]

But it doesn't change anything
Comment: Possible duplicate of [Rename a dictionary key](https://stackoverflow.com/questions/16475384/rename-a-dictionary-key)
Comment: Think about that code a minute. If v is dimension, you want to then set v to a list of strings? Maybe you meant to try to set k instead?
Answer: You could instead build the dictionary anew with the following dictionary comprehension with enumerate to format the key with the corresponding index:
{k if v != 'DIMENSION' else 'element_{}'.format(i):v  for i,(k,v) in enumerate(d.items())}

{'element_0': 'DIMENSION',
 'element_1': 'DIMENSION',
 'likes': 'METRIC',
 'subscribersGained': 'METRIC',
 'subscribersLost': 'METRIC',
 'views': 'METRIC'}

Input data -
d = {'channel': 'DIMENSION',
 'day': 'DIMENSION',
 'subscribersGained': 'METRIC',
 'likes': 'METRIC',
 'views': 'METRIC',
 'subscribersLost': 'METRIC'}

Comment: I'm getting the correct output @anna the one I've shared (just double checked)
Comment: If the sample data is not good enough to generalise, please share a more representative sample @AnnaDmitrieva
Answer: You can do it with a one-liner:
{(v == 'DIMENSION' and 'element_{}'.format(i) or k):v for i, (k, v) in  enumerate(d.items(), 1)}

Answer: Try this:
x = {'channel': 'DIMENSION',
     'day': 'DIMENSION',
     'subscribersGained': 'METRIC',
     'likes': 'METRIC',
     'views': 'METRIC',
     'subscribersLost': 'METRIC'}

index = 1
x_ = {}
for k, v in x.items():
    if v == 'DIMENSION':
        k = "element_{}".format(index)
        index += 1
    x_[k] = v

print(x_)

output:
 {'subscribersLost': 'METRIC', 'views': 'METRIC', 'element_1': 'DIMENSION', 'element_2': 'DIMENSION', 'likes': 'METRIC', 'subscribersGained': 'METRIC'}

I didn't use enumerate because it can generate, element_1, element_4 if the items are in sequential positions(Order is not guaranteed in dictionary):
{....'element_1': 'DIMENSION', `'element_4': 'DIMENSION'.....}`

Answer: you can create new dictionary using list comprehension, I defined lambda function to make the comprehension clean and readable
d = {'channel': 'DIMENSION',
 'day': 'DIMENSION',
 'subscribersGained': 'METRIC',
 'likes': 'METRIC',
 'views': 'METRIC',
 'subscribersLost': 'METRIC'}

## solution

get_key = lambda key, value, indx: f"element_{indx+1}" if value == "DIMENSION" else key

{get_key(key, value, i): value for i, (key, value) in enumerate(d.items())}


Why is there a debate over whether or not percussion instruments are pitched?

Question: Here is an excerpt from Introduction to the Study of Musical Scales by Alain Danielou.
The important part is in bold. I included the rest of the passage only to provide context:

It is the loss of this pedal point of the tonic, somewhere in the course of ages, which renders the modes of plain-chant so vague and so weak. They lack a basis, and their classification becomes a rather abstract game, like the system of the Greek Doris! i in the unreal form generally attributed to it. It is by an artificial conception that a mode can be assimilated to the plagal 9 form of another mode.
The melody remains unaffected and in the tone of C (Sa), because, to determine a tone, a permanent element is required, and habit can, up to a certain point, create this permanence in favor of C (Sa): that is, in favor of the western major mode, supposing that we are still using only the white keys of the piano. Another mode can be determined only by constantly imposing its tonic. Percussion instruments, such as drums, cymbals, etc., can be sufficient to determine this tonic. This is why, in ancient music, the problem did not arise, as such instruments were always present in a musical performance. The accurate tuning of the different notes of the scale should, of course, be sufficient to define the tonic, but, as the differences in intervals are very small, rare indeed are the musicians who can maintain this accuracy without referring constantly to the tonic.

Do cymbals as well as other "unpitched" drums actually have a pitch?
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/149107/discussion-on-question-by-lecifer-why-is-there-a-debate-over-whether-or-not-perc); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: There's no debate, there's a whole spectrum from almost unpitched to clearly pitched (e.g. timpani, marimba). There are a lot of weakly pitched instruments in the the middle (e.g. tomtoms: there are high and low toms even if the exact pitch is not clear). There's probably no such thing as a completely unpitched percussion instrument: even with an instrument like a snare drum, some instruments will have more high frequency components than others.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/149108/discussion-on-answer-by-piedpiper-why-is-there-a-debate-over-whether-or-not-perc); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: Many percussion instruments either produce many harmonically unrelated frequencies simultaneously (such as a snare drum) or produce frequencies that change significantly with time (e.g. a tom tom).  It's possible for a set of such instruments to have frequency spectra which seem to have a definite intervals between them, but not have pitches that can be compared with instruments that produce a steady set of harmonically related frequencies.  One could, for example, have a set of tom toms that were tuned and could play recognizable melodies, but be incapable of establishing a key center that would be applicable to another instrument such as a flute.
Comment: Y'all'd better be watching *me* for the changes.


What's the difference between hasMany and referencesMany in Strongloop loopback

Question: I read that embedsMany (in case of non relational db) puts the embedded models in the parent model document. While hasMany creates a new collection of child model and a relation is created between parent collection and child collection. What about referencesMany?
There is also this example project, where customer referencesMany Account
and hasMany Order. I am not understanding the difference.
Answer: embedsMany: puts all child data (naturally and relation) in itself model. each childs hasn't any id and can't be reusable in another rows). it needs just one collection for child and parent model.
referencesMany: puts just id of child relation (reference id) in itself model and puts data in child model (no need to store parent model id in child model and child model id is reusable for another models). it needs an actual two collection for parent and child model.
hasMany: puts child data and parent id in child model. it needs too an actual two collection;


Get form values (foreign key field) in django

Question: I'm trying to add the foreign key options to a select input but don't know how to get it. I want to make the same as using the form generated by Django, but with my own HTML.
The form is for creating a new "patient".
This is are the foreignkeys from my patient model:
ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE)
supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

And this is the patient form:
    class PatientForm(forms.ModelForm):
        class Meta:
            model = Patient
            fields = ['dni', 'first_name', 'last_name', 'birth', 'risk', 'status', 'ubication', 'supervisor']
            widgets = {
                'dni': forms.NumberInput(attrs={'class': 'form-control'}),
                'first_name': forms.TextInput(attrs={'class': 'form-control'}),
                'last_name': forms.TextInput(attrs={'class': 'form-control'}),
                'birth': forms.DateInput(attrs={'class': 'form-control'}),
                'risk': forms.CheckboxInput(attrs={'class': 'form-control'}),
                'status': forms.Select(attrs={'class': 'form-select'}),
                'ubication': forms.Select(attrs={'class': 'form-select'}),
                'supervisor': forms.Select(attrs={'class': 'form-select'})
            }

For example, here I want to add the supervisors from the supervisor model to vinculate it to the patient model:
<select class="form-select" aria-label="Default select example" required name="supervisor" id="id_supervisor">
                    <option selected>Select supervisor</option>
                    {% for f in form.supervisor %}
                    <option value="{{f.id}}">{{f.first_name}}</option>
                    {% endfor %}
</select>

Answer: I believe you want to make choice field where the user selects the supervisor based on one of the supervisors available, right?
You can create the choices in your form script.
on PatientForm do the following:
# SUPERVISORS is the model where the supervisors are stored in your code
# you will have to modify it
from .models import SUPERVISORS

CHOICES = [ (supervisor.id, supervisor.get_full_name())
            for supervisor in SUPERVISORS.objects.all() ]

class PatientForm(forms.ModelForm):
   supervisor = forms.ChoiceField(choices=CHOICES)
      class Meta:
      # leave the rest as is

If you want to tweak this you can get more info here.


Heartbleed: how to reliably and portably check the OpenSSL version?

Question: I was looking at a reliable and portable way to check the OpenSSL version on GNU/Linux and other systems, so users can easily discover if they should upgrade their SSL because of the Heartbleed bug.
I thought it would be easy, but I quickly ran into a problem on Ubuntu 12.04 LTS with the latest OpenSSL 1.0.1g:
openssl version -a
I was expecting to see a full version, but instead I got this:
OpenSSL 1.0.1 14 Mar 2012
built on: Tue Jun  4 07:26:06 UTC 2013
platform: [...]
To my unpleasant surprise, the version letter doesn't show. No f, no g there, just "1.0.1" and that's it. The listed dates do not assist in discovering a (non-)vulnerable version either.
The difference between 1.0.1 (a-f) and 1.0.1g is crucial.
Questions:

What is a reliable way to check the version, preferably cross distro?
Why isn't the version letter showing in the first place? I was unable to test this on anything else but Ubuntu 12.04 LTS.

Others are reporting this behaviour as well. A few examples:

https://twitter.com/orblivion/status/453323034955223040
https://twitter.com/axiomsofchoice/status/453309436816535554

Some (distro-specific) suggestions rolling in:

Ubuntu and Debian: apt-cache policy openssl and apt-cache policy libssl1.0.0. Compare the version numbers to the packages here: http://www.ubuntu.com/usn/usn-2165-1/
Fedora 20: yum info openssl (thanks @znmeb on twitter) and yum info openssl-libs

Checking if a older version of OpenSSL is still resident:

It's not completely reliable, but you can try lsof -n | grep ssl | grep DEL. See Heartbleed: how to reliably and portably check the OpenSSL version? on why this may not work for you.

It turns out that updating the OpenSSL package on Ubuntu and Debian isn't always enough. You should also update the libssl1.0.0 package, and -then- check if openssl version -a indicates built on: Mon Apr  7 20:33:29 UTC 2014.
Comment: This works on CentOS `[root@null~]# openssl version -a
OpenSSL 1.0.1e-fips 11 Feb 2013`
Comment: at least be sure that the OpenSSL version you have *isn't* g because of the date it shows
Comment: @PatoSáinz I've checked `apt-cache policy openssl` and it responded with: `Installed: 1.0.1-4ubuntu5.12` which is the 1.0.1g just released by Ubuntu for 12.04 LTS. I logged out and back in. Is there anything else I could do to verify?
Comment: I'll point out, for that that don't know, in case it's helpful... Ubuntu 12.04 LTS shipped with OpenSSL 1.0.1 (vanilla).
Comment: If that build date is accurate, you cannot have "release versioned" code more recent than 1.0.1e, since 1.0.1f came out in 2014 per [the OpenSSL 1.0.1 release notes](https://www.openssl.org/news/openssl-1.0.1-notes.html).  Individual lines or sections may have been backported to your Ubuntu version prior to the official OpenSSL 1.0.1f release, of course.  And the build date may be less that completely helpful.
Comment: Gentoo users could just run `emerge -av openssl`. Considering you have fresh portage tree it will offer you to update openssl and your current version with letter will be in output.
Comment: The `apt-cache policy openssl` worked for me on Debian and Ubuntu, you might want to add it in your question under "distro-specific".
Answer: Based on the date displayed by your version of OpenSSL, it seems you are seeing the full version displayed there.
Open SSL 1.0.1 was released on March 14th, 2012.  1.0.1a was released on April 19th of 2012.
So, I'm going to go ahead and assert that openssl version -a is the proper, cross-distro way to display the full version of OpenSSL that's installed on the system. It seems to work for all the Linux distros I have access to, and is the method suggested in the help.ubuntu.com OpenSSL documentation, as well.  Ubuntu LTS 12.04 shipped with vanilla OpenSSL v1.0.1, which is the  version that looks like an abbreviated version, on account of not having a letter following it.
Having said that, it appears that there is a major bug in Ubuntu (or how they package OpenSSL), in that openssl version -a continues to return the original 1.0.1 version from March 14, 2012, regardless of whether or not OpenSSL has been upgraded to any of the newer versions.  And, as with most things when it rains, it pours.
Ubuntu is not the only major distro in the habit of backporting updates into OpenSSL (or other packages), rater than relying on the upstream updates and version numbering that everyone recognizes.  In the case of OpenSSL, where the letter version numbers represent only bug fix and security updates, this seems nearly incomprehensible, but I have been informed that this may be because of the FIPS-validated plugin major Linux distros ship packaged with OpenSSL.  Because of requirements around revalidation that trigger due to any change, even changes that plug security holes, it is version-locked.
For example, on Debian, the fixed version displays a version number of 1.0.1e-2+deb7u5 instead of the upstream version of 1.0.1g.
As a result, at this time, there is no reliable, portable way to check SSL versions across Linux distributions, because they all use their own backported patches and updates with different version numbering schemes.  You will have to look up the fixed version number for each different distribution of Linux you run, and check the installed OpenSSL version against that distribution's specific version numbering to determine if your servers are running a vulnerable version or not.
Comment: HopelessN00b, there is nothing dubious about the policy of backporting fixes instead of bumping versions; it's a very good way of ensuring platform stability, which is highly-desirable in a server environment.  Like any decision, it has consequences, which users need to be aware of; but just because it breaks the "*I'm running foo x.y.z therefore I am/amn't vulnerable to the latest exploit*" line of reasoning, that doesn't make it a bad thing.
Comment: @NickW @Jubal @MadHatter the thing with OpenSSL, though, is that: [`After the release of OpenSSL 1.0.0 the versioning scheme changed. Letter releases (e.g. 1.0.1a) can only contain bug and security fixes and no new features.`](https://www.openssl.org/support/faq.html#MISC8) So, nothing is gained abandoning the upstream versioning scheme; backporting the updates is essentially the same as using the updated version, since the update only includes security and bug fixes anyway. What it does do is confuse things and leave us with no way to portably check OpenSSL version across Linux distros.
Comment: @towo Version numbers exist for a reason.  If we're just gonna chuck the upstream version numbers out the window because "enterprisey," or whatever, why bother with version numbers at all?  May as well just start naming all our stuff with alliterations.  We can call the vulnerable OpenSSL versions *Holy Heartbleed* and the fixed ones *Cunning Coagulant*.
Comment: @HopelessN00b I think you're getting caught up on the "this was fixed in version X.Y.Z" trap, they don't follow the version numbers because all that's getting imported into the latest version are bug and security fixes. If they bumped the version number, you'd also expect the additional functionality..  "I have OpenSSL v X.Y.Z, why don't I have ECDHA???? ..etc". It makes sense when you understand that it's only bugfixes.
Comment: My install is a simple Ubuntu 12.04 LTS without anything I've compiled myself or downloaded from other sources than the Ubuntu repositories. If Ubuntu is distributing OpenSSL with abbreviated version numbers, then `openssl version -a` isn't a portable method (at least not portable to Ubuntu). I've checked `apt-cache policy openssl` and it responded with: `Installed: 1.0.1-4ubuntu5.12` which is the 1.0.1g just released by Ubuntu for 12.04 LTS. I logged out and back in before checking.
Comment: Cripes, this ubuntu bug just caused several minutes of confusion and mild panic on my part. How stupid is that.
Comment: @HopelessN00bGeniusofnetwork We can easily check *versions* which is a different matter than checking *fixes* (or backports). As for easily checking on Debian/Ubuntu: `aptitude changelog libssl1.0.0 | grep -B10 CVE-2014-0160`
Comment: Exactly what @MadHatter says. Ensure you're updated, and you're good to go. Just because it breaks a "copy and paste this command" scheme of "ensuring" you're running a safe version, it isn't stupid. [If you're about to tell me "nagios check", I'll respond with "check for vulnerability instead of version number".]
Comment: Oh, Ubuntu... of course it's too much to ask that they'd do *anything* that might be similar to the way every other Linux distro in the world does things.  I'm getting dangerously close to spinning up a test Ubuntu VM.  **
Comment: @HopelessN00b: it's called 'backporting security fixes'; there are no functionality updates. So Debian Wheezy's version is what it says, 1.0.1e + the security fixes, not the latest.
Comment: @Martijn  ...and what does `openssl version -a` report now that you've relogged?  The March 14th, 2012 date is a dead give-away to the vanilla 1.0.1 version.
Comment: It's still giving me `OpenSSL 1.0.1 14 Mar 2012` and `built on: Tue Jun  4 07:26:06 UTC 2013`. This is reported by the binary in `/usr/bin/openssl` and I can't find any other openssl binaries on the system.
Answer: If you want something truly cross-platform, check for the vulnerability itself rather than relying on version numbers.
You might have code that reports a version number that is known to be vulnerable, but the actual code is not vulnerable. And the reverse -- silently vulnerable code -- could be even worse!
Many vendors who bundle open-source products like OpenSSL and OpenSSH will selectively retrofit urgent fixes to an older version of code, in order to maintain API stability and predictability.  This is especially true for "long-term release" and appliance platforms.
But vendors who do this silently (without adding their own version string suffix) run the risk of triggering false positives in vulnerability scanners (and confusing users).  So to make this transparent and verifiable, some vendors append their own strings to the major package version.  Both Debian (OpenSSL) and FreeBSD (in OpenSSH, via the VersionAddendum sshd_config directive) sometimes do this.
Vendors who don't do this are probably doing so to minimize the chance of breakage due to the many direct and indirect ways that other programs check version numbers.
So it can look like this:
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"

$ openssl version
OpenSSL 1.0.1 14 Mar 2012

... even though it's been patched:
$ dpkg -l openssl | grep openssl
ii  openssl  1.0.1-4ubuntu5.12  [truncated]

$ ls -la `which openssl`
-rwxr-xr-x 1 root root 513208 Apr  7 12:37 /usr/bin/openssl

$ md5sum /usr/bin/openssl
ea2a858ab594905beb8088c7c2b84748  /usr/bin/openssl

With things like this in play, you're better off if you don't trust the version number.
Comment: It's clear that checking versions isn't as easy and transparant as I hoped it would be.

Checking for the vulnerability is cross-platform, but also more difficult to do: you must have a reliable PoC or test handy for the particular vulnerable software service you're running.

In this case it all started out with a PoC for Apache and nginx. What if I was only using SMTP with SSL at that moment, and I wanted to check if I'm vulnerable? Eventually we'll have tests for most services, but it may take a while.
Comment: Martijn, that's a fair point. When a test is not available, secondary methods (like tracking down the checksum for the affected binaries on your target systems) are less optimal, but might be good enough to get the job done ... and then move on to the next fire. :-)
Answer: Unfortunately, I'm not sure there is a cross-platform way of doing this. As I discuss in a blog posting, the version of OpenSSL displayed on Ubuntu 12.04 REMAINS 1.0.1 after upgrading to a fixed version.
For Ubuntu 12.04 ONLY, you can tell if you've been updated if all of the below are true:

dpkg -s openssl | grep Version shows version 1.0.1-4ubuntu5.12 or later.
dpkg -s libssl1.0.0 | grep Version shows version 1.0.1-4ubuntu5.12 or later.
openssl version -a shows a "built on" date of April 7, 2014 or later.

Thanks to @danny for the additional info.
Comment: Ok, in that case I must add that package version `1.0.1-4ubuntu5.12` is ONLY for Ubuntu 12.04 LTS. If you're on Ubuntu 12.10 you should see at least version `1.0.1c-3ubuntu2.7` and if you're on 13.10 then it should be at least version `1.0.1e-3ubuntu1.2`, according to source: http://www.ubuntu.com/usn/usn-2165-1/
Comment: This is unfortunately insufficient. You *must* also upgrade `libssl1.0.0` explicitly on ubuntu.  If you're seeing a built on date before April 7 2014 even if openssl is version looks correct (`1.0.1-4ubuntu5.12` for Ubuntu 12.04) you are probably still vulnerable.
Comment: @danny You just saved me SO much work. I was trying to figure out why the build date was right on some 12.04 systems and wrong on others. You're a lifesaver!
Comment: `openssl version -a` might not need the build date of April 7, because the fix is being backported to the older releases.
Answer: Give the following a try.  It will extract all the strings from the crypto library that ssh is linked against.  It produces more than one line of output, but if necessary could be converted to 1 line.
ldd `which ssh` | awk '/\// { print $3 }' | grep crypto | xargs strings  | grep OpenSSL

produces
OpenSSLDie
DSA_OpenSSL
...
MD4 part of OpenSSL 1.0.1f 6 Jan 2014
MD5 part of OpenSSL 1.0.1f 6 Jan 2014
...
etc

e.g. on Gentoo before emerge
[ebuild     U  ] dev-libs/openssl-1.0.1f [1.0.1c] USE="bindist (sse2) tls-heartbeat%* zlib -gmp -kerberos -rfc3779 -static-libs {-test} -vanilla" 4,404 kB

the above command results in
...
OpenSSL 1.0.1c 10 May 2012

after
...
OpenSSL 1.0.1f 6 Jan 2014

Ouch, still no g.
Comment: I thought you were very close to providing a good solution, but unfortunately this doesn't work for the crypto library on Ubuntu 12.04 LTS. It displays all the strings with version `[...]  part of OpenSSL 1.0.1 14 Mar 2012`, the same way as `openssl version -a` does. This is a trick that may work in other cases though!
Comment: @Martijn Well that's unfortunate, but it does work on ubuntu 12.10. Strange that it would it mis-identify itself on 12.04.  Are there multiple libs?  Is it possible ssh does not use the most up-to-date?
Comment: I was unable to find any other openssl binaries or crypto libraries. It is suggested by others that the difference is that, on 12.04 LTS, Ubuntu is backporting the changes to 1.0.1 without upping the version. While 12.10 isn't an LTS and so Ubuntu uses the latest version there instead of a backport.
Answer: Do any of these scripts test all services, or do they only test HTTPS? AFAIK, PostgreSQL is vulnerable, but that's only a rumor until an in-the-wild attack surfaces.
There is a metasploit script available for use.
https://github.com/rapid7/metasploit-framework/commit/dd69a9e5dd321915e07d8e3dc8fe60d3c54f551a

You can type this (tested with GnuWin32 OpenSSL binary version 188.8.131.52, dated 2014-01-14), or just use the script in the comment below this one. It's more accurate and simpler!
s_client -connect a23-75-248-141.deploy.static.akamaitechnologies.com:443 -debug -state

Once connected type B and you'll see on a vulnerable host and you won't be disconnected:
B

HEARTBEATING
write to 0x801c17160 [0x801cbc003] (66 bytes => 66 (0x42))
0000 - 18 03 03 00 3d 8f 6f 3c-52 11 83 20 9c a2 c0 49   ....=.o 5 (0x5))
0000 - 18 03 03 00 3d                                    ....=
read from 0x801c17160 [0x801cb7008] (61 bytes => 61 (0x3D))
0000 - 05 4d f5 c0 db 96 d1 f5-c7 07 e5 17 1f 3b 48 34   .M...........;H4
0010 - 6e 11 9d ba 10 0c 3a 34-eb 7b a5 7c c4 b6 c0 c0   n.....:4.{.|....
0020 - b0 75 0e fe b7 fa 9e 04-e9 4e 4a 7d 51 d3 11 1f   .u.......NJ}Q...
0030 - e2 23 16 77 cb a6 e1 8e-77 84 2b f8 7f            .#.w....w.+..
read R BLOCK

You will get a heartbeat response that looks similar to this one.
On a patched host, you will see a response similar to below and you'll be disconnected:
Enter B
HEARTBEATING
write to 0x801818160 [0x8019d5803] (101 bytes => 101 (0x65))
0000 - 18 03 03 00 60 9c a3 1e-fc 3b 3f 1f 0e 3a fe 4c   ....`....;?..:.L
0010 - a9 33 08 cc 3d 43 54 75-44 7d 2c 7b f3 47 b9 56   .3..=CTuD},{.G.V
0020 - 89 37 c1 43 1c 80 7b 87-66 ff cb 55 5f 8d 1a 95   .7.C..{.f..U_...
0030 - 1b 4c 65 14 21 a1 95 ac-7a 70 79 fc cc a0 cf 51   .Le.!...zpy....Q
0040 - 0f 7e c5 56 14 c8 37 c1-40 0b b8 cb 43 96 8a e6   .~.V..7.@...C...
0050 - 21 42 64 58 62 15 fb 51-82 e6 7f ef 21 1b 6f 87   !BdXb..Q....!.o.
0060 - b9 c2 04 c8 47                                    ....G

Source:

Blog post How to test if your OpenSSL heartbleeds

There's also these tools:

https://github.com/titanous/heartbleeder
http://filippo.io/Heartbleed/
https://github.com/musalbas/heartbleed-masstest
Answer: I found this script in devcentral:
openssl s_client -connect example.com:443 -tlsextdebug 2>&1| grep 'server extension "heartbeat" (id=15)' || echo safe

Replace example.com with the name or IP address of the server you want to check.
Will return "safe" if your server is okay or "server extension "heartbeat" (id=15)" if not.
This doesn't rely on the version number, but on listing the server extension that causes the issue, so it should be immune to the library version shenanigans.
The machine you are running openssl s_client on must be using OpenSSL 1.0.1 or later in order for this to work.
Comment: ***BIG SCARY IMPORTANT WARNING*** - The machine you are running `openssl s_client` on MUST be using OpenSSL 1.0.1 or later in order for this to work. If you run this command on a machine with 0.9.8 or 1.0.0 ***IT WILL ALWAYS REPORT "Safe", even for vulnerable servers***.
Comment: Useful, but doesn't tell you if you have a version with the extension _and the fix_.
Comment: This is indeed a good way to check for the vulnerability and is what some scripts do. It does not actually require SSH access.
Comment: Odd. I'm running a version of OpenSSL that is supposedly affected by this bug, yet that string doesn't appear in the output...
Comment: @StefanLasiewski I updated my answer and removed the "need ssh" part
Comment: @voretaq7 Thanks for your comment. I added it at the end of my answer
Comment: @Michael That probably means that even if the ssl version is "insecure", it doesn't have the module that manifests the vulnerability active.
Comment: @voretaq7 : But according to CVE-2014-0160, OpenSSL 0.9.8 and 1.0.0 are not subject to the Heartbleed attack. So in that case, this is a valid test. OpenSSL 0.9.8 and 1.0.0 *are* 'safe' from Heartbleed.
Comment: But overall, this answer doesn't really answer the question "how to reliably and portably check the OpenSSL version?".
Answer: For Ubuntu you can use:
aptitude show libssl1.0.0 | grep Version

And compare with http://www.ubuntu.com/usn/usn-2165-1/. After a reboot (!!!) you can check with http://possible.lv/tools/hb.
Answer: You'd better upgrade to latest OpenSSL OpenSSL 1.0.1j.
http://blog.vincosolution.com/2014/10/upgrade-openssl-1-0-1j-debianubuntu.html


ruby bitwise operations on IPv4 addresses

Question: I'm doing some work with IP addresses and I would like to convert "slash notation" (e.g., /28) to dotted quad (e.g., 255.255.255.240)
Internally representing the IP and mask as a large integer is handy for different types of operations and conversions.
So I figured I would drop a 1 on the left, and shift right and drop another 1 there as many times as the slash indicates:
mask=0
28.times do
   mask>>=
   mask+=2**31
end
print "%x\n" % mask

... but for some reason this doesn't work.
I hear that Ruby automatically converts integers to larger sizes as needed.  I'll be doing a lot of bitwise operations in these routines, but the number of significant digits is very stable.
What's the right way to do bitwise operations on IPv4 addresses in Ruby?
Comment: Take a help from Ruby stdlib - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ipaddr/rdoc/IPAddr.html#method-i-mask
Comment: another link - https://www.ruby-forum.com/topic/139035#618171
Answer: >> '%b' % (1 << n)
=> "10000000000000000000000000000"
>> '%b' % ((1 << n) - 1)
=> "1111111111111111111111111111"
>> '%b' % (((1 << n) - 1) << (32-n))
=> "11111111111111111111111111110000"

Combining with IPAddr:
require 'ipaddr'
IPAddr.new(((1 << n) - 1) << (32-n), Socket::AF_INET).to_s
# => "255.255.255.240"

or as Arup Rakshit commented, use IPAddr#mask:
IPAddr.new('255.255.255.255').mask(28).to_s
"255.255.255.240"


Can feeds importer grab fields, too?

Question: I'm working outside the area of what I know about Drupal. We're looking at using feeds importer to migrate a number of nodes. However, I didn't see anything in the documentation about its ability to grab fields attached to those nodes. Can it? How do I configure it to do so?
We're using node export currently, which works well, but is tedious since we're doing it one-by-one.
Answer: It can, yes. We've used it extensively to import contacts (nodes) into a homebrew CRM.
After creating your Feeds Importer, you should see "Mapping" as the last item in your settings panel to the left. After configuring the rest of your importer to work with your export's format, the Mapping Settings of the processor will allow you to map source fields in your dataset to target fields in your actual destination content type. Your nodes should have the appropriate fields filled in on import.

Can feeds importer grab fields, too?


What measures the y-axis in stat_smooth, ggplot2 in R?

Question: I am fairly new with logistic regression. I have a binary response. And did this plot. The binary response is:
Y = 0: The student fails
Y = 1: The student succeed
library(ggplot2)
ggplot(data = both, aes(x = age, y = succeed)) +
  stat_smooth(method = 'glm', family = 'binomial') +
  theme_bw()+xlab("X")+ylab("The student succeed")

What is the y-axis? estimated probability that the student succeed? Or estimated log odds of a student succeed?
Feeling a little confused. Could someone explain what they are I have on the y-axis?
Answer: The y-axis is measured on the response scale, i.e. probability of success.
The help page for stat_smooth hints at this, but states that the prediction method is currently undocumented:

Calculation is performed by the (currently undocumented) predictdf
  generic function and its methods. For most methods the confidence
  bounds are computed using the predict method - the exceptions are
  loess which uses a t-based approximation, and for glm where the normal
  confidence interval is constructed on the link scale, and then
  back-transformed to the response scale.

ggplot2:::predictdf.glm shows that predict is used to generate predictions in the link scale, but these are then transformed to the response scale using the inverse link function.


Print lines after raising exception

Question: Is there a way to print out the contents of a dictionary after raising an exception?
Assuming that the dictionary is this,
d = {"orange":[1,2], "yellow":[5], "red":[2,6,7]}

I would like it to look something like this:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-63-719ba08e2a6c> in <module>
----> 1 raise TypeError("This is a TypeError. Printing out contents of dictionary...")

TypeError: This is a TypeError.
orange
1
2

yellow
5

red
2
6
7

Is this possible?
Comment: You use `try/except` to perform actions when an exception is raised. You can print the dictionary in the `except` block.
Comment: Could you please provide what you have attempted for this question, so that we can guide you to the right direction.
Answer: Append the dictionary to the exception message.
raise TypeError("This is a TypeError. Printing out contents of dictionary...\n" + str(d))

Answer: The format is not right, but this does the trick.
d = {"orange":[1,2], "yellow":[5], "red":[2,6,7]}

try:
    d["melon"]
except:
    raise Exception(f"{str(d)}")

or you can do:
try:
    d["melon"]
except:
    for k in d.keys():
        print(k, d[k])

Answer: try:
    # code here
except Exception as e:
    # Try and replace `Exception` with the error you're getting
    print(f"Error = {e}")
    for name, val in zip(d.keys(), d.values()):
        print(name)
        for i in val:
            print(i)

Just be mindful that with except Exception:, the try loop will except any error

Print lines after raising exception


Find all the entire functions satisfying $f^2+g^2=1$

Question: Find all the entire functions (holomorphic functions on $\mathbb{C}$) $f,g$ satisfying $f^2+g^2=1$.
Of course $f,g$ can be constants satisfying $f^2+g^2=1$. But if they are not constants, do they exist?
Maybe Liouville Theorem can be used here to solve this problem, but how to use?
Comment: For any entire function $h$ we can take $f(z)=\sin h(z),g(z)=\cos h(z)$. I suspect those might be all the examples. If we show $f$ is $\sin$ of some entire function $h$, it will follow $g$ is $\pm\cos h$, so replacing $h$ by $\pi-h$ if necessary we will have $g=\cos h$.
Comment: $\sin z$ can be defined by a convergent power series, so it is entire. Composing it with $h$, which is also entire, gives an entire function.
Comment: @Wojowu Is $\sin h$ holomorphic? (Sorry I haven't learnt about $\sin z$ defined in $\mathbb{C}$) And do there exsist  other functions in other forms?
Comment: @Wojowu I got it, thank you!
Answer: Since $f^2+g^2=1$, $(f+ig)(f-ig)=1$. So, $f+ig$ is an entire function without zeros, and therefore it can be written as $e^{hi}$, for some entire function $h$. So,$$f-ig=\frac1{f+ig}=\frac1{e^{hi}}=e^{-hi}.$$Therefore,$$f=\frac{f+ig+f-ig}2=\frac{e^{hi}+e^{-hi}}2=\cos\circ h$$and$$g=\frac{f+ig-(f-ig)}{2i}=\frac{e^{hi}-e^{-hi}}{2i}=\sin\circ h.$$
Comment: Nice, +1 for you
Comment: Nice prove! Thanks a lot!
Comment: I'm glad I could help.
Comment: astonishing as always.+1
Comment: A duplicate? ${}$
Comment: You also answered the same question here: https://math.stackexchange.com/a/2869127/42969.
Comment: @MartinR That's funny. I had no idea that I had answered that question before.