To show that R is a division ring given some property on ring R.

Question:
Let $R$ be a non-zero ring such that the equation $ax=b$ has a solution in $R$ for all $a, b\in R$ with $a\neq 0$. Show that $R$ must have unity and it is a division ring.

Now to show this we need to show that every non zero element is invertible.
If we take '$a$' as non zero element with $ax=b$ then how can I use the given fact to show the ring is a division ring. Please help.
Answer: Here is how you solve the problem if it is already assumed that $R$ has a unit:
Taking $b = 1$, a solution to $ax=1$ is a right inverse for each nonzero $a \in R$. Fix such a right inverse $ac=1$. Now $c$ also has a right inverse, $cd=1$. It follows that $a = a(cd) = (ac)d = d$, so $c$ is both a right and left inverse for $a$. This proves that every nonzero element of $R$ has a two-sided inverse.
For showing that $R$ has an identity:
What you have is, for each nonzero $a \in R$, an $e_a$ so that $a e_a = a$.
If $ab = 0$ for nonzero $a, b \in R$, then one can multiply on the right by the solution to $bx = e_a$ to get $0=abx = ae_a = a$, which is a contradiction. So $R$ has no zero divisors, which, as was noted in one of the comments, is equivalent to both left and right cancellation holding. So the $e_a$'s are unique for each fixed $a$.
As rschwieb's comment below suggests, you can use cancellation together with $a e_a e_a = a e_a$ to conclude that $e_a^2 = e_a$, making $e_a$ an idempotent. Then left canceling $e_a(e_a b - b) = 0$ makes $e_a$ a left unit for $R$, and right canceling $(b e_a - b) e_a = 0$ makes $e_a$ a right unit for $R$.
This is closely related to a standard trick for breaking down a ring given an idempotent: For $e \in R$ an idempotent in an arbitrary ring, we have $x = (x-ex) + (ex)$, which gives a direct sum decomposition of $R$ as a right module over itself.
Comment: More thoughts, since you are giving the best answer so far. From $ae_a^2=ae_a$ you get $e_a$ is idempotent. Then $(be_a-b)e_a=0$ implies $e_a$ is a universal right identity. Then $e_a(e_ab-b)=0$ implies it's a universal left identity.
Comment: @rschwieb Incorporated. Thanks!
Answer: Take $b=1$ then every $a$ has an inverse since the equation has a solution. Then take $a=b$ and see that for every $a$ there exists $ax=a$.
Comment: I'm not entirely convinced by this answer. Yes, there is some $x$ such that $ax = a$ for each $a$, but why is it clear that $x$ does not depend on $a$? That is, the unity element $e$ should satisfy $ye = y$ for all $y \in R$; why should the solution to $ax = a$ be consistent as $a$ varies?
Comment: How can I take b=1 if it is required to prove the same (i.e  to prove R must have unity)?
Comment: Indeed: in fact there exist rings without identity  in which the equations $ax=a$ and $xa=a$ have solution sfor every $a$ . This ought to be enough to make one more careful in this problem.
Comment: Sorry. I wrote it in the wrong order. First prove existence of unity.
Comment: Ok. But you gave the correct idea.
Comment: I thought about the dependency on a bit though it was trivial to solve. I see now that I was wrong.


Excluir linhas repetidas

Question: Bom dia,
Tenho uma tabela "Paciente" com as colunas (NO, Evento, Glicosimetro, Nome, Glicemia, Data, Leitura), qual melhor forma para excluir todas as linhas repetidas? Olhando na internet tentei o seguinte código porém não deu certo...

   String sql = "DELETE a FROM Paciente AS a, Paciente AS b WHERE a.NO=b.NO AND a.Id < b.Id";
   SqlCeCommand comando = new SqlCeCommand(sql, con);
   comando.ExecuteNonQuery();
   con.Close();

Comment: Seu código está como [nessa resposta](https://pt.stackoverflow.com/a/68378/100416). O que não deu certo? Dê um exemplo dos dados da tua tabela.
Comment: Reformulei a pergunta, desculpe.
Comment: Isto responde à sua pergunta? [Como remover linhas duplicadas de maneira eficiente?](https://pt.stackoverflow.com/questions/68377/como-remover-linhas-duplicadas-de-maneira-eficiente)
Comment: Eu vi este post porém esta dando erro como mostrado na primeira imagem... Sabe me dizer o que poderia ser esse erro?
Answer: Uma maneira de executar esta rotina é quebrar a tarefa em duas.
Desta maneira, eu escreveria primeiro o select que resolve este problema. Creio que está pronto conforme o código que postou.
SELECT a.id, a.NO FROM Paciente AS a, Paciente AS b WHERE a.NO=b.NO AND a.Id < b.Id;

Após verificar se o SELECT inclui o conjunto de ids que deseja, você pode utilizar o comando DELETE para apagar as linhas duplicadas. (fazer backup antes).
DELETE FROM Paciente WHERE id IN (SELECT a.id FROM Paciente AS a, Paciente AS b WHERE a.NO=b.NO AND a.Id < b.Id);

Verifique que neste comando DELETE dentro da clausula IN estamos selecionando apenas os ids.

Excluir linhas repetidas


How do I determine if an Apple Open Directory user is disabled via LDAP?

Question: I have an Open Directory user that has the "Access Account" box unchecked in Workgroup Manager so they cannot login.  Is there a way to determine this using an LDAP query?
It would also be good to be able to check their Login Shell setting for /bin/false via LDAP, as some administrators use that to disable logins.
Answer: Whether an account is disabled isn't stored in the LDAP database, so you can't get at it with any LDAP query; it's in the password server database, so you need to query the password server.  To do this, you first need to get the account's password slot ID, which will be in one of the authAuthority attributes in LDAP, something like this:
authAuthority: ;ApplePasswordServer;0x4ae508585b4ac9840000000500000005,1024 35
 1484429831226030758363098280788558407709702186716704057921377682138163682495133
 1971257473356121601282837516549920614867084718242948054970731529476886852497051
 1771493871066923475105955010041662310891335912128945258881795910315183596873989
 2049755102190782235854169470422244680045551515607049216054651273928793669
 email@example.com:10.0.0.5

In this example, "0x4ae508585b4ac9840000000500000005" is the user's pasword slot ID.  Once you have that, you can connect to the password server and check the user's password policies:
$ telnet 10.0.0.5 3659
Trying 10.0.0.5...
Connected to myserver.example.com.
Escape character is '^]'.
+OK ApplePasswordServer 10.6.0.0 password server at 10.1.0.1 ready.
getpolicy 0x4ae508585b4ac9840000000500000005
+OK isDisabled=1 isAdminUser=0 newPasswordRequired=0 usingHistory=0
canModifyPasswordforSelf=1 usingExpirationDate=0 usingHardExpirationDate=0
requiresAlpha=0 requiresNumeric=0 expirationDateGMT=44451553867008
hardExpireDateGMT=44451553900288 maxMinutesUntilChangePassword=0
maxMinutesUntilDisabled=0 maxMinutesOfNonUse=0 maxFailedLoginAttempts=0
minChars=0 maxChars=0 passwordCannotBeName=0 requiresMixedCase=0
requiresSymbol=0 notGuessablePattern=0 isSessionKeyAgent=0 isComputerAccount=0
adminClass=0 adminNoChangePasswords=0 adminNoSetPolicies=0 adminNoCreate=0
adminNoDelete=0 adminNoClearState=0 adminNoPromoteAdmins=0
quit
+OK password server signing off.
Connection closed by foreign host.

Note the "isDisabled=1" policy in that list, indicating that this user is currently disabled.
Comment: Seriously?  Geez louise.
Comment: If you're developing using the [Open Directory framework](https://developer.apple.com/library/mac/#documentation/Networking/Conceptual/Open_Directory/Introduction/Introduction.html) in Cocoa, the `ODRecord` class has a `passwordPolicyAndReturnError:` method which does this for you.
Answer: To find the Login Shell value user:
Search filter of (loginShell=/bin/false)  (Though you might need quotes around it since it has slashes in it.
Bind with an LDAP browser like ApacheDS or LBE and look at a user who can and one who cannot login, and look for obvious attributes.
While someone may just know the answer, this way teaches you to fish, instead of handing you a fish.  Or else it just stinks like a rotten fish.  Your mileage may vary.
Comment: Thanks, I've been looking for a good LDAP browser and found the LoginShell attribute, but can't see anything like eDirectory's LoginDisabled or Active Directory's userAccountControl to tell me if they aren't allowed to login.
Comment: `loginShell=/bin/false` just means that the user cannot login to the server, but the user may still be active and able to authenticate.


What is the name of this machine learning problem?

Question: I am confronted to a particular type of problem that I do not know how to handle. And I cannot find any literature about this problem.
Problem settings
I have a dataset of $n$ sample points. Each point consists in a set of $m$ vectors of features, named $x^{(i)}_j \in \mathbb R^d$, for $1 \leq i \leq n$ and $1 \leq j \leq m$.
For set of vectors $(x^{(i)}_j)_{1 \leq j \leq m}$, the corresponding values $y^{(i)}_1 , ..., y^{(i)}_m \in \{-1 ; 1\}$ are available. Among the $m$ values, only one is equal to $1$, and the other are equal to $-1$.
What I want the model to do
I would like to learn a model from these data which gives for a new set of vectors $(x^{(0)}_j)_{1 \leq j \leq m}$, the corresponding values $y^{(0)}_1 , ..., y^{(0)}_m$. More precisely, I search for a model which returns:
$$ \begin{pmatrix}
p(y^{(0)}_1 > 0 | x^{(0)}_1 , ..., x^{(0)}_m ) \\
\vdots \\
p(y^{(0)}_m > 0 | x^{(0)}_1 , ..., x^{(0)}_m )
\end{pmatrix}.
$$
My questions
Does this problem have a name in the statistical literature?
Could you point me papers which treat that issue or algorithms which are able to learn this particular classification problem?
Answer: You should consider multinomial logistic regression.  It is, I think, exactly what you are looking for, assuming that all d choices are available to all subjects.
If that assumption doesn't hold, you should look in the literature for discrete choice models.  Be wary of the assumptions of these models, many require behavioral assumptions that are dubious.
Comment: The products can different for each user i, so that I think it cannot be seen as a multilabel classification problem.
Comment: Ah, in that case you should look up the literature on Discrete Choice models.  They have a variety of (conditional) multinomial logistic models that work when the set of available items differs.  Just be careful when choosing a model, that it makes sense for your situation (I don't trust many of the utility theory models, but that might be what you are stuck with).  [Here](http://facweb.knowlton.ohio-state.edu/pviton/courses2/crp5700/5700-mlogit.pdf) is a nice set of examples of discrete choice models in R.


Retrieving HTML from ASP.NET page on postback

Question: I've found a few posts about retrieving HTML from an ASPX page, mostly by overriding the render method, using a WebClient, or creating an HttpWebRequest. All these methods return the HTML of the page as it's loaded, but I was hoping to actually retrieve the HTML after the user has entered information.
The purpose behind this is that I work in IT, and I'm attempting to build a logging library that has an overload that essentially does a "screen-scrape" on the page just as the user encounters an exception, that way I can log the exception, and create an HTML file in a sub-directory of the logging directory that shows the page exactly as the user had it before clicking "submit" or having some other random error, and add an "ID" to the error that's logged telling whoever is fixing the issue which page to look at.
I hope I've provided enough information, because I really have no idea where to start.
Also, We'd like to do this through our own library, because our logging library is included in our common library, and many of our common library functions use our logging class.
Answer: Hmmm...
If you want to see what the user sees after they've been using the page, you're most likely going to have to do some fancy client-side scripting.
A naive approach:
When the clicks the submit button, fire a JavaScript event that encodes the DOM and either passes it as a form variable to the server, or executes a separate AJAX request with the encoded data as a parameter. ("Encode" in this case may be as simple as grabbing document.innerHtml, but I haven't checked.)
This potentially introduces a lot of overhead to every form submission, so I'd keep it out of production code.
I'm not sure why you need the rendered HTML as part of your exception log - I've never found it necessary for server-side debugging.
Comment: It's not meant for every form submission, only when an exception occurs, and only for the exceptions we choose to use it on. Also, it's not included in the log, but rather in individual HTML files in a sub-directory of the logging directory. I'll look into using javascript (kinda figured I would have to), but thought I'd see if there's a .NET method to do it first.
Comment: Unfortunately, you can't tell if a server-side exception occurred until you're executing on the server, at which point you either have all the data you want for logging, or not. You'd have to send it with every request. You can't go back to the browser after an exception occurred and ask for the HTML.
Comment: Thanks. I guess I will have to go the javascript route. I like javascript, but hate trying to pass variables between javascript and ASP.NET.
Comment: Just add a hidden form field in your ASPX and set its value to the HTML string in the form's submit method. It's pretty straightforward.
Comment: Yea, but this is in a generic library. I don't like telling people to add items to their page in order to use the library correctly.
Comment: You can add the hidden field to the page dynamically when your exception handler runs.You would need to make the field name unlikely to used by other code and document it for users of your library in the section describing your exception logging feature.
Answer: You getting HTML code from a website. You can use code like this.
<code>string urlAddress = "http://www.jobdoor.in";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;
  if (response.CharacterSet == null)
  readStream = new StreamReader(receiveStream);
  else
  readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
  string data = readStream.ReadToEnd();
  response.Close();
  readStream.Close();
}
</code>
Comment: Thanks, but I think you're missing the point of the question.


Finding a distribution with a given correlation

Question: Below is a problem that I made up and my attempt at a solution to it. I am hoping that somebody here can help me finish it. I believe there is a unique
answer to the problem.
Thanks,
Bob
Problem:
Let $X$ and $Y$ be uniformly distributed independent variables on the interval $(-1,1)$. Let $K$ be
a real number. Let $Z = Y + KX$ such that the correlation of $X$ and $Z$ is $\frac{1}{2}$. Find $K$.
Answer:
If we select $K = 0$ then we get a correlation of $0$. If we select $K$ to be a very large number
then the correlation will be close to $1$.
\begin{align*}
\rho &= \frac{1}{2} \\
u_x &= 0 \\
u_y &= 0 \\
u_z &= u_y + K(u_y) = 0 + K(0) = 0 \\
\sigma_x^2 &= \frac{(1 - -1)^2}{12} = \frac{4}{12} \\
\sigma_x^2 &= \frac{1}{3} \\
\sigma_x &= \frac{1}{\sqrt{3}} \\
\sigma_y &= \frac{1}{\sqrt{3}} \\
\sigma^2_z &= \sigma^2_y + K^2 \sigma_x^2 + K(0) \\
\sigma^2_z &= \frac{1}{3} + K^2 \left( \frac{1}{3} \right) \\
\rho &= \frac{\sigma_x \sigma_z}{\sigma_{xz}} \\
\sigma_{xz} &= \frac{\sigma_x \sigma_z}{\rho} =
 \frac{ \left( \frac{1}{\sqrt{3}}  \right) \left( \frac{1}{3} + K^2 \left( \frac{1}{3} \right)  \right) }{\frac{1}{2} }\\
\sigma_{xz} &= \left( \frac{2}{\sqrt{3}}  \right) \left( \frac{1}{3} + K^2 \left( \frac{1}{3} \right)  \right) \\
\sigma_{xz} &= \left( \frac{2}{3 \sqrt{3}}  \right) \left( K^2 + 1 \right)  \\
\end{align*}
Answer: As you show, Pearson's $r$ should be a function of $k$. We will find that function and solve for
$r(k) = \frac{1}{2}$.
$r(A,B)$ may be calculated from the covariance $cov(A,B)$ and the standard deviations $\sigma_A$ and $\sigma_B$ as $\frac{cov(A,B)} { \sigma_A \sigma_B}$.
The covariance itself may be calculated as $E(AB) - E(A)E(B)$.
With $A$ and $B$ independent and each symmetric around $0$, the second term is $0$.
So with $Z = KX + Y$, we have $cov(X,Z) = E[X(kX+Y)] = E(KX^2) + E(XY)$.
Again, with $X$ and $Y$ independent and each symmetric around $0$, the second term is $0$.
$$ cov (X,Z) = E(KX^2) = KE(X^2) $$
The second moment $E(X^2)$ of a continuous uniform distribution $(a^2 + ab + b^2)/3$ where $a$ and $b$
are the bounds of the distribution. In this case, $(-1)^2 + (-1)*1 + 1^2 = 1 -1 + 1 = 1$.
$$ cov(X,Z) = K \frac{1}{3}  =  \frac{K}{3}$$

The variance $V(X)$ of a uniform distribution is $(b-a)^2/12$.
\begin{align*}
V(X) &= \frac{[1-(-1)]^2}{  12 } = \frac{2^2}{12} = \frac{1}{3} \\
V(Z) &= V(KX+Y) = K^2*V(X)*V(Y) = K^2V(X) + V(X) = (K^2+1)V(X) \\
V(Z) &= \frac{(K^2+1)}{3} \\
V(X)V(Z) &= \frac{K^2+1}{9} \\
\sigma(X)\sigma(Z) &= \sqrt{ \frac{K^2+1}{9} } = \frac{ \sqrt{K^2+1} }{ 3 }\\
r(X,Z) &= \frac{ \frac{K}{3}}{  \frac{\sqrt{K^2+1}}{3}}  = \frac{K}{ \sqrt{K^2+1)} } \\
\end{align*}

So for $r = \frac{1}{2}$, $\frac{K}{\sqrt{K^2+1}} = \frac{1}{2}$.
$$ 2K = \sqrt{K^2+1} $$
We will square both sides, which will give two solutions for $K$, only one of which will be relevant.
\begin{align*}
4K^2 &= K^2 + 1 \\
3K^2 - 1 &= 0 \\
\end{align*}
using $a^2 - b^2 = (a+b)(a-b)$, we see $(\sqrt{3}K +1)(\sqrt{3}K - 1) = 0$.
$$ \sqrt{3}K = 1 \text{ OR } -1$$
Since we can see in the original problem K must be positive to yield a positive correlation,
$\sqrt{3}K = 1$.
$$ k = \frac{1} {\sqrt{3}} $$


Differential equation $y''=e^y $

Question: Is there a quick way of finding $y(t)$ which satisfies the following equation:$$y''=e^y \ ?$$ Usually when given equation $ax''+bx'+cx=0$ I looked for roots of characteristic polynomial, but in this case I'm not sure how to proceed.
Comment: $$e^y=\frac{d^2y}{dt^2}=\frac{d\left(\frac{dy}{dt}\right)}{dt}$$

$$\implies e^y\ dy=\frac{dy}{dt}\ d\left(\frac{dy}{dt}\right)$$

$$\implies e^y+k=\frac12\left(\frac{dy}{dt}\right)^2$$

$$\frac{dy}{dt}=\pm\sqrt{2(e^y+K)}$$
Comment: Multiply both sides by $y'$ and integrate. Commonly occurring trick. because this type of DE shows up in equations of motion.
Comment: Why not Integrate  !!!!
Comment: @labbhattacharjee your comment would be more appropriate as an answer, preceding with the word **hint**.
Answer: This is a nice trick to use in general. Multiply each side by $y'$:
$$y'' y' = e^y y'$$
Integrate each side to get
$$\frac{1}{2} (y')^2 = e^y+C.$$
Solve for $y'$:
$$y' = \sqrt{2 e^y + C}.$$
Integrate again:
$$\int \frac{y'}{\sqrt{2 e^y + C}} dx = x + D.$$
Using Wolfram Alpha one gets:
$$-\frac{2}{\sqrt{a}} \tanh^{-1} \left(\sqrt{\frac{C+2e^y}{C}} \right) = x + D.$$
I will leave it to you to solve for $y$.
Comment: @Jules

$$\int \frac{y'}{\sqrt{2 e^y + C}} dx = x + D.$$

change of variables $v^2 = 2e^y + C$ leads to
$$
\int \frac{1}{v}\frac{2v}{\left(v^2-C\right)}dv = -\frac{2}{C}\int\frac{1}{1-\frac{v^2}{C}}dv
$$
change to $u^2 = v^2/C$ to clean up the integral we have
$$
-\frac{2}{\sqrt{C}}\int\frac{1}{1-u^2}du = -\frac{2}{\sqrt{C}}\int \frac{d}{du}\tanh^{-1}(u)du = -\frac{2}{\sqrt{C}}\tanh^{-1}(u) = x + D_{1}
$$ then transforming back to $y$ by $u=\sqrt{\frac{2e^y+C}{C}}$.
Comment: +1 for the multiplication trick, but you should explain the integral, WA is not an answer (it could be wrong, WA too has bugs)
Comment: totally, this integral doesn't look amicable, how can one calculate it without using Wolfram?
Comment: You can always differentiate the answer given by Wolfram to see if this answer is ok.
Answer: If you don't like the "ad hocness" of multiplying by $y'$ and then integrating, you can take note that since the ODE has translational symmetry in $x$, if we write out the ODE in terms of $x=x(y)$ it will be first order in $x'$: $\displaystyle x'=\frac{1}{y'}$, $\displaystyle x''=-x'^3e^y\implies -\frac{x''}{x'^3}=e^y$, and now integrating with respect to $y$ gives $\displaystyle \frac{1}{2}\frac{1}{x'^2}-e^y= $ const $\displaystyle \implies \frac{y'^2}{2}-e^y= $ const. and this can be written as a separable ODE and so can be reduced to quadrature.
Comment: @Taladris If $y_1=y_1(x)$ is a solution of the problem, then so is $y_2(x)=y_1(x+t)$ for all $t\in\mathbb{R}$.
Comment: What is "translational symmetry"?

Differential equation $y''=e^y $


Could not find com.android.tools.build:gradle:4.0.1 ( or any version )

Question: Error :
Could not find com.android.tools.build:gradle:4.0.1. Searched in the following locations:
https://jcenter.bintray.com/com/android/tools/build/gradle/4.0.1/gradle-4.0.1.pom
https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/4.0.1/gradle-4.0.1.pom
Required by: project : Open File
*** looks like google() and jcenter() are not working as expected.***
I migrated from android studio 2.3.3 to 4.0.1 and this error happened.
what is my problem???? plz tell me if you need more information .
thank you for your answer :)
Comment: Please use `mavenCentral()` for dependencies repository entry, `jcenter()` will be deprecated https://developer.android.com/studio/build/jcenter-migration
Comment: Entering the 6 lines in my gradle.properties from this answer https://stackoverflow.com/a/63235324/4833705 by @Sadegh is what fixed it for me. I described it here: https://stackoverflow.com/a/74113127/4833705
Comment: Have you tried clearing your build directory and rebuilding the project from scratch?
Comment: yeah. that's not work
Answer: This solution may only work in Iran. If you know that's working out of Iran, please let others know.
Why would a proxy be necessary? There have been a number of technology-related sanctions against Iran.
Windows
go to -> File | Settings | Appearance & Behavior | System Settings | HTTP Proxy,
and choose -> manual proxy configuration. set host name: fodev.org
and set port number: 8118. now you must find gradle.properties file. that must be in:
Windows: C:\Users\YOURUSERNAME.gradle\gradle.properties OR for
Linux: ~/.gradle/gradle.properties .
if it does't exist, create that yourself and copy this:
systemProp.http.proxyHost=fodev.org
systemProp.http.proxyPort=8118
systemProp.http.nonProxyHosts=*.jitpack.io, *.maven.org
systemProp.https.proxyHost=fodev.org
systemProp.https.proxyPort=8118
systemProp.https.nonProxyHosts=*.jitpack.io, *.maven.org

Mac
Open Network settings by  > System Preferences > Network. Then, choose your wifi and click on advanced, which is located on bottom-right of the panel (if there's a lock  at the bottom left of the Network pane, click it to unlock the preference pane). A window would open in which you should go under "Proxies" tab and then check the box for "Web Proxy (HTTP)". There is a textfield named "Web Proxy Server" in which you should set it to fodev.org and in the next textfield you can enter the port number which is 8118 in this case. The steps may vary depending on the version of macOS and more information about procy server settings can be found on Apple Support Guide. You can also take a look at the screenshot.

The last step is to make sure that have gradle.properties. On finder, choose Go > Go to Folder and then paste ~/.gradle/ and go (alternatively, you can trigger this menu by holding shift + command + G). If you don't see anyfile under the name ofgradle.properties, create it with textedit or terminal and paste this code there:
systemProp.http.proxyHost=fodev.org
systemProp.http.proxyPort=8118
systemProp.http.nonProxyHosts=*.jitpack.io, *.maven.org
systemProp.https.proxyHost=fodev.org
systemProp.https.proxyPort=8118
systemProp.https.nonProxyHosts=*.jitpack.io, *.maven.org

Now, you can run your project.
IMPORTANT : After installation of build.gradle 4.0.1 (or any version), restore this settings to previous state and remove the codes.
Comment: The best solution ever, I live in Syria and suffer from gradle sync ban, nothing worked with me but your solution, you deserve 10 upvotes
Comment: thank you man, it took me a week to solve this. cant we use psiphon instead?
Comment: thanks Sadegh. my problem was resolved with your help :) Thank you
Comment: @Ali.Rashidi you are welcome. I don't think so. vpn not working and we must use proxy.
Comment: It used to work with proxy or VPN, but it can't sync anymore. I suggest this solution: https://stackoverflow.com/questions/50291289/download-and-install-android-studio-gradle-offline
Comment: @Ehsan It's ok for me and there is no problem with sync. i 've been using it for months
Comment: Some companies may use WAF solutions and this may cause a problem retrieving certain URLs from the repositories. You may need to use a proxy/VPN or add the WAF certificate into your Android Studio's cacert file (the only caveat: you need to set the modified cacert file's timestamp the same as the original, otherwise Android Studio will complain; another issue you need to do this for every Android Studio update).
Comment: I was stuck with an issue for 2 days. I updated my `Firebase BoM` and the dependencies were no longer recognized. Upon further research the issue was: `PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target`. Once I added the 6 lines in my `gradle.properties` file, everything worked. THANK YOU!!!
Answer: Deleting and reinstalling my node modules seemed to work for me
rm -rf node_modules
yarn install

Answer: If you are importing a project from github or other.

Close the project in Android Studio. File -> Close project.
In file explorer, delete .idea, .gradle and gradle if there are any inside your project folder. (.idea, .gradle are hidden items. Make sure hidden items are shown in your file explorer) or if you are using command line, do ls -a
Open the project in Android Studio again.
Done.


If $\sum_{k=0}^{n}\binom nk=2^n$ then how is $2(\binom n0+\binom n2+\binom n4+...)=2^n$

Question: $$\sum_{k=0}^{n}\binom nk=2^n$$ then how is $2(\binom n0+\binom n2+\binom n4+...)=2^n$ ?? I don't think it could be because half of the members of the sum are chosen, that seems a bit intuitively risky to conclude, what am i missing here ?
Comment: The even terms have the same sum as the odd terms.
Comment: How is this possible ??
Comment: I cannot believe this is not a duplicate. Time to search.
Answer: We have
$$(1+x)^n = \sum_{k=0}^n \dbinom{n}k x^k$$
Plugging in $x=1$, we obtain
$$2^n = \sum_{k=0}^n \dbinom{n}k$$
Plugging in $x=-1$, we obtain
$$0 = \sum_{k=0}^n \dbinom{n}k (-1)^k$$
Adding both we obtain what you want.
Answer: $\sum_{k=0}^{n}\binom nk=2^n$ results from substituting $x = 1$ in the binomial expansion $(1+x)^{n}=\sum_{k=0}^{n}\binom nk x^k$. Just put $x = -1$ in the same expansion to get $\sum_{k=0}^{n}(-1)^k\binom nk = 0$. Adding these two relations cancels out the odd terms and you get the desired result.
Comment: Very original i must say


Storing images as nodes

Question: I am building a Drupal 7 platform where users can share images. In a nutshell, people should be able to comment on images and like them.
The way I realized this is by creating a custom content type called "image" and adding an image field to it. And then I grant users the permission to create "image" nodes.
However, yesterday I came across this Drupal 6 article http://drupal.org/node/325688 and it's section 'Images as nodes'. It introduces the Image module, which lets you upload images as nodes automatically. Unfortunately, the Image module hasn't been ported to Drupal 7.

Is this the clean way to implement images?
The article also mentions the solution that I made use of:

For example, using Imagefield, you could create a custom content type that contains one CCK imagefield, and configure that field to "contain" (refer to) only a single file. However, note that this custom CCK node type would not be compatible with Image module or its add-ons, and should be named something other than "Image" to avoid confusion.

Is there any point in not naming your custom content type "image"? I mean, it would be a super suggestive name. And the Image module which would provide a content type with the same name will most likely never be ported to Drupal 7. So there should never be confusion.
Lastly, the article mentions that

It is theoretically possible that, for sites with lots (say hundreds of thousands) of images, storing them all as individual nodes could result in a performance hit from the extra database overhead.

Well, storing lots of images is exactly what image sharing platforms are aiming at, isn't it? Is there a better way (in terms of performance) to store images in Drupal 7 while still making it possible for people to comment on them?
Comment: This question is a commentary on an article and several questions in response.  On *Drupal Answers*, it is best to limit a single post to a single question, because if different people answer different parts of your question, it is impossible to award an "accepted" answer.
Comment: my opinion is, if you want commenets and all the node stuff, it is absolutley ok to create node as a holder for images (you can then have flag module etc.). Everything can be a node :) . I am doing simmilar thing with files (sharing files between users (its educational ;) ). If you expect high trafic then consider dedicated server / clusters, but this is big business then.
Answer: The image module does not exist in Drupal 7 because this functionality is added to Drupal 7 core.

Implementing images as nodes was a clean way to do this in Drupal 7. You may still do this in Drupal 7. However, Drupal 7 has gone a long way and offers the entity alternative. At Drupal 6 'everything can be a node'. At Drupal 7, 'everything can be an entity'.
Nodes were meant to be used for publishing text. They come with a lot of functionality that you may find redundant in your use case. All this extra functionality can slow down your site if you have thousands or millions of entries.

I am not sure I understand why you should not do this. It was probably a suggestion and module specific. In Drupal 7 you can name your content type anything you want.

As I told you before, using entities for storing images is a better alternative, as far as the performance is concerned. But then you should implement your own method of commenting.

EDIT: In Drupal 8 there is some advances made in decoupling the comment module from node. See this issue.
Comment: Thank you, it really seems as if the entity approach would be a lot cleaner. And I guess the Media module already takes care of introducing "image" entities, so the only thing that's left to do would be to figure out a commenting solution; maybe making use of the Reply module.

However, there is one more thing that I was wondering about: Do you know if there is a way to use the Image module to let users add images merely to the image library? And not to a node or any type of content? It seems to me that the module manages images inside of nodes.
Comment: I need a simple "upload an image" functionality and not something like "add an image to this node". In other words, _where_ would I put the image field that lets users upload images?
Comment: The media module just replaces the core upload file functionality. This can be attached to any entity. Node, comment, commerce product are all entities. If you create your own entity, you will be able to add a field with a  widget type of 'media' The media module does not create a new entity. I guess you still have the comments problem. There is some advance in d8 about this issue. I have updated my answer about this.
Comment: The Media module contains the File Entity module (http://drupal.org/project/file_entity) which, in my understanding, introduces file entities. In particular, with Media and therefore File Entity installed it should be possible to create new file entities (e.g. image entities) without having to attach them to _other_ entites. Please excuse me if I'm getting this completely wrong.
Comment: I just found out that it _is_ possible, namely by navigating to media/browser and uploading an image to the library. That way the image will not be associated with any node. But I think it'd be great to have some kind of submission form that lets users upload files without having to navigate to the browser. And also when I add fields to the file entity "image", I can only fill in those fields later ('edit file') after I have uploaded the file and the Media module has realized that the file was in fact an image. I think it would be super nice to be able to do this in the first place.
Comment: I really had no idea of the file entity module. I think that your thoughts are in the right direction.
Comment: Thank you so much! One last questions: It seems like the whole file entity story is not quite as developed as I would like it to be (permissions, commenting function). You said using image nodes, which would obviously be the *easier* solution, would eventually (say 10 million images) slow down my site. But would this also be noticeable on a dedicated server with 4GB RAM? Also, could I ever make the transfer to entities when D8 comes out and turn every image node into an image entity somehow?
Comment: I can not really tell you, as this will depend on various things. I have used drupal with varnish which was a a success but this was mainly for anonymous users. There are solutions like mongdb that can certainly help you go a long way. You can look around for benchmarks. http://cyrve.com/mongodb
Answer: If I understand your issue correctly, Bulk Media Upload or Bulk File Nodes modules will do what you want.

Storing images as nodes


The same file on host and inside container is different, it is not in sync with its original

Question: I've faced a weird problem: I mount a file from a host to a container in RW mode, then I edit this file on the host but it's not get updated in the container.
This is an extract from docker inspect <container>'s output:
"Mounts": [
    ...
    {
        "Type": "bind",
        "Source": "/home/a_user/projects/drupal/d8-default/composer.json",
        "Destination": "/var/www/d8-default/composer.json",
        "Mode": "rw",
        "RW": true,
        "Propagation": ""
    },
    ...
]

As you may see, the file is mounted as read-write mode as a separate mount. Now when I edit it on the host, it doesn't get changed in the container. I see this by logging into the container and doing simple cat composer.json there and outside of it.
I've performed additional tests with random files and here is what I discovered:

If a file being edited is located in a directory (which is mounted in RW mode) then changes immediately appear in its container's copy.
If a file is mounted directly then changes are not transferred at all, it seems like the container is maintaining its own version of the file!

Indeed it is highly undesired behavior, it breaks my workflows and I haven't found a solution to overcome this disalignment yet. Any suggestions are welcome.
Answer: When you mount an individual file into a container, what you are mounting is the inode of the file on the linux filesystem. If you replace the file (which many editors do), then the inode changes. That's not normally an issue if you mount an entire directory because the directory's pointer to the inode gets updated. But when only mounting a single file, writes to the file after starting the container will not be reflected between the inside and outside of the container.
For more details, see this issue: https://github.com/moby/moby/issues/6011

Edit: If your goal is to modify a file outside of the container, and have that modify a single file in a directory of files that can't be in the volume mount, then I'd recommend changing the container to have a symlink to a file in a different directory where you can mount the entire directory instead of a single file. That would look like:
In your Dockerfile:
RUN mkdir -p /var/docker/composer \
 && ln -s /var/docker/composer/composer.json /var/www/d8-default/composer.json

And your volume mount would then be:
docker run -v /home/a_user/projects/drupal/d8-default:/var/docker/composer ...

Comment: Yes, thank you. I've also found this discussin: https://unix.stackexchange.com/questions/44373/single-bind-mounted-file-gets-out-of-sync-in-linux
My workaround is to stop using file-mounts at all and I've refactored the structure of my project to use directory-mounts only.


ToolStripMenuItem bigger vertical padding, or vertically centering text in a bigger ToolStripMenuItem

Question: I'm trying to set a bigger vertical padding for ToolStripMenuItems in a ContextMenuStrip. However, changing the Padding.Top property adds padding to the bottom, instead of the top.
I also tried setting a larger Height for the ToolStripMenuItem, it works, however, the text always gets aligned on top, even if the TextAlign property is MiddleCenter. It should be vertical aligned to the center!
I've tried different settings for different properties, nothing works. The idea is that I cannot get the ToolStripMenuItem to have more space around its text, both to the top and to the bottom.
I'm using C#, Windows Forms, Net 2.0, Visual Studio 2010 Express, Windows 7.
Answer: In addition to InBetween's answer, you can fix the highlight rectangle by using a custom renderer and adjusting its "TextRectangle" property. Here's some sample code:
    var itemHeight = 36;
    var verticalPadding = 36 - TextRenderer.MeasureText("A", _DisplayNameFont).Height) / 2;
    menu.Renderer = new MyRenderer { VerticalPadding = verticalPadding };

    class MyRenderer : ToolStripSystemRenderer
    {
        public int VerticalPadding { get; set; }

        protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
        {
            if (null == e)
            { return; }
            e.TextFormat &= ~TextFormatFlags.HidePrefix;
            e.TextFormat |= TextFormatFlags.VerticalCenter;
            var rect = e.TextRectangle;
            rect.Offset(0, VerticalPadding);
            e.TextRectangle = rect;
            base.OnRenderItemText(e);
        }
    }

Answer: You can get the same effect using Margin instead of Padding which will keep the Text of the ToolStripMenuItem aligned.
The drawback is that this wont modify the size of the highlight rectangle when the item is selected so it can look a little strange if you increase a lot the height.
Comment: You can adjust the "TextRectangle" of the ToolStripMenuItem's renderer if you add a few lines of code. See my answer below for details.
Answer: Adding a new line does the job.
It's not the best solution, but it's a quick way to add some padding.
Works well when adding support for small touch screens.
this.configToolStripMenuItem.Text = "\r\nSettings";


Factorization of Polynomial in an extension field

Question: I'm trying to understand the proof of the following problem:

Let $L / K$ be a field extension, and assume that $K$ has $q=p^{r}$ elements. Let $P(X)$ be a irreducible polynomial in $K[X]$. Let $M$ be a subfield of $K(\alpha)$ for $\alpha$ a root of $P(X)$, and suppose that the degree of $K(\alpha)$ over $M$ is $r .$ Show that $P(X)$ factors, in $M[X],$ as a product of $\frac{d}{r}$ irreducible polynomials of degree $r$.

Proof: We have the previous results: (a) $P\left(\alpha^{q}\right)=P(\alpha)^{q}$ for all $\alpha \in L$, (b) If $P(X)$ is irreducible, and has a root $\alpha$ in $L$, then $P(X)$ factors in $L$ as $(X-\alpha)\left(X-\alpha^{q}\right)\left(X-\alpha^{q^{2}}\right) \ldots\left(X-\alpha^{q^{d-1}}\right),$ where $d$ is the degree of $P(X)$. Now, let $Q(X)$ be an irreducible element of $M[X]$ that divides $P(X) .$ Then, since $P(X)$ factors into linear factors in $K(\alpha), Q(X)$ has a root in $K(\alpha) ;$ by (b) this root is of the form $\alpha^{q^{s}}$ for some $s$. Applying (b) with $M$ in place of $K$ and $Q(X)$ in place of $P(X)$ (and noting that $M$ has $q^{\frac{d}{r}}$ elements) we see that the other roots are $\left(\alpha^{q^{s}}\right)^{q^{k} \frac{d}{r}},$ for $0 \leq k \leq r-1,$ so $Q(X)$ has degree $r$ as claimed.

This proof feels a bit too quick for me. Could anyone explain the line "Applying (b) with $M$ in place of $K$ and $Q(X)$ in place of $P(X)$ (and noting that $M$ has $q^{\frac{d}{r}}$ elements) we see that the other roots are $\left(\alpha^{q^{s}}\right)^{q^{k} \frac{d}{r}},$ for $0 \leq k \leq r-1,$ so $Q(X)$ has degree $r$ as claimed?" More precisely,
(1) Why is $0 \le k \le r-1$, and why are the $\left(\alpha^{q^{s}}\right)^{q^{k} \frac{d}{r}}$  distinct for distinct $k$?
(2) How do we conclude $Q(X)$ has degree $r$?
Partial answers (answering only some of the questions) are very welcome! (I will upvote them too)
By the way, this is a problem from a basic algebra course. I do not know Galois Theory.
Comment: Ah! I see what the concern is (+1). I will revise my answer.
Comment: We have already covered this question from many angles on our site. Not sure whether your exact question is covered, because many of the earlier answers did rely on basic Galois theory of finite fields. I tried to do without. If we locate a good duplicate I will delete/CW my answer according how close a match is found.
Comment: @JyrkiLahtonen Thanks for your comment. I was trying to understand the exact sequence of logic that the above proof follows. (For example, if using (b) like the above proof does, then we get that $0 \le k \le deg(Q)-1$, not $0 \le k \le r-1$. Putting $r$ there seemed to me that the degree of $Q$ was being assumed to be $r$, which is circular logic.)
Comment: The revision may address this concern. I assume that (a) and (b) also contain the fact that the elements $\alpha^{q^i}$, $i=0,1,\ldots,d-1$, are distinct.
Comment: The closest hits I could find include [1](https://math.stackexchange.com/q/86778/11619) and [2](https://math.stackexchange.com/q/974485/11619). Both are phrased in a more general setting of Galois theory. I guess it is ok (at least for now), to leave an answer specific to finite fields in place.
Answer: From the factorization of $P(X)$ we know that the elements $\alpha^{q^i}$, $i=0,1,\ldots,d-1$, are all distinct. It may be better to restate this in the form
$$
\alpha^{q^i}=\alpha^{q^j}
$$
if and only if $i\equiv j\pmod d$
If $M$ is an intermediate field, $K\subset M\subset K(\alpha)$, by the tower law of field extensions we know that $\ell:=[M:K]$ is a factor of $d=[K(\alpha):K]$.
Also, $M$ has $q^\ell$ elements.
As noted, the polynomial $Q(X)$ has a root, say, $\beta=\alpha^{q^s}$. By (b) the other roots of $Q(X)$ are
$$
\beta_j:=\beta^{q^{\ell j}}
$$
for $j=0,1,\ldots, t-1$, $t=\deg Q(X)$. For all $i$ we have
$\beta_i=\alpha^{q^{s+\ell i}}.$

Observe that by using (a) and induction on $i$, we see that the element $\beta_i$ is a zero of $Q(X)$ for all natural numbers $i$. That is, not only when $0\le i\le t-1$.

The earlier observation says that
$$\beta_j=\beta_i$$ if and only if $$s+\ell i\equiv s+\ell j\pmod d$$
if and only if
$$
i\equiv j\pmod {d/\ell}.
$$
So there are $d/\ell$ distinct elements $\beta_i$. We know that the zeros of $Q(X)$ are distinct, so we can conclude that $t=d/\ell$.
This answers both parts as we see that $\ell=d/r$.
Comment: In a sense the key is that we get the minimal polynomial of any element $\gamma$ over a field of $q^m$ elements by repeatedly raising the previous roots to power $q^m$, and stop at the exact point we start getting repetitions. All those powers must be included iin the set of zeros, but no repetitions.


Confidence intervals vs sample size?

Question: I am totally new to stats and the field of confidence intervals. So this might be very trivial or even sound stupid. I would appreciate if you could help me understand or point me to some literature/text/blog that explains this better.
I see on various news sites like CNN, Fox news, Politico etc about their polls regarding the US Presidential race 2012. Each agency conducts some polls and reports some statistics of the form:
CNN: The popularity of Obama is X% with margin of error +/- x1%. Sample size 600.
FOX: The popularity of Obama is Y% with margin of error +/- y1%. Sample size 800.
XYZ: The popularity of Obama is Z% with margin of error +/- z1%. Sample size 300.
Here are my doubts:

How do I decide which one to trust? Should it be based on the confidence interval, or should I assume that since Fox has a larger sample size, it's estimate is more reliable? Is there an implicit relationship between confidence itnervals and sample size such that specifying one obviates the need to specify the other?
Can I determine standard deviation from confidence intervals? If so, is it valid always or valid only for certain distributions (like Gaussian)?
Is there a way I can "merge" or "combine" the above three estimates and obtain my own estimate along with confidence intervals? What sample size should I claim in that case?

I have mentioned CNN/Fox only to better explain my example. I have no intention to start a Democrats vs Republicans debate here.
Please help me understand the issues that I have raised.
Answer: In addition to Peter's great answer, here are some answers to your specific questions:

Who to trust will depend also on who is doing the poll and what effort they put into getting a good quality poll.  A bigger sample size is not better if the sample is not representative, taking a huge poll, but only in one, non-swing state would not give very good results.
There is a relationship between sample size and the width of the confidence interval, but other things also influence the width, such as how close the percentage is to 0, 1, or 0.5; what bias adjustments were used, how the sample was taken (clustering, stratification, etc.).  The general rule is that the width of the confidence interval will be proportional to $\frac{1}{\sqrt{n}}$, so to halve the interval you need 4 times the sample size.

If you know enough about how the sample was collected and what formula was used to compute the interval then you could solve for the standard deviation (you also need to know the confidence level being used, usually 0.05).  But the formula is different for stratified vs. cluster samples.  Also most polls look at percentages, so would use the binomial distribution.

There are ways to combine the information, but you would generally need to know something about how the samples were collected, or be willing to make some form of assumptions about how the intervals were constructed.  A Bayesian approach is one way.
Comment: +1. But is the outlook for #3 really so bleak or difficult? If I have a collection of independent estimates, each with its own margin of error, why can I not (at least roughly) combine them in the usual way (as a weighted mean, weighted inversely by squared MoEs) and combine their standard errors as well (using variance formulas)? It wouldn't be perfect, but it ought to be better than choosing one poll on which to rely, right?
Comment: @whuber, I did not mean to paint it as bleak, just to make sure that the poster was aware of and could live with the assumptions needed.
Comment: Thanks Greg! I much appreciate your answers. You mentioned in your reply to question 3 that "A Bayesian approach is one way". Could you point me to some literature that gives more information on this?
Comment: @whuber: Thanks for your comment. That's what I had been thinking of doing. Do you think it is justified to combine these estimates in this fashion? May be not completely, but to a large extent?
Comment: @Nik, there are many tutorials on the web for Bayesian statistics.  A simple approach (which would assume that the samples were all simple random samples, or that the survey design was such that the SRS assumption is not far off) would be to start with a beta prior, then use each poll with a binomial likelihood to update and get a new posterior.  One nice thing about the Bayes approach is you can discount the effect of the previous studies if you don't want them to have as much influence as the most recent poll.
Answer: This is a huge topic, but basically there are two issues:
1) Precision - this is determined by the sample size. Larger samples give more precise estimates with lower standard error and tighter confidence intervals
2) Bias - which, in statistics, doesn't necessarily have the negative connotations it does elsewhere. In polls, they try to get a random sample of XXXX (sometimes likely voters, sometimes registered voters). But, they don't. Some polls only use land lines. Different groups of people are more or less likely to answer. Different groups are more or less likely to just hang up.
So, all pollsters weight their responses. That is, they try to adjust their results to match known facts about voters. But they all do it a little differently. So, even with the same polling input data, they will give different numbers.
Who to trust? Well, if you look at Nate Silver's work on 538, he has ratings of how accurate pollsters were in previous elections. But that doesn't mean they will be equally accurate now.
Comment: Thanks Peter. So an estimate with lower margin of error is more 'precise'. Is there a way to also know how biased it is from just X% +/- x1% error margin? I guess that's not possible unless you know individual sample's preferences, right?
Comment: Yes, that's right. Of course, some pollsters have known biases (in one direction or another). Internal polls (run by one party or the other) are often biased. One way they can do this is by runnign several polls and only releasing those that are favorable.

Then there's the whole issue of "push polls" in which questions about a candidate are prefaced by negative questions about him or her.
Answer: This falls in the area of survey sampling.  In principle, the methods work because randomization is used.  Here are the things that can differ in polls based on subjective decisions.

Sampling frame.  What group of voters should I draw my sample from?

How do I handle the volatility of the undecided voter who may change his opinion on Obama vs Romney based on yesterday's poll or next week?

Peter has touched on the bias.  The literary digest poll of 1936 was a disaster.  It picked the Republican candidate over FDR because the sampling frame was based on a random selection of telephone numbers.  In 1936 only the upper middle class and the wealthy had phones.  That group was dominated by Republicans who tend to vote for the Republican candidate.  Roosevelt won by a landslide getting his votes from the poor and the middle class which tended to be very much a group of Democrats!  That illustrates bias due to the subtly poor choice of a sampling frame.

Survey sampling deals with finite populations.  The population size is N.  Say a simple random sample is drawn from that population and has size n.  For simplicity assume only Obama and Romney are running.  The proportion of votes Obama would get for this sampling frame is an average of binary variables (say 1 if the respondent picks Obama and 0 for Romney). The variance of the sample mean for this variable is [p(1-p)/n][N-n]/N
where p is the true population proportion that would pick Obama.  [N-n]/N is the finite population correction.  in most polls, N is much bigger than N and the correct can be ignored. Looking at p(1-p)/n we see the variance goes down with n.  So if n is large the confidence interval at a given confidence level will get small.  It is this variance (really its square root) that is used to get the margin of error that gets quoted.

Pollsters other survey samplers and statisticians at the US Census Bureau all have these statistical tools at their disposal and they do more complex and accurate methods (cluster random sample and stratified random sampling to mention a couple of methods).
When their modeling assumptions are valid the methods work remarkably well.  Exit polling is a prime example.  On election day you will see the networks accurately project winner in almost every state long before a near-final count.  That is because preelection day variability is gone.  They know historically how people tended to vote and they can determine selected precincts in a way that avoids bias.  The networks sometimes differ. This can be due to a competition to pick the winner ahead of the others' mentality.  It also can in rare instances be because the vote is extremely close (e.g Presidential Election 2000 in Florida).
I hope this gives you a clearer picture of what goes on. We no longer see gross mistakes like "Dewey defeats Truman" in 1948 or the Literary Digest fiasco of 1936. But statistics is not perfect and statisticians can never say that they are certain.
Comment: My answer had nothing to do with Clinton and the 2016 election which had many strange issues. (1) Russian intervention, (2) Clinton won the popular vote and (3) some Trump voters were reticent to admit that they would vote for Trump. Perhaps I should add that polls can be wrong when voter turnout is not what was expected.
Comment: Thanks for the detailed explanation. This really helped!
Comment: We no longer see gross mistakes? So Clinton won in 2016, did she? I take your known unknowns and raise you a [black swan](https://en.wikipedia.org/wiki/Black_swan_theory). Like my daddy used to say, "It's what you don't know that kills you."

Confidence intervals vs sample size?


For redirected domains, what DNS records are required?

Question: This applies to my VPS that runs both the web server (nginx) and email server (dovecot + postfix) for several domains.
Hypothetically, suppose that I have domain company.com, and that I additionally purchased the .org, .net, .us and .uk variants of the same domain to deter any unfortunate incidents.  The additional domains (every TLD not .com) will serve only to redirect to company.com.
Question: how do the DNS records for the primary domain and all the redirect domains differ?
Specifically:

What DNS records do I need, at the bare minimum, for the redirect domains?
For email subdomains such as autoconfig, imap, mail, pop, and smtp, do the redirect domains require the same?
What should MX records look like?  Is it just 1 mail.company.tld. across the board?
Am I correct in assuming that need an SSL cert for every domain, even the redirecting ones?

Thank you in advance!
Comment: What you need to do with these domains depends on your goals. *Why* did you purchase these additional domains (and not the 1300 other endings)?
Comment: Because those are the most commonly encountered by the average user and therefore mistaken for legitimate (unlike, say, .jewelry or .surgery), and also because those are cheap in my particular instance.
Comment: As for why not the other 1300+ TLD extensions: because I don't have $300,000 per year to waste of course: https://shkspr.mobi/blog/2019/05/how-much-would-it-cost-to-buy-every-domain-name/ (-:
Answer:
how do the DNS records for the primary domain and all the redirect domains differ?

They don't, as the DNS has no knowledge about "redirects", but just helps to resolve a name, through an IP address, so for all cases, through direct A or AAAA records, or with CNAME intermediate records.
All names must resolve to an IP address where a webserver listens for HTTP calls and does "redirects" (or proxying) as needed.

Am I correct in assuming that need an SSL cert for every domain, even the redirecting ones?

Again, this has nothing to do with the DNS. If you do an HTTPS call to https://www.example.com/ the webserver has to reply with a valid certificate for www.example.com and only after that it can reply with an HTTP 301, 302, 307 or 308 to denote a redirect to another URL.
PS: and please do not say "SSL cert" this has no meaning for at least two reasons.
Comment: Most of the time, in context of websites, I think "certificate" is enough to understand what it is about.
Comment: Now I am really interested if there is *any* (short) name for those, well, *"CAB compliant X.509 certificates"* that is bad for less than two reasons. (edit: found [your earlier answer here](https://serverfault.com/a/919103/250204))
Comment: Gotcha, so everything has to point to the web server, no change in DNS whatsoever.


Change the ZIndex from two element

Question: I have a simple WPF application with two button. This is the code in my xaml file:
<Grid x:Name="grigliaPulsantiBody" Visibility="Visible"
        Grid.Column="1" Grid.Row="0" Panel.ZIndex="2"
        HorizontalAlignment="Center" VerticalAlignment="Center"
        Width="Auto" Height="Auto">
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>

    <Button x:Name="buttonLookNao" Content="Guarda NAO negli occhi"
        Grid.Column="0" Grid.Row="0"
        Click="button_Click" Width="200" Height="100" Background="Red" />

    <Button x:Name="buttonLookParent" Content="Guarda Genitore negli occhi"
        Grid.Column="1" Grid.Row="1"
        Click="button_Click" Width="200" Height="100" Background="Green"/>

</Grid>

This is another control that I have create:
<local:RiepilogoEsercizio x:Name="riepilogoEsercizio" VerticalAlignment="Top" HorizontalAlignment="Right"
   Margin="0,-600,180,0" Panel.ZIndex="0"
   Grid.Row="0" Grid.Column="0" Visibility="Hidden"/>

If I click on a button, the elemt "riepilogoEsercizio" change his ZIndex, so I have this
 Canvas.SetZIndex(riepilogoEsercizio, 999);

This is ok.
Now I want to set hidden this element. I use this code:
private void annullaBoxUscita(object sender, RoutedEventArgs e)
{
    try
    {
    myLoadBoxRiepilogoAnimation.From = 1.0;
    myLoadBoxRiepilogoAnimation.To = 0.0;
    //mostro la finestra dei risultati dell esercizio
    Storyboard.SetTargetName(myLoadBoxRiepilogoAnimation, riepilogoEsercizio.Name);
    Storyboard.SetTargetProperty(myLoadBoxRiepilogoAnimation, new PropertyPath(UIElement.OpacityProperty));
    //riepilogoEsercizio.labelTempo.Content = gioco.tempoEsecuzioneEsercizio;
    //riepilogoEsercizio.labelRisposteEsatte.Content = gioco.numeroRisposteCorrette;
    //riepilogoEsercizio.labelTentativi.Content = gioco._numeroTentativi;
    //riepilogoEsercizio.Visibility = Visibility.Visible;

    Canvas.SetZIndex(riepilogoEsercizio, -800);
    Canvas.SetZIndex(grigliaPulsantiBody, 2);
    myStoryboardBoxRiepilogo.Begin(this);
    riepilogoEsercizio.IsEnabled = false;
    }
    catch (Exception exc)
    {
    log.Error("ButtonEsci_Click: ", exc);
    this.Close();
    Process.GetCurrentProcess().Kill();
    }
}

This code works, the element "riepilogoEsercizio" is hidden, but I can't click on second button "buttonLookParent", because the element "riepilogoEsercizio" is hidden but it is on this button. I try to change the ZIndex setting but not found.
Comment: Try setting its `Visiblity` to `Collapsed`.
Comment: Added that as answer. Please accept that so that others can learn from it.
Answer: Set the Visibility to Collapsed.
Answer: The problem here is that you have different panels, you have the Canvas and you have the Grid. In the grid you have the buttons, and in the canvas the controll you want to show/hide. The Panel.Zindex property works for the items that are in the same panel, so in this case decreasing the zindex value will doesn't work. A solution fo this is setting the Visibility property to Collapsed (like :Nikhil Agrawal said) in this way the visual item will behave like if it was not in the visual tree.
Hole this helps...

Change the ZIndex from two element


Why isn't table rows clickable, with data retrieved from MySQL & jQuery .click function?

Question: I've retrieved all data from MySQL table and echoed inside a table rows, once it is clicked a text editor appears, although only the first result is clickable while all the rest there are no effects when clicking on them.
foreach to retrieve data
$getInfo = $articleClass->get_all_article_info();

foreach($getInfo as $data)
{
    $article_title = $data['article_title'];
    $article_content = substr(htmlentities($data['article_content']),0,50).'...';
    $article_content_full = $data['article_content'];

    echo '

                '.$article_title.'

                '.$article_content.'

            <textarea id="editor1">

                    '.$article_content_full.'

            </textarea>

    ';
}

jQuery
$(document).ready(
function()
{
    $("#tr_id").click(function()
    {
        $("#post_info_id").css("display", "block");
        $("#table_id").hide();
    });
});

window.onload = function()
{
    CKEDITOR.replace( 'editor1' );
};

EX:
I get a list of results
[row 1] title1 | content1
[row 2] title2 | content2
[row 3] title3 | content3
[row 4] title4 | content4
[row 5] title5 | content5
[row 6] title6 | content6

If I click on row 1, the text editor opens up, hides the tr_id and displays the text editor, but if I return to the index page and click on row 2, it's an empty row. I am not sure if this issue is due to using a foreach or because jquery, which I doubt.
Answer: id need to be unique. So when doing $("#tr_id"), it return only 1 result (the first one) and do what you ask for. Change your id for a class.
In case you are lazy (but i mean really lazy) and don't care about valid HTML, here 2 working selector :
$("tr#tr_id");
$("[id='tr_id']");

Comment: Okay, I set the id of the tr to each unique article_id, all have unique id's now, but I cannot get the #post_info_id to correspond with the correct tr id as the jquery is outside of the echo, so when I click on the row it just display any of the #post_info_id that was retrieved.
Comment: @iBrazilian2 I am not quite following you here... All you had to do is change `id="tr_id"` to `class="tr_id"` and your selector to `.tr_id`.
Comment: That did not work because even if I do that, #post_info_id doesn't have an specific id either, so it just retrieves the first result always.
Comment: @iBrazilian2 you'll need to use [DOM traversing methods](http://api.jquery.com/category/traversing/).
Answer: Use class for

change jquery method to on tr class
$(".tr_class").click(function(){
//your code

})

Because if you want click event on all tr "ID" doesn't suits you well.


Coin Toss System

Question: http://www.quantwolf.com/calculators/recurrencetime.html
The expected number of runs for 2 consecutive heads or tails is 3.
Is there an edge if we place a progressive bet of consecutive appearance of H or T only after pattern HTH or THT appears? Or is prob=0.5 always?
Comment: why is the link there?
Answer: The probability is allways 0.5. This is independent of the previous pattern.

Coin Toss System


webform submission presave in a custom module

Question: I'm quite noob at drupal, i have a custom module with the function below:
<code>function at_custom_webform_submission_presave($node, &$submission) {
// my code here
}
</code>
i don't know why, but it's seems that the function is not called... what's
the problem ?
I tried to use an email function php and nothing happened. and when i tried the same thing with : at_custom_user_presave, i got an email.
So that's why i'm thinking that the function is not called anymore. Before it was.
The website use 7.61 version's drupal and 7.x-4.18 version's webform.
Thanks for helping.
Comment: Flush all caches, double check that At Custom Webform module is indeed enabled.
Comment: To check whether the function is running or not, you could add `drupal_set_message('Yes, it ran!');` inside the function.
Comment: Where the message will appear ?, is there a way to dump variables ? because var_dump, die doesn't work.
Comment: Yes, install & enable the **[Devel](https://www.drupal.org/project/devel)** module. Then use `dpm($varname);` to inspect variables.
Answer: According to your sample code,to use hook_webform_submission_presave
your module name must be "at_custom"

Enable Webform module
Enable your at_custom module
Put your hook under your module file: 'at_custom.module'

<code>    function at_custom_webform_submission_presave($node, &$submission) {
    // your code here
    }
</code>
Comment: It's exactly like that but it doesn't work :(
Answer: I think i find why it was not triggered.
the form was an user create form, no a webform. so that's why, thanks for the help.


Multiple outputs with a for loop in praat

Question: I have a script where I have multiple folders each with three audio files in them ID#_1, ID#_2, and ID#_3. The user can input a string of different ID#s, one after the other, and then the script recognizes the different IDs and runs the code for each of them.
I have a for loop set up for this -
form Settings
        comment Enter the IDs of the different subjects
        sentence subjectIDs
endform
numOfSubjects = length(subjectIDs$)/4

for i from 0 to (numOfSubjects - 1)
    subjectID$ = mid$(subjectIDs$, 1 + 4*i, 4 + 4*i)
    outFile$ = subjectID$ + "/SubjectResponseOnsets" + subjectID$ + ".txt"
    path$ = subjectID$ + "/" + subjectID$
    @firstOutput
    @secondOutput
    @thirdOutput'

Each of these procedures is defined previously in the code, and they basically output certain ranges from the audio files out to a text file.
The code seems to work fine and generate the output file correctly when one ID is given, but when I try to run it with more than one ID at a time, only the text file for the first ID is outputted.
The for loop does not seem to be working well, but the code does work fine in the first run.
I would greatly appreciate any help!
Answer: I don't know if I understood well what your script was trying to do, since the snippet you pasted was incomplete. It's best if you provide code that is executable as is. In this case, you were missing the closing endfor, and you were calling some procedures that were not defined in your snippet (not even as placeholders). I had to write some dummy procedures just to make it run.
Since you also didn't say how your script was failing, it was unclear what needed to be fixed. So I took a stab at making it work.
It sounded as if your ID splitting code was giving you some problems. I took the split procedure from the utils plugin available through CPrAN, which makes inputting the IDs easier (full disclosure: I wrote that plugin).
form Settings
  comment Enter the IDs of the different subjects
  sentence subjectIDs 01 02 03
endform

@split: " ", subjectIDs$
numOfSubjects = split.length

for i to numOfSubjects
  subjectID$ = split.return$[i]
  path$ = subjectID$
  outFile$ = path$ + "/SubjectResponseOnsets" + subjectID$ + ".txt"

  # Make sure output directory exists
  createDirectory: path$

  @firstOutput
  @secondOutput
  @thirdOutput
endfor

procedure firstOutput ()
  appendFileLine: outFile$, "First"
endproc

procedure secondOutput ()
  appendFileLine: outFile$, "Second"
endproc

procedure thirdOutput ()
  appendFileLine: outFile$, "Third"
endproc

# split procedure from the utils CPrAN plugin
# http://cpran.net/plugins/utils
procedure split (.sep$, .str$)
  .seplen = length(.sep$)
  .length = 0
  repeat
    .strlen = length(.str$)
    .sep = index(.str$, .sep$)
    if .sep > 0
      .part$ = left$(.str$, .sep-1)
      .str$ = mid$(.str$, .sep+.seplen, .strlen)
    else
      .part$ = .str$
    endif
    .length = .length+1
    .return$[.length] = .part$
  until .sep = 0
endproc

If this is not what you are having trouble with, you'll have to be more specific.
Comment: Thank you very much! I was very vague with my question because not all of the code was mine, so I was avoiding posting it online. However, your code and your split procedure (which I will give you credit for) helped me figure it out!
Comment: @Fancyvase Glad to hear. If this answered your question, please consider upvoting and marking it as the accepted answer. This helps others know about the quality and applicability of the answer.


Scroll do tamanho da window

Question: Olá.
Bom, sou novo na comunidade então me desculpem se algo que eu escrever não ficar muito claro. Gostaria de saber como eu faço para dar um scroll do tamanho da tela do navegador, quero dividir o site em três, tipo um efeito "ancora" só que com o scroll do mouse.
Obrigado dês de já.
Comment: Não ficou claro pra mim o que você quer. Pode fazer uma imagem?
Comment: Então em vez do usuário rolar a página gradativamente como é normal,eu queria que quando ele rola-se  ele fosse para um ponto específico
Comment: @AfonsoJorge Usando uma função que detecta a ação "scrolling" você pode verificar se a altura esta em um range e este tem um ponto determinado na pagina para onde será definido o `scroll`.
Comment: http://alvarotrigo.com/fullPage/ Você pode tentar usar este plugin! Seria isso? Lembrando que seu site vai ter que se adaptar em resoluções menores
Answer: Desenvolvi um exemplo, logo abaixo, que faz basicamente o que disse nos comentários da sua dúvida. Criei um listener do evento scroll que verifica nos ranges, que são os offsetTop do sections da pagina, para saber em qual section a função scrollTo deve posicionar o scroll.

// Object usado para regra
var oScroll = {
  y: 0,
  sec1: document.getElementById('sec1').offsetTop,
  sec2: document.getElementById('sec2').offsetTop,
  sec3: document.getElementById('sec3').offsetTop,
  prevent: true
}

window.addEventListener('scroll', function(e) {
  if(this.scrollY < oScroll.y) {
  // subindo
    if(this.scrollY > oScroll.sec1 && this.scrollY < oScroll.sec2) {
     this.scrollTo(0, oScroll.sec1);
    } else if(this.scrollY > oScroll.sec2 && this.scrollY < oScroll.sec3) {
     this.scrollTo(0, oScroll.sec2);
    } else if(this.scrollY > oScroll.sec3) {
     this.scrollTo(0, oScroll.sec3);
    }
  } else if(this.scrollY > oScroll.y) {
  // descendo
    if(this.scrollY > oScroll.sec1 && this.scrollY < oScroll.sec2 && oScroll.prevent) {
     this.scrollTo(0, oScroll.sec2);
    } else if(this.scrollY > oScroll.sec2 && this.scrollY < oScroll.sec3) {
     this.scrollTo(0, oScroll.sec3);
    }
  }
  oScroll.y = this.scrollY;
});
body::-webkit-scrollbar {
  display: none;
}
.main {
  height: 1500px;
  margin: 100px 0;
}
.section {
  background: lightblue;
  height: 500px;
  margin: 10px 0;
}

      Section 1

      Section 2

      Section 3

Veja o exemplo no JSFiddle se preferir.
Answer: segue uma opção utilizando CSS, especificamente transition e transform.

var container = document.querySelector(".container");
var contents = document.querySelectorAll(".content");

var containerHeight = 100 * contents.length;
var contentHeight = 100 / contents.length;
var contentAtual = 1;
var atualizarContent = function (incremento) {
  contentAtual += incremento;
  deslocamento = (contentAtual - 1) * contentHeight;
  container.style.transform = "translate3d(0px, -" + deslocamento  + "%, 0px)";
}

container.style.height = containerHeight + "%";
[].forEach.call(contents, function (content, indice) {
  content.style.height = contentHeight + "%";
});

atualizarContent(0);
container.addEventListener("wheel", function (event) {
  if (event.deltaY > 0) {
    if (contentAtual < contents.length) {
      atualizarContent(1);
    }
  } else {
    if (contentAtual > 1) {
      atualizarContent(-1);
    }
  }
});
/* transform: translate3d(0px, -100%, 0px); */

html, body {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
  overflow: hidden;
}

.container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  transition: transform 1s ease;
}

.content {
  position: relative;
  width: 100%;
  height: 100%;
}

#content1 {
  background-color: crimson;
}

#content2 {
  background-color: teal;
}

#content3 {
  background-color: steelblue;
}

#content4 {
  background-color: darkorange;
}

Scroll do tamanho da window


Dynamic subdomains on Mac os x

Question: Here is my ideal setup that I would like to figure out how to do:
I have a domain professionally hosted:
Example.net
I have a subdomain, home.example.net that points to my Mac mini at home. I've already got this working just fine. The document root for home.example.net is /Users/me/Sites
I want to setup dynamic subdomains such that anything that comes before home.example.net (the regex version: *.home.example.net) has the document root: /Users/me/Sites/$1
For example: visiting bacon.home.example.net will have the doc root /Users/me/Sites/bacon
How can I get this setup so I don't have to add a new vhost for every project?
Answer: You need to enable mod_rewrite
a2enmod rewrite

and add a the following directives to your Apache configuration:
ServerAlias *.home.example.net

<Directory /User/me/Sites>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^home\.example\.net
  RewriteCond %{HTTP_HOST} ^([^.]+).home\.example\.net
  RewriteRule ^(.*)$ http://home.example.net/%1/$1 [L]
</Directory>

Of course you need to make sure that the DNS records and subdirectories for each subdomain exist.
Comment: If he's already mapping `*.home.example.net` to his localhost, that shouldn't matter
Comment: Is there anyway to bypass "making sure the DNs record exists"? How does one do that?
Comment: Not unless you want to start managing `hosts` files. How is the browser supposed to resolve `foo.home.example.net` to an IP address without name resolution?
Comment: You're right. I hadn't thought of wildcard DNS records.
Comment: So just the mod rewrite will work then?!
Comment: If `host SOMETHING.home.example.net` returns an address it should work, yes.

Dynamic subdomains on Mac os x


How to report a SVM model to a 3rd party after cross-validation?

Question: I have a binary classification problem. I trained my dataset using a Support Vector Machine (SVM). Now I want to report the model I trained to a 3rd party so that they can use.
For the primal probem of SVM, the classifier equation is of the form,
y = w.x + b

where w is the weight vector, b is the constant and x is the new instance. Depending on the value of y, we can predict the class.
I could report the weight vector w and constant b which was obtained my model.
But if I want to test my model using cross-validation, then how do I report my model? Everytime I cross-validate, the equation of the classifier built will change.
Answer: You do cross-validation to estimate the generalization performance for a given parameter tuple. Once you have your estimate you train another model on the full training set using the same parameters and give that model to the third party.
Comment: @amoeba By parameter tuple I refer to the set of hyperparameters you use to construct the model (typically $C$ + kernel parameters in the context of SVM classifiers). You should use the same set in both cross-validation and training the overall model.
Comment: @MarcClaessen: Right, I am just clarifying for the benefit of OP (whose question sounds like he is quite confused). Note that he seems to be using linear SVM, in which case there is probably only one parameter ($C$) if I am not mistaken. I think your answer is the best here, because others go into unnecessary digressions into what OP is *not* asking (+1).
Comment: What exactly (in the context of this question) do you mean by parameter tuple?
Answer:
Everytime I cross-validate, the equation of the classifier built will change.

Usually, there is a series of assumptions associated with the cross validation:

First of all, you assume that each of the many surrogate models is equivalent (at least in its predicting power) to the model trained on the whole data set.
Noticing that this assumption is violated (the pessimistic bias of cross validation is a symptom of this violation), you can make the weaker assumption that at least the surrogate models are equvaltent to each other.  This allows you to pool the results of their testing.
If even that assumption breaks down, you have to face the fact that your models (or their predictions) are unstable.

So first of all, as long as 1. or at least 2. is met at the level of stable support vectors, there is no practical problem with your reporting. Different support vector sets can lead to models that basically give the same predictions. As long as that is the case, there is still no trouble: you have different support vectors that essentially describe the same decision boundary.
The only situation where these changes become problematic is when the predictions become unstable. But e.g. with iterated $k$-fold cross validation you can measure whether there is any problem of unstable predictions. (See e.g. Confidence interval for cross-validated classification accuracy)
If predictions are stable, you are fine with reporting the model trained on the whole data set.
If there is, there are 3 possibilities.

You can report the validation results including the observed instability (validation means demonstrating that your model does its job, and stable predictions are probably part of that).
And you can add to your professional experience that you overfitted the model, and go for a more restricted one.
(Strictly speaking, that will require its own independent test set. But you may get away here for practical reasons with cross validating again if you just step once towards a less complex model. If you do that, I'd recommend you make the reader aware that another validation should have been done, but that was impossible for practical reasons. And report the full "history" of developing the model.)
Slightly esoteric for SVM, but you can aggregate the surrogate models into an ensemble classifier.
Comment: "*But you may get away here for practical reasons with cross validating again if you just step once towards a less complex model. If you do that, I'd recommend you make the reader aware that another validation should have been done, but that was impossible for practical reasons.*. While true, this is only useful if the other party disposes of statisticians. In my experience, often the actual users of predictive models (for example clinical physicians) do not want this information as they don't know what to do with it. Providing too much info is sometimes considered to be communication noise.
Comment: @cbeleites: Wait, I am confused. Why don't you suggest to train the SVM on the full dataset after cross-validation? This seems to be the standard practice, and also an advice given in many other threads here (I can count three questions about that on the top-voted page of [tag:cross-validation] tag :)
Comment: @amoeba this is not strictly necessary for stable algorithms (like SVM), since a classifier trained on the whole data set will only differ marginally from the classifiers trained during cross-validation.
Comment: @amoeba: well, first of all I thought I had covered that in the explanation of assumption 1. Second: the only thing where you really don't do it is if you go for the ensemble model. There the final model would be the ensemble of all surrogate models. Thirdly, Marc already explained that aspect very clearly.
Comment: @cbeleites: I see, thanks! Just wanted to clarify if there is any difference in views here (but it seems not).


Problem with character vectors and linear regression in R

Question: Quick question.
I want to perform a linear regression that looks like this:
lm(y ~ x1 + x2 + x3 + x4 +x5, mydata)

This works fine if I manually write out this code.
However, the independent variables that I want to use are stored as a character, like this:
> vars
[1] "x1 + x2 + x3 + x4 +x5"

I tried typing this:
lm(y ~ vars, mydata)
Error in model.frame.default...

But it gives an error!
So then I tried this:
lm(y ~ noquote(vars), mydata)
Error in model.frame.default...

And then this
lm(y ~ print(vars, quote = FALSE), mydata)
Error in model.frame.default...

Anyone have a clue how I can get around this problem? The character string in "vars" is being provided to me by a program upstream, so I can't work around it at that level.
Thanks!
Comment: @Xi'an Alexander has a character string representing the RHS of a model formula in R. The problem then is how to create a valid R formula from this character string representation.
Comment: +1 From me - clear question with simple example and evidence of effort in trying to solve the problem. Not sure why this was down-voted?
Comment: Don't you have access to x1,...,x5? I do not get this "x1+...+x5" representation.
Comment: Yes, but I just put them there as placeholders as an example. They are just variables. I have thousands of variables in my database, so writing this code by hand is not possible.
Answer: You can build a formula from character vectors using standard R functions and as.formula(). The trick is to note that you need to have a full formula (containing at least a ~) for R to create a formula object for you. Here is an example
## predictors
vars <- "x1 + x2 + x3 + x4 + x5"

## dummy data for example
dat <- data.frame(matrix(rnorm(120), ncol = 6))
names(dat) <- c("y", paste("x", 1:5, sep = ""))

## create a formula - here we need to paste on the response part
##  y ~
form <- as.formula(paste("y ~", vars))

## Fit the model using `form`
mod <- lm(form, data = dat)

If you print form you'll see that R has created a special object that no longer prints as a character string would:
> form
y ~ x1 + x2 + x3 + x4 + x5

Comment: Gavin, thanks a ton for your help! This is the first time that I've come across the "as.formula()" function - quite useful!


Prove that the midpoint of $XY = AB$

Question:
Prove that given two point in the plane $A$ and $B$, the midpoint of $AB$ is the same as the midpoint of two points on $AB$, which are $X$ and $Y$ such that $AX = BY$.

I have a few ideas for how to prove this. It seems pretty intuitive at first that this must be true by drawing a few pictures, and I think an algebra proof will suffice for this one. However it might get a bit messy, so I was wondering what would be an efficient way to prove this.
Answer: EDIT: It's important that $X$ and $Y$ lie on segment $\overline{AB}$, not necessarily $AB$.  Otherwise, this proof fails.
EDIT2: The user below me implicitly pointed out a fallacy in my original argument; it has been fixed.
But in any case, a short chain of reasoning is the following: let $M$ be the midpoint of $AB$.  Assume WLOG that $AX<AM$; otherwise, we can simply swap $X$ and $Y$ to get an isomorphic proof.  But note that from $AX=BY$ we have $$AM-AX=BM-BY\implies MX=MY,$$ so $M$ is the midpoint of $XY$ as well.  $\blacksquare$
Comment: So if we wanted to prove the statement if $X$ and $Y$ are not on $\overline{AB}$ but rather line ${AB}$, would the proof be similar?
Comment: The proof would be false :P  (In particular, take, say, A, X, B, Y collinear in that order.)
Answer: Let the midpoint be called M.
Case 1 A, X, and M are colinear.  Then AM = 1/2 AB = MB and AM = AX + XM.  Now YM = XM < AM = MB, so B, Y, and M. Are colinear and MB = YB + YM.  But AM = MB and XA = BY so YB + YM = AX + MX so YM = MX so M is the midpoint of XY.
Case 2 A, M, X are colinear.  Proof similar.

Prove that the midpoint of $XY = AB$


Flamenco guitar strings

Question: Before the invention of nylon, from what material were strings made for use by  flamenco players? I have tried different search engines and forae but found no answer or similar question.
Answer: In Europe, stringed instruments (harps, guitars, violins) have used strings made from animal gut for millenia.
The lower strings of a guitar were sometimes made with gut wrapped around a silk core.
Here are the icky details.
Comment: It's like, who first ate snails?
Comment: Fascinating. Wonder if someone found out how to make them by accident. Some accident! Seriously, why would anybody do all that?
Comment: Whoever it was, we can't know their name, because by the time we'd thought of naming people, we'd already been eating snails for 27,000 years.

Flamenco guitar strings


Jointly Sufficient Statistic Question

Question: So here is a problem I have been working on:
Suppose that survival time $X$ has a lognormal distribution with parameters $\mu$ and $\theta$ (which are the mean and standard deviation of $\log(X)$, not of $X$ itself). Are $\sum_i X_i$ and $\sum_i X_i^2$ jointly sufficient for the two parameters? If not, what is a pair of jointly sufficient statistics?
My thoughts so far:
I wrote out a joint pdf for lognormal $X_i$'s. Then, I factored the pdf into two parts: one which contained $X_i$'s and the parameters and one which contained no parameters. As per my current understanding, this means that the statistics are jointly sufficient via the Neyman Factorization Theorem. Yet, here I am confused. How is it that two statistics can be jointly sufficient if I never introduced them into the equation? In other words, what step of my understanding am I overlooking?
Comment: You can use this along with the fact that $\log(X_1), \log(X_2), \ldots, \log(X_n)$ is a sample from a normal distribution to get the sufficient statistics for the log-normal.
Comment: Do you know a pair of sufficient statistics for a sample from a normal distribution?
Comment: Yeah, I think. sum(Xi) and sum((Xi)^2) are jointly sufficient for a sample from a normal distribution. What are you getting at?
Answer: Following up on the comment from @dsaxton, since you know that  $\log(X_1), \log(X_2), \ldots, \log(X_n)$ is a sample from a normal distribution, you can use knowledge of the sufficient statistics from for a normal to answer your question. Since the empirical mean and empirical variance are sufficient in that case, you get your sufficient statistics as
$$
\hat{\mu}=\frac1{n} \sum_1^n \log(x_i)
$$ and
$$
\frac1{n-1} \sum_1^n (\log(x_i) - \hat{\mu})^2
$$

Jointly Sufficient Statistic Question


Elementwise convergence of a seqence of matrices and implications for eigenvalues

Question: Let $A_n$ be a sequence of $d\times d$ symmetric matrices, let $A$ be a $d\times d$ symmetric positive definite matrix (matrix entries are assumed to be real numbers). Assume that each element of $A_n$ converges to the corresponding element of $A$ as $n\to \infty$. Can we conclude that for some $\epsilon>0$ there exists $N_\epsilon$ such that the smallest eigenvalue of $A_n$ is larger than $\epsilon$, for all $n \geq n_\epsilon$?
Comment: Does this answer your question? [Eigenvalues of matrix with entries that are continuous functions](https://math.stackexchange.com/questions/480619/eigenvalues-of-matrix-with-entries-that-are-continuous-functions)
Comment: Or maybe a better duplicate target: https://math.stackexchange.com/questions/1346866/are-eigenvalues-of-the-limit-of-a-sequence-of-matrices-limits-of-eigenvalue-sequ
Comment: @Eric Wofsey I think that the answer to the second question you've pointed out does reply to mine too, thanks. However, I quite like Yorch's answer (which is given from a "norm perspective").
Answer: Yes, since the coefficients of the characteristic polynomials of the $A_n$ converge to those of the char. polynomial of $A$, and the roots of a polynomial depend continuously on the coefficients.
Answer: Let $\lambda_1 \geq \dots \lambda_n$ be the eigenvalues. Any $e< \lambda_n$ works.
Suppose $\lambda < e$ is an eigenvalue of $A_n$, take an orthonormal basis of $A$, take a unitary eigenvector of $A_n$ for $\lambda$ and let the coordinates in the basis be $(a_1,\dots,a_n)$.
Note $A_nv = (\lambda a_1,\dots, \lambda a_n)$ and $Av = (\lambda_1a_1, \dots,\lambda_n a_n)$ so that the distance between the two vectors is $\sqrt{ \sum \limits_{i=1}^n (\lambda_i - \lambda)^2a_i^2 } \geq \lambda_n - \lambda$
By unicity of norms we have that $A_n$ converges to $A$ under the usual norm which is the supremum of the distances between $Av$ and $A_nv$ for $v$ in the unitary sphere. It follows that $A_n$ cannot have an eigenvalue less than $e$ for sufficiently large $n$.


Drupal navigation always returns a 404 error

Question: I have been given a Drupal site which I have to get it running.
I have Apache / Drupal / MySQL up and running, and created a new .conf file in Active Sites, and set the document location to /var/www/html/
I have edited my hosts file so that I have an entry for
127.0.0.1 samplesite.com

If I browse to samplesite.com/index.php I see the index of the site. So far so good. It is all styled, and as I see genuine content I must be hitting the database
Now no matter what link I click on on that page, I get a 404 error. (Looking in the log files its a 404 523 error if that has any bearing on it.)
I then found out the admin userid (using drush), reset the password, and cleared all caches. Still the 404 errors.
If I go to samplesite.com/user or samplesite.com/admin, I still get the 404 error, not an admin login page.
As this is an existing site, and works online, I am blaming something in my setup / configuration (being as the url on a failed link is similar to samplesite.com/about, I am assuming it is in the navigation configuration, but now I am stuck).
Is there an apache url rewriting module (or drupal one?) that needs some configuration? Or can anyone suggest something else I may have overlooked in apache / drupal configuration?
I now have the line $base-url = 'samplesite.com'; in my settings.php file, and none of the other urls work. However it accepts that I am logged in as admin as I have an additional admin menu at the top of the page. (none of the links work though)
Curiously, if I disable wifi, then the page doesn't load at all (I wouldn't have thought that wifi on or off would affect localhost)
Ok, My fix came when I followed this thread https://www.drupal.org/node/1572984
I needed to add in the following.
<Directory /var/www/html>
   RewriteEngine on
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

However I only got here because of the help I received along the way, I think this was just the missing piece.
Comment: Did you try the links without the clean urls?
Comment: No I haven't. As I can't see what the real urls are (I also see the clean urls on their live site), and can't access and of the admin areas to see what they should be. Are they stored in the database somewhere, so I can dig about and find them?
Comment: If you have admin access, try example.com?q=admin/config/search/clean-urls
Comment: I will try that, but it won't be until later I am afraid, not in front of that machine at the moment.
this wasn't a clean install of Drupal, but a copy of their live system. is there any chance that I need to edit some config files in case I am running under the wrong user (though then I'd expect a security error not a 404)
Comment: You only need to change your settings.php and then go to that link and disable clean urls for now.
Comment: ok, I'l post back later when I have tried that. all I have changed so far in settings.php is the database connection details
Comment: example.com?q=admin/config/search/clean-urls displays a page called Apache2 Ubuntu Default Page. Can't see anythign to turn smart links on / off
Comment: edited to update
Answer: Option 1 - RewriteRule and RewriteBase
Check if you can use an URL containing ?q=user or ?q=admin. Refer to my answer to the question "7.26 /admin, /user not found on Localhost" (which is about RewriteRule) for more details on that.
In that answer there is a link to the question about "drupal /?q=user is working but /user not working", for which the accepted answer of that question provides more details about tuning RewriteBase in your .htaccess.
Option 2 - Admin option 'Clean URLs'
I you can use the ?q=adminURL, then try to navigate to /index.php?q=admin/config/search/clean-urls to check the current status of clean urls (if it is enabled or disabled). Make sure "clean urls" is enabled.
Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Option 3 - base_url
Make sure the value of "base_url" is set correctly (in your settings.php).
Option 4 - .htaccess file
Verify if the .htaccess file is present in the directory where Drupal resides (and/or that it is not incomplete or corrupt). If it is missing, then upload it. If needed copy it again from the "Drupal" archive file (.zip or .tar) from Drupal.org again, and just use that new .htaccess file.

Note (about your "The ?q=admin URL didn't ask me to log in" comment to this answer) Check if you get the same problem using another browser. If with another browser it works, then that part might be a cookie problem (delete the cookie in the browser where you have the problem, and try again).
Comment: ?q=user will give me a login page. ?q=admin gives me a 403
I'll read the other link now
Comment: mysite.com/index.php?q=admin now takes me to an admin page, but any of the links from it go back to a 404
Comment: An incorrect RewriteBase in the main .htaccess can also cause non-front pages to break.
Comment: the ?q=admin url  didn't ask me to log in, which doesnt feel right to me, but I need to be able to access everything first, before I worry about why things aren't locled down
Comment: @rooby: thanks for the "support" ... I've tried to also make that a bit more clear, via the 2nd parg I added in my "option 1" part. Would you agree that's what you also mean?
Comment: Yep, that covers what I was referring to.
Comment: if I edit the base_url in /sites/default/settings.php to 'mysite.co.uk'; then any urls on the site are now mysite.co.uk/mysite.co.uk/index.php etc, so I must have the base-url correct.
My Rewrite_base in teh .htaccess was commented out. if I uncomment it and make it just '/' then I get no difference. My code is in the apache root at /var/www/html so I don't think I need to make changes there. Though I will download and try a new one just incase.
Answer: According to this link  and my experiences I Think it is because incorrect RewriteBase in .htaccess file, one and simple solution is  download raw drupal version from drupal.org (or if you has been downloaded it before) repalce .htacess file from it to your current root directory.


how to calculate percentage

Question: I need to calculate percentage in c# and bind it in xaml
in a list of item i need to %the active count by complete count
and bind it in a list called employee list if any one know please help me to figure it out
my calculation
<TextBlock
    x:Name="complainceValue"
    Grid.Column="6"
    Text="{Binding competencylevel}"
    FontSize="17"
    FontWeight="SemiBold"

  public String competencylevel { get; set; }

Comment: Provide a minimum code not post as a image
Comment: [Please do not upload images of code/errors](https://meta.stackoverflow.com/q/285551) but provide it as (properly formatted) text
Answer: To calculate a percentage in C# and bind it to an employee list in XAML, you can follow these steps:
First, define a class for an employee object that includes properties for the active count and complete count. For example:
public class Employee
{
    public int ActiveCount { get; set; }
    public int CompleteCount { get; set; }
}

Next, create a method that calculates the percentage based on the active and complete counts. This method should return a float value representing the percentage:
public float CalculatePercentage(Employee employee)
{
    return (float)employee.ActiveCount / employee.CompleteCount * 100;
}

Create a list of employee objects and populate it with data.
List<Employee> employees = new List<Employee>
{
    new Employee { ActiveCount = 10, CompleteCount = 20 },
    new Employee { ActiveCount = 5, CompleteCount = 10 },
    new Employee { ActiveCount = 3, CompleteCount = 6 }
};

In your XAML file, define a ListView or other control to display the employee list. Bind the ItemsSource property to the list of employees and define a DataTemplate to specify how each employee should be displayed.
<ListView ItemsSource="{Binding Employees}">
    <ListView.ItemTemplate>

This is the basic structure for calculating and displaying percentages for a list of employees in C# and XAML. To complete the implementation, you can add a TextBlock or other control to the DataTemplate to display the percentage value for each employee.

how to calculate percentage


How can i use Ajax request on multiple files?

Question: I have a JavaScript file called newsletter_init.js and it makes an Ajax request.
I add this JS file to every .php on my project and the issue here.
For example I use newsletter_init.js in my index.php and a URL for the ajax request will be res/ajax/request_newsletter.php.
Ok, that's working but when I add the same JS file on another directory for example adding newsletter_init.js on a index.php but placed on blog folder the URL will be invalid as it will search for ../res/ajax/request_newsletter.php instead of res/ajax/request_newsletter.php.
File structure about the scope:
index.php
blog > index.php

I have another way to do this:

Add content of newsletter_init.js on every file and change url but this is not a good way to approach this.

I have tried to use __DIR___ in PHP but i don't understand how to use it in this situation.

I have tried $(location).attr(pathname); in jQuery but it return the fild name also for example localhost/homepage/index

I can't use a direct url as i will change from localhost to my site so, i need a dynamic way.
Comment: Just use a domain-relative URL, starting with a slash.
Comment: @CBroe Can you give an example for relative url? I mean how can i use relative url on multiple files?
Answer: Just ensure your path is relative to the root directory.
/res/ajax/request_newsletter.php

Not:
res/ajax/request_newsletter.php

If you don't add the first slash, it will try to find that path starting in the directory where you are making the call (i.e. wherever your current PHP script is running).
Comment: Thank you so much, this made the whole project easier not just my problem