Dns resolution [BIND9] , pinging to the right domain, but answer coming from another domain

Question: I have created my /etc/network/interfacesconfigured like this:
/etc/network/interfaces
Then I have 2 files i created in /etc/bind
One of them is db.rag.es , which looks like this: db.rag.es file
And the other one is db.222.168.192 which looks like this db.222.168.192 file
Problem is whenever I ping servidor.rag.esit returns a proper responde from (192.168.222.2), but if i ping ftp.rag.es for some reason it pings to 192.168.22.4(desired) , but then ive a destination host unreachable coming from 192.168.222.2when im trying to ping .4 ping attempt
Comment: What happens when you ping 192.168.222.4 (not using the name ftp.rag.es)? If you get no response then it is not a DNS problem.
Comment: @DanielK destination host unreachable, apparently not a dns problem then. Its returtning from 192.168.222.2 for some reason
Comment: That is your NIC responding. This is normal.
Comment: @DanielK thanks for the clues, solved it by modifying /etc/network/interfaces by following this https://wiki.debian.org/NetworkConfiguration#Multiple_IP_addresses_on_one_Interface
Comment: Do not use `ping` to troubleshoot DNS issues, it is the wrong tool (for almost any troubleshooting in fact). DNS issues are to be troubleshoot using `dig` or a least `nslookup`. Also when asking for help remember to put all relevant information (which could be in your case DNS server configuration and zone content) IN the question (not through a remote link that can become stale) and AS TEXT (to enable copy, search, etc.). Do not bother first with reverse DNS also until you understand how this space is delegated (completely separate from domain names). You have online DNS troubleshooting sites
Answer: This is not a DNS problem. It is likely a firewall issue.
Comment: @DanielK - The point is that it is not a DNS problem, which is what the OP thought and the best answer available wit the given information (and enough to put the OP on the correct path it seems)
Comment: I have no firewall in my machine
Comment: In that case its a routing issue. What does your network look like? (Ie how are systems connected, what are the netmasks and routes?)
Comment: its a virtualbox virtualmachine running ubuntu, with the posted network configuration to have a static ipv4. Internal adapter is connected to "Internal network"
Comment: solved it by following https://wiki.debian.org/NetworkConfiguration#Multiple_IP_addresses_on_one_Interface to add extra ip addresses
Comment: This is not an answer. It could be any number of things preventing communication, including the firewall


Vocal fach and passaggio

Question: I am somewhat of a newbie singer and wondering what my voice type is. Most singers are probably aware of the passaggio locations chart for men. But how exactly do you determinate these passaggio points, since they depend a lot on the volume and vowel? (Here is the common chart)
For me I start to strain quite a bit at E4 and F4 is pretty much unsingable in pure chest. That makes me a lyric baritone according to the chart I think. But the problem is, I can't sing below A2 (without sounding terrible) and even that is a bit iffy. Is it possible to be higher voiced voice type with a low passaggio?
Comment: Eek - I spent about 2 hours this afternoon reading through that link & other pages on the site. I've only been singing 35 years & have never heard of most of the terminology used on there, other than the obvious, tenor, soprano etc. The entire 'which bit of chest/throat/head' to use was totally alien to me. I'm not sure that knowing all that now would do me any good at all... I can fairly comfortably get from D3 to A5. I have no falsetto whatsoever. I have no clue what bracket that would put me in :(
Comment: Did you read everything in the link you posted? It does mention about strain and volume as well. But if you want people to understand your voice it would be better if you posted a clip of your singing, I wouldnt really rely on finding the exact notes of your passaggios.
Comment: @user40079 To be honest the article is really confusing. It seems like it's detailing two different passaggios, but I sure can't feel more than one. Any ideas? If you are a teacher, how common is it for a voice type to deviate from that chart?
Comment: I'd only heard of, and noticed, chest and head voices before. But consciously thinking about it I can feel my voice move from chest -> throat -> head. However between chest/throat it seems more gradual than a sudden switch - but then I rarely sing very low so I've never thought about it before
Answer: I am not a voice teacher, however I do know it is not very often for a voice type to deviate by much. From what you describe, it sounds like you are likely a baritono lirico(lyric baritone) or tenore robusto(dramatic tenor).
One way you may determine your passaggi(every singer has two) is to sing one note at a time, first playing the note on a piano, then singing it. You move up the scale chromatically until you find particular notes within your range. These notes are the primo and secondo passaggio.
This is how they are characterized.
Primo Passaggio

When... untrained male singers approach the [end] of the comfortable speech range, they reach a point in the ascending scale where they often involuntarily raise the chin... the corresponding pitch is the first passaggio.

Secondo Passaggio

As the untrained singer continues to ascend... the untrained voice will either break off or resort to a sudden falsetto.

I think you may be a tenore robusto because of your lower range. However none of us have actually heard you sing a scale. Therefor, we cant give a definitive answer as too what your voice type is.

Resources

Personal experience
7 years of general music lessons
The book "The Structure of Singing" by Richard Miller
Comment: I am very confused because I absolutely lack the lows, but my 2nd passaggio (E4/F4) and highest note (A5, but take that to maybe G5 during song) are fairly low. I really have to find that first passaggio, but I don't think it will change anything. I guess, my voice is tenor's without the highs, or baritone's without the lows. Sucks lol (then again I am still able to sing pretty much all songs, unless they go to the 2nd octave).

Thanks for the answers anyway, if you find more about this sort of voice let me know!
Comment: If A2 is your lowest note, you would have a decent range. A2 to A5 is an average vocal range if I'm not mistaken.
Comment: Interesting... Still thinking my passaggio is very low compared to the lowest notes I can produce though. I think this means I have thin vocal chords? Maybe...
Comment: Check out this link for thin vocal chords.[link](http://voicedoctor.net/therapy/vocal-underdoers-weak-voices-and-voice-building)
Comment: @hmmm A5 is hardly an average limit for a male, surely? Tenor high C is only C5!
Comment: @Mr.Boy If I understand correctly, Tony is reaching A5 using falsetto. Many tenors and a few baritones I know, in both my choir and others, have no problem hitting that pitch and even surpassing it in falsetto. If he was singing in chest voice the whole time, now that would be quite a bit better than average! :)
Comment: @hmmm I was discounting falsetto but that would make sense
Answer: In all honesty, it is very difficult to truly determine your voice type until you have had some training. Once the voice is free, open, and supported from below, you truly cannot reach your full potential and have an understanding of your vocal fach and what repertoire is appropriate and healthy for you to sing. There are many factor which are considered when one is determining what voice type you are, passaggio,timbre, vocal range, and tessitura, and even age can be a factor. For males the voice does not fully mature until the later parts of your twenties and even into the late thirties. I hope that you consider (if you are not already) studying with a voice teacher, and please be patient with yourself and your vocal growth. I can say these thing because I had a very difficult time figuring out my voice type. Even different teacher debated some said baritone; other tenor. I felt within the core of my being that truly I was a tenor and I turned out to be correct. I could vocalize down to a low base C and had a great deal of power in my chest voice and it seemed as if I was a baritone. My issue was carrying up to much chest voice to the top of my range; without the allowing my chest voice to mix with my head voice. Basically I was shouting out the top notes and could not go higher than a G sometime I could shout up to an A. Once I begin to place my voice in the correct position for good singing by raising my soft palate and placing the voice forward into the nasal cavity, I suddenly realized my head voice. After some study my head voice became very strong and I learned to mix the head voice with the chest voice and found that that I could vocalize up to a high D sharp sometime even E. When I learned how to support from down below I realized I had a strong tenor high C and even a high D.
I am leaving out some details because I feel I have already made this response to long, my point it is hard to determine what your voice type is, until you open the voice and support your voice with proper breathing and good technique. You truly may be a baritone, but I would keep an open mind and not make a firm decision on your voice type for a while.
Have a great day.

Vocal fach and passaggio


Como faço pra pular o bloco "finally", em C#, quando a exceção for gerada?

Question: Caso a exceção seja gerada, quero saber se há uma forma de "pular" a execução do bloco finally. Caso não haja exceção, o finally execute normalmente.
Com o goto não funcionou.
Código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calculadora
{
    class Program
    {
        static void Main(string[] args)
        {
            double n1, n2, multiplicacao;
            try
            {
                Console.Write("Digite o primeiro numero.\n");
                n1 = double.Parse(Console.ReadLine());
                Console.Write("Digite o segundo numero.\n");
                n2 = double.Parse(Console.ReadLine());
                multiplicacao = n1 * n2;

                Console.WriteLine("\nResultado...\n");
                Console.WriteLine(n1+" * "+n2+" = " + multiplicacao);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao tentar fazer a conta.");
                goto pular;
            }
            finally
            {
                Console.WriteLine("\nO finally foi executado...");
            }
            pular:
            Console.WriteLine("\n\n O finally nao foi executou.");
        }
    }
}

Comment: Não faz muito sentindo isso q vc quer. O `finally` é para garantir que a rotina dentro dele seja sempre executada caso haja uma exceção e esta exceção pare o fluxo e faça com que ele saia do método onde ocorreu a exceção impedindo que um código importante seja executado. Com o `finally` vc consegue dar garantias que seja executado. Se vc ñ quer executar o q esta nele, simplesmente não declare o bloco `finally` e coloque sua rotina abaixo do `catch` para que ela seja executada (sem garantias) .
Answer: Não faz nenhum sentido isso que você está querendo, o finally, é para você executar as lógicas necessárias caso o bloco try consiga ou não fazer a sua tarefa.
Por exemplo
Você abre a conexão com SQL e depois durante uma consulta a conexão cai será gerado uma exceção, mas dando certo ou erro você precisa fechar a conexão com o SQL, ai você coloca esta lógica no finally.
Se você quer pular o finally simplesmente remove-o.
Comment: Eu sei que não faz sentido.Isso é só um demonstrativo pra outra necessidade. É que tenho que usar uma logica parecida em outra implementação, na faculdade. Pois isso coloquei esse  exemplo simples.
Comment: Obrigado. Amigão, acho que a minha pergunta que foi equivocada. Quero que a aplicação seja finalizada, assim ela não executará o finally.
Answer: Este código tem vários problemas, alguns são erros, outros é só questão de estilo ruim:
1 - Este problema não precisa lidar com exceção. Ele precisa verificar o erro e dar o devido tratamento. Use TryParse() e seja feliz sem exceções.
2 - Se fosse usar exceção, coloque no Finally só o que deve ser executado sempre. O que não deve ser executado se gerar uma exceção, coloque fora.
3 - Se capturar uma exceção, faça com a mais específica possível, sói use Exception se tiver uma ótima justificativa.
4 - Se não vai usar a variável de exceção, não a use.
5 - Só declare a variável onde vai usá-la, não faça pré-declarações que não trazem benefícios.
6 - Não é o fim do mundo neste caso, mas evite concatenações de string e prefira interpolação de string.
7 - Fiz outras melhorias quase cosméticas.
using static System.Console;

namespace Calculadora {
    public class Program {
        public static void Main(string[] args) {
            WriteLine("Digite o primeiro numero.");
            if (!double.TryParse(ReadLine(), out var n1)) { //dá para fazer genérico
                WriteLine("Dado digitado inválido");
                return;
            }
            WriteLine("Digite o segundo numero.");
            if (!double.TryParse(ReadLine(), out var n2)) { //reaproveite e não é necessário
                WriteLine("Dado digitado inválido");
                return;
            }
            double multiplicacao = n1 * n2;
            WriteLine("Resultado...");
            WriteLine($"{n1} * {n2} = {multiplicacao}");
            WriteLine("Tudo foi executado...");
        }
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Este código exige C# 7, mas com um pequena modificação pode rodar em C# 6 e com pouca coisa mais pode rodar em todas versões.
Se ainda quiser insistir na exceção e até para responder a pergunta, o que você deseja não é pular o finally é não existir o finally. O mecanismo de finalização da tentativa é que o código deve ser executado em qualquer caso. Se deseja que ele seja pulado quando der a exceção, então ele deve ficar fora de todo o bloco try-catch-finally. Simples assim. Pode fazer:
using System;
using static System.Console;

namespace Calculadora {
    public class Program {
        public static void Main(string[] args) {
            try {
                WriteLine("Digite o primeiro numero.");
                double n1 = double.Parse(ReadLine());
                WriteLine("Digite o segundo numero.");
                double n2 = double.Parse(ReadLine());
                double multiplicacao = n1 * n2;
                WriteLine("Resultado...");
                WriteLine($"{n1} * {n2} = {multiplicacao}");
            } catch (Exception) { //só para efeitos de teste, caso contrário não capture Exception
                WriteLine("Erro ao tentar fazer a conta."); //na prática agora nunca acontecerá a exceção
                WriteLine("O finally nao foi executou.");
                return;
            }
            WriteLine("Tudo foi executado...");
        }
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Note que há uma outra exceção ocorrendo. Acho que é algo momentâneo no .NET Fiddle, de qualquer forma mostra como é problemático capturar Exception, pega o que não se espera.
Reforço que tudo isto está errado, fique com o primeiro.
Se quiser terminar um programa e ele não está no Main() então no lugar do return deve usar o Environment.Exit(), a não ser que esteja em uma aplicação WinForms, aí deve usar o Application.Exit(). Existe outras variações para aplicações de outras tecnologias (WPF, UWP, ASPNET, etc.), inclusive se for um teste. Tem casos que até outras soluções são mais adequadas.
Além do que a pergunta não fala em terminar logo a aplicação, fala em pular o catch.
Answer: Citando a MSDN

Normalmente, as instruções de um bloco finally são executadas quando o
  controle deixa uma instrução try. A transferência de controle pode
  ocorrer como resultado da execução normal, da execução de uma
  instrução break, continue, goto ou return, ou da propagação de uma
  exceção para fora da instrução try.
Dentro de uma exceção tratada, é garantido que o bloco finally será executado.

Você pode utilizar o método Environment.FailFast() para finalizar a aplicação imediatamente, fazendo com que o bloco finally não seja executado.
Entretanto, pular o bloco finally e executar o código da maneira como você quer não é possível.
Comment: Muito obrigado! Tô tentando implementar no meu código, mas não estou conseguindo. Há como me você dá esse suporte ?
Comment: @RodrigoOliveira utilize `Environment.FailFast("Um erro fatal ocorreu.");`. Lembre de colocar `using System;` no início
Comment: Tô implementando, mas aí está executando o finally. Vamos no chat pra eu te mostrar.
Comment: @RodrigoOliveira colocou dentro do bloco `catch`?
Comment: Sim. Dá uma olhada.    `catch (Exception ex)
            {
                Console.WriteLine("Erro ao tentar fazer a conta.");
                Environment.FailFast(causeOfFailure);`
Comment: Se você não está querendo exeecutar o finally, então porque não tirar o código de dentro dele (que aparentemente seria alguma disposição dos recursos), e colocar depois do try...catch. Nesse caso se não quisesse continuar a aplicação, derrubaria ela no catch. Aliás, pela documentação o goto não pode pular o finally: https://msdn.microsoft.com/en-us/library/aa664758(v=vs.71).aspx
Answer: O objetivo do bloco finally é ser executado tanto após a execução do bloco try, quando após qualquer bloco catch. Não há como "pulá-lo".
Quando iniciamos algum processo no bloco try, que precisa ser encerrado, tais como conexão com o banco ou abertura de um arquivo, normalmente usamos o bloco finally para encerrar o processo. Evitamos assim, colocar o código de encerramento no bloco try e em todos os blocos catch.
No código apresentado em sua pergunta, não há motivos para ter um bloco finally. Então, simplesmente, não o implemente.
Comment: `Environment.Exit(0);`
Comment: Entendo sua lógica. Acho que me expressei errado. Eu quero finalizar a aplicação dentro do bloco catch. Há alguma maneira ?


convert many lists in wide format to long format

Question: I want to convert thousands of lists from wide to long format, given thousands of lists look like this:
   y2010 y2011 y2012 y2013 y2014 y2015 y2016 y2017 y2018 y2019 coverage_fraction
4     12    12    12    12    12    12    12    12    12    12      0.0005232538
9     12    12    12    12    12    12    12    12    12    12      0.1390771568
10    12    12    12    12    12    12    12    12    12    12      0.7728050947
.
.
46    12    12    12    12    12    12    12    12    12    12      0.0005232538

Is there a way to place pivot_longer(-c(11) into a function, like mapply(), that changes the columns from each list into long format, whilst retaining the individual list elements?
Essentially, I want to use this code:
lc_extract_pred <- landcover %>%
  exact_extract(r_cells, progress = FALSE) %>% *Convert from wide to long here* %>%
  map(~ count(., landcover=value)) %>%
  tibble(id = r_cells$id, data = .) %>%
  unnest(data)

If I could pivot_longer(), then the values from the years will usually be given a column name assigned value, hence assigning landcover=valuein map, and turning this into tibble() format.
dat_list %>% map_lgl(function(x) pivot_longer(-c(11)) )

Error in UseMethod("pivot_longer") :
no applicable method for 'pivot_longer' applied to an object of class   "c('double', 'numeric')"

Here's a reproducible code containg one row and a few lists:
list(c(y2010 = 1, y2011 = 1, y2012 = 1, y2013 = 1, y2014 = 1,
y2015 = 1, y2016 = 1, y2017 = 1, y2018 = 1, y2019 = 1, coverage_fraction = -1.33003238502638
), c(y2010 = 1, y2011 = 1, y2012 = 1, y2013 = 1, y2014 = 1, y2015 = 1,
y2016 = 1, y2017 = 1, y2018 = 1, y2019 = 1, coverage_fraction = 0.682342381930735
), c(y2010 = 1, y2011 = 1, y2012 = 1, y2013 = 1, y2014 = 1, y2015 = 1,
y2016 = 1, y2017 = 1, y2018 = 1, y2019 = 1, coverage_fraction = -2.09817126581704
), c(y2010 = 1, y2011 = 1, y2012 = 1, y2013 = 1, y2014 = 1, y2015 = 1,
y2016 = 1, y2017 = 1, y2018 = 1, y2019 = 1, coverage_fraction = -0.0942304747486628
), c(y2010 = 1, y2011 = 1, y2012 = 1, y2013 = 1, y2014 = 1, y2015 = 1,
y2016 = 1, y2017 = 1, y2018 = 1, y2019 = 1, coverage_fraction = -0.944268346233405
))

Answer: You could transpose every element in dat_list and rbind them together.
result <- do.call(rbind.data.frame, lapply(dat_list, t))

#  y2010 y2011 y2012 y2013 y2014 y2015 y2016 y2017 y2018 y2019 coverage_fraction
#1     1     1     1     1     1     1     1     1     1     1       -1.33003239
#2     1     1     1     1     1     1     1     1     1     1        0.68234238
#3     1     1     1     1     1     1     1     1     1     1       -2.09817127
#4     1     1     1     1     1     1     1     1     1     1       -0.09423047
#5     1     1     1     1     1     1     1     1     1     1       -0.94426835

Or with purrr's map_df :
purrr::map_df(dat_list, ~as.data.frame(t(.x)))


What is the type of precision in the prior distribution over user's and item's latent factors in PMF?

Question: I am trying to implement the pmf model in stan. paper
In this model, there are two prior normal distribution over the latent factors of users and items:
$U_i$ ~ $normal(0,\sigma^2I$)
And it is said that the $I$ is a indicator matrix where $I_{ij}$ equals 1 if user $i$ has rated $j$, otherwise 0. I wonder what is the type of $\sigma^2$? single value, or vector,matrix? I think it is just a single value. But if so, the product, $\sigma^2I$ should be a matrix? But the stan can not handle the case where the precision is a matrix, how can I transform it to vector or single value? Thank you in advance!
Comment: This does not make sense, because a covariance matrix must be symmetric but $\sigma^2 I$ will generally be asymmetric. It looks like the paper uses some confusing notation: It defines $I_{ij}$ as you describe, but it uses a boldface $\mathbf I$ to represent the identity matrix, not the matrix $I_{ij}$.
Comment: @BrentKerby is correct that this $I$ refers to the identity matrix. Also, you might be interested in [my Stan implementation of BPMF](https://github.com/AutonlabCMU/active-matrix-factorization/blob/master/stan-bpmf/bpmf.stan) from a few years ago; it does some tricks to speed things up, though it's possible more recent changes in Stan might need updates.
Comment: In retrospect, that code might not be ideal – for example, depending on the density of observations, it's probably faster to multiply $U V^T$ than to dot rows of them together separately. There also might be something smarter to do with the linear algebra, and/or Stan updated functions that would help....
Answer: If you want to use a multivariate normal distribution then you can do this in Stan using multi_normal, e.g. if $U_i$ is a vector of length $K$ you can do
U_i ~ multi_normal(rep_vector(0,K), Sigma)

where Sigma is the covariance matrix.
However $\Sigma = \sigma^2 I$ means you don't have any non-zero covariance terms, so you can just use univariate normals
U_i ~ normal(0, sigma)

which will give each element in $U_i$ a normal distribution with mean zero and standard deviation $\sigma$ (Stan parameterizes the univariate normal in terms of the standard deviation and not the variance).


Nginx and Apache, how to configure proxy_cache?

Question: I have Nginx installed as a front end proxy for Apache, where Apache is servicing PHP and Nginx is servicing static files. I'm having a problem configuring Nginx to cache the output from PHP into a static file. I've tried with proxy_cache, but obviously I'm doing something wrong.
Here is my base configuration:
    server {
            listen   80;

            root /var/www/web;
            index index.php index.html index.htm;

            server_name web.com;

            location / {
                    try_files $uri $uri/ /index.php;
            }

            # cache static files
            location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
                    expires 365d;
                    access_log off;
                    add_header Cache-Control public;
            }

            location ~ \.php$ {
                    proxy_pass http://127.0.0.1:8080;

                    # Set header to be what we requested
                    proxy_set_header        Host    $host;
                    # Set proxy_cache expiry time
                    proxy_cache_valid  200 302  5m;
                    proxy_cache_valid  404      1m;
                    proxy_cache_valid  301      1h;
                    # Need this for snooping with tcpdump (turns off upstream compression)
                    proxy_set_header        Accept-Encoding  "";
                    # Set real IP header (needed for client IP detection in apache)
                    proxy_set_header  X-Real-IP  $remote_addr;
                    # Explicitly allow critical headers
                    proxy_pass_header Set-Cookie;
                    # Prevent 304 responses being returned from Apache and cached by nginx
                    proxy_set_header If-None-Match "";
            }

            location ~ /\.ht {
                    deny all;
            }
    }

Comment: Did you set up the proxy_cache_path? See the answer to this similar question: http://serverfault.com/questions/30705/how-to-set-up-nginx-as-a-caching-reverse-proxy
Answer: set proxy_cache_path in your http{} - context and define your zone and parameters
http {
...

proxy_cache_path /tmp/cache/blue blue:100m ...;
proxy_cache_path /tmp/cache/white white:100m  ...;

...
}

set proxy_cache zone/off in corresponding server/location-context and your options as well
e.g. define your cache pathes globally and activate/deactivate for each server/location
location /blue {

proxy_cache blue;
proxy_cache_...

}

location /white {

proxy_cache white;
proxy_cache_...

}

location /red {

proxy_cache off;
proxy_cache_...

}

beware, your cached files will be in binary format
Comment: I'm still not able to get the cache working..the cache directory is always empty. (I've checked users and permissions on the directory, everything is ok). Here is my configuration: https://gist.github.com/SvenAlHamad/6397956
Comment: your config seems ok. do you have any entries in your error.log? /var/cache must be readable by www-data (chmod 755) and /var/cache/nginx must be writable by www-data (chown).
Comment: everything is fine there...but I noticed one strange thing. When I open mysite/index.php the cache is not created, so I decided to create a test file, text.php and inside I just wrote 'hello'. When I open mysite/test.php the cache file is created inside /var/cache/nginx
Here are the headers http://imgur.com/Ei5ri6v http://imgur.com/4RgDUnn
Comment: does the cache-control-header comes from apache too? http://stackoverflow.com/a/6077195. oh, and could you please change your answer to "how to configure proxy_cache?"
Comment: i asked to change the title of your question, not answer  :)
Comment: I've managed to get the same response headers on index.php as on test.php using proxy_hide_header..but still cache file is not created :( The test.php script creates the cache files normally. I managed to figure out that if I call 'session_start();' in PHP, then cache file is not created...if I remove the session_start, cache file is created.
Comment: hmmm, no clue. maybe you ask on the [nginx-forum](http://forum.nginx.org/)


How to find if this summation equals zero?

Question: For every value of $n_1$ i tested with, it came out as $0$. However I have no idea how to prove if it does or not for every value of ${n_1}$.
Note that ${n_1}$ has to be smaller than ${n_0}$ in the summation.
$$\sum_{i=1}^{n_1} \frac{(-1)^{i+1}2^{{n_1}-i}i({n_0}({n_1}-2+i)+{n_1}(i-1)+i^2-i)}{i!({n_1}-i)!({n_0}+i)({n_0}+i-1)({n_0}+{n_1})}$$
For instance, plugging $2$ to ${n_1}$ and solving the summation gives $\frac{2{n_0}}{({n_0}+1){n_0}({n_0}+2)}-\frac{2(2{n_0}+4)}{2({n_0}+2)({n_0}+1)({n_0}+2)}$, which is equal to $0$.
I have done everything to my knowledge but am still stuck. Any tips?
Comment: I'm not quite sure about this, but if it is zero for every integer $n_1$, then I believe each term must be zero. But the dependence of the individual terms on $n_1$ itself makes me unsure. What values of $n_1$ have you tested it with, and what is the relation, if any, between $n_0$ and $n_1$?
Comment: I have tested with n1 equal to 1,2,3 and 4. I have coded an algorithm that gives the result of this summation given n0 and n1 and in every case the number is extremely close to zero but even for the values i've proven by hand that its zero, the algorithm still gives a number extremely close to zero, i suspect it is because im not working with the floating point numbers well
Comment: $n_0$ shouldn't matter. it is just a constant. it should simplify in your algorithm without being defined. mathematica is probably a good program to test it in.
Comment: Well, I used the program you suggested, and it gave me the answer zero. However it didn't do any explaining. At least now I know it is zero and just have to prove it
Comment: Well, it is certainly nice to know what to aim to prove, so that's a good thing.
Answer: Your sum equals $0$.
The sum can be simplified using the idea of telescoping series.
$$\begin{align}&\sum_{i=1}^{n_1} \frac{(-1)^{i+1}2^{{n_1}-i}i({n_0}({n_1}-2+i)+{n_1}(i-1)+i^2-i)}{i!({n_1}-i)!({n_0}+i)({n_0}+i-1)({n_0}+{n_1})}
\\\\&=\frac{-2^{n_1}}{n_0+n_1}\sum_{i=1}^{n_1} \frac{(-\frac 12)^{i}({n_0}({n_1}-2+i)+{n_1}(i-1)+i^2-i)}{(i-1)!({n_1}-i)!({n_0}+i)({n_0}+i-1)}\tag1
\\\\&=\frac{-2^{n_1}}{n_0+n_1}\sum_{i=1}^{n_1}(f(i+1)-f(i))
\\\\&=\frac{-2^{n_1}}{n_0+n_1}(f(n_1+1)-f(1))
\\\\&=0\end{align}$$
where
$$f(i)=\frac{(-\frac 12)^{i-1}(i-1)(n_1+1-i)}{(i-1)!(n_1+1-i)!(n_0+i-1)}$$

Added :

how does one find f(i)?

The denominator of the sum in $(1)$ is $(i-1)!({n_1}-i)!({n_0}+i)({n_0}+i-1)$.
To have this denominator in $f(i+1)-f(i)$, one can think that the denominator of $f(i)$ is $(i-2)!(n_1-i)!(n_0+i-1)$. This is because the denominator of $f(i+1)$ is $(i-1)!(n_1-i-1)!(n_0+i)$, so the denominator of $f(i+1)-f(i)$ can be $(i-1)!({n_1}-i)!({n_0}+i)({n_0}+i-1)$.
Having $(-\frac 12)^i$, one can think that $f(i)$ is of the form
$$\frac{(-\frac 12)^{i-1}g(i)}{(i-2)!(n_1-i)!(n_0+i-1)}$$
where $g(i)$ is a polynomial on $i$.
Finally, comparing the terms gives $g(i)=1$ fortunately, one has
$$f(i)=\frac{(-\frac 12)^{i-1}}{(i-2)!(n_1-i)!(n_0+i-1)}=\frac{(-\frac 12)^{i-1}(i-1)(n_1+1-i)}{(i-1)!(n_1+1-i)!(n_0+i-1)}$$
Comment: @Eduard : I've found $f(i)$ by trial and error.
Comment: Thanks, but how does one find f(i)?
Comment: @Eduard: I've added some explanations.
Comment: Thank you so much, now I understand.


Model Explanation

Question: I have a problem where I am trying to predict something from historic tabular data.
We have features {X1,X2,..Xn} and I have a prediction {Y}
I am trying to find a way to explain why the model came up with a prediction. In other words, which features were impacting the most that specific output.
I know I can use algorithms such as Feature Importance or Elastic Net to know which features were more important to the model in general (X features), but I want to know given a single specific input what is more important.
Example: I have a client that wants to predict the budget of certain work that they do. I input some variables they give me and my trained model (let's say a DT or Random Forest regressors) comes up with a prediction value. I know that for the model I have X features that are more important but I can't tell my client every time they ask me to come up with a budget that the budget is for the same reasons(X features) than all of the other works.
I know I can plot the Decision Logic of a decision tree regressor with Graphviz for example, but that's okay only for me to understand. My client would want to see a more user friendly way of looking at the reasons behind that prediction. The final tool should be something like they being able to enter the features in fields, then the budget prediction would come up with lets say percentage circles of impact of their input in the prediction.
Do you know about any ways this type of tool can be implemented at least for experiments?
Do you know about any ways of displaying the specific decision path followed by a decision tree regressor of only one prediction?
Answer: Machine learning explainability is an area of active research, quite popular in recent years. This question cannot be answered briefly, because there are many research papers, tutorials, and even books on this subject. It would be an impossible task to summarize them in few sentences. I would encourage you to check the freely available online book Interpretable Machine Learning by Christoph Molnar that deals with this subject.
TL;DR for model-agnostic explanations of individual predictions, you can check methods such as SHAP or LIME. However, keep in mind that those methods approximate your model to give you the explanations, so it is always possible that those explanations may be incorrect.
Answer: To answer your question from a totally uncorrelated perspective, it's instructive to note that in financial engineering and economics, there needs to be some kind of uncertainty around cost or budget estimates, since a single prediction based on the best features won't be sufficient.  Even if you employ ML and determine which features are the most informative through model-building strategies using univariate/multivariate regression models, importance scores from random forests, or any other feature selection method, you still won't have anything to work with that explains how uncertain your cost estimate is.  What is needed is Monte Carlo cost estimation.
What could be more helpful would be to identify the best features which predict cost, develop an objective function, e.g. cost = hourly labor rate * #employees * hours of work.  Then generate histograms for these 3 example inputs, determine which probability distributions fit the best, then simulate quantiles from each, each time calculating the cost.  You will then have a histogram of cost, which you give to the customer, along with providing the 10th and 90th percentile values of cost (or 5th, 95th).  If you were designing an oil rig and presenting cost estimates for a loan from a bank on an enterprise scale, this is what you would be doing.  Below is a simple example of a run for a rollout of a new product after manufacturing.
The cost uncertainty distribution is on the lower right of the panel.
Comment: I understand what you are trying to say about the cost uncertainty. You are right. let's suppose instead of wanting to get a budget I want to predict the hours of work for a given work. How would you approach this type of problem?
Comment: In MC cost analysis, the inputs are usually not predicted.  For example, for the hours needed for a given work, you would need to fetch in your city from multiple companies their estimates of how many hours are required.  That would result in a histogram of hours required. You can use however, "expert knowledge" to make a guess of 3 values (lower, mode, upper) for hours required using a triangle distribution, like the upper left plot for manufacturing with parameters (100,400,500).
Comment: In most industries, there are database on how many whatever are needed to build x widgets or perform x amount of tasks, hourly labor rates, average and s.d. of how much each component cost.  But they are not free. You may be able find a city or government database or something at the U.S. Dept of Labor.   MC cost analysis to get a loan to build an oil rig is done by PhD economists who work at oil companies.  So if they need anything that's not free, they just fetch the money and buy it.

Model Explanation


Are the multiplicative inverses contained in the cone?

Question: Definition: A cone of a field $F$ is a subset $P$ of $F$ such that :

$x,y\in P\implies x+y\in P$
$x,y\in P\implies xy\in P$
$x\in F\implies x^2\in P$

I would like to know if the third condition is important in this definition, because for me it's just a consequence of the second one. Another doubt is if $x^{-1}\in P$ whenever $x\in P$.
Thanks a lot!
Comment: @HaraldHanche-Olsen you are right! I'm so sorry
Comment: Ah, I had missed the point that there is still an $F$ to the left of the implication in 3. Previous comment withdrawn.
Comment: @rschwieb I'm going to edit it
Comment: @rschwieb: clicking on the tag "real algebraic geometry" brings up a list of 15 questions...
Comment: @rschwieb It's up to you to decide, I found this material in a book in real algebraic geometry.
Comment: @AsalBeagDubh Oh! yeah I was looking at "0 followers," nevermind :) Let's go with it then.
Answer: Point 3 is not just a consequence of point 2. For example, $\Bbb Z$ satisfies 1 and 2 in $\Bbb Q$, but it does not satisfy 3.
Point 3 tells you that for any $x\in P$, $x^{-2}\in P$. Multipying $xx^{-2}$, you get $x^{-1}\in P$.
Comment: @user122342 That happens to me all the time :)
Comment: Of course, I had misread the third point. Thank you!
Answer: The example you should go to is $\mathbb R^+=\{x\in \mathbb R\mid x\geq 0\}$. This is a cone of $\mathbb R$ since $x+y\geq 0$ and $xy\geq 0$ if $x\geq 0$ and $y\geq 0$, and if $x\in \mathbb R$ then $x^2\in \mathbb R^+$. This should clarify that (2) and (3) are distinct conditions: we require that (for example) $(-1)^2\in \mathbb R^+$. In particular, a set like $\{x\in \mathbb R\mid x\geq 2\}$ is not a cone even though it satisfies (1) and (2).
Comment: I'm really sorry, it's good now.


Why are there owners willing to pay so much for sports teams?

Question: I found a list of most valuable sports teams, and I was amazed at the valuations. Why are there owners willing to drive the value of these teams so high?
For example, Real Madrid is listed with a value of USD 3.65 Billion.

We know that they are getting revenue through sponsorships, television broadcast rights fees, Internet broadcasting, and match ticket sales. Do those together justify such high valuations?
Comment: OK, then ask that question. "Why are there owners willing to pay to purchase sports teams when the valuations are so high?" That's not opinion-based, although it does ask for some speculation about motivations.
Comment: "Too much" seems to be entirely opinion based to me - that's the value because that's what someone else would have to pay to own the team.
Comment: @PhilipKendall i am curious to know why someone will pay that much to purchase the team!.....
Answer: From Application of Income Approach for Valuation of Football Club by Ilia Solntsev mention teams are getting revenues through number of causes namely:

Matchday, Broadcasting Revenues, Sponsorship, Merchandising, Stadium Revenues, Additional Sources of Income(pen branded restaurants, clubs, fitness centers etc.), Fans

but that can not justify those high valuations. Because clubs are valuated by different technique, above valuation is of Forbes Valuation Technique and different values will use different data to valuate clubs.
Look at this example used by Markham:

Anomalies in football club valuation – Tottenham Hotspur 2012:
Market Capitalisation Value :  £83.6m
Revenue Multiples Value : £245.2m
Forbes Value : £351.1m

Which clearly shows different method yields different club value.
From "What is the optimal method to value a football club?" by Tom Markham.
Traditional corporate valuation techniques are Market capitalisation, Discounted Cash flow (DCF) models, Bankruptcy valuation. And methodologies used within the football sector to ascertain a club's worth are Revenue multiples approach, Forbes valuation, Broker valuation and Multivariate model for EPL club valuation.
At last, valuations are done with different set of data and owner may not pay the same amount as valuation.
Forbes valuation hasn't been accurate to predict the sales of team i.e; Real Madrid valuation of USD 3.65 Billion doesn't mean that cost of buying Real is 3.65 Billion.

Results show that on average the transaction cost of the North American sports franchises was 27% higher than Forbes had estimated for 2004. Forbes estimates were between 59.2% lower (Manchester City in 2008) and 69.1% higher (Liverpool in 2010) than actual transaction prices.


Variable controlling in linear regression and covariates

Question: I am analyzing cardiac data and have interests in cardiac problems and exercise.
I just want to focus on the exercise effect and found AGE is significant variable.
I'd like to control AGE variable because it was not my interest.
All the variables were AGE, GENDER, blood pressure, smoke, BMI, drink, stress, exercise and the dependent variable is cardiac problem(the sum of cases of cardiomyopathy, heart failure, myocardial infarction), and the sample size is 2200.
After simple linear regression, I found the AGE, GENDER, blood pressure (measurement), BMI, exercise(time per week), stress (PWI-SF score) were significant. I separated the data by GENDER and made models by adding variables in order. The problem is I just want to focus on the association among the variables without AGE effect. Although AGE is important variable in the disease data, I'd like to deal with it as confounder.
I found this page explaining how to controlling AGE factor in the analysis.
http://rstudio-pubs-static.s3.amazonaws.com/310471_2dbd42091bab4771af1d39f687b2ac20.html
I understood this is an example of the subtracting the regression effect of the non-interesting variable from the dependent variable.
i.e.
new_Y = Y - predict(lm(Y ~ AGE)).
model = lm(data, Y ~ AGE + excercise + ...)
new_model = lm(data, new_Y ~ AGE + exercise + ...)

This looks different from ANCOVA, subtracting covariates from the variable.
Actually, I failed ANCOVA in r depending on the order of the variables (I couldn't control the AGE effect) and succeeded by this method.
So, I'd like to know whether my understanding is right and hopefully the reference.
Thank you.
Comment: The modelliing in the linked page seems like some kind of lngitudinal model which may not be appropriate for you study and data. Please edit the question to include details of all the variables you have and the size of the dataset.
Comment: @RobertLong edited, thanks.
Answer: First of all, try not to be too concerned with p values. They are heavily reliant on sample size. Second, the linked document is not relavent to your analysis as far as I can tell.
I would suggest a multivariable regression model.
You should include variables in your model based on expert knowlege of cardiology - if there is reason to believe that all the variables are associated with the outcome then they should be considered for inclusion in the model.
In your case it seems that age is a possible confounder - along with gender.
There is no point in splitting the data by gender and this will just lead to a loss of statistical power. Instead you can interact gender with your main exposure, exercise.
Then the issue becomes how to handle the other variables: Blood Pressure, BMI and Stress. It seems plausible that the main exposure, exercise, causes (negatively affects) all three of these, and also that all 3 of these may be causes of the outcome. As such, they lie on the causal path between exercise and thee outcome. That is, they are mediators and should NOT be included in the model, otherise you will only be estimating the direct effect of exercise, and not the total affect (the direct affect plus the mediated/ indirect effects)
It is always good to draw a causal diagram / DAG in this type of situation. Here is one that reflects the assumptions in the previous paragraph:

This was produced using http://www.dagitty.net/dags.html#
According to this diagram the correct model would be:
lm(Cardiac ~ Exercise + Gender + Age, data = mydata)

If you want to allow for different effects in each gender then you can also fit the interaction, as mentioned above:
lm(Cardiac ~ Exercise + Gender + Exercise:Gender + Age, data = mydata)

Of course it is possible that you disagree with the causal assumptions above. For example, you might believe that BMI causes exercise (because people with high BP will be encouraged to exercise more). This is a judgement you have to make yourself, and this reflects some of the inherent problems in analysing observational (rather than experimental) data. I would strongly recommend reading this post:
How do DAGs help to reduce bias in causal inference?
Comment: Maybe the similar view point, cause I thought the Structure Equation Model, other values as potential variables, but before the process, I think regression should be conducted first and wanted to get rid of confounders.  I should think about the attached web page contents. Thank you for your opinion!
Comment: You're welcome. I haven't studied the linked page in detail but at a glance, some of the things they are doing seem very strange to me. And, I agree, an SEM model might be useful.


Image measure - transportation of expectation (change of variable formula)

Question: In the "base case" of the proof of the change of variable formula, we have the following setting:
$(\Omega, \mathcal{A}, P)$ a probability space,
$h$ a measurable function from this probability space to $(S, \mathcal{S})$.
And it is written: For $B \in \mathcal{S}$
$\int_S 1_B d (h \circ P) < \infty$ iff $\int_{\Omega} (1_B \circ h) dP$
is obvious, where $(h \circ P)(A):=P[h^{-1}(A)]$ for all $A \in \mathcal{S}$.
can you help me proving that this is obvious?
Answer: The integral of an indicator function $\mathbf{1}_B$ is just the measure of $B$, by definition. Therefore
$$
\int_S \mathbf{1}_B \, d(h \circ P)
= (h \circ P)(B)
= P[h^{-1}(B)].
$$
Similarly, $\mathbf{1}_B \circ h = \mathbf{1}_{h^{-1}(B)}$ (since $h(\omega) \in B$ if and only if $\omega \in h^{-1}(B)$), so
$$
\int_\Omega (\mathbf{1}_B \circ h) \, dP
= \int_\Omega \mathbf{1}_{h^{-1}(B)} \, dP
= P[h^{-1}(B)].
$$
Therefore $\int_S \mathbf{1}_B \, d(h \circ P) = \int_\Omega (\mathbf{1}_B \circ h) \, dP$.


How to prove Codim $V(I + J) \leq$ Codim $V(I) + $ Codim $V(J)$?

Question: Let $I_1, I_2, I_3$ be three ideals in $\mathbb{C}[x_1, .., x_n]$.
Let $V(J) = \{ \mathbf{x} \in \mathbb{C}^n : f(\mathbf{x}) = 0  \ for \ all \ f \in J \}$.
How can I prove that  Codim $V(I_1 + I_2 + I_3) \leq$ Codim $V(I_1) + $ Codim $V(I_2)$ + Codim $V(I_3)$ ?
Here, Codim $V(I_j) = n - \dim V(I_j)$ and by dimension I mean as an algebraic set in $\mathbb{C}^n$. Any comments are appreciated. Thank you!
Comment: The title has two ideals, the body has three. Anyway, the statement for two ideals extends easily to any finite sum.
Comment: @egreg Right, and how does one prove this for two ideals?
Answer: Let us fix once for all times in the sequel the polynomial ring $A=\mathbb C[X_1,X_2,\dots,X_n]$, which is noetherian, in it two ideals $$I,\ J$$ generated by
$$f_1,\dots, f_i\in A\ ,$$
and respectively
$$g_1,\dots, g_j\in A\ .$$
We can and do assume that $i, j$ are minimal with these properties.
Let $K$ be the ideal generated by $I$ and $J$,
$$ K = I+J\ ,$$
it has the generators
$$f_1,\dots, f_i\ ;\ g_1,\dots, g_j\in A\ ,$$
but this list may not be minimal. (E.g. for $I=J$ non-trivial ideal.)
The question is now related and follows from "dimension theory". The dimension can be defined in various ways:Dimension_of_an_algebraic_variety
From the list, there are at least three "worlds", categories, mathematical domains, where the notion can be defined, and which are relevant for the question. These are:

For an ideal $I$ in a ring $R$ we can define its height. A notion of "dimension" is not used commonly for ideals, but it is used for commutative rings. In our case, this notion applies for $R$ and the quotient ring $R/I$, and it is called Krull dimension. Reference: Krull_dimension. This is a purely algebraic object.
In both cases, the definitions deal with the length of chains of prime ideals, ordered by strict inclusions. (The number of the strict inclusions in the chain is the length.)
(In order to relate $\dim A$ with $\dim (A/I)$ and the height of $I$, one has to find a natural way to "combine" and/or reduce chains. In the p.o.-set of ideals, one can consider the ideals that can be compared with $I$, and only chains going through this "strangulated" po-set. Then one needs a way to ensure same lenght of maximal chains - under favorable circumstances, we have such a situation.)
For an (affine) algebraic variety $X$ we have a dimension. This is defined in the algebraic geometry by passing to affine coverings, writing each affine piece as a Spec(trum) of a ring, then using the Krull dimension for rings.
For a differential manifold $M$ over $\mathbb C$ we also have a notion of dimension, this is defined by using charts (near regular points) to open domains in the one or other standard affine space $\mathbb C^k$ for some fixed $k$. (This is the dimension of $M$.) To an (affine) algebraic variety $X$ as in the posted question,
$$ X = \text{Spec}(A/I)\ ,$$
we can associate the corresponding manifold
$$M=X(\mathbb C)\ ,$$
which is as a set $V(I)$. Moreover, the projection
$$ A\to A/I$$
induces the map (of ringed topological spaces)
$$ \text{Spec} A \leftarrow \text{Spec} (A/I)\ ,$$
which is
$$ \mathbb C^n\leftarrow V(I)\ .$$
The left arrows are inclusions. The codimension in the question is taken with respect to these canonical inclusions for $I,J;K$.

The inequality $\text{codim} V(I+J)\le \text{codim} V(I) +\text{codim} V(J)$ follows now as follows:
\begin{align}
\text{codim} V(I) &= \dim \mathbb C^n -\dim V(I) = \dim A -\dim(A/I) = \text{height}(I)
\\
&= i\ ,
\\\\
\text{codim} V(J) &= \dim \mathbb C^n -\dim V(J) = \dim A -\dim(A/J) = \text{height}(J)
\\
&= j\ ,
\\\\
\text{codim} V(I+J) &= \dim \mathbb C^n -\dim V(I+J) = \dim A -\dim(A/(I+J)) = \text{height}(I+J)
\\
&\le i+j\ .
\end{align}
Here, we have tacitly used the passage

from chains of systems of generators like $()\subset (f_1)\subset\dots\subset (f_1,\dots,f_i)$
to chains of prime ideals included in $I$.

which is Krull's principal ideal theorem as stated here:
Consequences...
In most proofs, one needs Hilbert's Nullstellensatz.
Comment: Thank you very much for this!!! :)
Comment: You say codim $V(I) = i$, but this means $V(I)$ is a complete intersection... but I thought not all ideals were complete intersections?


Unexpected MYSQl error 1286

Question: I am using shared host and after some problems they restarted the server and my Drupal website shows the following error:
<code>PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286 Unknown table engine 'InnoDB': SELECT
</code>
This is the full log
Error message

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286
  Unknown table engine 'InnoDB': SELECT
  field_data_media_gallery_expose_block0.entity_type AS entity_type,
  field_data_media_gallery_expose_block0.entity_id AS entity_id,
  field_data_media_gallery_expose_block0.revision_id AS revision_id,
  field_data_media_gallery_expose_block0.bundle AS bundle FROM
  {field_data_media_gallery_expose_block}
  field_data_media_gallery_expose_block0 WHERE
  (field_data_media_gallery_expose_block0.media_gallery_expose_block_value
  = :db_condition_placeholder_0) AND (field_data_media_gallery_expose_block0.deleted =
  :db_condition_placeholder_1) AND
  (field_data_media_gallery_expose_block0.entity_type =
  :db_condition_placeholder_2) AND
  (field_data_media_gallery_expose_block0.bundle =
  :db_condition_placeholder_3) ; Array ( [:db_condition_placeholder_0]
  => 1 [:db_condition_placeholder_1] => 0 [:db_condition_placeholder_2] => node [:db_condition_placeholder_3] => media_gallery ) in field_sql_storage_field_storage_query() (line 577 of
  /home/fossisor/public_html/techiestuffs/modules/field/modules/field_sql_storage/field_sql_storage.module).

What is wrong with the database ?
Comment: A quick google gives this link, which gives some more insight: http://www.youdidwhatwithtsql.com/unknown-table-engine-innodb/760
Answer: Sounds like your hosting provider does not support InnoDB. There are a few others like you, here is a discussion thread with some ideas on how to fix it http://drupal.org/node/1089724
Comment: Have you checked your other sites since the server restart?
Comment: but My other drupal sites in same host works great

Unexpected MYSQl error 1286


How to show that if $ p \equiv 1,3 \pmod 8$ then there exists a $u,v \in \mathbb Z: u^2 + 2v^2 = p$

Question: I'm trying to show this statement:
$$p \equiv 1,3 \pmod 8, \; \; \exists \; u,v \in \mathbb Z : u^2 + 2 v^2 = p.$$
I believed I proved it the other direction using the ring $\mathbb Z{\sqrt{-2}}$. This is my reasoning so far: Suppose that $-2 \equiv x^2 \pmod p$ then $p$ divides $x^2 + 2 = (x - i\sqrt{2})(x + i\sqrt{2})$. This shows that $p$ is not a prime, that is $p = mn $. Taking the norms, we get $N(p) = N(m)N(n) = x^2 + 2y^2$ We can see that $p \equiv 1,3 \pmod 8$. How do I prove using the forward direction?
Comment: what about Jack D'Aurizio's proof ? It only uses fermat's descent (Elementary-Numbertheory)
Comment: http://math.stackexchange.com/questions/685958/let-p-be-prime-and-frac-3p-1-prove-that-p-is-of-the-form-p-a23b2/685983#685983 -- will this help ??
Comment: user129017 I am taking a class that only assumes that you've taken 1 calculus and 1 linear algebra course. The number theory is being introduced under the context of writing expository proofs. I am familiar with Legendre's symbol but not all of its properties and I have no idea what a lattice is.
Answer: As this has class number one there are many approaches. Solve
$$ \beta^2 \equiv -8 \pmod p.  $$ If your $\beta$ is odd, replace by $p-\beta$ which is even, anyway call it $b.$ Now you have
$$ b^2 \equiv -8 \pmod {4p}  $$ with $b$ even, or
$$ b^2 - 4pt = -8.  $$
So, the binary quadratic form
$$  \langle p,b,t \rangle  $$  or
$$  f(x,y) = p x^2 + b x y + t y^2  $$ has discriminant $-8.$ Gauss reduce this, the result is  $$  \langle 1,0,2 \rangle  $$ because that is the only reduced form for that discriminant.
ALMOST DONE
So, reduction: there is a 2 by 2 matrix with determinant 1, write it as
$$  P = \;
 \left(  \begin{array}{rr}
  \alpha &  \beta   \\
   \gamma & \delta
\end{array}
  \right),  $$
also name
$$  M = \;
 \left(  \begin{array}{rr}
  p & b/2   \\
   b/2 & t
\end{array}
  \right),  $$
and
$$  R = \;
 \left(  \begin{array}{rr}
  1 & 0   \\
   0 & 2
\end{array}
  \right).  $$
The relationship found by doing reduction step by step is
$$ P^T M P = R.  $$
Let $Q = P^{-1}.$ Then
$$ Q^T R Q = M.  $$
The left-hand column of $Q$ gives the representation of your original prime $p.$ Multiply it out.


Relations - Logical Boolean Matrix

Question: I am having trouble with the following question:
Relations $S$ and $R$ are defined on the set $$\{1, 2, 3, \ldots, 12\}$$
as follows: $$R = \{(x, y)\mid xy = 12\}$$ $$S = \{(x, y)\mid 2x = 3y\}$$
So far I have resolved the composite matrix S o R to be:
{(3,6),(6,3),(9,2)}
Would the logical boolean matrix therefore look the following?
Comment: Well, you need to completely define the matrix (that is, false everywhere except for the three entries above), but otherwise you are correct.
Answer: What you've written is fine, for those values, but it tells us nothing about the truth value of  $(1, 2)$ with respect to $S\circ R$. So I would add that for $x \in S$, you expand your answer (words will do). E.g.,
Putting $U = \{1, 2, 3, \ldots, 11, 12\}$:
Then for all $x \in U, \;x \notin \{3, 6, 9\}$, for all $y \in U$,  $(x, y)\notin S\circ R$, i.e., $\operatorname{boolean}(x, y) = F$

Relations - Logical Boolean Matrix


Markov Chain Ergodic Theorem

Question: Consider a discrete time Markov Chain on countable state space $X_{0},X_{1},\ldots$. Assume that the chain satisfies the Foster Lyapunov criteria, and since it is countable state space chain, we conclude that it is positive recurrent. Will it still be true that for a bounded function $f$ we have $\frac{1}{n}\sum_{i=0}^{n}f(X_{i})\to Ef(X)$, where the expectation on rhs is wrt the stationary distribution of the process.
Answer: Yes, when I am thinking about this I dont know why not. As long as is ensured that every state can be expected to be returned to. Then all states in such an irreducible Markov chain being ergodic; follows the chain to be ergodic. With criteria of Foster Lyapunov fulfilled I shall understand that stability is ensured.
Of course, we are talking about a first order Markov chain of no memory.
Comment: Note that I am assuming that I do not know the irreducibility measure. In the proof of Lyapunov drift implies positive recurrence  there should be an explicit expression for the irreducibility measure. I want to verify that. I guess I can take the unique stationary measure to be the $\psi$ irreducible measure.

 For example, the conclusion would be false for uncountable state space. In short the chain is such that all states are not reachable.
Comment: AHA! Have a look here complement to my answer. This goes deeper: http://www.sciencedirect.com/science/article/pii/S0304414900000855
Comment: Did the approach work?
Comment: seems the drift condition is sufficient....

Markov Chain Ergodic Theorem


NetLogo: How to create links with a defined number of other turtles

Question: I want to create a (scale-free) network where each turtle is connected to a specific number, say four, of other turtles. To allow some turtles to have many connections while others have few (but not less than four), my thought was to let each turtle have four out-links and let in-links would necessarily vary. Using the code for building a Barabasi-Albert scale-free network available on pg. 131 in Scott and Koehler's "A Field Guide to NetLogo" as a starting point, my code is included below.
My question is how to make each turtle connnect to four other turtles.
breed [liberals liberal]
breed [conservatives conservative]

to setup
    clear-all
    set-default-shape turtles "circle"
    create-liberals 5 [
    set adopt? false
    let n count turtles
    set color blue
    ]
create-conservatives 20 [
    set adopt? false
    let n count turtles
    set color red
    ]
    let m 4
    let p .05
    set my-threshold my-threshold
ask turtles[
    let me self
    let degrees max-n-of m turtles [count link-neighbors]
    foreach (sort degrees) [ [?] ->
    let chance random-float 1.0
    if ( ? != self) and (chance < p ) [
    ask self [ create-link-to ? ]
    ]
    ]
]
ask turtles with [(count out-link-neighbors) = 0 ] [
let degrees max-n-of m turtles [ count link-neighbors ]
let t one-of degrees
foreach (sort degrees) [
ask self [ if ( t != self) [ create-link-to t] ]
]
]
reset-ticks
end

The code above is part of my attempt to recreate Paul Ormerod's model, available at https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1468-0270.2006.00611.x
Answer: Since you are doing a directed network, you won't have any issues with simply telling each turtle to select 4 other turtles and connect to them. The code for that would be:
ask turtles
[ create-links-to n-of 4 other turtles
]

Note that this is much more difficult in undirected networks because the links they 'receive' lead to too many links overall. Then you need to do something like NetLogo Efficient way to create fixed number of links
However, this will not get to your stated goal of a preferential attachment (scale-free, Barabasi-Albert or whatever you want to call it) degree distribution. The mechanism that generates that outcome is that the turtles select the turtles to make links with using weighted random selection, with the weight a normalised degree. You need the rnd extension and that gets you the weighted-n-of primitive.
I also noted some general issues with your code that are related to (I think) confusion about how the preferential attachment algorithm works and/or how NetLogo works. The weighted-n-of primitive will get rid of your need to look at random numbers and should simplify your code a lot. However, I am not clear what let degrees max-n-of m turtles [count link-neighbors] is supposed to do, but it appears to be creating a list of the four highest degree turtles. But the preferential attachment algorithm allows links to be created with even low degree nodes, just with lower probability.
Comment: Okay. Have you programmed with other languages or are you also new to programming? Apart from any other issue, I strongly suggest you code more iteratively. Get code working to create the network, then worry about your different breeds of turtles, for example.
Comment: Hi JenB! Thanks for the quick response. I am definitely confused as I have just started to learn ABM and NetLogo, so the code above necessarily holds the mistakes from a process of trial and error. I will familiarize with the 'rnd' extension
Comment: I have only used Stata previously, so a step back is probably the best thing!


PCA: Iteratively reducing dimensions

Question: ist there a difference between Iteratively removing one dimension with the least variance by computing pca and repeating this process until the data has k dimensions less...
Compared to calculating pca and removing the k dimensions with the least variance at once.
Thank you!
Answer: I believe there are shorter explanations, but here is my bit on it: PCA component axes are eigenvectors of the data covariance, and if $u$ is a normalized eigenvector, $-u$ is also one. Since you can choose one of them arbitrarily, iterative PCA does not guarantee the same output. However, if we put a rule on the eigenvectors such that they're uniquely determined, e.g. the first non-zero element will be positive, the two procedures will produce same results.
Without loss of generality, we can assume that our data is centered, i.e. has zero mean; let's call it as $X_{n\times k}$, where $n$ is the number of samples and $k$ is the number of dimensions. Let the eigen decomposition of $X^TX$ be $US_kU^T$, where the diagonal elements of $S_k$ are in non-increasing order. The first $k-1$ columns of $U$ will define the first $k-1$ component axes. When we omit the last column, i.e. the column with the least explained variance, the new data is $X_1=X\ [u_1\ldots u_{k-1}]$, which also has zero mean.
Now, we apply PCA again on this one: $$\begin{align}X_1^TX_1&=\begin{bmatrix} u_1^T \\ \vdots \\u_{k-1}^T \end{bmatrix}X^TX\begin{bmatrix}u_1 \ldots u_{k-1}\end{bmatrix}=\begin{bmatrix} u_1^T \\ \vdots \\u_{k-1}^T \end{bmatrix}US_kU^T\begin{bmatrix}u_1 \ldots u_{k-1}\end{bmatrix}=\underbrace{S_{k-1}}_{U_1S_{k-1}U_1^T,\ \ U_1=I}\end{align}$$
$S_{k-1}$ denotes the upper-left $k-1\times k-1$ part of $S_k$, containing the largest $k-1$ eigenvalues. So, the new data scatter matrix is already in diagonal form, which means the eigenvectors are canonical vectors, i.e. $U_1=I_{k-1}$. When we do one more iteration, we calculate the following:
$$X_2=X_1[e_1\ldots e_{k-2}]=[x_{1,1}\ldots x_{1,k-1}]$$
where $x_{1,j}$ denotes the $j$-th column of $X_1$, and $e_i$ is the canonical vector, i.e. $e_i=[0\ldots \underbrace{1}_{i}\ldots 0]^T$. So, iteratively created new data is just the first $k-2$ columns of $X_1$. This is similar for $X_3,X_4$, ... etc. So, we're just filtering out the columns of $X_1$. We could have done this from the beginning, without the need of any iterations.
Comment: Thank you! Could you elaborate a little bit on the rule for the determining of the eigenvectors?
Comment: For a given matrix, finding the eigenvectors is equivalent to solving the equation $Ax=\lambda x$, for $\lambda,x$. There are plenty of resources in the internet. For example: https://lpsa.swarthmore.edu/MtrxVibe/EigMat/MatrixEigen.html

PCA: Iteratively reducing dimensions


How to implement Multi checkbox filter in Jquery?

Question: Here Fiddle:http://jsfiddle.net/abhiklpm/ZEDR9/5/
Here I have Implemented Multiple checkbox with filter, But the filter is getting overriden on clicking the second checkbox
EX: If i click Shipping all the shipping will come in below table
But at the same time if i click 1GB The intersection of shipping and 1GB should only come but shipping options getting overriden.
like If i click Shipping & 1GB Only (product) Memory1 only should come.
Help me out in this
<code>   **Script**

 $("input:checkbox").click(function () {
var showAll = true;
$('tr').not('.first').hide();
$('input[type=checkbox]').each(function () {
    if ($(this)[0].checked) {
        showAll = false;
        var status = $(this).attr('rel');
        var value = $(this).val();
        $('td.' + status + '[rel="' + value + '"]').parent('tr').show();
    }
});
if(showAll){
    $('tr').show();
}
});
</code>
Comment: http://jsfiddle.net/arunpjohny/y29Lp5p1/3/ ?
Answer: Try to create a filter set and loop through the filter and apply them like
<code>var $checks = $("input:checkbox").click(function () {
    var $trs = $('tr').not('.first');

    var filters = {}, flag = false;
    $checks.filter(':checked').each(function () {
        var rel = $(this).attr('rel');
        filters[rel] = filters[rel] || [];
        filters[rel].push('.'+rel+'[rel="'+this.value+'"]');
        flag = true;
    })
    if (flag) {
        $trs.show();
        $.each(filters, function (rel, list) {
            $trs.not(':has('+list.join()+')').hide();
        });
    } else {
        $trs.show();
    }
});
</code>
Demo: Fiddle


Let $A,B, C,A',B'$ be an abelian groups. Let $f:A\to B$ and $g:B\to C$ be group homomorphisms.

Question: Let $A,B, C,A',B'$ be an abelian groups.
Let $f:A\to B$ and $g:B\to C$ be group homomorphisms.
Suppose $A'\cong A$, $B'\cong B$ and $C\cong C'$ as abelian groups and $imf\subset kerg$.
Let $f':A'\to B'$ and $g':B'\to C'$ be induced map.
($f'$ is a composition map $ A'\cong A\to B\cong B'$, and the same for $g'$ )
Then, How can we say there is an isomorphism between $kerf/imf \cong kerf'/img'$ ?
If both $kerf$ and $img$ is finite, it is clear $kerf/imf$ and $kerf'/img'$ has the same order, but I'm stuck with constructing isomorphism between them.
Comment: "Then, How can we say there is an isomorphism between $kerf/imf \cong kerf′/img′$". Here, are you asking for isomorphisms between $ker f$ and $ker f'$ and $im g$ and $im g'$? I think there's a typo here, and also the way you've written this makes it look like you are taking quotients, which is confusing.
Answer: Preliminary fact.
Consider a commutative square of abelian groups as below, where the horizontal homomorphisms are isomorphisms: $\require{AMScd}$
$$\begin{CD}
M@>\sim>>M'\\
@V\alpha VV @V\beta VV\\
N@>\sim>> N'
\end{CD}$$

The unique homomorphism $\operatorname{ker}\alpha\to\operatorname{ker}\beta$ which makes the following square commutative is an isomorphism:
$$\begin{CD}
\operatorname{ker}\alpha@>>>\operatorname{ker}\beta\\
@VVV @VVV\\
M@>\sim>> M'
\end{CD}$$
The unique homomorphism $N/\operatorname{im}\alpha\to N'/\operatorname{im}\beta$ which makes the following square commutative is an isomorphism:
$$\begin{CD}
N@>\sim>>N'\\
@VVV @VVV\\
N/\operatorname{im}\alpha@>>> N'/\operatorname{im}\beta
\end{CD}$$

Answer.
In your problem, you obtain an isomorphism $h:\operatorname{ker}g\to\operatorname{ker}g'$, using point (1) on the following square: $$\begin{CD}
B@>\sim>>B'\\
@Vg VV @Vg' VV\\
C@>\sim>> C'
\end{CD}$$ Since $\operatorname{im}f\subset\operatorname{ker}g$ and $\operatorname{im}f'\subset\operatorname{ker}g'$, you get the following square:$$\begin{CD}
A@>\sim>>A'\\
@Vf VV @Vf' VV\\
\operatorname{ker}g@>h>> \operatorname{ker}g'
\end{CD}$$
Applying point (2) to the latter square gives the isomorphism you're looking for.
Comment: Oh, but this does not make the square diagram commutative.
Comment: But when $M=2\Bbb{Z}$, $M'=\Bbb{Z}$, $N=\Bbb{Z}$ and $N'=\Bbb{Z}$ and $α,β$ are both  inclusions, I think $N/imα$ and $N'/imβ$ is not isomorphic.


HTML 2 div's next to eachother but also centered

Question: HTML CODE
CSS CODE
I want the 2 "product" div's to be next to eachother.but them both in the middle
i tired float left, and text align center (in all kinds of combinations and under every .class related but noting worked
text align center puts them both in the center but underneath eachother
text align center, followed by float left, does the same, or puts them both left.
.articles{
    font-family: Arial, Helvetica, sans-serif;
}

.buy{
    padding: 5px 5px 5px 5px;
    font-size: 25px;
    font-weight: bold;
    text-decoration: none;
}

.product{
    margin: 60px 0 60px 60px;
    float: left;
}

.product img{
    width: 200px;
    height: 400px;
    border: 10px solid tan;
}

I tied the combo:
" text-align: center;
float: left;        "
both under .articles and under .product
also tried splitting them
(e.g. text-align under articles, and float under product. and other ways around)
Answer: Ok, you can do this with flexbox. Try this code right here:

      left

      right

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Count the number of pattern matches in a string

Question: For example, I have a string
"AAAAAAACGAAAAAACGAAADGCGEDCG"

I want to count how many times "CG" is repeated.
How do I do that?
Answer: You can use gregexpr to find the positions of "CG" in vec. We have to check whether there was no match (-1). The function sum counts the number of matches.
> vec <- "AAAAAAACGAAAAAACGAAADGCGEDCG"
> sum(gregexpr("CG", vec)[[1]] != -1)
[1] 4

If you have a vector of strings, you can use sapply:
> vec <- c("ACACACACA", "GGAGGAGGAG", "AACAACAACAAC", "GGCCCGCCGC", "TTTTGTT", "AGAGAGA")
> sapply(gregexpr("CG", vec), function(x) sum(x != -1))
[1] 0 0 0 2 0 0

If you have a list of strings, you can use unlist(vec) and then use the solution above.
Comment: Thank you again. And now, if I have a list of strings,[1] "ACACACACA"
[2] "GGAGGAGGAG"
[3] "AACAACAACAAC"
[4] "GGCCCGCCGC"
[5] "TTTTGTT"
[6] "AGAGAGA"     How can I apply the Gregexpr function?
Comment: The function is already vectorised. Do you have a `list` or a `vector`. If a `list` just `unlist( mylist )`
Comment: @lgxqzz I updated the solution and added another one for a vector of multiple strings.
Answer: Use str_count from stringr. It's simple to remember and read, though not a base function.
library(stringr)
str_count("AAAAAAACGAAAAAACGAAADGCGEDCG", "CG")
# [1] 4

Answer: The Bioconductor package Biostrings has a matchPattern function
countGC <- matchPattern("GC",DNSstring_object)

Note that DNSstring_object is FASTA sequence read in using the biostring function readDNAStringSet or readAAStringSet
Answer: In base R, you could use substring with a loop to look for the occurrences of CG
> str <- "AAAAAAACGAAAAAACGAAADGCGEDCG"
> x <- sapply(seq(nchar(str)-1), function(i) substring(str, i, i+1) == 'CG')
> sum(x)
## [1] 4

Answer: It might be interesting to perform a String processing Functions Benchmark
## Data
require("stringi")
vec = paste0(sample(LETTERS, 1e6, replace = TRUE), collapse = "")
df <- data.frame(vec, vec, vec, vec, vec,
                 vec, vec, vec, vec, vec,
                 stringsAsFactors = FALSE)

### Base method
base_fun <- function(x){
  sapply(gregexpr("CG", x), function(x) sum(x != -1))
}

### Stringi Method
stringi_fun <- function(x){
  sapply(x, function(x) stri_count_fixed(x,"CG"))
}

### Stringr method
library(stringr)
stringr_fun <- function(x){
  sapply(x, function(x) str_count(x, "CG"))
}

base_fun(df)
# [1] 1441 1441 1441 1441 1441 1441 1441 1441 1441 1441

stringi_fun(df)
# vec vec.1 vec.2 vec.3 vec.4 vec.5 vec.6 vec.7 vec.8 vec.9
# 1441  1441  1441  1441  1441  1441  1441  1441  1441  1441

stringr_fun(df)
# vec vec.1 vec.2 vec.3 vec.4 vec.5 vec.6 vec.7 vec.8 vec.9
# 1441  1441  1441  1441  1441  1441  1441  1441  1441  1441

require(rbenchmark)
benchmark(base_fun(df), stringi_fun(df), stringr_fun(df))
# test replications elapsed relative user.self sys.self user.child sys.child
# 1    base_fun(df)          100  17.499    1.000    17.513        0          0         0
# 2 stringi_fun(df)          100  34.897    1.994    34.926        0          0         0
# 3 stringr_fun(df)          100  17.555    1.003    17.564        0          0         0

In this particular example, this are the results. Feel free to add, or change whatever them.
    base_fun(df) = stringr_fun(df) > stringi_fun(df)
EDIT: The search engine in stringi 0.2-3 has been drastically improved. New benchmarks (on a different machine):
benchmark(base_fun(df), stringi_fun(df), stringr_fun(df))
##              test replications elapsed relative user.self sys.self user.child sys.child
## 1    base_fun(df)          100  26.412   21.214    26.353    0.004          0         0
## 2 stringi_fun(df)          100   1.245    1.000     1.241    0.000          0         0
## 3 stringr_fun(df)          100  26.995   21.683    26.905    0.011          0         0

So we have stringi << base = stringr
Comment: Why are you doing this on data.frame and not on vector?
Comment: To see how it scales. A data.frame has several vectors.
Answer: Use stri_count_fixed from stringi package
require("stringi")

dna=c("a","g","c","t")
N=160
x=sample(dna,N,4)
x2 <- stri_paste(x,collapse="")
stri_count_fixed(x2,"gaga")
## 2


Comparação de strings Javascript

Question: Estou começando a me aventurar no mundo da programação web e estou tendo dificuldades com o seguinte assunto:
Estou criando uma página para troca de senha. Gostaria de que o meu código comparasse o login que o usuário está tentando alterar a senha, com o login que está atribuído na minha session, convertendo o login para minúsculas e então fazendo a comparação.

Quando faço a comparação, mesmo com a string convertida para minúsculas, recebo a mensagem de que é impossível trocar o usuário.
Alguma dica?
Comment: você deveria fazer isso no **código server**, no seu caso em `php`, imagina a senha sendo exibida no `html` e fácil de qualquer um ver exibindo o código fonte da página?
Comment: É muito perigoso você fazer esta verificação em JavaScript. Hoje em dia, qualquer pessoa com conhecimento básico possa excluir suas verificações através da função "Inspecionar Elemento" do navegador. Como se trata de sessão, aconselho a fazer no seu script PHP.
Comment: Da onde saiu `formlogin`?
Comment: De onde surgiu essa sintaxe php no meio do js? `var logado = ""`
Comment: formlogin é o nome do formulário. $logado é a variável em php que contém o nome de usuário da $_session do PHP. Foi a maneira que encontrei de passar para o javascript o valor da variável da $_session.
Comment: eu coloquei no javascript para poder colocar um pop-up alertando... vou tentar reescrever o código usando só php.
Comment: Na sua verificação a var logado esta sendo passada para lowerCase enquanto a var login permanece sem a mesma conversão, tente colocar no seu if login.toLowerCase()
Answer: Tenta pegar o valor dos inputs dessa forma:
var login = document.getElementById('nlogin').value;

Comparação de strings Javascript


How to update table with multiple if statements

Question: I'm currently using a form to send up to 10 ItemID's to a PHP file. A side from the ItemID's I'm sending a "Status update" to let the user change the status of all those ID's. In this way I've managed to create an Admin function for my clients.
ItemID's are the primary trigger for most things and contains some information about the instrument such as Name, Description, location, etc.. ItemID's are simply unique for ONE instrument.
One part of every ItemID is the GroupID. The GroupID assemble what group an instrument belongs to. If an instrument contains of multiple parts it will be forced in to a group.
1. Let's say we've got this instrument bellow, a temperature sensor (ID: 1437) which contains of 2 sensors (ID: 1438, 1439) and the big calculator in it's highest majestic form. This instrument and the "extra" parts will be added to groupid = "10".
2. So with my code I want to scan every itemID for a groupID. If the groupID is over 0 change all the itemID's (under the specific group) to the status which been sent from the form. In the same time I want the function to change the status of all itemID's entered (mostly items where groupID="0"). In this way the user doesn't have to scan every part of a group and saves a lot of time for other work during the day.
3. The problem with the function in this state is that it will only change the status of either ONE group or ONLY the itemID's entered to the form. I need some advice to get me rolling with this function.
1.

2.
$con = mysql_connect("localhost", "root", "") OR die(' Could not connect');
$db = mysql_select_db('book1', $con);
$CalDate= $_POST["CalDate"];
$DueDate= $_POST["DueDate"];
$itemID1= $_POST["itemID1"];
...
$itemID10= $_POST["itemID10"];
$groupidset= $_POST["groupid"];
$status= $_POST["status"];
if (!$con) {
    die('Could not connect: '.mysql_error());
}
if(isset($itemID1) && isset($itemID2) && isset($itemID3) && isset($itemID4) && isset($itemID5) && isset($itemID6) && isset($itemID7) && isset($itemID8) && isset($itemID9) && isset($itemID10)){
    $DB = new mysqli("localhost", "root", "", "book1");
    $result = mysqli_query($DB, "SELECT * FROM booking WHERE itemID IN('$itemID1','$itemID2','$itemID3','$itemID4','$itemID5','$itemID6','$itemID7','$itemID8','$itemID9','$itemID10','$groupidset')");
    $result2 = mysqli_query($DB, "SELECT groupid FROM booking WHERE itemID IN('$itemID1','$itemID2','$itemID3','$itemID4','$itemID5','$itemID6','$itemID7','$itemID8','$itemID9','$itemID10','$groupidset')");
    while($row = mysqli_fetch_array($result2)){
        $groupid = $row["groupid"];
    }
    if(($groupid == 0)){
        $upd = "UPDATE booking SET status='$status/ADM', verification='No'";
        if($CalDate !=''){
            $upd.= ",CalDate='$CalDate'";
        }
        if($DueDate !=''){
            $upd.= ",DueDate='$DueDate'";
        }
        $upd.=" WHERE itemID IN ('$itemID1', '$itemID2', '$itemID3', '$itemID4', '$itemID5', '$itemID6', '$itemID7', '$itemID8','$itemID9', '$itemID10')";
    }
    if(!empty($groupid)){
        $upd = "UPDATE booking SET status='$status/ADM', verification='No' WHERE groupid IN ('$groupid')";
        if($CalDate !=''){
            $upd.= ",CalDate='$CalDate'";
        }
        if($DueDate !=''){
            $upd.= ",DueDate='$DueDate'";
        }
    }

Answer: I found a fix for this! Either way the ItemID can only take two routes in the first lines and the rest is self explained. I know it's a messy code but it works as i should!
if(isset($itemID1) && isset($itemID2) && isset($itemID3) && isset($itemID4) && isset($itemID5) && isset($itemID6) && isset($itemID7) && isset($itemID8) && isset($itemID9) && isset($itemID10)){
    $DB = new mysqli("localhost", "root", "", "book1");
    $result1 = mysqli_query($DB, "SELECT * FROM booking WHERE itemID IN('$itemID1')");
    ....
    $result10 = mysqli_query($DB, "SELECT * FROM booking WHERE itemID IN('$itemID10')");
    while($row = mysqli_fetch_array($result1)){
        $groupid1 = $row["groupid"];
        echo 'ItemID1, Groupid1: ';
        echo $groupid1;
        echo '
';
    }
    .....
    while($row = mysqli_fetch_array($result10)){
        $groupid10 = $row["groupid"];
        echo 'ItemID10, Groupid10: ';
        echo $groupid10;
        echo '
';
    }

    if(isset($itemID1) && isset($itemID2) && isset($itemID3) && isset($itemID4) && isset($itemID5) && isset($itemID6) && isset($itemID7) && isset($itemID8) && isset($itemID9) && isset($itemID10)){
        $upd = "UPDATE booking SET status='$status/ADM', verification='No'";
        if($CalDate !=''){
            $upd.= ",CalDate='$CalDate'";
        }
        if($DueDate !=''){
            $upd.= ",DueDate='$DueDate'";
        }
        $upd.= " WHERE ";
        if($groupid1 != 0){
            $upd.= "groupid IN('$groupid1')";
            if($groupid2 != 0){
                $upd.=" OR groupid IN('$groupid2')";
            }
            ....
            if($groupid10 != 0){
                $upd.=" OR groupid IN('$groupid10')";
            }
            if($groupid10 == 0){
                $upd.=" OR itemid IN('$itemID10')";
            }
        }
        if(empty($groupid1)){
            $upd.= "itemid IN('$itemID1')";
            if($groupid2 != 0){
                $upd.=" OR groupid IN('$groupid2')";
            }
            if($groupid2 == 0){
                $upd.=" OR itemid IN('$itemID2')";
            }
            ....
            if($groupid10 != 0){
                $upd.=" OR groupid IN('$groupid10')";
            }
            if($groupid10 == 0){
                $upd.=" OR itemid IN('$itemID10')";
            }
        }
    }


Very poor network performance with Server 2019

Question: We are having major performance issues with Server 2019. Read and write performance is very poor compared to Server 2016. we installed a number of servers on customer sites to replace old servers and all customers have complained about opening files from the server being slow.
We have set up a test server in our office and measured some read and write speeds and found a vast difference between 2019 and 2016.
We installed a 2016 and a 2019 VM on a 2019 host using Hyper V and used Lan Speed test to measure Read\write speeds to the VMs and the Host
The server is a Dell PowerEdge with 8x 15K disks configured RAID 10 using Intel quad port network card.
The 2016 VM the read\write speeds are 600 Mbps write and 780 Mbps read.
The 2019 VM the read\write speeds are 220 Mbps write and 115 Mbps read.
Both VMs are using the same virtual switch, are configured exactly the same, and are on the same virtual disk, the only difference is the operating system which is fully patched on both VMs.
We have now tested this on various specs of servers at customer sites and found the same results everywhere, 2019 is much slower than 2016.
All BIOS and drivers are the latest available from Dell.
This is not isolated to one server, it is happening on a number of servers, some of which replaced old SBS 2011 servers and yet run slower that the old SBS boxes.
Has anyone else found this issue?
Comment: What endpoint security product(s) are installed?
Answer: You may be seeing this due to Receive Segment Coalescing (RSC). In short, RSC is TCP segment aggregation that combines segments in order to process larger segments versus multiple small segments for efficiency. This was introduced as a default configuration change for Windows Server 2019 and has been the source of issues similar to yours in other environments.

You can disable a client's RSC for IPv4 traffic using PowerShell: Disable-NetAdapterRsc -Name $nic -IPv4.
You can check a Hyper-V vSwitch's current RSC status using PowerShell: Get-VMSwitch -Name $vSwitch | Select *RSC*.
You can disable a Hyper-V vSwitch's RSC in full using PowerShell: Set-VMSwitch -Name $vSwitch -EnableSoftwareRsc:$FALSE. This will not impact existing vSwitch connections.

Items #2 and #3 require you to have access to the Hyper-V PowerShell modules and proper Hyper-V management permissions. As you mentioned seeing this across multiple machines on a Hyper-V vSwitch it is likely that item #3 is where you may find relief. I've provided reference material for you here and here.
Comment: Thanks for your answer, disabling RSC was one of the first things we tried. It makes no difference if RSC is enabled or disabled, and surely if RSC was the issue this would affect both 2016 and 2019. the difference is huge as you can see from the figures I posted. I have seen RSC making a difference but not to this extent.
Comment: Clients connecting to our virtualized file server were exhibiting extremely slow performance when opening files over the network (3D dental image data). Turning RSC off on the host vSwitch brought a 1-3 minute load time down to 10 seconds or less. Specifically, these were Windows 10 clients connecting to a 2019 file server hosted on a 2019 physical server.
Answer: I can't believe Windows 2019 is still somewhat broken after all this time, but I encourage you to try adjusting the following settings and retest:
LAN
Set-NetTCPSetting -SettingName "DatacenterCustom" -CongestionProvider DCTCP
Set-NetTCPSetting -SettingName "DatacenterCustom" -CwndRestart True
Set-NetTCPSetting -SettingName "DatacenterCustom" -ForceWS Disabled

Set-NetTCPSetting -SettingName "Datacenter" -CongestionProvider DCTCP
Set-NetTCPSetting -SettingName "Datacenter" -CwndRestart True
Set-NetTCPSetting -SettingName "Datacenter" -ForceWS Disabled

WAN
Set-NetTCPSetting -SettingName "InternetCustom" -CongestionProvider CTCP
Set-NetTCPSetting -SettingName "InternetCustom" -DelayedAckTimeoutMs 50
Set-NetTCPSetting -SettingName "InternetCustom" -ForceWS Disabled

Set-NetTCPSetting -SettingName "Internet" -CongestionProvider CTCP
Set-NetTCPSetting -SettingName "Internet" -DelayedAckTimeoutMs 50
Set-NetTCPSetting -SettingName "Internet" -ForceWS Disabled

This reconfigures 2019 to behave a little more like 2016.
Answer: Was going to comment, but don't yet have the reputation.
I was seeing this issue on a new Dell T440 server running Server 2019 as the host OS with Hyper-V role, and a test VM (Win10) I spun up.
From my wired laptop - Lenovo P52S - running Win11 I was seeing avg 500Mbs write, but between 90 and 220Mbs read with LAN Speed Test Lite to the test VM.  Always using a 20Mb file.
To the host itself, using LAN Speed Test Lite I would see avg 500Mbs write and 500Mbs+ read, so nothing wrong with my laptop (or so I thought)
I disabled RSC on the virtual switch but it made no improvement for me, still poor read performance between laptop and VM, even after rebooting HOST, VM and laptop.  I reenabled RSC.
This morning I dug out an old MSI Win10 laptop and gave that a try. LAN Speed Test Lite returned 500Mbs+ write, 700Mbs+ read on first try. Wow!  So it was my machine?  Ran a few more tests and was seeing as much as 1600Mbs on the read.  I then ran twenty more consecutive tests and noticed that on 4 of the 20 tests, read speeds returned lower (about half as low) as the write speed.
Then I (re)disabled RSC on the virtual switch and ran another 20 tests.  All 20 returned consistent read > write results, averaging 700-800 on the read, 450-600 on the write.
Reenabled RSC on the virtual switch and 5 of the twenty tests this time saw slow read speed.  For me, I'd rather have consistent results rather than a read as high at 1600Mbs+ but as low as 220Mbs so off RSC will stay.
Back on my P52s laptop, still the same poor results but this looks to be Intel NIC related, as when using a USB->Gigabit ethernet adapter with Realtek chipset, speed results mirror that seen on the MSI laptop.  I mention this as OP also so no benefit with RSC disabled, as I did initially.
Cheers
Mike


How to copy all s3 buckets to another AWS account?

Question: I'm copying all EC2 instances to another AWS account (creating the AMIs, sharing them with that account and running the instances from AMIs there). I also need to move my S3 buckets since the applications at EC2 instances are using that buckets to store and retrieve files.
I'd like to know if it's possible to copy all S3 buckets to my another AWS account. If yes, how could I do this?
Thanks in advance.

Update
I think I should clarify the question. My task is to make a full backup of my AWS stuff to my second AWS account so if someone will hurt anything on my current one I can easily run my instances on the second account so the system will continue working. The documents in my MongoDB (at the EC2) have records that refer to S3 files and the application is using that records. This is why I want to just move all my buckets and save the file identifiers if it's possible.
Comment: You should be able to create a bucket on the new account, set a bucket policy for each bucket granting the other account full control, and then use s3cmd to sync the new and old bucket, and then delete the old bucket. This would have to be done for one bucket at a time (it won't copy over every bucket), will result in a new bucket id, and would incur the read/write (and depending on location, data transfer) costs for all the individual objects copied. You can't just change the owner of a bucket though.
Answer: http://docs.aws.amazon.com/AWSAndroidSDK/latest/javadoc/com/amazonaws/services/s3/model/AccessControlList.html

Every bucket and object in Amazon S3 has an owner, the user that created the bucket or object. The owner of a bucket or object cannot be changed. However, if the object is overwritten by another user (deleted and rewritten), the new object will have a new owner.


Error response from daemon: rpc error: code = 2 desc = The swarm does not have a leader

Question: I have created 3 nodes swarm cluster by Virtualbox using docker-machine. The three are all running and i'm able to use 'docker-machine ssh' to connect every one.There is a problem that I restart the physical machine and the cluster seems to not work,why? The follow is the details.Thanks for your guide and advice.

san@san-System-Product-Name:~$ docker-machine ls
NAME     ACTIVE   DRIVER       STATE     URL
SWARM   DOCKER        ERRORS
first    -        virtualbox   Running   tcp://192.168.99.100:2376
v17.06.0-ce
second   -        virtualbox   Running   tcp://192.168.99.101:2376
v17.06.0-ce
third    -        virtualbox   Running   tcp://192.168.99.102:2376
v17.06.0-ce

The first is a leader and the second is a manager while the third is a worker.I tried to use 'docker-machine ssh first docker node ls'.

Error response from daemon:

`rpc error: code = 2 desc = The swarm does not have a leader`.

It's possible that too few managers are online. Make sure more than
half of the managers are online.
exit status 1

san@san-System-Product-Name:~$ docker-machine ssh first docker info
Containers: 2
Running: 0  Paused: 0  Stopped: 2
Images: 3
Server Version: 17.06.0-ce
Storage  Driver: aufs
  Root Dir: /mnt/sda1/var/lib/docker/aufs
  Backing Filesystem: extfs
  Dirs: 17
  Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
  Volume: local
  Network: bridge host macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: pending
  NodeID: dowdk4pzfzm85zijbo23e6xs3
  Error: rpc error: code = 2 desc = The swarm does not have a leader. It's possible that too few managers are online. Make sure more than half of the managers are online.
  Is Manager: true  Node Address: 192.168.99.100
  Manager Addresses:
  192.168.99.100:2375
  192.168.99.102:2377
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: cfb82a876ecc11b5ca0977d1733adbe58599088a
runc version: 2d41c047c83e09a6d61d464906feb2a2f3c52aa4
init version: 949e6fa
Security Options:
   seccomp
     Profile: default
Kernel Version:
   4.4.74-boot2docker
Operating System: Boot2Docker 17.06.0-ce (TCL 7.2); HEAD : 0672754 - Thu Jun 29 00:06:31 UTC 2017
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 995.8MiB
Name: first
ID: ACGX:Z6QQ:5KOX:7W2O:OMMM:43PB:4QES:KKGJ:IXUC:J2SW:F4SJ:QMQ4
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 24
 Goroutines: 76
 System Time: 2017-07-28T01:57:37.410536525Z
 EventsListeners: 0
Registry: https://index.docker.io/v1/
Labels:  provider=virtualbox
Experimental: false
Insecure Registries:
  127.0.0.0/8
Live Restore Enabled: false

san@san-System-Product-Name:~$ docker-machine ssh first docker network ls
  NETWORK ID          NAME                DRIVER              SCOPE
    22e85840407d        bridge              bridge              local
    fc3c6786739c        docker_gwbridge     bridge              local
    e294dde63753        host                host                local
    55f8e340b794        none                null                local

how could i fix this problem and use

docker node ls

on manage node?very thanks for your advice.
Comment: I also want to know why this will happen,if you know the answer,please fill feel to give me a comment.
Answer: I had the same problem but I'm not sure what caused it. I was able to fix it by entering:
docker swarm init --force-new-cluster

Everything got restored.
Comment: For me, this command failed with `Error response from daemon: This node is not a swarm manager. Worker nodes can't be used to view or modify cluster state. Please run this command on a manager node or promote the current node to a manager.` Rerunning the command after a **restart of the Docker service** helped in my case.
Comment: But did you run this command in the manager node or in a worker node?
Comment: I ran this command on manager node, which was part of the Swarm, consisting of 4 managers only, with 3 of them being down.


Google Maps Javascript API v3 was disabled in application

Question: I have an application which use google map api v3(I run it on the localhost), every things run well still this morning, I opened my app and saw the error: Google has disabled use of the Maps API for this application. The provided key is not a valid Google API Key, or it is not authorized for the Google Maps Javascript API v3 on this site. If you are the owner of this application, you can learn about obtaining a valid key here: https://developers.google.com/maps/documentation/javascript/tutorial#api_key
I followed the given link to solve this problem.However, after did these:
1. Visit the APIs Console at https://code.google.com/apis/console and log in with your Google Account.
2. Click the Services link from the left-hand menu.
3. Activate the Google Maps JavaScript API v3 service.
4. Click the API Access link from the left-hand menu. Your API key is available from the API Access page, in the Simple API Access section. Maps API applications use the Key for browser apps.

nothing change in my app, and I still didn't overcome the issue. So can someone tell me exactly how can I do.
Answer: If you've gone through that document, created an API key for yourself then in your application your script source should look something like this:

You will just replace the "key=YOURAPIKEY". This is how Google tracks who is using its service.


Error when updating modules with Drush

Question: Iv managed to install Drush to the site on Go Daddy shared hosting(thanks to the greate tutorial!). Simple commands run without any errors, but when I try:
drush pm-update ctools

It returns:
    -bash-3.2$ drush pm-update ctools
The external command could not be executed due to an application error.                                                                                [error]
                                                                                [error]

Parse error:  syntax error, unexpected '{' in /home/content/XXX/XXX/drush/includes/environment.inc on line 518

, code: 255)
Update information last refreshed: Wed, 04/18/2012 - 06:11

Update status information on all installed and enabled Drupal projects:
 Name                                                   Installed version     Proposed version  Status
 Address Field (addressfield)                           7.x-1.0-beta2         7.x-1.0-beta2     Up to date
     Administration menu (admin_menu)                       7.x-3.0-rc1           7.x-3.0-rc1       Up to date

    ...

Security updates will be made to the following projects: Chaos tool suite (ctools) [ctools-7.x-1.x-dev]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n):

The code of the line 518 in environment.inc
is
517      try {
518      $db = new PDO($constr, $creds['user'], $creds['pass']);
519      $db = null;
520     }

Drupal is 7.12, Drush 5.1
What can be the reason of this error?
Also
In hosting cotnrol panel site is on PHP 5.3
But php -v returns 5.2.17
is it ok?
Comment: If you press "y", what happens?  Does it give you another error or does it update the modules?  Even if it shows a parse error, as long as you can proceed by pressing y I wouldn't worry too much.
Comment: I haven't tried to proceed further yet, as there are usually warnings that updates can harm the production site
Comment: The warnings are harmless, but you should always make sure you have a backup of your site whenever you do module updates.
Comment: Yes its true, the site is backed up. But after the "y" the result is: `File ctools-7.x-1.x-dev.tar.gz is corrupt (wrong md5 checksum).                                                                                [error]
Updating project ctools failed. Attempting to roll back to previously installed version.                                                                                [error]
Backups were restored successfully.  `
Comment: "In a shared hosting environment there may be some applications or modules that may not work due to the limitations and restrictions set on the shared environment.  This may be the case with the module that you are trying to use.  If you would like please reply back with the settings and configuration needed to run the module and we will see if it is compatible with the shared hosting plan you are on." GoDaddy support
Answer: This is a common issue in the Drush queue on drupal.org and the consensus is that its related to your version of PHP that runs in client mode versus the version running on your web server, ex. http://drupal.org/node/1402120 or http://drupal.org/node/436968. Of course, some of these were related to PHP 5 vs PHP 4 issues and you're just one version behind on the client but it may help to alias your php version as explained here:
echo 'export PATH="$HOME/packages/bin:$PATH"' > .bash_profile
mkdir -p packages/bin
ln -s /usr/local/php5/bin/php packages/bin/php

Patrick Kenny is right though that this parse error won't affect your upgrade in the end.
Answer: We had a similar problem on a machine. The reason was that the php running on cli did not have some extensions installed. In our case it were the extensions gd, xml and SimpleXML.
We solved that by installing the packages via apt-get install php5.6-gdand apt-get install php5.6-xml.

Error when updating modules with Drush