running a thread inside a class function

Question: I need to run some parts of my code with thread. But I got problem with accessing the variables from run() function. The variables (also the function arguments) needs to be defined as final, but as I do this I cannot change their value inside run() function. For example now variable iv is not accessible in run() method.
Is there any way I could handle this problem?
@Override
public View getView(int position,  View convertView, ViewGroup parent) {

    LayoutInflater inflater = getLayoutInflater();

    convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
    ImageView iv = (ImageView) convertView.findViewById(R.id.icon);
    final File file = new File(Uri.parse(getItem(position).toString()).getPath());

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Bitmap bmp = null;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            try {
                BitmapFactory.decodeStream(new FileInputStream(file), null, options);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            options.inJustDecodeBounds = false;
            options.inSampleSize = 2;
            try {
                bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            iv.setImageBitmap(bmp);
        }
    };

    new Thread(runnable).start();
    return convertView;
}

Comment: You aren't reassigning the `iv` variable... It can be `final`
Answer: What you need to do here is to make iv final:
final ImageView iv = (ImageView) convertView.findViewById(R.id.icon);

In this context final means that you cannot change reference to the object iv points to, but you still can call any methods of it. Also beware of creating new Thread for each view, I would suggest using thread pool represented by ExecutorService instead.
Comment: I've already done that! but now there is just an image view with no image inside it :(
Comment: @sara check the code/logcat, maybe you have some error; also you are decoding the same stream twice.


Remove buttons for a few seconds in Python/Tkinter?

Question: I'm writing a program where the user will make a selection based on a target image. I'm trying to get the program to remove the selection buttons and wait 2 seconds after updating the target image before the selection choices are re-presented. The code that I have seems to "disable" the clicked button for 2 seconds, but does not remove either button.
from tkinter import *
import random

root = Tk()
root.geometry("500x500")

def click_b(event):
    btn_b.pack_forget()
    btn_c.pack_forget()
    new_a()
    root.update()
    root.after(2000, show_btns())

def click_c(event):
    btn_b.pack_forget()
    btn_c.pack_forget()
    new_a()
    root.update()
    root.after(2000, show_btns())

def new_a():
    k = random.randrange(1, 3)
    if k == 1:
        btn_a.configure(image=a1)
    elif k == 2:
        btn_a.configure(image=a2)

def show_btns():
    btn_b.pack(side=LEFT)
    btn_c.pack(side=RIGHT)

a1 = PhotoImage(file="A1.gif")
a2 = PhotoImage(file="A2.gif")
orange = PhotoImage(file="orange_btn.gif")
green = PhotoImage(file="yellowgreen_btn.gif")
btn_a = Button(root, image=a1)
btn_a.pack()

btn_b = Button(root, image=orange)
btn_b.bind('<Button-1>', click_b)
btn_b.pack(side=LEFT)

btn_c = Button(root, image=green)
btn_c.bind('<Button-1>', click_c)
btn_c.pack(side=RIGHT)

root.mainloop()

Comment: Have you done any research? There are lots of questions on this site about hiding widgets, and probably most tkinter tutorials cover the subject in one way or another.
Comment: I've searched extensively. From everything that I've found the code I have should work. None of the questions that have been asked, that I have been able to find, re-present the widgets - they just remove them.
Comment: Actually this works fine for me... the buttons do disappear.
Comment: @ROAR how odd. I did test the code and got an error when pressing the buttons. Now it seams to work fine when testing the OPs code after your comment...
Comment: @SierraMountainTech well maybe when you changed the code for yourself to work (changed images and stuff) you accidentally changed something else you shouldn't have.
Comment: @ROAR. Thats possible. Oh well.
Answer: the issues is in your after() methods.
You need to remove the brackets for the show_btns function call or else tkinter will not run this command properly. If you have a function with no arguments you leave off the () portion.
If you do have arguments then you will need to either provide those arguments in the after statement IE after(2000, some_func, arg1, arg2) or use lambda to create a one off function to do the work like after(2000, lambda: some_func(arg1, arg2)). lambda can be more complicated but this is the basic concept.
change:
after(2000, show_btns())

To:
after(2000, show_btns)

As long as your paths to your images work fine the below code should work as intended.
from tkinter import *
import random

root = Tk()
root.geometry("500x500")

def click_b(event):
    btn_b.pack_forget()
    btn_c.pack_forget()
    new_a()
    root.update()
    root.after(2000, show_btns)

def click_c(event):
    btn_b.pack_forget()
    btn_c.pack_forget()
    new_a()
    root.update()
    root.after(2000, show_btns)

def new_a():
    k = random.randrange(1, 3)
    if k == 1:
        btn_a.configure(image=a1)
    elif k == 2:
        btn_a.configure(image=a2)

def show_btns():
    btn_b.pack(side=LEFT)
    btn_c.pack(side=RIGHT)

a1 = PhotoImage(file="A1.gif")
a2 = PhotoImage(file="A2.gif")
orange = PhotoImage(file="orange_btn.gif")
green = PhotoImage(file="yellowgreen_btn.gif")
btn_a = Button(root, image=a1)
btn_a.pack()

btn_b = Button(root, image=orange)
btn_b.bind('<Button-1>', click_b)
btn_b.pack(side=LEFT)

btn_c = Button(root, image=green)
btn_c.bind('<Button-1>', click_c)
btn_c.pack(side=RIGHT)

root.mainloop()

Comment: You don't have to use `lambda` for positional arguments. You can supply them as arguments to `after` (eg: `after(2000, some_function, arg1, arg2)`)
Comment: @BryanOakley I was not aware of that. Thanks for the info. I was under the impression that lambda was the only options if arguments were needed. I will update my answer.
Comment: Thank you both! My sample code for the question didn't have arguments but my actual program did. Both are working now.
Comment: @Ash.notKetchum good to know your main code had arguments. That is an important bit of info.


Not able to update module via drush

Question: I am trying to update a module via drush. Referring this link
<code>[root@localhost d7]# drush update
The drush command 'update' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have    [error]
installed new extensions.
</code>
But it is giving error that 'update' command could not be found. Can anybody help me with this?
Answer: Update all update available modules other than locked modules.
drush pm-update
or
Update specified module only.
drush up 'module-name'
Answer: You can update your module following this procedure too:

make sure db is backed up
put site in maint mode
disable the module
remove the old module's directory in /sites/all/modules/
put in the new module's directory in /sites/all/modules/
re-enable the module
run update.php
take site out of maint mode

and if "update" command is not found, may be your drush is not installed properly, try inreinstalling it.

Not able to update module via drush


A segunda QUERY do Store Procedure não roda... não achei o bug

Question: A segunda seleção do Store Procedure não roda... não achei o bug...
<? require("viskoo_conexao/conectar.php");?>

<?php

$consulta="CALL SPMenuConsulta";

$resultado = mysql_query($consulta)

or die("Falha na SP (1)");

?>

<?php

while ($linha = mysql_fetch_assoc($resultado))

{

$ValorAtributo = $linha[ValorAtributo];

$CodAtributoValor = $linha[CodAtributoValor];

echo $ValorAtributo." ($CodAtributoValor)
";

?>
        <? $resultado2 = mysql_query( 'CALL SpMenuSubConsulta(5)' ) or die(mysql_error()); ?>

        <?php
        while ($linha2 = mysql_fetch_assoc($resultado2))
        {
        $ValorAtributo = $linha2["ValorAtributo"];
        echo "--Sub".$ValorAtributo."
";
        }
        ?>

<?

}

?>

Comment: Exatamente @rray "Commands out of sync; you can't run this command now"
Comment: Pessoal não perdoa, 1 minuto e 2 negativos. Deviam usar esse esforço pra ajudar, mas enfim. Não entendi pq vc esta usando CALL SpMenuSubConsulta(5) em uma query. Pode explicar?
Comment: Um possível problema é o uso das funções obsoletas `mysql_*` que não trabalham corretamente com SP.
Comment: Hum? não entendi os primeiros comentários rs sim. Seguinte... eu preciso de 2 seleções nesse caso, pego os dados de uma SP e uso em outra SP com o while
Comment: E qual poderia utilizar no lugar? @rray
Comment: Qual erro aparece? é algo como out sync?
Comment: Da pra resolver de algumas formas, se não possível trocar as funções pelo `MySQLi` ou PDO pode armazenar o resultado da primeira SP em um array depois fazer um foreach com ele e chamar a segunda dentro, talvez tenha outra forma mas essas são as que lembro agora xD
Comment: Já tá ótimo brother @rray eu vou testar esses dois, resolvendo volto a publicar a resolução!! tks, obrigado brothers
Comment: Diego, Eu penso a mesma coisa cara, Se eles usassem isso para ajudar seria muito mais produtivo, parece que eles já acostumaram a negativar tudo, eu fiz uma pergunta e em alguns minutos tiveram 2 negativos e logo depois subiu para 2 positivo e 2 resposta cada uma com 1 postivo... Agora pensa... Aqueles que negativam eles negativam por quê?? se a pergunta estava dentro dos conforme e ganhou positividade?? tá vendo? tem algo muito errado nisso o povo prefere só atrapalhar ao invés de ajudar.
Comment: Entendi agora rs Diego! realmente rs
Answer: Brother, resolvi o problema usando um ARRAY, olha só! deu certinho!
                <?php
                $ArrayMenuAtr = array();

                    $mysqli = new mysqli('localhost', 'loja', 'Pass', 'loja' );
                    $result = $mysqli->query("CALL SPMenuConsulta()");

                    if( !$result ) {

                        die('Query failed returning error: '. $mysqli->connect_errno );

                    } else {

                        while( $row = $result->fetch_array(MYSQLI_ASSOC)) {
                            $ValorAtributo        =  $row['ValorAtributo'];
                            $CodAtributoValor        =  $row['CodAtributoValor'];

                            $ArrayMenuAtr[$CodAtributoValor] = $ValorAtributo;

                        }
                    }
                ?>

                <?

                foreach ($ArrayMenuAtr as $id => $categoria):

                echo "Menu: $categoria ($id)
";

                $mysqli = new mysqli('localhost', 'loja', 'Pass', 'loja' );
                    $result = $mysqli->query("CALL SpMenuSubConsulta($id)");

                    if( !$result ) {

                        die('Query failed returning error: '. $mysqli->connect_errno );

                    } else {

                        while( $row = $result->fetch_array(MYSQLI_ASSOC)) {
                            $ValorAtributo        =  $row['ValorAtributo'];

                            echo "Sub- ".$ValorAtributo."
";
                        }
                    }

                endforeach

                ?>

Answer:
Commands out of sync; you can't run this command now

Esse erro acontece geralmente ao utilizar stored procedures com as funções mysql_*, a mensagem diz algo como "não posso processar essa consulta porque ainda não terminei de tratar a anterior."
O ideal é migrar o código das funções mysql_* para as do MySQLi, se isso não for possível, faça o processamento da primeira consulta e armazena em um array e depois itere ele chame a segunda stored procedure.
<?php
   $consulta="CALL SPMenuConsulta";
   $resultado = mysql_query($consulta) or die("Falha na SP (1)". mysql_error());

   $arr = array();
   while ($linha = mysql_fetch_assoc($resultado)){
      $arr[] = $linha;
   }

   foreach($arr as $item){
      $ValorAtributo = $item['ValorAtributo'];
      $CodAtributoValor = $item['CodAtributoValor'];
      $resultado2 = mysql_query( 'CALL SpMenuSubConsulta(5)') or die(mysql_error());
      while ($linha2 = mysql_fetch_assoc($resultado2)){
         $ValorAtributo = $linha2["ValorAtributo"];
         echo "--Sub".$ValorAtributo."
";
      }
    }

Comment: Estranho, tentei e retornou o mesmo erro "Commands out of sync; you can't run this command now"
Comment: No Lugar no (5) eu gostaria de pegar o valor de $CodAtributoValor -- `CALL SpMenuSubConsulta($CodAtributoValor)´
Comment: @JosiasViskoo deu erro? em teoria é a mesma coisas
Comment: Aparentemente deu erro também... talvez exista alguma alternativa diferente para fazer o que estou pensando em fazer... talvez essa prática é errada... porque na web e no manual não tem nada do tipo... o que eu estou tentando fazer é um menu e submenu a partir de uma consulta variante. A Primeira SP retorna categorias e a segunda SP retorna os IDs das categorias que trazem outros subcategorias, pensei em fazer na mesma SP, mas utilizarei essa SP em outras páginas...
Comment: @JosiasViskoo mesmo executando a primeira consulta em um while da o out of sync?
Comment: Sim, deu o mesmo erro... estranho... até individuais também acontece isso, mas a diferença entre eles é que uma é parametrizada e outra não... talvez o mysql_query não suporta SP com parâmetro, será?
Comment: @JosiasViskoo o problema é que você tenta executar a segunda consulta sem ter acabado de tratar a primeira, to vendo aqui outras coisas ...
Comment: Hum entendi... pelo que entendi é isso, mas não consegui tratar essa questão nessa possibilidade... @rray


How do I integrate a function that returns a value in terms of another symbol

Question: I am currently trying to integrate a function using scipy.integrate.quad, but my function has two variables, the first is x, which is a variable being integrated out, and the second is G, which I am trying to solve for after the integration is complete.
I've already tried to use sympy.integrate which supports the integration of symbols, but my integral is too complex to be evaluated.
An example of the integral I am trying to solve is shown here:
C = integrate.quad(lambda x: x/(1+(3*G)*x)

I want to be able to evaluate the integral so that I could then solve for G because C is a constant value.
I expect the output to be some function of G that I can then use to solve for G, but I can't figure out how to integrate the function without previously defining G.
Answer: First note what your ultimate goal is: solve the equation f(G)==C, where f() is a function of a single argument. Now, it so happens that your f is the result of the integration with respect to a second variable. Therefore, simply define a single-argument function that computes this integral as follows:
def f(G):
    return quad(lambda x: x/(1+(3*G)*x), 0, 10)[0]

and call scipy.optimize.root_scalar to solve the equation (with C==1 in this example)
root_scalar(lambda G: f(G)-1, x0=2, bracket = [0,5])

      converged: True
           flag: 'converged'
 function_calls: 10
     iterations: 9
           root: 3.1734489114921782

Comment: Thank you very much for the suggestion. If I can ask another question, why did you choose those values for the starting point and bracket? Thanks.
Comment: I am also receiving an error now: "The occurrence of roundoff error is detected, which prevents the requested tolerance from being achieved.  The error may be underestimated."
Comment: @Lam All parameters in the code (including integration limits) were selected more or less arbitrarily. I did a plot of `f(G)-1` to get an idea of where the root is (in the domain `G>0`)
Comment: @Lam yeah, I got this warning as well for some parameters. Apparently, the function is not "behaving" well for some parameters/values of `G`. This is something you will have to work on your own (e.g., choose your function and/or parameteres/domain, etc, so that this issues do not occur or do not introduce problems finding the solution). But this has nothing to do with the overall approach described in the answer.


Isomorphic Submodules

Question: I would like to solve the following question: Let $M=\oplus_{i\in I}M_i$ be a direct sum of right $R$-modules and $X$ a nonzero submodule of $M$. Then there exists some $i\in I$ auch that $X$ and $M_i$ have nonzero isomorphic submodules.
I was telled to consider this:
Let $a\in X\setminus\{0\}$. Then $a=a_{i_1}+...+a_{i_n}$ with $a_{i_k}\in M_{i_k}\setminus\{0\}$ unique. I got a hint to consider an $a$ with "minimal support", so where the $n$ is minimal (but not $0$). But how I can use that?
Comment: I understand it like this: They have one isomorphic submodule, not that all have to be isomorphic.
Comment: Uhm... What does it mean for $X$ and $M_i$ to "have non-zero isomorphic submodules"? The obvious intepretation seems false: for instance, say, $R=\Bbb R$, $M=\Bbb R[x]=\bigoplus_{n\in\Bbb N} \Bbb Rx^n$ and $X=\Bbb R1\oplus \Bbb Rx\oplus\Bbb Rx^2$. Then, $X$ has submodules of dimension $2$, but none of the $\Bbb Rx^n$ has.
Comment: Your idea doesn't work, because you can't assume $a_i\in X$.
Comment: Thanks, I got my mistake. Any idea how to solve the question?
Answer: Take some $a \in  \bigoplus M_i$ with minimal support, say $a = a_1 + \ldots + a_n$. Now, consider cyclic modules $< a>_R \leq X$ and $<a_1>_R \leq M_1$; let's see they're isomorphic via the projection homomorphism $\pi(a_1 + \ldots +a_n):=a_1$:
$\pi$ is obviously onto and if $\pi(ar) = 0$, the first coordinate of $ar$ is zero contradicting the minimality of the support of $a$.

Isomorphic Submodules


Error : No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view

Question: I cannot work out some basic stuff ... what do I not correct?
Using D8, distribution varbase.
I  would like to create a reference from one content type to antoher in D8 so a user is able to use a select box by module chosen (https://www.drupal.org/project/chosen)
I looked up different post but cannot find the problem. The latest QA is followed is: How to create a select box field to select from a filtered list of articles?
or also this post How to create a view type of Entity reference display?
So I did I create a view
<code>- Add Display Entity Reference
- Format:Entity Reference list | Settings with content: title
- Show:Entity Reference inline fields | Settings with content title.
</code>
Then I add some fields as well. The result is a list of education
Clear cache, did drush CR.
I goto to the content type I would like to have the reference (e.g. student).
Add a field and would like to add this view a a selectbox to object student.
I should be entity reference the in the reference field I select Views with a filter reference. But every time I get the message here...
No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view.
The view list displays:
Nascholingsactiviteit voor leden  - Entity Reference Source
I made another view for testing purposes but no result of that as well.
I tried other fields but i cannot get it working. I though this is all in D8 core now... Any suggestions?
Comment: Which Drupal version exactly are you using? There still may be bugs with using the Entity Reference display in the older 8 versions. Is your Entity reference Display of the correct type? For example if you want to reference students (who may be user entities) from Education content (which may be node entities) then you need to create a Views Display of type User. Does your Views Display type match the Entity reference field settings options? I've never used the module Chosen. Does it work if you don't use the Chosen widget?
Comment: Using Varbase 8.4.21 which include Drupal core 8.5.3 Yes the view contains nodes and is therefore from the correct type.
Comment: Can you give more explanation on this one: Does your Views Display type match the Entity reference field settings options?
Comment: I did not use the chosen module yet .. only all is drupal basic stuff
Comment: It does sounds like a mismatch in configuration, if it's not the Chosen module or Varbase specific. It would be great if you post screenshots of the Views ER Display configuration, and of your ER field settings (edit the Question to add those in).
Answer: I solved it by chosing content as a reference. After that the options are the same but then it is displaying the view and it works.


Fréchet derivative of a matrix expression

Question: Suppose $h(Q) = Q^{T} A Q$, then the Fréchet derivative is given by $D_{h} (Q) [H] = H^{T} A Q + Q^{T} A H$. I am bit unsure about this so-called Fréchet derivative is obtained.
I would have just said:
$(h(Q))'= \dot{Q^{T}}AQ + Q^{T}\dot{A}Q + Q^{T} A \dot{Q}$, and then try to find an expression, but I haven't been able to come up with one.
Any help is appreciated.
Comment: Why is there $H$ in your expression?
Comment: @KBS Not only for this function. My main point here, however, is that it is deceptive to say that "this just follows from the definition" and then use something that is not "the definition"
Comment: @ArcticChar from the derivative
Comment: Why is it no $H$ in $\dot Q^TAQ$ but $H$ in the next two terms?
Comment: @ArcticChar my own Idea, but I am also a bit puzzled by this H. Seems like it means that in the book I am reading they are differentiating Q along H
Comment: What exactly do the dots mean to you?
Comment: @BenGrossmann derivatives
Comment: @ArcticChar that was a mistake I have made the edits now.
Comment: The most basic example is to find the derivative of the inverse matrix. This is simply apply the product rule to $XX^{-1}=I$. and then we end up with $\dot{X}^{-1} = - X^{-1} \dot{X} X^{-1}$. but the book I am following they derive this in a bit more formal manner, which confuses me. They say that: $F(X)X=I \implies DF(X)[U]X + F(X)U=0 \implies DF(X)[U]=-X^{-1}UX^{-1}$, which I suppose is the same thing that is confusing me in my question
Comment: @user What you seem to not be understanding is that by definition, the derivative of $h$ at $Q$, i.e. $Dh(Q)$, is itself a function. In this case, it is a linear map  between the domain and codomain (which you do not explicitly specify in your question). You might find [this post](https://math.stackexchange.com/a/2136649/81360) to be helpful.
Comment: @user21369645 You might also find [this post](https://math.stackexchange.com/a/1622704/81360) helpful
Comment: @user21369645 What exactly do you have in mind with $\dot{Q}$? The derivative described by the Frechet derivative formula is a derivative with respect to a matrix input, but your result in terms of $\dot{Q}$ or the result with $\dot{X}$ in your comment only makes sense with an interpretation $\dot{X} = \frac{dX}{dt}$ for some parameter $t \in \Bbb R$
Comment: This just follows from the definition $D_h(Q)[H]=\lim_{\epsilon\to0}(h(Q+\epsilon H)-h(Q))/\epsilon$.
Comment: @KBS which definition are you referring to?
Comment: The definition of the derivatives which are available all over the Internet. Did you look at the Wikipedia page before asking?
Comment: @KBS , This is my first time taking the derivative of a matrix function, which caused me some confusion. I don't see any reason to be hostile because you know something I don't.
Comment: @KBS That's uses the definition of the Gateaux derivative, not the Frechet derivative. It can be shown that this result is indeed equal to the Frechet derivative (whenever a function is Frechet differentiable), but as far as I have seen this is not how the computation of the Frechet derivative is ever presented
Comment: @BenGrossmann This is true, but they coincide for this function
Comment: It's worth noting that this approach does generally work: for example if $g(a, b, c)$ is a multilinear function then $$D[g(a(Q),b(Q), c(Q))][H] = g(Da(Q)[H], b(Q), c(Q)) + g(a(Q), Db(Q)[H], c(Q)) + g(a(Q), b(Q), Dc(Q)[H]).$$ On the LHS we're taking the derivative of the function $Q \mapsto g(a(Q), b(Q), c(Q))$. In your case $g(a, b, c) = a^Tbc$ and $h(Q) = g(Q, A, Q)$ so that $Da(Q) = DA(Q) = 0$ because $A$ is a constant. The obvious generalization works for multilinear functions of any arity.
Answer: As I've stated in my comments, I think your primary confusion is over the "data type" of the Frechet derivative. I've addressed this concern in the comments on your question. Here, I will talk primarily about how one computes the Frechet derivative.
There are several equivalent definitions of the Frechet derivative that can be used, but I prefer the following. For normed vector spaces $U,V$ and a function $f:U \to V$, the Frechet derivative of $f$ at the point $x \in U$ (written as $Df(x)$) is the unique linear map $Df(x) = A:U \to V$ for which
$$
f(x + h) = f(x) + A(h) + o(\|h\|)
$$
for $H \in U$. Here, $o(\|h\|)$ (which is little-o notation) denotes a sum of "higher order terms". In other words, at any given $x \in U$, the remainder $R(h) = f(x+h) - f(x) - A(h)$ satisfies
$$
\lim_{h \to 0}\frac{R(h)}{\|h\|} = 0.
$$
Note that $A(h)$ can be written as $[Df(x)](h)$ or, as you have writen it, in the form $Df(x)[h]$.
With that in mind, you seem to have a function $h:\Bbb R^{n \times m} \to \Bbb R^{n \times n}$ of the form
$$
h(Q) = Q^TAQ,
$$
for some $m \times m$ matrix $A$. At any given $Q$, $Dh(Q)$ will be a linear map that takes an $n \times m$ input and produces an $n \times n$ output. That is, for any $n \times m$ matrix $H$, $Dh(Q)[H]$ will be an $n \times n$ matrix.
My preferred approach to finding this linear map is to "expand" the expression $h(Q + H)$. In this case, this simply amounts to expanding a product of matrices; more generally, we might use something akin to a "linearization" or "Taylor series" expansion. We have
\begin{align}
h(Q + H) &= (Q + H)^TA(Q + H)
\\ & = \underbrace{Q^TAQ}_{h(Q)} + H^TAQ + Q^TAH + \underbrace{H^TAH}_{o(\|H\|)}.
\end{align}
The initial term of the sum  is equal to $h(Q)$. The final term of the sum involves a multiplication of two $H$'s, which means that its norm $\|H^TAH\|$ scales with $\|H\|^2$, which means that as $H \to 0$, this term approaches zero faster than $\|H\|$. The piece that remains is $H^TAQ + Q^TAH$, which depends linearly on $H$. That is, $\mathcal L(H) = H^TAQ + Q^TAH$ is a linear map. With this linear map, we have
$$
h(Q + H) = h(Q) + \mathcal L(H) + o(\|H\|).
$$
So, by definition, $\mathcal L = Dh(Q)$. That is, we have
$$
Dh(Q)[H] = H^TAQ + Q^TAH.
$$
Comment: Thank you so much for taking your time to make such a thorough answer. Much appreciated! I will go through it slowly and try to digest it. If you have used any references for this question, may I ask which one?
Comment: Glad to help. Another post that comes to mind: in [this post](https://math.stackexchange.com/a/3792657/81360), I used the [Frechet derivative](https://math.stackexchange.com/a/3792657/81360) to apply the chain rule in the context of back-propogation (for neural-nets)
Comment: @user21369645 I don't have a reference for you off the top of my head
Comment: Related to this question there's an identity which relates the jacobian with the vectorization and Kroenecker product. Do you mind if I ask it in this chat?
Comment: @user21369645 I don't know what you're referring to so it's likely that I don't know the answer. I recommend that you post a new question and then put a link to that question in another comment on my answer.
Comment: Having obtained the derivative, they state that the Jacobian $J_h$ is $J_h(vec Q) = ((AQ)^{T} \oplus I)\Pi + I \oplus Q^{T} A$, where $\Pi$ is the permutation matrix $\Pi^{T}=\Pi$ s.t. $\Pi vec(X) = vec(X^{T})  \ \forall X$. They stress the importance of the identity $vec(AXB)=B^{T} \oplus A vec(X)$. I have looked into this: https://math.stackexchange.com/questions/1829956/differentiation-w-r-t-the-mboxvec-operator
Comment: @user21369645 ok, now I know what you're referring to. I still recommend that you post a new question.
Comment: I think I figured it out, it follows almost immediately from one of the many identities regarding kroenecker and the vectorization operator. Thanks a lot for your time though! If I get stuck I will post a fully question later. I will try to work out the details at first.
Comment: https://math.stackexchange.com/questions/4667862/jacobian-and-vectorization


how to get current row index when reading DbDataReader in ADO.net

Question: i have an excel sheet which i read with a code like this
Public Async Function ReadRecordAsync() As Task(Of SellingList)
        Try
            Dim Sellings As New SellingList
            Await Conn.OpenAsync()
            Cmd = New OleDbCommand()
            Cmd.Connection = Conn
            Cmd.CommandText = "Select * from [Sheet1$]"
            Dim Reader = Await Cmd.ExecuteReaderAsync()
            While Reader.Read()
                If CheckEmptyReader(Reader) Then
                    MsgBox("First Empty Cell Index = " & Reader.Depth)
                    Exit While
                End If
                Dim x As New BuyableObject
                If Not Reader.IsDBNull(0) Then
                    x.Name = Reader.GetString(0)
                End If
                If Not Reader.IsDBNull(1) Then
                    x.SoldCount = GetIntegerValue(Reader(1).ToString)
                End If
                If Not Reader.IsDBNull(2) Then
                    x.SellingPrice = GetSingleValue(Reader(2).ToString)
                End If
                If Not Reader.IsDBNull(3) Then
                    x.OriginalPrice = GetSingleValue(Reader(3).ToString)
                End If
                x.UpdateCounts()
                If x.Name IsNot Nothing Then
                    Sellings.Add(x)
                End If
            End While
            Reader.Close()
            Conn.Close()
            Return Sellings
        Catch ex As Exception
            MsgBox(ex.ToString)
            Return New SellingList
        End Try
    End Function

and i want to get the current row index at
MsgBox("First Empty Cell Index = " & Reader.Depth)

but it doesn't work and always returns 0
and to check empty reader :
Public Function CheckEmptyReader(reader As DbDataReader) As Boolean
        If IsDBNull(reader(0)) AndAlso IsDBNull(reader(1)) AndAlso IsDBNull(reader(2)) AndAlso IsDBNull(reader(3)) Then
            Return True
        Else
            Return False
        End If
    End Function

so how do i get the current row index with the reader ?
Answer: i found a simple solution by adding a simple counter
Dim counter As Integer = 1 'start index
While Reader.Read()
   If CheckEmptyReader(Reader) Then
      MsgBox("First Empty Row Index = " & counter)
      Exit While
   End If
   'some code
   counter += 1
End While


Evitar duplo clique e redirecionar para outra página

Question: Boa tarde!
Eu fiz uma função para impedir que o utilizador carregue duas vezes no mesmo botão, esta parte funciona perfeitamente.
global.js
$('.form-disable').on('submit', function(){

var self = $(this),
button = self.find('input[type="submit"], button'),
submitValue = button.data('submit-value');

button.attr('disabled','disabled').val((submitValue) ? submitValue : "Aguarde...");
});

O problema é que agora ele já não redirecciona para a próxima página. O botão serve para inserir dados na base de dados e para o utilizador ser redireccionado.

comentario.php

<form method="POST" action="" class="form-disable">

                        Deixe aqui o seu comentário

                    <textarea rows="13" cols="165" name="textarea" id="textarea" placeholder=""></textarea>

Limite de caracteres: 150

                        <input type="submit" id="enviar" name="enviar" class="enviar" value="✓">

                    <?php
                    if (isset($_POST['enviar'])) {
                    //procura na tabela questionario o id da pergunta 'pergunta_id'
                        $procura = mysqli_query($link,"SELECT pergunta_id from questionario");
                        $registos_pergunta_id=mysqli_num_rows($procura);

                    //pegar pergunta_id da tabela questionario
                        while ($registos_pergunta_id!=0) {
                            $get_pergunta_id=mysqli_fetch_array($procura);
                            $registos_pergunta_id--;
                        }

                        $resposta = $_POST['textarea'];
                    //inserir os dados na tabela resposta
                        $inserir=mysqli_query($link,"INSERT INTO resposta (resposta_id, pergunta_id, resposta) VALUES ('','".$get_pergunta_id[0]."','$resposta')");
                        if (!$inserir) {
                        //caso os dados nao sejam inseridos na base de dados irá msotrar um erro a informar
                            echo "Erro ao inserir na base de dados";
                        }else
                        {
                        //se os dados forem inseridos na base de dados irá para a página agradecimento
                            header('location: agradecimento.php?id=1');
                        }
                    }
                    ?>

                            <input type="submit" name="desistir" class="desistir" value="X">
                            <?php
                            if (isset($_POST['desistir']))
                            {
                            //apagar o ultimo id inserido da tabela caso o utilizador desista da sua opçao
                                $apagar = mysqli_query($link,"delete from questionario order by pergunta_id desc limit 1");
                                if (!$apagar) {
                                    echo "Erro ao apagar o último registo inserido";
                                }else{
                                //redireciona novamente para a página principal
                                    header('location: index.php?id=1');
                                    exit();
                                }
                            }
                            ?>

    </form>

Será que alguém pode me ajudar?
Obrigada!
Answer: O seu return false impede que o formulário seja enviado, sendo assim, basta removê-lo:
$('.form-disable').on('submit', function(){
 var self = $(this),
 button = self.find('input[type="submit"], button'),
 submitValue = button.data('submit-value');
 button.attr('disabled','disabled').val((submitValue) ? submitValue : "Aguarde...");
});

Não está sendo redirecionada porque os headers já foram enviados e você chama novamente a função header() para fazer o redirecionamento.
Você pode resolver redirecionando de outra forma. Com javascript, por exemplo:
no lugar de:
header('location: index.php?id=1');

Coloque:
echo "


Get exception object in custom error controller

Question: I am using spring boot and write a global exception handler use AbstractErrorController. How could i get an exception object in controller?
@Controller
public class MyCustomErrorController extends AbstractErrorController {

    public MyCustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping("/error")
    public void handleError(HttpServletRequest req, HttpServletResponse resp) {
        Exception e = ...; // how to get exception here
        log.error(e);
        displayError(req, resp, e);
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

Comment: I don't understand the logic here. Do you want to retrieve an error from an endpoint? Usually error handlers catch an exception and return an error for any controller that thrown that exception.
Answer: You can get the exception from the HttpServletRequest as follows:
    @Controller
    public class MyCustomErrorController extends AbstractErrorController {

        @RequestMapping("/error")
        public void handleError(HttpServletRequest request) {
            Exception e = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
            ...
        }
    }

Comment: If this ErrorController pick up other error like resource not found from your database, or invalid endpoint /dsaklfja, the exception casted here is null
Answer: this is how it works in Spring Boot 3.1.0.
But should work in previous versions as well:
import org.springframework.web.servlet.DispatcherServlet;

   @Controller
    public class MyCustomErrorController extends AbstractErrorController {

        @RequestMapping("/error")
        public void handleError(HttpServletRequest request) {
                   Exception e = (Exception) request.getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE);

            ...
        }
    }

Answer: An handler intercepts an Exception generated or re-thrown by a controller. It doesn't have an endpoint because it usually does it for all the controllers in your application. The Handler instructs the application server to return a specific error when a specific Exception is thrown.
Here is an example:
@ControllerAdvice // Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes.
public class ResourceNotFoundExceptionHandler {

@ExceptionHandler(value = { ResourceNotFoundException.class })
public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
    ApiError error = new ApiError(HttpStatus.NOT_FOUND,  ex.getLocalizedMessage(), ex);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

    ResponseEntity<Object> response = new ResponseEntity<>(error, headers, HttpStatus.NOT_FOUND);

    return response;
}
}

In this example ApiError is a data structure that reports the error to the UI. What this code does is intercepting the Exception "ResourceNotFoundException", create an appropriate error Data transfer object, set the response HttpStatus and headers and return the error.
you can find a different example here:  https://github.com/otrebor/springbootseed-openshift/blob/master/src/main/java/com/company/example/springbootseed/core/errorhandling/handlers/
Comment: But ControllerAdvice dosen't catch exception from filter.
Comment: did you have a look to https://github.com/otrebor/springbootseed-openshift/blob/master/src/main/java/com/company/example/springbootseed/core/errorhandling/handlers/RequestValidationErrorHandler.java ?
Comment: or https://stackoverflow.com/questions/34595605/how-to-manage-exceptions-thrown-in-filters-in-spring
Comment: You can get the endpoint point of which ever url failed by :
        String url = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
Answer: Add Exception as an extra parameter to handleError()
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to display results of Smartsearch

Question: I'm creating a webpart that uses the SearchHelper to get smart search results based on the search paramaters to display in a live search via Ajax.
I am looking for a way to display the results using the dataset that
SearchHelper.Search(SearchParameters)

returns in the same manner that the SearchResults webparts work.
Answer: Ok never mind, found the answer. The answer is to just use the BasicRepeater.
var results = SearchHelper.Search(sp);
BasicRepeater br = new BasicRepeater();
br.DataSource = results;
br.ItemTemplate = CMSDataProperties.LoadTransformation(this, CMS.Root.SmartSearchResults", false);

How to display results of Smartsearch


Limit question as x approaches -infinity (Absolute value in limit)

Question: I'm given this limit question which I don't know how to do.
$$\lim_{x\rightarrow -\infty }(\frac{2x+\left | x \right |}{4x-3\left | x \right |}) $$. Can someone give me some hints? Thanks a lot.
Comment: Hint: What is $|x|$ for $x < 0$ ?
Comment: assume $x < 0$.
Answer: Hint:
Your limit is simply
$$\lim_{x\to-\infty}\frac{2x-x}{4x+3x}$$
Comment: How to simplify?
Comment: @Mathxx By definition, $$|x|=\begin{cases}\;\;\;x&,\;\;x\ge 0\\{}\\-x&,\;\;x<0\end{cases}$$


How to read active ip connection command

Question: Can you tell me what the 937 is?  Forgive me I'm new to Linux and I don't know where to start looking.
When I run:
<code>$ netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n

  1 184.108.40.206
  1 220.127.116.11
  1 126.96.36.199
  1 220.127.116.11
  1 22.214.171.124
  1 Address
  1 servers)
  2 127.0.0.1
  2 126.96.36.199
  2 220.127.116.11
  3 188.8.131.52
  3 220.127.116.11
  6 184.108.40.206
937
</code>
Comment: Run the command with each of the piped commands removed e.g "netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c " then "netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort" etc. and that should throw some light on it
Answer: There are IPv6 addresses (field 5) of the form ::1:33766 so with a delimiter of ":" the first field is "". There are 937 lines that have an IPv6 address.
Edit: See Wikipedia page describing shortening of IPv6 addresses for more information.


CSS Cache Busting Via the Style Sheet

Question: Many of us already know the traditional method of cache busting:
<link rel="stylesheet" href="/css/example.css?v2" type="text/css">

Is it possible to do a cache bust via the Style Sheet itself? Perhaps something along the lines of template?v2.css. A method that does not rely on the reference for the cache bust, but rather the file itself. I have a style sheet I regularly update on a external website that is used for over 90 pages. I wouldn't want to have to edit all 90 pages when major edits are made (via the reference).
Answer: You can try to use some .htaccess magic:
source
RewriteEngine On
RewriteBase /
RewriteRule ^css/example-([0-9]+).css$ /css/example.css [L]

This will redirect example-002.css request to the real file  example.css.
After that you will have to rename the style definition in your htmls:
<link href="http://z.askapache.com/css/example-002.css" rel="stylesheet" type="text/css" />

It may look as a lot of work to edit 90 files ... but if your names are consistent,
you can just use Search&Replace ALL with some IDE and update all references of the css to the next version:
find: example-002.css
replace with: example-003.css

Also if you make 90 references to the same css in different pages of your site ...
may be there is a way to optimize it and set a base template with the default settings, that is inherited ?
If you use PHP, something like this may work for you :
<link href="http://z.askapache.com/css/example-<?php echo $css_version?>.css" rel="stylesheet" type="text/css" />

And define $css_version somewhere in your index.php or settings.
So you will have to update all the htmls once, and after that only update this property.

CSS Cache Busting Via the Style Sheet


A condição do except está sendo lida mesmo com o try dando certo

Question: def registerUser(self):
        self.userRegister = self.usernameRegisterEntry.get()
        self.emailRegister = self.emailRegisterEntry.get()
        self.passRegister = self.passwordRegisterEntry.get()
        self.cPassRegister = self.cPasswordRegisterEntry.get()

        self.connDB()

        self.cursor.execute(
            """
            INSERT INTO Users(
                Username,
                Email,
                Password,
                ConfirmPassword
            )
            VALUES (?, ?, ?, ?)
        """,
            (
                self.userRegister,
                self.emailRegister,
                self.passRegister,
                self.cPassRegister,
            ),
        )

        try:
            if (
                self.userRegister == ""
                or self.emailRegister == ""
                or self.passRegister == ""
                or self.cPassRegister == ""
            ):
                msgb.showerror(
                    title="Sistema de Login",
                    message="Os dados não podem estar vazios\nPreencha todos os campos corretamente",
                )
            elif len(self.userRegister) < 4:
                msgb.showwarning(
                    title="Sistema de Login",
                    message="O nome de usuário deve ter no mínimo 4 caracteres",
                )
            elif len(self.passRegister) < 8:
                msgb.showwarning(
                    title="Sistema de Login",
                    message="A senha precisa conter no mínimo 8 caracteres",
                )
            elif self.passRegister != self.cPassRegister:
                msgb.showwarning(
                    title="Sistema de Login",
                    message="A senhas não conferem",
                )
            else:
                self.conn.commit()
                msgb.showinfo(
                    title="Sistema de Login",
                    message=f"Parabéns!\n O usuário {self.userRegister} foi registrado com sucesso",
                )
                self.desconnDB()
                self.cleanElementsRegister()
        except:
            msgb.showerror(
                title="Sistema de Login",
                message="Erro no processamento do seu pedido\nPor favor tente novamente",
            )
            self.desconnDB()

Comment: Sua pergunta parece ter alguns problemas e sua experiência aqui no Stack Overflow em Português poderá não ser a melhor por causa disso. Queremos que você se dê bem aqui e consiga o que quer, mas para isso precisamos que você faça a sua parte. Veja algumas orientações que vão te ajudar: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045) ([versão curta](https://pt.meta.stackoverflow.com/q/8089/101)).
Answer: Primeiramente, é uma boa prática (FailFast) colocar a validação antes de fazer a inserção no banco de dados; Porquê se já estiver com erro, você valida primeiro antes de sequer tentar inserir e já retorna ali, sem precisar abrir conexão com o banco;
Então colocar a exceção e fazer a exibição dela para ter mais detalhes.
Pode ser que esteja ocorrendo o erro justamente ali nos processos finais da execução, por isso não aparenta;
except Exception as e:
msgb.showerror(
                title="Sistema de Login",
                message= str(e) + "\nErro no processamento do seu pedido\nPor favor tente novamente",
            )

Comment: Exibindo a exceção com detalhes eu consegui identificar onde o erro estava acontecendo e fazendo a correção o código voltou a funcionar normalmente.


2 computers on the same subnet of an ISP can't talk

Question: I have networks connected to the same ISP. Both routers are configured with a static IP like:
Router 1:
Static IP address: 184.108.40.206
Subnet Mask: 255.255.255.0
Gateway: 126.96.36.199

Router 2:
Static IP address: 220.127.116.11
Subnet Mask: 255.255.255.0
Gateway: 22.214.171.124

So both routers are on the same subnet as each other and I think that's the problem. When I try to ping one from the other, I get a "Destination Host Unreachable" message. However, I can ping both from an outside ISP which has a different subnet.
Router 1 "ip route" contains:
22.214.171.124/24 dev eth8 proto kernel scope link src 22.214.171.124

Router 2 "ip route" contains:
default via 188.8.131.52 dev eth2  proto zebra
22.214.171.124/24 dev eth2  proto kernel  scope link  src 220.127.116.11

How do I make it so the 2 routers can talk to each other? Static route?
Comment: You're likely hitting some sort of a `port security` configuration on an ISP side - that is client ports can only talk to uplink and not to each other. You should investigate this with `arp -an` and simultaneous `tcpdump` sessions on both routers to see what's going on with ARP resolution. If ARP's are not heard by the other side you should create a ticket with your ISP..
Answer: After further investigation, I found that I could not see any ARP packets on the interface. I talked to my ISP and they added an ARP Proxy on their side which fixed the problem.


Editar formatação de parâmetros passados pela URL CakePHP 3

Question: Tenho um formulário de campo único, um input type="text", quando o formulário é submetido a URL fica da seguinte forma:

http://localhost:8765/products/search?search=notebook

gostaria que ela fica-se da seguinte forma quando submete-se o formulário:

http://localhost:8765/products/search/notebook

Digitando a URL acima manualmente funciona perfeitamente (criei um método que é capaz de pegar o conteúdo após search/ desde que esteja no formato acima, também criei uma rota especifica para ter a URL acima)
Código da rota criada (routes.php):
$routes->connect('/products/search/:search', ['controller' => 'Products', 'action' => 'search'],
        [':search' => '\w+', 'pass' => ['search']]);

Código do ProductsController.php (método responsável pela action search)
public function search($search)
    {
        if($this->request->is('get'))
        {
            //$product = $this->request->params['pass'];
            $this->paginate = [
                'fields' => ['product_name', 'quantity', 'sold', 'description', 'price', 'old_price', 'thumbnail'],
                'conditions' => ['product_name LIKE' => '%'.$search.'%'],
                'order' => ['price' => 'DESC'],
                'limit' => 3
            ];

            $this->set('products', $this->paginate($this->Products));
        }
    }

Código do form:
<?= $this->Form->create(null, ['url' => ['controller' => 'Products', 'action' => 'search'], 'type' => 'get', 'id' => 'search-form', 'class' => 'navbar-form span7 text-center']) ?>
            <button class="btn btn-info" title="Favorite o Site">

            </button>
            <?= $this->Form->text('search', ['class' => 'form-control', 'placeholder' => 'Search']) ?>
            <?= $this->Form->button('Buscar ', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
        <?= $this->Form->end() ?>

OBS1: Imagino que a modificação deva ser feita neste form (É só uma suposição).
OBS2: Estou usando o CakePHP 3
Comment: O formato `[...]search?search=notebook` é o padrão do método. Para uar `[...]search/notebook` creio que somente manipulando a URL na hora do submit com JS.
Answer: Usei a lib jQuery para assim que o form for submetido ela suprimir seu comportamento padrão, criar a nova url e fazer a redireção:
$("#search-form").submit(function(event){
    event.preventDefault(); // suprimir o comportamento padrão
    action = $(this).attr('action') + '/' + document.getElementById('search').value; // criar a nova url no formato desejado
    window.location.href = action; //faz a redireção:
});


Let $E$ be a topological vector space and $f:E \to \mathbb R$ linear. Then $f$ is continuous if and only if $f$ is continuous at $0$.

Question: I'm trying to prove that

Let $E$ be a topological vector space and $f:E \to \mathbb R$ linear. Then $f$ is continuous if and only if $f$ is continuous at $0$.

Could you verify if my below proof is fine?
My attempt: The direction $\implies$ is clear. Let's prove the reverse. Let $(x_d)_{d \in D}$ be a net in $E$ such that $x_d \to a \in E$. Let $x'_d := x_d -a$. Let $U$ be an open neighborhood of $0 \in E$.
Consider a map $T: E \to E, x \mapsto x-a$. Then $T$ is continuous by definition of a t.v.s., so $T^{-1} (U) =U+a$ is an open neighborhood of $a$. By net convergence, there is $n_U \in \mathbb N$ such that $x_d \in U+a$ and thus $x'_d \in U$ for all $d \ge n_U$. This means $x'_d \to 0$.
By continuity of $f$ at $0$, we get $f(x'_d) = f(x_d) - f(a) \to f(0) = 0 \in \mathbb R$. Just as previously, we get $f(x_d) \to f(a)$. This completes the proof.
Comment: Your proof looks correct.
Answer: The proof is fine. If you're using nets anyway (which I would do too BTW), note that $t_a(x)=x-a$ is continuous for any $a$ (axioms of a TVS) so
$$(x_d-a)_d = t_a(x_d) \to t_a(a)=a-a=0$$ by continuity of $t_a$.
So continuity at $0$ of $f$ (plus linearity of $f$) tells us that
$$f(x_d)-f(a) = f(x_d -a) \to f(0)=0$$ and so by continuity of $u(x)=x+f(a)$ (where $u$ is defined and continuous on $\Bbb R$)
we get
$$f(x_d)= u((f(x_d) - f(a)) \to u(0)=f(a)$$ as required.
So it's basically a consequence of translations (in $\Bbb R$ and $E$) being continuous. "Anything at any point happens at all points" (homogeneity).


Using window.location.origin in angular library configuration using AOT

Question: When I pass window.location.origin in the forRoot({...}) configuration object argument of my angular library and compile using AOT, it's value is just null. Is there a way to pass it's value to my angular library with AOT enabled?
After some googling I'm thinking perhaps an injection token needs to be set with WINDOW and then consumed on the library side but I'd like to avoid this if possible. I can also just hard code the origin but that is quite limiting. Would like a sort of set it and forget it approach hence why I carved out a feature into a library.
My Library is set up as follows.
export class AppConfig {
  origin: string;
}

...

export const APP_CONFIG_TOKEN = new InjectionToken<AppConfig>('APP_CONFIG_TOKEN');

...

@NgModule()
export class MyLibrary {
  public static forRoot(config: AppConfig) {
    return {
      ngModule: MyLibrary,
      providers: [
        {
          provide: APP_CONFIG_TOKEN,
          useValue: config
        }
      ]
    };
  }

I'm consuming the value of the token in a service within the library
@Injectable()
export class MyService {
  constructor(@Inject(APP_CONFIG_TOKEN) private config: AppConfig) { }

  myOrigin(): string {
    return this.config.origin; // expecting it to return a value like `http://localhost:4200` but it returns `null`
  }
}

and I'm importing the library in my AppModule like so
@NgModule({
  imports: [
    MyLibrary.forRoot({
      origin: window.location.origin // with AOT, this seems to be null
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Comment: I think it's all about passing a primitive. If you have passed a reference to an object you would get an actual value in it when the code is executed. So try replacing `window.location.origin` with `window.location`
Comment: Also, why would you want to pass a globally accessible data to you library whist you could access it right in your library's code?
Comment: @Sergey Well the library needs a URL value which for my purpose is the origin, this can be hard coded (for testing let's say) or the location origin. Just wanted to provide flexibility basically.
Answer: AOT builds parts of the app so that the client has to do less computing.
Try looking at this issue
https://github.com/angular/angular-cli/issues/10957


Algebraic number field quotiented by a prime ideal

Question: Let $K$ be a number field, $\mathcal{O}_K$ its ring of integers, $\mathfrak{p} \subset \mathcal{O}_K$ a prime ideal, and $p \in \mathbb{N}$ the rational prime lying below $\mathfrak{p}$.
I find myself unable to either prove or disprove the following:

(i) Is it true that $\mathcal{O}_K/\mathfrak{p}$ is a finite field of characteristic $p$?
(ii) Is it true that $\mathcal{O}_K/\mathfrak{p} \cong \mathbb{F}_{p^n}$, where $n:= [K:\mathbb{Q}]$?

These questions have come up in my attempt to prove the existence of the Frobenius element in the Galois group of an extension of algebraic number fields.
I am aware of the existence of this post, but it is not what I am looking for. In particular, it only considers quadratic number fields.
Thank you for your attention.
Answer: Given a non-zero prime ideal $\mathfrak{p}$ of $O_K$

The first step is to prove that $\mathfrak{p}$ contains an integer, namely the constant coefficient of the minimal polynomial of any of its elements.
Since $\mathfrak{p}$ contains an integer then $O_K/\mathfrak{p}$ has finite characteristic, since it is an integral domain it has characteristic $p$ prime.
Since $K$ is a $n$ dimensional $\Bbb{Q}$- vector space and $O_K$ is a subgroup then $O_K/pO_K$ has at most $p^n$ elements, ie. $O_K/\mathfrak{p}$ is a finite group thus a finite integral domain thus a finite field. Being also a $\Bbb{F}_p$ vector space it has $p^k$ elements.
Up to isomorphism there is only one finite field with $p^k$ elements (the splitting field of $x^{p^k}-x\in \Bbb{F}_p[x]$) thus $O_K/\mathfrak{p}\cong \Bbb{F}_{p^k}$.
Comment: Many thanks. What is the $k$ introduced in your third bullet?
Comment: The dimension of $O_K/\mathfrak{p}$ as a $\Bbb{F}_p$-vector space. If can be any integer between $1$ and $n$ (because $O_K/(p)$ has $p^n$ elements). If $K/\Bbb{Q}$ is Galois then $k$ divides $n$. In general $k$ divides $[L:\Bbb{Q}]$ where $L$ is the Galois closure of $K/\Bbb{Q}$. Usually $k$ is denoted $f(\mathfrak{p}/p)$.


Sum of infinite powers

Question: I know that the sum $1+x+x^2+...+x^n$ is  $\frac{x^{n+1}-1}{x-1}$ but when $n \to \infty$ the sum is $1/(1-x)$ when $ - 1 < x <1$. I can derive the former but not the latter.
How is this the case? How do you prove this? If I use the formula above, replacing $n $ with infinity seems to make the whole thing infinity.
Comment: Think about how $x^n$ behaves for large $n$ when $-1<x<1$.
Answer: $$\sum_{i=1}^{\infty}{a_0r^{n-1}} \equiv S$$
$$S = a_0r^0+a_0r^1+a_0r^2+\cdots$$
$$S = r\left(a_0r^{-1} + a_0r^{0} + a_0r^1+\cdots\right)$$
$$S = r\left(a_0r^{-1} + S\right)$$
$$S = a_0 + rS$$
$$(1-r)S = a_0$$
$$S = \frac{a_0}{(1-r)}$$
In this case, $a_0=1$ and $r=x$.
Also, if you want to see it from the general formula $$S=\frac{(1−r^n)}{1−r}$$
$$S=\frac{1}{1-r}-\frac{r^n}{1-r}$$
For $n → ∞$, the quantity $\frac{r^n}{1-r}→ 0$ for $-1.0 < (r ≠ 0) < +1.0$.
Comment: I'm starting the sum from i=0 though, not 1 (does that matter? )
Comment: I don't think $i=0$ would make sense. You started from $i=1$ only. Sorry, it is supposed to be $i$ in place of $n$ if that is what confusing you.
Answer: So as you are aware the sum to infinity requires $|x|<1$
This then means that $\lim_{n \to \infty} x^{n+1} = 0$
In turn this means that
$$
\lim_{n \to \infty} \frac{x^{n+1}-1}{x-1}=\frac{-1}{x-1}=\frac{1}{1-x}
$$
Comment: What do we say the limit is if $x>=1$? Doesn't exist?
Answer: To show that
$x^n \to 0$
as $n \to \infty$
when
$0 < x < 1$:
Since
$0 < x < 1$,
$x = \frac1{1+a}
$,
where
$a
=\frac1{x}-1
> 0
$.
By Bernoulli's inequality,
$(1+a)^n
\ge 1+na
> na
$.
Therefore
$x^n
=\frac1{(1+a)^n}
< \frac1{na}
= \frac1{n(1/x-1)}
\to 0
$
as
$n \to \infty$.
Note:
Nothing here is original.

Sum of infinite powers


JTable: remove gridline on the rightmost column

Question: I have a Jtable that looks like this now, and I'm trying to remove the grid line on the rightmost column. Is there any way to do this? Also the columns are swappable.
Answer: Here's my attempt:

Sets the JTable does not draw vertical lines between cells and, other than the first cell, set the Border to draw the left vertical line.

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

public class TableGridLineTest {
  public JComponent makeUI() {
    JTable table = new JTable(5, 3);
    table.setAutoCreateRowSorter(true);
    table.setFillsViewportHeight(true);
    table.setShowVerticalLines(false);
    //table.setShowHorizontalLines(false);
    table.setIntercellSpacing(new Dimension(0, 1));
    table.setBorder(BorderFactory.createEmptyBorder());
    table.getTableHeader().setBorder(BorderFactory.createEmptyBorder());

    table.getTableHeader().setDefaultRenderer(new DefaultTableCellRenderer() {
      private final CellBorder border = new CellBorder(2, 2, 2, 2);
      @Override public Component getTableCellRendererComponent(
          JTable table, Object value, boolean isSelected, boolean hasFocus,
          int row, int column) {
        JLabel c = (JLabel) super.getTableCellRendererComponent(
            table, value, isSelected, hasFocus, row, column);
        border.isStartCell = column == 0;
        c.setBorder(border);
        c.setBackground(Color.ORANGE);
        return c;
      }
    });

    table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
      private final CellBorder border = new CellBorder(2, 2, 2, 2);
      @Override public Component getTableCellRendererComponent(
          JTable table, Object value, boolean isSelected, boolean hasFocus,
          int row, int column) {
        JComponent c = (JComponent) super.getTableCellRendererComponent(
            table, value, isSelected, hasFocus, row, column);
        border.isStartCell = column == 0;
        c.setBorder(border);
        return c;
      }
    });

    JScrollPane scroll = new JScrollPane(table);
    scroll.setBorder(BorderFactory.createLineBorder(Color.ORANGE));

    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 20));
    p.add(scroll);
    return p;
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new TableGridLineTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

class CellBorder extends EmptyBorder {
  private final Color gridColor = UIManager.getColor("Table.gridColor");
  public boolean isStartCell = false;
  protected CellBorder(int top, int left, int bottom, int right) {
    super(top, left, bottom, right);
  }
  @Override public boolean isBorderOpaque() {
    return true;
  }
  @Override public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.translate(x, y);
    g2.setPaint(gridColor);
    if (!isStartCell) {
      g2.drawLine(0, 0, 0, h - 1); // Left line
    }
    g2.dispose();
  }
}

Comment: I love your solution, thank you! I was thinking I might have to make my own BasicTableUI.paintGrid() and then do something about the table header, but your solution works perfectly :)


What are the advantages of Random Forest over Decision Trees

Question: I am currently searching for the advantages of random forest over decision trees, but unfortunately I didn't find a research paper that does such a conclusion that summarize all the advantages of RF over DT. Does anyone know any trusted resource that I can use to find a complete answer?
Thanks in advance
Answer: Detailed explanations of the random forest procedure and its statistical properties can be found in Leo Breiman, "Random Forests," Machine Learning volume 45 issue 1 (2001) as well as the relevant chapter of Hastie et al., Elements of Statistical Learning.
OP's username is "CS Student," which suggests that OP has access to a university library. Librarians are extremely helpful people! Their job is to organize and retrieve knowledge! A librarian probably won't do your searching for you, but they might be able to help you learn how the library's collection is organized and how to use different research tools.
Answer: Another excellent resource is the book by Max Kuhn and Kjell Johnson, Applied Predictive Modeling. The book focuses more on the practice of modeling and less on theory, so it might be a good complement to the two citations from above. A nice feature of the book is that it provides a summary of various models (including tree-based approaches) and some of their characteristics with respect pre-processing, interpretability, tuning parameters, computation time etc.
Answer: Briefly, although decision trees have a low bias / are non-parametric, they suffer from a high variance which makes them less useful for most practical applications.
By aggregating multiple decision trees, one can reduce the variance of the model output significantly, thus improving performance. While this could be archived by simple tree bagging, the fact that each tree is build on a bootstrap sample of the same data gives a lower bound on the variance reduction, due to correlation between the individual trees.
Random Forest addresses this problem by sub-sampling features, thus de-correlating the trees to a certain extend and therefore allowing for a greater variance reduction / increase in performance.

Details on this can be found in chapter 15 of The Elements of Statistical Learning as well as chapter 8 of An Introduction to Statistical Learning by Hastie and Tibshirani.
Comment: @CSStudent Having a low bias / being non-parametric is not a disadvantage at all, however non-parametric models tend to have a high variance and often over-fit easily.
Bagging (of which Random Forests are a special case in context of decision trees) trys to reduce the variance, thus making models more robust.
In theory, every model can be bagged, it just happens to work particularly well for trees because they have an exceptionally high variance.
Comment: @CSStudent no problem, thanks for your kind words.
Comment: Thank you for this extremely informative and summarizing of the key advantages. I believe it will help me while I am searching. I have one question about "non-parametric" point, how this is a disadvantage in DT?
Comment: Please if you have a resource support your answer provide it at the end of your answer so I can choose it as the best answer for the question. Thank you very much.
Comment: I couldn't describe how much you made this post a good source of information. Thank you very much for your efforts, I wish that I can evaluate this answer. Thank you once again.


React - Managing UI State

Question: I'm creating an UI component, which should be able to maintain its own UI state, but receives data from a parent component via props. This is a common scenario, so what would be considered a best practice?
Example: A directory tree component. The component receives its structure and text content from parent component via props. However, the tree component should manage the visibility status of the nodes by itself (closed/expanded). Should I copy props to state when they are received/updated, and add visibility data there? I'm under impression that initializing state from props is a bad practice.
Comment: well, [Redux](https://redux.js.org/basics/usagewithreact) is basically what you are looking for but still, you would need to handle the events.
Answer: Maybe something like this?
https://gist.github.com/acro5piano/4945264cfb0a83b681822332ef351ece
You do not need to copy props to local state in such case :)
If you have to modify or convert your prop data, try computed property instead:
<code>get someValueFromProps() {
  return this.props.value.replace('foo', 'bar')
}
</code>
The less local state, the better component, as state creates bugs unless programmers pay attention to them.
Comment: Oh, it seems like my problem was that I didn't have a separate component for a node. It's much clearer when each node controls its visibility, instead of trying to control the visibility of all nodes in the tree component. Thanks for pointing that out! :)

React - Managing UI State


XOR between string and int in Python

Question: How to do a XOR operation between a string with an integer in Python?
Below is what I type:
x = 'a'
y = x^5
print(y)

It show me this error: TypeError: unsupported operand type(s) for ^: 'str' and 'int'
Any idea how to solve it?
Comment: What is your expected outcome? Are you really wondering how to xor the hexadecimal number `0xa` with `5`?
Comment: I'm not sure to understand why you'd want to do that...?
Comment: What do you expect e.g. `"fart" ^ 5` to do?
Answer: Convert the string (char) to ord:
y = ord('a')^5

Comment: The `ord()` method returns an integer representing the Unicode code point of the given Unicode character. For example `'5'` [is](https://ascii.cl/) 53. It will convert your char to integer value.
Answer: ord gives you the unicode value of a character. A character's binary representation is the binary of its ASCII/Unicode value.
x = 'a'
y = ord(x) ^ 5

print(y)
>>> 100

Using bin() to check the binary representation of 100, we see 100 is 0b1100100.
Of course this only works on single characters and not strings.

XOR between string and int in Python


Regression: Transforming Variables

Question: When transforming variables, do you have to use all of the same transformation? For example, can I pick and choose differently transformed variables, as in:
Let, $x_1,x_2,x_3$ be age, length of employment, length of residence, and income.
Y = B1*sqrt(x1) + B2*-1/(x2) + B3*log(x3)

Or, must you be consistent with your transforms and use all of the same? As in:
Y = B1*log(x1) + B2*log(x2) + B3*log(x3)

My understanding is that the goal of transformation is to address the problem of normality. Looking at histograms of each variable we can see that they present very different distributions, which would lead me to believe that the transformations required are different on a variable by variable basis.
## R Code
df <- read.spss(file="http://www.bertelsen.ca/R/logistic-regression.sav",
                use.value.labels=T, to.data.frame=T)
hist(df[1:7])

Lastly, how valid is it to transform variables using $\log(x_n + 1)$ where $x_n$ has $0$ values? Does this transform need to be consistent across all variables or is it used adhoc even for those variables which do not include $0$'s?
## R Code
plot(df[1:7])

Comment: [This quant SE answer](https://stats.stackexchange.com/a/525103/322254) may also be helpful.
Answer: One transforms the dependent variable to achieve approximate symmetry and homoscedasticity of the residuals.  Transformations of the independent variables have a different purpose: after all, in this regression all the independent values are taken as fixed, not random, so "normality" is inapplicable.  The main objective in these transformations is to achieve linear relationships with the dependent variable (or, really, with its logit).  (This objective over-rides auxiliary ones such as reducing excess leverage or achieving a simple interpretation of the coefficients.)  These relationships are a property of the data and the phenomena that produced them, so you need the flexibility to choose appropriate re-expressions of each of the variables separately from the others.  Specifically, not only is it not a problem to use a log, a root, and a reciprocal, it's rather common.  The principle is that there is (usually) nothing special about how the data are originally expressed, so you should let the data suggest re-expressions that lead to effective, accurate, useful, and (if possible) theoretically justified models.
The histograms--which reflect the univariate distributions--often hint at an initial transformation, but are not dispositive.  Accompany them with scatterplot matrices so you can examine the relationships among all the variables.

Transformations like $\log(x + c)$ where $c$ is a positive constant "start value" can work--and can be indicated even when no value of $x$ is zero--but sometimes they destroy linear relationships.  When this occurs, a good solution is to create two variables.  One of them equals $\log(x)$ when $x$ is nonzero and otherwise is anything; it's convenient to let it default to zero.  The other, let's call it $z_x$, is an indicator of whether $x$ is zero: it equals 1 when $x = 0$ and is 0 otherwise.  These terms contribute a sum
$$\beta \log(x) + \beta_0 z_x$$
to the estimate.  When $x \gt 0$, $z_x = 0$ so the second term drops out leaving just $\beta \log(x)$.  When $x = 0$, "$\log(x)$" has been set to zero while $z_x = 1$, leaving just the value $\beta_0$.  Thus, $\beta_0$ estimates the effect when $x = 0$ and otherwise $\beta$ is the coefficient of $\log(x)$.
Comment: @Chris All Box-Cox transformations transition from negative to positive at $1$, too. That's irrelevant for a nonlinear transformation, though, because it can be followed up by any linear transformation without changing its effects on variance or linearity of a relationship with another variable. Thus, if your client is allergic to negative numbers, just add a suitable constant *after* the transformation. Adding the constant *before* the transformation, though, can have a profound effect--and that's why no recommendation always to use $1$ could possibly be right.
Comment: @landroni If the data show that (say) a log transform produces a linear relationship between two variables, then that is useful and insightful information.  If you were not familiar with the logarithm, you would find that transformation is difficult to interpret, too.  But that's a subjective issue--it says nothing about the data.  Interpretability is a matter of *familiarity*. That means understanding the mathematical nature of the transformation. It eventually comes with study and experience.
Comment: Very helpful description, thanks for the direction and the detail on my subquestion as well.
Comment: In one of my datasets that I am working on, I noticed if I shifted the dependent response variable to anchor at 1 and used a box cox transformation to eliminate the skew, the resulting transformation was weakened leading credence to your critique. ;)
Comment: @whuber My previous question was very silly (will probably delete comment). Of course $\beta_0$ pertains to the $z_x$ dummy indicator, and NOT to the constant in the model. Thank you again for the extensive and clear explanations of this setup; very helpful for my work. Overall I prefer this parametrization as opposed to [this other, equivalent approach](http://stats.stackexchange.com/a/6565/36515).
Comment: http://pareonline.net/getvn.asp?v=15&n=12
  Osborne (2002) recommends anchoring the minimum value in a distribution at exactly 1.0. http://pareonline.net/getvn.asp?v=8&n=6
Comment: @Chris Thank you for the interesting references. I think the reasoning is invalid, though. There is no mathematical basis to the assertion that "similar to square root transformations,
numbers between 0 and 1 are treated differently than
those above 1.0. Thus a distribution to be transformed
via this method should be anchored at 1.00." The logarithm doesn't suddenly change its behavior at $1$! For an example of a more nuanced and statistically appropriate approach to this question, see my answer at http://stats.stackexchange.com/a/30749.
Comment: The authors are pointing out that  log(0.99) is negative while log(1.01) is positive... I will read your post. :)
Comment: @whuber *The main objective in these transformations is to achieve linear relationships with the dependent variable [...]. (This objective over-rides auxiliary ones such as [...] achieving a simple interpretation of the coefficients.)* This is also one of the central messages coming from CAR... While I am starting to understand the need for transforming data, I'm still a bit unclear on how to approach the interpretation of resulting coefficients. With `log` it's simple, as it allows transformation while maintaining relatively straightforward interpretations.
Comment: @whuber But, to take an example from my real data, what if your variable requires e.g. a Yeo-Johnson transformation with `lambda=-2` (cf `symbox()` and `yjPower()` in `car`) to achieve symmetry and near-normality? How do you approach interpretation of the associated coefficients then? Such transformations seem to limit comments srictly to the sign and significance of the estimated effect... (In CAR Fox and Weisberg advocate for the use of `effects` displays, especially when dealing with models containing transformations and interactions, but I haven't quite gotten the hang of them yet.)
Comment: Thanks so much for this clear answer! I am implementing this approach in an analysis I'm conducting, but I find I'm seeing very high multicollinearity as a result; the correlations between the zero-indicator variables and the variables indicating the (log transformed) value of that same variable above 0 are ranging .91 to .99 in my data. Should I just not attempt to interpret the resulting coefficients individually?
Comment: @Rose This tends to be a problem with binary variables that are highly skewed (so that one value predominates). The multicollinearity can create large standard errors of the coefficient estimates, making it unreliable to interpret the coefficients.  How to deal with that depends on the amount of data you have, the purpose of the regression, theories about the relationships, and much more.
Comment: @whuber -- how does your "two variables" method with an indicator relate to zero-inflated models? Seems very similar.
Comment: @abalter They share some features.  One difference is that zero-inflated models concern the *conditional response* whereas the models discussed here concern the *regressor variables.*  This is an important distinction, because the former is random while the latter is determinate.

Regression: Transforming Variables


what is the difference between angular.element and document.getElementById

Question: Angularjs get element by id : You can use the angular.element('#element_id'); to get the element by id where #element_id is id of element.
Here is an alternative of javascript document.getElementById in angularjs –
Angularjs get element by id:
var currentElement = angular.element('#element_id');

But what is the difference between angular.element and  document.getElementById
Comment: thanks, but what's the best I can use in angular App and why ?
Comment: did [my answer](http://stackoverflow.com/a/40429365/2545680) help?
Answer: When you select an object with an ID using angular.element (or jQuery), it takes a shortcut and uses document.getElementById.
The biggest difference is that angular.element is a jQuery alias, and returns a jQuery (or jQuery lite) object.
Whereas document.getElementById is a native DOM method, which returns an HTMLElement object.

tl:dr;
Always read the documentation
Comment: (anyone who wants to downvote, please leave a comment)
Comment: Thank you very much
Answer: I would add to the @evolutionxbox answer, that document.getElementById should probably be slightly faster than angular.element, since it doensn't have to go through the routine of figuring out what is passed into the function and what steps should be taken based on that.
Regarding what should be used when. Since these two methods return different object types (jquery vs HTMLElement), you can select the method based on either the standard practice in your application - whether to use jquery elements or native dom elements for manipulation, or on what operations you're going to perform on them as some operations are easier to do with jquery object than with native HTMLElement.
For example, if you want to use any jquery method, like .hasClass() you need to wrap element like this angular.element(document.getElementById('some')).hasClass(), so it's easier to just go with angular.element('#some').hasClass(); in the first place.
Generally, I would go with angular.element approach as it's preferred method inside angular's native directives.
Comment: Thank you Maximus but for angular.element is that it has advantages over document.getElementById ?
Comment: adding to what I've written, if you want to use any jquery method, like `.hasClass()` you need to wrap element like this `angular.element(document.getElementById('some')).hasClass()`, so it's easier to just go with `angular.element('#some').hasClass();`
Comment: @MohammedAkdim, you can also accept my answer if you feel it fully answers your question
Comment: you said document.getElementById should probably be slightly faster than angular.element but why AngularJS the community adding angular.element ??

And is it possible to use both(document.getElementById & angular.element) in a project AngularJS ?
Comment: because it's a `slightly faster speed vs greater convenience` choice, and angular team opted for the latter. And I would too. yes, it's certainly possible to use both in your app, but that would create incostistency
Comment: @MohammedAkdim, you're welcome, consider accepting the answer then


The acute angle between two plane

Question: There are 2 planes.
plane 1: $2x+3y-4z=15$
plane 2: $x+y-4z=17$
How can I find the acute angle between 2 planes with those 2 equations?
thanks ;)
Answer: Find the normal vectors to both planes, $\hat{n}_1$ and $\hat{n}_2$.
Next, find the angle between them by using the fact that $\vec{u} \cdot \vec{v} = |u| |v| \cos{\theta}$.
How is the angle between the normal vectors related to the angle between the planes? (This picture may help)
Answer: Angle between 2 planes is defined as the angle between their normals.
Comment: Well, not sure about *that* definition, @GTX OC. Over here, in high school 3-dimensional analytic geometry, it is defined in a very different, apparently, way: as two non-parallel planes $\;\pi_1,\pi_2\;$  *always* intersect in a straight line, call it $\;l\;$, the angle between $\;\pi_1,\pi_2\;$ is defined as follows: choose a point $\;O\;$ on $\;l\;$ and draw perpendiculars to $\;l\;$ at $\;O\;$ on $\;\pi_1,\pi_2\;$ . Now look at the plane determined by these perpendiculars and $\;O\;$. The angle between the perp's on this new plane is, by def., the angle between the planes.
Comment: What do you mean by "look at the place determined by these perpendiculars and O. "?
Comment: place =plane. it was edited before.

The acute angle between two plane


How to address the numerical instability of a function involving erf and an exponential

Question: We need to compute this function:
$f(x) = x + \sqrt {\frac 2 \pi} \cdot \sigma_x \cdot \frac {e^{- ( \frac {x} {\sqrt 2 \cdot \sigma_x} )^2}} {1 + erf(\frac {x} {\sqrt 2 \cdot \sigma_x})}$
We noticed that, for negative values of $\frac {x} {\sqrt 2 \cdot \sigma_x}$ lower than a certain value (and different depending on which software we use to compute it, say about $-5$ for instance), there is numerical instability (oscillations).
I saw this post suggesting how to achieve better stability, although on a rather different function:
Numerical Instability with this cumulate
Do you think a similar method would work here? And if so, should I express the $erf$ as an integral?
Or would you suggest some other method? Taylor expansion? Anything else...?
Thanks

EDIT after evaluation of the responses
Thank you all very much for your feedback!
I think there is a complication here that I had not explicitly foreseen.
First I will make the following substitution, so your alternative expressions of $erf$ can be used directly:
$x = y \cdot \sqrt 2 \cdot \sigma_x$
$f(y) = \sqrt 2 \cdot \sigma_x \cdot y + \sqrt {\frac 2 \pi} \cdot \sigma_x \cdot \frac {e^{- y^2}} {1 + erf(y)}$
Now, the theory we used to derive this equation requires that:
$f(y) > 0, \forall y$
$\lim_{y \to -\infty} f(y) = 0$
So, we expect $f(y)$ to be very slowly approaching $0$ as $y$ becomes more negative; but $f(y)$ should never be negative.
In fact, if I plot the second term of $f(y)$, it looks like, as $y$ becomes more and more negative:
$\sqrt {\frac 2 \pi} \cdot \sigma_x \cdot \frac {e^{- y^2}} {1 + erf(y)} \approx - \sqrt 2 \cdot \sigma_x \cdot y$
This is in substantial agreement with Claude's approximation for the $erf$ part.
I.e., using:
$\frac{e^{-y^2}}{1+\text{erf}(y)} \approx -\sqrt{\pi } \,y\Bigg[1+\frac{1}{2 y^2}-\frac{1}{2 y^4}+\frac{5}{4
   y^6}+O\left(\frac{1}{y^8}\right)\Bigg]$
I get:
$\sqrt {\frac 2 \pi} \cdot \sigma_x \cdot \frac {e^{- y^2}} {1 + erf(y)} \approx \sqrt {\frac 2 \pi} \cdot \sigma_x \cdot (-\sqrt{\pi }) \,y\Bigg[1+\frac{1}{2 y^2}-\frac{1}{2 y^4}+\frac{5}{4
   y^6}+O\left(\frac{1}{y^8}\right)\Bigg] =$
$= - \sqrt {2} \cdot \sigma_x \cdot \,y\Bigg[1+\frac{1}{2 y^2}-\frac{1}{2 y^4}+\frac{5}{4
   y^6}+O\left(\frac{1}{y^8}\right)\Bigg]$
which indeed approaches $- \sqrt 2 \cdot \sigma_x \cdot y$ when $y$ becomes very negative.
With the above approximation:
$f(y) \approx \sqrt 2 \cdot \sigma_x \cdot y - \sqrt {2} \cdot \sigma_x \cdot \,y\Bigg[1+\frac{1}{2 y^2}-\frac{1}{2 y^4}+\frac{5}{4
   y^6}+O\left(\frac{1}{y^8}\right)\Bigg] = $
$= - \sqrt {2} \cdot \sigma_x \cdot \,y\Bigg[\frac{1}{2 y^2}-\frac{1}{2 y^4}+\frac{5}{4
   y^6}+O\left(\frac{1}{y^8}\right)\Bigg] $
Numerically, this 'does the trick', i.e. for $y \le -4$ it seems really very close to the function I need to compute, as indicated by Claude. And in fact with the rational function version even up to $y \le -1$.
This seems to imply that only polynomial approximations are viable, not the $erfc$-based ones, or am I wrong?
Any thoughts?
Answer: I would suggest a series expansion for $x \leq- 4$
$$f(x)=\frac{e^{-x^2}}{1+\text{erf}(x)}=-\sqrt{\pi } \,x\Bigg[1+\frac{1}{2 x^2}-\frac{1}{2 x^4}+\frac{5}{4
   x^6}+O\left(\frac{1}{x^8}\right)\Bigg]$$ For $x=-5$, the "exact" value is $9.03318$ while this truncated expansion gives $9.03313$.
Much better would be the Padé approximants
$$f(x)=-\sqrt{\pi } \,x \,\frac{8 x^6+84 x^4+210 x^2+105 } {8 x^6+80 x^4+174 x^2+48 }$$ which, for $x=5$, leads to an error of  $2.2\times 10^{-8}$.
Comment: Thank you Claude, your solution seems to work very well! I am probably going to accept it as the answer. Could you please just comment briefly on how you obtained that expansion?
Comment: @user6376297. The first one is obtained by composition of the Taylor series for large negative values of $x$. Taking more terms, it is easy to build the corresponding Padé approximant. The one I produced is equivalent to a Taylor series to $O\left(\frac{1}{x^{13}}\right)$. If you want better, let me know since it just need a couple of minutes to build. Cheers :-)
Comment: Thanks, no, I do not need a more precise approximation, I was just trying to understand how you made yours, so for similar cases I could do it myself. Unfortunately I cannot see how that is a Taylor series, as per definition it should only have positive powers of x. https://en.wikipedia.org/wiki/Taylor_series . Also, I would not know on which point to 'center' the series, as here we say 'very negative x', which for me means make x go to $-\infty$, but then I cannot write Taylor terms with $(x+\infty)^n$... So I am a bit stuck. I will do more research. And I will accept your answer.
Comment: OK I found two posts that maybe clarify this. https://math.stackexchange.com/questions/595426/series-expansion-of-a-function-at-infinity/595437 and https://math.stackexchange.com/questions/51770/taylor-expansion-at-infinity . Perhaps there are some substitution and back-substitution steps being taken, not simply a Taylor expansion. The other issue is that the CAS I am using to do this gets the limit wrong for $f(x)$ and its derivatives at $x \to - \infty$. But OK, that can be addressed somehow.
Comment: No, tried it out and still does not work for me :( I might post another question about that, unless you can comment on the method you used.
Comment: @user6376297. Where is your problem ? In the derivative ? Do you want to go to a chat room ? If yes, open a room and I join you.
Comment: @user6376297. I you prefer *"Laurent series"*
Comment: Indeed, I submitted 'Taylor series exp(-x^2)/(1+erf(x)) of degree 6 for x -> -infinity' to Wolfram Alpha and it gave me the same result as yours, but with a '(Laurent series)' note next to it. I had found 'Laurent series' when searching for Taylor series with negative powers of the variable, but when I saw those circular integrals and it said that it applied to complex functions, I thought it had little to do with my example. [This post](https://math.stackexchange.com/questions/1180609/how-to-find-laurent-series-expansion) says something about Laurent series. Still very unclear to me.
Comment: I created the chat room. Not sure why it assigned it to chemistry, but OK. https://chat.stackexchange.com/rooms/120743/laurent-series-workshop
Answer: In the negatives, $$\text{erf(x)}$$ very quickly tends to $-1$ and it is no surprise that you soon reach the limits of the floating-point representation.
You will regain full accuracy by computing
$$\text{erf}(x)+1$$ directly. It is possible that you will obtain better results with $\text{erfc}(-x)$, but that depends on the numerical library you use.
Otherwise, you could use the fourth approximation in https://en.wikipedia.org/wiki/Error_function#Approximation_with_elementary_functions, and you will see a nice simplification with your numerator.
Answer: $1 + erf(x)$ suffers from catastrophic cancellation in the negative half plane. This is avoided by replacing it with $erfc(-x)$, that is, use of the complementary error function. Most standard math libraries, for example the C++ standard math library, include this as a function erfc.
Many special function libraries also offer the exponentially scaled complementary error function, $e^{x^{2}} erfc(x)$, often as a function called erfcx. With that, one can compute $\frac{e^{-x^{2}}}{1+erf(x)}$ accurately as 1.0 / erfcx (-x). I also provided a double-precision implementation of erfcx on Stackoverflow.
As I became aware belatedly, there is a second instance of catastrophic cancellation in $f(x)$ for negative $x$ large in magnitude: $x$ and the rest of the expression are similar in magnitude but of opposite sign. Around $-10^{7}$ complete loss of accuracy occurs.


Excel Charts, add custom forecasting line

Question: I got the following graph (in purple):

Now I want to add the dotted forecasting line.
It's a cell value, but not referenced to the point on the X-Axis (Oktober 13).
I am a bit lost as to how I could accomplish it. Anyone got an idea?
Thanks in advance
Comment: What "it's a cell value"? Slope? X-Y or line graph?
Comment: The forecasted value is written in a cell. It should be an Y-value of presumably a second graph. My original thinking was, that I add a second line graph with the Y plot points for September 13 and the forecast number, but I cant match them with the X plot points, namely September 13 and Oktober 13, because they dont correspond.
But X-Y Plot might be an interesting idea, I'll have a look.
Answer: As I responded to this exact question in the Mr Excel forum:
Use data like this and make a simple line chart:
<code>  Date        Actual   Forecast
10/1/2012      1650
11/1/2012      1050
 5/1/2013      1100
 6/1/2013      1125
 7/1/2013      1400
 8/1/2013      1100
 9/1/2013      2200      2200
10/1/2013      1450      2450
11/1/2013
12/1/2013
</code>
Answer: Can be achieved (in my case with Excel 2007) but proved to be rather fiddly and I would not recommend an x-axis with irregular time intervals:

Basically a Stacked Line chart, with November 13 and Dezember 13 data points formatted for Line Color No Line and one of the Oktober 13 data points formatted with a different Line Style.
A question like this might be better suited to Super User where, if you are lucky, you might attract Jon Peltier's attention.


Could not cast value of type 'ProjectName.AddNewPropery' (0x10fa2edf0) to 'ProjectName.ViewProfile' in swift

Question: I am getting crash while pushing view controller in action method i used this code
<code> let vc = self.storyboard?.instantiateViewControllerWithIdentifier("addProperty") as! ViewProfile
 self.navigationController?.pushViewController(vc, animated: false)
</code>
What would be the reason?
Answer: I got it. i missed "AddNewPropery" class name of second view controller. replacing "ViewProfile" to "AddNewPropery" fixed my problem.
<code> let vc = self.storyboard?.instantiateViewControllerWithIdentifier("addProperty") as! AddNewPropery
self.navigationController?.pushViewController(vc, animated: false)
</code>


How do you construct a musical motive?

Question: I was wondering if I could get a second opinion on methods for constructing a musical motive.  I have been creating melodies for quite some time, mainly without taking harmonic progression into consideration, and this I believe has lasting implications as far as overall continuity of my piece goes.  Are there any methods for etching motives out of chord progressions, or anything like that?
I realize this inhibits the artistic license of the composer, but it seems like it would be a good exercise for someone in my position, but nevertheless (or at least until I can start to develop some harmonic intuition in my melodies).
Thank you.
Answer: "methods for constructing a musical motive"
For me, it doesn't work like that. A melody comes to me, and in retrospect, I find the motives. I can't really explain how that works, a motive is just anything that I recognize as a distinct unit - some kind of pattern.
Whether something is a pattern is to some extent subjective. Melodic and rhytmic properties are to some extent independent: it may be a particular rhythm, or it may be a sequence of melodic intervals, or even a single interval. It might even not be pinned down to intervals, but just a particular pattern of melodic motion. Whether something is a motive or not is also context dependent - you might not recognize something as a pattern if it occurs only once; repetition, or even re-statement or a variation might trigger recognition on the listener's part.
This all sounds very abstract, but in practice it's usually not that hard to find motives.
Once you have motives, it really helps in creating larger forms.
You can use them to "fill in" parts, kinda like the way some people doodle figures in the margin of their notebooks. Of course you should use your taste and ears and let them do their work as well. Simply mechanically filling everything up with the same motives can become boring.
Or you try and feel whether the motives you found have a tendency to "go somewhere". For example, a rhytmic motive that starts with long notes, and gradually accelerates into shorter notes may be restated and varied to accelerate even more by adding even more shorter notes. Or a melodic motive that starts with step-wise motion and continues with ever larger leaps can be exaggerated by adding more, even larger leaps.
Sequences are also a very tried method to work out motives. Sequences take a motive (typically, consisting of both a rhytmic and a melodic pattern) and systematically repeat it at another pitch. This is done typically 3 times, and typically the change in interval is persistent for all legs of the sequence.
Because the sequence is both repetition as well as variation, this is a very powerful device to develop motives. You can play with the size and motion of the interval to invoke a sense of tension or relaxation. For instance, if you use an ascending interval of a second or a third typically feels like an increase in tension, and often this can be used to force a modulation to another key.
Here's a nice example of motives and sequenes: http://musescore.com/user/13172/scores/130814
(BWV 847 The Well-Tempered Clavier Part I Fuga II)
The visualization over here shows the sequences as a little stairs icon:
http://bach.nau.edu/clavier/nature/fugues/Fugue02.html
Check out the text in that page too. It does a great job of explaining how the motives in the theme are used throughout the piece.
Comment: A great example of a melodic sequence is the opening few bars of Beethoven's Fifth Symphony.  Another one, perhaps a bit more straightforward, is at the beginning of Mozart's G minor symphony.  The first sequence of notes is repeated a step lower.
Comment: I hate to be a pain, but could you elaborate on "sequences"?  I'm sure it's a very in-depth concept and I apologize.  I've checked it out on wikipedia and the articles tend to be very cryptic, or assume too much of the reader.
Comment: Sure! Will update the answer.
Comment: Interestingly, Beethoven is said to have been out walking with a student when he suddenly stopped and said he had just thought of the theme to the last movement of his Appassionata sonata.  He immediately walked home and dissmissed his student, saying he had a great deal of work to do.
Comment: @BobRodes You mean,the first 5 bars? That would have just 2 legs, and not even a partial third leg. Personally I would not call it a very typical sequence. But that said, this is a really great example of how an incredibly small motive can completely define a really large movement.
Comment: I don't know, I didn't count the bars.  I could probably think of one that had more than two "legs" in the sequence, but those two came to mind as ones that the OP might not have to look up.  As for not typical, maybe not, but because it is so short, rather than because it has only one repetition of the sequence.  That happens quite a bit in my experience; as in the Mozart.  The opening theme of Brahms's Op. 119, No. 4 comes to mind.  I suppose you could say that one is three, though, since the first instance repeats again after the second.

How do you construct a musical motive?


SQLAlchemy event registration

Question: I'm trying to figure out how SQLAlchemy handles event registration. I have a situation where I want to keep all of my event listeners in a single file, rather than in the model (I want to do this to avoid my models importing controllers with business logic). But if I try to do something like the following in a separate file the code will not fire:
<code>from sqlalchemy.event import listens_for
from models import User

@listens_for(User, 'before_update')
def before_update_listener(mapper, connection, instance):
    print "do something"
</code>
Which makes sense, this module is never imported, but then how do I tell SQLAlchemy that event listeners exist in some listeners.py file?
Comment: Just import the file?
Answer: The file must be imported, you can do something like the following:
<code># listeners.py
from sqlalchemy.event import listens_for
from models import User

@listens_for(User, 'before_update')
def before_update_listener(mapper, connection, instance):
    print "do something"
</code>
.
<code># __init__.py
from . import events
del events
</code>

SQLAlchemy event registration