Summation inequality problem: $n +(1 + 1/2 + 1/3 +.....+1/n) > n(n + 1)^{1/n}$

Question:
Let $S_{n} = 1 + 1/2 + 1/3 +.....+1/n,$ then prove that $$n + S_{n} > n(n + 1)^{1/n}.$$

My work: To show $1 + S_{n}/n > (n + 1)^{1/n}.$ I start with Cauchy-Schwartz inequality,
$(1 + 2 + \cdots + n)(1 + 1/2 + 1/3 +.....+1/n)>n^2$ which implies $S_n/n > 2/(n + 1).$ But after adding $1$ to both sides I can not find the desired result.
So is there any problem?
Comment: I think you forgot the squares on the L.H.S. of the inequality.
Comment: Ohhoooo..Sure. But then also it will be difficult to find the result
Answer: Hint: $$n+S_n = \frac{2}{1} + \frac{3}{2} + \frac{4}{3} + \cdots + \frac{n+1}{n}.$$ Now apply the AM-GM inequality.
Comment: very nicely done.
Comment: I got it...good way
Answer: $$1+\sum_{i=1}^n\frac{1}{i\cdot n}=\frac{n+\sum_{i=1}^n\frac{1}{i}}{n}$$
Now use the Inequality of arithmetic and geometric means and the fact that $\sum_{i=1}^n\frac{1}{i}>1$. It's only true for $n\geq 2$ otherwise you get $\geq$ instead of $>$


Modified Bessel differential equation

Question: The modified Bessel differential equation is always presented as
$$r^2 \frac{\partial^2 f(r)}{\partial r^2} + r\frac{\partial f(r)}{\partial r} - (r^2 + n^2)f(r) = 0$$
with solutions
$$f(r) = AI_n(r) + BK_n(r)$$
But if I had
$$r^2 \frac{\partial^2 f(r)}{\partial r^2} + r\frac{\partial f(r)}{\partial r} - (\alpha^2 r^2 + n^2)f(r) = 0$$
What form should have the solutions and how to prove it? It seems not to be a simple substitution $r' = \alpha r$, because $\alpha$ appears just one time in the second equation and not in all the $r$ terms (as I would expect instead).
Comment: Maple says this here $$f \left( r \right) =1/4\,{\alpha}^{2}{r}^{2}+1/2\,{n}^{2} \left( \ln
 \left( r \right)  \right) ^{2}+{\it \_C1}\,\ln  \left( r \right) +{
\it \_C2}
$$
Answer: If you scale the $r$ axis by a factor $\alpha$ then the first two terms do not change because the re-scaling of $r$ is compensated by a re-scaling of the derivatives.
Comment: thank you, this is an intuitive way to view this problem
Answer: Your intuition is correct.  Let $r'= \alpha r$ and $f(r)=g(r')$.  Then, using the chain rule yields
$$\begin{align}
\frac{\partial f(r)}{\partial r}&=\frac{dr'}{dr}\frac{\partial g(r')}{\partial r'}\\\\
&=\alpha \frac{\partial g(r')}{\partial r'} \tag 1
\end{align}$$
Then, using $(1)$ we obtain
$$\begin{align}
0=&r^2\frac{\partial^2 f(r)}{\partial r^2}+r\frac{\partial f(r)}{\partial r}-\left(\left(\alpha r\right)^2+n^2\right)\\\\
&=\left(r'/\alpha\right)^2(\alpha^2)\frac{\partial^2 g(r')}{\partial r'^2}+(r'/\alpha)(\alpha)\frac{\partial g(r')}{\partial r'}-\left(\left(\alpha r'/\alpha\right)^2+n^2\right)g(r')\\\\
&=r'^2\frac{\partial^2 g(r')}{\partial r'^2}+r'\frac{\partial g(r')}{\partial r'}-\left(r'^2+n^2\right)g(r')\tag 2
\end{align}$$
The solution to $(2)$ is
$$g(r')=AI_n(r')+BK_n(r')=AI_n(\alpha r)+BK_n(\alpha r)=f(r)$$
Comment: Except for the fact that the $((\alpha r)^2 + n^2)$ term should have a minus sign, thank you, it was very helpful.
Comment: You're welcome.  And thank you for carching the typo!  +1 for the catch

Modified Bessel differential equation


ORA-01861: literal does not match format string,

Question: Currently I am trying to compare date fields with the below statement
<code>AND (AIA.INVOICE_DATE >= NVL(TO_DATE(:P_INV_DT_FROM,'DD-MON-YYYY'), '01-JAN-1900')
OR AIA.INVOICE_DATE IS NULL)
AND (AIA.INVOICE_DATE <= NVL(TO_DATE(:P_INV_DT_TO,'DD-MON-YYYY'), '31-DEC-4712')
OR AIA.INVOICE_DATE IS NULL)
</code>
However, I am getting the below error,

ORA-01861: literal does not match format string
  01861. 00000 -  "literal does not match format string"
*Cause:    Literals in the input must be the same length as literals in
             the format string (with the exception of leading whitespace).  If the
             "FX" modifier has been toggled on, the literal must match exactly,
             with no extra whitespace.
*Action:   Correct the format string to match the literal.

P.S: AIA.INVOICE_DATE is tn the form of 'DD-MON-YYYY' and p_inv_dt_from and p_inv_dt_to is in the form of 'YYYY/MM/DD HH24:MM:SS'
Comment: These are not date values: `'01-JAN-1900'`, `'31-DEC-4712'`
Comment: Also, if `AIA.INVOICE_DATE` has any "format", it must be a string, not a date column.
Answer: You need to explicitly identify the format of '01-JAN-1900' and '31-DEC-4712' (that is wrap them in TO_DATE('01-JAN-1900','DD-MON-YYYY')).  Otherwise, Oracle will attempt to convert the strings to a date based on the environment session settings of whoever is running the code.  Your session, for instance, may have NLS_DATE_FORMAT='MM/DD/YYYY', which isn't compatible with '01-JAN-1900'.


Playing streaming video in WPF

Question: I've written a WCF service that streams media files. I'm now writing a WPF application that consumes this service and have only just found out that the MediaElement does not accept Stream objects as input parameters for the source property.
I've been Googling endlessly for the past two days and have looked at several alternatives including the Silverlight Viewports inside WPF, VLC ActiveX controls, VideoRendererElement and WPFMediaKit. Unfortunately I've been hampered by lack of documentation and/or examples and haven't really made any progress so far. The fact that this is the very first time I'm using WPF doesn't help either.
To put it simply, what I'm looking for is something that comes with documentation or examples demonstrating streaming in WPF and, if possible, is also straightforward to implement. The solution doesn't have to be perfect; all I need is something that works.
Answer: You could host a HttpListener inside your WPF app and supply the stream which you receive from your WCF service through an URL which is served by HttpListener to MediaElement.Source .
Other options (though you seem to have ruled them out):

http://directshownet.sourceforge.net/
http://wpfmediakit.codeplex.com/

Not sure if this is an option for you, but there are commercial libraries for multimedia including video playback from streams in WPF:

http://www.leadtools.com/sdk/multimedia-suite.htm#-
http://www.visioforge.com/video-capture-sdk-net2.html or http://www.visioforge.com/media-player-sdk-net.html
Comment: The WCF service uses TCP bindings, and runs outside of an IIS as a Managed Windows Service. Would I be able to use TcpListener instead of HttpListener to somehow get the URL of the incoming Stream?
Comment: I assume that your WCF service return a a IStream - IF this assumption is true then you would just use the WCF proxy class to get the Stream and then supply that stream to either the libraries I mentioned and or "relay" it to an http URL inside you app with HttpListener and tell MediaElement to use that http URL... I strongly recommend using one of the libraries though...
Comment: I've never used the HttpListener class before, so I don't quite understand how I'd relay a stream to a HTTP URL. Is this what you mean? http://pastebin.com/iELVyybp
Comment: that is a first step, there are some quirks (problems) and inefficencies in that code.. but again I would strongly discourage this routs since using HttpListener is a permissions/rights issue (it basically is an "embedded HTTP-Server") depending on what permissions/rights your user has...
Comment: In that case, are you absolutely certain that Visioforge's Media Player SDK is going to allow the WPF application to play the IStream that the WCF service returns?
Comment: since I don't know your WCF service and I don't know which video format it delivers etc. I can't be absolutely certain... just download their SDK and try, AFAIK it can be used without registration in trial mode (you could mail them about a trial version/key).
Comment: Hi! Could u provide more examples around "host a HttpListener inside your WPF" , please?
Comment: @Peretz What exactly do you need ?
Comment: Well.. I need C# code for this:  "host a HttpListener inside your WPF"
Comment: @Peretz The link in my answer has a simple example with source code... do you need anything specific ?
Answer: There is a way to achieve this using a pseudofiles, i.e. emulation of file system calls.
When a path passed, a media player firstly opens the file (CreateFile is called), then reads data from it (ReadFile is called), moves position within the file (SetFilePointer is called).
It just moves within the video file and reads required blocks.
For example here described this approach (file calls just mapped to appropriate IStream methods: ReadFile -> Read, SetFilePointer -> Seek, CreateFile -> Clone etc.): http://boxedapp.com/encrypted_video_streaming.html

Playing streaming video in WPF


TableCellRenderer, problema na exibição de cor na tabela

Question: É o seguinte, eu quero mudar a cor de letra uma especifica parte da minha tabela quando o pagamento do usuário está em dia para azul. Caso contrario, quero que mude para vermelho. Quero que só a coluna "situação" faça isso. Ou seja, Quando eu encontrar "ok" quero mudar para azul ou para vermelho quando encontrar "Pendente".
// Esse é meu Renderer
public class pagamentoTableCellRenderer extends JLabel implements TableCellRenderer {
    // lista de objeto dos usuários
    private ArrayList<ModelUsuario> listaAluno;

    public pagamentoTableCellRenderer(ArrayList<ModelUsuario> situacao) {
        this.listaAluno = situacao;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        ModelUsuario situacao = listaAluno.get(row);

        if (situacao.getSituacao().equals("ok")) {

            setForeground(Color.blue);

        } else {
            setForeground(Color.red);
        }

        return this;
    }
}

public class ModeltabelaCarregar {

     public static  void main(String [] args) throws ParseException{
         new viewControleDePagamento().setVisible(true);;

    }

}

Answer: Faz assim:
public class ColorirTabelaTramitacao extends DefaultTableCellRenderer {

/**
 *
 */
private static final long   serialVersionUID    = 1L;
public static final float R = 0.9f;
public static final float G = 0.5f;
public static final float B = 0.8f;

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
   //203,216,227
    //Color c = new Color(203,216,227);

    Color c = Color.WHITE;
    Object text = table.getValueAt(row, 3);
    Object text2 = table.getValueAt(row, 10);
    if (text != null && "LICENÇA EMITIDA".equals(text.toString())){
        // RGB
        c = new Color(126,195 ,255);
    }
    if(text != null && "DESARQUIVADO".equals(text.toString())){
        c = Color.GREEN;
    }
    if(text != null && "ARQUIVADO".equals(text.toString())){
        c = Color.RED;
    }
    if(text2 != null){
        c = Color.YELLOW;
    }

       setBackground(c);

   if (isSelected){
          //setForeground(Color.BLUE);
          setBackground(table.getSelectionBackground());
  }

    return this;

}

}
Chama assim:
private void defineModelo() {
        tableModel = (DefaultTableModel) tblTramitacao.getModel();

        listModel = tblTramitacao.getSelectionModel();

        tblTramitacao.setDefaultRenderer(Object.class, new ColorirTabelaTramitacao());

Vai ficar assim:
Comment: valeu cara, consegui resolver o problema! Mas teria com eu alterar a cor de apenas uma coluna?
Answer: Nesse Caso você instancia um objeto DefaultTableCellRenderer ficando assim:
DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {

        @Override
        public void setValue(Object value) {
            switch ((String) value) {
                case "Sim":
                    setBackground(Color.YELLOW);

                    break;
                case "Não":
                    setBackground(Color.WHITE);

                    break;
            }
            super.setValue(value);
            setForeground(Color.BLACK);
        }
    };

O  parâmetro do método setCellRenderer requer um argumento TableCellRenderer:
suaTabela.getColumnModel().getColumn(7).setCellRenderer(colorRenderer);

Resultado é esse:


Is there a way to re-categorize content in a list form?

Question: There are hundreds of content pages on a site I work with. These are categorized with Taxonomy, which connects the pages to the menu system. There is a need to revise these connections. I would like to create a page (view) where these Taxonomy references couyld be updated?
Is this possible?
Answer: Assuming I read your question correctly, you could try the Edittable Views module. details from its project page:

Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.


Problem with the Definition of Inner Product Space.

Question: Let $V$ be a vector space over a field $F=\mathbb{R}/\mathbb{C}.$ Then an inner product on V is defined to be a function $(,):V\times V \rightarrow \mathbb{F}$ satisfying the following property:

Linearity in the first coordinate.

Conjugate-Symmetry.

Positivity: For all $x \in V$, if $x$ is nonzero then $(x,x)>0$.

My Questions:

If I  take $\mathbb{F}$ to be $\mathbb{C}$. Since it is not an ordered field,
the idea of positivity does not make sense. But I find this definition
everywhere. Am I missing something out?

Every Inner Product defined on $V$ (an $\mathbb{R}$-vector space) is bilinear.
Does every bilinear map $f: V\times V\rightarrow \mathbb{R}$  give rise to an
inner product on $V$?
Comment: Because of Property 2 one gets that $(x,x)\in \mathbb{R}$.
Answer:
The third condition should be: for every $x\in V$, $(x,x)\in[0,\infty)$. In particular, $(x,x)$ is always a real number.
No. If, say $f(x,x)$ is always equal to $0$; then $f$ is not an inner product. And, if $V=\Bbb R$ and $f(x,y)=-xy$, this $f$ is also not an inner product.
Comment: Thanks for the answer. I have added one more question to this. Can you please provide an answer to the added question?
Comment: @Saikat Done.${}$
Comment: By $f(x,x)=0$ always, you mean a bilinear map with this property. Correct? That is if we take  $f(x,y)=0$ always. Then this works well. Am I correct?
Comment: Conjugate-symmetry tells us that $(y,x) = \bar{(x,y)}$ for all $x,y \in V$. So, $(x,x) = \bar{(x,x)}$ for all $x \in V$. This shows that $(x,x)$ must be real. So we don't need to modify the third condition.
Comment: @Saikat Yes, that is correct.


Minima of $f(x)$

Question:
The miniumum value of $\left(1+ \dfrac{1}{\sin^n \alpha}\right)\left(1+ \dfrac{1}{\cos^n\alpha}\right)$ is?

Attempt:
I expanded the brackets and then differentiated and set the derivative equal to zero but it gets really complicated with that because of too many trig functions.
What is the efficient way to solve it?
The answer given is:

 $(1+2^{\frac n2})^2$
Comment: Won't it depend on whether $n$ is odd or even? (If its even shouldn't it be 0, which occurs when $\alpha=n\frac{\pi}{2}$ for $n\in\Bbb Z$)?
Comment: thats not in domain @aidangallagher4
Comment: Sorry I'm being stupid — it should still matter if $n$ is odd or even though shouldnt it?
Comment: It would be good to state the domain (and why).
Answer: Cauchy Schwarz Inequality
$\displaystyle (a^2+b^2)(c^2+d^2)\geq (ac+bd)^2$
and equality hold when $\displaystyle \frac{a}{c} = \frac{b}{d}.$
Here I am assuming $\displaystyle \alpha \in \bigg(0,\frac{\pi}{2}\bigg).$
$$\Bigg[1+\frac{1}{\left(\sin^{\frac{n}{2}}\alpha\right)^2}\Bigg]\cdot \Bigg[1+\frac{1}{\left(\cos^{\frac{n}{2}}\alpha\right)^2}\Bigg]\geq \bigg[1+\frac{1}{\sin^{\frac{n}{2}}\alpha\cdot \cos^{\frac{n}{2}}\alpha}\bigg]^2$$
$$ = \bigg[1+\frac{2^{\frac{n}{2}}}{\left(\sin 2\alpha\right)^{\frac{n}{2}}}\bigg]^2 \geq \bigg(1+2^{\frac{n}{2}}\bigg)^2.$$
Answer: hint
If $n=2p$ then put
$$x=\sin^2 \alpha$$ and find the minimum of
$$\left(1+\frac{1}{x^p}\right)\left(1+\frac{1}{(1-x)^p}\right)$$
Answer: Let $$f(x)=\left(1+\frac{1}{\sin^nx}\right)\left(1+\frac{1}{\cos^nx}\right)\text{ for } 0<x<\frac{\pi}{2}$$
Then $$\begin{align}
f(x)&=\left(1+\frac{1}{\sin^nx}\right)'\left(1+\frac{1}{\cos^nx}\right)+
\left(1+\frac{1}{\sin^nx}\right)\left(1+\frac{1}{\cos^nx}\right)'\\
&=\frac{-n\cos x}{\sin^{n+1}x}\left(1+\frac{1}{\cos^nx}\right)+
\frac{n\sin x}{\cos^{n+1}x}\left(1+\frac{1}{\sin^nx}\right)\\
&=\frac{n}{\sin^nx\cos^nx}\left(-\frac{\cos^{n+1}x+\cos x}{\sin x}+\frac{\sin^{n+1}x+\sin x}{\cos x}\right)
\end{align}
$$
Since $\cos x > \sin x > 0$ on $(0, \pi/4),$ we see that $f'(x)<0$  on $(0,\pi/4).$  Similarly, $f'(x)>0$ on $(\pi/4,\pi/2),$ so that $f$ attains it minimum on $(0,\pi/2)$ at $x=\pi/4$.

Minima of $f(x)$


Sphinx saying: FATAL: no readable config file

Question: root@ded69-145:/var/lib/mysql# /etc/init.d/sphinxsearch restart
Restarting sphinxsearch: Sphinx 2.0.4-id64-release (r3135)
Copyright (c) 2001-2012, Andrew Aksyonoff
Copyright (c) 2008-2012, Sphinx Technologies Inc (http://sphinxsearch.com)

FATAL: no readable config file (looked in /etc/sphinxsearch/sphinx.conf, ./sphinx.conf).

I'm getting this error but the config file is definitely there.
Answer: Try typing searchd - this will fire up the indexes and start the Sphinx Daemon.
Answer: Even though its saying the error what you mentioned(FATAL: no readable config file), i don't think it will not affect the usage of sphinx when you configured in your project. If you search the config file it might be with the name sphinx.conf.dist. You just start index the file and it will work fine. The same error throws for me but it worked well.
Answer: if you installed the package using yum install sphinx, you have to start using service searchd start, and update config file in /etc/sphinx/sphinx.conf, but if you want to use /etc/init.d/sphinxsearch restart you have to specify config file with --config and the path where the config file is.


Why docker system prune did not remove the dangling images while docker rmi $(docker images --filter "dangling=true" -q --no-trunc) did

Question: This is the first time I hit the situation that docker system prune did not remove the dandling images. After running docker system prune I still have many images has the tag <none>.
docker images --filter "dangling=true" -q --no-trunc  removed them, but why ?
BTW, those  images were create when I pull the new ones with the same tags. There is another SO why does docker prune not remove my dangling images? talking about the similar problem but I don't think we were the same problem.
Answer: Might there still be containers based on those images?
If not: It seems that docker system prune doesn't consider images without a tag as dangling. More on that can be found here: Moby issue
Try: docker system prune -a
Comment: Found a similar problem on https://gist.github.com/anildigital/862675ec1b7bccabc311#gistcomment-2274889 but without a real solution either.
Comment: The images having name and tag as none in `docker images` are dangled. How to check their size? Also, the images having name and tag as none in `docker images -a` are intermediate images. Can they be deleted and how to check their size?


5 card selection from bundle

Question: Determine in how many ways you can select 5 cards from a standard 52-card bundle, and  each color is chosen among your selections.
The standard set of cards contains 13 different cards in 4 colors.
I am looking for solution of this.
My idea is
$${\binom{13}{1}  \binom{13}{1} \binom{13}{1} \binom{13}{2} }$$
Disclaimer: this is not a homework
Answer: I think you are almost there. One more thing you should consider is that the color including $2$ cards can be chosen from $4$ different colors as well (which color will have $2$ cards?). This makes the answer
$$\binom{4}{1}\binom{13}{1}  \binom{13}{1} \binom{13}{1} \binom{13}{2}$$

5 card selection from bundle


Como faço para usar o intervalo de datas no Progress 4gl

Question: estou fazendo um programa para listar

listar cliente
Quantidade de pedidos
Quantidade de pedidos por cliente

tudo referente ao mes de fevereiro de 2015
como eu faria pra pegar somente o intervalo de
<code>>= 01/02/2015 && <=  28/02/2015
</code>
Comment: qual o nome do seu campo data?
Comment: consegui meu chefe me ajudou
Comment: ficou assim

FOR EACH ped-venda WHERE MONTH(ped-venda.dt-emissao)= 2
                     AND YEAR(ped-venda.dt-emissao) = 2015 BREAK BY ped-venda.nome-abrev BY ped-venda.dt-emissao DESC:
Comment: Coloca tua resposta e finaliza o post para que possa ajudar mais pessoas.
Answer: Vi que voce fez ali no comentario.
Mas usar funcoes que necessitem do valor da tabela que voce esta pesquisando automaticamente transforma o for each em um full table scan, ou seja, ele nao vai conseguir aplicar indices na sua query. Em bancos com numero grande de pedidos, essa pratica joga a sua performance no lixo.
Eu faria desse jeito:
<code>FOR EACH ped-venda WHERE ped-venda.dt-emissao >= 02/01/2015
     AND ped-venda.dt-emissao <= 02/28/2015
 BREAK BY ped-venda.nome-abrev BY ped-venda.dt-emissao DESC:
</code>
Sendo a data fixa, como voce sugeriu. Isso faz com que o Progress utilize o indice mais apropriado, acelerando bastante a busca do result set da sua query.


Show that $\int \frac{1}{x-z}\,\mathrm{d}\mu(x)$ exists on the upper half-plane if $\int (1+|x|)^{-1}\,\mathrm{d}\mu(x)<\infty$

Question: In Harmonic Analysis: A Comprehensive Course in Analysis, Part 3 page 62, he states a definition of Stieltjes transform of a finite (Borel) measure on $\mathbb{R}$:

If $\mu$ is a finite measure on $\mathbb{R}$, its Stieltjes transform, $F_\mu(z)$, is the function on (the upper half-plane) $\mathbb{C}_+$ given by
$$
F_\mu(z)=\int \frac{1}{x-z}\,\mathrm{d}\mu(x).\qquad (*)
$$

It is not difficult to see that this integral is well-defined. Later on page 64, he removed the assumption that $\mu$ is finite;

For $F_\mu$ to exist, one only needs $\int (1+|x|)^{-1}\,\mathrm{d}\mu(x)<\infty$ ...

I want to know the reason behind it. I tried to find the upper bound of the integrand in (*) in different ways to see if somewhere can be at most $(1+|x|)^{-1}$, but no luck! Here is one of my tries: I write $z=u+iv$ with $v>0$, then
$$
\frac{1}{x-z}=\frac{x-u}{(x-u)^2+v^2}+i\frac{v}{(x-u)^2+v^2},
$$
Multiplying both sides by $z=u+iv$, we get
$$
\frac{z}{x-z}=\frac{ux-u^2-v^2}{(x-u)^2+v^2}+i\frac{vx}{(x-u)^2+v^2}\\
=\frac{u(x-u)-v^2}{(x-u)^2+v^2}+i\frac{vx}{(x-u)^2+v^2}\\
=\frac{u(x-u)/v^2-1}{\left ( \frac{x-u}{v} \right )^2+1}+i\frac{x/v}{\left ( \frac{x-u}{v} \right )^2+1}
$$
Then I get stuck ...
Answer: For fixed $z=u+iv$ with $ v > 0$ is
$$
 x \mapsto \frac{1+|x|}{|x-z|} = \frac{1+|x|}{\sqrt{(x-u)^2+v^2}}
$$
a continuous function on $\Bbb R$ with limit $1$ for $x \to \pm \infty$. It is therefore bounded, so that
$$
\frac{1}{|x-z|} \le C \cdot \frac{1}{1+|x|}
$$
for some constant $C > 0$ and all $x \in \Bbb R$.
Comment: That's interesting ... If you have shown that $|f(x)|\to 1$ as $|x|\to \infty$, wouldn't we get that for some $C>0$, we have $|f(x)|\leq C$ for all large $|x|$? What I don't understand, why this holds for "all $x\in \mathbb{R}$".
Comment: @James2020: Because it is a *continuous* function. If you have $|f(x)| \le K_1$ for $|x| \ge R$ then $f$ has a maximum $K_2$ on $[-R, R]$, so that $C = \max(K_1, K_2)$ is an overall maximum.
Comment: Amazing! Thanks so much for your help


Como corrigir erros de dependência na instalação do ng-bootstrap em um projeto Angular

Question: Estou com problemas para fazer a instalação da dependência @ng-bootstrap. Atualmente utilizo Debian e VScode.
Ao executar o código: npm install --save @ng-bootstrap/ng-bootstrap o retorno é um erro de conflito de dependências no package @ng-bootstrap.
Erro do npm ao tentar instalar a dependência:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: email@example.com
npm ERR! Found: @firstname.lastname@example.com
npm ERR! node_modules/@angular/compiler
npm ERR!   @angular/compiler@"~13.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/compiler@"13.3.9" from @email@example.com
npm ERR! node_modules/@angular/localize
npm ERR!   dev @angular/localize@"^13.2.7" from the root project
npm ERR!   peer @angular/localize@"^13.0.0" from @firstname.lastname@example.com
npm ERR!   node_modules/@ng-bootstrap/ng-bootstrap
npm ERR!     @ng-bootstrap/ng-bootstrap@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/gropp/.npm/eresolve-report.txt for a full report.

Detalhe: para eu conseguir rodar o projeto sem outros erros, preciso ter essa dependência.
Answer: Como o próprio log de erro sugere, você pode corrigir os conflitos e erros de dependência utilizando o comando --force ou --legacy-peer-deps.
SOLUÇÃO 1 -
Geralmente o comando --legacy-peer-deps tende a funcionar, você pode tentar adiciona-lo no final do seu comando npm, por exemplo: npm i @ng-bootstrap/ng-bootstrap --legacy-peer-deps.
SOLUÇÃO 2 -
Uma outra opção se acima não funcionar, você pode tentar baixar o angular globalmente pelo comando:
npm install -g @angular/cli
e em seguida utilizar o angular para adicionar o @ng-bootstrap ao angular e ao seu projeto:
ng add @ng-bootstrap/ng-bootstrap ou
ng add @ng-bootstrap/ng-bootstrap --project myProject
Como mostra nessa docs.
SOLUÇÃO 3 -
Apague a pasta /node_modules, que é a pasta responsável por guardar suas dependências, em seguida refaça a instalação de todas deps usando npm i --legacy-peer-deps, se a dependência @ng-bootstrap não estiver no arquivo package.json, você deve executar npm i @ng-bootstrap/ng-bootstrap --legacy-peer-deps novamente para instalar e adicionar a dependência ao package.json.
Se nada funcionar, uma quarta saída seria você diminuir a versão do seu node, em alguns casos pessoais de instalação de dependências muito antigas funcionou.
Comment: Obrigado pela explicação. Como era muita informação e como estou começando agora no web desenvolvimento, ficou confuso o retorno do erro. Executei o comando com os parâmetros de legacy, instalou o ng-bootstrap, mas isso ocasionou algumas coisas inesperadas. A primeira é que não consegui fazer funcionar o dito popup dos botões, o segundo problema é que todas as chamadas de diretivas [ngStyle] e [ngClass] pararam de funcionar, o VSCode está acusando que não são propriedades das tag essas diretivas. Você sabe o que tem que fazer para arrumar? Agradeço antecipadamente.
Comment: Esse erro é bem abrangente, sem o log de erro fica complicado te ajudar com mais detalhes, mas talvez a solução 3 seja uma saída.
Comment: Obrigado novamente meu amigo. Eu desisti do ng-bootstrap. Reinstalei novamente o angular, refiz o projeto e parei de inventar. Vou estudar mais um pouco esses frameworks para aprender como funciona.


Given $f(x)=x^2-3x+3$, find the value(s) of $x$ such that $f(x)=13$.

Question: I need to find the values for this problem. I already tried to plug in the $f(x)=13$ and I keep getting the wrong answer. I am not even sure how to start this. The problem is:
Given $f(x)=x^2-3x+3$, find the value(s) of $x$ such that $f(x)=13$.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: This surely means that you would require the quadratic formula. Do you know this formula?
Answer: $f(x) = x^2-3x+3 = 13\\
f(x) - 13 = x^2-3x-10 = 0$
Do you know how to find the factor that polynomial and find its roots?
Comment: Yes, this helps a bit i didn't think to set it equal to 0, but im confused on why you put -13 in the front of the equation
Comment: Because it's the value of $f(x)$ minus $13$.
Answer: You need to solve $$x^2-3x+3=13;$$ that is, $$x^2-3x-10=0,$$ so $$x=\frac{3\pm\sqrt{(-3)^2-4(1)(-10)}}{2(1)},$$ i.e., $x=5$ or $x=-2$.
Comment: @ahmad: if you want to do better then I suggest you find an avatar who looks more in need of intellectual assistance than Einstein and learn how to spell  "amateur". $\ddot{\smile}$.
Comment: it looks like a question have a better chance for getting an answer if the attached profile photo of the OP is beautiful, i have a statistically strong  evidence.
Comment: @RobArthan first i said that, because i knew i will get somebody nervous, secondly even in my country its known that pretty women are treated differently so why are you upset ?
Comment: You're better off raising this in the meta site, @Ahmad, rather than my answer to a rather simple, unrelated question.
Comment: @Ahmad: I am not at all upset, but your comments have nothing to do with the mathematics in Shaun's answer and it would be a kindness if you spelled "amateur" correctly in your profile.


Python question, first if statement not running when bucket_name matches an item in bucket list

Question: #1 Activates Boto for use and directs it to s3 storage
import boto3
s3 = boto3.resource('s3')

#2 Python ask user to create a bucket name
  bucket_name = input("Select a bucket name (must be all lowercase).  ")

#3 Python gathers bucket names within s3 and prints list
for bucket in s3.buckets.all():
    print(bucket.name)
bucket = list(s3.buckets.all())

#4 Checks bucket_name against the names with s3  to see if it matches any names,
informs them if there is a match, and ask to create another name. If the name
doesn't it create a new bucket with new unique name.
if bucket_name in bucket:
    print("The name you selected is already taken, please choose a different name")
    bucket_name = input('Select another bucket name (must be all lowercase).  ')
else:
    print('Your new bucket is named',bucket_name,"!")
    def create_bucket():
        s3_client = boto3.client('s3')
        s3_client.create_bucket(Bucket=bucket_name)
    create_bucket()

Answer: First extract all the buckets names with the following code.
import boto3
s3 = boto3.resource('s3')

bucket_name = input("Select a bucket name (must be all lowercase).  ")

all_buckets = [bucket.name.lower() for bucket in s3.buckets.all()]

Now check for the bucket_name present in it or not.
if bucket_name in all_buckets:
    print("The name you selected is already taken, please choose a different name")
    # Your rest of the logic goes here.

Answer: This will run and search for every entered name using your logic until you quit. Input will automatically be lowered with .lower().
import boto3
s3 = boto3.resource('s3')
bucketNames = [bucket.name for bucket in s3.buckets.all()]

def create_bucket(bucket_name):
    s3_client = boto3.client('s3')
    s3_client.create_bucket(Bucket=bucket_name)

while True:
    bucket_name = input("Write a bucket name (q to quit):  ").lower()
    if bucket_name not in bucketNames:
        print(f'Your new bucket is named {bucket_name}!')
        create_bucket(bucket_name)
    else:
        print("The name you wrote is already taken, try a different name")
        bucket_name = input('Write a bucket name (q to quit):  ').lower()
    if bucket_name == "q" or bucket_name == "quit":
        break

Answer: This should work:
import boto3

def create_bucket(bucket_name):
    s3_client = boto3.client('s3')
    s3_client.create_bucket(Bucket=bucket_name)

bucket_name = input("Select a bucket name (must be all lowercase).")

s3 = boto3.resource('s3')
all_buckets = list(s3.buckets.all())

if bucket_name in all_buckets:
    print("The name you selected is already taken, please choose a different name")
    bucket_name = input('Select another bucket name (must be all lowercase).  ')
else:
    print('Your new bucket is named',bucket_name,"!")
    create_bucket(bucket_name)


Drop Down Menu In Navigation Bar got Hidden

Question: Within the existing navigation bar menu, I want to add and drop down menu on the last menu item. However, by clicking on drop down menu, the menu got hidden be hide html body which looks something like this:

The drop down menu is on Action menu, and it is hidden already when I clicked on it.
Here I what I tried to do:

html,
body {
  background: #f7f7f8
}

.text-white {
  color: #fff !important;
}

section.header {
  padding: 90px 0;
}

.logo {
  line-height: 60px;
  /*position: fixed;*/
  float: left;
  margin: 0 46px;
  color: #FFF;
  font-weight: bold;
  font-size: 20px;
  letter-spacing: 2px;
}

nav {
  /*display: flex;*/
  background: #099cec;
  height: 64px;
  color: #FFF;
  width: 100%;
  line-height: 60px;
}

nav ul {
  line-height: 60px;
  list-style: none;
  background: rgba(0, 0, 0, 0);
  overflow: hidden;
  color: #FFF;
  padding: 0;
  text-align: right;
  margin: 0;
  padding-right: 40px;
  transition: 1s;
}

nav.black ul {
  background: #000;
}

nav ul li {
  display: inline-block;
  padding: 0 40px;
  ;
}

nav ul li a,
nav ul li a:hover {
  text-decoration: none;
  color: #FFF;
  font-size: 16px;
}

.menu-icon {
  line-height: 60px;
  width: 100%;
  background: #000;
  text-align: right;
  box-sizing: border-box;
  padding: 15px 24px;
  cursor: pointer;
  color: #fff;
  display: none;
}

@media(max-width: 786px) {
  .logo {
    /*position: fixed;*/
    color: #FFF;
    top: 0;
    margin-top: 16px;
  }
  nav ul {
    max-height: 0px;
    background: #000;
  }
  nav.black ul {
    background: #000;
  }
  .showing {
    max-height: 34em;
  }
  nav ul li {
    box-sizing: border-box;
    width: 100%;
    padding: 24px;
    text-align: center;
  }
  .menu-icon {
    display: block;
  }
}

  .form-group {
      position: relative;
  }
  .form-control {
    background: #f7f7f8;
    border: 0;
  }
  .has-feedback .form-control-feedback {
    top: 10px;
  }
  .form-control-feedback {
      position: absolute;
      z-index: 2;
      display: block;
      width: 2.375rem;
      height: 2.375rem;
      line-height: 2.375rem;
      text-align: center;
      pointer-events: none;
      color: #aaa;
      top: 0;
      left: auto;
      right: 0;
  }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

      Morakot Package

            <input type="text" class="form-control" placeholder="Find a package">

Upload

Copy Token

Help

            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Action
              </button>

Action

Another action

Something else here

Separated link

What am I missing with my style sheet to make my drop down menu work properly ? Thanks
Comment: Please check what you wrote, it's very confusing. Not correct English.
Comment: make sure z-Index of underlying element has less value than that navigation dropdown.
Answer: If you want to make the dropdown menu to overlap main menu you can add this css
.menu-icon {
    line-height: 60px;
    width: 100%;
    background: #000;
    text-align: right;
    box-sizing: border-box;
    padding: 15px 24px;
    cursor: pointer;
    color: #fff;
    display: none;
    position: absolute;
    left: 0px;
}


Proof of equicontinuity via uniform convergence

Question: I am studying for an entrance exam in August and I am trying to review and cover the real analysis section. I came across this problem on one of the past exams and I am having some trouble with it.
Let $G(x, y)$ be a continuous function on $R^2$ and suppose for each positive
integer $k$, that $g_k$ is a continuous function defined on [0, 1] with the property that $|g_k(y)| \leq 1$ for all $y \in [0, 1]$. Now define
$$f_k(x) := \int_{0}^{1}g_k(y)G(x, y) dy.$$
Prove that the sequence ${f_k}$ is equicontinuous on [0, 1].
So for the problem above, given that $[0,1]$  is compact, I think that it is sufficient to show that {${f_k(x)}$} is uniformly convergent on the interval $[0,1]$. How would I show that {${f_k(x)}$} is uniformly convergent on {${f_k(x)}$}?
Comment: Hint: prove that for each $x$, and $\epsilon >0$ there is a small interval $I_x$ around $x$ such that for all $x' \in I_x$, $0 \leq y \leq 1$, $|G(x',y)-G(x,y)| \leq \epsilon$. Prive that such an $I_x$ is an "interval of $\epsilon$-continuity" for each $f_k$.
Comment: Whoops, I goofed. I accidentally wrote "uniformly continuous" instead of "uniformly convergent" in the last paragraph. My mistake, I fixed it. So do your comments still apply?
Answer: You cannot prove convergence. Instead, take $\epsilon >0$ and  choose $\delta >0$ such that $|G(x,y)-G(x',y')| <\epsilon$ whenever $\|(x,y)-(x',y')\| <\delta$. This is possible because any continuous function on the compact space $[0,1]\times [0,1]$ is unifomly continuous. From this you get $|f_k(x)-f_k(y)| <\epsilon$ whenever $|x-y| <\delta$ which is the definition of equicontinuity.


Basic VPS and DNS / Nameserver questions

Question: I have this situation:

my own domain example.com registered at companyA.com
a cPanel/WHM hosting at companyB.com, where I have the website for example.com.
a new VPS, provided by companyC.com

At companyA.com, I setup the Nameservers of example.com to point to ns1.companyB.com and ns2.companyB.com, and everything works.
Now I need to setup another website on the VPS, and make sub.example.com point to it.
This is my first VPS and I need some basic knowledge:
1) Do I need to change the hostname of the VPS? (currently vpsXXX.companyC.com)
2) Do I need to set the Nameservers on the VPS? To What? I don't want to run my own DNS.
3) At companyB.com I think I should insert an A record for sub.example.com pointing to the VPS IP, right?
The VPS has 1 IP Address, and runs CentOS 6 + CentOS Web Panel
Thank you very much
Comment: Vps ip u have, point your subdomain as an A record in company B
Answer:

Do I need to change the hostname of the VPS?

A system can only have 1 hostname but many DNS names can be pointed towards it, but there is no technical requirement that favours one of those additional DNS records over the current hostname.
If you do change the hostname, just ensure that the reverse DNS records is updated accordingly.

Do I need to set the Nameservers on the VPS?

Normally you should not need to run your own DNS server to manage your domain(s).
But DNS resolving will need to be configured on the VPS so it can do DNS lookups. Typically the VPS will be deployed with correct settings in /etc/resolv.conf already but if not commonly used public DNS services are Google's 188.8.131.52 and 126.96.36.199.

At companyB.com I think I should insert an A record for sub.example.com. pointing to the VPS IP, right?

Yes! As simple as that.
Comment: Ok, I did point #3 and it works!
Also, checked point #2, they are set to Google DNS, so ok.

#1 is still not so clear, though.. let's say I change the hostname to match my own domain.. what should I do to check the reverse DNS?

Thank you!
Comment: Reverse DNS is typically manager though Your hosting provider, check their management console and documentation. From the command prompt `dig -x ` and also don't forget IPv6


jQuery get object's element by the string name of the attribute

Question: $.each ( columns, function ( index, value ){
    var td = document.createElement('td');
    var text = document.createTextNode( data.attr( value ) );
    td.appendChild(text);
    tr.appendChild(td);
});

I have data.
I have value = "name"
I can't do data.name, I need to do the equivalent using the string. I tried  .attr( value ) but that didn't work.
Comment: and if data.name don't work because data it not a object then you can try access via array data['name'] ?
Comment: Possible duplicate of http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable
Comment: can you create fiddle or post what you have and what you want to do with it?
Comment: Welcome to Stack Overflow - Good edit there! Your example was way too long, see [the help center](http://stackoverflow.com/help/mcve).
Comment: @daremachine https://jsfiddle.net/c19y2e27/
Comment: @daremachine this was it. Make it an answer and I'll select it.
Answer: You can access to object properties in two ways.
With [dot] chaining or like an array.
If you have a problem with access to object property or your object property is variable then you use array access.
Simple example
var data = {
    aaa: {
        items: [
            { id: 1, name: "test" },
            { id: 2, name: "test2" }
        ]
    },
    bbb: {
        items: [
            { id: 1, name: "test" }
        ]
    }
};

In example below if you want to set empty array in specific object and your decisive key is a variable then you can't use [dot] chaining because variable is not affected. Then you can use array access.
// set aaa as bbb
var aaa = 'bbb';

// WORK aaa is bbb
data[aaa]['items'] = [];

// DOES NOT WORK PROPERLY aaa is not bbb but still aaa
data.aaa.items = [];

Hope it helps
Comment: Your example does not work. If you type it in your browser console, it will obviously throw an error: `TypeError: undefined is not a function`, because `data[0][name]` is equivalent to `data[0].aaa` and since your object does not have an `aaa` field it returns `undefined`... And trying to read a property of `undefined` throws a `TypeError`. Please check your examples before posting. @James Please check that the answer is actually correct before accepting.
Comment: @Kyll thank you for your advice. I edited it. Now is it complete and what i wanted to say.


How do I deal with this NullReferenceException?

Question: public partial class Form1 : Form
{
    string[] id;

private void button_Click(object sender, EventArgs e)
{
    char[] delimiters = { ',', '\r', '\n' };
    string[] content = File.ReadAllText(CSV_File).Split(delimiters);

    int x = content.GetUpperBounds(0)
    int z = 0;
    int i - 0;

    for (i = 0; i <= x / 3; i++)
        {
            z = (i * 3);
            id[i] = content[z]; // this line gives the error
        }

}
}

I want to get every 3rd value from array content, and put it into array id. This gives a 'NullReferenceException was unhandled' error and suggests I use 'new', but it is not a type or namespace. What should I do here?
They are both string arrays, and the error occurs on the first run so I do not think it is related to exceeding the bounds.
Comment: But you will end up exceeding the bounds, if `x` is evenly divisible by 3.
Comment: Yeah struggling with that now :p i'll try and figure it out myself, if not ill be sure to ask you!
Comment: @Shredder - Every language has basic concepts that need to be grasped, and a question isn't automatically "silly" because the poster is yet to grasp a concept. Note that in some languages (eg MATLAB) the line of code 'id[i] = content[z]' would cause the 'id' variable to be automatically assigned and resized.
Answer: You need to initialize id array before the for loop:
id = new string[x/3];

Answer: This line of code:
string[] id;

is actually creating a null reference.
When you declare an array, you have to explicitly create it, specifying the size.
In your example, you have two alternatives

Determine how big the array will be beforehand, and create the array length
Actually populate a container that manages its own size.

The first option:
int x = content.GetUpperBounds(0)
int z = 0;
int i - 0;

id = new string[x/3];
for (i = 0; i <= x / 3; i++)
    {
        z = (i * 3);
        id[i] = content[x];
    }

The second option:
int x = content.GetUpperBounds(0)
int z = 0;
int i - 0;

List<string> list = new List<string>();
for (i = 0; i <= x / 3; i++)
    {
        z = (i * 3);
        list.Add(content[z]);
    }

id = list.ToArray();

The first option would perform better, as you are only allocating one object.
Admittedly, I tend to disregard performance and use the second option, because it takes less brainpower to code.


Ext js problem setting height dynamicly of a grid when autoHeight is already set

Question: I am trying to toggle the height off a grid when the initial setup has autoheight is true.
I want to be able to toggle the height when the grid becomes bigger then the browser view.
The grid is on a normal page without an ext viewport.
If I try setting a height like this, then I loose the scrollbar.
I can see in firebug that the overflow is set to visible instead off auto.
How can I change that?
mygrid.autoHeight=false;
mygrid.setHeight(200);

If I leave autoHeight is true out of the initial setup of the grid, I have no way to determine the height it needs for the rows.
Does anyone possibly have a solution/workaround for this problem?
Thanks in adv, Richard
EDIT
I think this will work
var scroller = Ext.select("#grid-rekovz div.x-grid3-scroller");
scroller.setStyle('overflow-y','auto');

Comment: Correct me if I'm wrong, but if you leave autoHeight to true, when the data is loaded and doLayout is called the grid will resize to fit all the rows, will it not? It does in all of mine...(though I know "It works for me" is the most unhelpful response ever!)
Answer: If you use autoHeight:true; then you delegate height calculating problems to browser, so you lose control of it. If you use autoHeight:false; then you can change height as you wish, but browser will not added scrollbar to content if it became larger than assigned area.


PHP Accessing property containing *

Question: i am returned an array that looks like this:
array(1) { [0]=> object(stdClass)#176 (1) { ["COUNT(*)"]=> string(1) "1" } }

when var_dump() is executed.
So how would i acceess the count object?
Its
$result[0]->COUNT(*)

but this results in an error?
$result[0]->{COUNT(*)}

does not help either.
Comment: Modify your SQL query to return that value with an alias
Answer: Use brackets:
echo $data->{'COUNT(*)'};

But it's about SQL and I recommend to give an alias to your field, like
SELECT COUNT(*) AS records_count FROM t

PHP Accessing property containing *


Generic variant of bi f a b = (f a, f b)

Question: Is there any type-safe way to write a function
bi f a b = (f a, f b)

such that it would be possible to use it like this:
x1 :: (Integer, Char)
x1 = bi head [2,3] "45"

x2 :: (Integer, Char)
x2 = bi fst (2,'3') ('4',5)

x3 :: (Integer, Double)
x3 = bi (1+) 2 3.45

?
In rank-n-types examples there are always something much simpler like
g :: (forall a. a -> a) -> a -> a -> (a, a)
g f a b = (f a, f b)

Comment: I don't think so.  You'd have to quantify it over all input types, which requires abstracting over typeclass constraints.
Comment: @LouisWasserman, there are some new stuff (ConstraintKinds) which allows to abstract over constraints.
Comment: Okay, I see that, but I don't think you can quantify over the result types like you'd have to.  If it had the form `a -> a`, you could do  `bi :: (cxt a, cxt b) => (forall x . cxt x => x -> x) -> a -> b -> (a, b)`, but I don't think you can automatically get the "type function" from each input to its result type.
Answer: {-# LANGUAGE TemplateHaskell #-}

bi f = [| \a b -> ($f a, $f b)|]

ghci> :set -XTemplateHaskell
ghci> $(bi [|head|]) [2,3] "45"
(2,'4')

;)
Answer: Yes, though not in Haskell. But the higher-order polymorphic lambda calculus (aka System F-omega) is more general:
bi : forall m n a b. (forall a. m a -> n a) -> m a -> m b -> (n a, n b)
bi {m} {n} {a} {b} f x y = (f {a} x, f {b} y)

x1 : (Integer, Char)
x1 = bi {\a. List a} {\a. a} {Integer} {Char} head [2,3] "45"

x2 : (Integer, Char)
x2 = bi {\a . exists b. (a, b)} {\a. a} {Integer} {Char} (\{a}. \p. unpack=p in fst {a} {b} x) (pack<Char, (2,'3')>) (pack<Integer, ('4',5)>)

x3 : (Integer, Double)
x3 = bi {\a. a} {\a. a} {Integer} {Double} (1+) 2 3.45

Here, I write f {T} for explicit type application and assume a library typed respectively. Something like \a. a is a type-level lambda. The x2 example is more intricate, because it also needs existential types to locally "forget" the other bit of polymorphism in the arguments.
You can actually simulate this in Haskell by defining a newtype or datatype for every different m or n you instantiate with, and pass appropriately wrapped functions f that add and remove constructors accordingly. But obviously, that's no fun at all.
Edit: I should point out that this still isn't a fully general solution. For example, I can't see how you could type
swap (x,y) = (y,x)
x4 = bi swap (3, "hi") (True, 3.1)

even in System F-omega. The problem is that the swap function is more polymorphic than bi allows, and unlike with x2, the other polymorphic dimension is not forgotten in the result, so the existential trick does not work. It seems that you would need kind polymorphism to allow that one (so that the argument to bi can be polymorphic over a varying number of types).
Answer: Even with ConstraintKinds, I think the barrier is going to be quantifying over the "type function" from the arguments to the results.  What you want is for f to map a -> b and c -> d, and to take a -> b -> (c, d), but I don't think there's any way to quantify over that relationship with full generality.
Some special cases might be doable, though:
(forall x . cxt x => x -> f x) -> a -> b -> (f a, f b)
 -- e.g. return

(forall x . cxt x => f x -> x) -> f a -> f b -> (a, b)
 -- e.g. snd
(forall x . cxt x => x -> x) -> a -> b -> (a, b)
 -- e.g. (+1)

but given that you're trying to quantify over more or less arbitrary type functions, I'm not sure you can make that work.
Answer: This is about as close as you're going to get, I think:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
module Data.Function.Bi (bi, Fn(..))

bi :: (Fn i a a', Fn i b b') => i -> a -> b -> (a', b')
bi i a b = (fn i a, fn i b)

class Fn i x x' | i x -> x' where
      fn :: i -> x -> x'

Use it like so:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, RankNTypes,
             FlexibleInstances, UndecidableInstances #-}
import Data.Function.Bi

data Snd = Snd

instance Fn Snd (a, b) b where
         fn Snd = snd

myExpr1 :: (Int, String)
myExpr1 = bi Snd (1, 2) ("a", "b")
-- myExpr == (2, "b")

data Plus = Plus (forall a. (Num a) => a)

instance (Num a) => Fn Plus a a where
         fn (Plus n) = (+n)

myExpr2 :: (Int, Double)
myExpr2 = bi (Plus 1) (1, 2) (1.3, 5.7)
-- myExpr2 == (3, 6.7)

It's very clunky, but as general as possible.
Comment: There are several mistakes in this code. First, an instance of `Fn` takes three arguments, which is not the case in `Fn (Plus a)`. Second, the kind of `Plus` is `*` so `Plus a` is invalid. Last, you need `FlexibleInstances` since the type variable `b` appears twice in the `Snd` instance.


Why I can't delete the rows in python?

Question: I am trying to delete the rows with missing values in python and the code runs but with no effect whatsoever. The rows are not deleted.
I've added also a screenshot of my xls file.
This is how my code looks like:
  df = Pandas.read_excel('C:/Downloads/Report.xls')
  engine='python'
  new_df = df.dropna(inplace = true)
  puts new_df.to_string()

I've tried also with:
new_df = df.dropna(axis=0, how="any", inplace=false)
OR
new_df = df.dropna()
IT DOES NOT DELETE THE ROWS.
I get the following result:
Unnamed: 2
0    asset_number
1    WG0000000000
2    WG0000204381
3    WG0000204381
4    WG0000204381
5    WG0000204379
6    WG0000204379
7    WG0000204379
8    WG0000204366
9    WG0000204366
10   WG0000204366
11   WG0000204368
...
Comment: `new_df = df.dropna()` or `df.dropna(inplace = true)`. Can't mix the two - then `new_df` would be `None`. `inplace=false` would not have worked because `false` is not the same as `False` in python (capitalization matters). `puts new_df.to_string()` is not even valid python - what's `puts`? also `new_df.to_string()` would have failed since `new_df` would have been `None` and you would have gotten an `AttributeError`. Please edit the post to include the actual code you're using so that we can help you. Also, is this in python or ruby (the question is tagged with both)?
Comment: @inspectorG4dget I am running ruby but for my code I need pandas and python which are python code. ```puts``` is the ```print``` in ruby.
This is the actual code that I use:
```require 'pandas'
require 'win32ole'
require 'capybara/dsl'

Then(/^I delete all empty rows from the spreadsheet$/) do
  df = Pandas.read_excel('C:/Downloads/Report.xls')
  engine='python'
  new_df = df.dropna(axis=0, how='any')
  puts new_df.to_string()
end```
Thank you in advance!
Answer: First fill the empty rows with NaN and then delete the na value as following:
nan_value = float("NaN")
Convert NaN values to empty string
df.replace("", nan_value, inplace=True)
df.dropna(inplace=True)
print(df)

Before dropping:-

After dropping:-
Comment: Thanks @venkatesh ! It made the replacement but it still did NOT delete the rows.
```  nan_value = Float('NaN', exception: false)
  #Convert NaN values to empty string
  df.replace("", nan_value, inplace=true)
  df.dropna(inplace=true)
  puts (df)```
The outcome:
 Photos                                         Unnamed: 1    Unnamed: 2
0    object                                          file_name  asset_number
1     asset                                                NaN  WG0000000000
Comment: Any other suggestions? Or how to delete the rows that include NaN? Thanks
Comment: # dropping the rows having NaN values
df = df.dropna()

# To reset the indices
df = df.reset_index(drop = True)

# Print the dataframe
df
try this onc# dropping the rows having NaN values
df = df.dropna()

# To reset the indices
df = df.reset_index(drop = True)

# Print the dataframe
df
Try this Once
 @MrMihaiCostache
Comment: When I saved my files it adds also the index column - is there a way to suppress the index column and get only my initial 3 columns?  or just save the result to my original file without the NaN rows?
Comment: df.to_csv('',index=False)

Why I can't delete the rows in python?


How can these two equations be solved by elimination?

Question: In this question, the following two equations were solved using elimination. With a google crash course I sort of get how elimination works, but it seems like these are much too complex to add the left sides together in a way that cancels out x or y.
$$
\frac{3x(3x^2+9)}{2y}
-
\frac{(3x^2+9)}{8y^3}^3
-
y
=
6 \pmod {23}
$$
$$
\frac{(3x^2+9)^2}{(2y)^2}
-
2x
=
12 \pmod {23}
$$
Ultimately I'm trying to figure out any way (the easiest preferably) to reduce these such that x=18, y=10 or x=19, y = 3 in order to convert it to a function in a scripting language.
If elimination is the way to go, what were the steps involved in arriving at the following equation?
$$x^4-48 x^3-18 x^2+13968 x=-86481 \pmod {23}$$
Comment: Polynomial elimination based on resultants is a lot work to do manually. It's best left to a computer: [WA](http://www.wolframalpha.com/input/?i=Eliminate%5B%7B(2*x%2Bx)*(3*x%5E2%2B9)%2F(2*y)-(3*x%5E2%2B9)%5E3%2F(2*y)%5E3-y%3D%3D6,(3*x%5E2%2B9)%5E2%2F(2*y)%5E2-x-x%3D%3D12%7D,%7By%7D%5D)
Comment: In [M2](http://habanero.math.cornell.edu:3690/) `R=QQ[x,y]` `f=3*x*(3*x^2+9)*(4*y^2)-(3*x^2+9)^3-(y+6)*8*y^3;g=(3*x^2+9)^2-(2*x+12)*(2*y)^2;` `factor(resultant(f,g,y))` yields
$(x^2+3)^6(x^4-48x^3-18x^2+13968x+86481)(46656)$. Change `QQ` to `ZZ/23` to do the calculation mod 23: $(x+5)(x+4)(x^2+3)^6(x^2-11x-8)(-11)$.
Comment: @Jan-MagnusØkland That is fantastic! Is there a way to see the steps involved in the arriving at the output? Ultimately I need to programmatically step through this process and it's difficult when the work isn't shown.
Answer: If you would like to see how to get the equation by hand:
Introduce a third variable $$z = \frac{3x^2+9}{2y}$$ We have three equations
$$2yz - 3x^2 = 9\\3xz - z^3 - y = 6\\z^2 - 2x = 12$$
Multiplying the second equation by $2z$ and adding the first eliminates $y$:
$$6xz^2 - 2z^4 - 3x^2 = 12z + 9$$
Substituting for $z^2$ from the final equation gives $$6x(2x + 12)  - 2(2x +12)^2- 3x^2 = 12z + 9\\x^2 - 24x - 297 = 12z$$
Squaring both sides, then substituting for $z^2$ again
$$(x^2 - 24x - 297)^2 = 144(2x + 12)\\x^4 - 48x^3 - 18x^2  +13968x + 86481 = 0$$
Modulo $23$, this reduces to
$$x^4 - 2x^3 + 5x^2 + 7x + 1 \equiv 0 \mod 23$$
Comment: This is exactly what I was looking for. Thank you! You wouldn't happen to know how to get `x=18 or x=19` from your final answer, do you?
Comment: One could apply Ferari's equations, and reduce the answer modulo 23. However, since there are only 23 values that $x$ can be, it is easier just to calculate all 23 values and see which give a 0 result modulo 23. When you do the answer turns out to be 18 and 19.
Answer: If you want to implement the resultant yourself, you can use the Sylvester matrix (see wikipedia).
In M2:
R=ZZ/23[x,y]
f=3*x*(3*x^2+9)*(4*y^2)-(3*x^2+9)^3-(y+6)*8*y^3;g=(3*x^2+9)^2-(2*x+12)*(2*y)^2;
sylvesterMatrix(f,g,y)

yields
$${\tiny \begin{pmatrix}{-8}&
  {-2}&
  -10 x^{3}-7 x&
  0&
  -4 x^{6}+10 x^{4}+7 x^{2}+7&
  0\\
  0&
  {-8}&
  {-2}&
  -10 x^{3}-7 x&
  0&
  -4 x^{6}+10 x^{4}+7 x^{2}+7\\
  -8 x-2&
  0&
  9 x^{4}+8 x^{2}-11&
  0&
  0&
  0\\
  0&
  -8 x-2&
  0&
  9 x^{4}+8 x^{2}-11&
  0&
  0\\
  0&
  0&
  -8 x-2&
  0&
  9 x^{4}+8 x^{2}-11&
  0\\
  0&
  0&
  0&
  -8 x-2&
  0&
  9 x^{4}+8 x^{2}-11\\
  \end{pmatrix} }$$
determinant sylvesterMatrix(f,g,y) gives the same output as resultant(f,g,y).
As for factoring the output
$$-11 x^{16}-x^{15}-3 x^{13}-2 x^{12}-3 x^{11}+7 x^{10}-10 x^{9}+x^{8}+8 x^{7}-6 x^{4}+4 x^{3}+10 x^{2}+10 x+8$$
to $$(x+5) (x+4) ({x^{2}+3})^{6} (x^{2}-11 x-8) ({-11})$$
you probably don't need the whole functionality, just check on $x=-11,\ldots,11$ whether the value is divisible by $23$.


Erro ao compartilhar session do HTTP com socket.io. io.sets "is not valid".

Question: Estou aplicando o passo a passo do livro "Node.js, aplicações real-time" do Caio Ribeiro Pereira. Tudo bem até a parte de compartilhar a express-session do HTTP para o socket.io.
Até onde vejo não tem nada errado, mas quando tento ligar o server, aparece isso:

O server liga e da pra navegar pela aplicação mas cai assim que tento entrar na rota do chat.

Aqui está o meu código referente ao erro da primeira imagem
io.set(function(socket, next) {
    var data = socket.request;
    cookieSec(data, {}, function(err) {
        var sessionID = data.signedCookies[KEY];
        SesMemStore.get(sessionID, function(err, session) {
            if (err || !session) {
                return next(new Error('acesso negado'));
            } else {
                socket.handshake.session = session;
                return next();
            }
        });
    });
});

Seria algum problema de atualização do express ou do socket.io?
Comment: Quanto ao segundo erro, voce esta tentenado enviar as headers depois do conteudo, o que é impossivel pelo HTTP. Quanto ao socket.io / express informe que versao esta usando para podermos saber.
Comment: ^1.2.1 é a versão do meu socket.io. Quanto ao header atrasado, por que isso está ocorrendo já que é um processo que normalmente não é manipulável?
Comment: @OlimonF. esqueci de te marcar
Answer: Creio que essa API do socket.io está deprecada. A solução seria mudar seu uso
do método Server.prototype.set pelo Server.prototype.use, que vai plantar um middleware como aqueles do express.
Há uma versão atualizada dos exemplos do livro do Caio Ribeiro Pereira.
Acho que esse exemplo
demostra o que você está tentando fazer, usando Server.prototype.use:
Encontrei um artigo do socket.io explicando as diferenças desde a versão 0.9,
especificamente no que diz respeito a autenticação, sugiro que dê uma olhada aqui.
O seu código deve funcionar com essa pequena mudança de set para use:
io.use(function(socket, next) {
  var data = socket.request;
  cookieSec(data, {}, function(err) {
    var sessionID = data.signedCookies[KEY];
    SesMemStore.get(sessionID, function(err, session) {
        if (err || !session) {
            return next(new Error('acesso negado'));
        } else {
            socket.handshake.session = session;
            return next();
        }
    });
  });
});

Da documentação do socket.io, traduzida livremente para o português:

Namespace#use(fn:Function):Namespace
Registra um middleware; uma função que é executada para toda conexão (Socket) que chega e recebe como parâmetros o socket e uma função para opcionalmente passar a executar o próximo middleware registrado.

Aqui, Namespace#use(fn:Function):Namespace, significa que isso é um método sobre a classe Namespace, que recebe uma função como argumento e retorna um Namespace, para chaining. É o padrão de retornar o this para poder encadear métodos (outro exemplo seria o superagent: request.get(url).query(query).end(fn);).
Isso pode parecer confuso, porque o objeto io no seu código é uma instância da classe Server, não da classe Namespace. A ideia é que você pode criar vários objetos Namespace, exatamente como você pode criar vários objetos Router no express 4, cada um com o seu próprio conjunto de handlers e middlewares.
Por padrão, Server.prototype.use vai chamar Namespace.prototype.use sobre o Namespace padrão, que maneja as conexões à /. Isso é similar à relação entre o Application e o Router do express.


Line Chart not updating everytime

Question: So I am using Line from react-chartjs-2 and I've added an onClick event to the labels which blur all the lines except the current one.
Here is my onClick function code:
legend:{
             'onClick': function(e, legendItem) {
                var index = legendItem.datasetIndex;
                var ci = this.chart;

                console.log(ci.data.datasets);
                //var alreadyHidden = (ci.data.datasets[index].borderColor === ci.data.datasets[index].accentFadedColor) ? false : true;

                for(var i=0; i< ci.data.datasets.length;i++){
                  if (i !== index) {
                      ci.data.datasets[i].borderColor = ci.data.datasets[i].accentFadedColor;
                  } else if (i == index){
                    ci.data.datasets[i].borderColor = ci.data.datasets[i].accentColor;
                  }
                }

                that.updateValue(index);

                ci.update();

              }

The problem is, the function updates the chart on first click but not after that. Though I can see the updates values with console.log()
Any idea what I am doing wrong?

Update:
So apparently my chart is working fine. Inside the onClick() I'm making call to another function ( which sets state ) which is causing this behavior.
Here's a link to stackblitz
Any advice?
Comment: Can you reproduce this in stackblitz?
Comment: @Justcode updated question
Answer: So apparently, just making the function call inside onClick() but before updating the datasets solved the problem.
I think rendering after setState and canvas update were somehow mixing up.
Here's the updated code:
legend:{
             'onClick': function(e, legendItem) {
                var index = legendItem.datasetIndex;
                var ci = this.chart;
                that.updateValue(index);
                for(var i=0; i< ci.data.datasets.length;i++){
                  if (i !== index) {
                      ci.data.datasets[i].borderColor = ci.data.datasets[i].accentFadedColor;
                      ci.data.datasets[i].lineWidth = ci.data.datasets[i].highlightedWidth;
                  } else if (i == index){
                    ci.data.datasets[i].borderColor = ci.data.datasets[i].accentColor;
                    ci.data.datasets[i].lineWidth = ci.data.datasets[i].fadedWidth;

                  }
                }
              ci.update();                }

Line Chart not updating everytime


Cannot get lines of small length to show up in plot

Question: I am having problems getting segments of small lengths to appear in my plot.
Assuming the following sample data:
x=c(11,22,33,44,55)
y=c(15,23,33,45,57)
z=strptime(20120101:20120105,'%Y%m%d')

If I were to create segments out of this data my segment for the third record does not show up if I want square or butt line ends.  It does show up if I allow my line ends to be round lend=0.
plot(z,x,type='n')
segments(as.numeric(z),x,as.numeric(z),y,lwd=5,lend=2)

If I try this:
segments(as.numeric(z),x,as.numeric(z),y,lwd=5,lend=0)

It shows a circle at 33.  Is there a way to get at the very least a flat line that will appear at 33 (hopefully in base)?
I would have used my actual data which is also doing this when the range is small for instance 33.0005 to 33.0010, but that data is huge and I was hoping solving for when they are identical would also solve for small ranges.
ETA: If lwd=15 the circle looks even more ridiculous.
Maybe segments are not the right way to approach this?
This is for a candlestick chart, so these numbers would represent open and close.  I also have high and low numbers which extend beyond this range and are drawn using lwd=1 under these segments.
Comment: (1) If you ask R to draw a segment of length 0, why would R draw anything? (2) In your real example, surely it's possible that on the scale of your plot, a distance of 0.0005 could be below your screen's resolution?
Comment: I agree, but why does it draw something when the `lend=0`?
Comment: Possibly because in order to create that style of line ending, R is actually plotting a filled circle at an "endpoint"? (I'm honestly not sure.)
Comment: I guess using segments then, is the wrong approach.  Even though record 3 in the above example ranges from 33 to 33, there actually is an occurrence at 33 and that needs to show up on the plot.  Maybe there is a different way to do this like boxplots like Carl mentions below.  I will look into it.
Answer: As @Joran points out, this may well be the "correct" behaviour.
But a kludgy workaround is to simply add an arbitrary small number to the values. This value should be small enough to not "distort" the data, but large enough to show up in your plot, given your plot device resolution.
delta <- pmax(0.2, y - x)

plot(z,x,type='n')
segments(as.numeric(z),x ,y1 = y + delta, lwd=10, lend=1)

PS. I advise against this.  You have been warned.
Comment: Maybe you will get the desired result using `boxplot` ?
Comment: @thequerist Why don't you just plot a symbol at the start and end point of each line?
Comment: +1 for advising against it.  As I always ask: What is the problem you are trying to solve?  That is: what exactly do you want to show in your graph?  Is there some underlying relationship between your X and Y data that you're looking for?  Is it more interesting or less interesting when X==Y ?   Answer those and you can figure out what the graph should emphasize.
Comment: I also have an issue with tampering with the data.  This portion would represent the open and close part of a candlestick chart.  So if I put nothing there, one will not have the open/close quote information for that day.  I also have different sets of data with different ranges so this solution would also require changing the `pmax` value for each set of data, although that should not be too much of a problem.  I was hoping there would be a clean way to do this.
Comment: Carl, I am going to give this a try.
Answer: Base graphics does supply rect.  And in fact, it does what you want.  Using your definitions above.
xdiff <- max(as.numeric(z)) - min(as.numeric(z))
segwidth <- xdiff/50

plot(z,x,type='n')
rect(z-segwidth/2, x, z+segwidth/2, y, col="black")

Answer: Given the edits to your question, I suspect the way to go about this is to plot points to indicate your open and close, and a segment to indicate the range.
In this way, if your open and close points are identical (or close), you get a symbol at the correct point.
x <- strptime(20120101:20120105,'%Y%m%d')
y1 <- c(11,22,33,44,55)
y2 <- c(15,23,33,45,57)

r <- range(c(y1, y2))

plot(c(x, x), c(y1, y2), type="n", xlab="Date", ylab="y")
points(x, y1, pch=18)
points(x, y2, pch=18)
segments(as.numeric(x), y0=y1, y1=y2)

Answer: There's something a little odd about "square" lineend
library(grid)
epsilon <- 1e-4
grid.newpage()
grid.points(x=c(0.5-epsilon,0.5+epsilon), y=c(0.5,0.5), pch="+", gp=gpar(cex=2), def="npc")
grid.segments(0.5-epsilon, 0.5, 0.5+epsilon, 0.5, gp=gpar(lineend="square",lwd=50, alpha=0.2))
grid.segments(0.5-epsilon, 0.5, 0.5+epsilon, 0.5, gp=gpar(lineend="round",lwd=50, alpha=0.2))
grid.segments(0.5-epsilon, 0.5, 0.5+epsilon, 0.5, gp=gpar(lineend="butt",lwd=50, alpha=0.2))

the behavior has a jump at epsilon = 0,
 for epsilon=1e-4 vs
 for epsilon=0
As a workaround, I would draw rectangles instead of lines; they always have at least one linewidth.
grid.newpage()
grid.rect(x=0.5, y=0.5, width=0.01, height=0, gp=gpar(fill="black", col="red", lwd=10, linejoin="mitre"))


How to minimize the memory used at spring MapJobExecutionDao

Question: I took a heapdump from my app and I can see 3 objects that are consuming a lot memory
org.springframework.batch.core.repository.dao.MapJobExecutionDao: 124MB
org.springframework.batch.core.repository.dao.MapStepExecutionDao: 120MB
org.springframework.batch.core.repository.dao.MapExecutionContextDao: 92MB
What can I do to minimize the use of the memory of these objects?
Thanks?
Answer: Don't use them :)  Those are essentially HashMaps that will grow as long as your java process is running.  Per the javadoc for the MapJobRepositoryFactoryBean the Map based job repository isn't intended for production use.
Comment: Those classes have nothing to do with scheduling/orchestration.  Use HSQLDB configured in memory and configure a task to run delete scripts from it periodically...
Comment: so... what do I use? Do you think if I use spring-ehCache it get better?
Comment: I can see a clear method but I do not know how to call it... http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/repository/dao/MapJobExecutionDao.html#clear--
Comment: how about to use Quartz?


How can I disable future dates?

Question: I am developing a custom module, where I need to disable future dates in the date pop-up. How can I do this?
Answer: This can be achieved by adding an attribute max
$form['date'] = [
  '#title' => $this->t('Date'),
  '#type' => 'date',
  '#attributes' => [
    'type' => 'date',
    'min' => '-25 years',
    'max' => 'now',
  ],
  '#date_date_format' => 'd/m/Y',
];

Reference: https://api.drupal.org/comment/61733#comment-61733
Answer: $form['birthDate'] = array(
        '#type' => 'date_popup',
        '#title' => t("Birth Date"),
        '#date_format' => 'Y-m-d',
        '#date_year_range' => '-100:0',
        '#datepicker_options' => array('maxDate' => '-1 day' ),
        '#date_label_position' => 'invisible',
        '#required' => TRUE,
    );

Comment: Why did you post the code here?
Comment: Can you expand on how this addresses the problem?  Thanks.

How can I disable future dates?


xcode 9 crashes when opening storyboard created with xcode 8

Question: xcode 9 crashes 100% of the time while opening a storyboard created by xcode 8 on high sierra.
This happens on every project.
Error message was :
"There can only be one document registered with a given URL"
Answer: The fix for me was to :

Cleaning build folder
Clean, delete derived data
Delete saved state
Reboot with reopening windows
Create new single view application
Open storyboard.

Now you should be able to open your storyboards again
Answer: Create a new single view application, open the storyboard there, and then go back to your original project and it should work.


Android common Java class best practices

Question: I am building a new project which uses some Java class from my other projects. I just found a bug in one of my file and I have to fix it everywhere.
Is there a way or best practices to solve this issue.
I have now these projects:

Project A (game)
Project B (game)
Project C (tutorial app)

in each projects I have these common classes:

Settings.java
Progress.java

Now I copy these files to each projects. All these files are identical and other than the bug I just found, I do not have to change them.
Thanks
Answer: How about making your own Android Library Project and linking to it from the projects where you are willing to use it.
Here, take a look. Explanation of different kind of projects you can create.
Comment: and how do I do that with Android Studio 1?
Comment: There's a great Vogella tutorial [here](http://www.vogella.com/tutorials/AndroidLibraryProjects/article.html).
Comment: @Olaia That is using Eclipse
Comment: You can create any kind of Android app or library with either IDE.

You even have a wizard on Android Studio. :)


Exhaustively matching a range of integers involving a "larger than" case

Question: Consider a Rust program with a built-in integer constant const N: u64 and a runtime integer value x: u64. I would like to match on x such that values x < N each get an individual special case. Additionally there should be a single case for x == N and one for x > N respectively. My first attempt looked like this:
const N: u64 = 3;

match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N => println!("Equal"),
    _ => println!("Larger"),
}

This works, but it has the following shortcoming: Imagine I increase the value of the constant to N = 4 but forget to add the new special case x = 3. The code above will not catch this at compile-time, because the last match pattern (_) covers the forgotten case too and the code breaks silently. So I'm looking for a solution that has this kind of compile-time guarantee.
To achieve this, the last case should only match x > N instead, so I tried using an if condition:
match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N => println!("Equal"),
    _ if x > N => println!("Larger"),
}

But now I get an error from Rust that the match is not exhaustive, which I think is due to the compiler not being clever enough to analyze the if condition. It is clever enough to analyze ranges though, but I don't know how I can express that last case as a range. It would have to be something like (N+1)..=u64::MAX, but that does not actually compile because of the plus sign.
My best solution so far is using a nested match as shown below. This seems to work and also gives the desired compile-time error when N is changed, but I wonder if there is a more elegant solution to this.
match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N..=u64::MAX => match x {
        N => println!("Equal"),
        _ => println!("Larger")
    }
}

Comment: "due to the compiler not being clever enough to analyze the if condition." Not quite; the semantics of match guards is that they are always considered fallible, even `if true`. The reasoning is that match guards that can't fail are usually pointless – you could just as well remove them. So the compiler _should_ not analyze the if condition, regardless of how smart it is.
Answer: You can do it like this:
match x {
    0 => println!("Special case for 0"),
    1 => println!("Special case for 1"),
    2 => println!("Special case for 2"),
    N => println!("Equal"),
    N.. => println!("Larger"),
}

Playground


Filtering DynamoDB Streams events for a specific field change

Question: I'm interested in value changes of a specific (numeric) field/column (say "count") of a DynamoDB table.
I know that I could write a Lambda that, once triggered, compares the new image with the old one and then decides whether it is the case of actually doing something or not. But, since my table collects a sort of status updates and only a few of them are actually significant for my trigger, in such a setting, the Lambda would be invoked pointlessly most of the times (and, moreover, I would be charged money for having invoked the Lambda).
So I want to filter the DynamoDB Stream events and, according to the docs, it should be possible (even if no example for similar cases is given).
My problem is that I cannot find how to write the equivalent of OldImage['count'] != NewImage['count'] in the filter pattern.
Here is an example of how this part of my SAM template should appear.
CountChangeDetector:
    Type: 'AWS::Serverless::Function'
    Properties:
      CodeUri: src/
      Handler: trigger.lambda_handler
      Runtime: python3.8
      FunctionName: "CountChangeDetector"
      AutoPublishAlias: live
      Events:
        Stream:
          Type: DynamoDB
          Properties:
            Stream: !GetAtt MyTable.StreamArn
            BatchSize: 10
            StartingPosition: TRIM_HORIZON
            FilterCriteria:
              Filters:
                - Pattern: '{"OldImage": {"count": [ { "anything-but": [ {"NewImage": {"count"}} ] } ]}}'

Of course, the way I've defined the pattern is incorrect and I get an error.
So, how shall the pattern be defined?
Answer: Most likely, you have already found your answer, but still adding for any newbie searching for the same.
Unfortunately the answer is "No". You cannot compare two two fields of the stream data with each other. Because, there is no "numeric not equal" operator available for pattern.
The work around would be writing the logic in the pre-processing of lambda function before calling the handler.
Comment: Yeah, that's exactly what I did in the end (checking if the count has changed and storing that info as a bool that trigger the trigger), but I'm not completely satisfied with this approach. Is there anything like "string not equal"? If so, I could cast that number to string and still exploit the initial idea…
Comment: What do you mean by *writing the logic in the pre-processing of lambda function*?


Discussing one-one onto.

Question: f: R2 to R2. f(x,y)= (e^x cosy, e^x siny). f is:
1. not one-one on all of R2.
2. one-one on some neighbourhood of any point in R2.
3. an onto map.
4. such that neighbourhood of any point surjects onto R2.
For 1-1, f1=f2 should give (x1,y1)=(x2,y2). But I couldn't go far with this method. Instead if I see that sin, cos are periodic functions, so, this would be a many-one function. But since their period is 2pi, this function would be 1-1 in pi neighbourhood of any point. So, 1st and 2nd are true.
Regarding onto, e^x cosy=a, e^x siny =b, e^2x=a2+b2. Does it imply that the range is an exponent curve? So whole of R2 won't be covered? Even if we make an open ball around any point, all of it won't represent the range. So, 3rd and 4th are incorrect.
Seeking your confirmation regarding my explanation.
Comment: x is the log f the radius of the circle your point is on (with center 0) and y is the angle for your point.
Answer: For 1-1, what is $f(0,0)$ and $f(0,2\pi)$?
For 1-1 in a neighbourhood around any point, yes, $(\cos(y),\sin(y))$ is 1-1 in a neighbourhood around any given $y$, since $cos(y)$ is 1-1 in a neighbourhood of every point that is not an integer multiple of $\pi$, but at those points, $\sin(y)$ is clearly 1-1 in a small enough neighbourhood, and $e^x$ is 1-1 for all $x$-values, so as long as your neighbourhood of $(x, y)$ doesn't span too much in the $y$-direction, you're good.
Regarding onto, can we ever have $f(x, y) = (0,0)$?

Discussing one-one onto.


Can I enable the Honeypot module for comments on the Advanced Forum pages?

Question: How do I configure the Honeypot module to work on comment pages for the Advanced Forum module?
I enabled the Honeypot module, checked Blog entry node form and Forum topic node form in Node forms and Comment forms.
Answer: The module configuration page is just the one on /admin/config/content/honeypot, which has the following settings.

If you expect to see a difference on protected forms, there isn't anything visible. The module creates a form element that is hidden to users, but tools that automatically fill the form will fill also that, making clear they aren't human users.
The module also doesn't accept a form submission before time limits seconds are passed from the moment the form is rendered.
If you are testing a form using a user account with the administrator role, that has the Bypass Honeypot protection permission, so you will not see any hidden form element even watching at the HTML markup of the page.


Unable to Start Activity ComponentInfo when Starting a New Activity

Question: {I know there's already a whole bunch of questions like this, but I can't see any problems that related to my program.}
I have an Android App that is supposed to take a name from a EditText and put it in a TextView in another activity. It previously worked, but then I wanted it to start another activity if the EditText's value was equal to "ANDROID". However, now the app crashes whenever I try to start either activity.
First Activity:
package net.timtim17.dev.android.fun.nametag;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText et = (EditText) findViewById(R.id.editText1);
    Button submit = (Button) findViewById(R.id.button1);
    submit.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            String text = et.getText().toString();
            if(text.equals("ANDROID")){
                Intent android = new Intent(MainActivity.this, AndroidNameTag.class);
                startActivity(android);
            }else{
                Intent intent = new Intent(MainActivity.this, NameTag.class);
                intent.putExtra("name", text);
                startActivity(intent);
            }

        }

    });
}

}

NameTag Activity:
package net.timtim17.dev.android.fun.nametag;

import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

public class NameTag extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tag);

    TextView tv = (TextView) findViewById(R.id.textView2);
    tv.setText(getIntent().getExtras().getString("name"));
}
}

AndroidNameTag Activity:
package net.timtim17.dev.android.fun.nametag;

import android.app.Activity;

import android.graphics.drawable.AnimationDrawable;

import android.os.Bundle;
import android.widget.ImageView;

public class AndroidNameTag extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_android);

    ImageView iv = (ImageView) findViewById(R.id.imageView1);
    iv.setBackgroundResource(R.anim.animation);
    AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
    anim.start();
}
}

LogCat Error:
10-26 11:26:35.602: E/AndroidRuntime(2900): FATAL EXCEPTION: main
10-26 11:26:35.602: E/AndroidRuntime(2900): java.lang.RuntimeException: Unable to start activity ComponentInfo{net.timtim17.dev.android.fun.nametag/net.timtim17.dev.android.fun.nametag.NameTag}: java.lang.NullPointerException
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.os.Looper.loop(Looper.java:137)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.ActivityThread.main(ActivityThread.java:5103)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at java.lang.reflect.Method.invokeNative(Native Method)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at java.lang.reflect.Method.invoke(Method.java:525)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at dalvik.system.NativeStart.main(Native Method)
10-26 11:26:35.602: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException
10-26 11:26:35.602: E/AndroidRuntime(2900):     at net.timtim17.dev.android.fun.nametag.NameTag.onCreate(NameTag.java:15)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.Activity.performCreate(Activity.java:5133)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-26 11:26:35.602: E/AndroidRuntime(2900):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-26 11:26:35.602: E/AndroidRuntime(2900):     ... 11 more

MainActivity Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="16dp"
    android:text="@string/main_text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="14dp"
    android:text="@string/submit_button" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_alignTop="@+id/button1"
    android:ems="10"
    android:inputType="textPersonName" >

    <requestFocus />
</EditText>

Comment: `Caused by: java.lang.NullPointerException
10-26 11:26:35.602: E/AndroidRuntime(2900):     at net.timtim17.dev.android.fun.nametag.NameTag.onCreate(NameTag.java:15)` Line 15 seems to be `TextView tv = (TextView) findViewById(R.id.textView2);` so textView2 probably does not exist in the layout activity_android.
Comment: post your `R.layout.activity_tag` xml file
Answer: Turns out that I accidently switched the layouts for the NameTag Activity and the AndroidNameTag Activity, and removed the 2nd TextView in the wrong activity...


Formula for 95% confidence interval for $R^2$

Question: I googled and searched on stats.stackexchange but I cannot find the formula to calculate a 95% confidence interval for an $R^2$ value for a linear regression. Can anyone provide it?
Even better, let's say I had ran the linear regression below in R. How would I calculate a 95% confidence interval for the $R^2$ value using R code.
lm_mtcars <- lm(mpg ~ wt, mtcars)

Comment: @ZERO: that will work in a simple linear regression, that is, with a single predictor and an intercept. It won't work for multiple linear regression with more than one predictor.
Comment: Well you know the relationship between the correlation $r$ and $R^2$ is that you are squaring the correlation coefficient to get $R^2$ so why not calculate the confidence interval for $r$ and then square the lower and upper limits of the interval?
Comment: @StephanKolassa, very true! I guess I was basing it off of his `R` code where there is only one regressor but that is a very good point to clarify.
Comment: @kjetilbhalvorsen: The OP should write "for the *true* $R^2$", which is well defined.
Comment: You can e.g. use a very small R function https://github.com/mayer79/R-confidence-intervals-R-squared based on properties of the non-central F-distribution.
Comment: $R^2$ is not a population parameter so is not clear what would be the meaning of the confidence interval ... (exception if you have sampled from a multinormal population)
Comment: http://www.danielsoper.com/statcalc/formulas.aspx?id=28
Answer: You can always bootstrap it:
> library(boot)
> foo <- boot(mtcars,function(data,indices)
        summary(lm(mpg~wt,data[indices,]))$r.squared,R=10000)

> foo$t0
[1] 0.7528328

> quantile(foo$t,c(0.025,0.975))
     2.5%     97.5%
0.6303133 0.8584067

Carpenter & Bithell (2000, Statistics in Medicine) provide a readable introduction to bootstrapping confidence intervals, though not specifically focused on $R^2$.
Comment: (+1) It might be of interest that the approximate formula quoted by @Durden, with $n=32$ and $k=1$ gives the interval $(0.546,0.960)$. It would be almost perfectly correct if we drop the factor of $2$ multiplying the SE in that formula!
Comment: May also be worth noting that you can get other types of confidence interval (e.g., BCa) from the bootstrap resampling distribution using `boot.ci()`.
Answer: In R, you can make use of the CI.Rsq() function provided by the psychometric package. As for the formula it applies, see Cohen et al. (2003), Applied Multiple Regression/Correlation Analysis for the Behavioral Sciences, p. 88:
$SE_{R^{2}} = \sqrt{\frac{4R^{2}(1-R^{2})^{2}(n-k-1)^{2}}{(n^2 - 1)(n+3)}}$
Then, the 95% CI is your $R^{2} \pm 2 \cdot SE_{R^{2}}$.
Comment: (1) $(1-R^2)$ is squared in your reference. (2) It is important to note that "$R^2$" is intended to be the sample value rather than the population value (which clearly is what "$R^2$" refers to in the question, whence the potential for confusion). (3) It is also important that this is only an asymptotic ("large-sample") result, giving "adequate approximations" for "$n-k-1 \gt 60$".  (I believe $k+1$ counts an intercept plus the number of independent variables.) It would be useful to see a worked example supported by simulation, because this interval looks too wide.
Comment: According to Wishart (1931) the formula is unsuitable for nonnormal distributions.
Comment: Is there an approximation available for non-normal distributions?