Why is this series proven to converge with this approxiamation?

Question: I am given the series
$$ \sum_{n=2}^{\infty} \frac{n^2}{(n^4-1)} $$
and asked if it diverges or converges. Why does the integral
$$\int \frac{1}{x^2} \, dx$$
Find it converges? I thought $$\frac{1}{x^2}<\frac{1}{(x^2-1)}$$
so the lower function converging has no bearing on if the greater function converges?
Comment: 1. There are several criteria. 2. The bound $n^4-1>n^\frac{7}{2}$ also holds.
Comment: @user112167 well, $$\frac{x^2}{x^4-1}=\frac{1}{x^2-\frac{1}{x^2}}.$$ So I'm not sure what you mean by your above comment.
Comment: $\frac {n^2}{n^4-1}=\frac{1}{2 \left(n^2+1\right)}+\frac{1}{2 \left(n^2-1\right)}$ helps
Comment: Also
$$ \frac{n^2}{n^4-1} = \frac{1}{2}\left(\frac{1}{n^2+1}+\frac{1}{n^2-1}\right)=\frac{\frac{1}{2}}{n^2+1}+\frac{\frac{1}{4}}{n-1}-\frac{\frac{1}{4}}{n+1}$$
so by telescopic sums
$$ \sum_{n\geq 2}\frac{n^2}{n^4+1} = \frac{3}{4}+ \frac{1}{2}\sum_{n\geq 2}\frac{1}{n^2+1}=\frac{1}{2}+\sum_{n\geq 1}\frac{1}{n^2+1}<\frac{1}{2}+\frac{\pi^2}{6} $$
Comment: " I thought $\frac{1}{x^2}<\frac{1}{(x^2-1)}$" Wait. What does this have to do with anything? Did you mean to write: "I thought $\frac{1}{x^2}<\frac{x^2}{(x^4-1)}$..."
Comment: I thought that $$x^2/(x^4-1)$$ could be approximated by $$1/(x^2-1)$$
Answer: We have
$$\sum_{n=2}^\infty \frac{n^2}{n^4-1}<\sum_{n=2}^\infty \frac{n^2}{n^4-n^3}=\sum_{n=2}^\infty \frac{1}{n(n-1)}=1$$
What you are asking about is basically this:
$$\sum_{n=2}^\infty \frac{n^2}{n^4-1}\text{ converges}\Leftrightarrow \sum_{n=2}^\infty \frac{1}{n^2}\text{ converges}$$
since
$$\lim_{n\to\infty}\frac{n^2}{n^4-1}\cdot \frac{n^2}{1}=1$$
But we also have
$$\sum_{n=2}^\infty \frac{1}{n^2}\text{ converges}\Leftrightarrow \int_1^\infty \frac{1}{x^2}dx\text{ converges}$$
by the integral test. We conclude
$$\sum_{n=2}^\infty \frac{n^2}{n^4-1}\text{ converges}\Leftrightarrow \int_1^\infty \frac{1}{x^2}dx\text{ converges}$$


How to restrict IAM policy to not allow stop/terminate an EC2 instance but can create new instances?

Question: I want to create IAM policy which will restrict group or users to stop/terminate two used EC2 instances but they can create their own EC2 instances.
I used following policy statement for this:

{
        "Sid": "Stmt1449662318000",
        "Effect": "Allow",
        "Action": [
            "ec2:*"
        ],
        "Resource": [
            "*"
        ]
    },
    {
        "Sid": "Stmt1449662339000",
        "Effect": "Deny",
        "Action": [
            "ec2:*"
        ],
        "Resource": [
            "arn:aws:ec2::myAcctId:instance/i-4a36178ef",
            "arn:aws:ec2::myAcctId:instance/i-9e3fb747"
        ]
    }

But this is not working correctly. It allows other user/group to stop my already used 2 instances.
How to achieve this?
Answer: I was able to achieve this by adding following statement to policy:

{
      "Action": "ec2:*",
      "Effect": "Allow",
      "Resource": "*",
      "Condition" : {
                    "StringNotEquals" : {
                        "ec2:ResourceTag/Name" : [
                                        "UAT-Environment",
                                        "INT-Environment"
                                      ]
                            }
                    }
    }


Hover a div and modify the CSS of another div using JS inside of the same row in a table with 3 rows using same classes

Question: I have a HTML table that includes 3 rows.
Each row has a column circle and a column panel (sometimes the panel column is before the circle, sometimes after).

When hover panel, panel goes left or right from 10px.
    table .panel-left:hover,
    table .panel-left:focus {
      margin-right: -10px;
      margin-left: 10px;
    }

    table .panel-right:hover,
    table .panel-right:focus {
      margin-left: -10px;
      margin-right: 10px;
    }

With javascript, i want to modify the css of circle when hover the panel-left or panel right
    $(document).ready(function() {

      $(".panel-left").mouseover(function(){
        $(".circle").css("border", "5px solid #16a085");
      });

      $(".panel-left").mouseout(function(){
        $(".circle").css("border", "3px solid #cccccc");
      });

      $(".panel-right").mouseover(function(){
        $(".circle").css("border", "5px solid #16a085");
      });

      $(".panel-right").mouseout(function(){
        $(".circle").css("border", "3px solid #cccccc");
      });

    });

This is working well, except than all the circle are modified, when it should be only the circle inside of the row that contains the panel hovered.
What should be the javascript?
Comment: Can you make a fiddle?
Answer: Is this what you want?:
HTML:

CSS:
.circle, .panel-right, .panel-left {
   background-color:red;
   width:200px;
   height:200px;
   border-radius:100%;
   border:3px solid #cccccc;
}

.panel-right, .panel-left {
    width:200px;
    height:200px;
    background-color:green;
}

.panel-left:hover,
.panel-left:focus {
  margin-right: -10px;
  margin-left: 10px;
}

.panel-right:hover,
.panel-right:focus {
  margin-left: -10px;
  margin-right: 10px;
}

Javascript
$(document).ready(function() {
    $('.panel-left, .panel-right').mouseover(function() {
        $(this).closest('td')
               .siblings('.circle-td')
               .find('.circle')
               .css('border', '5px solid #16a085');
    }).mouseout(function() {
        $(this).closest('td')
               .siblings('.circle-td')
               .find('.circle')
               .css('border', '5px solid #cccccc')
    });
});

And here is the fiddle
Comment: Thank you so much, I just tried it and that worked out perfectly!! You are a genius!!!
Comment: Thank you!

Except than it is when the user hover on then panel than the circle should be modified, otherwise it is a simple CSS hover modification
Comment: My apologies. The code and fiddle have been updated to suit your needs.


Proving divisibility of a polynomial by a square of a polynomial.

Question: I need to prove that a polynomial $f \left( x \right) \in \mathbb{Q} \left[ X \right]$ is divisible by a square of a polynomial iff $f$ and $f'$ have a greatest common divisor of positive degree.
I have no idea where to start, except that I have to use the properties of Polynomial Rings as Euclidean Domain.
Comment: The easy direction: Suppose there is some polynomial $g(x)$, which is not a unit,such that $g(x)^2k_1(x)=f(x)$. Then take derivative on both side of the equation to get $2g(x)g'(x)k_1(x)+g(x)^2k_1'(x)=f'(x)$. Well this says that g(x) is a common factor of $f(x)$ and $f'(x)$.
Comment: You can find a proof for this in any standard algebra textbook. I came across its proof in the book Algebraic Number Theory and Fermat's Last Theorem by Ian Stewart and David Tall. It's theorem 1.5 in the fourth edition.
Answer: Let $q(x)$ be an irreducible common divisor of $f$ and $f'$. Division of $f$ by $q^2$ provides
$$
f=kq^2+r, \quad \text{with}\,\,\,\deg r<\deg q^2
$$
and as $q$ divides $f$, then $q$ divides $r$, and thus
$$
f=kq^2+r_1q, \quad \text{with}\,\,\,\deg r_1<\deg q.
$$
Differentiating we obtain
$$
f'=k'q^2+(2kq'+r_1')q+r_1q'
$$
But since $q$ divides $f'$, then $q$ divides $r_1q'$, and since $q$ is irreducible, then $q$ divides $q'$or $r_1$. But, $\,deg q>\deg q'$, and hence $q$ does not divide $q'$, as $q'\ne 0$. Hence $q$ divides $r_1$, which implies that $r_1\equiv 0$, since $\deg r_1<\deg q$.
Comment: "Division of $f$ by $q$" should be "Division of $f$ by $q^2$" right? Also, "q divides f', then q' divides $r_1q$' " should be "q divides f' then q divides $r_1q$' "right?
Comment: @mathnoob Yes - I corrected my answer. Thanx!
Answer: Hint: One direction is easy. For the other direction, note that $f$ and $f'$ have a greatest common divisor of positive degree iff $f$ and $f'$ have an irreducible common divisor.
Make sure to pinpoint where working over $\mathbb{Q}$ enters in your argument.


Exportação query para EXCEL em PHP erro UTF-8

Question: Quando faço a exportação dos dados o UTF-8 não está agindo, como posso resolver isto?
// Formatação do header do arquivo
header ("Expires: Mon, 18 Nov 1985 18:00:00 GMT");
header ("Last-Modified: ".gmdate("D,d M YH:i:s")." GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header ("Content-type: application/x-msexcel");
header ("Content-Disposition: attachment; filename=Dados.xls");

header ("Content-Type: text/html; charset=UTF-8");
echo "\xEF\xBB\xBF";

?>

            Fazenda
            Talhão
            Data
            Deficit (mm)
            Irrigação (mm)
            Irrigação (h)
            Velocidade (%)
            Pluviometria (mm)
            Temp Min (°C)
            Temp Med (°C)
            Temp Max (°C)

        <?php
            while ($Dado = $conexao->busca($Dados))
            {
                ?>

                    <?=$Dado['Nome_Fazenda']?>
                    <?=$Dado['Nome_Parcela']?>
                    <?=$Dado['Data_Irr']?>
                    <?=$Dado['Deficit']?>
                    <?=$Dado['IrrMM']?>
                    <?=$Dado['IrrHS']?>
                    <?=$Dado['Velocidade']?>
                    <?=$Dado['Pluviometria']?>
                    <?=$Dado['Temp_Min']?>
                    <?=$Dado['Temp_Med']?>
                    <?=$Dado['Temp_Max']?>

                <?php
            }
        ?>

Comment: o problema ocorre nos elementos que vêm do bd ou todos, incluindo os que vc digitou à mão?
Comment: em todo, vou colocar uma imagem para você ver como fica, ainda vem um símbolo no começo.
Comment: @WeesSmith fiz a alteração.
Comment: tem algo antes desses headers?
Comment: Sim, uma query para buscar na variável $dados.
Comment: os headers tem que serem os primeiros de tudo, coloca eles isolados no topo da pagina logo abaixo do <?php
Answer: Os header()s devem vir sempre no topo da página, antes de qualquer coisa:
<?php
    header ("Expires: Mon, 18 Nov 1985 18:00:00 GMT");
    header ("Last-Modified: ".gmdate("D,d M YH:i:s")." GMT");
    header ("Cache-Control: no-cache, must-revalidate");
    header ("Pragma: no-cache");
    header ("Content-type: application/x-msexcel");
    header ("Content-Disposition: attachment; filename=Dados.xls");
    header ("Content-Type: text/html; charset=UTF-8");

Comment: Beleza, vou verificar.
Comment: Consegui amigo, obrigado!
Comment: Fiz a alteração, mesmo assim não deu certo.
Comment: deixa só o `header("charset=UTF-8")` e tira os outros para ver
Comment: Na página aparece tudo certo, quando está exportando para o Excel que não está dando certo
Comment: da uma olhada aqui https://stackoverflow.com/questions/4164719/utf-8-encoding-xml-in-php


Finding Fourier Coefficients given $f(x) = \left\{ \begin{array}{rcl} -4\,x & \text{if} & -\pi<x<0 \\ 4\,x & \text{if} & 0<x<\pi \end{array}\right.$

Question:
The Fourier series of the function
  $f(x) =
\left\{
\begin{array}{rcl}
 -4\,x & \text{if} & -\pi<x<0 \\ 4\,x & \text{if} & 0<x<\pi
\end{array}\right.$
is given by
  $f(x) \sim c_0 - \displaystyle
   \sum\limits_{n=0}^\infty c_n\;\cos\big((2\,n+1)\,x\big) -
   \sum\limits_{n=1}^\infty b_n\;\sin\big(n\,x\big)$

I'm asked to find $c_0$, $c_n$, and $b_n$.
Given that this is an even function, we get $b_n =0$.
I have already found $c_0=4\pi$, but I am having trouble finding $c_n$.
Here is where I get confused. The general formula that I am given to find $c_n$ is given as
$$c_n=\frac{2}{L} \int_{0}^{L} f(x)\cos(\frac{n\pi x}{L})dx$$
where $L$ are the boundary conditions.
However, given that I have $cos((2n+1)x)$, I'm assuming I would have to modify the general formula to accommodate this term.
Solving for $c_n$, I get
$$c_n=\frac{2}{\pi} \int_{0}^{\pi} 4x\cos((2n+1)x)dx$$
$$c_n=\frac{2}{\pi} [\frac{-4\pi(2n+1)\sin(2\pi n)-4\cos(2\pi n)}{(2n+1)^2} -\frac{4}{(2n+1)^2}]$$
$$c_n=\frac{-8}{\pi} \frac{\pi(2n+1)\sin(2\pi n)+\cos(2\pi n)+1}{(2n+1)^2}$$
Apparently this is not correct, so I'm not sure what I'm doing wrong. Any help would be appreciated!
Comment: Why do you have $\cos((2n+1)x)$? Where did that come from?
Comment: Please show additional steps leading to your answer, then we can find the mistake
Comment: $\sin 2\pi n = 0, \cos 2\pi n = 1$
Comment: @Dylan $cos((2n+1)x)$ is given to me in the question.
Comment: How did $2n+1$ become $2n$ in the second line?
Answer: I think you had the correct anti-derivative, but you evaluated the limits incorrectly
$$ c_n = \frac{2}{\pi} \left.\left( -\frac{4x\sin \big((2n+1)x\big)}{2n+1} - \frac{4\cos\big((2n+1)x\big)}{(2n+1)^2} \right)\right|_{x=0}^{\pi} \\
= \frac{8}{\pi} \left(-\frac{\pi\sin \big((2n+1)\pi\big)}{2n+1} - \frac{\cos\big((2n+1)\pi\big)-1}{(2n+1)^2} \right) $$
Since $\sin\big((2n+1)\pi\big) = \sin(\pi) = 0$ and $\cos\big((2n+1)\pi\big) = \cos(\pi) = -1$, this simplifies to
$$ c_n = \frac{16}{\pi(2n+1)^2} $$
Answer: use $-\pi$ and $\pi$ as your boundary conditions, and your period is $L = 2\pi$
$a_n = $$\frac {1}{\pi} \int_{-\pi}^{\pi} f(x)\cos nx\ dx\\
\frac {1}{\pi} \int_{-\pi}^{0} -x\cos nx\ dx + \int_{0}^{\pi} x\cos nx\ dx\\
\frac {2}{\pi}\int_{0}^{\pi} x\cos nx\ dx\\
\frac {2}{\pi}(\frac {x}{n}\sin nx - \frac {1}{n^2} \cos nx)|_0^{\pi}\\
 \frac {4}{n^2\pi}$
If $n$ is odd, and $0$ if $n$ is even.
$a_{2n+1} = \frac {4}{(2n+1)^2\pi}$
Comment: The function is $4x$ not $x$


converting a chi-square with more than one degree of freedom into a pearsons r

Question: I want to run a power analysis for a study using correlations between two continuous variables. Previous research with the variable I am interested in used a Kruskal-Wallis test to look at differences between groups (by converting one variable into a grouping variable). To run my power analysis, I need to somehow convert the chi-square value $X^2(2)=10.44, p<.01$ to an r value. I understand that this is quite simple to do when the chi-square analysis involves only two groups, but is it possible to convert the chi-square to an r value when I have three groups?
Comment: The chi-square value you're asking about is the one from the Kruskal-Wallis test?
Comment: Yes it is. I also have the associated n value.
Answer: I am guessing that the earlier researchers split a continuous variable into 3 categories (a bad idea, but never mind) and you now want to somehow go back to the continuous version.
I don't know a way to do this directly from the $\chi^2$ value, but one thing you could do is assume a distribution for the variable that was split into 3 groups and then, within each group, assign a numeric score (using a suitable random number generator) and then use that.  I'd suggest trying several different sets of values and looking at them all as a sort of sensitivity analysis.
Comment: Are you familiar with the work around converting chi-squares with two groups into correlations- http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2850938/ There seems to be a formula, but I can't access the books referenced to understand it.
Comment: No, but someone else here may be.


Rails3 Autocomplete Gem - Two Different Autocompletes on Same ClassName and Method

Question: I am successfully using the ":scopes =>" option of this gem to return a subset of the rows of the table.  Now I want to create a nearly identical autocomplete, on the same ClassName and Method, with a different scope, for a different view.
The problem is, the first two arguments of autocomplete in the controller are ClassName and Method, and those also create the functional name of the autocomplete function, as it is used in the view and route.  Therefore, both of my autocompletes would have the same name.
Is there a workaround I can use to assign a different name to each of the similar autocompletes?
Example code:
autocomplete :my_class_name, :my_method, :display_value => :my_formatting_method,
:extra_data => [:id], :scopes => [:active_and_special]

def active_and_special
    where("active = ?", true).
    where("special = ?", true).
    order("name  ASC")
end

Then the again for the 2nd one, with the same class-name and method, but a different scope.
Answer: Best workaround I've found is to use "column_name" to override the part of the naming which ordinarily refers to the method - like this:
autocomplete :my_class_name, :foo, :column_name => 'my_method',
  :display_value => :my_formatting_method, :extra_data => [:id],
  :scopes => [:active_and_not_special]

def active_and_not_special
    where("active = ?", true).
    where("special = ?", false).
    order("name  ASC")
end

This has route:
get 'my_class_names/autocomplete_my_class_name_foo'

Whereas the original has route:
get 'my_class_names/autocomplete_my_class_name_my_method'

This allows us to generate a 2nd, different autocomplete, on the same Class and Method as another, with its own unique name.
Having an independent name, vs the 'magic' autogenerated one (to save 1 second of typing?) would prevent this trouble - or am I missing something?
I'll leave this open for a bit to see if anyone has a better solution.


Let $f(z) = \frac{\pi^2}{\sin^2(\pi z)}$. For some $z=n$, show it has a pole of order 2.

Question:
Let $$f(z) = \frac{\pi^2}{\sin^2(\pi z)}.$$
  For some $z=n$, show it has a pole of order 2.

Aside from appear elsewhere, this function is discussed on p188 of Ahlfors.
I can answer the question I posed above by expanding $\sin(\pi z)$ into its power series, taking the square of the series in the denominator, and then using polynomial long division to get the actual Laurent series.
What would be some other, faster ways to achieve the answer? For finding out the order of the pole, I tried to use the definition of a pole to put $f(z)$ in the form
$$
f(z) = \frac{g(z)}{(z-n)^n}
$$
and solve for $n$. Aside from using the knowledge that $1/sin(z)$ is has a pole of order one, how else can we find the order?
Comment: Intuitively, $sin(z)$ can be approximated as $z$  near zero.  Thus one would expect the pole at $z = 0$ to be order 2.  Just a suggestion, I would try writing out the taylor expansion for $\sin^2(\pi z),$ factoring out a $z^2,$ then using the binomial expansion (assuming we are looking around small $z$) to get an expansion for $(\sin^2(\pi z))^{-1}.$
Answer:
For finding out the order of the pole, I tried to use the definition of a pole to put $f(z)$ in the form
  $$
f(z) = \frac{g(z)}{(z-n)^n}
$$
  and solve for $n$.

Good idea, but if you tried exactly what you wrote, you've made a mistake : you use $n$ for two independant things !!!
You want to solve
$$f(z) = \frac{g(z)}{(z-n)^k}$$
Or in other words, to find the smallest $k \in \mathbb{N}$ such that $\lim_{z\to n} (z-n)^kf(z)$ exist and is finite
And this is immediate to answer if you remember that $\sin(z) \sim z  $
Comment: Thanks! This is exactly what I was hoping for.
Comment: Also, should we add that the limit we are looking for exists, is finite, and is also **non-zero**?
Comment: @mathjacks : if the limit is zero, then $k$ is not the smallest. And the limit (for $k$) is finite non-zero if and only if it has a pole of order $k$
Answer: Note that $ \sin(x+iy) = \sin(x)\cos(iy) + \cos(x)\sin(iy) = \sin(x)\cosh(y) - i\cos(x)\sinh(y) $, then this function is complex differentiable at $ x + iy = 0$ as it satisfies the Cauchy-Riemann equations there. Then, the complex derivative must agree with the real derivative at that point, which is $ 1 $. Therefore, we have
$$\sin'(0) = \lim_{z \to 0} \frac{\sin(z) - \sin(0)}{z - 0} = \lim_{z\to 0} \frac{\sin(z)}{z} = 1 $$
which shows that the pole at $ z=0 $ is of order $ 1 $.
Comment: Also a helpful approach. Thank you!


Escada JavaScript

Question: "use strict"
let array = []
function exibeNumero(entrada) {
    for (let i = 0; i < entrada; i++) {
        array.push("#".repeat(i))
    }
    for (const entrada of array) {
        console.log(entrada)
    }
}
exibeNumero(10)

Estou tentando mudar o lado da escada.
Esse é o resultado que estou tendo

Quero inverter o lado dela, ficando assim
Answer: Tente usar esse loop:
for (const linha of array) {
    console.log(linha.padStart(entrada-1, ' '))
}

O método padStart adiciona o caractere passado como segundo parâmetro no início da string, até que ela atinja o tamanho passado no primeiro parâmetro.
Answer: Também consegue resolver utilizando apenas o repeat que já tem no seu código. A ideia é primeiro escrever uma determinada quantidade de espaços e de seguida junta com uma quantidade de # que faça sentido para a linha em que vai.
Num cenário em que o tamanho final é de 5 carateres, cada linha teria os seguintes carateres:

4 espaços, 1 #
3 espaços, 2 #
2 espaços, 3 #
1 espaço, 4 #
0 espaços, 5 #

Implementação:

let array = []
function exibeNumero(entrada) {
    for (let i = 0; i < entrada; i++) {
        array.push(" ".repeat(entrada - i - 1) + "#".repeat(i + 1))
        //          ^^^^^^^^^^^^^^^^^^^^^^^^^^                ^^^
    }
    for (const entrada of array) {
        console.log(entrada)
    }
}
exibeNumero(5)

A unica instrução alterada foi a que coloca o elemento no array. Repare que foi necessário trocar o próprio repeat do # para que da primeira vez já escrevesse um caratere em vez de zero.
Answer: Uma solução:
function escada (n){

    var array = [];
    var cont = 1;

    for (i=0; i<n; i++){
        array[i] = '#'.repeat(cont).padStart(n);
        cont++;
    }
    return array;
}

Escada JavaScript


Conectar o BD sql server ao sql developer

Question: estou tentando conectar meu sql developer ao sql server, porém não está funcionando. A senha e usuário estão corretos. Sabem qual o problema?
Comment: ja tive esse problema, porém precisava acessar com o usuário SA, precisei liberar o acesso remoto e depois habilitar o usuário SA. Veja se isso te ajuda: http://www.systematiza.com.br/site/?page_id=837 e https://atendimento.redehost.com.br/hc/pt-br/articles/218105357-Habilitando-usu%C3%A1rio-SA-no-SQL-Server-2012
Comment: pelo sqlmanager studio vc consegue conectar?
Comment: @AdrianoGomes, sim, consigo. Porém quero conectar ao sql developer.
Comment: @AdrianoGomes, excelente. Habilitando o usuário `sa` foi o suficiente para conectar o sql developer ao sql server. Obrigado.
Comment: @AdrianoGomes, peço que coloque seu comentário como resposta da minha pergunta, desta forma, poderei fechar de forma correta a pergunta. Obrigado.
Answer: Conforme dito nos comentários acima, basta habilitar o usuário SA. Um exemplo de como fazer isso está no nesse link.
Comment: Obrigado. Ajudou muito.


Need a replacement for "Snoopy"

Question: Currently, we use Snoopy to monitor all commands issued by users on some externally accessible servers.  We're in the process of updating everything to RHEL8 to ensure supportability and compliance, and discovered that my beloved Snoopy is no longer maintained.  So it won't pass the compliance audit and needs to be replaced.
I looked into using auditd to do it, by enabling "pam_tty_audit.so" in system-auth and password-auth.  This did the trick, but the output is, well let's just say it's less then desirable.  Not to mention basically unreadable.
I tried setting-up /etc/profile to log by adding this...
function log2syslog
{
   declare COMMAND
   COMMAND=$(fc -ln -0)
   logger -p local1.notice -t bash -i -- "${USER}:${COMMAND}"
}
trap log2syslog DEBUG

And adding this to /etc/rsyslog.conf
local1.* -/var/log/cmdline

It works GREAT!  But the solution was declined because it can be overridden by users.
I even tried using rootsh as a shell for users and logging that.  Logs well, but there's no time/date stamps on it.  So not acceptable.
So back to the question at hand.  I need a replacement for Snoopy, that logs EVERY command executed, in a readable format with time/stamps, that users cannot override.
Any thoughts?
Comment: Eh? `pam_tty_audit` output is quite readable, if you do it correctly, as documented, with `aureport --tty` plus any filtering options you wish.
Comment: Our log output is crazy.  Here's a small example...

29. 09/30/2020 18:27:51 126 1000 ? 3 view "G",,,,,,,,,,,,,,,,,":q",
30. 09/30/2020 18:27:58 127 0 ? 1 bash "su - y",,"test_user2",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"sesta",,,"exit",
Comment: So far I have been unsuccessful in finding ways to turn the output.
Comment: Someone used the arrow keys a lot. This is pretty normal. I don't know how the old snoopy logged the use of arrow keys, but it probably wasn't quite as readable as this.
Comment: Our snoopy config didn't log arrows, tabs, etc.  Only completed commands.  Honestly, that's what I'm trying to replicate is the logging of the user's commands.  As to the arrow keys junkie, guilty as charged!  That was me.  After all, why type a 7 character command, when you can press "up" 12 times?  lol
Answer: The audit system is perfectly capable of logging all users' commands without pam_tty_audit, which only logs terminal keystrokes. You should set up auditing to do this instead of pam_tty_audit. By default on RHEL 8 auditing is already enabled and logs many system events.
To configure auditing to log all user commands, edit the file /etc/audit/rules.d/audit.rules. First, since you need syscall auditing, comment out the existing line:
## This suppresses syscall auditing for all tasks started
## with this rule in effect.  Remove it if you need syscall
## auditing.
# -a task,never

Now add for auditing 64-bit and 32-bit commands:
-a exit,always -F arch=b64 -S execve -k auditcmd
-a exit,always -F arch=b32 -S execve -k auditcmd

Note that here, auditcmd is a key with which you can search the audit logs with ausearch. You can change this to anything you like.
Kill and restart auditd. Note that it needs to be killed manually by root; the systemd unit will not let you stop or restart it.
# killall auditd; systemctl start auditd

Now run a few commands, and then you can use ausearch to see them in the audit log.
# ausearch -k auditcmd    # you can use additional filters; see the man page
...
time->Fri Oct  2 15:39:03 2020
type=PROCTITLE msg=audit(1601667543.738:64335): proctitle=636174002F6574632F61756469742F72756C65732E642F61756469742E72756C6573
type=PATH msg=audit(1601667543.738:64335): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=214448 dev=fd:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:ld_so_t:s0 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=PATH msg=audit(1601667543.738:64335): item=0 name="/usr/bin/cat" inode=201558633 dev=fd:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:bin_t:s0 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=CWD msg=audit(1601667543.738:64335): cwd="/root"
type=EXECVE msg=audit(1601667543.738:64335): argc=2 a0="cat" a1="/etc/audit/rules.d/audit.rules"
type=SYSCALL msg=audit(1601667543.738:64335): arch=c000003e syscall=59 success=yes exit=0 a0=558ba44ba550 a1=558ba42da110 a2=558ba4472790 a3=8 items=2 ppid=4070001 pid=1516048 auid=1000 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts1 ses=2 comm="cat" exe="/usr/bin/cat" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key="auditcmd"
----
time->Fri Oct  2 15:39:06 2020
type=PROCTITLE msg=audit(1601667546.102:64336): proctitle=6175736561726368002D6B006175646974636D64
type=PATH msg=audit(1601667546.102:64336): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=214448 dev=fd:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:ld_so_t:s0 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=PATH msg=audit(1601667546.102:64336): item=0 name="/usr/sbin/ausearch" inode=2004931 dev=fd:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:bin_t:s0 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=CWD msg=audit(1601667546.102:64336): cwd="/root"
type=EXECVE msg=audit(1601667546.102:64336): argc=3 a0="ausearch" a1="-k" a2="auditcmd"
type=SYSCALL msg=audit(1601667546.102:64336): arch=c000003e syscall=59 success=yes exit=0 a0=558ba4476360 a1=558ba44aa840 a2=558ba4472790 a3=8 items=2 ppid=4070001 pid=1516273 auid=1000 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts1 ses=2 comm="ausearch" exe="/usr/sbin/ausearch" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key="auditcmd"

You can see that all of the information about the command is logged, including its arguments, working directory, user/group, SELinux context, and much more. If you just want the command, that's in the EXECVE line. It's also encoded in hex in the PROCTITLE line, which you can feed to a hex decoder.
See also RHEL KB article How to audit all commands run in the system?
Comment: Thanks Michael!  That did the trick.  :)

Need a replacement for "Snoopy"


Primefaces tag library on tomcat, rendering an empty page from a valid jsp file

Question: I've posted here earlier about how to make a tic tac toe for two users using jsf and I got the link for this great taglib, Primefaces. It's absolutely perfect for what I need to do, but I'm being stuck on trying to make it do anything, even render the examples from their website.
So I've been following this tutorial I found (sadly, there aren't many of them on the subject of Primefaces): http://java.dzone.com/articles/primefaces-quickstart-tutorial
Step by step, I made everything according to this tutorial, yet when I run it, it renders an empty page every time.
So I tried a simpler example from the official website: http://www.primefaces.org/gettingStarted.html
This (test.xhtml):
<code> <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
    <h:head>
    </h:head>
<h:body>
<p:spinner />
</h:body>
</html>
</code>
renders an empty page, while this:
<code> <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
    <h:head>
    </h:head>
<h:body>
test test test test
<p:spinner />
</h:body>
</html>
</code>
renders only the "test test test test" text.
So I guess the problem must be in the tags, tomcat doesn't see them/doesn't know how to interprete them.
But, according to the tutorial and the primefaces website all I need to do is to put the jars in WEB-INF/lib as I have done (by the way, I'm using Eclipse and the empty project I created was "Dynamic Web Project").
In my WEB-INF/lib I have the following jars:
jsf-api-2.0.3.jar
jsf-impl-2.0.3.jar
jstl-1.0.2.jar
primefaces-3.3.RC1.jar
If it's of any help, here's the content of the tomcat console:
<code>    2012-05-27 13:18:11 org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in                         production environments was not found on the java.library.path:         .:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java
    2012-05-27 13:18:12 org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Primefaces1' did not find a matching property.
    2012-05-27 13:18:12 org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    2012-05-27 13:18:12 org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 1127 ms
    2012-05-27 13:18:12 org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    2012-05-27 13:18:12 org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
    2012-05-27 13:18:13 com.sun.faces.config.ConfigureListener contextInitialized
    INFO: Initializing Mojarra 2.0.3 (SNAPSHOT 20100726) for context '/Primefaces1'
    2012-05-27 13:18:17 org.primefaces.webapp.PostConstructApplicationEventListener processEvent
    INFO: Running on PrimeFaces 3.3.RC1
    2012-05-27 13:18:17 org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    2012-05-27 13:18:17 org.apache.jk.common.ChannelSocket init
    INFO: JK: ajp13 listening on /0.0.0.0:8009
    2012-05-27 13:18:17 org.apache.jk.server.JkMain start
    INFO: Jk running ID=0 time=0/63  config=null
    2012-05-27 13:18:17 org.apache.catalina.startup.Catalina start
    INFO: Server startup in 5096 ms
</code>
What can be the case? Am I putting the jars in wrong place, is it a tomcat failure or maybe something else entirely?
Answer: Ok, I solved it, maybe someone will someday find this useful.
So, when using Primefaces with JSF, not only the webpage files have to have the .xhtml extension (a solution I've found here: http://www.coderanch.com/t/473437/JSF/java/not-allowed-template-text), but also the web.xml file must be modified (a solution I've found here: Simple primefaces application not working), like this:
<code><servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</code>
Now it works perfectly well.
Comment: This problem is not strictly related to PrimeFaces, but to basic JSF in general. You would have exactly the same problem when not using PrimeFaces. Rightclick page in browser, *View Source*, you'll see that standard JSF tags like `` and so on are **also** unparsed when the request did not invoke the `FacesServlet`!
Comment: Can you explain step by step, how to implement Tic Tac Toe using JSF and primefaces @Natalia Zon


Why i can't take a screenshot with Puppeteer for this website https://www.leptitpinard.fr

Question: I usur this code to do a screenshot :
const puppeteer = require('puppeteer');
async function run() {
try {
const browser = await puppeteer.launch({ args: ['--no-sandbox'], headless: 'new' });
const page = await browser.newPage();
<code>    await page.goto('https://www.leptitpinard.fr', { waitUntil: 'networkidle0' });
    await page.screenshot({path: 'screenshot.png'});
    await browser.close();
} catch (error) {
    console.error('Error during capture:', error);
}
</code>
}
run();
I make screenshots without problem for all sites except this one : https://www.leptitpinard.fr
I have this error :
root@vps-0134553348d1:/var/www/vhosts/xxxxx.fr/httpdocs/api# node test1.js
/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/util/assert.js:28
throw new Error(message);
^
Error: Cannot extract value when objectId is given
at assert (/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/util/assert.js:28:15)
at valueFromRemoteObject (/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/common/util.js:239:28)
at createClientError (/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/common/util.js:122:16)
at CDPPage._CDPPage_handleException (/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.js:894:94)
at /var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.js:186:100
at /var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/third_party/mitt/index.js:3:248
at Array.map ()
at Object.emit (/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/third_party/mitt/index.js:3:232)
at CDPSessionImpl.emit (/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js:87:22)
at CDPSessionImpl._onMessage (/var/www/vhosts/xxxxx.fr/httpdocs/api/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js:441:18)
Answer: May be there is a bug https://github.com/puppeteer/puppeteer/issues/10224 on that specific version.
I have tested your code on v20.4.0 and its working fine.


Definitions of Knot Theory

Question: I am currently doing a course in Knot Theory and after looking at different texts I have found many ways to define knots and knot equivalence. In our course we are given the following definitions:
A knot $K\subseteq\mathbb{R}^{3}$ is a subset of the form $K=f(\mathbb{R})$ where $f:\mathbb{R}\rightarrow\mathbb{R}^{3}$ is a map with the following properties.

$f(x_{1})=f(x_{2})$ if and only $x_{1}-x_{2}\in\mathbb{Z}$
The derivative $\frac{d^{n}}{dx^{n}}f$ exists for all $n\in\mathbb{N}$
The derivative is not zero everywhere, $\frac{df}{dx}\neq 0$

Knots $K$ and $K^{\prime}$ are equivalent if there exists a collection of knots $K_{x}$ for each $x\in\left[ 0,1\right]$. such that $K_{0}=K$ and $K_{1}=K^{\prime}$, and such that there exists a smooth map $F:\left[ 0,1\right]\times \mathbb{R}\rightarrow\mathbb{R}^{3}$ with the property that $F(x,\cdot )$ represents $K_{x}$ in the sense of the previous definition.
I think I understand intuitively what is happening here and that this smooth map ensures that we make no illegal 'jumps'. I am at the same time taking a course in Algebraic Topology and for the sake of my note keeping I would like to give an alternative definition of equivalence more in line of homeomorphisms from Topology, which If im not mistaken is essentially what is going on here.
So I would say that two knots $K$ and $K^{\prime}$ are equivalent if there exists a homeomorphism $f:\mathbb{R}^{3}\rightarrow\mathbb{R}^{3}$ for which $f(K)=K^{\prime}$.
Would this definition be satisfactory, if not how could I change it? Is there any substantial difference from my definition and the one given by my lecturer?
Comment: Left and right trefoils aren't equivalent, but isn't reflection a homeomorphism taking one to the other?
Comment: Ah, very true. Is there some way I can ask for a homeomorphism which preserves left and right handness?
Answer: As was pointed out in the comments, you need to differntiate mirror images to agree with your first definition. This is fixed by asking for an orientation-preserving homeomorphism $f: \mathbb{R}^3 \to \mathbb{R}^3$. See https://en.wikipedia.org/wiki/Knot_theory#Knot_equivalence, where it is also (briefly) explained why these two notions of equivalence are the same.
Comment: Thank you very much. I see now how these coincide, and how I must define it.

Definitions of Knot Theory


Oracle Client 32 bit windows connecting to Oracle Server

Question: I have to connect or make service (i don't know what you called exactly),there are table spaces created and i have user name ,password for that,but i don't know how to connect to the Oracle DB,i think there is a procedure by giving credentials and service name,can you please advice me how to do that
Comment: Based on my Oracle Script,they have created table spaces,i think services to be activated from my server where i installed my application and needs to be connected from application.
Comment: i have installed oracle 32 bit client,there is sql developer and sql plus,i need to connect from my pc to oracle server.
Answer: You must setup a TNS entry. Google sample tnsnames.ora or use the New Database Connection wizard in SQL Developer. Typically a TNS entry requires your hostname, port (default is 1521) and SID.
Look under your Oracle client home for NETWORK\admin directory
Create tnsnames.ora with an entry that matches your environment. You can also use the Oracle Net Configuration Assistant (Start -> Programs -> OracleHome1 -> Configuration and Migration Tools) on Windows
ORA1 =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.5)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = ORA1)
    )
  )

Then connect with the TNS alias and username and password
Try pinging it first:
tnsping ora1

SQLPlus
sqlplus scott/tiger@ora1


Can I use Windows Server BMB to backup an entire Hyper-V host?

Question: I have a Windows 2012 R2 Hyper-V host server hosting a few VMs via Hyper-V. I need to do the following:

Backup/image the entire host server
Install new hard drives and create a new RAID array
Restore the backup/image to the new array
Pray everything works as it should

Would Windows BMB be sufficient to backup an entire host server? If I restore the server backup, will all the Hyper-V VMs still exist and work as they should? Any additional ideas or suggestions about this whole project are also appreciated.
Thanks for reading. Let me know if there's any detail I should add.
Answer: You normally backup VMs, it's must faster to provision new virtualization host from scratch, comparing to what you restore from backups.
Comment: I'd be more keen to rebuild the host and import backups of the VMs if this were a personal or internal project. This is a client project and I'd be much more comfortable backing up their entire configuration to avoid any hiccups, even if it's a slower process. The total size of their host is only around 200 GB.
Comment: Use bare metal backup for host and VM backup for VMs. It's actually more complex than just provision new host from scratch but as long as it works for you... Why not?
Answer: While you can use Windows Server Backup to backup the entire server including the virtual machines and the Hyper-V component, it's probably easier to either backup the virtual machines or export them, then rebuild the server from scratch and restore or import the virtual machines.
Comment: I'd be more keen to rebuild the host and import backups of the VMs if this were a personal or internal project. This is a client project and I'd be much more comfortable backing up their entire configuration to avoid any hiccups, even if it's a slower process. The total size of their host is only around 200 GB.
Comment: Exporting a virtual machine is a built-in capability of Hyper-V. It's intended to be used as an "enterprise level" method of moving virtual machines. I've exported/imported virtual machines across enterprise Hyper-V hosts and environments many times. Do yourself a favor, try your backup/restore method but export the virtual machines after you back them up. That way if there are problems with the restore you can simply rebuild the Hyper-V host and import the exported virtual machines.


Do flamenco guitarists use distinctive chords?

Question: Classical guitarist here. Does flamenco guitar use distinctive chords (other than, say, the major, minor, augmented, and diminished triads and seventh chords), or is it just the favored modes, chord progressions, rhythm, dynamics, timbre, dances, and playing techniques that distinguish it from other styles?
Aside from "the chords themselves," are there certain voicings they tend to favor?
Comment: There are a whole lot of musics that all use "the same chords," at least from an instrument-agnostic sense, and that differentiate by what they do with them. There may well be some flamenco-specific guitaristic technical considerations.
Comment: Instant fake flamenco chord: 023100.
Comment: Have you at least looked up some basic music reference sources? https://en.wikipedia.org/wiki/Flamenco#Music
Comment: @MichaelCurtis I'm not sure that source answers my question. For example, it mentions the Andalusian cadence and the flamenco mode, but my question is about the chords themselves, not about modes and not about cadences. Unless perhaps you are hinting, by the source's apparent silence with respect to my question, that the answer to my question is no.
Comment: @NoahJ, in the wiki article "cadence" isn't used in the technical sense, it's a chord progression. But the wiki article is just an example of one source. I'm really asking if you have looked up anything? Like Andy Bonner commented a lot of the chord/scale material will be like other music.
Answer: I'm not a Flamenco player, but one thing that seems noticeable to me is a characteristic use of open strings. A few examples...

...and...

Those came out of a method book: Essential Flamenco Guitar: Volume 1: An In-Depth Course for Absolute Beginners to More Advanced Players.
Notice the open E string above both an A and Bb bass? That particular method book doesn't get into harmony theory, but in my mind I think of this kind of an E over a bass/root Bb as less a chord tone and more a pedal or drone. At least part of the purpose, beyond sustaining tones of the tonic chord, is to make the guitar more resonant.
Also, I notice those chord changes over the E drone use a lot of half step changes.
Here is another passage that just begins to touch on harmony theory...

The book says the root (tonic) chord will be the A major chord, but the tonality is phrygian with a sort of vague reference to D minor.
Notice the chord list (A Bb C7 C Dm) is all diatonic to D minor, yet the tonic is A. (Notice also the open E string drone for all the chords listed.) That list may seem strange if one expected all the chord to be diatonic to an A phrygrian scale. Without going into a long description of phrygian modal harmony, one quick and dirty way to describe, in my own words, is: play in a minor key but treat the dominant major triad V chord as the tonic.
Those are at least two chord/harmony strategies to take, use open string drones and try the quick and dirty guideline to play in phrygian mode. I would look into some other study sources to flesh that out. Look for transcriptions of authentic Flamenco guitar. Beyond that, the real heart of Flamenco as I understand will be much more about rhythm and strumming/plucking technique.


How to prove that a graph with degree of each vertex equal to 4, has a Hamiltonian cycle?

Question: I need to this for my homework and I've been looking for over an hour but don't really know where to start. A tip would be appreciated!
Assume we have the following graph:

How can you prove that it has a Hamiltonian cycle?
I know there exists a Hamiltonian cycle (drawn below)
Comment: You have already proved it.
Comment: You just gave an example of a such cycle... Done! ;)
Comment: You prove that the graph has a Hamiltionian cycle by finding one.
Comment: I have to prove my claim but I don't know how. And since my drawing is my claim it is no sufficient prove
Answer: A complete (simple) graph is one in which each vertex is connected to each other. It's known that every complete graph on more than two vertices is hamiltonian. Since your graph is complete, it follow from that it has a hamiltonian cycle.
As I recall, there's also a theorem like: If the sum of degrees of every two distinct vertices is at least $n$ in an $n$ vertex graph it has a hamiltonian cycle.
Comment: The theorem you are thinking of is called Ore's Theorem, and the condition applies to only nonadjacent vertices, hence it is trivially satisfied in the complete graph!
Comment: @BobKrueger Thanks, I found the thing in a graph theory book but forgot the details.


Can we use PACF plots for feature selection?

Question: Disclaimer: Not from math background
I want to use neural networks for forecasting a time series data. I am reading/watching basics about ACF and PACF. While reading about those functions I came to understand that PACF is an important function to find different time series models for example AR(1), AR(2) etc which tells us which lagged time series is important for forecasting.

In the above PACF image time series lagged at 1,2,12,24 are more prominent and above confidence level. Can we use these time series lagged data Y(t-1),Y(t-2),Y(t-12), and Y(t-24) as the feature vectors for neural network for training to forecast Y(t+n)?
Answer: Yes, this is usually the case when creating autoregressive (AR) models, as you can see in this question: Estimate ARMA coefficients through ACF and PACF inspection
However, ACF and PACF compute linear correlations, while neural networks are nonlinear, so the applicability of those techniques may not be obvious. This paper shows that they are indeed useful for feature selection on neural networks.


Copy only one color of an image to another image

Question: I need to copy the pixels from one image to another, but only the black pixels.  I have to separate the black pixels out for sending to a printer using the K Panel on the printer ribbon.
Basically I need to make every pixel in the image that isn't black transparent or white.
What's the best way to do this?
The only idea I have is something along the lines of:
<code>        var attr = new ImageAttributes();
        attr.SetColorKey(minColor, maxColor);
        using (Graphics g = Graphics.FromImage(backGround))
        {
            var destRect = new Rectangle(0, 0, backGround.Width, backGround.Height);

            g.DrawImage(kPanelImage, destRect, 0, 0, backGround.Width, backGround.Height, GraphicsUnit.Pixel, attr);
        }
</code>
Comment: Well I can set the ImageAttributes color key to a range of colors, but I don't know what ranges would be everything except black.
Answer: <code>Bitmap mySource = new Bitmap("your_image.jpg");

for(int w=0; w<mySource.Width; ++w)
   for(int h=0; h<mySource.Height; ++h)
   {
      Color pixelColor = mySource .GetPixel(w, h);
      if ( pixelColor != Color.Black )
           mySource .SetPixel(w, h, Color.White);
   }
</code>
Comment: Yeah... makes perfect sense when you're not trying to over complicate things.
Answer: Why don't you iterate every pixel in the image then check it's color. If it is not black then change it's color to white


How can i get total base measurements in shopify theme file

Question: I want to display "total base measurement" on the cart page. How can I achieve this one?
Answer: Product measurements are part of variant object. If your theme does not support this, you can follow this Shopify guide to display unit prices. However, latest Shopify supported themes display this information on Product as well as Cart pages. Relevant code snippet from Shopify Debut theme, that shows unit prices on Cart page.
{%- comment -%}
    Markup template for unit price
{%- endcomment -%}

        {{ 'products.product.unit_price_label' | t }}

        {%- capture unit_price_separator -%}
            /{{ 'general.accessibility.unit_price_separator' | t }}
        {%- endcapture -%}
        {%- capture unit_price_base_unit -%}
            {%- if item.unit_price_measurement.reference_value != 1 -%}
                {{- item.unit_price_measurement.reference_value -}}
            {%- endif -%}
            {{ item.unit_price_measurement.reference_unit }}
        {%- endcapture -%}
            {{ item.unit_price | money }}{{- unit_price_separator -}}{{- unit_price_base_unit -}}

This is how the Cart page looks
Comment: thanks, @bilal but I need to display like this $0.88 / unit
Comment: If you need the word **unit** regardless of unit, simply change the last `{{- unit_price_base_unit -}}` to _unit_


Does boost's multi index copy key object

Question: Does boost::multi_index create a copy of the key object. This question came into my mind since std::map HAS to store a key object according to it's design. However boost::multi_index does not explicitly asks for the key but instead it is gathered from the stored object.
Another question is if boost::multi_index does create a copy of it's keys, is there any container which does not create a copy of it's keys to keep the footprint to the minimum?
Answer: Boost.MultiIndex does not keep keys separately from the objects they're associated to, but relies on so-called key extractors to retrieve the info from the objects themselves, without external key storage.
Comment: The memory overhead of using pointers to objects rather than internally copying the objects is independent of what container you use. The aspect where Boost.MultiIndex can get you some memory savings relates to the fact that keys are implicitly part of the objects stored.
Comment: So in respect to memory overhead of storing pointers to objects, which one(map or multi_index) uses less memory?
Comment: Thanks that's exactly what I was asking for


Cookies not being sent back and forth properly in Opera

Question: First off, I'm not sure whether this is a problem in Opera 12.01 or not, but the problem only occurs in Opera. I've tested in FF14, Chrome 21, Safari 5 (Windows) and Safari Mac and Webkit browsers on Android and iPhone.
My application runs on the trigger.io forge platform and uses a proxy to route requests from the web application to the service. The proxy simply forwards the requests and cookies along and this works as expected in most of the browsers.
After inspecting the request in dragonfly, I noticed that the server sends the proper headers in the response, but Opera seems to be ignoring setting the values. I'm wondering whether this is due to some misconfigured path value for the cookie. I've attached screenshots of 2 requests in Firefox and Opera.
As you can see in the screens, FF sees the cookie headers and sets them appropriately, but Opera does not.
Firefox Request

Opera request 1 Screen

Opera Request 2  Screen

I haven't included the code from the proxy that does the request forwarding, so please let me know if you need that to gain some insight. On the service end, I'm running PHP and Codeigniter. Please let me know if I need to add any more info here on my environment, thanks.
UPDATE : This issue occurs even in my production environment which does not use a custom TLD. Other sites that use cookies work fine and cookies are enabled.
Comment: I found the setting in `about:config` and unticked it, didn't fix the issue. Cookies are enabled as well, other sites work fine. I should have mentioned that this happens even on my production environment so can't be due to the TLD. Will add that info to the question, thanks.
Comment: Daft question, but are cookies enabled in your Opera installation (Settings > Preferences > Advanced > Cookies)?  If so, you might consider setting `Do Not Show Cookie Domain Errors=0` under `[User Prefs]` in `operaprefs.ini` to see whether Opera's rejecting the cookie due to uncertainty over the appropriate restriction level for your private `.locdev` TLD.
Comment: Couple of initial thoughts - Opera is the only browser to support Set-Cookie2. I don't know the implications of that but perhaps it's related to the problem? Another thought - how many cookies do you have set for the /_forge path: Opera has a limit of 30 whereas Firefox has a limit of 50 and it's unclear whether new cookies would cause old ones to disappear or just be rejected. And how that works could vary by browser..
Comment: @AmirNathoo Will check up on set-cookie2, thanks. As for the number, we only have about 4 - 5 cookies. Definitely not more than 10 so that shouldn't be the case either. Also, I checked it on a clean install and it was still failing.
Answer: Double quotes are formally illegal in a cookie value. If you escape them as %22 it will work.
Comment: I will try to dig into the proxy's code to confirm this, but if this were the case wouldn't it affect every other browser as well?
Comment: I went through the proxy code and switched things about a bit. Removing the double quotes and putting in replacement characters worked like a charm! Thanks!
Answer: Have you checked if this is an issue with cookie domains ? I'm assuming you're using Javascript to set/read the cookies ? In any case there are 4 cookie domain issues that you might want to check (I know I've had these issue with an old FF version):
1 - check for illegal cookie characters: allowed cookie characters you might not be allowed to use '-' or '=' in the cookie name, and you shouldn't use non-ASCII characters in cookies at all. A base64 encode might deal with this.
2 - check that the domain on which you set your cookie (via javascript code or any other way) is identical to the domain on which the code is executed.
3 - check that the cookie domain is not localhost; see if you can test setting the cookie from a remote domain
4 - if you're using JS to set your cookies, try testing if you can set the cookie with a CGI in your browser to make sure it's not a browser issue. If it works which it should, see if you can read the cookie using JS (as opposed to setting it).
Let me know how this goes in the comments, I've dealt with similar issues a number of times and depending on what you get with these checks, I'm pretty sure I can help you fix the issue.
Comment: This might not be the case but can you please confirm that if you create a NEW php file with just the cookie content, that cookie still doesn't get set in Opera ? And also, can you please include the cookie settings in your php.ini file? You might want to hide the exact domain name and such sensitive info...
Comment: See my answer about the double quotes. I have tested this across several browsers, I know that's cause of the problem.
Comment: @JohnP I was afraid of that... is the proxy domain the same as the one for which the cookie is set ? Can you try to set a cookie directly from the proxy ?
Comment: The cookies are set by PHP codeigniter and it seems to be encoding it so that should be clean. The domains are identical. I have this problem on my live server. And my local server is not named localhost. The only cookies that seem to be going through are those ones that are set by JS. The PHP cookies don't seem to work. Btw, this only breaks on Opera. Everything else works fine.
Comment: There are a number of reasons that could cause this: Have you checked that headers aren't sent beforehand ? Maybe a hidden PHP notice is thrown before the cookie code is executed ?
Comment: Since the JS cookies do get set (with the same content, I'm assuming) it makes me wonder whether it's a php.ini setting you're dealing with, or headers being sent to early.
Comment: CosminAtanasiu @hallvors  Thanks for the help guys, will check these point out tonight. And no, no notices are being thrown,
Comment: @CosminAtanasiu The cookies get set. They work fine when you're trying it out in a regular PHP file. I have the problem only when I run it through the proxy.
Comment: No, the cookies are being set for a subdomain. For example, the application is on stackoverflow.com and the cookies are being set for chat.stackoverflow.com. The proxy looks at the header and passes the cookies on. I've set the domain for the cookie properly.
Comment: @CosminAtanasiu Thank you for your help in this, user hallvors reply about removing double quotes fixed the problem for me :)
Comment: Alright, glad to be of help, and glad to hear you had your problem fixed!
Answer: Have you checked the "leading dot" form of a cookie domain in setcookie. I've been using leading dots for years and only recently noticed my app wont set cookies on opera (chromium et al?) due to the leading dot which is part of a deprecated RFC. In opera, it's not that the leading dot gets ignored but the very setting of the cookie itself. I've removed the leading dot and its working now.
Answer: Looking at those Opera screenshots, they seem to be AJAX / XHR requests which are processed within the same second. Is it possible that Javascript is triggering both of those requests "simultaneously", so the response from the "first" is not arriving before the request for the "second" is constructed - and therefore the cookies have not yet been set?
I'm not familiar with the technologies/toolkits you're using, so don't know if these are stock code or part of your custom application.
Comment: Fair enough. It was a reasonable theory based on the evidence presented, so I'm glad you've ruled it out experimentally.
Comment: No, they aren't run during the same second. I've set it up sequentially. And if you look at the response, you can see the cookies being returned but not actually being used.
Comment: Then why do both of your Opera screenshots list the response time as "Wed, 08 Aug 2012 17:00:09 GMT"? And yes, the server is setting cookies on both responses, but if the browser created the second request before it had seen the first response, then of course it wouldn't send those cookies back.
Comment: Good point but I checked it and that doesn't seem to make a difference. I delayed the second request by 2 seconds and still the same. This is a grab from a local setup, so that's why the timestamps are so close. I can assure you the code is running sequentially.


Gaussian process on hyperparameter tuning

Question: I feel it is kind of circular to use GP for hyperparameter tuning, since GP has its own hyperparameters. Or is it the case that GP typically has less number of hyperparameters than the model we want to tune (say NNs), which mitigates the issue somewhat?
Answer: You are correct Gaussian process has it's own hyperparameters. But same is true for every other hyperparameter tuning algorithm you would use. If you use grid search, you need to decide on the grid of points to use, if you want to do random search, you need to decide on the distributions used for sampling the parameters, etc.
The good news is that in many cases, the models we use are not that sensitive to the hyperparameters (it doesn't matter that much if the learning rate is 0.01, 0.013, or 0.014, but matters if it's closer to 0.0001), so it is not that important for the algorithms that we use for hyperparameter tuning to be that precise.
Comment: Just to clarify are you trying to make a case to say GP is not super sensitive to its  hyperparameter setting, or in general ML model is not super sensitive to hyperparameter setting? If it is former then I guess it has to do with some of GP's properties but if it is the latter then isn't using GP for hyperparameter search not that meaningful anymore?
Comment: @Zzy1130 ML models in general. What I'm trying to say is that you don't need to have perfectly tuned parameters for GP when using it for hyperparameter optimization. Many out-of-the-box tools have reasonable defaults. Of course, there may be cases where some tuning would improve the results.


How to initialize and train a Hidden Markov Model to improve the classification produced by a previous classifier?

Question: Say we've previously used a neural network or some other classifier C with $N$ training samples $I:=\{I_1,...I_N\}$ (that has a sequence or context, but is ignored by C) the, belonging to $K$ classes. Assume, for some reason (probably some training problem or declaring classes), C is confused and doesn't perform well. The way we assign a class using C to each test data $I$ is: $class(I):= arg max _{ {1 \leq j \leq K} }    p_j(I)$, where $p_j(I)$ is the probability estimate of $I$ corresponding to the $j$-th class, given by C.
Now, on top of this previous classifier C, I'd like to use a Hidden Markov Model (HMM) to "correct" the mistakes made by the previous context-free classifier C, by taking into account the contextual/sequential information not used by C.
Hence let in my HMM, the hidden state $Z_i$ denote the true class of the $i$-th sample $I_i$, and $X_i$ be the predicted class by C. My question is: how could we use the probabilistic information $cl(I):= arg max _{ {1 \leq j \leq K} }    p_j(I)$ to train this HMM? I understand that the confusion matrix of C can be used to define the emission prob. of the HMM, but how do we define the transition and start/prior prob.? I'm tempted to define the start/prior prob. vector as $\pi:=(p_1(x_1), ..., p_K(x_1))$.  But I may be wrong. This is my main question.
A follow up question: One can define an HMM in the above way (using confusion matrix and the prob. information from C); call the resulting parameter set $\Theta_0$. But after doing so, is it advisable to estimate the parameters to best fit the data $I$ used for C, while initializing a parameter set with the values mentioned in the previous paragraph?
Your answer is greatly appreciated!
Answer: To improving classification with HMM you have to set its parameters like:
A transition matrix : is the consecutive for the true classes in train set "I" then divide every row by its sum
B emission matrix : is the transpose of confusion matrix of C
π start prob : is the biggest prob from multiply transition matrix by emission matrix and taken from the row which ends in train set.


I'm creating a ModelBinder. What do I do to change the way it binds the property from the model back to the client on EditorFor?

Question: I've learned how to create a custom ModelBinder that successfully changes the way the properties are set as parameters of my controller actions.
Now how do I intervene the inverse way? changing the way it sets the property back from the model to the View in the EditorFor method?
Answer: You can use Default Templates.
This is basically a snippet of code that is used for the type. It needs to be in the Views\Shared\DisplayTemplates and Views\Shared\EditorTemplates.
Name of the view needs to be name of the Class.
This way you may change DateTime and other basic types as well.
Comment: well, that makes a lot o sense. Actually the other way around is solved with templates, not with ModelBinders. That worked. Thanks so much


I want to call the same function multiple times, without loosing its previews outputs. I don't want to use a database. What should I use?

Question: I need to generate multiple tables, by calling the same function. When I do this, the previews table gets lost, because I recall the function. I am new to JavaScript. Can you suggest me what should I use. Note: I don't want to use a database to save the information. I am not sure if I should do it with Ajax or there is some other simple way, just by using JavaScript.
    <form>
        Row: <input type="text" id="x"    />
        Columns:<input type="text" id="y"  />
        <input type="button"  value="OK" onclick='createTable();'></input>
    </form>

Comment: Return the table instead of overwriting it directly, then decide outside the function how you want to update it. In general, prefer returning data to manipulating outside things inside a function.
Answer: You could add the new table to the last table in the output
document.getElementById("table").innerHTML += theader + tbody + tfooter;
//                                         ^

function createTable() {
  var x = document.getElementById("x").value;
  var y = document.getElementById("y").value;
  var rX = parseInt(x, 10); // add base
  var cY = parseInt(y, 10); // add base
  var theader = '
\n';
  var tbody = "";

  for (i = 1; i <= rX; i++) {
    tbody += '
';
    for (j = 1; j <= cY; j++) {
      tbody += '';
      tbody += i + ':' + j;
      tbody += '	';
    }
    tbody += '
\n';
  }
  var tfooter = '
';
  document.getElementById("table").innerHTML += theader + tbody + tfooter;
}
<form>
  Row:
  <input type="text" id="x" />Columns:
  <input type="text" id="y" />
  <input type="button" value="OK" onclick='createTable();'></input>
</form>


Cloud9 ide img not working

Question: I can use background img tags still but cloud 9 is not displaying images for me. I have used local and online images to try and nothing. Also if it helps I'm using bootstrap. I have been able to use images before fyi.
Comment: Please read this : http://stackoverflow.com/help/how-to-ask , and reformulate your question... If you're not more explicite, your question will be closed. If a man says "my car doesn't work", it may have a lot of reasons.
Comment: Can you paste some html with the part of the code that contains the images?
Comment: It's not my html code. I switched back to notepad++ and the code works perfectly. I believe it's a cloud9 settings or error. I know my question is general but my situation is general. I just love the live preview in cloud9 not refreshing every minute.
Answer: Instead of

or

try using source path with foldername or filename directly like this

Cloud9 ide img not working


Free introductory resources for learning algebra?

Question: I have a non-mathematician friend who is interested in re-learning algebra. I am more than happy to help, but I am in no position to judge what is a good introductory text --- only to identify when a text is a very bad one.
My friend is interested in starting from "basics" --- he's comfortable with order-of-operations, minus-times-minus-is-plus, and positive integer exponents. He's shaky with negative exponents, logarithms, and roots.
Any recommendations for good, freely-available resources?
Comment: @muad: The question was about highschool algebra.
Comment: people love to recommend http://www.khanacademy.org/, but I have no experience with it.
Comment: I assume you mean the version that isn't called "abstract algebra" and is about groups and such (Lang's book is about that)

For self-study I'd suggest you take a look at the Schaum's series about algebra, they are cheap, full of examples and exercises.
Comment: I don't understand, I always thought Lang is a great book - that is what I used myself.
Comment: Oops! I was thinking of *Algebra* By Saunders Mac Lane, Garrett Birkhoff. Don't know why I confused that with Lang!
Answer: Khan Academy offers dozens of videos on particular Algebra topics, among thousands of videos on other academic topics.
Answer: Curriki is supposed to be a good resource for this kind of stuff, but I haven't tried it out myself.
Answer: There's a pretty good video course on YouTube EDU, "College Algebra"


How to prove that $\langle Av,w\rangle=\langle v,A^Tw\rangle$?

Question: How to prove:
$$\langle Av,w\rangle=\langle v,A^Tw\rangle$$
$\langle,\rangle$ represents inner-product, $v,w$ denote vectors and $A$ is a matrix.
Comment: That is false, in general. Check carefully the conditions...
Comment: @DonAntonio Reference for the statement: https://www.youtube.com/watch?v=WBqxm4y-Ejg&t=529s
Answer: This only holds for real valued $A$. In general, the following is true:
$$ \langle A v,w \rangle = \langle v,A^{\mathsf H} w\rangle
$$
where $\mathsf H$ means the conjugate transpose (adjoint) of $A$. This property uniquely defines $A^{\mathsf H}$ from $A$.
To prove your statement, observe that $\langle u,v \rangle = v^\intercal u$. Hence
$$ \langle A v,w \rangle = w^\intercal A v = (A^\intercal w)^\intercal v = \langle v,A^\intercal w \rangle
$$
Answer: I'm assuming you are talking about $n\times n$ real matrices.
Hint: Write down everything component-wise and use the definition of inner product in $\mathbb{R}^n$.

Alternatively, in $\mathbb{R}^n$, assuming one uses column vectors, one has
$$
\langle x,y\rangle=x^Ty
$$
for $x,y\in\mathbb{R}^n$.


How actually my time series models tells me about data behaviour?

Question: I have different models namely AR, ARMA, ARIMA for different time series (in data set of 4449)
stationary-3096, Non stationary-1353 , why this classification appears to be?
If I have $AR(p=1-5)$ and $AR(p >5)$ what does my data tell ?,
I have many time series which follows ARMA-1239 best models, some are AR-90 best model & ARIMA-7 best models out of 3096 stationary data set
Please, kindly tell me in philosophical/non-statistical way (because I didn't understand by term like normal/marginal distribution).
Comment: This is all rather unclear to me - are you saying you have 4,449 different time series? It seems like you're saying 90 of them only required AR terms, 1239 required MA terms as well, etc.. but I'm not sure. You'll have a much better chance at getting a good answer if you edit and give a clearer description of the data and the problem.
Comment: it seems to be  confusing to you sir,don't worrytell me separate thing,without considering data size,
1) If I have AR(p=1−5) and AR(p>5) what does my data tell ?,
2) most of time series follows ARMA process than AR,(for each time series i calculate both models,best model selected on basis of lowest AIC value)
Comment: It might also help if you give some context, and describe exactly what problem you're trying to solve
Answer: The order of the an AR model tells you how the current value is linearly related to the past p values.
The theory of stationary time series tells us that any stationary model has an infinite autoregressive representation (which could be finite) and also there is an infinite moving average representation (which could be finite).  If the AR representation is finite an AR model works. If the MA representation is finite an MA model works.When both representations are infinite you need an ARMA model for a finite parameterization.
ARIMA models allow the modeling of a special kind of nonstationary process namely a process that is stationary after differencing of the series.  Frist order differencing eliminates a linear trend and higher order differencing eliminates the higher order polynomial trends.  The class of ARIMA models therefroe represent a broad class of stationary and nonstationary time series.  They do not cover seasonal trends but Box and Jenkins introduced seasonal differencing to deal with seasonal 9or periodic) trends.
Regarding normal distributions, it is commonly assumed for ARIMA models that the random or noise component has the normal (Gaussian) probability distribution usually with zero mean and a common variance.  The collection X1, X2, ..., Xn have a multivaraite distribution determined by the model.  The individual or univariate distribution of X1 say is called the marginal distribution.  If the time series is stationary then all the Xis have the saem marginal distribution.


Clicar no botão e abrir outra Activity

Question: Estou desenvolvendo um aplicativo em JAVA , e vai ter 2 opções para a pessoa escolher, quero que quando ela aperte em 1 dos 2 botoes abra uma nova Activity no aplicativo, Alguém pode por favor me dizer qual o código para isso ?
Estou utilizando o Android Studio.
Answer: Para isso você pode utilizar o método startActivity ( Documentação )
Este método solicita como parâmetro um Intent
Neste deve se informar um Context (no caso sua Activity) e a class da Activity que deseja abrir:
Intent intent = new Intent(this, SegundaActivity.class);
startActivity(intent);

ADICIONAR O CLICK EM UM BOTÃO ATRAVÉS DO XML:
No Seu xml no primeiro elemento adicione a seguinte linha:
xmlns:tools="http://schemas.android.com/tools"

Com isto você poderá adicionar qual é a classe de contexto deste xml:
 tools:context="seu.pacote.app.SuaActivity"

Após, vamos informar no botão qual o método ele irá chamar:
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"

    android:onClick="proximaTela"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="-2dp" />

No Java adicione o método um método público void e que receba uma View como parâmetro:
public class SuaTela extends AppCompatActivity {

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

    public void proximaTela(View view){

        Intent intent = new Intent(this, SegundaActivity.class);
        startActivity(intent);
    }
}

Comment: Muito Obrigado.
Comment: Só lembrando que não pode esquecer de declarar a nova Activity no AndroidManifest.xml
Comment: Muito obrigado Thiago!!!

Clicar no botão e abrir outra Activity


Why are all von Neumann ordinals contained in each other?

Question: I'm a high school student and I'm giving a lecture in my high school math class on ordinal numbers, and I would like to prove that the von Neumann ordinals are well-ordered by set membership.
The definition of von Neumann ordinal that I'm using is as follows. An ordinal is a set $A$ such that the elements of $A$ are well-ordered by $\in$ and such that $\forall x (x\in A\implies x\subset A)$.
In order to prove that the von Neumann ordinals themselves are well-ordered, I will first show that they are totally ordered. To do this, I first show that the ordering is transitive, i.e. if $A\in B$ and $B\in C$ then $A\in C$. I then want to show that the ordering is trichotomous, i.e. for all $A$ and $B$, exactly one of the following is true, either $A\in B$ or $A=B$ or $B\in A$. I am having trouble showing this last part.
In other words, I would like to show, given only the definition of von Neumann ordinal written above, that any pair of ordinals are either equal, or one is a member of the other. Any help would be appreciated.
Answer: Observe that for given ordinals $A$ and $B$ the following claims hold true:

If $A$ is a proper subset of $B$, then $A \in B$.
$A \cap B$ is an ordinal.

Now, given ordinals $A \neq B$ consider $A \cap B \subseteq A,B$. If $A \cap B = A$, then $A \subseteq B$, so that either $A = B$ or $A \in B$. Analog $A \cap B = B$ implies either $B = A$ or $B \in A$. If $A \cap B$ is a proper subset of both $A$ and $B$, then $A \cap B \in A \cap B$, which contradicts the axiom of regularity.
Comment: I'm magic, baby!
Comment: "If $A$ is a proper subset of $B$, then $A \in B$": This requires proof, I think. It's certainly not true for _all_ proper subsets of $B$.
Comment: @TonyK Let $X = \min B \setminus A$ and show that $X = A$.
Comment: Is there a way to do this without assuming regularity?
Comment: @Henno: You don't use regularity here, since you already assumed that ordinals are well-founded with $\in$.
Comment: @Henno Actually, the author already assumes any ordinal to be well-ordered by $\in$, so that we get $A \cap B \not \in A\cap B$ for free.
Comment: @Asaf More often than not, your infinitesimal response time baffles me :D
Comment: @TonyK Both claims require a proof. I thought it was a good idea to let her/him prove them.
Comment: The second claim is easy to prove. If the first claim is also easy, I'm not seeing it.
Comment: @AsafKaragila By well-founded with $\in$, you mean that ordinals are assumed to be *strictly* well ordered by $\in$?
Comment: @VoiletFlame: Since well-orders are normally defined as strict ordering, yes.
Answer: For any ordinals $A$ and $B$, below statements hold true:

$A\subsetneq B\implies A\in B$. (I presented a proof for this at If $\alpha\ne\beta$ are ordinals and $\alpha\subset\beta$ show $\alpha\in\beta$)
$A\cap B$ is an ordinal. (It's quite easy to prove this)

For $A=B$, the theorem is trivially true. For $A\neq B$, let $z=A\cap B$, hence $z$ is an ordinal. We will prove this case by contradiction.
Assume $A\not\subsetneq B$ and $A\not\subsetneq B$. Since $z\subsetneq A$ and $z$ is an ordinal, then $z\in A$. Similarly, $z\in B$. Thus $z\in A\cap B=z$, which contradicts the fact that $z$ is ordinal and hence well-ordered under $\in$. As a result, either $A\subsetneq B$ or $B\subsetneq A$.


How to modify PHP password connection to the database?

Question: I have only access to a source code (connect.php) from previous developer as
<?php $_F=__FILE__;$_X='Pz48P3BocA0KNG40X3M1dCgnZDRzcGwxeV81cnIycnMnLCdPZmYnKTsNCiRjMm4gPSBteXNxbF9jMm5uNWN0KCJsMmMxbGgyc3QiLCJyMjJ0IiwibW0xYWFhOSIpOw0KbXlzcWxfczVsNWN0X2RiKCJtNHRyMSIsICRjMm4pOw0KNGYgKCEkYzJuKQ0KICB7DQogIGQ0NSgnSzJuNWtzNCBnMWcxbCAhOiAnIC4gbXlzcWxfNXJyMnIoKSk7DQogIH0NCj8+';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));?>

Then I googled there's tool to decode the above encrypted text which gives me
?><?php
ini_set('display_errors','Off');
$con = mysql_connect("localhost","root","mma2229");
mysql_select_db("mitra", $con);
if (!$con)
  {
  die('Koneksi gagal !: ' . mysql_error());
  }
?>

All I need is just to change the password (example to "123") but I do not know where to start.
How can I set the my connect.php with my new password ?
Comment: A general hint: a "php developer" delivering code in such a form should not be trusted. If I were you I would dump all that code and start from scratch or using other examples. A programmer who relies on such way to "protect" database credentials most likely also has other areas where he propagates more then questionable "solutions".
Comment: That probably was the reason, which I already stated. But it makes no sense at all. This is _not_ a protection, it is obfuscation which does not add security. It generates a false sense of security. It demonstrates a fundamental miss understanding of security aspects.
Comment: Just delete the previous developers base64 encoded mess, and use the decoded php and change the password.

No reason to base64 encode this stuff.
Comment: go to your database management system panel and change password there and then update it here
Comment: this is a root password and my mysql is used by multiple applications. Changing the password will break the other connections.
Comment: then create another user in your database management system.. do you use phpmyadmin as your system software for database?
Comment: Lets say I have a new user and password. How do I fit them to the source code in the `connect.php` ? How do I encrypt them just like the above example ?
Comment: you don't need to encrypt your password.. because your password isn't going to visible to anyone. If you do so, there will no benefit for this you will have i believe
Comment: @arkascha. I thought the reason he did what he did is to secure the credentials. Is not it ?
Comment: what is the value of $_F=__FILE__; ?
Comment: As long as the script is outside of the document root tree, there is no risk for exposing the credentials. And even if it is inside, when the web server is configured properly there is no risk either.
Comment: How did you decrypt the encrypted php text to give you the code?
Comment: @Webdev Just look at the code given, it is base64 encoded twice.
Comment: To add to what @Boli commented , you can create new php code with tne new password and then base64 encode it twice and include it in your code
Comment: Its not simply encoded twice. The next encoded eval string is: $_X=base64_decode($_X);
$_X=strtr($_X,'123456aouie','aouie123456');
$_R=ereg_replace('__FILE__',"'".$_F."'",$_X);
eval($_R);
$_R=0;
$_X=0;

But this does not matter - just delete the entire code and use the none encoded mysql connect code with your new password. :)
Comment: I have never used PHP before. The idea is to get it up and running so I can see the application on my laptop. Thank you all for the insights :)
Answer: Just replace the previous delevopers code:
<?php $_F=__FILE__;$_X='Pz48P3BocA0KNG40X3M1dCgnZDRzcGwxeV81cnIycnMnLCdPZmYnKTsNCiRjMm4gPSBteXNxbF9jMm5uNWN0KCJsMmMxbGgyc3QiLCJyMjJ0IiwibW0xYWFhOSIpOw0KbXlzcWxfczVsNWN0X2RiKCJtNHRyMSIsICRjMm4pOw0KNGYgKCEkYzJuKQ0KICB7DQogIGQ0NSgnSzJuNWtzNCBnMWcxbCAhOiAnIC4gbXlzcWxfNXJyMnIoKSk7DQogIH0NCj8+';eval(base64_decode('JF9YPWJhc2U2NF9kZWNvZGUoJF9YKTskX1g9c3RydHIoJF9YLCcxMjM0NTZhb3VpZScsJ2FvdWllMTIzNDU2Jyk7JF9SPWVyZWdfcmVwbGFjZSgnX19GSUxFX18nLCInIi4kX0YuIiciLCRfWCk7ZXZhbCgkX1IpOyRfUj0wOyRfWD0wOw=='));?>

With:
<?php
ini_set('display_errors','Off');
$con = mysql_connect("localhost","root","123"); // put your new password instead of 123
mysql_select_db("mitra", $con);
if (!$con)
  {
  die('Koneksi gagal !: ' . mysql_error());
  }
?>

Comment: @abiieez And don't forget to replace `mysql_*` with either `mysqli` or `PDO`.
Answer: In your phpMyAdmin panel write query like this:
SET PASSWORD FOR 'root'@'localhost' = password('mynewpass')

Setting new user / change password in view
If you want to do it with clicking, go to phpMyAdmin, click on the top Users -> Edit Privileges and there you can change a password. In this view you can also add new user which can be used in your PHP code.


MPAndroidChart: How To Have Draggable Data Entries

Question: I am working on creating an app that allows someone to control a motorized camera slider. I am implementing MPAndroidChart as the base of my position as a function of time graph. I am able to allow users to add a "keyframe" (an Entry in MPAndroidChart terms) by double tapping somewhere on the LineChart; however, for functionality sake the user should also be able to select an existing keyframe and move it by dragging the keyframe to wherever they would like it to be. My question is how do I implement that with MPAndroidChart? Below is my current code for the project.
<code>package com.emotion.slider.activities

import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import com.emotion.slider.R
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import com.github.mikephil.charting.listener.ChartTouchListener
import com.github.mikephil.charting.listener.OnChartGestureListener
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.EntryXComparator
import kotlinx.android.synthetic.main.mainactivity.*
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity(),
    OnChartGestureListener, OnChartValueSelectedListener{
    private val TAG = "Main Activity"
    lateinit var chart: LineChart   // LineChart is initialized From XML
    var keyFrames_TrackSlide = ArrayList<Entry>()

    override fun onChartGestureStart(
        me: MotionEvent?,
        lastPerformedGesture: ChartTouchListener.ChartGesture?
    ) {
        Log.i(TAG, "onChartGestureStart: X: " + me?.getX() + "Y: " + me?.getY())
    }

    override fun onChartGestureEnd(
        me: MotionEvent?,
        lastPerformedGesture: ChartTouchListener.ChartGesture?
    ) {
        Log.i(TAG, "onChartGestureEnd: $lastPerformedGesture")
    }

    override fun onChartScale(me: MotionEvent?, scaleX: Float, scaleY: Float) {
        Log.i(TAG, "onChartScale: Scale-X: $scaleX Scale-Y: $scaleY")
    }

    override fun onChartLongPressed(me: MotionEvent?) {
        Log.i(TAG, "onChartLongPressed: ")
    }

    override fun onChartSingleTapped(me: MotionEvent?) {
        Log.i(TAG, "onChartSingleTapped: ")
    }

    override fun onChartDoubleTapped(me: MotionEvent?) {
        Log.i(TAG, "onChartDoubleTapped: " + me.toString())

        // Convert Position Of Double Tap To A Point On The Graph
        var x: Float? = me?.x                                                                                // Grab the X-Coordinate
        var y: Float? = me?.y                                                                                // Grab the y-Coordinate
        var newTouchPoint = chart.getTransformer(YAxis.AxisDependency.LEFT).getValuesByTouchPoint(x!!, y!!)     // Create a New Touch Point From The X and Y Coordinates (Will Map Raw Data To A Point On The Graph)
        var xValue = newTouchPoint.x
        var yValue = newTouchPoint.y
        var xValueRounded = "%.2f".format(xValue).toFloat()
        var yValueRounded = "%.2f".format(yValue).toFloat()
        var newEntry = Entry(xValueRounded, yValueRounded)

        Log.i(TAG, "ValueX: $xValueRounded, ValueY: $yValueRounded")

        // Grab Pre-Existing Data (Points) From Chart
        var chartDataPoints = chart.data
        if (chartDataPoints == null){
            chartDataPoints = LineData()
            chart.data = chartDataPoints
        }

        keyFrames_TrackSlide.add( newEntry)
        Collections.sort(keyFrames_TrackSlide, EntryXComparator())
        chart.data.clearValues()
        var set1 = LineDataSet(keyFrames_TrackSlide, "Data Set 1")
        set1.fillAlpha = 110
        var dataSets = ArrayList<ILineDataSet>()
        dataSets.add(set1)
        var data = LineData(dataSets)
        chart.data = data

        chartDataPoints.notifyDataChanged()
        chart.notifyDataSetChanged()

    }

    override fun onChartFling(
        me1: MotionEvent?,
        me2: MotionEvent?,
        velocityX: Float,
        velocityY: Float
    ) {
        Log.i(TAG, "onChartDoubleFling: Velocity-X: $velocityX Velocity-Y: $velocityY")
    }

    override fun onChartTranslate(me: MotionEvent?, dX: Float, dY: Float) {
        Log.i(TAG, "onChartTranslate: dX: $dX dy: $dY")
    }

    override fun onNothingSelected() {
        Log.i(TAG, "onNothingSelected: ")
    }

    override fun onValueSelected(e: Entry?, h: Highlight?) {
        Log.i(TAG, "onValueSelected: " + e.toString())

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.mainactivity)
        createLineGraph()                       // Creates The Line Graph

    }

    private fun createLineGraph(){
        // Setup LineChart From XML
        chart = this.lineChartFromXML                                   // Grab LineChart from XML
        chart.isScaleYEnabled = false                                   // Don't Allow User To Scale On Y-Axis
        chart.isScaleXEnabled = true                                    // Allow User To Scale On X-Axis
        chart.legend.isEnabled = false                                  // Disable The Chart's Legend (We'll provide our own)
        chart.maxHighlightDistance = 50.0f                              // Sets The max distance away a touch can be from a keyframe in order to access/modify the keyframe
        chart.isDoubleTapToZoomEnabled = false                          // Disable The Double Tap To Zoom Feature (We'll use double tap to signify a new keyframe)
        chart.onChartGestureListener = this@MainActivity                // This Activity will be able to handle gestures from User input
        chart.setOnChartValueSelectedListener(this@MainActivity)        // This activity will allow for the value selector listener to work

        // Setup Right Y-Axis' Settings
        val rightYAxis = chart.axisRight                                // Grab The LineChart's Right Y-Axis Object
        rightYAxis.setDrawGridLines(false)                              // Don't show grid lines on right side of Y-Axis
        rightYAxis.axisMaximum = 180F                                   // Set The Maximum Of The Right Y-Axis to be 180
        rightYAxis.axisMinimum = -180F                                  // Set The Minimum Of The Right Y-Axis to be -180
        rightYAxis.setLabelCount(5, true)                  // Show 5 Labels On The Right Y-Axis
        rightYAxis.textSize = 12.0f                                     // Set Label Size

        // Setup Left Axis' Settings
        val leftYAxis = chart.axisLeft                                  // Grab The LineChart's Left  Y-Axis Object
        leftYAxis.setDrawGridLines(false)                               // Don't show grid lines on left side of Y-Axis
        leftYAxis.axisMaximum = 180F                                    // Set The Maximum Of The Left Y-Axis to be 180
        leftYAxis.axisMinimum = -180F                                   // Set The Minimum Of The Left Y-Axis to be -180
        leftYAxis.setDrawLabels(false)                                  // Don't draw any labels on the Left Y-Axis

        // Setup X-Axis' Settings
        val xAxis = chart.xAxis                                         // Grab The LineChart's X-Axis Object
        xAxis.axisMinimum = 0F                                          // Set X-Axis' Minimum To 0 (seconds)
        xAxis.axisMaximum = 6F                                          // Set X-Axis' Maximum to 6 (seconds)
        xAxis.position = XAxis.XAxisPosition.BOTTOM                     // Set The Labels of the X-Axis to be on the bottom of the X-Axis
        xAxis.textSize = 12.0f                                          // Set Label Size

        // THE FOLLOWING IS PUTTING ENTRIES INTO AN ARRAY OF ENTRIES, WHICH THEN BECOMES AN ARRAY OF
        // DATA SETS, WHICH THEN BECOMES LINE DATA, WHICH THEN GETS ASSIGNED TO THE XML's LINE CHART,
        // FINALLY- THE VIEWER IS REFRESHED.

        // Step 1.) Create Entries With Position NOT Changing Over Time (Initial Chart's Keyframes)
        keyFrames_TrackSlide.add(Entry(0f, 0f))  // Time = 0 Sec, Position = Origin
        keyFrames_TrackSlide.add(Entry(6f, 0f))  // Time = 6 Sec, Position = Origin

        // Step 2.) Create a LineDataSet from the given Entries
        var dataSetTrackSlide = LineDataSet(keyFrames_TrackSlide, "TrackSlide")

        // Step 3.) Create an Array of the DataSets
        var dataSets = ArrayList<ILineDataSet>()
        dataSets.add(dataSetTrackSlide)

        // Step 4.) Create a LineData object from the DataSet Array
        var data = LineData(dataSets)

        // Step 5.) Assign The LineData to the chart from the XML
        chart.data = data

        // Step 6.) Refresh the XML view by calling invalidate()
        chart.invalidate()
    }
}
</code>
Answer:
Figured it out, created a new class that would implement a few things: [KOTLIN]
<code> class myChartTouchListener() : Activity(), OnTouchListener,
 GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
     // Code For Class Goes Here, Implement All Necessary Functions
 }
</code>

Called it from main activity passing my view which holds MPAndroidChart
<code> // Set My onTouchListener for any touches on the MPAndroidChart
 this.lineChartFromXML.setOnTouchListener(myChartTouchListener())
</code>


HTML input type=file should show only wav files

Question:
Possible Duplicate:
How to get the HTML's input element of "file" type to only accept pdf files?

I have basic HTML input tag and content-type="audio/wav"
<input type="file" name="file" />

by using this we will get chose file or browse file. When you click on chose file button this open system window which shows the all file.
But my requirement is I want to show only ".wav" in this popup.
Answer: I'm afraid you can't, at least with standard html controls.
Here you will find a list of attributes you can specify for input tag and there is nothing suitable. http://www.w3schools.com/TAGS/tag_input.asp
Comment: W3Schools is rubbish ( http://w3fools.com/ ) but even they haven't failed to notice (right at the top of the list) the `accept` attribute (although it comes with caveats )
Comment: @David Dorward: I thank you for the info on w3school, I didn't know about it. By the way: Are the info I'm providing wrong? Are the info provided into the page I linked wrong (provided that the accept attribute won't work in mayors brother and therefore it is useless)? In other words: why the downvote?
Comment:
Is not working in firefox.
Comment: accept="audio/*" working fine in chrome showing audio type file in popup, same thing is not working in firefoz this is showing all kind of files. I don't know why. any other way to do this?
Answer: If you use an "open file dialog, this will explain it to you:
http://www.eggheadcafe.com/community/aspnet/2/10051298/how-to-use-openfile-dialog-in-c-with-aspnet.aspx


How to discover devices other subnet

Question: Printers like some thermal I have tried Bixolon and samsung laser printer ,even mikrotik router have a tool where they discover the device via its mac address.No matter what the ip is. And they discover it fast within seconds. How is this done ? So in case you lost the printer or router from bad configuration you can find them with this tool. How can I do the same ? All arp scans here seem to look a subnet.
I havent got any answer for this only "these devices want to be discovered" but doesnt answer the question
Answer: I believe you are looking for the term "multicast".
Using e.g. SLP (Service Location Protocol) multicast discovery you can possibly find printers also in remote subnets. For example HP Jetdirect specific multicast address: 18.104.22.168
Other methods can be SNMP broadcast queries or plain IP range discovery (specific network scan).
Comment: so they have an address that they know ?
Comment: The example 188.8.131.52 looks like a pretty specific address to me.
Comment: I did some test and it seems to have to do with broadcast ip range. Thank you for helping. Question closed by ret*

How to discover devices other subnet


How to set files public directory programmatically?

Question: I have standalone script for adding some files to Drupal nodes. It is in main Drupal directory. It is multisite enviromnent. I know how to choose database and I am sure that I am choosing proper database, but my files lands in sites/default/files but I want them in sites/domain/files. I am getting public files path by
drupal_realpath('public://')

It returns sites/default/files.
All other things are correct and file data lands in proper database.
I checked site (admin/config/media/file-system) that database I am using and this path is set to site/domain/files...
Is there any chance to set public path programmatically? So file_copy will use proper path.
EDIT
The reason that I am asking is that my hooks: hook_file_presave doesn't invoke and I am thinking that is because public path problem. (All required module are enabled)
In single site env script works ok.
Probably the only solution is to create module, but it strange it isn't works.
I wanted to stay away from creating modules for long running task because it's take longer and Batch API is slower that good old CLI. All my previous scripts worked with multisites.
Answer: You can set that variable like so:
variable_set('file_public_path', 'sites/domain/files');

Hopefully someone else will be able to tell you why this problem is happening, I have no such issue in any of my multisite installations.
Comment: Thanks a lot, it works. Hooks still doesn't invoke, but it is different problem.


Function which preserves closed-boundedness and path-connectedness continuous?

Question: Let $f:\mathbb{R^n}\to\mathbb{R^m}$ be a function such that the image of any closed bounded set is closed and bounded, and the image of any path-connected set is path-connected. Must $f$ be continuous? What if we replace "path-connected" with "connected"?
Answer: For both "path-connected" and "connected" cases, $f$ must be continuous.
By reduction to absurdity, assume that $f$ is discontinous as some point $x\in\mathbb{R}^n$. since $f$ maps compact sets to compact sets, we can find a sequence $\{x_k:k\ge 1\}\subset \mathbb{R}^n$ with $\lim_{k\to\infty}x_k=x$, such that for the sequence $\{y_k:=f(x_k):k\ge 1\}\subset\mathbb{R}^m$, $y:=\lim_{k\to\infty}y_k$ exists and $y\ne f(x)$. By choosing a subsequence of $\{x_k\}$ if necessary, we only need to consider two special cases: (i) $y_k=y$ for every $k$; (ii) $y_k\ne y$ for every $k$.
For case (i), let $L_k$ be the line segment joining $x_k$ and $x$, then by either "path-connected" or "connected" assumption, $f(L_k)$ is connected and $\{y,f(x)\}\subset f(L_k)$. Then for each $k$, we can replace $x_k$ with some $x_k'\in L_k$, such that $y_k':=f(x_k')\ne y$ but $\lim_{k\to\infty}y_k'=y$. Since $\lim_{k\to\infty}x_k'=x$, we have reduced case (i) to case (ii).
For case (ii), the set $\{x_k:k\ge 1\}\cup\{x\}$ is compact, but its image under $f$ is $\{y_k:k\ge 1\}\cup\{f(x)\}$, which is noncompact, a contradiction.