Call non-class function from a class method C++

Question: I want to call the function print which is outside the class.
At the forward declaration void print(Entity* e), I'm getting errors like this:
'Entity' undeclared identifier
'e' undeclared identifier
'print' illegal use of type 'void'
term does not evaluate to a function taking 1 arguments (at the function call)-> `print(this);`
'print': redefinition; previous definition was 'data variable' (at the definition of print)

My Program
void print(Entity* e);

class Entity {
public:
    int x, y;

    Entity(int x, int y) {
        this->x = x;
        this->y = y;
        print(this);
    }
};

void print(Entity* e)
{
    cout << e->x << " " << e->y << endl;
}

int main()
{
    Entity e(1, 2);
    return 0;
}

Comment: At the point of your forward function declaration of `print()` `Entity` isn't known by the compiler, because neither a class definition of forward class declaration was made before.
Comment: Please look into [this C++ reference](https://en.cppreference.com/w/cpp) and the documentation of your C++ compiler (e.g. [GCC](http://gcc.gnu.org/)) and debugger (e.g. [GDB](https://www.gnu.org/software/gdb/)...)
Answer: In your first line of code, the compiler doesn't know what a Entity is. So add the following line to the top of your code:
class Entity;


How can I fix this? JavaFX - Wrong JPEG library version: library is 80, caller expects 70

Question: I get this error whenever I try to create an Image in JavaFX. Absolutely no images are loading, but everything else on the UI is. The only time I see this is when prism.verbose=true
Other answers to similiar questions here on StackOverflow suggest reinstalling libjpeg. But when I do sudo apt-get remove libjpeg8, it tries to remove 4 GB worth of packages that seem pretty dang important.
Has anyone else experienced this and found a feasible solution that isn't going to require me to reinstall my entire OS?
Here is the entire stacktrace:
java.io.IOException: Wrong JPEG library version: library is 80, caller expects 70
at com.sun.javafx.iio.jpeg.JPEGImageLoader.initDecompressor(Native Method)
at com.sun.javafx.iio.jpeg.JPEGImageLoader.<init>(JPEGImageLoader.java:187)
at com.sun.javafx.iio.jpeg.JPEGImageLoaderFactory.createImageLoader(JPEGImageLoaderFactory.java:49)
at com.sun.javafx.iio.ImageStorage.getLoaderBySignature(ImageStorage.java:419)
at com.sun.javafx.iio.ImageStorage.loadAll(ImageStorage.java:266)
at com.sun.javafx.tk.quantum.PrismImageLoader2.loadAll(PrismImageLoader2.java:142)
at com.sun.javafx.tk.quantum.PrismImageLoader2.<init>(PrismImageLoader2.java:77)
at com.sun.javafx.tk.quantum.PrismImageLoader2$AsyncImageLoader.processStream(PrismImageLoader2.java:252)
at com.sun.javafx.tk.quantum.PrismImageLoader2$AsyncImageLoader.processStream(PrismImageLoader2.java:225)
at com.sun.javafx.runtime.async.AbstractRemoteResource.call(AbstractRemoteResource.java:109)
at com.sun.javafx.tk.quantum.PrismImageLoader2$AsyncImageLoader.access$201(PrismImageLoader2.java:225)
at com.sun.javafx.tk.quantum.PrismImageLoader2$AsyncImageLoader.lambda$call$428(PrismImageLoader2.java:259)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.PrismImageLoader2$AsyncImageLoader.call(PrismImageLoader2.java:258)
at com.sun.javafx.tk.quantum.PrismImageLoader2$AsyncImageLoader.call(PrismImageLoader2.java:225)
at com.sun.javafx.runtime.async.AbstractAsyncOperation.lambda$new$272(AbstractAsyncOperation.java:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

And this is my version info for java. I'm using the Oracle version.
java version "1.8.0_72"
Java(TM) SE Runtime Environment (build 1.8.0_72-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode)

EDIT:
I ran strace on my app and it looks like something is searching specifically for libjpeg 8 only. It's not ever trying to look for any default libjpeg library or libjpeg 7 at all.
Comment: I have the same behavior on Arch with AdoptOpenJDK 11.0.10, turbojpeg (80). `Wrong JPEG library version: library is 80, caller expects 90`
Comment: Seems like you are running a Debian derivative. Are you using OpenJDK or Oracle's JDK? If you're on OpenJDK, you might want to try to switch: sudo sudo add-apt-repository ppa:webupd8team/java &&
sudo apt-get update &&
sudo apt-get install oracle-java8-installer && sudo apt-get install oracle-java8-set-default
Comment: I'm using Oracle's JDK. I've also updated my question with my version info.
Comment: Could you try to install libjpeg7 and see if that solves it?
Comment: I don't see libjpeg7 in my package manager's repos. Only libjpeg62 and libjpeg8.
Comment: And I pulled down libjpeg 7 from source and built it. Still no luck, even after placing it in my `/usr/lib` path and also placing it in `LD_LIBRARY_PATH`.
Answer: A possible workaround is to not let JPEGImageLoader decode the jpegs but rather do it with ImageIO instead. You lose some of the built-in features of the javafx Image only available via constructor parameters such as smooth, preserveRatio, backgroundLoading but at least it is safer on linux.
Something like this might work for you:
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;

public static Image createImage(File file) throws IOException {
    BufferedImage bufferedImage = ImageIO.read(file);
    WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, null);
    if (writableImage.isError()) {
        throw new RuntimeException(writableImage.getException());
    }
    return writableImage;
}

Answer: I think that Java is linked against libjpeg7, but you might have libjpeg8 in your LD_LIBRARY_PATH, so the interface does not match.
libjpeg.so comes with Java (in the lib/amd64 folder for x64 systems), but this is not beeing used probably due to an override in your LD_LIBRARY_PATH.
Comment: The only thing in my `LD_LIBRARY_PATH` is `/usr/local/IntelliJ-15.0.3/bin` from my IDE. It only contains a couple of .so files. Neither one is libjpeg. But I do see the libjpeg.so file in my jre's bin.
Comment: So you're running this from IntelliJ, with the bundled JRE? Any difference when running with the system installed Oracle JRE?
Comment: I chose to run the project using the system's JRE instead. I also tried running the project outside the IDE using just Gradle from the terminal and the same thing happened. I'll double check though when i get to work.


How to handle escaped string in lxml with Python

Question: I'm trying to use lxml to help me parse some XML files and output it. However,there are some special characters in the XML file. I don't want to replace it because it is too complicated to escape it and unescape it. Also I can't force the others to produce a well-formed XML.
Is there any way Python can let me handle the non-well-formed XML with lxml?
I can read it in properly:
  parser = etree.XMLParser(recover=True)
  root = etree.parse(sys.argv[1],parser=parser)

But when I want to print the element text, it can only print the content until the special character occurs.
  for element in root.iter("content"):
    print("%s - %s  attr - %s" % (element.tag, element.text, element.get("name")))

Answer: lxml does unescaping for you transparently. So you could try to fix invalid characters in the input first and then feed the result to lxml. For example, you could try a simple regex-based solution to escape invalid characters.
Answer: A popular option to deal with less-than-perfect markup language files in Python is to use Beautiful Soup.  It can use many parsers, including lxml.
Can you post some of the XML that's giving you problems?


PHP - Como percorrer um array de radios?

Question: Tenho o seguinte código:
<?php while($row = mysql_fetch_array($alunosTurma)){ ?>

              <?php echo $row['NM_NIS_ALU']; ?>
              <?php echo $row['ST_NOME_ALU']; ?>
                <input type="hidden" value="<?php echo $row['ID_ALUNO_ALU']; ?>" name="aluno[]">

                    <input type="radio" name="options[]" value="0">

                    <input type="radio" name="options[]" value="1">

          <?php } ?>

Isso cria uma tabela listando todos os alunos e coloca à frente de cada um dois rádios (um de presença e um de falta).
No arquivo que faz o input no banco (ou deveria) tenho o seguinte:
$data = $_GET['dtChamada'];
$turma = $_GET['idTurma'];
$aluno = $_POST['aluno'];
$status = $_POST['options'];
$cont = 0;
foreach ($aluno as $idAluno) {
mysql_query(" INSERT INTO CHAMADA (DT_CHAMADA_CHMD, ID_TURMA_TUR, ID_ALUNO_ALU, FL_STATUS_CHMD) VALUES ('$data', '$turma', '$idAluno[$cont]', '$status[$cont]') "));
print_r("$data
");
print_r("$turma
");
print_r("$aluno[$cont]
");
print_r("$status[$cont]

");
$cont++;
}
?>

Para o primeiro aluno chegam os dados como preciso, mas do segundo em diante o status (presença ou falta) dá o seguinte erro:

**Notice: Undefined offset: 1 in
C:\xampp\htdocs\NISFRAM\processa\lancaChamada.php on line 26**

Como posso percorrer cada aluno gravando seu status no banco?
Comment: Como o foreach não precisa indexar o array, basta `$idAluno`
Answer: A Tabela
<?php while($row = mysql_fetch_array($alunosTurma)){ ?>

              <?php echo $row['NM_NIS_ALU']; ?>
              <?php echo $row['ST_NOME_ALU']; ?>
                <input type="hidden" value="<?php echo $row['ID_ALUNO_ALU']; ?>" name="aluno[]">

                    <input type="radio" name="options[<?php echo $row['ID_ALUNO_ALU']; ?>]" value="0">

                    <input type="radio" name="options[<?php echo $row['ID_ALUNO_ALU']; ?>]" value="1">

          <?php } ?>

O PHP
<?php
$data = $_GET['dtChamada'];
$turma = $_GET['idTurma'];
$aluno = $_POST['aluno'];
$status = $_POST['options'];

foreach ($aluno as $idAluno) {
mysql_query(" INSERT INTO CHAMADA (DT_CHAMADA_CHMD, ID_TURMA_TUR, ID_ALUNO_ALU, FL_STATUS_CHMD) VALUES ('$data', '$turma', '$idAluno', '$status[$idAluno]') "));
print_r("$data
");
print_r("$turma
");
print_r("$aluno[$idAluno]
");
print_r("$status[$idAluno]

");
}
?>
?>


Prove $a_n=\frac{(2^{n-1}+1)a_1-2^{n-1}+1}{2^{n-1}+1-(2^{n-1}-1)a_1}$ for the recursive sequence $a_{n+1}=\frac{3a_n-1}{3-a_n}$

Question:
Prove the statement:
  $$a_n=\frac{(2^{n-1}+1)a_1-2^{n-1}+1}{2^{n-1}+1-(2^{n-1}-1)a_1}$$
  for the given recursive sequence:
  $$a_{n+1}=\frac{3a_n-1}{3-a_n}. $$

My attempt:
Proof by induction:

(1) Base: $\tau(1)$.
  $$
\begin{align}
a_2 &=\frac{(2+1)a_1-2+1}{2+1-(2-1)a_1} \\
&=\frac{3a_1-1}{3-a_1}.
\end{align}
$$
(2) Assumption: Let
  $$ a_n=\frac{(2^{n-1}+1)a_1-2^{n-1}+1}{2^{n-1}+1-(2^{n-1}-1)a_1} $$
  hold for some $n\in\mathbb N$.
(3)  Step $\tau(n+1)$:
  $$
\begin{align}
a_n &= \frac{3\cdot\frac{(2^{n-1}+1)a_1-2^{n-1}+1}{2^{n-1}+1-(2^{n-1}-1)a_1}-1}{3-\frac{(2^{n-1}+1)a_1-2^{n-1}+1}{2^{n-1}+1-(2^{n-1}-1)a_1}} \\
&= \frac{3\cdot2^{n-1}a_1+3a_1-3\cdot2^{n-1}+3-2^{n-1}-1+2^{n-1}a_1-a_1}{3\cdot 2^{n-1}+3-3\cdot 2^{n-1}a_1+3a_1-2^{n-1}a_1-a_1+2^{n-1}-1} \\
&= \frac{(4\cdot 2^{n-1}+2)a_1-4\cdot 2^{n-1}+2}{4\cdot 2^{n-1}+2-(4\cdot 2^{n-1}+2)a_1} \\
&= \frac{(2^n+1)a_1-2^n+1}{2^n+1-(2^n+1)a_1}
\end{align}
$$

Is this correct and is there a more efficient method than induction?
Answer: Embed $a_n$ in a projective coordinate $[a_n,1]$ for each $n$. Then the given recursive relation may be written as
$$\left[\begin{array}{c}a_{n+1}\\ 1\end{array}\right]=\left[\begin{array}{cc}3&-1\\ -1&3\end{array}\right]\left[\begin{array}{c}a_n\\ 1\end{array}\right].$$
It follows by recursion that $$\left[\begin{array}{c}a_n\\ 1\end{array}\right]=A^{n-1}\left[\begin{array}{c}a_1\\ 1\end{array}\right],n\geq 1~\quad (1)$$ where $$A=\left[\begin{array}{cc}3&-1\\ -1&3\end{array}\right].$$
Diagonalize $A$ to get $$ \frac 12\left[\begin{array}{cc}1&1\\ 1&-1\end{array}\right]A\left[\begin{array}{cc}1&1\\ 1&-1\end{array}\right]=\left[\begin{array}{cc}2&0\\ 0&4\end{array}\right]$$ $$\Rightarrow A^{n-1}=\left[\begin{array}{cc}1&1\\ 1&-1\end{array}\right]\left[\begin{array}{cc}2^{n-1}&0\\ 0&2^{2n-2}\end{array}\right]\frac 12\left[\begin{array}{cc}1&1\\ 1&-1\end{array}\right]$$
$$=\left[\begin{array}{cc}2^{n-2}+2^{2n-3}&2^{n-2}-2^{2n-3}\\ 2^{n-2}-2^{2n-3}&2^{n-2}+2^{2n-3}\end{array}\right].$$
Substituting this back to (1), one gets that
$$\left[\begin{array}{c}a_n\\ 1\end{array}\right]=\left[\begin{array}{cc}2^{n-2}+2^{2n-3}&2^{n-2}-2^{2n-3}\\ 2^{n-2}-2^{2n-3}&2^{n-2}+2^{2n-3}\end{array}\right]\left[\begin{array}{c}a_1\\ 1\end{array}\right]$$
$$\Leftrightarrow a_n=\frac{(2^{n-2}+2^{2n-3})a_1+(2^{n-2}-2^{2n-3})}{(2^{n-2}-2^{2n-3})a_1+(2^{n-2}+2^{2n-3})}=\frac{(2^{n-1}+1)a_1-2^{n-1}+1}{2^{n-1}+1-(2^{n-1}-1)a_1},$$ as required. QED
Answer: This is my solution
Let
$$ \alpha_n = V_n + \beta    $$
$$a_{n+1} = V_{n+1} + \beta$$
then
$$V_{n+1} = \frac{3V_n + V_n\beta + (\beta^2 - 1)}{3-V_n-\beta} $$
At here we choose $\beta = 1$ as result from $\beta^2 - 1 = 0$
So we got $$V_{n+1} = \frac{4V_n}{2-V_n}$$
Continue we let
$$V_n = \frac{1}{u_n}$$
then
$$\frac{4\frac{1}{u_n}}{2-\frac{1}{u_n}} = \frac{1}{u_{n+1}}$$
$$ <=> \frac{1}{2}u_n - \frac{1}{4} = u_{n+1}$$
From here we need to find $u_1 $based on $v_1$ ,$\beta$ and $a_1$ then find $u_n$,$V_n$. Finally we will find out $\alpha_{n}$
Answer: Let
$$a_n=\frac{x_n}{y_n}$$
Then
$$\frac{x_{n+1}}{y_{n+1}}=\frac{3x_n-y_n}{3y_n-x_n}$$
Assume
\begin{align}
&x_{n+1}=3x_n-y_n&
&y_{n+1}=3y_n-x_n
\end{align}
Then $y_n=3x_n-x_{n+1}$ from which $3x_{n+1}-x_{n+2}=3(3x_n-x_{n+1})-x_n$ which gives
$$x_{n+2}-6x_{n+1}+8x_n=0$$
This linear recurrence has general solution
$$x_n=2^{n-1}(4x_0-x_1)+2^{2n-1}(x_1-2x_0)$$
By symmetry, we have
$$y_n=2^{n-1}(4y_0-y_1)+2^{2n-1}(y_1-2y_0)$$
hence
\begin{align}
a_n
&=\frac{2^{n-1}(4x_0-x_1)+2^{2n-1}(x_1-2x_0)}{2^{n-1}(4y_0-y_1)+2^{2n-1}(y_1-2y_0)}\\
&=\frac{(4x_0-x_1)+2^{n}(x_1-2x_0)}{(4y_0-y_1)+2^{n}(y_1-2y_0)}\\
&=\frac{(2^n-1)x_1-4x_0(1-2^{n-1})}{(2^n-1)y_1-4y_0(1-2^{n-1})}\\
\end{align}
Answer: For each $n = 1, 2, 3, \ldots$, we have
$$
\begin{align}
a_{n+1} &= \frac{3a_n -1 }{3 - a_n } \\
&= \frac{ 3a_n - 9 + 8 }{ 3 - a_n } \\
&= -3 + \frac{8}{ 3 - a_n }.
\end{align}
$$
Thus we obtain
$$ a_2 = - 3 + \frac{8}{3-a_1} = \frac{3a_1 - 1}{3 - a_1}. $$
$$ a_3 = -3 + \frac{ 8 }{ 3 - a_2 } = -3 + \frac{8}{3 - \frac{3a_1 - 1}{3 - a_1} } = ... $$
This approach might make it easier for you to proceed.
Comment: thank you for answering!


Splitting the string, integer and also the special character ("_")

Question: I'm trying to split between the string, integer and also special character, I've try some of the way, but does't work for me, so any ideas on it?
source code:
    String a = "abc1_xyz1";

        String[] qq = a.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)|('_')");

        for(int i=0; i<qq.length; i++){
            System.out.println(qq[i] + " \n");
        }

The expectation output from me is:
abc
1
_
xyz
1

But what I get is:
abc
1
_xyz
1

Anyone here can give me the guideline?
Comment: Can you tell us, generally, how the string is supposed to look like?
Comment: One more reason why your regex fails, by the way, is the fact that it requires single quotes around the `_`.
Comment: ya, i just realize that, and also need to put at the front to split first.
Answer: You have a couple of small problems.
\D will match _ and you don't expect that in your code
Also, splitting on _ will exclude it from the output.
This code would work
    String a = "abc1_xyz1";

    for (String s : a.split("" +
        "(?<=[a-z])(?=\\d)" +    // space between letter and digit
        "|(?<=\\d)(?=[a-z])" +   // space between digit and letter
        "|(?<=_)(?=\\d)" +       // space between _ and digit
        "|(?<=\\d)(?=_)" +       // space between digit and _
        "|(?<=_)(?=[a-z])" +     // space between _ and letter
        "|(?<=[a-z])(?=_)" +     // space between letter and _
        "")) {
        System.out.println(s);
    }

Comment: Thanks Andreas, it is perfectly work for me, really thanks a lot.
Comment: I agree but this is pretty clear and not very error prone. Simplification usually leads to the code being harder to read.
Answer: I think split() is the wrong way to go here as you don't really have any delimiter and wants to use everything that is split (it gives you empty lines in between the values).
Instead, assuming the expression is regular I would use Pattern.compile() and Matcher.group(), as such:
    String a = "abc1_xyz1";
    Pattern p = Pattern.compile("(\\D+)(\\d+)(_)(\\D+)(\\d+)");
    Matcher m = p.matcher(a);
    if (m.find()) {
        for (int i = 1; i<=m.groupCount();i++) {
            System.out.println(m.group(i));
        }
    }

If any of the groups are optional, you can add a question mark after it (then the group will be empty).
Comment: This would only work for a string formatted exactly as in the question and not for example 1_abc_2xyx. If the string is formatted exactly the same (same groups) each time I would also prefer this solution as it's much more easy to read.
Comment: ya, it can be more better.=)
Answer: Another solution: Check for _ before you check for the digit/non-digit boundaries:
String[] qq = a.split("(_)|(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");

Answer: According to the documentation of Pattern \D is "a non-digit". _ is a non-digit, therefore it will be matched.
Try replacing \D in your code with \p{Alpha} (matching any ASCII letter) or \p{L} (matching any Unicode letter).
Comment: Hi, Joachim, thanks for your information, I just check with other character classes, instead of using \p{Alpha}, the \p{Punct} is more suitable and work for me, thanks a lot.


Showing inequality about number of vertices with ceratin degree for planar graphs

Question: I am currently struggling on showing the following inequality for planar graphs without loops. Let $\delta(G) \geq 3$ and $\tau_i$ be the number of vertices with degree $i$, then:
$$
\tau_5 + 2 \tau_4 + 3 \tau_3 \geq 12 + \tau_7 + 2 \tau_8 + 3 \tau_9 + \ldots + (\Delta-6) \tau_\Delta
$$
So far I know that $\delta(G) \leq 5$ since the graph is planar and without loops. Furhtermore I tried using the inequality $3n-6 \geq m$ for planar graphs or counting the vertices in different ways however I am unable to introduce the scalars $(i-6) \tau_i$ into the equation.
I also tried proving this fact by induction over $\Delta$ however I got stuck at the induction step when trying to reduce it to the base case by merging vertices somehow.
Any tips/help would be greatly appreciated.
Comment: Can you write the Euler characteristic in terms of these $ \tau_i$? EG $V = \sum \tau_i$.
Comment: For $E$, count the edges in 2 ways. Each edge is connected to 2 vertices. Each vertex is connected to how many other vertices? Hence, how many edge-vertex pairs are there?  $\quad$ For Faces, given that this is a tree, how many faces are there?
Comment: @CalvinLin Definetly, that would be $n(G) = \sum_{i=3}^\Delta \tau_i = 2 - l(G) + m(G)$ however as stated in the question I am not sure on how to implement the coefficients (of the $\tau$'s) into this equation.
Comment: I don't quite get what you are getting at. Each vertex $x$ ist connected to $d(x)$ many other vertices. There are $2m(G)$ edge-vertex pairs (I know that $2m(G) = \sum_{v \in V(G)} d(v)$). If the graph was a tree there would only be one face. However I still don't see what role the scalars for the $\tau$'s play here to be honest.
Answer: Elaborating on the comments by Calvin Lin I was able to find the following solution:
With the handshaking lemma we get that:
$$
2m(G) = \sum_{v \in V(G)} d(v)
$$
Furthermore we now surely have
$$
\sum_{v \in V(G)} d(v) = \sum_{i=3} ^\Delta i \tau_i
$$
since in the second sum also the degree of each vertex is counted once.
Furthermore we now have for planar graphs that:
$$
2(3n(G) -6) \geq 2m
$$
Combining these two we get
$$
-12 \geq \sum_{i=3} ^\Delta (i-6) \tau_i
$$
And with this
$$
\tau_5 + 2 \tau_4 +3 \tau_3 \geq 12 + \sum_{i=7}^\Delta (i-6) \tau_i
$$
Which was to be shown.
Comment: Yup, that's what I was going for.


Select onde aparece nome do mês?

Question: No momento estou desenvolvendo um app onde eu listo em uma tabela o mês e a soma do consumo de cada mês em KW como mostra no print abaixo:

só que eu n sei como eu faria pra ao invés de listar o número do mês aparece-se o nome do mês referente ao número, no momento estou usando o seguinte comando SQL:
SELECT      ROUND(SUM(c.potencia/12))/1000  AS potencia
        ,   MONTH(c.data_criacao)
FROM        consumo c
WHERE       c.comodo_id = :id
GROUP BY    c.data_criacao

Answer: Acho que para isso basta evocar o método nativo do MySQL, MONTHNAME:
SELECT      ROUND(SUM(c.potencia/12))/1000  AS potencia
        ,   MONTHNAME(c.data_criacao)       AS mes
FROM        consumo c
WHERE       c.comodo_id = :id
GROUP BY    c.data_criacao

Se quiser ter mais trabalho ou se for mesmo necessário:
SELECT      ROUND(SUM(c.potencia/12))/1000  AS potencia
        ,   CASE MONTH(c.data_criacao)
            WHEN 1 THEN 'Janeiro'
            WHEN 2 THEN 'Fevereiro'
            WHEN 3 THEN 'Março'
            WHEN 4 THEN 'Abril'
            WHEN 5 THEN 'Maio'
            WHEN 6 THEN 'Junho'
            WHEN 7 THEN 'Julho'
            WHEN 8 THEN 'Agosto'
            WHEN 9 THEN 'Setembro'
            WHEN 10 THEN 'Outubro'
            WHEN 11 THEN 'Novembro'
            ELSE 'Dezembro'
            END                             AS mes
FROM        consumo c
WHERE       c.comodo_id = :id
GROUP BY    c.data_criacao

Comment: Muito obrigado, eu não sabia da existência dessa função.
Comment: Se for resposta da sua pergunta, não esqueça de aceitar @AndréPaiva

Select onde aparece nome do mês?


Git: merge two folders and get rid of one from the history

Question: Imagine that I have all my software in a 4GB folder named A1. Imagine that I am tracking A1 together with another folder Foo that contains some documents.
My daily work consists in developing my software in A1, changing some files in Foo and perform some commit.
However, during my development I only change some files contained in A1. Other developers can change all the files in A1, but they are using another version control system. Every once in a while, they release an update version of A1 and they ask me to integrate my code in the new release and continue my development from there. Let's call the folder released by the other developers A2.
The problem now is that I have the folder A1 with my contribution that I am tracking through git, but now there is a new updated folder folder A2 in some shared area that I shall use.
A simple solution from to this problem would be the following
git mv A1 A2
git commit
git checkout -b update_A1_A2
cp -rf MyCollegauesSharedSpace/A2 .
git add A2
git commit
git checkout master
git merge update_A1_A2

but in this case, I am afraid that my repo will grow very fast, since now in the history are present both A1 and A2, and each one is of 4GB.
However, given that from now on I am only interested in developing on A2, it would be enough to cancel from the history all the previous commits that contains A1.
However, if on one hand I would get rid of all the A1 (saving then 4 GB), on the other hand I would also get rid of the folder Foo that I want to keep. How to solve this problem?
Answer: Why are you using two directories A1 and A2? Aren't you jut mimicking what git will do for you anyway?
Also, it would be good to know what your artifact is? A patch for them? A finished compiled product? Are your contributions supposed to flow back into their version control system, and if so, how?
If i was in your shoes, i would create a branch 'pristine' for their developments, and only commit their changes to this branch, every time they do a new release. From that i'd create a branch with my contributions, and work only there. Every time they release a new version, i'd commit that to the pristine branch and tag it. Then i'd merge these changes to my development branch. This lets git take care of tracking file changes, and keeps the size manageable.


Pandas groupby all rows between boolean column values

Question: Looking for the Pandas syntax for grouping rows between column boolean values.
DataTable

distance
time
new

0
2020-10-11 1:30:15
true

5
2020-10-11 1:31:15
false

10
2020-10-11 1:32:15
false

1
2020-10-11 2:30:15
true

2
2020-10-11 2:31:15
false

30
2020-10-11 2:32:15
false

31
2020-10-11 2:33:15
false

0
2020-10-12 1:31:15
true

5
2020-10-12 1:32:15
false

Question
Looking to group all the rows that are a part of each activity. A new activity is determined by the true value in the new column. Based on the data above there should be 3 groups. Each group needs to start with the first row with True and end with the last False before the next True.
How can this be achieved using groupby?
Code
Here is the ability to use groupby and group by the date, but like I said above, I'm looking to change this to group by the "new" column group rows into activities. I'm planning to use in a for loop like this though.
for idx, day in df.groupby(df.timestamp.dt.date):
    print(idx)
    print(day)

Answer: Just group by df['new'].cumsum():
for idx, day in df.groupby(df['new'].cumsum()):
    print('-----')
    print(idx)
    print(day)

Output:
-----
1
   distance                time    new
0         0  2020-10-11+1:30:15   True
1         5  2020-10-11+1:31:15  False
2        10  2020-10-11+1:32:15  False
-----
2
   distance                time    new
3         1  2020-10-11+2:30:15   True
4         2  2020-10-11+2:31:15  False
5        30  2020-10-11+2:32:15  False
6        31  2020-10-11+2:33:15  False
-----
3
   distance                time    new
7         0  2020-10-12+1:31:15   True
8         5  2020-10-12+1:32:15  False

Comment: That was it. I figured that there had to be an easy method to do this in pandas. Thanks!


Poisson process (find mean) - solution check

Question: Mary receives 22 messages in 5 hours according to a Poisson Process. What is the mean number of messages Mary receives in an hour?
Seems like a simple question, so just to confirm: Mean = 22/5
Isn't it?
Comment: @whuber I believe that even if Poisson Process is removed from this question - the answer stays the same.
Comment: It might be helpful to contemplate under what circumstances your answer might change if "according to a Poisson process" were changed or even omitted altogether.  To what extent does, or should, your assumptions about a phenomenon determine your description of what actually happened?
Answer: The units on the rate, say $\lambda$, should be messages per hour. First, do you have the right units? Trivially,
$$\frac{22 \text{ messages}}{5 \text{ hours}}=\frac{22}{5} \text{ messages/hour}$$
Next, your $\lambda$ should be the average number of messages per hour.  With a little thought on how an average is calculated, you should be feeling pretty decent.


Prolog parse tree generation fails

Question: I have the following prolog rules.
b(b(true)) --> [true].
b(b(false)) --> [false].
b(b(E,[=],E)) --> e(E),[=],e(E).
b(b([not],B)) --> [not],b(B).
e(e(I)) --> i(I).
e(e(N)) --> n(N).
e(e(N,O,E)) --> n(N),o(O),e(E).
e(e(I,O,E)) --> i(I),o(O),e(E).
o(o(+)) --> [+].
o(o(-))--> [-].
o(o(*))--> [*].
o(o(/)) --> [/].
i(i(x)) --> [x].
i(i(y)) --> [y].
i(i(z)) --> [z].
i(i(u)) --> [u].
i(i(v)) --> [v].
n(n(0)) --> [0].
n(n(1)) --> [1].
n(n(2)) --> [2].
n(n(3)) --> [3].
n(n(4)) --> [4].
n(n(5)) --> [5].
n(n(6)) --> [6].
n(n(7)) --> [7].
n(n(8)) --> [8].
n(n(9)) --> [9].

But I dunno why
[6] 26 ?- b(A,[x,=,4],[]).
false

fails. I tried to debug the code. 4 is not getting matched with n(n(4)). I couldn't understand wat the problem is.
Answer: (You would have received an answer much earlier if you would have used the prolog tag instead)
So, how can we localize the error? Let's start with your query:

?- phrase(b(A),[x,=,4]).
   false.

Bad!
Shall I really fire up a trace/debugger?
What you are currently asking is: What are the solutions for A for a well-formed sentence.
Alas, there is none.
Can't we ask Prolog a more general question?
So, dear Prolog - at least - do you know any sentence?
Please say a word!

?- phrase(b(A),L).
   A = b(true), L = [true]
;  A = b(false), L = [false]
;  ... .

So there is something - I will remove the A, because we want to see the sentences, first.

?- phrase(b(_),L).
   L = [true]
;  L = [false]
;  L = [x,=,x]
;  L = [y,=,y]
;  L = [z,=,z]
;  L = [u,=,u]
;  L = [v,=,v]
;  L = [0,=,0]
;  L = [1,=,1]
;  L = [2,=,2]
;  L = [3,=,3]
;  L = [4,=,4]
;  L = [5,=,5]
;  L = [6,=,6]
;  L = [7,=,7]
;  L = [8,=,8]
;  L = [9,=,9]
;  L = [0,+,x,=,0,+,x]
;  ... .

Do you see a pattern here?
Maybe we can refine this.
What are the sentences of length 3 you know of?
?- L = [_,_,_], phrase(b(_),L).
  L = [x,=,x]
;  L = [y,=,y]
;  L = [z,=,z]
;  L = [u,=,u]
;  L = [v,=,v]
;  L = [0,=,0]
;  L = [1,=,1]
;  L = [2,=,2]
;  L = [3,=,3]
;  L = [4,=,4]
;  L = [5,=,5]
;  L = [6,=,6]
;  L = [7,=,7]
;  L = [8,=,8]
;  L = [9,=,9]
;  L = [not,not,true]
;  L = [not,not,false]
;  false.

In other words: There are no other three word sentences than those.
Now, do you get it?
There is a rule for sentences with =:

b(b(E,[=],E)) -->
   e(E),[=],e(E).

It requires that the expression on the left-hand side is the same as the expression on the right-hand side. Therefore only those sentences above.

When debugging a Prolog program, there is much less need to type (on the keyboard) test data than in other languages. Instead, use variables to let Prolog fill-in-the-variables. After all, Prolog is much faster on that than we are ; and it does not suffer CTS.

Prolog parse tree generation fails


How do I query user registry settings on a remote machine?

Question: Supposing that I have a remote machine on which I'm an admin, and I want to query some values in the windows registry in HKEY_CURRENT_USER for a given user on a given machine. (The user may be logged in or off.)
Is it possible to query HKCU like this? And, if so, how?
Answer: You need to find the user's SID (Security Identifier) and query HKEY_USERS\{SID}


How do I display a block on a page

Question: I simply want to display a table generated from an external database on a page.  In researching this I found it would be easiest to do it by writing a module.  Using a tutorial I created a block module that does what I want, but I can't figure out how to make a block module appear on a normal page. This must be something people do on a regular basis.  This is version 7.
Is there such a thing as a page module rather than a block module?
Thanks,
Jim
Just to extend this a bit, eventually I want to be able to add a select form element and perhaps write a bit of javascript (jQuery calls) to change the query that generates the table, etc.  But for now just to be able to display the table on a node/page would be fine.
Comment: Not sure what you mean exactly...you can manage your blocks, including what pages they appear on, at http://mysite.com/admin/structure/block
Comment: That's my point, I don't want to put data in a region I want it on the page, node 13 for instance. Thanks.
Answer: There are a couple of ways to tackle this...

If you're coding the node content yourself you can use the following snippet to get the output of a particular block into a string:
$block = block_load($module, $delta);
$render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = render($render_array);

There's the Block Reference module

Defines a field type Block reference which creates a relationship to a block and allows the block to be displayed as the content of the field. It saves this relationship using the block's bid, not its delta + module.
Comment: @user1424074, it is same as my first option :)
Answer: You can render a block using the following code snippet in your template file.
<?php
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);
?>

The template file would be page.tpl.php for every page, but for a specific page, let's say your have a page node/13, you may have a custom page template page--node--13.tpl.php for that page.
But I think the good practice is to create a variable in hook_preprocess_page() and make it avaibable to the template. Then print it in page.tpl.php.
function MYTHEME_preprocess_page(&$variables) {
    if(isset($variables['node']) && $variables['node']->nid == 13){
        $block = module_invoke('module_name', 'block_view', 'block_delta');
        $variables['myblock'] = render($block['content']);
    }
}

OR, another way is to use the Panel module to create a custom page in which you can create layouts and place any content such as blocks, nodes, views, forms, etc.

The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.
Comment: For the future, the Panels module looks like it will be useful. Thanks
Comment: @user1424074, Not now? :)
Comment: I don't currently have the time to implement it.  Since the simple solution solved my current need, when I need the more complex solution, I'll investigate it more thoroughly. Thanks...
Answer: You can also add the block directly in your body, using Insert Block module :

[block:name of module=delta of block]
...will insert the contents of a rendered sidebar block into the body
  of your node. If no delta is specified, the default block for that
  module will be displayed.
Comment: By 'rendered sidebar block' does that mean it has to appear in a region somewhere for it to be visible on my page?
Comment: @user1424074, it says in the body of your node.

How do I display a block on a page


Insert data to Realtime Database does not works

Question: I'm trying to create an app if someone want to use my app they must create a user.
When they register they will insert first name, last name, phone and email address.
After I confirm that the phone is theirs by using Firebase authorization I want to insert his data to a table named Users in my RealTime Database.
When I tried to do it by using this function:
**EDIT: I added the onComplete function but it doesn't execute **
private void storeNewUserData() {
        FirebaseDatabase rootNode = FirebaseDatabase.getInstance();
        DatabaseReference reference = rootNode.getReference("Users");
        User user = new User(phone,firstName,lastName,email);
        reference.setValue(user).addOnCompleteListener(this);
    }

@Override
public void onComplete(@NonNull Task<Void> task) {
    if(task.isSuccessful()){
        Toast.makeText(this, "Inserted User: "+phone+firstName+lastName+email, Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(this, task.getException().toString(), Toast.LENGTH_SHORT).show();
    }
}

The database has not been updated but the Toast appeared (with all the data).
I don't think there is a problem in my code maybe it's a problem in my Firebase account.. Anyway I add the rules to this database and an image of the table.
Rules
{
  "rules": {
    ".read": "true",
        ".write": "true"
  }
}

build.gradle(app)
dependencies {
    implementation platform('com.google.firebase:firebase-bom:26.8.0')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-auth:20.0.3'
    implementation 'com.google.firebase:firebase-database:19.7.0'

    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation "androidx.browser:browser:1.3.0"
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    testImplementation 'junit:junit:4.13.2'

}

';
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
        @Override
        public void onSuccess(AuthResult authResult) {
            progressDialog.dismiss();
            User user = new User(phone,firstName,lastName,email);
            storeNewUserData();
            Toast.makeText(PhoneAuthActivity.this, "Logged in as "+phone, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(PhoneAuthActivity.this, MainActivity.class));
        }

    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            progressDialog.dismiss();
            Toast.makeText(PhoneAuthActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

logcat
2021-03-30 03:41:02.326 15207-15345/com.example.teorialearning E/FirebaseAuth: [GetAuthDomainTask] Error getting project config. Failed with INVALID_CERT_HASH 400
2021-03-30 03:41:02.344 15207-15257/com.example.teorialearning V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 396
2021-03-30 03:41:02.345 15207-15257/com.example.teorialearning V/FA: Activity paused, time: 15824705
2021-03-30 03:41:02.389 15207-15207/com.example.teorialearning E/zzf: Failed to get reCAPTCHA token with error [There was an error while trying to get your package certificate hash.]- calling backend without app verification
2021-03-30 03:41:02.391 15207-15257/com.example.teorialearning V/FA: Activity resumed, time: 15824751
2021-03-30 03:41:02.395 15207-15245/com.example.teorialearning W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-30 03:41:02.641 15207-15207/com.example.teorialearning D/MAIN_TAG: onCodeSent:ALiwoWIdFZrl9ResXiUM94aPJW-csmRjdDOqoa9DTOkNQbv2Vf8YN7X6mvBwXgg9MJxEnFUVoE2rWAP2JzpT8QdBcRK2kIi82e_uO3pXW_rC5CZqWgJaqYqPO6nMOxiavmaJELnkSRtTXo6HoYoEY2_CmtVplEbz2Q
2021-03-30 03:41:02.644 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:02.677 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:02.739 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:04.679 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:04.789 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:07.416 15207-15257/com.example.teorialearning V/FA: Inactivity, disconnecting from the service
2021-03-30 03:41:08.627 15207-15245/com.example.teorialearning W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-30 03:41:08.668 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.685 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.691 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.696 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.755 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.936 15207-15245/com.example.teorialearning W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-30 03:41:09.147 15207-15245/com.example.teorialearning D/FirebaseAuth: Notifying id token listeners about user ( QgYB9guxYgT2AQbr8u9CVrGnELw2 ).
2021-03-30 03:41:09.149 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.178 15207-15257/com.example.teorialearning V/FA: Recording user engagement, ms: 6787
2021-03-30 03:41:09.180 15207-15257/com.example.teorialearning V/FA: Connecting to remote service
2021-03-30 03:41:09.181 15207-15257/com.example.teorialearning V/FA: Activity paused, time: 15831539
2021-03-30 03:41:09.189 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.193 15207-15257/com.example.teorialearning V/FA: Connection attempt already in progress
2021-03-30 03:41:09.212 15207-15225/com.example.teorialearning V/FA: onActivityCreated
2021-03-30 03:41:09.229 15207-15257/com.example.teorialearning V/FA: Activity resumed, time: 15831590
2021-03-30 03:41:09.233 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.243 15207-15257/com.example.teorialearning V/FA: Connection attempt already in progress
2021-03-30 03:41:09.244 15207-15257/com.example.teorialearning V/FA: Connection attempt already in progress
2021-03-30 03:41:09.295 15207-15257/com.example.teorialearning D/FA: Connected to remote service
2021-03-30 03:41:09.296 15207-15257/com.example.teorialearning V/FA: Processing queued up service tasks: 4
2021-03-30 03:41:09.298 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.329 15207-15207/com.example.teorialearning W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
2021-03-30 03:41:09.330 15207-15207/com.example.teorialearning W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
2021-03-30 03:41:11.206 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:13.170 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:14.310 15207-15257/com.example.teorialearning V/FA: Inactivity, disconnecting from the service
2021-03-30 03:42:02.393 15207-15348/com.example.teorialearning W/FirebaseAuth: [SmsRetrieverHelper] Timed out waiting for SMS.

P.S: I'm using Android studio
Comment: You should use a `ValueEventListener` to track changes in a specific node/branch.
Comment: Have you tried to attach a complete listener to the setValue() method?  Please respond with @AlexMamo
Comment: @AlexMamo I haven't tried please attach code so I can try it
Comment: @ShubhamPanchal Please attach code so I can try it
Comment: reference.setValue(user).addOnCompleteListener(/* ... */);
Comment: @AlexMamo the task is not successfully completed how can I know why?
Comment: Try to log the message that comes when the task is not successful, right?
Comment: @AlexMamo I just find out that onComplete doesn't execute...
Comment: Which Toast message is displayed? Are you also sure you have an internet connection on the device/emulator?
Comment: @AlexMamo I used this in my manifest:

I get no Toast onComplete doesn't execute
Comment: Most likely, you don't have an internet connection on the device/emulator, right?
Comment: @AlexMamo I does get the Toast in onSuccess (after storeNewUserData())
Comment: @AlexMamo I'm not sure...
Comment: @AlexMamo but I'm pretty sure... I added the permission
Comment: Internet permissions are not necessary when writing data in Firebase. So most likely you don't have an internet connection (**not** internet permission) on the device.
Comment: @AlexMamo should I use my physical android device?
Comment: @AlexMamo I tried using my physical device  but still no change..
Comment: @ShubhamPanchal help
Comment: @AlexMamo help,
Answer: I could resolve this issue by changing my device's internet connection network. The app won't work on mobile data, but it worked on the WIFI of some other device.

The reason behind the problem isn't clear yet.

Reference answer -> https://stackoverflow.com/a/51122769/13546426


Derivative of ellipse

Question: Find $y'=\frac{dy}{dx}$
when: $$2x^2-xy+y^2=1$$
How do I solve this?
Do I start with this?:
$$y=\frac{2x^2+y^2-1}{x}$$
$$y'=\left(\frac{2x^2+y^2-1}{x}\right)'$$
Comment: You want [implicit differentiation](https://www.math.ucdavis.edu/~kouba/CalcOneDIRECTORY/implicitdiffdirectory/ImplicitDiff.html).
Answer: You can follow in this trace:
$$(2x^2-xy+y^2)'=1' \implies 4x-(y+xy')+2yy'=0 \implies y'=\frac{y-4x}{2y-x}.$$
Comment: You should view $y$ as a function on $x$.  @Peppa, Could you upvote me so that I will get 10k reputation:)
Comment: @peppa First, remember that $(fg)'=f'g+fg'$ (the product rule). Also remember that $x'=\frac{\operatorname d\!x}{\operatorname d\!x}=1$. Now, use the product rule, where $f=x$ and $g=y$.
Comment: Why is: $$(xy)'=y+xy'$$

Derivative of ellipse


linear, continuous functional, Schwartz space

Question:
Is $g:\mathbb{R}\to\mathbb{C}$ measurable such that it exists $N\in\mathbb{N}$ with $x\mapsto \frac{g(x)}{(1+x^2)^n}\in L^1(\mathbb{R},\lambda)$, then defines $g$ a continuous, linear functional $S_g:\mathcal{S}(R)\to\mathbb{C}$, where $\mathcal{S}(\mathbb{R})$ is the Schwartz space.
$S_g(f)=\int_{\mathbb{R}} f(x)g(x)\, dx$

[This question is related to: Schwartz space, functional analysis ]
To show, that $S_g$ is linear, is easy. Let $\mu\in\mathbb{R}$, then
$(\mu S_g)(f)=\int_{\mathbb{R}} \mu f(x)g(x)\,dx=\mu \int_{\mathbb{R}} f(x)g(x)\, dx=\mu S_g(f)$
$(S_g+S_h)(f)=\int_{\mathbb{R}} f(x)(g(x)+h(x))\, dx=\dotso=S_g(f)+S_h(f)$
Is it correct, that I can show that $S_g$ is continuous by showing it is continuous in $0$?
Can you help me to show, that $S_g$ is continuous?
Thanks in advance.
Answer: It suffices to prove at $0$ because it is translation invariant. Also, it is metrizable, it suffices to prove that, given a sequence $(f_{n})$ and $f$ of Schwartz functions with $f_{n}\rightarrow f$ in the Schwartz seminorms, then $S_{g}(f_{n})\rightarrow S_{g}(f)$. But $\sup|(1+|x|^{2})^{N}(f_{n}(x)-f(x))|\rightarrow 0$, so $\displaystyle\int|f_{n}(x)-f(x)||g(x)|dx\leq\sup|(1+|x|^{2})^{N}(f_{n}(x)-f(x))|\int\dfrac{|g(x)|}{(1+|x|^{2})^{N}}dx$, so the result follows.
And one thing, actually you need to show that $S_{g}(f)$ is defined, that is, the integral exists for Schwartz function $f$.
Comment: For arbitrary topological vector spaces, it is understood that the topology is translation-invariant, so to prove continuity of a linear map it _always_ suffices to prove continuity at $0$. Not just for normed spaces, etc. But/and that remark did not affect the rest of your explanation.
Comment: Thanks, as what you have said, I just realized that is translation invariant, yes, then, $0$ is suffices.
Comment: What would change if we prove it for 0? Does that mean, that $f\equiv 0$?
Comment: Yes, it is just the zero function.
Comment: @user284331 I apologize for dragging this up this late, but could you please explain the observation "$ sup|(1+|x|^2)^N(fn(x)−f(x))| \rightarrow 0$"? Obviously $f_n - f \rightarrow 0 $, but $sup (1+|x|)^N$ is infinite, so how exactly does that work out?
Comment: That is one of the properties of Schwartz functions, you may search Wikipedia for the definition of Schwartz functions.
Answer: Continuity was shown.  You need to show that the integral will always converge though.
If $f \in \mathbb{S}$, then there exists N sufficiently large such that outside of some compact interval $[-N,N]$ we have that $|f| < \frac{1}{(1+x^2)^n}$.  Thus $$\int_{-\infty}^{\infty}|f(x) g(x)| dx < \int_{-N}^{N}|f(x) g(x)| dx  + \int_{-\infty}^{-N} \frac{|g(x)|}{(1+x^2)^n} dx +  \int_{N}^{\infty} \frac{|g(x)|}{(1+x^2)^n} < \infty  $$
Comment: why is the first integral finite?
I would do it in another way:
$\int_{-\infty}^\infty |f(x)g(x)|\mathrm{d}x =\int_{-\infty}^\infty |f(x)g(x)\frac{(1+x^2)^n}{(1+x^2)^n}|\mathrm{d}x $
and then using Hölders inequality and that $f(x)(1+x^2)^n$ is bounded


Drupal 7 How to find Nodes, tagged with Broken Taxonomies?

Question: In Drupal 7, some Taxonomy Terms were deleted (by force from direct DB Query, for some reason). So some Nodes left remained by still tagging this deleted Taxo Terms. Then the problem is arising at the Site Indexing stage. The process is getting broken.
So i believe i need to find the Nodes which are tagging to these no longer existing/broken Taxonomy Terms, to un-tag those.

Which is the best way to do it?
What will be the best Query for it?

Thanks.
Comment: I notice you also have 14 question, but have only accepted two answers.  I've answered your question anyway because I am a stand-up guy and I've found it to be similar to a problem I've had a couple of times ;-)  You might want to evaluate some of your previous questions though and accept some answers :)
Answer: Just as an FYI, even if the terms had been deleted properly, the references still would have been broken (see Database records not deleted for Term Reference Fields after Term is Deleted).
Either way, to answer your question, you could use use super useful Taxonomy Orphanage module.

This module provides interfaces (drush, cron, admin form) for removing
  orphaned taxonomy term references from entities.
Answer: Taxonomy Term data is saved in 'taxonomy_term_data' table. And when you add a field e.g. Article Category (machine name - field_category) in your Article Content Type which is of type Term Reference to say Category Vocabulary then system creates a table like 'field_data_field_category'.
Now after knowing your table name for your custom field, you can execute a query which will give you Nodes which are tagging to these no longer existing/broken Taxonomy Terms,
SELECT f.* FROM field_data_field_category f left join taxonomy_term_data t on f.field_category_tid = t.tid WHERE t.tid is null;

Here you just need to specify your table/field name.
Comment: Huhh, sound interesting but, do i need to run for everrrrrrry field? I have more then 100 fields @_@
Comment: you can store all the fields required in PHP array


Evaluating covariance for independent variables.

Question: Let $x_i,x_j$, two independent variables.
Consider this calculation:
$$\text{Cov}(x_i, x_ix_j) = E(x_i^2x_j) - E(x_i)E(x_ix_j) = E(x_i^2x_j) - E(x_i^2)E(x_j) \\= E(x_i^2)E(x_j) - E(x_i^2)E(x_j) = 0$$
Questions:

Why is true that $E(x_i)E(x_i) = E(x_i^2)$?
Why is true that $E(x_i^2x_j) = E(x_i^2)E(x_j)$. We don't know that $x_i^2$ and $x_j$ are independent.
Comment: 1) is true only if $Var(x_i) = 0$. Is that the case?
Answer: It is wrong. You have
$$
Cov ( X_i, X_iX_j) = E[X_i^2 X_j] - E[X_i]E[X_iX_j]
$$
since $X_i$ and $X_j$ are independent we can split up the expected values:
$$
Cov ( X_i, X_iX_j) = E[X_i^2]E[ X_j] - E[X_i]^2 E[X_j]
$$
Observe the difference with your computations. The second term has the "square" outside. Finally you can write:
$$
Cov ( X_i, X_iX_j) = \left(E[X_i^2] - E[X_i]^2\right) E[X_j] = Var[X_i] E[X_j].
$$
Then the covariance is 0 if and only if, either $Var[X_i]=0$ or $E[X_j]=0$.
Conclusion:
1) It is not true.
2) Yes, they are of course still independent. Take a look at this post: Are functions of independent variables also independent?
Answer: $E[X^2]\not = E[X]E[X]$ in general. Consider a random variable taking the values $-1$ and $+1$ with equal probability. Then $E[X]=0$ and $E[X^2]=1$.


Express in Rectangular Form

Question: a) $(-1+i)^{-i}$
so I know that the answer is $9.92-3.58i$. My track getting there is off.
I know that $x=-1$ and $y=1$, so $r = \sqrt{2}$, also that $\displaystyle \theta=-\frac{pi}{4}$.
I've plugged them into de Moivre's but my final answer does not match the right answer.  Help?
b) $(-1)^{1/pi}$
Answer: Let  $-1+i=r(\cos\theta+i\sin\theta)=r\cdot e^{i\theta}$ (Using Euler's Identity)
Equating the real & the imaginary parts
$-1=r\cos\theta, 1=r\sin\theta$
Squaring and adding we get $r^2=2\implies r=\sqrt2$
$\implies \cos\theta=-\frac1{\sqrt2}<0, \sin\theta=\frac1{\sqrt2}>0 $
From the definition of $\arctan\frac yx,\theta= \pi+\arctan\frac1{(-1)}=\pi-\frac{\pi}4 =\frac{3\pi}4$  as the principal value of arctan lies $\in\left[-\frac\pi2, \frac\pi2\right]$
So, $$(-1+i)^i=e^{i\ln(-1+i)}=e^{i\ln(\sqrt 2e^{\frac{3\pi i}4})}$$
$$=e^{i(\frac12\ln2+\frac{3\pi i}4)}$$
$$=e^{-\frac{3\pi}4}\cdot e^{\left(i\frac{\ln 2}2\right)}$$
$$=e^{-\frac{3\pi}4}\left(\cos \frac{\ln 2}2+i\sin \frac{\ln 2}2 \right)$$
Comment: I'm not following your work. if z=re^itheta, then I have (sqrt(2)e^(i3pi/4))^-i = (sqrt(2))^-i *e^3pi/4.
Comment: @xfitpi, $\sqrt2 e^{\frac{3\pi i}4}=e^{\ln \sqrt2 e^{\frac{3\pi i}4}} $ right?
Comment: @xfitpi, more generally $a=e^{\ln a}$ and $\ln e^b=b\ln e=b$
Comment: yes, that's correct. so then my final answer in rectangular is √2e^3πi/4
Comment: @xfitpi, without calculator, yes.
Comment: what if my equation is (-1)^(1/pi).  then how do I solve for the real and imaginary parts?
Comment: As the principal value of $-1=e^{i\pi};$ So, $(-1)^\frac1{\pi}=(e^{i\pi})^\frac1{\pi}=e^i=\cos1+i\sin1$

Express in Rectangular Form


IFS equal to newline character is not working in bash

Question: I have a multiline string and I want to split is based on \n for which I'm setting IFS=$'\n' but it's not working, I've also tried IFS= and IFS="
" but no luck.
Below is the sample code
IFS=$'\n' read -ra arr <<< "line1\nline2\nline3"
printf "%s\n" "${arr[@]}"
# it only generates array of length 1

I'm using Ubuntu with bash version being
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Can someone point out the obvious.
Comment: The problem is you are not actually reading input, you are providing a string, whether single-quoted or double-quoted, word-splitting will not occur. Your default `IFS` is `" \t\n"` (`space tab newline`), so there is no need to alter `IFS`. This is one of those quirks on how the shell handles a literal. Further, you are only reading once. You seem to be wanting to use `readarray` or `mapfile` rather than `read -a`. You may also be also be confusing `-a` with `-a -d '\n'` where you want to specify the delimiters are `'\n'`.
Comment: The `printf` would produce the same result if the command succeeded. How exactly are you determining the size of the array?
Comment: You are providing a quoted string, e.g. `'line1\nline2\nline3'`, word-splitting will not occur.
Comment: @tripleee by `echo ${#arr[@]}` results in `1`.
Comment: @DavidC.Rankin , edited the question still same result, not getting the split.
Comment: Switching to double quotes doesn't change the fact (if anything, the opposite). You apparently want `<<<$'string'`
Comment: Hint: Try `cat <<<"no\nnewlines\nhere"`
Comment: There are some defects in your script including others have commented:
- Even if you surround the string with double quotes, "line1\nline2\nline3" is not interpreted as newline-separated lines.
- `read` is a line oriented command and it exits after a line is read. This means that you cannot use `-a` option when reading a `newline` separated text.
Comment: From what I can tell you actually want `readarray -t arr < <(printf "line1\\nline2\\nline3\\n"); declare -p arr` which results in `declare -a arr='([0]="line1" [1]="line2" [2]="line3")'` (you can use just `'\n'` instead of the POSIX `'\\n'` in the `printf` string)
Answer: The primary problem with your attempt is word-splitting is not preformed with a herestring. From man bash:

Here Strings
   A variant of here documents, the format is:

          <<<word

   ... Pathname expansion and word splitting are not performed.
   The result is supplied as a single string to the command on its
   standard input.

Bash does provide a heredoc (e.g. "Here Document" in man bash) on which word-splitting will be preformed with the default IFS. However, even then you will still read the literal '\n' as part of the contents of the array. Not to fear, bash has provided a specific manner in which this can be avoided with the -t option to readarray (a/k/a mapfile).
A short example as close as I can get to your original attempt would be:
readarray -t arr << EOF
line1
line2
line3
EOF
declare -p arr

Which results in your lines being saved as desired, e.g. the output would be:
declare -a arr='([0]="line1" [1]="line2" [2]="line3")'

The other alternative is to use process substitution and let printf provide the splitting, e.g.
readarray -t arr < <(printf "line1\nline2\nline3\n")

The key to filling the array without the newlines included is readarray -t, the key to allowing word-splitting to occur is to avoid the herestring.
Answer: from bash manual, bash builtins section:

read

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars]
    [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]

One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option,

and the line delimiter can be specified with -d

-d delim

The first character of delim is used to terminate the input line, rather than newline.

Note that followed by an empty argument -d '', the line delimiter will be the nul character, if there is no nul character in input, it can be used to read the whole input.
However read is slow with even with -r mode.
For larger input a faster solution can be to use word splitting:
input=$'line1\nline2\nline3'
IFS=$'\n';set -f;arr=($input);set +f;IFS=$' \t\n'

note set -f to avoid glob matching phase.


What's the reason for "Error:Cannot determine Java VM executable in selected JDK"?

Question: I am using IntelliJ IDEA 13.1.4 and also tried the latest release 14.
Running SBT I get the following error:
Error:Cannot determine Java VM executable in selected JDK

I have JDK 1.7 installed on my machine and on PATH.
In the logs (~/Library/Logs/IntelliJIdea14/idea.log on MacOS) there's the following stack trace:
2014-11-03 11:22:05,054 [4896641]   WARN - nal.AbstractExternalSystemTask - Cannot determine Java VM executable in selected JDK
com.intellij.openapi.externalSystem.model.ExternalSystemException: Cannot determine Java VM executable in selected JDK
    at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$10.apply(SbtExternalSystemManager.scala:97)
    at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$10.apply(SbtExternalSystemManager.scala:97)
    at scala.Option.getOrElse(Option.scala:120)
    at org.jetbrains.sbt.project.SbtExternalSystemManager$.executionSettingsFor(SbtExternalSystemManager.scala:96)
    at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$getExecutionSettingsProvider$1.apply(SbtExternalSystemManager.scala:54)
    at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$getExecutionSettingsProvider$1.apply(SbtExternalSystemManager.scala:54)
    at org.jetbrains.sbt.package$$anon$3.fun(package.scala:29)
    at org.jetbrains.sbt.package$$anon$3.fun(package.scala:28)
    at com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.getExecutionSettings(ExternalSystemApiUtil.java:590)
    at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager.a(ExternalSystemFacadeManager.java:201)
    at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager.a(ExternalSystemFacadeManager.java:178)
    at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager.doInvoke(ExternalSystemFacadeManager.java:133)
    at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager$MyHandler.invoke(ExternalSystemFacadeManager.java:270)
    at com.sun.proxy.$Proxy57.getResolver(Unknown Source)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:48)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$1.run(ExternalSystemUtil.java:543)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:609)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$7.run(ProgressManagerImpl.java:410)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.application.impl.ApplicationImpl$10$1.run(ApplicationImpl.java:640)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)

What can be the reason for this?
Comment: It's likely that you have JRE in `Project SDK` for the project defined. Could you check Project Settings for the project in question and see the settings under Project?
Comment: I found that I needed to **Invalidate Caches** as described [in this answer](http://stackoverflow.com/a/4482827/77567).
Answer: You should be able to work it around by setting the jdk from the settings not from the open/import project dialog.
From the welcome screen, go to Configure -> Project defaults -> Project structure and add the jdk.

Opening the sbt project should work well then.
Found solution from here
Answer: Another way to set JDK is from your current module/project settings (for your current project)
PickOpen Module Settings from project context menu (or default hit F4),  then from left tab select Project and point correct Project SDK on dropdown.
Answer: The issue is usually caused by a wrong JDK version in ".idea/sbt.xml", e.g.:
<option name="jdk" value="1.7" />

This option is not updated accordingly when the Project SDK is changed, see SCL-10085. If you have the other JDK (1.7 in my example) generally configured, no error will occur, but the Project SDK will silently be changed back. Otherwise, this error occurs.
The problem can easily be resolved by manually editing the value in ".idea/sbt.xml" to the right JDK version.
Answer: Same error also occurs when you try to do a refresh in "SBT tasks".
Open
Preferences -> Language & Frameworks -> Scala Compiler Server

Turn on
Run compile server (in external build mode)

Once you done with refreshing the project, turn it off again to enable hotswapping back when you change your code in the editor.
Answer: I had to open Settings -> Language & Frameworks -> Scala Compiler Server
Then set the JVM SDK there, which was <No SDK>.
This was in addition to setting the Project SDK in Project Structure -> Project.
See the screenshot here.
Answer: IntelliJ 13.1.6 > File > Project Structure > set Project SDK
Answer: I got the same problem after I delete Java1.6 and Java1.7 from Project Settings(with Java8 as default).
Finally I solve the problem by change SBT JVM config to Custom Java(Settings -> Build, Execution, Deployment -> Build Tools -> SBT).
Answer: For me the above suggestions did not help for some reason. However, I did figure out that under Project Defaults > Project Structure (Welcome screen) my default Project SDK was set to the Go SDK.
What worked for me was setting this default SDK to the Java JDK.
Answer: For me, I had selected the JDK in "Open Module Settings" > Module > Dependencies > Module SDK.
However, SBT was looking for JDK at project level which is set in "Open Module Settings" > Project > Project SDK as @michasm has pointed out above
Answer: The latest Nightlies of the Scala plugin change how the project JDK is set, which should solve this in most cases. Let me know if it still breaks on some cases.
Answer: This happened to me in a multi-language project when my primary module's Project SDK was Python and I was trying to add a secondary module that was JDK (importing an sbt project).
I had to temporarily switch the primary module's Project SDK to JDK in order to add the sbt module. I then had the ability to go back and change each module to the correct SDK.


How to lodge tracking event for Customer using Kustomer API

Question: I am trying to integrate Kustomer with a service of mine using their APIs. I am successfully able to create Customer Objects Using their Customer Create API.
Now I want to lodge tracking events for a particular Customer, also I want to control to which session I want to lodge the event using sessionId. Currently I with respect to their API reference Kustomer Event Tracking API I am confused about how to exactly link a tracking event to a Customer and how to exactly use the trackingId and sessionId for successful integration.
Answer: Depending on what you are trying to track and manage here, it may make more sense to leverage custom attributes or kobjects attached to the customer record.  Feel free to reach out to us at firstname.lastname@example.com, and we would be happy to review your particular use case further and advise on an appropriate solution.
Best Regards,
Lucas


Dealing with Brute Force Attack

Question: For the better part of yesterday (and today so far) my server is being attacked with brute force.
I am rather an inexperience admin when it gets passed the basics. I understand how to find things, sometimes understand how to configure things. This attack has got me stressed and tired now.
Every time I think I got it, it comes back.
Here is my CPU usage for the las 24 hours.

It initialized as an xmlrpc attack with some WordPress sites, I've since disabled that with some plugins - I've also removed the files themselves.
The attacks continue. My auth.log show a lot of attempts. I did some reading, could fail2ban is a great tool for stopping brute force attacks.
Configured it - I think it's right even though there are some "Command not found" errors - it says it banned an IP that was attacking me.
Things are quiet for now.
I check this morning - CPU cranked up.
I run top to see whats taking up all the APU
the program 'host' is running.
<code>4274 forge     20   0 1721620   6760   3264 S 98.8  0.3  14:04.99 host
4537 forge     20   0  362804  33656   8664 R  0.3  1.6   0:00.14 php5-fpm
1 root      20   0   33504   3968   2624 S  0.0  0.2   0:01.48 init
2 root      20   0       0      0      0 S  0.0  0.0   0:00.00 kthreadd
3 root      20   0       0      0      0 S  0.0  0.0   0:00.06 ksoftirqd/0
5 root       0 -20       0      0      0 S  0.0  0.0   0:00.00 kworker/0:0H
6 root      20   0       0      0      0 S  0.0  0.0   0:00.10 kworker/u2:0
</code>
It even says by my user. Something else is running this - how can I find out?
Comment: The `host` command can be launched by `fail2ban`. Can you show the output of `ps auxf`?
Comment: Hi -Here is my output for ps aux
http://paste.ofcode.org/XD2ggSwg2xYLj7YRDtmxw4
Comment: I setup fail2ban after the attack began. It seems on a timer, because I can kill the process but usually between an hour or two it starts up. Something already on the machine? A lot of attempts in my auth.log. Hard to tell where to look.
Comment: I can not see any `host` process. Did the CPU load stop?
Comment: Yes, I stopped it. Should I have left it running?
Answer: Xmlrpc.php can start dos to other domains keeping your host as source.. You should remove xmlrpc.php , change login page link , or allow login to your known few IPs from .htaccess .
example from wpscan:
[!] The WordPress 'http://cffcinc.com/readme.html' file exists exposing a version number
[+] Interesting header: LINK: http://cffcinc.com/wp-json/; rel="https://api.w.org/", http://cffcinc.com/; rel=shortlink
[+] Interesting header: SERVER: Apache
[+] XML-RPC Interface available under: http://cffcinc.com/xmlrpc.php
[+] WordPress version 4.6.1 (Released on 2016-09-07) identified from advanced fingerprinting, meta generator, readme, links opml, stylesheets numbers
Comment: I got things under control - I did find more malicious files inside the yoast-seo plugin. A .sh file (shell script) which once I removed the plugin altogether it stopped the bots from running. Meanwhile I changed the login links to all WP; xmlrpc; setup banning with fail2ban; and disallowed reading of directories and such. I'll continue working out various aspects as well to keep it secure.

Dealing with Brute Force Attack


IA32 Assembly: lea instruction

Question: I know that the sentence I am about to say is probably the best way to become very unpopular on StackOverflow very quickly. I'll say it anyway: Why doesn't this work (completly)?
I was trying to figure out what the lea/leal instruction does. The way I understand it, lea/leal finds out the memory address of the first operand and writes this address into the second operand (which might be a register or so).
This part seems to work. When I run the program below it says:
The memory address of var is 134518204.

However, right after this it says something like "memory access error". pushl (%eax) obviously doesn't work. Why not?
.data
    var:    .long 42
    str1:   .string "The memory address of var is %d.\n"
    str2:   .string "At this memory address we find var's value: %d.\n"

.text
.global main
main:
    leal var, %eax          # Copy the address of var into %eax
    pushl %eax
    pushl $str1
    call printf             # Print str1
    pushl (%eax)
    pushl $str2
    call printf             # Print str2

    # Some stack cleaning should be here :)

    movl $1, %eax
    int $0x80

I am not even sure if I got right what lea/leal does. Help is appreciated. ;)
Comment: `movl src, dest` means `dest = src`. `leal src, dest` means `dest = &src` (i.e dest = address of src)
Comment: To be more accurate, `movl` evaluates the source, treats it as an address and moves it's contents to destination.

But, `leal` evaluates the source and moves the evaluated value to destination.
Comment: possible duplicate of [What's the purpose of the LEA instruction?](http://stackoverflow.com/questions/1658294/whats-the-purpose-of-the-lea-instruction)
Answer:
The way I understand it, lea/leal finds out the memory address of the first operand and writes this address into the second operand (which might be a register or so).

Sounds accurate enough. It's used to perform address arithmetic; which can be as simple as just loading an address, but you can also use it to perform multiplication by certain constants.

pushl (%eax) obviously doesn't work. Why not?

Your push instruction is not referencing the address you think it does: printf returns the number of characters written, and that value is returned in the %eax register, so %eax no longer contains the address of var.
Comment: Thank you so much! I actually just read that according to the C Calling Convention, %eax will ALWAYS be changed. Seems like I really need to do something else for a while... :D
Answer: lea is usually (ab)used for calculations: if you just want the address of a global in a register, movl $var, %eax is clearer (and a byte shorter) than the lea.
Also, to make it clear, the destination operand of lea must be a register.

IA32 Assembly: lea instruction


How to extend a module hook from another module?

Question: I want to be able to clone/replicate a node from one language to another on click of a button using a custom module. Basically we have a view which displays all nodes in the system and under the "operations" column, we have Edit, Delete, Clone.
On click of the Clone button, I want to replicate the node (keeping the same exact data values as is except for the language field) to other languages.
I have installed the node_clone and replicate modules to help me, but I am struggling to see how I can create a custom module that can call the hooks in those contrib modules in such a way that I can save the node in different languages automatically instead of click on the "Translate" tab and manually doing it one by one.
I have tried calling the clone_node_save from the Node clone module from my custom module, but that does not work.
How can I extend a module hook in a custom module?
Answer: You can use the following code to solve your problem:
//clone the node
$new = clone $node;
//set the node to new
$new->is_new = true;
//unset the nid and the vid
unset($new->nid);
unset($new->vid);
//setting the new language
$new->language = 'fr';
//save the new node
node_save($new);

Reference: Programmatically create a new node from an existing NID
Comment: This is awesome, thank you!

Would it be advised to use the batch api as well so that way once the data is saved to the database i can get all the fields copied to the appropriate languages?
Comment: If you do not want to have the cloned node connected to the initial node as translation this is the way to go.
Answer: I assume you're triggering the clone using the "clone item" VBO action provided by the node_clone module?  If so, have you looked at hook_clone_node_alter()?  It gives you the node (and some context data - see clone_action_clone() in clone.module) and lets you change values before the cloned node is saved.
If you are not using the VBO action, and therefore don't have the hook available, you might want to look at clone_action_clone() and copy the relevant code.
Comment: I shall look at the clone_action_clone as I am not using VBO
Answer: I think you don't need the node clone module. Look at this solution from the comment: https://www.drupal.org/node/1069774#comment-4834192
This is actually utilizing the entity translation module's translation handler.
Here is the code again:
<?php

$translation = array(
  'translate' => 0,
  'status' => 1,
  'language' => 'sv', // here is the language you're translating to
  'source' => 'en', // here is the source language
);

$node = node_load($nid); // If you've called node_save($node) before, you'll have the node object already and you can omit this
$handler = entity_translation_get_handler('node', $node);
$values['name_field']['sv']['0']['value'] = $sv_name; // You can write the array like this, I find it easier to read
$handler->setTranslation($translation, $values);
field_attach_update('node', $node);

?>

Create a module with hook_menu and a page callback that holds the snippet above.


"RESTORE HEADERONLY is terminating abnormally" error when restoring backup

Question: When I try to restore a database backup file, I get the following error:

An exception occurred while executing a Transact-SQL statement or batch.
  (Microsoft.SqlServer.ConnectionInfo)
Additional information:

Cannot open backup device 'C:\Domains\Backup.bak'. Operating system error 5(Access is denied.).
RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3201)

This only happens on our remote machine. The backup file restores fine locally. The user has administrative privileges on the remote machine and the network service has access to the database and backup file. What is the problem here?
Answer: The SQL user needs the rights to access that location. Network service and local user are not used by SQL anymore.
Comment: how to give rights to access that location to the sql server?
Comment: Exactly what rights are needed? Having the same trouble and giving access to the computer name, as per [this](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-windows-service-accounts-and-permissions?view=sql-server-ver15#Unusual_Locations). Giving read or read-write access doesn't seem to matter. I do see the account gets access granted in EventLog. Also the backup file's read-only attribute is not set.
Answer: While installing sql server if u have selected network services then you will have to add network service in services.msc. select sql server (mssqlserver) and then click properties and then log on. Here specify the account you have used while installing sql server and I hope your problem will be solved. Still if it not solved then you can get in touch with me at firstname.lastname@example.com
Answer: Is this using 2008/2008r2/win7/vista?  If so, Adminsitrator users aren't administrators... until after UAC has it's say-so.  You could try running the restore process with the application running in "Administrator Mode" (right-click run as administrator)... and see if that helps.


Do we have an option to change/override the drupalsettings variable which is defined by some other module through our custom module?

Question: What is the best approach to change/override the drupalsettings variable which is defined by some other module (basically core) through our custom module ? If I follow the same hooks then how to call it at very last in Drupal 8?
Here: by drupalsettings, I am asking about the Drupal behaviors variable.
The question is updated as suggested by @leymannx.
Comment: This is usually the last resort and following the same hook is not specific to the topic drupalsettings. These can be defined in different ways. In hook_page_attachments, then there is a hook_page_attachments_alter,  in render arrays, which can be changed like any other rendered content in various hooks of the render pipeline and finally for dynamic overrides there is hook_js_settings_alter.
Comment: Were does the contrib module attach this variable? Did you try to implement a similar hook and set your own value the same way the contrib module did? What happened? Maybe you then need to ensure to have your implementation run last. Please update your question and provide more details.
Comment: Maybe it works similar to this: https://www.drupal.org/node/2974681. Attach your own JS from where you need it and have it set `Drupal.settings.foobar = 'hello world'` to override the foobar settings declared somewhere else before.
Comment: Thanks for putting your effort @leymannx, your comment is appreciable. I already did the same thing as I was continued debugging. And yes I am on the same page as you have asked, the issue is in the ordering of my module's hook. What will be the best approach to call it last ? some hook like hook_module_implements_alter or using the module modules_weight ?
Comment: Yeah, hook_module_implements_alter.
Comment: Thanks, @4k4, make sense.
Answer: You can alter the drupalSettings with the hook "hook_js_settings_alter":
function hook_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {

  // Add settings.
  $settings['user']['uid'] = \Drupal::currentUser();

  // Manipulate settings.
  if (isset($settings['dialog'])) {
    $settings['dialog']['autoResize'] = FALSE;
  }
}

For more information see: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_js_settings_alter/8.9.x
I checked the code and the theme hook is run after the module hook. So if you really want to be last. Add the hook to your theme.
web/core/lib/Drupal/Core/Asset/AssetResolver.php:
$this->moduleHandler->alter('js_settings', $settings, $assets);
$this->themeManager->alter('js_settings', $settings, $assets);

Comment: You could also use this hook to make sure your module is last: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21module.api.php/function/hook_module_implements_alter/8.5.x
Comment: Useful findings @andeersg, btw I was looking the way to achieve it through module only. Would you also suggest to replace the existing assets(JS/CSS) with my custom one using the same hook ? or I  should just append my custom js in the $assets->setLibraries()?
Comment: If you want to alter/replace the assets I would recommend this hook: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_library_info_alter/8.2.x, `js_settings_alter` is just for altering the settings.


Overfitting in LCM for some indices, but not others

Question: I am estimating latent curve models (btw, this is my first time using LCM) for multiple indices (n = 6) taken from the same sample of research subjects. For some of these indices, the fit measures TFI and IFI are indicating that the model is overfitted (TFI > 1.2 & IFI > 1.2), but for other indices they are telling me the model fit is quite good (TFI and IFI around 1.0). Also, none of the conditional models (predictors n = 3) indicate overfitting.
Can someone explain why, for some indices, the model is overfitted, yet for others it is not, even though the sample size nor the number of parameters does not change?
Answer: It's not overfit (necessarily). I've never heard people describe these indicators as overfitting.
Some fit indices can go over 1, others can't. You seem to have a typo in your question, as you report IFI being 1.0 and also being 1.2. I presume that by TFI you mean TLI - it's also called the NNFI, which stands for Non-Normed Fit Index - it's not normed because it can go over 1.
Check the equations for the indices - if your chi-square is lower than df, the the indices might go over 1 (or might be equal to 1).
I'm not sure what you mean by multiple indices.
Comment: In Bollen & Curran (2005), they state that TLI (sorry for the typo) and IFI scores "much greater than 1 (e.g. 1.2) suggest the possibility of overfitting the data or having a model with too many parameters" (p. 46).
For my study, I am creating multiple models for different indices (e.g. word frequency, word range, concreteness) taken from the same sample of subjects. The models for some of these indices are returning TLI and IFI values that are what Bollen and Curran (2006) claim to be evidence of overfitting. Models for some of the other indices, are not.

Thanks. I'll check my equations.
Comment: Thanks. I didn't remember that (and I've read that book!)
Comment: I suspect your model has very few df - is that the case?
Comment: The models returning TLI and IFI scores at or above 1.2 all have df = 8. I don't remember (from what I've read) if that's considered "very few".
Comment: It's on the lower side. But it's not bad for LCMs that don't have anything complicated going on.
Comment: I don't think you should necessarily be worried about the models that fit too well.


Using linear algebra to find resonance frequency and normal oscillations and motion

Question: I am stuck part way through the following and not sure how or if finding eigenvalues will help with finding modes of oscillations:
Consider the system of three masses and two ideal elastic bands:
$(m)$---$k$---$(2m)$---$2k$---$(m)$  [$m$ are masses, $k$ is spring constant]
Find the resonance frequencies of oscillation, normal modes of oscillation and describe motion of masses corresponding to modes of oscillations.
My work so far:
$$V=\frac{1}{2}(k9x-y)^{2}+k(y-z)^{2}=\frac{1}{2}k[x^{2}-2xy+3y^{2}-4yz+2z^{2}]$$
$$m\ddot{x}=-\frac{\partial V}{\partial x}=-k(x-y)$$
$$m\ddot{y}=-\frac{\partial V}{\partial y}=-k(-x+3y-2z)$$
$$m\ddot{z}=-\frac{\partial V}{\partial z}=-k(2z-2y)$$
$$\therefore\ \ m\ddot{x}+m\ddot{y}+m\ddot{z}=0$$
$$y=\frac{-1}{2}(x+z)$$
$$\therefore -m\omega^{2}x=-\frac{1}{2}k(3x+z)$$
$$\therefore -m\omega^{2}y=-k(x+3z)$$
Up to here I'm good. But from here, to find the normal modes of oscillation I am not sure where to go. If I define $\lambda=\frac{m\omega^{2}}{k}$(from an example in text) I get:
$$\lambda(X) = \left[ \begin{array}{cc}
\frac{3}{2} & \frac{1}{2} \\
1 & 3 \\ \end{array} \right](X)$$
Would I then use $(A-\lambda I)(X)=0$ to find eigenvalues? If I do so, I get:
$\lambda_{1,2}=\frac{1}{4}(9 \pm \sqrt{17})$. At this point I begin to lose confidence and understanding in my method. Any help or guidance would be appreciated. Also, I apologize if the formatting is off putting, I am still learning the language.
Answer: Without using the condition $m\ddot{x}+m\ddot{y}+m\ddot{z}=0$, just write your 3D system as
$$ k\left[ \begin {array}{ccc} -1&1&0\\1&-3&2
\\ 0&2&-2\end {array} \right] \left[ \begin {array}{c} x\\y\\z\end {array} \right]=m\left[ \begin {array}{c} \ddot{x}\\\ddot{y}\\\ddot{z}\end {array} \right]$$
Now compute the frequencies as eigenvalues and normal modes of oscillation as eigenvectors.
Notice that the eigenvalue $0$, corresponding to uniform motion of the system as a whole, appears naturally.
Comment: We start with 3 equations which in matrix notation are $M\vec{v}=\ddot{\vec{v}}$. We want to change basis in order to *decouple* these equations and arrive at 3 equations of the form $\lambda_i X_i=\ddot{X_i}$. This decoupling is what diagonalization of $M$ provides.
Comment: I guess I've not come across (that I can remember) an eigenvalue problem like this (vector $x$ on one side and vector $\ddot{x}$ on the other). Would it still be of the form $(\frac{k}{m}A-\lambda I)(X)=0$ where (X) is {x,y,z}?


Is the batsman lbw or bowled in this scenario?

Question: If the ball hits the batsman's pads in front of the wicket but then the ball goes on to hit the stumps, does the bowler still have the option of appealing for an lbw or will the batsman be given out bowled regardless?
Answer: Bowled. Refer to Law 32.2:

The striker is out Bowled if his/her wicket is fairly broken as in 32.1, even though a decision against him/her for any other method of dismissal would be justified.

Also note that the fielding team never has to appeal for a specific method of dismissal; Law 31.4:

An appeal "How's That?" covers all ways of being out.


plotting with pcolormesh, changing axis

Question: Supppose I am plotting a assymetric matrix with pcolormesh:
import prettyplotlib as ppl
import matplotlib.pyplot as plt
import numpy as np

plt.figure()
fig, ax = plt.subplots(1)
ppl.pcolormesh(fig, ax, np.random.randn(10,80))
plt.show()

Now I want to change the x-axis such that its extents are for example -500  to 500 without changing the plot, only the labels of the x-axis, the same for y-axis. How can I accomplish that?
Comment: it is better to pass in the correct X/Y arrays to `pcolormesh` so that the tick labels take care of them selves.
Comment: this is a good advice, but could you please show how to do that properly?
Answer: After the ppl.pcolormesh command you can define the ticklables directly using
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)

where xticklabels is an array of your desired labels and xticks are the values at which the labels should apply.

plotting with pcolormesh, changing axis


Select the next and previous id with certain arguments

Question: I have a table that looks like this (with non-important columns omitted
`pictures` (
  `picture_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `picture_title` varchar(255) NOT NULL,
  `album_id` int(10) unsigned DEFAULT NULL,
  `authenticated` tinyint(4) DEFAULT '0',
  `approved` tinyint(4) DEFAULT '0'
)

What I want to do is to get the next and previous authenticated and approved picture_id. There's a catch though - that occurrence either has to have picture_id = album_id or album_id IS NULL.
Here's an image to easier describe what I want to achieve. https://i.stack.imgur.com/slkit.png
The columns marked in red is what I want to select, the one marked in green is the picture_id I have and wanna find the next/previous id of. Note that it skips picture_ids 2 < 9 because it has an album_id that isn't equal to its picture_id and it skips picture_id 11 because it's not authenticated/approved.
How do I achieve this? I'm clueless.
edit: reworded a bit
Comment: Just write two queries: one for the preceding entries, one for the following entries, and use a proper `ORDER BY id DESC` or `ORDER BY id ASC` respectively, add `LIMIT 1` , and you have your previous and next values. If you want them in 1 query, just `UNION` them.
Comment: Can't you use the solutions in the **Related** questions?
Answer: You could use a simple union query, where you take the following into account:

The middle picture matches your id.
The prior picture matches your conditions PLUS its id is lower, BUT is the highest id, from the lower part of the table.
The next picture matches your conditons PLUS its id is higher, BUT is the lowest id, from theupper part of the table.

Check this (Note id 2 getting skipped, cause it does not match the "id=album or album=null" contraint.):
See this fiddle: http://sqlfiddle.com/#!2/42ce6/17
  (SELECT
    *
  FROM
    pics
  WHERE
    id = 10
  ) -- target id image
UNION
  (
  SELECT
    *
  FROM
    pics
  WHERE
    id < 10 AND
    authenticated = 1 AND
    approved = 1 AND
    (id = album OR ISNULL(album))
  ORDER BY id DESC LIMIT 0,1
  ) -- highest id of lower part
UNION
  (
  SELECT
    *
  FROM
    pics
  WHERE
    id > 10 AND
    authenticated = 1 AND
    approved = 1 AND
    (id = album OR ISNULL(album))
  ORDER BY id ASC LIMIT 0,1
  ) -- loweste id of upper part
  ORDER BY id

Limiting the "upper" part and "lower" part of the table to 1 matches exactly the 2 entries you want to fetch.
Output:
ID  TITLE   ALBUM   AUTHENTICATED   APPROVED
1   My fav  1   1   1
10  test 2  (null)  1   1
12  Holiday pictures    (null)  1   1


Dojo Tooltip appears in top-left corner of the page

Question: I have a Dojo tooltip that's been initialized and it works perfectly find when hovering over the desired node.  The problem is that once the tooltip shows up for the first time, when i'm no longer hovering over the "tooltip" area then the tooltip appears in the top-left part of the page.  How do I hide the tooltip when i'm out of the "hover" area for the tooltip.
Here is my initialization bit of code:
<code>new dijit.Tooltip({
  connectId: [this.myCloseContainerId],
  label: this.substitute(this.tooltipTemplate, {
    tooltipText: this.closeTooltipText
  }),
  position: ["below"],
  showDelay: 50
});
</code>
All of the "variables" are set and defined.
Answer: The solution is the following.  Since when Dojo positions the tooltip it sets the CSS opacity to 1, then the easiest solution is to set the opacity to 0 by default, i.e., in your own css define the following rule:
<code>.dijitTooltip {
  opacity: 0;
  filter: alpha(opacity=0); /* this is for IE support */
}
</code>
This seems to have resolved the issue.


Penalties scored by both feet?

Question: Bobby Zamora and Obafemi Martins have scored with both feet on kicks from the penalty mark in the Premier League. So, I'm interested in knowing, whether there are any players that have done the same thing in other top European leagues.
Note: Doesn't have to be in the same match or within 90 minutes.
In top level football, e.g, Andreas Brehme Germany's left-back at the 1986 and 1990 World Cups, took two penalties with both feet in consecutive tournaments. The kick in 1990, with his right foot, was the winning goal in the World Cup final. Here are those penalty kicks:

Source: The Telegraph
Answer: Apart from players already mentioned in the question (Zamora, Martins, Brehme), I couldn't find anyone else who scored penalty-kicks with both feet in top level football (let alone in top European leagues).
But, I have something juicier for you!
Simone Verdi has scored 2 free-kicks in one game with both feet for Bologna F.C. 1909, in a Serie A match of the 2017/18 season, Bologna 2-3 Crotone.
Here is the left-foot free-kick:

Here is the right-foot one:

Source: Serie A YouTube video
Comment: I thought so too after searching for it's answer, so until someone answer otherwise I am accepting this answer. And at this rate you will clear unanswered questions in no time. Thanks for your effort.

Penalties scored by both feet?