Como checar se o número de resultados do mysql é vazio?

Question: Estou com alguma dificuldade pra exibir uma mensagem quando a consulta não retorna resultados. Quando o select retorna 1 resultado "if(mysqli_num_rows($result1) > 0)" está mostrando corretamente, porém quando não retorna, não traz nada (else).
Segue abaixo o meu código:

Redefina a sua nova senha

  <?php
    if(isset($_GET['hash'])) {
      $hash = $_GET['hash'];

      $sql1 = "SELECT * from hr_link where link = '$hash' limit 1";
      $result1 = mysqli_query($connect, $sql1);
      while($reg = mysqli_fetch_array($result1)){

        $hash2 = $reg['link'];
        $idusuario = $reg['idusuario'];
        if(mysqli_num_rows($result1) > 0) {
    ?>

            <form style="max-width: 450px" method="POST" name="formuser" action="cadastrok2.php" class="form-horizontal">
              <input type="password" name="txtnovasenha" placeholder="Nova Senha" class="txtfieldd" />
              <input type="password" name="txtrpt" placeholder="Confirme a nova senha" class="txtfieldd" />
              <input type="hidden" name="txtidusuario" value="<?php echo $idusuario ?>" />

                <input type="submit" name="rec_key" value="Salvar" onclick="return validar() "  style="color: white; background: green; padding: 15px; font-size: 18px; border-radius: 5px; margin-top: 20px; cursor: pointer;border: none"/>

            </form>

    <?php
        } else { ?>

              <form style="max-width: 450px" name="loginform" method="post" action="userauth.php?">

Link expirou. Clique aqui para gerar novamente

              </form>

 <?php
       }
    }
  }else{
?>

        <form style="max-width: 450px" name="loginform" method="post" action="userauth.php?">

Link expirou. Clique aqui para gerar novamente

        </form>

<?php } ?>

Answer: Simples, o num_rows está dentro do while, o seu código não faz sentido. O que o código está fazendo é...

Enquanto houver linhas (while ($reg = mysqli_fetch_array($result1))):

Se houver linhas (mysqli_num_rows($result1) > 0)):

Exibe fomulário

Se não:

Exibe "Link expirou"

O while só vai funcionar se houver um registro (ou mais), ele nunca vai funcionar se houver zero registros. Logo, em situação normal, esse if nunca será utilizado, ele sempre será > 0. Então, para que o if seja chamado é preciso que o while seja executado, o while somente será executado quando houver uma linha (ou mais linhas).

Você pode simplesmente ignorar o while, afinal existe o LIMIT 1, isso iria resolver o problema:

Redefina a sua nova senha

<?php

if (isset($_GET['hash'])) {
    $hash = mysqli_real_escape_string($connect, $_GET['hash']);
    $result1 = mysqli_query($connect, "SELECT link, idusuario from hr_link where link = '$hash' LIMIT 1");

    if (mysqli_num_rows($result1) > 0) {
        list($hash2, $idusuario) = mysqli_fetch_row($result1);
        ?>

            <form style="max-width: 450px" method="POST" name="formuser" action="cadastrok2.php"
                  class="form-horizontal">
                <input type="password" name="txtnovasenha" placeholder="Nova Senha" class="txtfieldd"/>
                <input type="password" name="txtrpt" placeholder="Confirme a nova senha" class="txtfieldd"/>
                <input type="hidden" name="txtidusuario" value="<?php echo $idusuario ?>"/>

                    <input type="submit" name="rec_key" value="Salvar" onclick="return validar() "
                           style="color: white; background: green; padding: 15px; font-size: 18px; border-radius: 5px; margin-top: 20px; cursor: pointer;border: none"/>

            </form>

        <?php
        exit();
    }
}
?>

    <form style="max-width: 450px" name="loginform" method="post" action="userauth.php?">

Link expirou. Clique aqui para gerar novamente

    </form>

Embora isso ainda esteja com outros problemas, isso irá funcionar como esperado.
Comment: Muito obrigado,Inkeliz. Deu certo, me ajudou bastante.


Centralizar paginação no Bootstrap v2.1.0

Question: Preciso centralizar uma paginação de resultados utilizando o Bootstrap v2.1.0, já tentei colocar o text-align na div mas também não deu. Esse é o código que estou usando:

Já tentei também colocar outros spans acima e abaixo da div "div_paginacao" mas também não deu. Na verdade até deu, mas ao redimensionar a página, o espaçamento não diminui.
Answer: A partir da versão 2.3.0, já é possível utilizar a classe text-center.
Caso não dê certo, utilize o text-align do css como no exemplo
Comment: Já tentei com o text-align mas também não deu certo
Comment: o proprio text-center do bootstrap não funcionou ? poste seu código com o css no jsfiddle para analisarmos
Comment: Então amigo, eu coloquei a versão errada, na verdade estou usando a 2.1.0, portanto, não tenho como colocar a classe text-center
Comment: Tinha colocado como resolvido, mas percebi que deu erro quando a paginação chega em um determinado numero, devido ao tamanho da div. Tem como alinhar uma div com o min-widht?
Comment: min-width é pra quando você deseja uma largura mínima fixa, dependendo pode até ajudar no alinhamento, mas não é pra isso que serve
Answer: Problema resolvido.
A div ficou assim:

Comment: Pelo que entendi, você não está querendo centralizar textos e sim divs, correto ? Nesse caso não seria melhor utilizar o .container acompanhado de .span-**-offset ?
Comment: Vou tentar usar sua alternativa amigo, até porque não deu certo com eu coloquei acima
Comment: Então amigo, até centraliza a div utilizando do container, span e offset, mas o problema é que se eu redimensiono a janela, a div não acompanha entende?
Comment: posta sua pagina inteira no jsfiddle com o css, provavelmente sua estrutura de pagina esta errada e esta conflitando.
Comment: Então amigo, o problema é que mesmo que eu poste a página toda, não vai conseguir ver a paginação porque depende de outras ferramentas aqui do sistema entende?
Comment: ctrl+U e copie o código fonte
Answer: Faça assim :
//div que tem o panel.

 box

//e use esse .css abaixo para centralizar.
.center {
    float: none;
    margin-left: auto;
    margin-right: auto;
}

Answer: Não me lembro bem, mas caso o Bootstrap 2.1.0 não tenha a class .pagination-centered basta criá-la. Veja o exemplo:
.pagination-centered {
    text-align: center;
}

«

1

2

3

»


Probability $1$, $10$, $100$, $1000$ all show up on display of calculator at some point?

Question: I just asked this question accidentally from my older brother's account, so deleting it and asking it on mine:
From the HMMT competition:
https://hmmt-archive.s3.amazonaws.com/tournaments/2003/feb/comb/solutions.pdf

A calculator has a display, which shows a nonnegative integer $N$, and a button, which
replaces $N$ by a random integer chosen uniformly from the set $\{0, 1, \ldots , N − 1\}$, provided that $N > 0$. Initially, the display holds the number $N = 2003$. If the button is pressed repeatedly until $N = 0$, what is the probability that the numbers $1$, $10$, $100$, and $1000$ will each show up on the display at some point?

Here's what I did. Let's first count the total number of display sequences. Note that there's a bijection between a display sequence and a subset of $\{1, 2, \ldots, 2002\}$, and so the total number of display sequences is $2^{2002}$. Now, let's count the number of display sequences that pass through $1000$, $100$, $10$, and $1$. For $2003$ to $1000$ it's $2^{1002}$, for $1000$ to $100$ it's $2^{899}$, for $100$ to $10$ it's $2^{89}$, and for $10$ to $1$ it's $2^8$. Thus the desired probability is:$${{2^{1002}2^{899}2^{89}2^8}\over{2^{2002}}} = {1\over{16}}$$However, the official answer at the above link says the answer is$${1\over{1001}} \cdot {1\over{101}} \cdot {1\over{11}} \cdot {1\over2} = {1\over{2224222}}$$So what is wrong with my reasoning?
Answer: Not all the sequences are equally probable, which is where your calculation fails.  The chance you get all the numbers because you always select the highest available is $\frac 1{2002!}$.  The chance you only get $1$ because that is the first one selected is $\frac 1{2002}$


Why do lm and biglm in R give different p-values for the same data?

Question: Here is a small example:
MyDf<-data.frame(x=c(1,2,3,4), y=c(1.2, .7, -.5, -3))

Now with thebase::lm:
> lm(y~x, data=MyDf) %>% summary

Call:
lm(formula = y ~ x, data = MyDf)

Residuals:
    1     2     3     4
-0.47  0.41  0.59 -0.53

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   3.0500     0.8738   3.491   0.0732 .
x            -1.3800     0.3191  -4.325   0.0495 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7134 on 2 degrees of freedom
Multiple R-squared:  0.9034,    Adjusted R-squared:  0.8551
F-statistic: 18.71 on 1 and 2 DF,  p-value: 0.04952

Now, try the same thing with biglm from the biglm package:
XX<-biglm(y~x, data=MyDf)
print(summary(XX), digits=5)

Large data regression model: biglm(y ~ x, data = MyDf)
Sample size =  4
             Coef     (95%      CI)      SE       p
(Intercept)  3.05  1.30243  4.79757 0.87378 0.00048
x           -1.38 -2.01812 -0.74188 0.31906 0.00002

Note that we need the print and digits to see the p-value. The coefficients and standard errors are the same, but the p-values are very different. Why is this so?
Comment: +1 Hint: compare `pt(-3.491, 2)*2` to `pnorm(-3.491)*2`, for example.
Comment: I think idea is that normal is not not that different from t with high $\nu$ value. Try example from first comment, but change pt(-3.491, 2)*2 to pt(-3.491, 2e3)*2.
Comment: @whuber Thanks. So essentially it is a t-distribution vs. normal distribution issue. Is the idea that the normal distribution makes more sense for large data sets that are typical of biglm?
Answer: To see which p-values are correct (if either), let's repeat the calculation for simulated data in which the null hypothesis is true.  In the present setting, the calculation is a least-squares fit to (x,y) data and the null hypothesis is that the slope is zero.  In the question there are four x values 1,2,3,4 and the estimated error is around 0.7, so let's incorporate that in the simulation.
Here is the setup, written to be understandable to everyone, even those unfamiliar with R.
beta <- c(intercept=0, slope=0)
sigma <- 0.7
x <- 1:4
y.expected <-  beta["intercept"] + beta["slope"] * x

The simulation generates independent errors, adds them to y.expected, invokes lm to make the fit, and summary to compute the p-values.  Although this is inefficient, it is testing the actual code that was used.  We can still do thousands of iterations in a second:
n.sim <- 1e3
set.seed(17)
data.simulated <- matrix(rnorm(n.sim*length(y.expected), y.expected, sigma), ncol=n.sim)
slope.p.value <- function(e) coef(summary(lm(y.expected + e ~ x)))["x", "Pr(>|t|)"]
p.values <- apply(data.simulated, 2, slope.p.value)

Correctly computed p-values will act like uniform random numbers between $0$ and $1$ when the null hypothesis is true.  A histogram of these p-values will allow us to check this visually--does it look roughly horizontal--and a chi-squared test of uniformity will permit a more formal evaluation.  Here's the histogram:
h <- hist(p.values, breaks=seq(0, 1, length.out=20))

and, for those who might imagine this isn't sufficiently uniform, here's the chi-squared test:
chisq.test(h$counts)

X-squared = 13.042, df = 18, p-value = 0.7891

The large p-value in this test shows these results are consistent with the expected uniformity.  In other words, lm is correct.
Where, then, do the differences in p-values come from?  Let's check the likely formulas that might be invoked to compute a p-value.  In any case the test statistic will be
$$|t| = \left| \frac{\hat\beta - 0}{\operatorname{se}(\hat \beta)}\right|,$$
equal to the discrepancy between the estimated coefficient $\hat \beta$ and the hypothesized (and correct value) $\beta = 0$, expressed as a multiple of the standard error of the coefficient estimate.  In the question these values are
$$|t| = \left|\frac{3.05}{0.87378 }\right| = 3.491$$
for the intercept estimate and
$$|t| = \left|\frac{-1.38 }{ 0.31906 }\right| = 4.321$$
for the slope estimate.  Ordinarily these would be compared to the Student $t$ distribution whose degrees of freedom parameter is $4$ (the amount of data) minus $2$ (the number of estimated coefficients).  Let's calculate it for the intercept:
pt(-abs(3.05/0.87378), 4-2) * 2

[1] 0.0732

(This calculation multiplies the left-tailed Student $t$ probability by $2$ because this is a test of $H_0:\beta=0$ against the two-sided alternative $H_A:\beta \ne 0$.)  It agrees with the lm output.
An alternative calculation would use the standard Normal distribution to approximate the Student $t$ distribution.  Let's see what it produces:
pnorm(-abs(3.05/0.87378)) * 2

[1] 0.000482

Sure enough: biglm assumes the null distribution of the $t$ statistic is standard Normal.  How much of an error is this?  Re-running the preceding simulation using biglm in place of lm gives this histogram of p-values:

Almost 18% of these p-values are less than $0.05$, a standard threshold of "significance."  That's an enormous error.

Some lessons we can learn from this little investigation are:

Do not use approximations derived from asymptotic analyses (like the standard Normal distribution) with small datasets.
Know your software.
Comment: Good answer (+1). But you are taking $n = 4$ which is not really big data... I think the author of the package disregarded the small $n$ case in favour of the typical big data case. Worth to point it out, however, in the help to avoid these confusions.


Apertar button com a tecla enter do teclado

Question: Possuo um botão gravar em meu site, gostaria de que ao apertar a tecla "Enter" do teclado esse botão seja acionado, como se fosse um click do mouse, existe alguma função para fazer isso?
Código do botão:
<button type="reset" class="btn btn-primary btn-sucesso" onclick="parent.fecharJanelas('ListaBancos')"> Gravar</button>

Esse botão chama uma função de uma classe pai, quero que ao clicar o enter o parent.fecharJanelas('ListaBancos') seja executado
Esse é meu botão:

Código:
<button type="reset" class="btn btn-primary btn-atualizar" onclick="window.location.reload()"> Atualizar</button>

<button type="reset" id="btnFecharJanelas" class="btn btn-primary btn-sucesso" onkeypress="parent.fecharJanelas('ListaBancos')"> Gravar</button>

<button type="reset" class="btn btn-primary btn-sair" onclick="parent.fecharJanela('ListaBancos')"></button>

<button type="button" class="btn btn-primary btn-incluir button" onclick="parent.geradorCodigo('FrmGrdBanco', 'Tabela de Bancos', '/Bancos/Index', 980, 443);"></button>

Answer: Abaixo uma forma usando JQuery:
Botão:
<button type="reset" id="btnFecharJanelas" class="btn btn-primary btn-sucesso" onkeypress="fecharJanelas('ListaBancos')">Gravar</button>

JQuery:
jQuery(document.body).on('keypress', function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        $("#btnFecharJanelas").trigger("click");
    }
});

Assim em qualquer parte do documento que o usuário apertar Enter irá chamar o botão.
O e.keyCode === 13 indica que a tecla Enter foi pressionada
O e.preventDefault() previne que seja feito um postback da página
O ("#btnFecharJanelas").trigger("click"); chama o evento click do botão
Você pode também definir que isso ocorra em apenas um escopo, como um form, exemplo:
jQuery(document.body).on('keypress', '#myForm', function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        $("#btnFecharJanelas").trigger("click");
    }
});

Comment: Desculpe a demora, é que estive envolvido em outra parte, essa função é boa, mas, tem um problema, eu tenho q apertar o botão "gravar" para só então consegui apertar o enter, não sei explicar o porque, mas amanhã posto o código todo na pergunta
Answer: É bastante possível utilizando apenas javascript.
Utilizando KeyboardEvent

document.addEventListener('keydown', function(e) {
    if(e.key == "Enter"){
      document.getElementById("btFechar").click();
    }
});
<input type="button" id="btFechar" onclick="alert('Putz, alguém me bateu!');" />

Utilizando onkeypress

function checkMyKey(e) {
  var keyCode;
  //  Browsers de verdade
  if(e.which){
    keyCode = e.which;
  }
  // Internet Explorer
  else if(window.event){
    keyCode = e.keyCode;
  }
  if (keyCode == 13) {
    document.getElementById("btFechar").click();
  }
}

  <input type="button" id="btFechar" onclick="alert('Putz, alguém me bateu!');" />

Comment: Ah, desculpe, burrice minha, seu código resolve meu problema, obrigado
Comment: Eu gostei utilizando javascript, porém qualquer tecla que eu aperte chama a função
Comment: Atualizei a resposta!
Comment: Agora está funcionando apenas com o click do mouse
Comment: Tá executando na sua página ou utilizando o "Executar" aqui? Testei as duas soluções e tá tranquilo (até no Microsoft Edge...)
Comment: Estou usando o executar daqui mesmo, utilizo o google chrome, vou testar em outro navegador
Comment: Estranho, nem no edge foi, vou testar no meu projeto
Answer:

document.addEventListener('keydown', function(e) {
    if(e.key == "Enter"){
      document.getElementById("btFechar").click();
    }
});
<input type="button" id="btFechar" onclick="alert('Putz, alguém me bateu!');" />
Answer: Usando somente JavaScript
Quando o usuário pressionar a tecla Enter do teclado a função vai ser executada.
Qualquer logica que esteja dentro da função vai ser executada, nesse exemplo coloquei um simples alerta

<!DOCTYPE html>

<button type="reset" onkeypress="btnFechar()">Gravar</button>

Comment: e como esse código faz o que foi perguntado *"com a tecla enter do teclado"*?
Comment: O ´´´´onkeypress´´´´ funciona igualmente ao ´´´´onclick´´´´, porem para quando o usuário pressionar a tecla Enter, quando você atrela uma função a esse evento, tecnicamente você pode fazer qualquer logica dentro dessa função, até mesmo chamar outra função para ser executada.
Comment: Antônio, seu código em nenhum momento trata o pressionar enter, nada mais faz que conectar ao evento *keypress*, sua resposta ainda não responde ao ponto principal da pergunta, talvez por isso tenha alguns *downvotes*. Comento só pra ajudar que deixes uma resposta que ajude a quem perguntou e também os outros usuários. Inclua também a explicação do comentário acima que você fez na pergunta para melhorar o entendimento ;)
Comment: Com o onkeypress, eu preciso clicar no botão primeiro, pra só então depois poder apertar alguma tecla do teclado, e ai qualquer tecla que clicar executa a função, não é isso que estava querendo, mas obg pela resposta


Conformal transformation preserve convexity

Question: Suppose $\Sigma$ a hypersurface in the eucildean space $\mathrm{R}^n$ and equip the inherited metric from the standard metric of $\mathrm{R}^n$.
If $\Sigma$ is $k-$convex, i.e. it has exactly $k$ nonnegative principal curvature.How to show that the $k-$ convex property is preserved under conformal
transformation?Thanks!
Answer: You have to see how the extrinsic geometry of $\Sigma$ changes. Let $\rho\colon \mathbb{R}^n\to \mathbb{R}$ be smooth, let $D$ and $\nabla$ denote the Levi-Civita connections of the original metrics $g^\circ$ and $g$ on $\mathbb{R}^n$ and $\Sigma$, and write $U = {\rm grad}_{g^\circ}\rho$ for the gradient field of $\rho$ on $\mathbb{R}^n$. Write $\widetilde{g}^\circ = {\rm e}^{2\rho}g^\circ$ for the conformal metric on $\mathbb{R}^n$, and $\widetilde{g}$ for the restriction of $\widetilde{g}^\circ$ to $\Sigma$. Observe that $\widetilde{g}$ agrees with ${\rm e}^{2\rho|_\Sigma}g$. Let $\widetilde{D}$ and $\widetilde{\nabla}$ be the Levi-Civita connections of $\widetilde{g}^\circ$ and $\widetilde{g}$.
Conformal changes in metric do not affect orthogonality, so the decomposition $\mathbb{R}^n = T_x\Sigma \oplus (T_x\Sigma)^\perp$ is independent of the metric. Let $\sigma$ be the second fundamental form of $(\Sigma, g)$ in $(\mathbb{R}^n, g^\circ)$, and $\widetilde{\sigma}$ be the second fundamental form of $(\Sigma, \widetilde{g})$ in $(\mathbb{R}^n, \widetilde{g}^\circ)$. The big question is: how does $\widetilde{\sigma}$ relate to $\sigma$?
Fix $X,Y\in\mathfrak{X}(\Sigma)$. Let's summarize all the information we know:
$$D_XY = \nabla_XY + \sigma(X,Y), \qquad \widetilde{D}_XY = \widetilde{\nabla}_XY + \widetilde{\sigma}(X,Y),$$but $$\widetilde{D}_XY = D_XY + X(\rho)Y+Y(\rho)X - g^\circ(X,Y)U$$and$$\widetilde{\nabla}_XY = \nabla_XY + X(\rho)Y+Y(\rho)X - g(X,Y)U^\top,$$where we write $U = U^\top + U^\perp$. Subtract both relations to get $$\widetilde{\sigma}(X,Y) = \sigma(X,Y) - g(X,Y)U^\perp.$$This "transformation law" is very benign and holds for any codimension. Now, let $N$ be a $g^\circ$-unit normal field along $\Sigma$, and consider the shape operator $A\colon T\Sigma\to T\Sigma$ characterized by the relation $g^\circ(\sigma(X,Y), N) = g(AX,Y)$. We have that $\widetilde{N} = {\rm e}^{-\rho}N$ is $\widetilde{g}^\circ$-unit and normal to $\Sigma$, and it has its own associated shape operator $\widetilde{A}$, characterized by $\widetilde{g}^\circ(\widetilde{\sigma}(X,Y), \widetilde{N}) = \widetilde{g}(\widetilde{A}X,Y)$.
What is the relation between $A$ and $\widetilde{A}$? Combining the above relations, we have that $$\widetilde{A}X = {\rm e}^{-\rho}(AX - g^\circ(U^\perp, N)X).$$However, the sign of the principal curvatures changes if you change the sign of the normal field. So, if we start by choosing $N$ pointing in the same direction of $U^\perp$, so that $g^\circ(U^\perp, N) > 0$, we conclude that if $\{\kappa_i\}_{i=1}^n$ are the eigenvalues of $A$, then the eigenvalues of $\widetilde{A}$ are $\{{\rm e}^{-\rho}(\kappa_i - g^\circ(U^\perp, N))\}_{i=1}^n$. Clearly the factor ${\rm e}^{-\rho}$ makes no difference for the signs of these curvatures. Now, it should not be difficult to compare $g^\circ(U^\perp, N)$ and the $\kappa_i$'s to get the desired conclusion.


Basic math subjects book recommendations

Question: I've been wondering about what are the best books to review some of the elementary math subjects. My choices are listed below:
Real Analysis: Introduction to Real Analysis, R.G. Bartle
Multivariate Calculus: Vector Calculus, J.E. Marsden
Linear Algebra: Linear Algebra and Its Applications, G. Strang
Complex Analysis: Basic Complex Analysis, J.E. Marsden
However, I'd like to hear other suggestions. Thank you.
Comment: What Dog_69 suggests as a good textbook is really more useful to most as a reference book; it is rather terse which makes it difficult to understand if you're not already at least somewhat acquainted with the subject.
Comment: Serge Lang _Algebra_ is a very good book. It has almost 1000 pages, so it is very complete, but you can skip all the stuff you are not interested in. It would be my recommendation for linear algebra. For analysis of one and more variables, you can choose Thomas' book _Calculus_. It is thought for physicist and engineers and this is the reason why I think it is ''basic''.
Comment: Linear algebra by Hoffman Kunze
Comment: As far as Complex analysis goes, depending on which side you want to go... I didn't mind Brown/Churchill but really enjoyed the Stein/Shakarchi book (this latter duo has a series of four books that are quite good, in my opinion).
Answer: Undergradute Analysis by Serge Lang
Mathematical Analysis by Tom Apostol
Principles of Mathematical Analysis by Walter Rudin
Calculus Volumes I and II by Tom Apostol
Linear Algebra by Serge Lang
Linear Algebra with Applications by W. Keith Nicholson
Complex Analysis by Theodore W. Gamelin
Complex Analysis by Joseph Bak and Donald Newman
Answer: Visual Complex Analysis, by Needham, is a wonderful book which helps gaining a lot of intuition on the subject (especially geometric and visual one).
Answer: Introduction to Real Analysis by Robert Bartle
Multivariate Calculus by James Hurley
Differential Equations by Shepley Ross
Complex Fundamentals of Complex Analysis for Mathematics, Science And Engineering (2nd Edition)
by E. B. Saff (Author), A. D. Snider (Author)
Introduction to Linear Algebra (Gilbert Strang)


User Form action in Excel Sheets

Question: I got confused about something. How can i control the excel sheet via userform?
For example:

Open user form by clicking form button on excel sheet
Create new excel sheet by clicking the button in user form.

Do i need to write the required code in the "module" section of vba or the "userform" section?
Answer: First, Create a new Module, and inside add a Sub, like the code below:
Public Sub Main()

' call a Use_ Form1
User_Form1.Show

End Sub

Second , in your Sheet, once adding a Button, you will get a message box to add Macro Name, Select Main.  Now, once you click on your Sheet's Button, your Main module will run, and it will Call the User_Form1.Show.
Third, in your User_Form, add a button (in this example it's Btn_1), once you click it, add the simple code below (just for testing purposes).
Private Sub Btn_1_Click()

' add a Sheet to this workbook, after the last one, and name it "Test"
ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)).Name = "Test"

End Sub

And that's an example how to connect between the 2 objects.

User Form action in Excel Sheets


Proof approach: A 7x7 matrix with 15 ones can allow at least three marriages

Question: This is quite difficult to prove imho with regards to Hall's Marriage Algorithm  I can visualize a number of scenarios that work (i.e. put ones from the first entry to the fifteenth, or across diagonals) and they all work.  However I'm not so sure how to write it down for a generic case.  Can someone give me some help?
Answer: Minimise the number of possible marriages by reducing the number of matches i.e. number of rows or columns that have any ones.
Since any row or column can have at most 7 ones, two rows or two columns can have at most 14 ones between them. Then you have an extra one that must go in a different row or column, and this entry dictates a marriage. Then the previous row/column has six further possible exclusive matches to give a second marriage; then the initial row/column has five further possible exclusive matches to give a third marriage. So there is a minimum of 3 marriages.


2 non-linearly correlated variables

Question: I am currently looking at some code that uses 2 independent variables, which look as follows when scatter plotted:

Clearly, they are (non) linearly correlated. IMHO this violates a key assumption of a linear model (the code currently uses PROC GLMSELECT to fit the model). is there anything I could do to rectify this? Any feedback would be very much appreciated. Thanks.
Answer: You could try with the natural log, $ln(\dotso)$, like so (in R):
<code># Generate some data that fits the picture:
x <- seq(from = -6, to = -0.01, by = 0.01)
y <- 0.03/x
plot(x,y)
</code>
And you get this:

You can add some more noise to the picture, if you prefer, but it doesnt really matter. Now, if we assume there are no numbers in either $y$ or $x$ which are $=0$. We can simply take logs of the absolute numbers:
<code># Now make all the numbers positive, and take ln(...):
plot(log(x*-1), log(y*-1))
</code>

Which is linear (sorta)... It will not be this pretty for your data, but the idea is the same.
Comment: sorry not sure how this helps in my situation where I want to avoid linear correlation like this.
Comment: I am confused by your statement, in OP you say that the variables are non linearly related, and ask what you can do to rectify this. This is what I try to answer, can you please clarify?
Comment: Sorry about the confusion. First of all I would like to know, if you agree with me that the variables are correlated and thus violate one of the key assumptions of linear regression. if this is true I would like to hear about possible solutions.
Comment: Btw one suggestion I had was to ignore everything less than -1 for both variables. If you look at the above scatter, this corresponds to zooming in and it looks much less correlated when you 'zoom' in.
Comment: I don't understand, correlation of variables is not a problem for the linear model... It's the entire idea? Are you talking about two independent variables? Those can be correlated aswell they just can't be perfectly correlated (which yours definitely aren't)
Comment: Yes I am talking about 2 independent variables - sorry maybe that's the cause of this confusion. So you in your opinion, looking at the scatter plot, this non linear correlation is not be a problem for use in a linear reg model?
Comment: No not at all, you can calculate the correlation and check that it isn't 1 or -1.

2 non-linearly correlated variables


Man in The Middle Attack, or something else?

Question: I was wondering if someone could help me out with this problem.
We have a webservice that is available only through https:// port 443.
Using netstat I see that there is particular ip that tries to connect to the server.
For example, all the other connections connect to the server from their port to the server's 443 port (normal https behaviour).
This particular ip: 126.96.36.199, tries to open connection from remote port 443 to a local port. (Its state is always TIME_WAIT, it goes away and then it comes back as TIME_WAIT after minute or so.
I am reporting this ip in the open because it has been reported here before:
https://www.abuseipdb.com/check/18.104.22.168
There is a CISCO firewall that protects the company network and my system admin told me that he could not find any hits from that ip to the server.
But the netstat tool reports otherwise.
Can you offer me any suggestions? Or tell me what is going on? Thank you!
That is what the netstat command shows:
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 server_ip:32884         126.96.36.199:443      TIME_WAIT
tcp6       0  69000 server_ip:443           remote_ip:65045     ESTABLISHED
tcp6       0      0 server_ip:443           remote_ip:20467     TIME_WAIT
tcp6       0      0 server_ip:443           remote_ip:55430     TIME_WAIT
tcp6       0      0 server_ip:443           remote_ip:65248     ESTABLISHED

Thank you all for helping me out solve this problem. It was a call to gravatar after all
Comment: Well, the first thing to try is seeing which process uses this port. Check the output of `netstat -tulpen`.
Comment: Glad you solved it, but please mark an answer as accepted so the question is closed.
Answer: Probably there's no-one trying to connect from 443 to a local upper port. Connections usually originates from dynamic port range (49152 through 65535). Is the 32884 always 32884 or is it actually always something within that range?
The IP address 188.8.131.52 hosts wordpress.com and gravatar.com etc. It's way more likely that your server is connecting to that server to gather some information. We couldn't know the details, because we don't know your site and what's its purpose.
Comment: Thank you. I just found out that this was the case. It took me a while since the web application is a paid php web application protected/encrypted  by http://www.ioncube.com, so I had take a better look at the profile page. Netstat shows connection to gravatar.com shorty after you login into the web app.
Answer: A normal hit to  188.8.131.52 redirects to https://en.gravatar.com/. This is definitely not MITM attack.
Your website is using a module of gravatar and it is trying to connect to its server to gather data i.e the User avatar to be used for comments. You need not worry about it and since it dies after TIMED_WAIT it is not able to connect to the server.
You should not be worried since the IP is not detected from the firewall. It would be best to fix the module trying to access gravatar and allow access to it.
Comment: Thank you. I just found out that this was the case. It took me a while since the web application is a paid php web application protected/encrypted  by http://www.ioncube.com, so I had take a better look at the profile page. Netstat shows connection to gravatar.com shorty after you login into the web app.
Comment: Cool. That this is resolved. If the answer was helpful do upvote. This would be my first. :)
Answer: This is an outbound connection, your server is connecting to a remote address, not the other way around. That usually translates to: you have some background service that sends data somewhere. To work out what the process is, use netstat (with root permissions):
netstat -tulpn

If you don't see it in the output, try (also as root):
lsof -i tcp

That will show you all the connections with the relevant process name. Find your outgoing connection, look at the process.
As an example, my server regularly maintains an outbound connection to a foreign https port, because I have Nginx Amplify running, and it needs to report server statistics to it.
You can see an example of this here, in my server's current output (redacted):
joe@testbed~$ sudo lsof -i tcp
COMMAND     PID      USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
amplify-a  6355  user-nam   14u  IPv4  7657189     0t0  TCP testbed.avx.local:36970->ec2.us-west-1.compute.amazonaws.com:https (ESTABLISHED)

My server there is making an outbound connection from a random port to a https port, just like yours. Run the commands, find the process, then you can decide if it's malicious or not.
Answer: The IP 22.214.171.124 ended up in my firewall also today. It is indeed from gravatar.
The reason for the IP getting caught is because the TCP connection had both syn and fin flags and my firewall adds those connections to a list.
From https://www.juniper.net/documentation/en_US/junos/topics/concept/tcp-syn-fin-flags.html

Both the SYN and FIN control flags are not normally set in the same
  TCP segment header. The SYN flag synchronizes sequence numbers to
  initiate a TCP connection. The FIN flag indicates the end of data
  transmission to finish a TCP connection. Their purposes are mutually
  exclusive. A TCP header with the SYN and FIN flags set is anomalous
  TCP behavior, causing various responses from the recipient, depending
  on the OS


How do I hide the core version to the outside world?

Question: I was bothered in knowing with whatcms.org a version can be given for drupal 8, even a minor version - no minor version, instead, when I tried with a drupal 7.
Curiously enough in my case, I got a version slightly newer (just one minor version ahead), but I'm concerned anyway, should I not?
I'm thinking of every situation where a security update cannot be performed right away.
I don't even know how can the version be guessed from outside.
I issued a tail -f on the access log while pressing the Detect CMS button on whatcms.org, but, mysteriously, I got no log entry from there. Perhaps they cache the previous results on the same site not to perform a fetch each time the button is pressed with the same domain string input?
Comment: This question comes up over and over again, and over and over it is the same answer: **There is no security through obscurity**.  Why should an evil bot waste ressouces with an additional version check request, if he can right away hit the vulnerable URL?
Comment: You can know the exact version Drupal.org is using by looking at https://www.drupal.org/CHANGELOG.txt. For a Drupal 8 site, the relative path is slightly different: [/core/CHANGELOG.txt](https://git.drupalcode.org/project/drupal/-/blob/8.1.x/core/CHANGELOG.txt). Only the Drupal 9 [CHANGELOG.txt](https://git.drupalcode.org/project/drupal/-/blob/9.5.x/core/CHANGELOG.txt) file is vague enough to make just understand the site is running Drupal.)
Comment: Does this answer your question? [How can I obscure what I am using to run my site?](https://drupal.stackexchange.com/questions/237/how-can-i-obscure-what-i-am-using-to-run-my-site)
Comment: If they were doing those checks, they would not even try to access a URL that is available from a site implemented in .NET in a Drupal site, or a WordPress URL in a Drupal site. As @Hudri said, they just try to gain access using a vulnerability; if they aren't able, they just pass to the next site.
Comment: I'm sorry for the nth question on the same subject. Before posting I tried to find an answer, but I couldn't. I'm not knowledgeable about attacking practices, so I couldn't tell whether knowing a version number could be relevant to an attacker or not. Besides I'd be however curious about how version can be read from outside, even disregarding in my case I read a version slightly different from the real one. In the HTTP headers I read just, it's a drupal CMS. So I wonder where the other piece of information can be read withouth accessing the file system or the administration interface.
Comment: This topic is not really specific to Drupal or PHP or any CMS, this is a general principle in IT. For version guessing, there are a few of metadata  (readme's, YMLs, package files...) files with versions numbers and years in it that allow version guessing.
Comment: One never stops learning, @Hudri... I thought there could be a surgical practice to know the exact version, but I realize it may come up to be just a guess for a *probable version*. You named some kind of file. I wonder what the algorithm whatcms.org uses may be for drupal. It's a matter of curiosity, I'm not neglecting your considerations about the idea of hiding versions. ;-)
Comment: I believe this is a duplicate of https://drupal.stackexchange.com/questions/237/how-can-i-obscure-what-i-am-using-to-run-my-site/20608#20608
Answer: If you want to hide the Drupal version then you can use the following module:
https://www.drupal.org/project/remove_http_headers
Comment: I say don't try to hide it, be proud of running Drupal dang it!
Answer: whatcms.org does not seem to get the right Drupal version used on a site; for drupal.org, it reports it is using Drupal 7.92, while drupal.org is using Drupal 7.96, which is the version visible in its CHANGELOG.txt file.
While Drupal 8.x stopped to give detailed information about the changes in the recently created releases in its CHANGELOG.txt file, it is possible to understand whether a site is using Drupal 8 because that files contains the following line.

For a full list of fixes in the latest release, visit: https://www.drupal.org/8/download

Drupal 9.0.x changed that line to the following one, more generic.

For a full list of fixes in the latest release, visit: https://www.drupal.org/latest-release

There could be other publicly accessible files that can be used to understand what Drupal version is used, especially knowing which JavaScript libraries are used from each Drupal version (and which version of those JavaScript libraries). For example, the absence of the jQuery Once library, on a site that could be either be using Drupal 9 or Drupal 10, says the site is using Drupal 10 or any higher version; if the installed jQuery version is 3.6.3, the site could be using Drupal 9.5, 10.0.x, or 10.1.x, any release created after December 21,  2022.
You can alter the HTTP headers returned by a Drupal site, but sites could still gather information from the files they are still able to access, including any JavaScript or CSS file, which are necessary for a browser to correctly render Drupal pages and cannot be made inaccessible.


Disjoint union of the torus and the sphere is a boundary of a compact manifold.

Question: What is the disjoint union of the torus $S^1\times S^1$ and the 2-sphere $S^2$?
I ask, because I am trying to prove that the torus is cobordant to the sphere. By definition, this means that their disjoint union is the boundary of a compact maniofold with dimension 3.
So, my next question is: Is the disjoint union the boundary of a compact manifold of dimension 3?
Comment: Your question «what is the disjoint union of the torus and a $2$-sphere?» is very weird… What sort of answer do you expect? The only answer is «it is the disjoint union of the torus and a $2$-sphere».
Answer: Take a solid torus in $\mathbb R^3$ and remove a small open ball from the inside.
Answer: The tangent bundle to the torus is trivial, so its Stiefel-Whitney classes vanish. While the tangent bundle to the sphere is stably trivial. The Stiefel-Whitney class is stable, so the sphere's Stiefel-Whitney classes also vanish. It is a theorem that there exists a bordism between two manifolds if and only if they have the same Stiefel-Whitney numbers. Therefore there is a bordism between the torus and the sphere.
More explicitly, let's take a large 3-ball, and remove a small open solid torus from the center. A ball with a ring hollowed out. Here we have a 3-manifold with boundary a 2-sphere union a torus.
Comment: I find it extraordinary that you understand what a Stiefel-Whitney class is and at the same time ask if the ball is compact :-1
Comment: Yes, a ball is compact
Comment: @MarianoSuárez-Álvarez in case the asker could not use an answer in terms of Stiefel-Whitney classes, you and I both offered explicit examples of the requested bordisms.


What is the determinant of a null matrix?

Question: What is the determinat of a null matrix of dimension $n×n$?
Comment: The determinant of the matrix $A=0$ is simply $0$ , no matter what $n$ is.
Answer: In fact, if any square matrix has one row or one column of zeroes, its determinant is zero. Yours is a special case of this statement, which is easily checked by cofactor expansion.


Is it possible to have seasonality at 24, 12, 8 periods in hourly based wind power data?

Question: I have taken hourly-based wind power data, by taking its periodogram after making it stationary in R. It gives me four seasonal patterns at periods of 24, 12, 08, and 06, as shown in the figure below.
Is it possible to have sub-hourly seasonality in my wind power data?
The data is given as follows:
Comment: *"after making it stationary in R"* Could you elaborate on this.
Comment: You probably mean "sub-*daily*", not "sub-*hourly*" seasonality.
Comment: when I take ndiffs() of the data, it shows me to take non-seasonal differencing (stationarity). i read it in this post, https://stats.stackexchange.com/questions/16117/what-method-can-be-used-to-detect-seasonality-in-data
Answer:
TLDR; The signal period is $24$ hours, eventhough you have your power spectrum indicating components with a smaller period. The components with period $6, 8, 12$ hrs also repeat themselves every $4 \times 6 = 24, 3 \times 8 =24, 2 \times 12 =24 $ hrs. So they all have, in a way, a common period of 24 hrs.

It gives me four seasonal patterns at periods of 24, 12, 08, and 06

This sounds like you get overtones. If your periodogram is a sort of Fourier spectrum, then this is not weird. It means that the daily pattern consists of more structure than just a single sine wave.
This doesn't mean that the period of the signal is smaller than 1 day. Below is an example signal constructed with several overtones (wave lengths smaller than 1 day), and you can see that the period of the signal is 1 day. The higher frequency signals influence the shape but not the period of the signal.

The period of a function that is a sum of periodic functions is the least common multiple of the periods of the functions in the sum.
<code>### t is time for one week of data sampled every ten minutes
t = seq(0,7*24*60,10)

### some example measurement of data that depends on sin waves with multiple sub-daily periods
Td = (24*60)/(2*pi)  ### daily period
y = 2 + sin((t+1000)/(Td)) + 0.4* sin((t+1200)/(Td/2)) + 0.1* sin((t+800)/(Td/3)) + 0.1* sin((t+1000)/(Td/4))

### plot
plot(t/24/60,y+rnorm(7*24*6,0,0.2),
     type = "l", xlab = "time in days", ylab = "signal",
     main = "example of signal with a daily period, but several overtones")
</code>
Comment: Sir thank you for your kind response, I want to check the number of seasonal patterns in my wind data, but when I take built-in mstl() function in R, it asks me to provide the frequencies at which these seasonal patterns occur. these frequencies I don't know. when I take acf plots and pacf plots to see seasonal patterns then it gives me the spikes at an integer multiple of 24 periods and above and below of this period. which is more confusing for me. that's why i tried periodogram of my wind data and I got more confused.
Answer: This suggests a daily periodic signal with harmonics
When looking at time-series data in the frequency domain, it is common for periodic signals in the data to consist of a main frequency and then a set of harmonics.  The harmonic frequencies are integer multiples of the main frequency of the signal.  This occurs because each of the spikes in the frequency domain correspond to a sinusoidal wave in the time domain, and the actual periodic signal in the time domain is often not a perfect sinusoidal wave.  Thus, what you have here sugggests that your wind power data has a periodic daily signal that is not a perfect sinusoidal wave (but which can be created as a weighted sum of a main sinusoidal wave and then four harmonics that are smaller sinusoidal waves at the harmonic frequencies).
Comment: sir thank you for your response, what I am looking for by taking the periodogram of my wind data is to find out the exact number of seasonal patterns (seasonality). which can be found by taking the mstl() function in R, but the problem with mstl() in R is to tell frequencies, which I don't know.
Answer: Many things are possible. (Here is one possible data-generating process that might lead to such sub-daily seasonalities, but no, I'm not really serious about that.)
I am not an expert in wind power generation as such, however, I find such a periodicity extremely unlikely. I understand that wind could have intra-daily patterns (differences between night and day), i.e., a seasonal period of 24 hours, and intra-yearly patterns (differences between summer and winter), i.e., a seasonal period of about 8766 hours. (These are examples of multiple-seasonalities - you may find the tag wiki helpful.)
However, other patterns simply don't make a lot of sense from a data generation point of view. Yes, the moon might have some very weak effect on the wind, perhaps via tides, so we might have intra-monthly patterns. I see no reason why the wind itself should have intra-weekly effects. Conversely, wind power generation might actually have such patterns: since electricity demand has weekly patterns, it might be that wind farms get cycled up or down with a certain weekly influence. But subdaily patterns at all these periodicities sound like an artifact or an error to me.
I have to admit that I am a forecaster and think like one. To a forecaster, the question is not so much whether a structure is present in a time series, but whether it helps us forecast the series better. As such, I naturally turn to papers about forecasting wind power, e.g., something connected with a good journal like the International Journal of Forecasting, and then I start skimming them on whether they report this kind of seasonality. Here is a paper that sampled in 10-minute buckets and found daily seasonality ($24\times 6 = 144$) periods per cycle - nothing about the kinds of seasonality you found. The GEFCom2014 did include a competition on wind power forecasting, but the summary paper does not go into details on what seasonalities were modeled by the winning methods. You might be able to get a better idea of what other people have found with a deeper literature search.
Comment: @User1865345: I like to say that the proof of the pudding is in the eating, and the proof of the model is in the prediction or forecast. I would not assume everyone here to agree.
Comment: If this is in a coastal area, patterns during the day (initially the water is warmer, then the land warms up faster etc. changing the wind patterns - vs. night where things cool down) are certainly a known thing and might be in ~ 6 to 8 hour periods. Would not hold in all locations (on average, I guess this gets water down).
Comment: @Björn: I would expect effects like that to lead to intra-daily patterns. but not subdaily ones with two or more cycles per day. But then, I'm not an expert in coastal wind dynamics...
Comment: As well as any small daily and annual pattern, you may also need to consider the much larger impact of very short-term autocorrealtion (if it is very windy now then it is likely to be windy in an hour's time) - it is surprising that the $0.041667$ uptick is not the highest.  The whole shape of the chart looks strange, and I almost wonder if it is a mix of data collected with different time intervals.
Comment: The apt xkcd reference and the precious statement: _To a forecaster, the question is not so much whether a structure is present in a time series, but whether it helps us forecast the series better._ Thank you. $+1.$
Comment: sir thank you for your detailed answer, I have also searched for research articles, about whether or not this kind of seasonality reported earlier, but I also couldn't be able to find anything like this. I am trying to find out the exact number of seasonality present in my wind data.
Comment: I would think that the other answers that point to likely harmonics of your intra-daily patterns as a possible explanation, are almost certainly right. Take a look at an STL decomposition of your data, which is not limited to highly regular sine/cosine seasonal patterns, for potential enlightenment.


haml_tag not returning any string

Question: Hi I've tried to copy my old haml_tags and it seems either they are not working for Rails 3.1rc4 or i'm doing somethign wrong. Can anyone point me to the right direction?
def bonus_value_of(stat)
  bonus = current_user.character.send("bonus_#{stat}".to_sym)
  capture_haml do
    haml_tag :span, :class => "positive" do
      "+#{bonus}"
    end
  end
end

thats my code which i call with
= bonus_value_of(stat)

and all i get is a blank span with positive class but no content(not even the plus)
is this a bug?
Answer: Here's my version.
1.Your helper should be in controller's helper, not in module Haml::Helper like it was described in some article.
2.Change your helper to this:
def bonus_value_of(stat)
  bonus = current_user.character.send("bonus_#{stat}".to_sym)
  haml_tag :span, :class => "positive" do
    haml_concat "+#{bonus}"
  end
end

And then use it in your view like this:
- bonus_value_of(stat)

Answer: I just ran into this. I needed to pass my span text as the second value to haml_tag.
def bonus_value_of(stat)
  bonus = current_user.character.send("bonus_#{stat}".to_sym)
  capture_haml do
    haml_tag :span, "+#{bonus}", :class => "positive"
  end
end

haml_tag not returning any string


Difference between 2 mono/stereo setup?

Question: Don't mind about "Guitar", it could be Bass or anything else. Imagine you have 2 setups:

Guitar -> Pedals (stereo end) -> 2 Amps running -> Mixer
Guitar -> Pedals (mono end) -> 1 Amp running -> Rec Out/Phones -> Split to 2 channel -> Mixer

Let's say (on 1st option) rather than running the delay in stereo, I run it on mono (so it won't have ping-pong delay), but I put chorus and reverb in stereo. On the other option, I pan each channel (on the mixer) hard left and hard right. Would it be any difference? If there is, what's the differences?
Comment: You've already alluded to the difference, in your question - If the chorus and reverb are stereo algorithms, then you'll lose their stereo effect by going to mono then splitting.
Answer: Once you've lost the stereo image by going mono, the signal in any split subsequently will be the same in both channels. So each side will sound the same. If there is a stereo output,initially, from whatever pedal, then that integrity needs to be retained, as the moment it gets 'monoised', there will be no difference between each sound, left/right or one/two channel.

Difference between 2 mono/stereo setup?


Simple problem with regex pattern

Question: please help me get the link and text from this tag.
 has to be included because I want the links from that specific tag.

Text

my work so far is
<?php

$string = file_get_contents('http://www.domain.com');

$regex_pattern = "";

unset($matches);
preg_match_all($regex_pattern, $string, $matches);

foreach ($matches[0] as $paragraph) {
echo $paragraph;
echo "
";
}
?>

Thank you in advance
Comment: possible duplicate of [Regular expression for grabbing the href attribute of an A element](http://stackoverflow.com/questions/3820666/regular-expression-for-grabbing-the-href-attribute-of-an-a-element)
Comment: additional usage examples: http://stackoverflow.com/questions/3893375/how-can-i-scrape-a-website-with-invalid-html/3894558#3894558
Comment: *(related)* [Best Methods to parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662)
Answer: Don't use regex to parse HTML. It's a bad idea. Use an HTML/XML parser. Since you are using PHP, you can try using PHP Tidy or DOMDocument. It will make your life much easier.
Comment: I don't think Tidy is really appropriate here -- it offers only the most basic DOM traversal.  DOMDocument + XPath is preferable, especially in the context of the OP's requirements.  He's essentially described an xpath query something like `//h3[@class="post-title entry-title"]/a/@href`
Comment: @Frank I think it depends on what he wants to use. XPath would, of course, be the best. But I find Tidy useful if I'm getting HTML from some other source. I use Tidy to clean up the HTML before I parse it.
Comment: Hi there I have managed and got the link! thank you! But how can I get the text also ?
Comment: @Giannis What are you using? Tidy or `DOMDocument`? If you're using `DOMDocument`, you should be able to obtain a reference to a `DOMNode` object. This object has a `$textContent` property which should give you what you need. See [`DOMNode`](http://www.php.net/manual/en/class.domnode.php).
Comment: I did it :) My last question why I can do it on this link ? http://feeds.feedburner.com/blogspot/hyMBI Does it have any protections ?
Comment: @JBCurious I'm not sure what you mean by "protections"? What are you trying to do with that site?
Comment: @vivin -- DomDocument does pretty well with your average untidy tag-soup HTML, surprisingly; the only bad HTML I remember it struggling with had a  tag right smack in the middle of it (worst. html. ever.).
Comment: @Frank Ah, I didn't know that. I guess I'm just paranoid about the structure!
Answer: I would recomend you to use DOMDocument and XPath to extract the url from the page instead of using regexp.
This tutorial gives you some starters how to use xpath and dom.
http://www.merchantos.com/blog/makebeta/php/scraping-links-with-php#php_dom
edit:
If you use firebug-addon in firefox, you can inspect your element on the page, and copy it's xpath.
Answer: The regex:
(?<=href=").+(?=")

Should match anything in between href tags
You can test this in RegexStorm
Answer: Following your example, this regex will find "http://mymplogk.blogspot.com/2011/03/h_25.html" and "Text":
$regex_pattern = '/
]+class\s*=\s*[\'"]post-title entry-title[\'"][^>]*>.*?]+href\s*=\s*"([^"]+)"[^>]*>([^<]*)</s';

This matches single or double quotes around the h3 tag, and allows additional attributes in h3 tag and optional whitespace between attributes and values.  It also matches multiple times in $string, e.g.
$string = '

Text

doot

More Text

';

Comment: Hi there, thanks! It can display any results but i think this is because  has single quotes on page source, not double. Please can you make me a modification on your pattern? I can't escape the characters correctly by myself. This is what I had before $regex_pattern = "/([^`]*?)<\/h3>/";
Comment: (I don't know if this is a good answer, but +1 for polishing the edits!)

Simple problem with regex pattern


A detail in proving that a sequence of uniformly integrable random variables converges weakly.

Question: I would like to prove the following result that is stated in a textbook, but I am not able to grasp a couple of details in the proof.
Let $\{X_n: n \in N\} $ be a sequence of uniformly integrable random variables on some probability space . There there is a subsequence which converges weakly in $L^1(P); $ i.e., there is a random variable $X $ such that
$$ E[X_nZ] \to E[XZ] $$
for every random variable $Z\in L^\infty(P). $
The idea provided is to start with a sequence of random variables like
$$ X_{n,k} = X_n\cdot 1_{\{|X_n|\le k\}}  $$
for each $k. $
This sequence is bounded in $L^2 $ by construction and therefore there exists a subsequence which
converges weakly in $L^2 $  (is there a special name for this result?)
Then, and this is where I have my real issue, they asy that by the Cantor diagonalization procedure, we can extract a single subsequence $\{n_j: j \in N\} $ such that
$$ X_{n_j,k} \to L_k $$
weakly for each $k. $
I fail to see how I can extract a single sequence that converges to $L_k $ starting for example from the sequence $X_{1,1}, X_{2,1}, X_{3, 1}, \ldots $ If my recollection is correct, I need to keep using subsequences of subsequences to make the Cantor diagonalization process work.  But, how is a
subsequence of $X_{1,2}, X_{2,2}, X_{3,2}, \ldots, $ a subsequence of the first one?
I tried everything I could think, but nothing.  The rest of the proof I can see, but this Cantor "thing", I cannot.
Any insight offered greatly appreciated.
Thank you.
Maurice.
PS I have barely a modicum of exposure to Functional Analysis and I wonder if this result has something to do with the Dunford-Pettis theorem.
Comment: You cut down to a subsubsequence for $k=2$, then a subsubsubsequence for $k=3$, etc.  If you make appropriate control of the rates of convergence of these subsubsub...subsequences, your diagonal subsequence will converge.
Comment: Could you elaborate, please? If I start say with a subsequence for k=1, k=2, k=3, etc...  How do I choose the subsequence according to Cantor diagonalization scheme so that it converges to L1, L2, L3, etc....     This is what I am not seeing..   All random variables in the sequence for k=1 are bounded in absolute value by 1. those for k=2 are bounded by 2. If L2 were equal to , say1.5, how can a sequence that converges to something in [-1,1] converge to 1.5?
Answer: Extract from $\left(X_{n,1}\right)_{n\geqslant 1}$ a subsequence $\left(X_{n_k^{(1)},1}\right)_{k\geqslant 1}$ which converges wealky to some $L_1$.
Then extract from $\left(X_{n_k^{(1)},2}\right)_{k\geqslant 1}$ a subsequence
$\left(X_{n_k^{(2)},2}\right)_{k\geqslant 1}$ converging weakly to some $L_2$ in $L^2$. By definition, $\{n_k^{(2)},k\geqslant 1\}\subset \{n_k^{(1)},k\geqslant 1\}$.
Now we can continue the process: suppose that we found sequences of integers $\{n_k^{(1)},k\geqslant 1\},\dots,\{n_k^{(i)},k\geqslant 1\}$ such that
$$
\{n_k^{(i)},k\geqslant 1\}\subset \{n_k^{(i-1)},k\geqslant 1\}\subset\dots\subset\{n_k^{(1)},k\geqslant 1\}
$$
and $\left(X_{n_k^{(u)},u}\right)_{k\geqslant 1}$ converges to some $L_u$ weakly in $L^2$. We have to find an increasing sequence of integers $(n_k^{(i+1)})_{k\geqslant 1}$ such that  $\{n_k^{(i+1)},k\geqslant 1\}\subset \{n_k^{(i)},k\geqslant 1\}$ and $\left(X_{n_k^{(i+1)},i+1}\right)_{k\geqslant 1}$ converges to some $L_{i+1}$ weakly in $L^2$. To do so, extract from $\left(X_{n_k^{(i)},i+1}\right)_{k\geqslant 1}$ a weakly convergent subsequence in $L^2$.
To sum up, we found increasing sequences of integers $(n_k^{(i)})_{k\geqslant 1}$, $i\geqslant 1$ such that

for each $i\geqslant 1$, $\{n_k^{(i+1)},k\geqslant 1\}\subset \{n_k^{(i)},k\geqslant 1\}$ and
for each $i\geqslant 1$, $\left(X_{n_k^{(i)},i}\right)_{k\geqslant 1}$ converges to some $L_i$ weakly in $L^2$.

To conclude, let $n_k:= n_k^{(k)}$; by the first bullet, $(X_{n_k,i})$ is a subsequence of $(X_{n_k^{(i)},i})$ for all $i$.
Comment: Thank you Davide. The description is very clear. I follow the diagonal argument very well, no problem there. However, I still have one issue, just one. I get the first sequence $\{X_{n,1}\} $ and how to extract a subsequence from it that converges to $L_1. $ No problem there. But now, I take a further subsequence and for it I consider $X(n_k^{(1)}, 2) $ This is where I am having a hard time. If the first terms were either 0 or random variables in $[-1, 1] $, when I consider the second subsequence aren't these also 0 or bounded by $[-1, 1]. $? .... this is my crux.
Comment: Or perhaps do you mean that after I select the variables in the first subsequence,  I "filter" the original variables via the$I_{|X_n|\le k} $? In other words, I am not now filtering the $X_{n_j, 1} $ but the original $X_{n_j} $.. If I do this then things make sense. For some reason I guess that I was assumed that the original random variables were only used in creating $X_{n,1} $ and then I was applying the conditions to these which would only change the variables that were set to zero in $X_{n,1} $ but the others would remain equal to themselves.  That is what confuses me in the definition.
Comment: @Maurice Paradoxally, it seems that this particular setting makes the things more complicated. Actually, all you need in the following: for each $k\geq 1$ suppose that the  sequence $(Y_{n,k})_{n\geq 1}$ is bounded in $L^2$. Then using the above procedure,  there is an  increasing sequence of integers $(n_i)$  and random variables $L_k,k\geq 1$ such that $(Y_{n_i,k})_k$ converges weakly in $L^2$ tp $L_k$ for  all $k$. Then apply this to $Y_{n,k}=X_n\cdot 1_{\{|X_n|\le k\}}$.
Comment: Thank you, again, Davide. If you allow me one last request for clarification, please. I understand the diagonal scheme. My only doubt is about what I use as subsequences. Say we start with $Y_{n,1} = X_n\cdot 1_{\{|X_n}\le 1\}}. $ It is bounded in L2 and it has a convergent subsequence. Perfect. Now for the diagonal argument I need to pick another subsequence from this subsequence. But all elements in $\{Y_{n,1}\} $ are either 0 or r.v.'s bounded in $[-1,1]. $ So, only elements $Y_{n_k,2} =1_{\{|X_{n,k}|\le 2}  $ is different from $Y_{n_k,1} $ has to be one of those that were set to zero ?


Java unchecked or unsafe operations message

Question: I am getting the following error when compiling a Java class in BlueJ.
AuctionManager.java uses unchecked or unsafe operations.

This error is only displayed when the following deserialization code is in one of my functions:
try {
  ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename));
  ArrayList<AuctionItem> AuctionList = (ArrayList<AuctionItem>) in.readObject();
  in.close();
}
catch (Exception e) {
  e.printStackTrace();
}

Can I please have some information as to why this error is being displayed, and some help to use the deserialization code without the error.
Answer: First the message you get is not an error, is it a warning; it doesn't prevent you program from compiling, or running.
As for the source, it is this line:
ArrayList<AuctionItem> AuctionList = (ArrayList<AuctionItem>) in.readObject();
Since you are casting an object (readObject returns an Object) to a parameterized type (ArrayList<AuctionItem>).
Comment: What is the best way to fix the code so that the warning does not show?
Answer: user2351151: You can do this for warning doesn't show:
ArrayList tempList; // without parameterized type
try {
  ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename));
  tempList = (ArrayList) in.readObject();
  for (int i = 0; i < tempList.size(); i++) {
    AuctionList.add(i, (AuctionItem)tempList.get(i)); // explict type conversion from Object to AuctionItem
  }
  in.close();
}
catch (Exception e) {
  e.printStackTrace();
}

You must rewrite ArrayList with explict type conversion (you can use temporary ArrayList without parameterized type).


How to control from a module the block visibility of a block implemented by another module?

Question: The default options in the administrative page for block visibility (e.g. admin/build/block/configure/block/3) are not enough for my needs.
For security reasons, I do not wish to use the PHP option (Show if the following PHP code returns TRUE (PHP-mode, experts only).).  I plan to turn off all PHP configuration throughout the site.
The only route that remains available is to create a module that will control the visibility of certain blocks on specific pages.  I am an experienced module developer but I do not know how to implement this specific thing.
What API exist that I could use? Apparently it's possible in Drupal 7. What alternatives do exist in Drupal 6?
Edit:
I actually easily found the answer to my original question. Now, I want to be able to control from my module the visibility of a block implemented by another module. My specific use case is thus: core's aggregator.module  create feed blocks, but I want each feed block to be displayed on pages of certain types authored by specific users who are associated with specific feeds. I could re-implement the whole aggregator_block() or... I could let the aggregator.module do its job and simply control the visibility of the block that it produces. Is it possible?
Answer: You can call the aggregator's (or an other module's) block routines by doing something like this in your module...
$foo=module_invoke('aggregator', 'block', 'view', 'BLOCK_DELTA');
$content.=$foo['content'];

...with the resulting $content containing the html of the block in question.
So, it would be fairly trivial to include something like the above in your custom module's block view hook instead of copying all of the aggregator module's code into your module.
More information on module_invoke() here.
Just an FYI:  Using the visibility key set to PHP in hook_block() actually requires the <?php ... ?> brackets with the whole shabang being passed through eval() so IMHO I don't think it is all that much safer than using the Block UI's PHP option.
Comment: +1 Thanks. Your solution is much cleaner than what I was working on. Regarding PHP input and safety, I prefer to have PHP code within a module than having PHP filtering enabled on the web site. My (administrator) account could be hacked and if php.module is not enabled, the harm that the hackers can do is limited. They cannot change the code in the module. Thanks.
Answer: Edit: this answers the original question, but not the follow up.
I should have looked closer before asking.
Apparently, it's also possible in D6:
https://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_block/6
'visibility' = 2: Use custom PHP code to determine visibility. 'pages' gives the PHP code to use.
'pages' = custom PHP code when 'visibility' is set to 2.
I had seen that question but I thought it only applied to D7.
Can't set PHP block visibility programatically
I'll try that!


Can't connect to local IP address on OSX

Question: I'm trying to connect to a webserver that's running on my mac OSX 1.6. I'm able to connect to it locally using http://127.0.0.1:8888/myapp but when I attempt to connect to it using my machine's local IP address (http://192.168.1.15:8888/myapp IP shown below) from the same machine (or another on the network) I cannot connect. I can ping the LAN IP address.
I've tried adding IP forwarding to my router for port 8888 but it didn't help.
I've checked and the OSX firewall is disabled
Can anyone suggest what else is blocking the connection?
Here's what I get when I run ifconfig:
<code>~ :ifconfig
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
    inet6 ::1 prefixlen 128
    inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
    inet 127.0.0.1 netmask 0xff000000
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    ether 00:1f:5b:e8:16:4d
    media: autoselect status: inactive
    supported media: autoselect 10baseT/UTP <half-duplex> 10baseT/UTP <full-duplex> 10baseT/UTP <full-duplex,hw-loopback> 10baseT/UTP <full-duplex,flow-control> 100baseTX <half-duplex> 100baseTX <full-duplex> 100baseTX <full-duplex,hw-loopback> 100baseTX <full-duplex,flow-control> 1000baseT <full-duplex> 1000baseT <full-duplex,hw-loopback> 1000baseT <full-duplex,flow-control> none
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    inet6 fe80::21e:c2ff:febf:4809%en1 prefixlen 64 scopeid 0x5
    inet 192.168.1.15 netmask 0xffffff00 broadcast 192.168.1.255
    ether 00:1e:c2:bf:48:09
    media: autoselect status: active
    supported media: autoselect
fw0: flags=8802<BROADCAST,SIMPLEX,MULTICAST> mtu 4078
    lladdr 00:1f:5b:ff:fe:2b:b3:3c
    media: autoselect <full-duplex> status: inactive
    supported media: autoselect <full-duplex>
en5: flags=8822<BROADCAST,SMART,SIMPLEX,MULTICAST> mtu 1500
    ether 00:1e:c2:8e:0f:45
    media: autoselect status: inactive
    supported media: none autoselect 10baseT/UTP <half-duplex>
en2: flags=8922<BROADCAST,SMART,PROMISC,SIMPLEX,MULTICAST> mtu 1500
    ether 00:1c:42:00:00:00
    media: autoselect status: inactive
    supported media: autoselect
en3: flags=8922<BROADCAST,SMART,PROMISC,SIMPLEX,MULTICAST> mtu 1500
    ether 00:1c:42:00:00:01
    media: autoselect status: inactive
    supported media: autoselect
</code>
Comment: Try turning off the OS X firewall.
Answer: Your webserver is probably binding to the loopback interface by default.  Applications can "bind" to specific interfaces - if it only listens on the loopback interface, you'll be able to connect via a 127.x.x.x ip but not an external ip.  You can look at the "Network Utility" -> Netstat -> display state of all socket connections, which will display all open sockets.  Further debugging will require the relevant lines from this (probably the one on port 8888) and potentially what webserver you're running...
Comment: Thanks Steven,

I ran netstat but don't see any mention of port 8888. Running "netstat -a | grep 8888" returns nothing. My server (jetty) is still running and responding locally.
Answer: This was working fine for me and then it just stopped working all of a sudden.  I don't believe I changed anything in my Run/Debug configurations, but maybe I did.
Regardless, the answer is to add the --address=0.0.0.0 parameter to the Run/Debug configuration.  To do this:

Right-click your project.
Choose Run As... -> Run Configurations
Make sure your project is selected in the Run Configurations dialog and choose the Arguments tab.
Insert the argument:  --address=0.0.0.0

As I said, this was working for me right along and I hadn't set this parameter before that I remember.  Anyway, I added it and now things work fine.
TR
Answer: Unless this is programming related this question might belong on ServerFault or SuperUser.
In any case, if you are writing an application on Mac OS perhaps you need to specify
the exact interface your application is listening on.
Comment: Hi - I'm not exactly trying to configure a server - I'm developing locally and trying to connect to a Jetty application server that's hosting my GWT application. I'm not sure what you mean by "specify the exact interface". Do you mean protocol?
Comment: Hi,
No, It is very likely you have multiple interfaces , such as the ethernet interface, the wlan interface and of course the loopback interface. (fw0, en0, en1, lo0) You might have to be very specific about the interfaces on which your application has to listen for incoming requests.
Answer: BTW - I think this was user error. I think I was probably running GWT in hosted mode with a Firefox plugin. There was no webserver running or listening to port 8888 which is why it didn't show up!


MVC4 Why are these radiobuttons disabled?

Question: I have webpage with two text boxes and two radio buttons and one submit button.
If I wanna show the page, both of the radio buttons are disabled. I have tried true and false. And I have tried this way:
@using (Html.BeginForm("MyWeb"))
{
    Company:<input id="txtCompany" name="Company" type="text" size="50" />

    Branche:<input id="txtBranche" name="Branche" type="text" size="50" />

    En:<input type="radio" name="AND" checked /><

    Of:<input type="radio" name="OR" checked="checked"/>

    <input type="submit" value="Submit" name="Submit" />

}

My question is why the radio buttons are disabled? The rest of page is only selected text.
Answer: They are not actually disabled, its just that they cant be 'unselected' because there is no alternative selection.
Your radio buttons have different names ("AND" and "OR") which mean they do not belong to the same group. Make the names the same as the property you want to bind to on postback. In this case, property string MyProperty will be either "AND" or "OR" depending on the selection
<input type="radio" name="MyProperty" value="AND" checked /> // this on will be checked
<input type="radio" name="MyProperty" value ="OR"/>

Note. I strongly recommend you learn to use the strongly typed html helpers rather than trying to write html by hand
Comment: Everything works fine now. The last thing I had to do, was adding the latest building dll on my website.


Problema de carregamento de função Node socket.io

Question: Tenho o seguinte código:
module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('chat/index');

        var io = app.get('io');

        io.on("connection", function(socket) {
            console.log("Usuario Conectado");
            socket.on('chat message', function(msg) {
                var userdata = socket.handshake.session.userdata;
                msg = userdata.name + ' : ' + msg;
                io.emit('chat message', msg);
            });

            socket.on("setName", function(name) {
                var msg = 'Usuario ' + name + ' Conectado';
                var userOnline = {
                    'id': socket.id,
                    'name': name
                };
                io.emit('chat message', msg);
                io.emit('user online', userOnline);
                socket.handshake.session.userdata = {
                    'id': socket.id,
                    'name': name
                };
                socket.handshake.session.save();
            });

            socket.on("disconnect", function() {
                var userdata = socket.handshake.session.userdata;
                if (userdata) {
                    var msg = 'Usuario ' + userdata.name + ' Desconectado';
                    io.emit('chat message', msg);
                    io.emit('user offline', userdata.id);
                    delete socket.handshake.session.userdata;
                    socket.handshake.session.save();
                }
                console.log("Usuario Desconectado");

            });
        });

    });
};

Toda vez que a função app.get('/' é executada cria uma nova conexão io.on("connection". Isso está gerando varias conexões a cada acesso. Existe alguma maneira de abrir a conexão fora da função app.get('/'?
Answer: Não testado mas você pode tentar se conectar fora do get, algo assim:
module.exports = function(app) {

    let io = app.get('io');
    io.on("connection", function(ret) {
        let socket = ret;
    });

    app.get('/', function(req, res) {
    // uso do socket aqui

Comment: já avia tentando isso antes mas ele retorna o seguinte erro: io.on("connection", function(ret) {
      ^

TypeError: Cannot read property 'on' of undefined
Comment: Significa que o `app.get('io');` não está funcionando (ou é assíncrono).


Numpy: appending items to matrix-like array

Question: I used to code in R and now trying to find my way into python. I have been using lists most of the time but now I need to get things done with numpy. Somehow this seems to work quite differently in comparison to R and most of the time I run into problems of broadcasting input arrays from different shapes. Maybe if I can figure out what's going wrong in the following code, I'll be able to understand better what numpy is trying to do and how I can address certain parts of an array.
import numpy as np

a = np.array((1,2,3,4))
b = np.array((2,4,6,8))
c = np.array((3,6,9,12))

myArray = np.asarray((a,b,c))

now I would like to append each row on myArray with its mean. I tried this:
for i in range(myArray.shape[0]):
    myArray[i] = np.append(myArray[i,:], np.mean(myArray[i,:]))

and I get "could not broadcast input array from shape (5) into shape (4). I figure, it tries to squeeze the new item into the old array of size four, whereas I would like to append it. How do I do that?
My desired output would look like:
[In] print myArray
[Out] [[1.0  2.0  3.0  4.0  2.5]
      [2.0, 4.0, 6.0, 8.0, 5.0]
      [3.0, 6.0, 9.0, 12.0, 7.5]]

Answer: Get the mean/average values across rows with .mean(1) and then stack those alongside the input array as two "columnar blocks" with np.column_stack, like so -
np.column_stack((myArray,myArray.mean(1)))

For doing this in a loop, you need to initialize and store, as shown below -
m,n = myArray.shape               # Get shape of input array
# Define output array with same rows as input, but one more column in it
myArrayOut = np.zeros((m,n+1))
for i in range(myArray.shape[0]):
    # Store each row alongwith its mean as the last element
    myArrayOut[i] = np.append(myArray[i,:], np.mean(myArray[i,:]))

Comment: @offeltoffel It would depend on the actual use-case, but for performance (which is why people go for NumPy), I would go with vectorized methods. Please be mindful of that.
Comment: I updated the question and added the desired output. column_stack looks great, but can you also apply it in a loop? I might have to add different values to these arrays

Update: ok, I calculated a list "d" that contains all desired values and than column-stacked myArray and d. That works, but I'd have to create a new list for each item to append. Maybe there is an easier way to do it?
Comment: @offeltoffel So, are you looking for list of arrays or a single array as output?
Comment: Single array output would be the most convenient. The idea of "initializing and storing" is great, since I always know the size of the final array, so I can create it in advance and then fill it with the stacked or appended values. Thanks!


html float right set the span in new line

Question: How to set two span inline in opera, where the html this:

                Text

                    Applications

Answer: CSS:
#board-sub-header span { float: left; width: 50%; display: block; }

http://jsfiddle.net/EKQkS/


Function or code to compare multiple sheets in Excel and display them sorted in ascending order in a new sheet

Question: I have a workbook which has let's say 3 similar worksheets. Each from different supplier. I want to compare them to find out who is cheaper and who is the cheapest with each and every item.
For example:
Worksheet 1 (D) (stands for David)
<code>    A            B             C             D
    1            quality 1     quality 2     quality 3    .....
    2 Apple      20            30            40
    3 Orange     25            33            46
</code>
Worksheet 2 (O) (stands for Oliver)
<code>    A            B             C             D
    1            quality 1     quality 2     quality 3    .....
    2 Apple      18            30            35
    3 Orange     25            35            46
</code>
Worksheet 3 (H) (stands for Harry)
<code>    A            B             C             D
    1            quality 1     quality 2     quality 3    .....
    2 Apple      22            33            44
    3 Orange     20            36            39
</code>
I expect the output to be something like this:
Worksheet 4 (sorted by the cheapest)
<code>    A            B             C             D
    1            quality 1     quality 2     quality 3    .....
    2 Apple      O;D;H         D=O;H         O;D;H
    3 Orange     H;D=O         D;O;H         H;D=O
</code>
Thanks in advance for your time and consideration.
Comment: as a new user, please take the [tour], then learn [ask]. Edit your question before it gets closed.
Answer: What's tough about this one is that Excel ranges can't really cross worksheets, it isn't really 3D.  So in VBA you'll probably end up with:

An Array of sheet names for your 3 (or more?) sheets to be compared
A loop to pull the values from a given 2D address across the array of sheets into an Array
Sort the Array (which isn't a thing, you have to dump the array into a temp range somewhere and sort that, along with a list of sheet names)
A loop to go down the sorted array's temp range, naming the sheets in order and putting in either an equals sign or semicolon depending on the next value
which all constructs a string of the type in your output sheet.

...I'd do all that as an Excel function, then copy the function into all the cells of Sheet4, since the names of sheets1-3 are hard-coded into the function.
If you want to be able to do this for any arbitrary list of sheets, trickier still.
But before we get into that, do you have a lot of this 3D data processing to do?  Because Excel has a powerful tool for multi-dimensional data, called a Pivot Table, and your data is eminently suitable for putting into a pivot table, and this would allow you to "pivot" the data so that "which supplier" becomes a column or row, rather than sheet.
Pivot tables have a learning curve, but they're the way to go for this kind of problem.
Comment: Thank you Mr. Roy Brander!
Yes, I have 9 sheets, each of them has 60 rows and AZ columns.
If putting all data in one sheet will make it easier I can do that.
Pivot Table tool can summarize my data put could it compare them the way I want? Because summarizing them is not important for me, instead comparing each cell is what matters.
Any more information could be helpful Mr. Roy. Thank you again!
Comment: There's nothing that can produce the long string of letters and punctuation marks you specified, but a pivot table could show the 9 values that are all in (say) cell C7, as a column of 9 values - and then sort those, so that you can see which are equal and which are greater than the next;  I wondered if that might eliminate the need for your string of sorted sheet names and "=;" marks.    It would also be much easier to write a macro to produce that string if you already had the sorted list.    HOWEVER, my question was whether you have a lot of different things to do or just this one job.
Comment: If you just have this one thing to do, then the work to move the data into a pivot table is not worth it; less time to just write the longer macro that does what I outlined in my answer.

This isn't a code-writing service, but if the steps outlined in my answer don't seem to be within your ability, I could provide some code fragments for the harder steps.

Oh, and I see you're new here.   It's polite to "thank" answers that you feel are useful by  clicking on that little up-arrow beside the useful answer, to indicate it WAS rated as an answer, and not a bad thing.
Comment: I actually did voted your answer but I get this message: "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score."
As appreciation of your efforts I will accept your answer so you earns +15 reputation I guess.
Comment: I'm a VBA beginner. What I've tried is oppening a new sheet and in the first cell of it I wrote: =D!B2,O!B2,H!B2
And then I dragged the handle to copy the formula to all cells in the new sheet.
Now each cell has all the prices. However, I still need to do the comparison work manually.


Busca no Firebase

Question: Bom dia amigos, tenho a seguinte estrutura no firebase. Preciso fazer uma busca no meu banco, exibindo todos os produtos que estão na child Sem Barra, e também os supermercados e preço que estão salvos dentro de cada produto. Não encontrei nenhum metodo que me ajude a exibir todos os supermercados. Alguem poderia me ajudar?
Answer: Responder a sua pergunta corretamente me tomaria muito tempo, logo estarei respondendo de forma a lhe ajudar com o que você almeja. Eu costumo trabalhar com o firebase de forma mais padronizada possível e isso sempre me ajuda, exemplo esquemático:
<code>achocolatado_1:
    estado: CE
    cidade: Fortaleza
    supermercado: Meu Supermercado
    ...

café_1:
    estado: RS
    cidade: Pelotas
    supermercado: Supermercado Compra Bem
    ...
</code>
e assim por diante.
Procure na documentação do Firebase como baixar dados em massa utilizando uma classe (objeto) com seus gets e sets, onde cada variável deverá ter exatamente o mesmo nome das chaves do Firebase.
Há um Listener assíncrono que observa se houve alguma alteração em seus dados e assim, sempre que altera-os, tudo será atualizado automaticamente.
Logo, você poderá referenciar quais nós quiser e chamar quais dados quiser.
Eu também gosto de controlar os dados assíncronos salvando-os com o SharePreferences do Android e isso facilita muito a minha vida.
Não tem como lhe explicar com muitos detalhes pois é muita coisa, mas acredito ser um bom caminho.
Qualquer dúvida complementarei a resposta se possível.

Busca no Firebase


How to specify a particular tenant as an argument with "ant importImpex" command?

Question: I'm trying to import the impex files using ant importImpex -DSource=items.impex. This is successfully importing the impex files but the changes are reflecting in the MASTER tenant.
How to specify a particular tenant as an argument with ant importImpex command?
I have tried ant importImpex -DSource=items.impex -Dtenant=tenantID but it is not working.
Is there any other way?
Comment: Can you write code and compile the project ?
Answer: There is no option to set tenant in this ant target.
To know available options type ant -p. Note that in hybris 6.1 you'll see that the option to set impex path is -Dresource
What you can do is use Bean Shell annotation in your impex file.
Add this line before your INSERT_UPDATE statements :
"#% Registry.setCurrentTenantByID(""tenantId"");"
Then run the regular ant importImpex target and you'll see that the data are only in the tenant set in the annotation.
Comment: I also figured out another approach for this, with that we can use ant **importImpex -DSource=items.impex -Dtenant=tenantID**.

For this we need to edit the **platformadministration.xml** present inside **HYBRIS_HOME/bin/platform/resources/ant** and add the following to the **importImpex** microdef.

`Registry.setCurrentTenantByID("${tenant}");`

Add this after
`import de.hybris.platform.core.Registry;
import de.hybris.platform.servicelayer.impex.impl.CmdImpExService;`
Answer: Also you can go to the tenant section in the administration console and then open the console for the desired tenant( you might need to initialise it first if you haven't already done so). From there you can access the impex console of this particular tenant and execute your impex from there.


How can I find the closest points that form a perpendicular?

Question: I have three points $A, B, C$ and I would like to find the three closest points $A', B', C'$ that

Cause $\vec{A'B'}$ to be perpendicular to $\vec{B'C'}$ and
Minimize the sum-square error between corresponding points $\epsilon = \lvert A' - A\rvert^2 + \lvert B' - B\rvert^2 + \lvert C' - C\rvert^2$

Since I know(?) that the best points will be in the same plane as the original points, I approached the formulas for the best points by using the original points as origins and bases:
$A' = A + t_{AA}(A - B) + t_{AC}(C - B)$
$B' = B + t_{BA}(A - B) + t_{BC}(C - B)$
$C' = C + t_{CA}(A - B) + t_{CC}(C - B)$
If I assume I know $A', B', t_{CC}$, I can compute $t_{CA}$ by applying the perpendicularity constraint via a zero-valued dot product:
$0 = (A' - B') \cdot (C' - B')$
...which leads to (if I figure correctly):
$t_{CA} = -\frac{(A' - B') \cdot (C - B') + t_{CC} (A' - B') \cdot (C - B)}{(A' - B') \cdot (A - B)}$
Since only the $\lvert C' - C\rvert^2$ part of $\epsilon$ is affected by by $t_{CC}$, I should be able to compute $t_{CC}$ by minimizing error:
$\frac{\partial}{\partial t_{CC}}[\lvert C' - C\rvert^2] = 0$
I can sort of get a result from solving the above using $\lvert C' - C\rvert^2 = (C' - C) \cdot (C' - C)$, but my Mathematica-foo is not strong enough to get a concise expression for $t_{CA}$ that eliminates $t_{CC}$.  Then, I figure I would need to repeat that process 4 more times to find one of the $t_{xx}$ scalars as a function of only the knowns $A, B, C$.
Is there a better way to compute $A', B', C'$ and/or is someone better able to use Mathematica than me?  I want to find expressions for $A', B', C'$ that only use the knowns $A, B, C$.
Answer: Take a point $A'$ lying on a circle of radius $r_1$ centered at $A$, such that the radius vector $AA'$ makes an angle $\theta_1$ with the positive direction of  the $x$ axis.  And take a point $C'$ lying on a circle of $r_2$ centered at $C$ such that the radius vector $CC'$ makes an angle $\theta_2$ with the positive direction of $x$ axis.  Then we have
$ A' = A + r_1 (\cos \theta_1, \sin \theta_1 ) $
$ C' = C + r_2 (\cos \theta_2, \sin \theta_2 ) $
Since we $A'B'$ to be perpendicular to $B'C'$, then this means that $B'$ lies on a circle whose center is the midpoint of $A'C'$ and whose radius is $\dfrac{1}{2} \overline{A'C'} $.  Further, we want $B'$ to be closest to $B$
Hence, if we let
$ M = \dfrac{1}{2} (A' + C') $
And
$ \theta_3 = \text{atan2}( B_x - M_x, B_y - M_y ) $
(Note that the order of the parameters for $atan2$ is reversed in some computer languages.  The convention I am using, is $ \phi = \text{atan2}(u, v)$ retruns an angle $\phi$ such that $\tan \phi = \dfrac{v}{u} $.)
And finally,
$ R = \dfrac{1}{2} \| A' C' \| $
Then
$B' = M + R ( \cos \theta_3, \sin \theta_3 ) $
Note that the distance $r_3 = \| B B ' \| = \| B M \| - R $
Now the function we want to minimize is
$ f = r_1^2 + r_2^2 + r_3^2 $
And we four variables $r_1, \theta_1,  r_2 , \theta_2 $.  To carry out the minimization, I resorted to numerical methods, in particular the simple and very basic algorithm named steepest descent.  This algorithm requires the gradient vector $\nabla  f = [ \dfrac{\partial f }{\partial r_1} , \dfrac{\partial f }{\partial \theta_1} ,\dfrac{\partial f }{\partial r_2} , \dfrac{ \partial f}{\partial \theta_2} ]^T$.
This can be obtained by numerical differentiation.
The code I've developed is listed below, followed by the converged triangle $A'B'C'$.  The points $A,B,C$ are the vertices of a 13-14-15 triangle.
Public Sub mse_min_sum_squared_distances_perpendicular()
Dim a(3), b(3), c(3) As Double, ap(3), bp(3), cp(3) As Double

Dim x(4), y(4) As Double

Dim pts(4, 2), pts2(4, 2) As Double

Dim x_(4), y_(4), dx(4), dy(4) As Double

a(1) = 0
a(2) = 0

b(1) = 14
b(2) = 0

c(1) = 5
c(2) = 12

x(1) = 0
x(2) = 0
x(3) = 0
x(4) = 0

success = 0

For ic = 1 To 2000

' find the gradient

Call find_y_minsumsq(a, b, c, x, y, ap, bp, cp)

k = 10
narcs = 0
ipass = 2

For i = 1 To 2
pts(1, i) = a(i)
pts(2, i) = b(i)
pts(3, i) = c(i)
pts(4, i) = a(i)

pts2(1, i) = ap(i)
pts2(2, i) = bp(i)
pts2(3, i) = cp(i)
pts2(4, i) = ap(i)
Next i

Call draw_points(2, 1, 4, pts, 1)
Call draw_points(2, 1, 4, pts2, 3)

Call plot_curve(0, 10, 0, 0, 0, "", "")

MsgBox ("")

If norm(y, 4) < 0.000001 Then
MsgBox (norm(y, 4))

success = 1
Exit For

End If

If ic = 1 Then

 gamma = 0.01

Else

For i = 1 To 4
dx(i) = x(i) - x_(i)
dy(i) = y(i) - y_(i)

Next i

If norm(dx, 4) < 0.000001 Then
   success = 1
   MsgBox ("converged in " + Str(ic - 1))
   Exit For
End If

dynormsq = norm(dy, 4) ^ 2

gamma = Abs(dotn(dx, dy, 4)) / dynormsq

End If

For i = 1 To 4
x_(i) = x(i)
x(i) = x(i) - gamma * y(i)
y_(i) = y(i)
Next i

Next ic

If success = 0 Then
MsgBox ("did not converge")
Exit Sub
End If

End Sub

Public Function find_f_minsumsq(a, b, c, x, ap, bp, cp) As Double
Dim m(2) As Double

r1 = x(1)
th1 = x(2)
r2 = x(3)
th2 = x(4)

ap(1) = a(1) + r1 * Cos(th1)
ap(2) = a(2) + r1 * Sin(th1)

cp(1) = c(1) + r2 * Cos(th2)
cp(2) = c(2) + r2 * Sin(th2)

For i = 1 To 2
m(i) = 0.5 * (ap(i) + cp(i))
u1(i) = 0.5 * (ap(i) - cp(i))
Next i

r = norm(u1, 2)

th_3 = WorksheetFunction.Atan2( b(1) - m(1), b(2) - m(2) )

bp(1) = m(1) + r * cos(th_3)
bp(2) = m(2) + r * sin(th_3)

For i = 1 To 2
u1(i) = a(i) - ap(i)
u2(i) = b(i) - bp(i)
u3(i) = c(i) - cp(i)
Next i

find_f_minsumsq = dotn(u1, u1, 2) + dotn(u2, u2, 2) + dotn(u3, u3, 2)

End Function

Public Sub find_y_minsumsq(a, b, c, x, y, ap, bp, cp)

Dim u(4) As Double
Dim ap2(2), bp2(2), cp2(2) As Double

Dim i, j As Integer
Dim f1, f2 As Double

f1 = find_f_minsumsq(a, b, c, x, ap, bp, cp)

For j = 1 To 4

For i = 1 To 4
u(i) = x(i)
Next i

u(j) = u(j) + 0.01

f2 = find_f_minsumsq(a, b, c, u, ap, bp, cp)

y(j) = 100 * (f2 - f1)

Next j

End Sub


How do I replace a string when using hook_node_view()?

Question: I am trying to use hook_node_view() to replace, in the front page,
:placeholder1:
 with the content of $string.
function mymodule_node_view(&$node, $view_mode, $langcode){
  $string = "I am here";
  $node->field_column_second['und'][0]['value']['#markup'] = array(
     '#markup' => str_replace(':placeholder1:', $string, $node->field_column_second['und'][0]['value'])
);

I also cleared Drupal cache, but I don't see any change.
What am I doing wrong?
Comment: Are you writing this snippet in mymodule.module with mymodule.info existing as well?
Comment: Why do you think `hook_node_view()` would be invoked for the front page too. What did you set as front page?
Answer:
According to the doc, the first parameter should be $node, rather than &$node.
The replacement code should look something like this:
$node->content['body'][0]['#markup'] = str_replace($old, $new, $subject); so you missed [0] in your code, when in doubt, do a dsm($node) and check the variable you want.
Complete code:
function test_node_view($node, $view_mode, $langcode){
    if (drupal_is_front_page()) { // check if necessary
    $string = "new";
    $node->content['body'][0]['#markup'] = str_replace('old', $string, $node->content['body'][0]['#markup']);
    }
    //dsm($node);
}
Comment: Can you please check, I edit my question.
Comment: Updated, I believe the value gets displayed comes from $node->content


How to factor $^{49}−$ over $GF(7)$ as a product of irreducible polynomials.

Question: Question: How to factor $^{49}−$ over $GF(7)$ as a product of irreducible polynomials?
My approach: would like to know if it's okay, any help is appreciated.
$$\begin{align}P(x) &= x^{49} - x\\
 &= x(x^{48} -1)\\
 &= x(x^{24} +1)(x^{24} -1) \\
&= x(x^{12} - 1)(x^{24} +1)(x^{12}+1) \\
&= x(x^6-1)(x^6+1)(x^{24}+1)(x^{12}+1)\\
&=x(x^3-1)(x^3+1)(x^6+1)(x^{24}+1)(x^{12}+1)\\
&=x(x-1)(x+1)(x^2+1-x)(x^2+1+x)(x^2+1)(x^4+1-x^2)(x^8+1)(x^{16}+1-x^8)(x^4+1)(x^8+1-x^4)\\
&=x(x-1)(x+1)(x^2+1)(x^4+1)(x^8+1)(x^2+1-x)(x^2+1+x)(x^4+1-x^2)(x^8+1-x^4)(x^{16}+1-x^8)\end{align}$$
For your convenience: (image below)

Another approach:
$GF(49)$ has dimension $2$ over $\mathbb F_7$. Over $GF(49)$ the polynomial $x^{49}-x$ has $7$ linear factors $x-t,t=0,...,6,$ and $21$ quadratic factors, one of which is $x^2+6x+6.$
Hence, working modulo $7$, if we set $x^2=x+1$, we can take $x+2$ as a generator (its first few powers are $x+2,5x+5,6x+1,5x+1,2x,6x+2,6x+3,5,...)$ because $(x+2)^t \neq 1$ for $1 \le t \le 47$ and, of course, $(x+2)^{48} = 1$. There are many other choices I guess.
Comment: Note that $x^{49}\equiv x$ for all $x$ in $\mathbb F_7$ so you should at least have every first-order polynomial once.
Comment: I haven't looked too closely at your factoring, but it seems to be generally valid over any field. I suspect that you haven't used that we are working specifically over $GF(7)$.
Comment: @HenningMakholm You mean $GF(49)$ has dimension $2$ over $\mathbb F_7$. Over $GF(49)$ the polynomial $x^{49}-x$ has $7$ linear factors $x-t,t=0,...,6,$ and $21$ quadratic factors, one of which is $x^2+6x+6.$

Hence, working modulo $7$, if we set $x^2=x+1$, we can take $x+2$ as a generator (its first few powers are $x+2,5x+5,6x+1,5x+1,2x,6x+2,6x+3,5,...)$ because $(x+2)^t \neq 1$ for $1 \le t \le 47$ and, of course, $(x+2)^{48} = 1$. There are many other choices I guess.
Answer: Using $(\pm1)^2=1=-6$, $(\pm2)^2=4=-3$ and $(\pm3)^2=2=-5$ and using the completion of the square "from the outer term", $$x^4+ax^2+b^2=(x^2\pm b)^2+(a\mp2b)x^2,$$ you can further get (blue=incomplete factorization)
\begin{align}
(x^2+1−x)&=(x+3)^2-1=(x+2)(x-3)\\
(x^2+1+x)&=(x-3)^2-1=(x-2)(x+3)\\
(x^4+1)&=(x^2+1)^2-2x^2=(x^2+1)^2-(3x)^2=(x^2-3x+1)(x^2+3x+1)\\
(x^4+1−x^2)&=(x^2+3)^2-1=(x^2-3)(x^2+2)\\
\color{blue}{(x^8+1)}&=\color{blue}{(x^4-3x^2+1)(x^4+3x^2+1)}\\
(x^4-3x^2+1)&=(x^2-1)^2-x^2=(x^2-x-1)(x^2+x-1)\\
(x^4+3x^2+1)&=(x^2-1)^2+5x^2=(x^2-1)^2-(3x)^2=(x^2-3x-1)(x^2+3x-1)\\
\color{blue}{(x^8+1−x^4)}&=\color{blue}{(x^4-3)(x^4+2)}\\
(x^4-3)&=(x^2+2)^2-4x^2=(x^2-2x+2)(x^2+2x+2)\\
(x^4+2)&=(x^2-3)^2+6x^2=(x^2-x-3)(x^2+x-3)\\
\color{blue}{(x^{16}+1−x^8)}&=\color{blue}{(x^4-2x^2+2)(x^4+2x^2+2)(x^4-x^2-3)(x^4+x^2-3)}\\
(x^4-2x^2+2)&=(x^2+3)^2-x^2=(x^2-x+3)(x^2+x+3)\\
(x^4+2x^2+2)&=(x^2+3)^2-4x^2=(x^2-2x+3)(x^2+2x+3)\\
(x^4-x^2-3)&=(x^2-2)^2-4x^2=(x^2-2x-2)(x^2+2x-2)\\
(x^4+x^2-3)&=(x^2-2)^2-9x^2=(x^2-3x-2)(x^2+3x-2)\\
\end{align}
Comment: apart from that, the solution is okay? :)
Comment: That depends on what "okay" means. Your factorization is correct, just not completely down to irreducible factors.
Comment: I see, adding the blue factorization completes the solution I assume :)
Comment: The other way around, the blue lines have reducible factors on the right side, the factors for the complete factorization are the right sides of the black lines (the following black lines for the blue lines).
Comment: Oh right, thank you so much.