Hide admin email address in user's from field (Webform)

Question: I am using the Webform  module.
So far the user can send an email via a form to my admin email.
However when I reply to the user my admin email address shows in their 'from' field! - How do I hide that to the site's name (but still pointing to my admin email address)?
Answer: After saving the new component, visit the emails tab. Select the newly created component from the "Component value" select list and select add. The final results will look similar to this.


imagens escapando da coluna

Question: Eu estou tendo problemas com um grid de imagens que em resoluções menores ficam uma sobre a outra como camadas e em resolução maiores elas ficam com uma espaço muito grande entre elas.
As colunas são geradas dinamicamente por isso não posso colocar uma row na segunda linha, no exemplo eu fiz de forma estática imagem por imagem.
o max-width com !importantesta ali pra tratar quando a imagem não vem quadrada como a quarta imagem. Pode acontecer alguns casos de chegar em uma resolução igual da quarta imagem.
obs: Para ver os espaços ver em "Página toda"

img {
    display: block;
    max-width: 324px !important;
    max-height: 324px;
    object-fit: cover;
  }
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Comment: Cara se a imagem tem no máximo 324px de largura ela não vai passar disso... como vc espera que ela se comporte? Ocupando todo o espaço da `col` ?
Comment: @hugocsl eu quero que ela tenha no max 324px mas quando está em resolução menor ela não acompanha a div ficando uma por cima da outra. Se eu tiro esse max ela funciona com as a maioria das imagens mas essa imagem com resolução diferente fica maior que as outras.
Answer: Vc tem alguns problemas no seu código, primeiro que no BS 4 não existe col-xs-6, se vc quer que cada coluna tenha 50% de largura em telas pequenas basta colocar col-6 no lugar de xs-6.

Outro problema é que vc colocou um width máximo com max-width, por isso elas encavalam uma na outra, vc tem que declarar além do max-width tb o width:100% Assim quando o container tiver menos de 324px a imagem ocupa 100% do container entende...
Uma dica sobre a imagem no formato diferente das outras o ideal é que vc coloque o tamanho em um container e não diretamente na imagem, assim o container fica com o tamanho que vc quer, e a imagem dentro dele fica com 100% de altura e largura...

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Tratando a imagem mais alta
Uma opção para corrigir o problema da imagem mais alta é colocar d-flex, tb nos container pai, como no link e na própria col
Repare na imagem abaixo que agora todos as imagens da mesma coluna seguem a altura do maior item

Código da imagem acima

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Comment: Obrigado, Hugo entendi o problema agr e consegui resolver com sua ajuda.
Comment: @GiovanniDias legal que deu certo ai, sucesso
Answer: Você pode usar display:grid no .photocontainer e na img usar object-fit: cover:
/* The parent container */
.photocontainer {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

img {
  max-width: 100%;
  object-fit:cover;
}

Comment: Cara se vc respondeu pelo cel talvez vc não tenha testado seu código... ele ficou como na imagem http://prntscr.com/ofw5iz ... ele não respeita os tamanho máximos definidos para a imagem e a imagem que é maior fica bem diferente das outras... Nem foi eu que te negativei, mas veja que a resposta resolve um problema, mas gera outros colaterais etc... OBS: se meu monitor fosse maior as imagens continuariam a crescer, pois o max é 1fr, ou seja se meu monitor tiver 4000px de largura cada imagem teria 1000px de largura
Comment: Respondi do celular, vim aqui reformatar e recebi downvote? Sério isso?
Comment: Ah entendi, faz sentido. Valeu!

imagens escapando da coluna


"The SOAP request must use SOAP 1.1..."

Question: I am writing some code that generates XML and, using the requests library, POSTs the XML to Salesforce.com's SOAP service.  Here is the code that I'm using to generate the XML:
from lxml import etree

class SalesforceLeadConverter(object):

    def __init__(self, session_id, lead_id, **kwargs):

        self.session_id = session_id
        self.lead_id = lead_id

    def build_xml(self):
        root = etree.Element(
            '{soapenv}Envelope',
            soapenv='http://schemas.xmlsoap.org/soap/envelope/',
            urn='enterprise.soap.sforce.com'
            )
        soapenv = etree.SubElement(root, '{soapenv}Header')
        urn = etree.SubElement(soapenv, '{urn}SessionHeader')
        session_id = etree.SubElement(urn, '{urn}sessionId').text=self.session_id
        soapenv2 = etree.SubElement(root, '{soapenv}Body')
        urn2 = etree.SubElement(soapenv2, '{urn}convertLead')
        lead_converts = etree.SubElement(urn2, '{urn}leadConverts')
        lead_id = etree.SubElement(lead_converts, '{urn}leadId').text=self.lead_id

        return """<?xml version="1.1" encoding="utf-8"?>""" + etree.tostring(root)

Then from the shell, I try to make a request as follows:
 >>> from myapp.salesforce.soap import SalesforceLeadConverter
 >>> slc = SalesforceLeadConverter(session_id="foo...", lead_id="00Qxkdf...")
 >>> xml = slc.build_xml()
 >>> import requests
 >>> headers = {'Content-Type':'text/xml', 'SOAPAction':'convertLead'}
 >>> out = requests.post('https://na1.salesforce.com/services/Soap/c/10.0', data=xml, headers=headers)

out returns a 500 error, and the error text returns

soapenv:VersionMismatchThe
  SOAP request must use SOAP 1.1, did not recieve a SOAP 1.1 Envelope as
  the document
  root'

I inspected the xml value, which is:
'<?xml version="1.0" encoding="utf-8"?><ns0:Envelope xmlns:ns0="soapenv" soapenv="<a rel="nofollow" class="external free" href="http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>" urn="enterprise.soap.sforce.com"><ns0:Header><ns1:SessionHeader xmlns:ns1="urn"><ns1:sessionId>00Dj0000001obaf!AR8AQAvJgjiwkh.BbJa48PB2RZ_ITHBqoZCDa2tf98_6kir5xGBSX4Iz_E7Mt3i_.RwylUoNNEHrrKsyR9huvrxIYoCdUg95</ns1:sessionId></ns1:SessionHeader></ns0:Header><ns0:Body><ns2:convertLead xmlns:ns2="urn"><ns2:leadConverts><ns2:leadId>00Qj000000PMV3h</ns2:leadId><ns2:doNotCreateOpportunity>False</ns2:doNotCreateOpportunity><ns2:sendNotificationEmail>False</ns2:sendNotificationEmail></ns2:leadConverts></ns2:convertLead></ns0:Body></ns0:Envelope>'

I'm wondering if the HTML encoding set to soapenv in the header envelope is the issue, and if so, how do I prevent that encoding?  Is there something else that I'm doing wrong?
Answer: After a lengthy research process, I came across this post, which recommended the following:
from lxml import etree

S_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
S_PRE = '{' + S_NS + '}'

env = etree.Element(S_PRE + 'Envelope', nsmap={'soapenv': S_NS})
header = etree.SubElement(env, S_PRE + 'Header')
body = etree.SubElement(env, S_PRE + 'Body')

print(etree.tostring(env, pretty_print=True, encoding='unicode'))

"The SOAP request must use SOAP 1.1..."


Discrete probability function Vs Probability density function

Question: I wanted to know some difference between these two "System Simulation" technical points.
(It would mean a lot. Thanks ahead. I can't find it anywhere, so.)
(Let me know if u need more info)
Comment: This question is IMV too broad.
Comment: @drhab what IMV stand for? I google it, one was "in my view". But if that was right guess, than u have a grammar mistake. I should be, "IMV this question is too broad"
Comment: Indeed "in my view" is what I had in mind. Thank you for attending me on my grammar mistake. Without thinking I used an order that is okay in Dutch language but wrong in English.
Answer: I think you want to know the difference between Probability Mass Function(pmf) and Probability Density Function(pdf).
Probability Mass Function is for the probability distribution of a discrete random number.
PDF vs PMF
In Simulation, we need to generate random numbers according to the probability distribution. The basic random number generator usually generates a uniform random number between 0 and 1.
When the random number is discrete, we divide the range from 0 to 1 in the way that each interval becomes the probability.
For example, rolling a die, each number has a chance of $\frac{1}{6}$
Therefore, if the uniform random number fall in between 0 and $\frac{1}{6}$, generate a random number 1, if it falls in between $\frac{1}{6}$ and $\frac{2}{6}$, generate 2, and so on.
However, continuous random number case, we cannot divide the range.
Therefore, we match the uniform random number to the CDF (Cumulative Density Function)
the details can be found here. Simulation class Note
Note, the discrete case is also matching uniform to CDF technically.
Comment: But my exam paper has asked, "Discrete probability function Vs Probability density function". Is the question is wrong? Why can't be there some difference between them?
Comment: Probability Mass Function is a function shows the probability of a discrete random number. PMF is more widely/technically used, but I would not say the Discrete Probability Function is a wrong expression.
Comment: What should I do? My university question bank includes "Discrete probability function Vs Probability density function". What should I do in that case? Should I correct the question and write this answer!
Comment: I meant that you can think *Discrete Probability Function* = *Probability Density Function*.


Linux: How to get a machine's IP address?

Question: I'm using Linux CentOS 6.4 .
I'm writing a shell script and I need to extract a machine's IP in order to use it in the script.
How can I find the machine's IP?
I'm looking for the "best" way because I know there are a few ways to get IP addresses.
Thanks
Answer: Here are ways to get your Linux machine IP address:
/sbin/ifconfig

If you know the name of your Network Interface card, you can specify it in the command and get the results for that specific NIC:
/sbin/ifconfig eth0

Another command is:
/sbin/ip addr

If you know the name of your Network Interface card, you can specify it in the command and get the results for that specific NIC:
/sbin/ip addr show eth0

I think this is the best way:
hostname -i

Bare in mind that in some servers you might have more than one Network Interfacr Cards...
Comment: That was quick! thank you! I think I'll use the `hostname -i` one.
Comment: use of hostname -i is discouraged in the manpage:

Display the network address(es) of the host  name.  Note  that  this works  only  if  the  host  name  can  be resolved. Avoid using this option; use hostname --all-ip-addresses instead.
Comment: In case your machine is behind a router and you need your public IP you can use this service: `curl ifconfig.me`
Answer: I'd use facter for that.
yum install facter
facter ipaddress
facter ipaddress_eth0

Comment: Isn't facter related to Puppet or something like that?
Comment: yes it comes from the puppet ecosystem, but works perfectly fine as standalone application.
Comment: Facter is related to Puppet, yes, but you can use Facter without Puppet (though not the other way around).


R script not completing execution when called from PHP - stops when trying to run RODBC's sqlQuery function

Question: SOLUTION: I just wanted to give an update on how this was fixed. Although I could query SQL directly in the R console, PHP did not have a connection to the SQL Server and would stop running my script in R once it hit R's sqlQuery(). I was able to get this working after establishing a connection using sqlsrv_connect() in PHP and by explicitly stating SQL Server Authentication credentials in the connection strings.

"I am trying to execute an R script from PHP that should run a stored procedure that will update a table in a SQL Server 2005 database. I've added in some print() lines to see where the script stops running and it will execute everything up until the sqlQuery function. However, this works fine when I run it in the R Console. My R script is below:
args <- commandArgs(TRUE)
X <- args[1]
sink("test.txt")

library(RODBC)
conn<-odbcDriverConnect('driver={SQL SERVER};server=server;database=database;trusted_connection=true')

print(conn)

print(X)

sqlQuery(conn,paste("EXEC sp.usp_Stored_Procedure @Test='",X,"', @Test2='Y', @Test3='Z'",sep=""))

print(X)

When I pass the argument "bread" through PHP, the R script will run and create the 'test.txt' file with these values:
[1] -1
[1] "bread"
So I at least know the connection has been made and it executes up until sqlQuery(). Again, this runs completely fine directly in the R console, so I'm wondering where it's being lost when I try and execute the R script from PHP. I am running Windows 7 and I connect to SQL Server using Windows authentication.
EDIT: Here's the PHP script:

echo "<form action='rfile.php' method='get'>";
echo "Enter name: <input type='text' name='X' />";
echo "<input type='submit' />";
echo "</form>";

if(isset($_GET['X']))
{
  $X = $_GET['X'];

  exec("C:\wamp\www\R\R-2.15.2\bin\Rscript em.R $X");

  $indsc = file_get_contents('test.txt');

  echo $indsc;
}
?>

When executed on the front end, $indsc returns the values of the 'test.txt' file fine with the exception of everything following sqlQuery() in the R script."
Comment: You need to add the PHP script here otherwise the question can't be answered.
Comment: When you do 'print(conn)' it is printing -1? This suggests to me that the connection to the database is not being made. When you run successfully it from the R console and do 'print(conn)' what do you get?
Comment: Sorry but Why use R for this?
Comment: I've edited my original post with the PHP script. I am using R because there will be some statistical analysis that will need to be done on the values that populate the table updated by the stored procedure.
Answer: I believe you are having the same problem as I did when running R scripts from PHP. Firstly, ensure that when calling R from PHP you do it in this way:
exec('"C:\Program Files\R\R-3.0.1\bin\Rscript.exe" "myrscript.r" 2>&1', $output);

Notice the "2>&1" - this allows PHP to collect any errors that have occurred into the $output - otherwise they are lost. You can then print out $ouput using print_r($output) to see any feedback/errors produced by R. This should provide some clues as to what is failing when you run your script.
I think what is happening is that the call to 'library(ODBC)' is failing. I'm not sure why but it always seems to fail when I do this too when I call from PHP. To fix it, in my R script I did this instead:
library(ODBC, lib.loc = "path/to/r/library/root/folder")

The lib.loc tells R exactly where to find the ODBC library. This should fix the problem.
P.S. On my system, the path to the R libary root folder is "C:/users/myusername/Documents/R/win-library/3.0".


geometric algebra expression for a linear transformation defined on basis vectors

Question: I have a transformation $T(u)$ between 3D vector subspaces of a 4D vector space, $A \rightarrow B$, defined by a mapping of their basis vectors:
$A:\{a_1=e_1\,,\,a_2=e_2\,,\,a_3=e_4\}$
$B:\{b_1=e_2\,,\,b_2=e_3\,,\,b_3=e_1\}$
$T(a_i)=b_i$
I have aligned each space to the standard bases in this example, but I don't want to assume that will always be the case.
My question is: Is there a general process for computing an expression in geometric algebra for this transformation? I know there are ways to define a matrix for this transformation, but is it possible using only the language of geometric algebra?
From reading Linear and Geometric Algebra by Alan Macdonald, I know that there are simple expressions for some classes of linear transformations like symmetric, orthogonal, and skew transformations.
For example, symmetric transformations can be expressed as   $T(u)=\sum{(u \cdot v_i)\lambda _i v_i}\;$ for normalized eigenvectors $v_i$ and eigenvalues $\lambda _i$ . It does not seem like these were found by a general method. Perhaps the best process is simply to classify the transformation and use the consequences of that classification to construct one (if possible).
According to this question, closed due to its ambiguity, this guess is correct. The accepted answer claims that geometric algebra does not have a standard representation for all linear transformations.
So, if the best process is to classify the transformation and use the consequences of that classification to construct one (if possible), I am still unsure how I should apply this to my example problem. Is there a complete way to classify the set of linear transformations defined from basis maps, and do all classifications have corresponding expressions in geometric algebra? Or, is this a misapplication of ideas, as the linked answer suggests?
Answer: It is not possible to represent all linear transformations on R^n within G^n. However the paper Lie groups as spin groups
(http://bdml.stanford.edu/twiki/pub/Rise/GeomAlgebra/lie_groups.pdf) claims that it is possible with G^(n,n). For an explanation of G(n,n) see Chapter 10 of my book. I have not read the paper.
Two notes. 1. In your listing of transformations represented in GA you didn't include those from Chapter 7.

All of my representations are on a vector space. Your example is between two vector spaces.

Chapter 10, on the conformal model was added in later editions. It is available at the book's web site: http://www.faculty.luther.edu/~macdonal/laga/ .
Yes, you can consider your example to be on a vector space, but you did not phrase it that way.
Comment: Thanks, I will take a look at that paper. My version of your book only has nine chapters, was 10 added in a later version maybe?
To your notes: 1. Yes, I did not mean for the list to be exhaustive, and it could have included Projection, Reflection, and Rotation.
2. Since my 3d vector spaces are in a 4d vector space, can't the transformation be considered a transformation on the 4d vector space?


Cyclotomic polynomial

Question: I want to prove basic results of cyclotomic polynomials over $\mathbb{Q}$.

$(1)\ \Phi_n(0)=1$ for all $n>1$.
$(2)\ \Phi_{2n}(x)=\Phi_n(-x)$ for all odd numbers $n>1$.

I want use this result as definition: For every positive integer $n$,
$$ x^{n}-1=\prod_{d|n} \Phi_{d}(x)$$
where $d$ runs over all positive divisors of $n$.
Answer: 1. Remark that $n=1$ is an exception, since $\Phi_1(0) = -1$. Since $x^n-1 = \prod_{d \mid n} \Phi_d(x)$, putting $x=0$ on both sides yields $$-1 = \prod_{d\mid n} \Phi_d(0).$$ Now use induction on $n$, and the fact that $\Phi_1(0)$ accounts for a factor of $-1$ on the right-hand side.

2. Remark that $n=1$ is again an exception, because $\Phi_2(x) = x+1 = -\Phi_1(-x)$. Now, for a general odd $n$,
$$\prod_{d \mid 2n} \Phi_d(x) =x^{2n}-1 = (x^n-1)(x^n+1) = -(x^n-1)((-x)^n-1) = -\prod_{d \mid n} \Phi_d(x)\Phi_d(-x).$$
Now we use induction on $n$. The divisors of $2n$ come in pairs $(d, 2d)$, where $d$ is a divisor of $n$. By the induction hypothesis, $\Phi_{2d}(x) = \Phi_d(-x)$ for each proper divisor of $n$, except when $n=1$ when there is an extra minus sign. By comparing both sides it follows that $\Phi_{2n}(x) = \Phi_n(-x)$.
Comment: @SiddhantTrivedi The right-hand side can be written as $-\Phi_n(x)\Phi_n(-x) \prod_d \Phi_n(d)\Phi_n(-d)$ where the product is over the proper divisors of $n$. The left-hand side can be written as $\Phi_n(x)\Phi_{2n}(x) \prod_d \Phi_d(x)\Phi_{2d}(x)$, where the product is also over the proper divisors of $n$. Now apply induction...
Comment: in the right hand side(last term) how can i get $\Phi_{n}(-x)$?i had done induction but i get two times product on divisors.
Comment: very nice, thanks Bruno!
Comment: My pleasure, @1LiterTears !
Comment: @BrunoJoyal For second part i have done in exactly same way but i ended up with $Φ_{2n}(x)=−Φ_n(x)$.. I guess you also got the same thing....i do not know how could you get rid off that negative sign.. :( :(
Comment: @PraphullaKoushik We have the relation $\prod_{d \mid 2n} \Phi_d(x)=-\prod_{d \mid n} \Phi_d(x)\Phi_d(-x)$, where on the left side exists the component $\Phi_2(x)$ and on the right side exists the component $\Phi_1(-x)$ and $\Phi_2(x)=-\Phi_1(-x)$. That' s how you get rid off the negative sign.
Answer: Here is another answer that uses the basic definition
$$\Phi_n(x) = \prod_{1\le k\le n \atop \gcd(k,n)=1} (x-e^{2\pi i k/n}).$$
This gives
$$\Phi_n(0) = (-1)^{\varphi(n)} \prod_{1\le k\le n \atop \gcd(k,n)=1} e^{2\pi i k/n}.$$
Now recall that for $n>1$ we have $$\sum_{1\le k\le n \atop \gcd(k,n)=1} k = \frac{1}{2} \varphi(n) n.$$
This gives
$$\Phi_n(0) = (-1)^{\varphi(n)} e^{(2\pi i/n) \times 1/2\times \varphi(n) \times n}
=  (-1)^{\varphi(n)}  e^{\pi i  \varphi(n)} =  (-1)^{2\varphi(n)} =1.$$
For the second part we get that
$$\Phi_n(-x) = \prod_{1\le k\le n \atop \gcd(k,n)=1} (-x-e^{2\pi i k/n})
= (-1)^{\varphi(n)} \prod_{1\le k\le n \atop \gcd(k,n)=1}
(x+e^{2\pi i k/n}) \\ =
(-1)^{\varphi(n)} \prod_{1\le k\le n \atop \gcd(k,n)=1}
(x-e^{\pi i + 2\pi i k/n})=
(-1)^{\varphi(n)} \prod_{1\le k\le n \atop \gcd(k,n)=1}
(x-e^{2\pi i (k/n+1/2)})\\
= (-1)^{\varphi(n)} \prod_{1\le k\le n \atop \gcd(k,n)=1}
(x-e^{2\pi i (2k+n)/(2n)}).$$
This almost concludes the proof. We can ignore the sign because $\varphi(n)$ is even.
We now claim there is a bijection between the primitive roots modulo $2n$ call them of class $\mathcal{P}_1$ given by $e^{2\pi i k/(2n)}$ where $\gcd(k,2n)=1$ and $1\le k\le 2n$ and the values produced by $e^{2\pi i (2k+n)/(2n)}$ call them of class $\mathcal{P}_2$ where $\gcd(k,n)=1$ and $1\le k\le n.$ (These two conditions will be our domain of $k.$)
Let $\mathcal{Q}$ be the class of primitive roots modulo $n$. The $\mathcal{P}_1$ roots can be obtained from these by taking $q$ as is if it is odd and taking $q+n$ if it is even (recall that $n$ is odd). Now to establish a bijection to $\mathcal{P}_2$ we must show that $q\equiv 2k+n\bmod (2n)$ and $q+n\equiv 2k+n\bmod (2n)$ always have a unique solution $k$ in the domain of $k$. In the first case we take $k=(q+n)/2$ which is easily seen to be in this domain. In the second case take $k=q/2,$ also clearly in this domain. Moreover we clearly hit each value of $k$ exactly once. This finishes the proof.
Comment: for $n>1$ how can i prove this? $$\sum_{1\le k\le n \atop \gcd(k,n)=1} k = \frac{1}{2} \varphi(n) n.$$
Comment: I got it.Thanks.
Answer: The OP does not say what additional information may be used, so here are two answers that use Möbius inversion as in
$$\Phi_n(x) = \prod_{d|n} (x^d-1)^{\mu(n/d)}$$
since this is a instant consequence of the formula you were given to work with.
Using this formula we have immediately that
$$\Phi_n(0) = \prod_{d|n} (-1)^{\mu(n/d)}
= (-1)^{\sum_{d|n} \mu(n/d)}.$$
Now for $n>1$ we have $\sum_{d|n} \mu(n/d) = 0$, and hence $\Phi_n(0) = (-1)^0 = 1.$ For $n=1$ we get $\Phi_1(0) = (-1)^1 = -1.$
For the second part start with
$$\Phi_n(-x) = \prod_{d|n} ((-x)^d-1)^{\mu(n/d)}.$$
Now since $d$ is odd we have $(-x)^d = (-1)^d x^d = -x^d$, giving
$$ \prod_{d|n} (-x^d-1)^{\mu(n/d)}
= \prod_{d|n} \left(\frac{x^{2d}-1}{-x^d+1}\right)^{\mu(n/d)}
= \prod_{d|n} (-1)^{\mu(n/d)}
\prod_{d|n} \left(\frac{x^{2d}-1}{x^d-1}\right)^{\mu(n/d)}\\
= \prod_{d|n} (-1)^{\mu(n/d)}
\prod_{d|n} \left(\frac{x^d-1}{x^{2d}-1}\right)^{\mu(2n/d)}
\\= \prod_{d|n} (-1)^{\mu(n/d)}
\prod_{d|n} \left(\frac{x^d-1}{x^{2d}-1}\right)^{\mu(2n/d)}
\prod_{d|n} \left(\frac{x^{2d}-1}{x^{2d}-1}\right)^{\mu(2n/d/2)}\\
=  \Phi_{2n}(x)  \prod_{d|n} (-1)^{\mu(n/d)}
\prod_{d|n} \frac{1}{(x^{2d}-1)^{\mu(2n/d)}(x^{2d}-1)^{\mu(n/d)}}\\
= \Phi_{2n}(x)  \prod_{d|n} (-1)^{\mu(n/d)}
\prod_{d|n} \frac{1}{(x^{2d}-1)^{\mu(2n/d)+\mu(n/d)}}.$$
Now since $n>1$ we have  $\prod_{d|n} (-1)^{\mu(n/d)}=1$ and $\mu(2n/d)+\mu(n/d)=0$ so that the final answer is
$$ \Phi_{2n}(x) \times 1 \times
\prod_{d|n} \frac{1}{(x^{2d}-1)^0} =  \Phi_{2n}(x).$$
Comment: In the 2nd proof how to get 3rd setp?(in the power you changed $\mu(2n/d)$)
Comment: What a proof!really great.
Comment: Can u give me any proof of first formula? or any link for this.

Cyclotomic polynomial


Cancellable Sort in .NET?

Question: I'm using ListView in VirtualMode to show extremely big number of rows, millions of rows.
The data of the rows stored in a Generic List.
Now i want implement a sort feature, that will sort the List by some Comparer.
The problem is that for now, an average single sort takes around 30 seconds, and during this time the user cannot do anything with the ListView and have to wait until it ends.
Not every user will accept to wait that much time, most of users would cancel the sort, if they could, and i want to allow that cancel feature. Unfortunately, the built-in List.Sort cannot be cancelled nor Array.Sort.
For now the sort occurring on separate thread, so I could use Thread.Abort, but it probebly will result in corrupted List, unacceptable for me.
Is there something i can do except reimplement the whole Sort algorithm by myself?
thanks.
Comment: Where do you get the millions of rows from? A database? Why don't you just fetch the data sorted? And btw showing millions of rows is not a very good idea. You should try streaming the data i.e. retrieve only a portion (say, the first 100) and, when the users scrolls to say, the 75th item, load the next 100.
Comment: what is the source of these rows? why are you trying to sort on the client like this? what data types - many, just one, custom?
Comment: can the user cancel waiting for all these millions of rows to load too ? ;-)
Comment: ditto the above, also, sort off the UI thread if you can.
Comment: I building file-search program. The source is a file system. each row represent a file/directory, therefor the rows cannot be pre-sorted by the source. The whole idea of VirtualMode is that i not showing all millions of rows at once, i'm using some lazy evaluation mechanism. Demonstration executable: http://planetnana.co.il/ivg/MasterSeekerRelease.rar
Comment: Have you considered using some kind of lightweight database (e.g. SQLite, VistaDB) to cache and index the filesystem data?
Answer: Copy the list, sort the copy in a thread then replace the original list (if the sort completes without getting interrupted).
But I'd go with Martinho's suggestion if possible - having the millions of rows in the application to begin with feels wrong to me. Databases can do a far better job of filtering and sorting data before it gets to you.
Comment: But how would you interrupt the sort without calling Thread.Abort?
Comment: DxCK was already sorting on a different thread, but worried about corrupting the list. If the thread is working on a *copy* of the list, then aborting it shouldn't affect the original.
Comment: Thank you. At first sight it sounds good, but i little worried about copying the whole List of millions rows, because of memory and performance overhead. For now, i prefer waiting for more answers before accepting this one.
Comment: Good point SimonJ.  DxCK, your sort is still going to be the dominating factor in the performance so the copy might wind up being insignificant. But, I would definitely run some tests to verify.
Comment: I have finally used your method, working fine and fast. thank you.
Answer: I had a similar problem. Beating the framework Array.Sort is not easy, and using Thread.Abort is not recommended at all.
I decided sort operation would not be cancel-able, however I thought about this solution ( did not test it)
Implements your own comparer able to access your IAsyncResult object having a CancelRequested bool field. Before any comparison, check the bool, true throws an exception cought in your your bground thread. No thread abort e.g. any lock can be released correctly. Your initial items are safe. But you still need to build an array, either of ref or of keys indexing your original items, because throwing while comparing may leave the array corrrupted. I guess it is not the case but there's no guaranty for this.
Hope this helps
Comment: I created a CompareCanceledException and threw that from my comparer if the operation was canceled. That exception is rethrown by Sort as an InvalidOperationException, so I ended up with something like this:

try
{
  list.Sort(comparer);
}
catch (InvalidOperationException x)
{
  if (x.InnerException is CompareCanceledException)
    list.Clear();
  else
    throw;
}
Answer: There are several ways you could do this.  I might write a class that uses the standard BeginXXX/EndXXX asynchronous pattern with a special CancelXXX method.  I have left out a lot of code, but I think there is enough here to make the point.  Unfortunately with this method you would have to code your own sorting algorithm.
<code>public class Sorter
{
  public IAsyncResult BeginSort(IList<T> values, AsyncCallback complete)
  {
    MyAsyncResult asyncResult = new MyAsyncResult();
    Thread t = new Thread(() =>
      {
        // Implement your sorting algorithm here.
        // Periodically check asyncResult.Cancel at safe points.
        asyncResult.Complete();
        if (complete != null)
        {
          complete(asyncResult);
        }
      });
    t.Start();
    return asyncResult;
  }

  public void EndSort(IAsyncResult asyncResult)
  {
    MyAsyncResult target = asyncResult as MyAsyncResult;
    if (target == null)
    {
      throw new ArgumentException();
    }
    // Add code here to extract any additional information from the IAsyncResult that
    // you might want to return to the client. Perhaps this method will be empty.
  }

  public void CancelSort(IAsyncResult asyncResult)
  {
    MyAsyncResult target = asyncResult as MyAsyncResult;
    if (target == null)
    {
      throw new ArgumentException();
    }
    target.Cancel = true;
  }

  private class MyAsyncResult : IAsyncResult
  {
    private volatile bool m_Cancel = false;

    public bool Cancel
    {
      get { return m_Cancel; }
      set { m_Cancel = value; }
    }

    public void Complete()
    {
      // Add code here to mark this IAsyncResult as complete.
    }
  }
}
</code>
Answer: depending completely upon the environment in question - one approach is to let the user cancel waiting for the sort (which is running on a separate thread) but you secretly continue sorting the list in the background and then tell them when its finished with a subtle notification.
Answer: If you need possibility to cancel sort then you have to create a separate thread. You can prevent corrupting of the original list by reating it's copy and sorting the copy. If user doesn't cancel sorting just exchange original list wist sorted one.

Cancellable Sort in .NET?


Regra de negócio em um sistema pessoal

Question: Conceito de regra de negócio

São declarações sobre a forma da empresa fazer negócio. Elas refletem
  políticas do negócio. As organizações com isto têm políticas para
  satisfazer os objetivos do negócio, satisfazer clientes, fazer bom uso
  dos recursos, e obedecer às leis ou convenções gerais do negócio.

https://pt.wikipedia.org/wiki/Regras_de_neg%C3%B3cio
Tentando compreender o que são as regras de negócio:

"São declarações sobre a forma da empresa fazer negócio. "

Eu posso desenvolver um sistema pessoal, para mim mesmo, e esse conceito ainda se aplica a esse caso?
Por exemplo, vamos supor que desenvolvi um sistema para as minhas caminhadas ou corridas. Esse sistema registra a distância percorrida. Essa distância pode ser em metros ou quilômetros. O sistema registra o tempo gasto na caminhada. Esse tempo pode ser em segundos, minutos ou horas. O sistema registra a data e a hora da caminhada. Posso acessar as minhas caminhadas através de um histórico.

"Esse sistema registra a distância percorrida."
"Essa distância pode ser em metros ou quilômetros."
"O sistema registra o tempo gasto na caminhada."

Essas são regras de negócio?
Se sim, voltando ao conceito: elas são declarações que representam como a empresa (no caso, eu mesmo) faz (faço) seus (meus) negócios?
Se isso está correto, o que significa "negócios"? Em um âmbito comercial imagino que seja venda de produto, pagamento, descontos, etc., o que não se aplica nesse meu exemplo de sistema de caminhada.
No meu exemplo de sistema de caminhada, percebo que as regras de negócio são aquilo o que o sistema faz: "Esse sistema registra a distância percorrida. "; e também são detalhes, restrições ou condições daquilo que faz: "Essa distância pode ser em metros ou quilômetros. ". É isso o que entendo como regra de negócio. Estou equivocado em alguma coisa?
Comment: Será que consideraram todas as minhas dúvidas neste post antes de querer fechá-lo ou negativá-lo?
Comment: Há outros posts sobre regras de negócios, mas neste, além de abordar o conceito geral, eu também as questiono dentro de um sistema específico. Também pergunto se determinadas coisas, desse sistema em específico, são regras de negócios.
Answer: Entenda regras de negócio como o que define  o que teu programa fará. Indiferente de você ter ou não um negócio.
É a maneira como o sistema se comportará. No caso do teu sistema pessoal para controlar as caminhadas, as regras serão para calcular o tempo percorrido, transformar o tempo de horas para minuto ou vice e versa, etc.
Em resumo, é o que dá sentido ao software.
Answer: No seu sistema pessoal você pode não permitir, por exemplo, que o email cadastrado seja do GMAIL ou que o usuário tenha mais de 18 anos ou obriga a verificação do numero do telefone, enfim; isso são regras de negócio.
As restrições que seu sistema impoe ao usuário para atingir o objetivo são as regras de seu negócio.
Comment: @HeyJoe Acho que neste caso, regras de negócio seriam coisas como "Se a distância for menor que X, o sistema deve fazer A e B", "distâncias com valores Y e Z são descartadas", "distâncias maiores que X são notificadas para usuários Fulano e Ciclano" e por aí vai. De maneira geral, a ideia é essa. Eu costumo dizer que, se temos que perguntar pro cliente qual deve ser o comportamento do sistema em determinada situação, a resposta que ele dá (geralmente) vira uma regra de negócio :)
Comment: Então, eu defini dessa maneira: as regras de negócio são aquilo o que o sistema faz: "Esse sistema registra a distância percorrida. "; e também são detalhes, restrições ou condições daquilo que faz: "Essa distância pode ser em metros ou quilômetros. ". Só não tenho certeza se o que o sistema faz ou deve fazer pode ser uma regra de negócio.
Comment: Não exatamente o que ele faz, mas as regras que ele impõe para fazer.
Comment: "Esse sistema registra a distância percorrida. " é uma regra de negócio?
Comment: Ou então "O sistema deve registrar a distância percorrida" é uma regra de negócio?
Comment: Não. O que o sistema faz não é uma regra.
Comment: Entendi, essa era uma de minhas dúvidas.
Comment: @hkotsubo O que o sistema deverá fazer não é uma regra de negócio, então pensei que seria um requisito de software. Li neste link https://www.devmedia.com.br/introducao-a-requisitos-de-software/29580 sobre requisitos e o conceito parece ser o mesmo da regra de negócio.
Comment: "O sistema deverá fazer isso e aquilo", tem algum termo técnico para isso? Não sei se estão conseguindo entender a minha dúvida. Na verdade, no link que passei, o conceito que disse ser o mesmo de regra de negócio era o conceito geral apresentado no texto. Depois, na classificação dos requisitos, ele define o que o sistema deve fazer como Requisito Funcional.
Comment: @HeyJoe *"O sistema deverá fazer isso"* é um requisito. Mas há casos em que a fronteira não é muito clara. Ex: *"O sistema só aceitará cadastros até a data X"* é um requisito ou regra de negócio? Alguns dirão que **com certeza** é o primeiro, outros que é o segundo, pra outros tanto faz (e alguns polemizam esta questão até demais, na minha opinião). Eu não ficaria tão focado na definição exata, o importante é que estas coisas sejam bem definidas (sem ambiguidades, sem margem para interpretações erradas) e todos tenham o mesmo entendimento delas. O resto é "preciosismo acadêmico" :)
Answer: De uma forma resumida, a definição de um sistema passa por algumas fases. Após essa definição é que o sistema entra em "produção". A parte acadêmica que cuida dessa parte é chamada Engenharia de Software. Quando digo resumida é porque o processo todo é bastante complexos e com muitos detalhes.
Embora a sua questão seja para um sistema pessoal, o que muda é que você acaba fazendo todos os papéis no processo. O fato do sistema ser pessoal não muda a metodologia que você emprega no desenvolvimento, muda apenas a complexidade e o esforço que você precisa empregar e permite que você possa abreviar o tempo para chegar no final.
Vou descrever essas primeiras fases porque eu entendo ser mais fácil de entender tendo um contexto ao invés de falar apenas de regras de negócio.
Visão
A visão de um sistema determina o que é o sistema, o que ele deve fazer, qual o objetivo, qual problema ele pretende resolver, qual o público que ele pretende atender e outras questões relacionados ao negócio do sistema e sua viabilidade. Essas características determinam uma fronteira e dá uma chance aos envolvidos na construção do sistema de entender o investimento que precisará ser feito para o seu completo desenvolvimento e assim decidir se vale ou não a pena continuar com a empreitada. É a parte mais importante do sistema porque é nessa parte que se determina os limites do sistema.
Normalmente pequenos empreendedores não fazem isso. As pessoas tem ideias baseadas em necessidades ou de automatizar algum negócio que já funciona de forma manual ou para criar soluções para problemas de uma forma diferente, inovadora. As vezes a solução é bastante simples e não é necessário entender todo o escopo para iniciar, mas as vezes é fundamental para não se perder no caminho.
Quando essa parte não é considerada, os projetos de sistemas geralmente começam e geralmente não terminam porque suas fronteiras não foram delimitadas. A visão é importante para dar uma direção clara para o projeto que vai dar vida ao sistema.
Análise
Essa é a parte mais controversa, na minha opinião, no processo de desenvolvimento do sistema. É uma parte onde é preciso empregar algumas técnicas que podem ser científicas (segundo as pessoas que usam Engenharia de Software) ou empíricas (segundo as pessoas que não conhecem Engenharia de Software) na tentativa de entender o problema que o sistema quer resolver. Algumas vezes ao conversar com os usuários que tem o problema a ser resolvido pode-se descobrir que a solução não é um sistema, ou muito pior, pode-se entender errado o problema e dar uma solução para um problema que não existia. =)
Requisitos
Os requisitos são a transformação das ideias e da análise dos problemas que o sistema quer resolver em partes que determinam "o que" o sistema deve ter para atender as necessidades dos usuários e assim resolver os problemas propostos na visão. Algumas metodologias seguem com uma análise direta das necessidades do negócio e outras tentam mapear processos já existentes, na tentativa de extrair essas necessidades e ao mesmo tempo direcionar o desenvolvimento da solução. Essa segunda abordagem normalmente é mais usada quando um processo de negócio já funciona ou já foi analisado/melhorado. A primeira abordagem também pode não só servir ao desenvolvimento do sistema como também o desenvolvimento de um processo, quando ele não existe.
Ao pensar nesses requisitos, o programador, que normalmente é uma pessoa que entende da parte de como desenvolver, de que linguagens usar, de que componentes são necessários, que banco de dados é melhor, que tecnologias são mais adequadas, que plataforma de desenvolvimento é mais ágil, que tipo de teste precisa ser feito, etc., normalmente não foca no "o que" o sistema precisa fazer e sim "como" ele deve fazer.
Nesse ponto é que entra as tais regras de negócio. Ou seja, sempre que um sistema é construído para resolver um problema ele terá restrições que deve atender para que possa alcançar o objetivo de forma eficaz. Normalmente as pessoas que escrevem essas regras de negócio são pessoas que entendem do negócio em si e o que precisa ser resolvido e nem sempre é o próprio desenvolvedor. As vezes essas regras não são apenas para que o sistema funcione corretamente, mas também para que atenda algum norma, alguma lei.
As regras de negócio serão derivadas dessa "lista" de requisitos porque ao tentar entender o requisito surgirão perguntas do tipo "como isso é calculado?", "que formato deve ter esse relatório?", "que formato devo enviar isso para o governo?", "qual a relação entre esse percentual e esse dado que o usuário informou?", "qual informação é solicitada primeiro?", etc.
Todas essas questões vão surgindo conforme os requisitos vão sendo entendidos e detalhados e essas regras de negócio podem ser mais ou menos complexas conforme os envolvidos vão explorando as possibilidades tecnológicas. Por isso, muitas vezes essas regras não estão claras no início do sistema e vão surgindo conforme as pessoas vão entendendo o negócio e os requisitos. Algumas vezes, o negócio já é bem claro no início do desenvolvimento e algumas regras já são conhecidas e precisam apenas ser atendidas.
Outras Fases
Implementação, Teste, Instalação e outras fases surgem na sequência. É claro que cada metodologia explora essas fases com uma visão diferente, em ciclos diferentes, com diferentes abordagens, mas no geral essas são as fases que são sistematizadas em uma "Fabricação de Software".

Regra de negócio em um sistema pessoal


HCF, LCM, and remainders

Question: I think this is kind of a lame problem after seeing the quality of questions on this site, but I couldn't find anything related to my question
Now the basic questions is as follows,
Q. Find the least number which when divided by x, y, and z leaves remainder in each case a, b, and c.
A. The solution to this "when x-a = y-a = z-c = D" will be LCM(x, y, z) - D
My 1st question is how is the above possible?
EDIT
For eg. Find the least number which when divided by 3, 4, 5 leaves a remainder of 1, 2, 3 respectively.
Now the answer would be:
D = 3-1 = 4-2 = 5-3 = 2
LCM(3, 4, 5) = 60
So the answer is 60 - 2 = 58
2nd Part
Now the problem comes when x-a <> y-a <> z-a
EDIT
Q. Find the least number when divided by 7 and 5 leaves in each case a remainder 2 , 3 respectively.
The way I thought to solve for numbers 7, 5 leaving a remainder 2, 3 respectively was like this:
Construct two arithmetic sequences:

a(1st term) = 9(7+2) and d(common difference) = 7
a = 8(5+3) and d = 5

The first term common to these series will be the answer, but shouldn't it be natural that the second question also have an answer that can be deduced by taking LCM, HCF on some operation involving (7, 5) and (2, 3).
But there is also a condition that there will be no solution, the idea is to check till LCM(7,5), why is that?
Comment: For small numbers, a solution can usually be easily spotted. For larger numbers, please see (say on Wikipedia) Chinese Remainder Theorem. Part of what is needed is the Extended Euclidean Algorithm, so, as you intuited, the greatest common divisor is involved.
Comment: @AndréNicolas Thanks.The chinese remainder theoren does look like what I want, but actually I am just preparing for a SAT like exam so I guess for small numbers I should stick to my technique.
Comment: @Kartik Could you please give a more *specific* example of the precise equations you are attempting to solve. It is not clear from what you wrote.
Comment: @BillDubuque for the first part or the second?
Comment: @BillDubuque I've made the edits
Answer: Hint $\rm\ \ x,y,z\:|\:a\!+\!D \iff m = lcm(x,y,z)\:|\:a\!+\!D.\:$ Thus $\rm\:a\equiv -D\pmod m,\:$ which has least natural representative $\rm\:a = m\!-\!D\:$ if $\rm\:0\le D < m.$
Thus, in your example you have that $\rm\:a\:$ is congruent to a constant value mod all moduli, i.e. $\rm\:a \equiv -D \equiv -2\:\ mod\ 3,4,5,\:$ i.e. $\rm\:3,4,5\:|\:a+2\:$ $\Rightarrow$ $\rm\:60 = lcm(3,4,5)\:|\:a + 2,\:$ therefore $\rm\: a = -2 + 60\:\!k,\:$ with least natural solution $\rm\:a = 58.$
You can find much further discussion of this constant-case of CRT (Chinese Remainder) in many of my prior posts, e.g. here.
The second example isn't a constant case of CRT, but one can use an easy form of CRT, viz.
Theorem (Easy CRT) $\rm\ \ $ If $\rm\ p,\:q\:$ are coprime integers then $\rm\ p^{-1}\ $ exists $\rm\ (mod\ q)\ \ $ and
$\rm\displaystyle\quad\quad\quad\quad\quad \begin{eqnarray}\rm n&\equiv&\rm\ a\:\ (mod\ p) \\
\rm n&\equiv&\rm\ b\:\ (mod\ q)\end{eqnarray} \ \iff\ \ n\ \equiv\ a + p\ \bigg[\frac{b-a}{p}\ mod\ q\:\bigg]\ \ (mod\ p\:\!q)$
Proof $\rm\ (\Leftarrow)\ \ \ mod\ p\!:\:\ n\equiv a + p\ (\cdots)\equiv a\:,\ $ and $\rm\ mod\ q\!:\:\ n\equiv a + (b-a)\ p/p \equiv b\:.$
$\rm\ (\Rightarrow)\ \ $ The solution is unique $\rm\ (mod\ p\!\:q)\ $ since if $\rm\ x',\:x\ $ are solutions then $\rm\ x'\equiv x\ $ mod $\rm\:p,q\:$ therefore $\rm\ p,\:q\ |\ x'-x\ \Rightarrow\ p\!\:q\ |\ x'-x\ \ $ since $\rm\ \:p,\:q\:$ coprime $\rm\:\Rightarrow\ lcm(p,q) = p\!\:q\:.\quad$ QED
Applying this to your example we find
$\rm\displaystyle\quad\quad\quad\quad\quad \begin{eqnarray}\rm n&\equiv&\rm\ 2\:\ (mod\ 7) \\
\rm n&\equiv&\rm\ 3\:\ (mod\ 5)\end{eqnarray} \ \iff\ \ n\ \equiv\ 2 + 7\ \bigg[\frac{3-2}{7}\ mod\ 5\:\bigg]\ \ (mod\ 7\cdot 5)$
But $\rm\displaystyle\ mod\ 5\!:\ \frac{1}{7} \equiv \frac{6}2\equiv 3,\: $ therefore $\rm\:\ n\:\equiv\: 2 + 7\cdot 3\equiv 23\pmod{7\cdot 5}$
Comment: Sorry but I guess I don't have the required know how to interpret your answer, actually I am not exactly aware of the symbols you are using(The vertical bar)
Comment: @KartikAnand the notation $a\,|\,b$ means '$a$ divides $b$'.
Comment: @ChrisTaylor Silly mistake(I am more comfortable with '/') :)
Comment: The notation $\rm\:a,b\:|\:c$ means that $\rm\:a\:$ and $\rm\:b\:$ both divide $\rm\:c\,\:$ i.e. $\rm\:c/a,\:c/b\:$ are integers. It is standard number theory notation. One cannot use the notation '/' for that purpose (unless one says $\rm\:c/a\in\mathbb Z$).
Comment: @KartikAnand Be sure you understand: $a\,|\,b$ does not mean '$a$ divided by $b$' (that is, $a\div b$), it means '$a$ divides $b$' (that is, $b/a$ is a whole number).
Comment: @BillDubuque Sorry but I still can't interpret your answer, I've made the edits to my post by giving an example.Please see
Comment: @Kartik I worked out your specific example. Please let me know what parts are not clear and I'll be happy to elaborate.
Comment: @BillDubuque after working out I got it, thanks.Can you help me with the second part of my question as well?
Comment: @Kartik I cannot determine what the problem is in the second case. Could you please write it more precisely. If it's not equivalent to a constant case then you may need the general CRT.
Comment: @BillDubuque actually yes it isn't equivalent to a constant case, but because my exam would consist of only small numbers, I thought hit and trial would suffice, but somewhere I read that hit and trial can be limited to the LCM of the two numbers in this case LCM(7,5) = 35;i.e if I do  not find any number less than 35 which satisfies the given conditions then there is no possible solution, any idea why is that ?
Comment: You could use trial and error, since the solution has form $\rm\:2 + 7k = 2,9,16,23,30\pmod{35}\:$ you need simply test which is $\equiv 3\pmod 5.\:$ But such brute-force will be more difficult for larger numbers. Easy CRT calculates the exact value  $\rm\:k = (3-2)/7\:$, which involves computing an inverse, which generally involves using the extended Euclidean algorithm or some closely related algorithm (but here, is simple because the numbers are small).

HCF, LCM, and remainders


If a matrix $A$ is orthogonal, show that $\Delta(f \circ A) = (\Delta f)\circ A$

Question: Let $O(d)$ be the space of orthogonal $d \times d$ matrices over $\mathbb{R}$. These matrices act on $C_c^2(\mathbb{R}^d)$, the set of twice continuously differentiable functions $f : \mathbb{R}^d \to \mathbb{R}$ with compact support, via $(f \circ A)(x) := f(Ax)$, where $A \in O(d)$. I am trying to show that for all $f \in C_c^2(\mathbb{R}^d) $ and for all $A \in O(d)$, we have $\Delta(f \circ A) = (\Delta f)\circ A$. Here, $\Delta$ denotes the Laplace operator.
I am aware of the hint in the answer given to this related question here, however I am unable to complete the proof. Further hints on how exactly to apply the chain rule, as well as a full proof would be very much appreciated. Thanks!
Edit: Until now, I have the following: Let $A := (a_{ij})$, $x := (x_1,...,x_d)$. Since $AA^\top = I$, we have
$$ \sum_{j=1}^d a_{ij}a_{kj} = \delta_{ik}, $$
where $\delta_{ik}$ is the Kronecker Delta. We thus have
$$(f \circ A)(x) = f(Ax) = f \left( \sum_{i=1}^da_{1i}x_i,..., \sum_{i=1}^da_{di}x_i\right).$$
We denote $z_i = g_i(x_1,...,x_d) = \sum_{k=1}^da_{ik}x_k$. With the chain rule
$$ \frac{\partial f}{\partial x_j} = \sum_{i=1}^d  \frac{\partial f}{\partial z_i} \frac{\partial z_i}{\partial x_j},$$
we get that
\begin{align}
\frac{\partial}{\partial x_j}(f \circ A)(x) &= \frac{\partial}{\partial x_j}f(z_1,...,z_d)\\
&= \sum_{i=1}^d \frac{\partial f(z_1,...,z_d)}{\partial z_i} \frac{\partial g_i(x_1,...,x_d)}{\partial x_j}\\
&= \sum_{i=1}^d a_{ij} \frac{\partial f(z_1,...,z_d)}{\partial z_i}.
\end{align}
In the next step we get
\begin{align}
\frac{\partial^2}{\partial x_j^2}(f \circ A)(x) = \frac{\partial}{\partial x_j} \left( \sum_{i=1}^d a_{ij} \frac{\partial f(z_1,...,z_d)}{\partial z_i} \right) = \sum_{i=1}^d a_{ij} \frac{\partial^2 f(z_1,...,z_d)}{\partial x_j \partial z_i},
\end{align}
but I'm not sure if this last step is valid.
Now, if we compute $(\Delta f) \circ A$, we get
\begin{align}
((\Delta f)\circ A)(x) &= (\Delta f)(Ax)\\
&= \left( \sum_{j=1}^d \frac{\partial^2f}{\partial x_j^2} \right) (z_1,....z_d)\\
&= \sum_{j=1}^d \frac{\partial^2f(z_1,...,z_d)}{\partial x_j^2},
\end{align}
and since we already computed the first and second partial derivative of $f$, we get that $\Delta(f \circ A) = (\Delta f) \circ A$.
I have two problems:

I haven't used the fact that $A$ is orthogonal.
I'm unsure whether or not I'm using the definition of the chain rule correctly.

Any help is appreciated!
Comment: I would suggest, you look the precise statement of those rules up and post an attempt how to apply them in your question above. Then we see where you get stuck. In fact showing one's attempts is considered good practice on this site and not doing it results quite often in closing or downvoting the question.
Comment: You can just use the Leibniz rule and the chain rule. Doing it twice will give you the double sume that simplifies.
Comment: @SeverinSchraven Could you perhaps elaborate? My problem is that I'm not sure how to apply these rules correctly
Comment: @SeverinSchraven Will do. Thank you for the advice!
Comment: This calculation is part of [this](https://math.stackexchange.com/a/1523173/80734) answer that I posted a long time ago
Comment: @CalvinKhor Thanks, I'll take a look at it
Answer: I think part of your confusion stems from the use of $\partial /\partial_{z_j}$. It might be easier to see it, when you use the partial derivative $\partial_j$ (meaning you take the partial derivative with respect to the $j$th slot of the function). You have correctly computed
\begin{align}
\frac{d}{dx_j} (f\circ A)(x) &= \frac{d}{dx_j} f( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \\
&= \sum_{k=1}^d (\partial_k f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \cdot \frac{d}{dx_j} \left( \sum_{\ell=1}^d a_{k\ell} x_\ell\right) \\
&= \sum_{k=1}^d a_{kj} \cdot (\partial_k f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i )
\end{align}
Repeating the same argument with $\partial_k f$ instead of $f$ leads to
\begin{align}
\frac{d^2}{dx_j^2} (f\circ A)(x) &= \sum_{k=1}^d a_{kj} \cdot \frac{d}{dx_j} (\partial_k f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \\
&= \sum_{k=1}^d a_{kj} \sum_{\ell=1}^d a_{\ell j} (\partial_\ell \partial_k f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i )
\end{align}
Thus, using your equation for the coefficients we get
\begin{align}
\Delta (f\circ A)(x) &= \sum_{j=1}^d \frac{d^2}{dx_j^2} (f\circ A)(x) \\
&= \sum_{j=1}^d \sum_{k=1}^d a_{kj} \sum_{\ell=1}^d a_{\ell j} (\partial_\ell \partial_k f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \\
&= \sum_{k,\ell=1}^d \left( \sum_{j=1}^d a_{kj} a_{\ell j} \right) (\partial_\ell \partial_k f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \\
&= \sum_{k,\ell=1}^d \delta_{k,\ell} (\partial_\ell \partial_k f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \\
&= \sum_{k=1}^d (\partial_k^2 f)( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \\
&= (\Delta f) ( \sum_{i=1}^d a_{1i} x_i, \dots, \sum_{i=1}^d a_{di} x_i ) \\
&= (\Delta f)(Ax) \\
&= ((\Delta f)\circ A)(x)
\end{align}
Comment: I changed your answer to use `\begin{align}` and `\end{align}` for readability. I hope you don't mind!
Comment: @CameronWilliams Thank you very much! It looks so much better.
Comment: @SeverinSchraven Wonderful, thank you very much for your help!
Comment: @jasnee You're welcome. Is it clear now, where you went wrong?
Comment: @SeverinSchraven Yes. I should have repeated the argument exactly as in step 1 with $\partial_k f$ instead of $f$. I failed to apply the chain rule correctly, so it led to this weird expression with just one sum, instead of the expression that you got
Comment: @jasnee Great! It is in the beginning quite confusing with all those indices (at least it was so for me). With time it will get easier.
Comment: This is awesome, thank you very much!!!
Comment: @FabrizioGambelín Glad you like it!
Answer: $
\newcommand\dd{\mathrm d}
\newcommand\tr{\mathop{\mathrm{tr}}}
$Here is a coordinate-free proof.
The Laplacian is the divergence of the gradient; the gradient is defined to be the unique function such that
$$
  v\cdot\nabla g(x) = \dd g_x(v)
$$
for all vectors $v$ and $x$ and where $\dd g_x$ is the total derivative of $g$ at $x$. It is easiest to apply the chain rule using the total derivative:
$$
  v\cdot\nabla[f\circ A](x) = \dd[f\circ A]_x(v) = \dd f_{Ax}(\dd A_x(v)) \overset{(1)}= \dd f_{Ax}(Av) = (Av)\cdot[\nabla f](Ax) \overset{(2)}= v\cdot(A^{-1}[\nabla f](Ax))
$$
(1) follows because the derivative of a linear transformation is itself; (2) follows because $A$ is orthogonal. Thus
$$
  \nabla[f\circ A] = A^{-1}\circ[\nabla f]\circ A.
$$
Now we want to take the divergence of this, but the divergence is the trace of the total derivative; applying this fact and the chain rule gives
$$
  \Delta[f\circ A](x) = \tr\dd\bigl[A^{-1}\circ[\nabla f]\circ A\bigr]_x = \tr A^{-1}\circ\dd[\nabla f]_{Ax}\circ A = \tr\dd[\nabla f]_{Ax} = [\nabla\cdot\nabla f](Ax) = [\Delta f](Ax).
$$
Comment: Maybe another way to state the idea would be: the Laplacian can be expressed as a composition of $d : \Omega^0 \to \Omega^1$, the duality isomorphism $\Omega^1 \to \Omega^{n-1}$, and $d : \Omega^{n-1} \to \Omega^n$.  However, $d$ is coordinate-free, whereas the duality isomorphism depends only on the inner product (Riemannian manifold structure on $\mathbb{R}^n$), and the idea of an orthogonal matrix is precisely that it gives an automorphism of the inner product space.


Two different front pages?

Question: I have a website at mydomain.com. I am creating a clone of it on mydomain2.com. The only difference is that I want the landing pages to be different. Both domains are running the same codebase.
How do I make the landing page differ, depending on what domain you are on?
(Note: Without using i18n)
Comment: They're using different databases? Just change the front page setting under Site Information in the admin.
Comment: Same database for both.
Answer: You can do this by using the Domain Access module which is meant for creating a site (with one code base and one database) where certain content is accessible by DomainA and other content is accessible by DomainB. In your case you can set all content to be accessible to both domains and just change the site settings for the front page based on current domain. In D8 there is the Domain Site Settings module which makes this easier, but in D7 you should use Domain Variable to change site_front based on the current domain.
This method will allow you (for example) to create two view pages or nodes or whatever (one for each domain) and display completely different content (or content in a different order) depending upon the domain.
Answer: I would suggest creating a custom Route (or hook_menu for D7) that acts as a routing mechanism to send you to the right page. The custom logic would look at the $_SERVER variable and then do a drupal_goto to the appropriate page of choice.
example.com/landing would route to example.com/other-landing
Comment: I dont want two different pages. If it's accessed via either url, it must stay at /
Answer: you can use hook_theme in your template.php file to introduce two different theme to drupal, then in page.tpl.php file check if user is visiting current page (use $is_front variable for that) or you can use page--front.tpl.php, the you can check $front_page value which has the address of front page, based on different address you can print one of your themes
example :
in template.php :
function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'first_front' => array(
      'render element' => 'page',
      'template' => first-front-page,
    ),
    'second_front' => array(
      'render element' => 'page',
      'template' => second-front-page,
    ),
  );
}

then in page--front.tpl.php, use this code:
<?php if($front_page == "first_url") : ?>
  <?php print render(theme('first_page', array('page' => $page))); ?>
<?php endif; ?>
<?php if($front_page == "second_url") : ?>
  <?php print render(theme('second_page', array('page' => $page))); ?>
<?php endif; ?>

Comment: I dont know who downvoted this, but I'll test it and let you know if it works.
Comment: This only allows you to change the look and layout of the front page (per domain)... it does not allow you to have different content. I think that is why it was downvoted
Comment: FYI: Because my new site is only going to have about two pages, this is probably going to be the route I go.

Two different front pages?


open_basedir problems with APC and Symfony2

Question: I'm currently setting up a shared staging environment for one of our applications, written in PHP5.3 and using the Symfony2 framework.
If I only host a single instance of the application per server, everything works as it should.
However, if I then deploy additional instances of the application (which may or may not share the exact same code, dependent on client customisations), I get errors like this:
<code>[Tue Nov 06 10:19:23 2012] [error] [client 127.0.0.1] PHP Warning:  require(/var/www/vhosts/application1/httpdocs/vendor/doctrine-common/lib/Doctrine/Common/Annotations/AnnotationRegistry.php): failed to open stream: Operation not permitted in /var/www/vhosts/application2/httpdocs/app/bootstrap.php.cache on line 1193
[Tue Nov 06 10:19:23 2012] [error] [client 127.0.0.1] PHP Fatal error:  require(): Failed opening required '/var/www/vhosts/application1/httpdocs/app/../vendor/doctrine-common/lib/Doctrine/Common/Annotations/AnnotationRegistry.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/vhosts/application2/httpdocs/app/bootstrap.php.cache on line 1193
</code>
Basically, the second site is trying to require the files from the first site, but due to open_basedir restrictions it can't do that. I'm not willing to disable open_basedir as that is only masking the problem instead of solving it, and creates a dependency between applications that should not be present.
I initially believed this was related to a Symfony2 error, but I've now tracked it down to an issue with APC; disabling APC also solves the error, but I'm concerned about the performance impact of doing so.
Does anyone have any suggestions on what I might be able to do?
Answer: Ok, this turned out to be a problem with our own code, rather than anything specifically wrong with either APC or Symfony2.
For the reference of anyone else who might run across this one:

We were using the ApcUniversalClassLoader component from Symfony2.
That allows you to specify a prefix for your cache files.
This prefix was the same across each instance of our application; which is why it worked fine so long as there was only one instance per server.
Because the prefix was the same, APC attempted to load the classes belonging to the first instance of the application which had been accessed immediately after the server had been restarted.
Changing the prefix to be different per-instance of the application makes this behave correctly, loading the classes from the correct folders.

Hopefully, this will prevent anyone else from banging their head off the desk when they realise why it's not working :)
Comment: Run into the exact same problem. Thanks very much for pointing me to a working solution.


DNS Issue Windows Server 2012

Question: Background:
I have a windows server 2012 install with AD, DNS and DHCP.
I also have a netopia router/modem providing my WAN access.
My router/modem is configured with DHCP off and connected to a 24 port switch.
My WS2012 has static IP and uses the router/gateway as its default gateway for internet traffic and uses loopback for DNS. This WS2012 is also connected to same 24port switch.
The Problem:
My DNS server has forwarding enabled to my ISP's dns servers.
Here is the problem:
All my workstations on the network are getting extremely slow internet access (.1-.2 Mbps). Connecting directly to the modem and setting static IP (and completely bypassing the WS2012) gets about 4-5 Mbps. The reason I think this is a DNS issue is because whenever I go into DNS manager and clear the Cache the internet on all machines runs at 4-5 Mbps for about 10-20 minutes and then slows to crawl again.
I have already checked my reverse lookup records and forward records and they seem to be in-tact.
This issue just arose about 1 week ago and this WS2012 has been in production for 6-7 months without a single hickup. No configuration changes have been made to this machine. Nobody has even logged into this machine (headless) since put into production besides a monthly reboot (from login screen via RDP).
PS. All internal traffic runs at full speed.
Comment: Welcome to Server Fault. If you solved your own problem, please post it as an Answer and then accept it by clicking the check mark next to your own answer. This is not a forum, and so it's not necessary to put things such as "SOLVED" in the question title.
Comment: odd...what happens if you change forwarders to something like 22.214.171.124 or 184.108.40.206?
Comment: So workstations have GW set as netopia router, but when DNS is set to WS2012 after a while their access gets slow? when it is slow. have you tried doing NSlookups to see if dns resolution is indeed taking a long time? but also this would only affect loading pages, etc.  once it gets the answer, file downloads/etc should not be affected as they are not using DNS.  The normal way I would set something up like this is disable DHCP in the router, enabled DHCP / DNS in the WS server, and set forwarders int the server to the upstream caches.
Comment: TheCleaner: so I initially had forwarders set to google's dns as you mentioned with ISP as fallback. This had worked for the last 6-7 months flawlessly.

@Doon This is what does not make sense to me either since DNS is only used for lookup of IP and initial page load. However when running speedtest.net after clearing cache its 4-5Mbps and then after 10-20 minutes as mentioned it slows to about .1-.2. Now what is the part you mentioned about "set forwarders int the server to the upstream caches." this part i am not sure about.
Comment: (i am not windows guy). but AD needs to be the master DNS, and all workstations needs to use it  else naming breaks, etc. also it seems to work better when the Domain is in control of everything(DNS/DHCP/etc...)   So the router is just a router,  disable DNS and DHCP on it, letting the windows server do those functions  It just becomes the default gateway..  Then inside your windows server in the dns snap in, under actions-> properties you should have a forwarders tab, that you can use your ISP (or googles servers). This way local queries are local, but unknowns get forwarded and then cached)
Comment: but yeah the network slowdown after clearing DNS cache for things that aren't new connections is odd.  How are you clearing the cache in the router?  (or is the Server). And to be clear the router is the GW. Also are both your wan and lan connections plugged into the same switch/same vlan?
Comment: @Doon Here is a better map of the network [link](https://www.dropbox.com/s/7iu2msm7fwm9twi/2013-07-18%2010.30.28.jpg)[/link] When clearing cache i'm using the windows DNS manager and rightclick on dns server and clear cache. Under my DHCP server should I set the default gateway to be the WS2012 so all data is routed through the WS2012?

Thanks in advanced for your help
Comment: no don't set the GW to the Server, that is what I was making sure wasn't already in place.  the router is the GW. Sorry I guess my it above was ambiguous. I meant the router is just the GW, let the server handle the rest.  Have you tried to clear the cache in the middle of a slow speedtest and see if that changes the in process connection.  if it does then I am totally stumped
Comment: also do you have the ability to sniff the traffic going towards the gateway to see if you have something that is eating up your bandwidth that you don't know about?  Could be virus/bot or the like that is filling your uptream, thus slowing your down stream  and perhaps flushing ths dns cache slows it down a bit (this is a WAG, but worth looking into all things being the same )
Comment: @doon yeah that is the way everything was setup (router is only the GW everything else going to WS2012). I am going to try to run wireshark in catch all traffic mode to see if something (virus/bot) is trying to eat up traffic. However the only thing running on the network when I was trouble shooting last night was my Mac, the WS2012 and PBX system which is running standalone PBX software (linux).
Comment: Seems doubtful this is a DNS issue; more likely P2P, music/vid downloads, offsite backup and/or virus/bot.  I would enable SNMP on the router, install PRTG on a local workstation and see how much traffic is flowing through the router.  A firewall (or a managed switch, port mirroring & Wireshark) would be the solution to see where the traffic is coming from.  Without that, since network seems small, watch PRTG, pull the network cables on 1/2 wkstns, keep doing this until the source(s) are narrowed down.
Otherwise, have you confirmed w/ ISP that circuit is running fine w/ no errors?
Answer: So it worked fine with 220.127.116.11 as the original forwarder but not with your ISP's DNS servers?
That would seem to be the issue then, that your forwarders you have in place are causing slow DNS resolutions. You can easily confirm if DNS is causing this. Just use FileZilla and FTP into an FTP site via IP address (not FQDN) and then transfer a large file from that FTP site to you. If it runs at the right speed, then your issue is DNS resolution (and probably just your forwarders).
Comment: Ok so i solved the issue and this a new one. So the previous sysadmin had opened up the router to put a dedicated External IP on the server. With the new install there were no external services running on the machine(Email, webserver, etc)so i setup the DNS server with open modifications from outside since I assumed (My fault) that it was providing strictly internal dns functions. Well the domain started getting dns update requests on from tons of different places and it looks like that was causing slow down and thats why clearing cache worked for a bit. Removed static IP and it works now. :)
Comment: I had it working fine with 22.214.171.124 as dns for 6-7 months no issues. About a week ago these issues arose. I changed dns to ISP thinking that was issue but it was not since the internet was very fast when i cleared dns cache from inside dns manager on WS2012. After a little bit of time (10-20 min) it becomes slow again.
Comment: Can you try the FTP via IP test and see what bandwidth results you are getting?  You need to start narrowing it down.

DNS Issue Windows Server 2012


Let $A$ be an integer. Consider two integers $A$ and $A+1.$ Print the sum of the numbers that cannot be formed using any combination of $A$ and $A+1.$

Question:
Not getting any sort of lead for this question

for A=2, answer is 1

for A=4, all numbers with combination of A and A+1 except 1,2,3,6,7,11. So, answer is 30 (1+2+3+6+7+11)
Comment: When you say any combination, they can only be added? Why can I not subtract them to get numbers lower than $A$? The question is not very clear on that.
Comment: Welcome to MSE. It is in your best interest that you type your questions (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.
Comment: okay, sorry about that....... @JoséCarlosSantos
Comment: Calculating the first six terms allowed me to find http://oeis.org/A002417
Comment: There is a general theorem that if $a$ and $b$ are coprime positive integers, then the maximal integer not representable in the form $ax + by$ (where $x\ge0, y\ge0$ are integers) is $c=ab-a-b$, and moreover, that the set of representable and non-representable integers turn into each other after symmetry with respect to the point $c/2$. This theorem should be enough to solve this problem, try to first use it and then prove it.
Comment: yes, @Arthur this is the one
Thank you
Comment: You may want to start [here](https://math.stackexchange.com/a/70040/11619). Admittedly the setting is a bit more general.there.
Answer: Here is a pattern that I was able to derive. This is not a complete answer and you will have to refine it further.
This is for any given positive integer $A$, where all possible numbers $n$ need to be built using
$n = iA + j(A+1)$ where $i, j \in Z$ and $i, j \ge 0$
say $k = A - 1$
Numbers that you cannot make using $A, A + 1$ -
(1) $ \, 1$ to $A - 1$
(2) $ \,A+2$ to $2A-1$
(3) $ \,2A+3$ to $3A-1$
...
...
(A-2) $ \,(A-3)A + (A-2)$ to $A(A-2) -1$ ($2$ numbers)
(A-1) $ \,(A-2)A + (A-1)$ to $A(A-1) -1$ (just $1$ number and the largest number).
In other words, we can write it as
$S = \sum \limits_{i=1}^k \sum \limits_{j = 1}^{A - i} (i-1)A + (i -1) + j$
EDIT:
I tried to simplify and see if it came to the same answer as in Arthur's link -
$S = \sum \limits_{i=1}^k (i-1) (A + 1) (A - i) + \frac {(A - i) (A + 1 - i)} {2}$
$S = \frac {1}{2} \sum \limits_{i=1}^k (2A^2 + 2A + 1) i - (2A + 1) i^2 - A (A + 1)$
$S = \frac {1}{2} [\frac {A(A-1)(2A^2 + 2A + 1)}{2} - \frac {A(A-1)(2A-1)(2A+1)}{6} - A (A-1) (A + 1)]$
Simplifying I get $ \, S = \frac {(A-1)(A^3-A)}{6}$ which is same as in the link as there, the numbers are $n + 1, n + 2$ instead of $A, A + 1$.
Comment: Thank you. I have to do the same program. I did the part A and it worked for A = 2, 3. I missed the part B and that is why it was not working for A = 4 or greater. Now I understand. Let me change the program and test.
Answer: I solved your problem (with no more than secondary-school mathematics). Here is the problem-solving strategy I used:

For $A\leq 5$, write out all the numbers that cannot be written as a nonnegative integral linear combination of $A$ and $A+1$.
Develop a conjecture on patterns of consecutive integers in those numbers.
Prove the conjecture.
Use formulae for sums of consecutive integers and sums of squares to arrive at a formula for the sum of those numbers.
Answer: Following the terminology of the theory of numerical semigroups, let $S$ be the additive semigroup generated by $A$ and $A+1$. The set ${\Bbb N} − S$ is called the set of gaps in $S$ and is denoted by $G(S)$.
Since $A$ and $A+1$ are relatively prime, the largest number that is not in $S$ (called the Frobenius number of $S$), is
$$
F(S) = A(A+1) - (A + (A+ 1)) = A^2 - A - 1.
$$
and the size of $G(S)$ is $A(A-1)/2$.
The elements of $S$ lesser than or equal to $F(S)$ are of the form $kA + i$ with
$0 \leqslant i \leqslant k$ and $1 \leqslant k <A$. The sum of these elements is
\begin{align}
\sum_{1 \leqslant k < A} \Bigl(\sum_{0 \leqslant i \leqslant k} (kA + i)\Bigr) &= \sum_{1 \leqslant k < A}k(k+1)(A + 1/2) \\
&= (A + 1/2)\sum_{1 \leqslant k < A}k(k+1) \\
&= (A + 1/2)2\binom{A}{3}= (2A + 1) \binom{A}{3}
\end{align}
It follows that the sum of the elements of $G(S)$ is
\begin{align}
F(S)(F(S) + 1)/2 - (2A + 1) \binom{A}{3} &= 3(A^2 - A - 1)A(A - 1)/6 - (2A + 1) A(A-1)(A-2)/6 \\
&= A(A-1)^2(A+1)/6 = (A-1)\binom{A+1}{3}
\end{align}
\begin{array}{c|cccccc}
A&2&3&4&5&6&7\\
\hline
\text{SUM}&1&8&30&80&175&336
\end{array}


I'm unable to findFirstByAttribute in MagicalRecord

Question: In the documentation of MagicalRecords it is given that

If you have a unique way of retrieving a single object from your data
store you should do this

Person *person = [Person MR_findFirstByAttribute:@"FirstName" withValue:@"Forrest"];
I'm doing this
DX *foundDX = [DX MR_findFirstByAttribute:@"code" withValue:cell.DXCodeName];
NSLog(@"Found DX: %@, Cell Code Name is: %@",foundDX,cell.DXCodeName.text);

If I know the value is in the entity it still give me

Found DX: (null), Cell Code Name is: F45

But I have this value already in the DX entity

So What am I missing?
Answer: Sorry for putting this here but I don't have the reputation to comment yet. Have you tried passing in the value cell.DXCodeName.text?
Comment: Yes I'm passing value as `[self.AddEditDX setCode:[NSString stringWithFormat:@"%@",cell.DXCodeName.text]];`
Comment: Sorry, I meant on this line like this
     DX *foundDX = [DX MR_findFirstByAttribute:@"code" withValue:cell.DXCodeName.text];
Comment: By changing that I'm getting this in NSLog `Found DX:  (entity: FavDX; id: 0xd0000000001c0000  ; data: {
    code = F45;
    descriptions = "Somatoform disorders";
    isFav = 1;
}), Cell Code Name is: F45`
Comment: So now it's finding the core data model that you're looking for


Different behaviour between enumerateObjectsUsingBlock: and for( in )

Question: Give this code
NSMutableArray *array = [NSMutableArray new];
for (int i = 0; i < 10000; i++) {
    [array addObject:@(i)];
}

queue1 = dispatch_queue_create("com.test_enumaration.1", DISPATCH_QUEUE_CONCURRENT);
queue2 = dispatch_queue_create("com.test_enumaration.2", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue1, ^{
    int idx = 0;
    for (NSNumber *obj in array) {
        NSLog(@"[%d] %@", idx, obj);
        idx++;
    }
});

double delayInSeconds = 0.3;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, queue2, ^(void){
    [array removeObjectAtIndex:9000];
    NSLog(@"----");
});

I'm expecting that this code crash because at some point the block dispatched on queue2 get executed concurrently to the enumeration and this will trigger the assertion that you cannot mutate an the array while enumerating. Indeed, this is what happens.
The interesting part is when you substitute for ( in ) with enumerateObjectsUsingBlock:
NSMutableArray *array = [NSMutableArray new];
for (int i = 0; i < 10000; i++) {
    [array addObject:@(i)];
}

queue1 = dispatch_queue_create("com.test_enumaration.1", DISPATCH_QUEUE_CONCURRENT);
queue2 = dispatch_queue_create("com.test_enumaration.2", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue1, ^{
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"[%d] %@",idx, obj);
    }];
});

double delayInSeconds = 0.3;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, queue2, ^(void){
    [array removeObjectAtIndex:9000];
    NSLog(@"----");
});

In all my different test the block that remove the object is executed in the middle of the enumeration (I see the print of @"----") and the interesting thing is that the enumeration behave correctly printing [8999] 8999 and then [9000] 9001.
In this case the array is mutated during the enumeration without firing any assertion. Is this an intended behaviour? If yes, why? I'm I missing something?
Comment: possible duplicate of [Objective-C enumerateUsingBlock vs fast enumeration?](http://stackoverflow.com/questions/8509662/objective-c-enumerateusingblock-vs-fast-enumeration)
Comment: @trojanfoe Not really, in the linked answer is stated "both methods protect mutable collections from mutation inside the enumeration loop" in my case I'm not trying to change the change the collection inside the enumeration block but i'm mutating this from a different thread.
Comment: @LucaBernardi: *Both* variants crash with the "Collection <__NSArrayM: 0x100113d10> was mutated while being enumerated" exception when I run your code.
Comment: I run the test again and for me the is know crash and I saw logged the "----" in the middle of the enumeration and in fact the output is [8999] 8999 and the [9000] 9001
Comment: I got the same output as described by @LucaBernardi. Indeed, it seems like enumerateObjectsUsingBlock: does not complain when the array is mutated while being enumerated and simply skip the removed object.
Answer: Since the introduction of fast enumeration, it's become the go-to method for ... making enumeration fast. Most implementations of enumerations, such as for(in) and enumerateObjectsUsingBlock:, will use fast enumeration under the covers.
Fast enumeration will look at how the data is stored. In the case of NSMutableArray, I would guess that the underlying data is stored in several chunks of data; a ten-thousand item array might be implemented as a hundred chunks of 100 items, with each chunk storing its hundred items in contiguous memory. Analysis of some assembly suggests that (at least on some iOS devices) the class is implemented as a single, giant circular buffer. Either way, the enumerated list might contain multiple contiguous blocks of objects. Ultimately, the exact storage mechanism is irrelevant; it's access to the underlying contiguous storage that makes fast enumeration better than the alternative.
Generally, enumeration is supposed to prevent the list from being mutated. You will always see that with the for(in) enumeration. Apparently some implementations of enumerateObjectsUsingBlock: do not robustly guarantee that the list is not mutated during enumeration. I am getting an assertion failure on the devices that I've tried... but it sounds like there are some devices where this protection is broken. I'd guess that the mutation guard used within NSFastEnumerationState is not complete, perhaps only watching a single chunk instead of the entire array.
I'd consider this a bug in enumerateObjectsUsingBlock:.
Further, any code that might generate an exception here is by definition bad code: you'll need to provide a mechanism to prevent your own code from trying to modify an array while another thread is iterating over it.
Comment: do you have any resource for your claim that NSMutableArray is storing its data in chunks? [This article](http://ciechanowski.me/blog/2014/03/05/exposing-nsmutablearray/) shows it is a circular buffer.
Comment: Mike Ash implied that this was the case in https://mikeash.com/pyblog/friday-qa-2010-04-09-comparison-of-objective-c-enumeration-techniques.html. Bartosz, in the article you mention, likewise is making a guess to the actual implementation. That aside, the implementation itself is not open-sourced, and Apple retains the ability to change the implementation on different devices and OS versions. So, no, I don't *know* that's how it's stored. I'll edit the post to reflect that.
Comment: Mike Ash's article doesn't make any statement about the internals of NSMutableArray.
Comment: Indeed, there is no statement; only an implication. Plus, the specific implementation is irrelevant. The point is to introduce to the reader the idea of "multiple chunks of contiguous objects", which I think is a possible source for the bug.
Comment: and where is the implication. I cannot find it. if there where multiple chunks within one array, most of the observations of Bartosz wouldn't be possible.
Comment: Using a circular buffer allows up to two disjoint chunks of contiguous objects... which happen to be joined by a chunk of contiguous null pointers (or unused object storage). As for Mike Ash's article, search for the phrase "If there are multiple contiguous object stores".
Comment: NSFastEnumeration protocol can be adapted for custom classes. those could have different stores, Mike does not imply that is true for arrays.
Comment: I must have mistakenly inferred it. My bad.


Putting Two ORGs Together

Question: I'm building a boot loader that boots the content that is located at the 1000h part of the floppy. I was doing that using Fasm(because my friend only uses Fasm, and he was helping me with this), but I prefer to use Nasm, and now I'm having problems with the syntax, then I want to know how could I do this in Nasm:
org 7C00h
    %include "boot.asm"

org 1000h
    %include "kernel.asm"

PS: I already put the %include directive using Nasm-syntax style, on Fasm it should be just include.
Answer: See here for the description of your problem or what I think it is since it's a little hard to tell from the question. It's a good idea when posting questions with "I'm having problems with the syntax" to actually show what the syntax problem is :-)
See here for the solution (but it may not work, see below).
Basically, the org statement in NASM is meant to set the base address for the section and cannot be used to arbitrarily insert bytes into the stream. It suggests you use something like:
org 1000h
%include "kernel.asm"
times 7c00h-($-$$) db 0 ; pad it out with zero bytes
%include "boot.asm"

However, have you thought about what you're trying to do. If you're creating a flat binary file to load into memory, I don't think you want both the boot sector and kernel in a single file anyway.
The BIOS will want to load your boot sector as a single chunk at 7c00:0 and will almost certainly be confused when it has the kernel at the start of that chunk. I think what you will need to do is to create two totally separate flat binary files, one for the boot sector and another for the kernel. BIOS will load your boot sector, then your boot sector will load your kernel.
Then you can put the relevant org statement in the two source files and your problem should hopefully be solved.
Answer: While org is only allowed once in NASM bin format source, you can use its multi-section support to create what I believe is the exact same as your FASM output with two org directives. Refer to https://www.nasm.us/xdoc/2.14.02/html/nasmdoc7.html#section-7.1.3
This is what a bootloader with such a second stage would look like:
        org 7C00h
        section BOOTSECTOR start=7C00h

        ; boot sector content here

        times 510 - ($ - $$) db 0
        dw 0AA55h

        section KERNEL follows=BOOTSECTOR vstart=1000h

        ; kernel content here

Answer: The simple answer is that this cannot be done in NASM.
The org statement works the same in FASM as it does in NASM but differently in MASM.
In NASM the example code would have to be assembled separately and then combined to create the final image.

The happy answer is that this is the rare (and probably only) case where code with different start addresses needs to be combined (with NASM) or assembled (with FASM) into a single image.
The boot sector is transferred to 7C00h by the BIOS. It is immediately followed on the media (floppy disk, hard drive, USB flash drive) by the payload which is transferred to it's start address by the boot sector - boot loader.

Putting Two ORGs Together


K fold cross validation; How many epochs to train for?

Question: I am doing k-fold cross validation across my training set with the goal of finding the best structure for a neural network.
Within each fold, should I
A) train the network for a constant number of epochs? OR
B) train each fold until the error on the current fold starts increasing?
If I do B) then each parameter set will be trained for different number of epochs. This gives me an additional hyper parameter (number of epochs) which I could use but I am planning on using an additional holdout set to test the performance. Should I then just ignore the number of epochs that the cross validation found and train on the entire training set until the error on the holdout set increases ??
Answer: You could do A but it is not recommended. The steps most often employed are described in pg 245 of the text (pg 264/764 in the pdf)
https://web.stanford.edu/~hastie/Papers/ESLII.pdf
An important caveat: The book recommends
Often a "one-standard
error" rule is used with cross-validation, in which we choose the most parsimonious
model whose error is no more than one standard error above
the error of the best model.. I have seen some papers where they chose the minimum error model also. There is nothing right or wrong in either method. These are typically caveats based on heuristics. The one std. error rule they describe is motivated by the bias-variance tradeoff.
The number of iterations is typically not relevant; the convergence criteria is. Is there a reason you care about the number of iterations?
Comment: During cross validation, you are assuming that the data barring the fold you are using for validation is your train set, so train all the way through till your error starts increasing, much like is suggested in part B of your post
Comment: Thanks for your answer. I was interested in the number of epochs as I am implementing this in code and need to know when to stop training each fold (some sets of hyper parameters will no doubt take longer than others to reach a minima).


Why use Task.Run to create a new task around a simple async method call?

Question: This is a pattern I'm seeing in some code I'm working on:
result = await Task.Run(async () => await MyAsynchronousMethod());

and I'm failing to see what this does that this does not do:
result = await MyAsynchronousMethod();

What is the former construction here intended to accomplish?
Comment: `Task.Run()` runs code in a background thread. `await` does not.
Comment: @DiskJunky Only if you remove `async` as well.
Comment: Couldn't the second `await` in the first example be removed entirely?
Answer: Task.Run starts a task on the thread pool that will execute the async method. So in the first case, the async method itself will be called on a background thread.
In the second case, the MyAsynchronousMethod method will run synchronously, just like any other non-async method, on the calling thread until it hits an await. This might block the calling thread, at least for a while, depending on how the async method is implemented.
There are examples of poorly implemented async methods that blocks the calling thread before they hit an await and calling such a method on the dispatcher thread in a UI application may for example freeze the application.


Convergence of $1+\frac13-\frac12+\frac15+\frac17-\frac14+\frac19+\frac1{11}-\frac16+\ldots$

Question: I was reading Rudin PMA, example 3.53 on P76. There he points out that rearrangement may not give same limit of a series. Then he says that it is left as exercise to show that above mentioned series converges. I thought clubbing three terms, but did not seem 'legal'.

How to show that series $1+\dfrac13-\dfrac12+\dfrac15+\dfrac17-\dfrac14+\dfrac19+\dfrac1{11}-\dfrac16+\ldots$ converges?

I tried root test: Let this series be $\sum_{n=1}^{\infty}a_n$, then $\limsup\limits_{n\to\infty}\sqrt[n]{|a_n|}=1$, since basically, this series is rearrangement of $\sum \frac {(-1)^n}n$. So root test is inconclusive.
Comment: @edo1998 But $\frac{(-1)^n}n$ doesn't converge absolutely, so rearrangements may change the convergence.
Comment: Why is it that 99 out of 100 persons talking about an infinite series wouldn't be able or willing to tell you the definition of convergence, but they will remember (a mutilated version of) the ratio test or the root test? Both tests are (even in their correct form) mostly useless outside the context of power series and their radius of convergence.
Comment: Hint: Compute an equivalent of the $k$th block of three consecutive terms.
Comment: Isn't just a rearrangement of $\displaystyle\frac{(-1)^n}{n}$ that converges for Leibniz?
Comment: @ancientmathematician No, it's a comment, because I'm at work and don't have the time for a real answer.
Comment: What is the general term of this series?
Comment: Yes, you are right, it is not decreasing!
Comment: How exactly is this series defined? What is the 1000-th term of this series? What is the $n$-th term?
Comment: @ProfessorVector Probably because it's the first test you learn when doing series. I mean, the test is easy to calculate so it usually doesn't hurt to try it, even though it usually doesn't work :)
Comment: BTW, it's easy to check that the partial sum of the first $3n$ terms is $\displaystyle H_{4n}-\frac12\,H_{2n}-\frac12\,H_n\to\ln4-\frac12\,\ln2=\frac32\,\ln2$.
Comment: Far and away the best answer, @ProfessorVector.
Comment: Similar to, but not the same as, [Prove $1-\frac{1}{2}-\frac{1}{3}+\frac{1}{4}+\frac{1}{5}-\frac{1}{6}-\frac{1}{7}+\cdots$ converges.](https://math.stackexchange.com/questions/712413/prove-1-frac12-frac13-frac14-frac15-frac16-frac17).
Comment: This is not unclear, but the context is minimal. Unfortunately, there was one vote to close citing "lack of context" and two votes citing "unclear what you're asking" so the reason came through as unclear.
Answer: In blocks of $3$ terms, the series is
$$
\sum_{n=0}^{\infty} \left(\dfrac{1}{4n+1}+\dfrac{1}{4n+3}-\dfrac{1}{2n+2}\right)
=
\sum_{n=0}^{\infty} \dfrac{8 n + 5}{32 n^3 + 64 n^2 + 38 n + 6}
\le
\dfrac56+
\sum_{n=1}^{\infty} \dfrac{1}{n^2}
< \infty
$$
This proves that the partial sums $S_{3n+2}$ of the original series converge. The other partial sums, $S_{3n+1}$ and  $S_{3n}$, differ from $S_{3n+2}$ by one or two terms that converge to zero and so they converge as well, to the same limit. Thus, the partial sums converge, that is, the series converges.
Comment: @M.Winter, if the terms tend to $0$, which they don't for $\sum(-1)^n$, then you *are* allowed to group a bounded number (in this case three) of terms at a time.
Comment: @M.Winter, see my edited answer. Thanks for the nudge.
Comment: @Silent, it's been time since I've looked at how any textbooks present the elementary theory of infinite series, so I can't give any references. Maybe someone else can.  As for "bounded number of terms," note that $$1-1+{1\over2}+{1\over2}-{1\over2}-{1\over2}+{1\over3}+{1\over3}+{1\over3}-{1\over3}-{1\over3}-{1\over3}+\cdots$$ fails to converge even though the terms are tending to $0$ and $$(1-1)+({1\over2}+{1\over2}-{1\over2}-{1\over2})+({1\over3}+{1\over3}+{1\over3}-{1\over3}-{1\over3}-{1\over3})+\cdots=0+0+0+\cdots$$ makes it look convergent.
Comment: Also I thought this was a valid reasoning at first, I now came to the conclusion that you are not allowed to group alternating series like that. E.g. by the same reasoning one can argue that $\sum (-1)^n$ converges to zero by grouping $\sum (1+(-1))$. You can group only positive terms, or only negative terms, but not mixed.
Comment: @BarryCipra I see. Thanks for this enlightenment. I think this is a non-trivial part of the reasoning and should be at least mentioned in the answer. Otherwise one might think this is generally valid (it took me some thinking to get this and I think it needs a proof or a name which can be googled).
Comment: @lhf, I think you are using comparison test, but [this](https://www.symbolab.com/solver/step-by-step/%5Cfrac%7B8%20n%20%2B%205%7D%7B32%20n%5E%7B3%7D%20%2B%2064%20n%5E%7B2%7D%20%2B%2038%20n%20%2B%206%7D%3C%5Cfrac%7B1%7D%7Bn%5E%7B2%7D%7D) says that $\frac{8\:n\:+\:5}{32\:n^3\:+\:64\:n^2\:+\:38\:n\:+\:6}<\frac{1}{n^2}$ holds for no $n$
Comment: @Silent, I'm not sure how symolab works, but the conclusion you've drawn is most decidedly wrong. If nothing else, just plug in $n=1$ and check that the inequality holds.
Comment: So sorry @BarryCipra, Thanks for pointing that out! I need one more help though: It is very  new point to me which you mentioned [here](https://math.stackexchange.com/questions/2663152/convergence-of-1-frac13-frac12-frac15-frac17-frac14-frac19-frac111-fr#comment5500982_2663169), and seems to be very powerful, since we have to look at a subsequence of partial sums. Can you give a link that has proof of this statement? Also, what does bounded mean there?
Answer: It seems like the series is alternatingly composed of positive terms (and it is okay to group them) of the form
$$a_{2n}=\frac1{4n+1}+\frac1{4n+3}=\frac{8n+4}{(4n+1)(4n+3)}=\frac{8n+4}{16n^2+16n+3}=\frac{n+1/2}{2n^2+2n+3/8}.$$
for $n=0,1,2,...$, and negative terms of the form
$$a_{2n+1}=-\frac{1}{2n+2}.$$
also for $n=0,1,2,...$. Note that for sufficiently large $n$ we have
$$
\underbrace{\frac1{2n}}_{|a_{2n-1}|}
\ge \underbrace{\frac{n+1/2}{2n^2+2n+3/8}}_{|a_{2n}|}
\ge \underbrace{\frac 1{2n+2}}_{|a_{2n+1}|}.
$$
So we have an alternating series with absolutely decreasing terms with $|a_n|\to 0$. We can apply the alternating series test to reason that the sum converges.
Answer: As many people already pointed out, the series converges thanks to Leibniz criterion! Indeed the series is
$$ \sum_{n=1}^\infty (-1)^{n+1} a_n, $$
where $a_n$ are
$$ a_n = \begin{cases}
\frac{1}{n} & n\ \text{even,}\\
\frac{1}{n+n-1}+ \frac{1}{n+2+n-1} = \frac{1}{2n-1}+\frac{1}{2n+1} & n \ \text{odd,}
\end{cases} \qquad a_n \to 0. $$
Answer: $c_1 := 1+\frac{1}{3}$.
$c_2 := -\frac{1}{2}$.
$c_3 := \frac{1}{5} + \frac{1}{7}$.
$c_4 := -\frac{1}{4}$.
$c_5 := \frac{1}{9} + \frac{1}{11}$.
$c_6 := -\frac{1}{6}$.
$\cdots$
$c_{2 k - 1} := \frac{1}{4 k - 3} + \frac{1}{4 k - 1}$ for $k \in \{1, 2, 3, \cdots\}$.
$c_{2 k} := -\frac{1}{2 k}$ for $k \in \{1, 2, 3, \cdots\}$.
Then,
(a)
$\frac{1}{4 k - 3} + \frac{1}{4 k - 1} > \frac{1}{4 k} + \frac{1}{4 k} > \frac{1}{4 k + 1} + \frac{1}{4 k + 3}$.
$\therefore |c_{2 k - 1}| > |c_{2 k}| > |c_{2 k + 1}|$ for $k \in \{1, 2, 3, \cdots\}$.
(b)
$c_{2 k - 1} \geq 0$ and $c_{2 k} \leq 0$.
(c)
$\lim_{k\to\infty} c_{2 k - 1} = \lim_{k\to\infty} c_{2 k} = 0$.
$\therefore \lim_{n\to\infty} c_n = 0$.
So, $\sum c_n$ is an alternating series and converges by Theorem 3.43 on p.71.
$c_1 = s'_2$.
$c_1 + c_2 = s'_3$.
$c_1 + c_2 + c_3 = s'_5$.
$c_1 + c_2 + c_3 + c_4 = s'_6$.
$c_1 + c_2 + c_3 + c_4 + c_5 = s'_8$.
$c_1 + c_2 + c_3 + c_4 + c_5 + c_6= s'_9$.
$\cdots$
So, $s'_2, s'_3, s'_5, s'_6, s'_8, s'_9, \cdots$ is a convergent subsequence of $\{s'_n\}$.
So, $s'_2, s'_5, s'_8, s'_{11}, \cdots$ is a convergent subsequence of $\{s'_n\}$.
$s'_{3 k - 2} = s'_{3 k - 1} - \frac{1}{4 k - 1}$.
So, $s'_1, s'_4, s'_7, s'_{10}, \cdots$ is a convergent subsequence of $\{s'_n\}$.
$\{s'_1, s'_4, s'_7, s'_{10}, \cdots\} \cup \{s'_2, s'_3, s'_5, s'_6, s'_8, s'_9, \cdots \} = \{s'_1, s'_2, s'_3, s'_4, s'_5, s'_6, s'_7, s'_8, s'_9, s'_{10}, \cdots\}$.
So, $\{s'_n\}$ converges.
Comment: I wrote this answer for my memo. Is my answer correct?