Given a linear operator $T:\mathbb R^3 \to \mathbb R^3$ with $(x_1,x_2,x_3) \mapsto (3x_1,x_1-x_2,2x_1+x_2+x_3)$. Show that $(T^2-I)(T-3I)=0$

Question: Given a linear operator $T:\mathbb R^3 \to \mathbb R^3$ with $(x_1,x_2,x_3) \mapsto (3x_1,x_1-x_2,2x_1+x_2+x_3)$.
Show that $$(T^2-I)(T-3I)=0$$

The linear operator $T$ is a function such that $$
\begin{bmatrix}
x_1  \\
x_2\\
x_3 \\
\end{bmatrix}
\quad
 \mapsto P\begin{bmatrix}
x_1  \\
x_2\\
x_3 \\
\end{bmatrix}
\quad$$
Where $$P=
\begin{bmatrix}
3& 0 & 0 \\
1 & -1 & 0\\
2 & 1 & 1\\
\end{bmatrix}
\quad
$$
Moreover $$T^2(x_1,x_2,x_3)=T(3x_1,x_1-x_2,2x_1+x_2+x_3)=(9x_1,2x_1+x_2,9x_1+x_3)$$
$$I(x_1,x_2,x_3)=(x_1,x_2,x_3)$$
$$T^2(x_1,x_2,x_3)-I(x_1,x_2,x_3)=(8x_1,2x_1,9x_1)$$
$$T(x_1,x_2,x_3)-3I(x_1,x_2,x_3)=(0,x_1-4x_2,2x_1+x_2-2x_3)$$
But I don't understand what does $(T^2-I)(T-3I)$ means and that's why I can't show the desired result,besides is the matrix $P$ helpful here?
Answer: The given $T$ has a triangular matrix. In this case the diagonal of $T$ shows the eigenvalues. It follows that $T$ can be diagonalized with the numbers $3$, $-1$, $1$ in the diagonal. Since the polynomial $p(z):=(z^2-1)(z-3)$ vanishes at these three places it follows that $p(T)=0$.
Answer: $(T-3I)(a,b,c)=(0,a-4b, 2a+b-2c)$. Call this vector $(x_1,x_2,x_3)$ and apply $T^{2}-I$ to it. From your computaion of $T^{2}-I$ is is clear that $(T^{2}-I)(T-3I) (a,b,c)=((8)(0), (2)(0),(9)(0))=0$. Since this is true for all $(a,b,c)$ we conclude that  $(T^{2}-I)(T-3I)=0$.
If you want to use $P$ you have to compute $P^{2}$ and $P^{3}$ and show that $(P^{2}-I)(P-3I)=P^{2}-3P^{2}-P+3I=0$ but that is a lengthy computation.


Multisite or multiple sites setup with Open ID server

Question: I am working on a project where I have a basic site with a sets of modules and configurations. Currently when I get a new client for this project in order for him/her to use their own site, I setup a subdomain, load a basic DB and copy the basic site files over.
This setup has work for me, but now I am having to deal with more clients and the manual process will just make it hard to manage and maintain. Ideally I will love to have it a single set of files will connect each user DB and I don't care if instead of subdomains (they are nicer) I have to use sub-directories.
What will be best for this setup multisite or multiple sites, and will it make sense to have a centralize account (open id) server?

Note: I was thinking in register the users in a single place and then they can login into their private sites using this centralize
  account system. Otherwise each site will have to have a user 1 account
  with a password to be manage for each site.

Thank you
Comment: Will each sub-site need it's own user base or just the client admin account?
Answer: I think multisite would work well if you're keeping all of the same code.  I know you can do it with subdomains (or even completely different domains) using the sites.php file, I'm not so sure about sub-directories.
Have a look at the Features module which will allow you to import all of your standard settings as a single module on new sites.
Comment: Thank you for your quick answer. I have been avoiding Features like the plague waiting for the file configuration system on D8 and/or Backdrop.
Comment: That's what I have right now a basic site with the modules and the DB configuration that I copy over the newly created subdomain. The question about Open ID is just to learn if it will make sense or not to use it with such setup.
Comment: I was thinking in register the users in a single place and then they can login into their private sites using this centralize account system. Otherwise each site will have to have a user 1 account with a password to be manage.
Comment: Best update your question with that, people might miss it in the comments =)
Comment: Good point. I just did that. Once again, thank you.
Answer: I use multisite to run about 50 Drupal sites from a single code base, but each site has its own database.
To be able to manage all the site, I use the Drupal Remote Dashboard Server module and its corresponding Drupal Remote Dashboard module. These modules let me out all the servers into maintenance mode, or run update.php.
Comment: Does each site has a user 1 plus any other user or do you use something like Open ID to have a centralize account directory? Do you have modules in one of the sites that you don't use in another?
Comment: Each site has its own User1 (me), but the Drupal Remote Dashboard Server module take care of logging you in to them all.

Each site has its own set of modules, installed into its /site/sitename.com/modules directory.
Comment: Do you share any tables between the site databases? Do you have the sites as sub domains or directories of the main site?
Comment: Each site has its own database, to ensure data integrity. Each site has its own full domain.


Finding all intermediate fields

Question: STATEMENT: Let $\alpha$ be the real positive fourth root of 2. Find all intermediate fields in the extension $\mathbb{Q}(\alpha)$ of $\mathbb{Q}$.
QUESTION: I basically used the tower law to show that $\mathbb{Q}(\alpha),\mathbb{Q}(\alpha^2),\mathbb{Q}$ are all intermediate fields by tower law, and $\mathbb{Q}(\alpha^3)=\mathbb{Q}(\alpha)$.  I am just not sure how to show that these are all of the intermediate fields. I would really appreciate a hint or suggestion.
Comment: Do you know that extensions of $\mathbb Q$ with the same degree are isomorphic by means of an isomorphism that fixes $\mathbb Q$?
Comment: No, I did not know. But with that fact I think I can show that there are only three intermediate fields. Thanks Git.
Comment: Any desired subfield must be of degree 2 over $\mathbb {Q} $ and contained in $\mathbb{R} $. And hence it must be of the form$\mathbb{Q} (\sqrt{a}) $ where $a>0,a\in\mathbb {Q}, \sqrt{a} \notin\mathbb {Q} $. Show that $\sqrt{a} \in\mathbb {Q} (\sqrt{2})$.
Answer: Here is an alternative argument that does not use Galois theory. Instead one can make use of the linear algebraic structure:
Observation 1: $\operatorname{irr}(\alpha,\Bbb{Q},X)=X^4-2$ is the irreducible polynomial of $\alpha$ over $\Bbb{Q}$, for example by Eisenstein's criterion. Thus if $F$ is an intermediate field of $\Bbb{Q}(\alpha)$ over $\Bbb{Q}$, i.e. if $F$ a field such that
$$\Bbb{Q}< F<\Bbb{Q}(\alpha),$$
then $4=\operatorname{deg}(\operatorname{irr}(\alpha,\Bbb{Q},X))=[\Bbb{Q}(\alpha):\Bbb{Q}]=[\Bbb{Q}(\alpha):F][F:\Bbb{Q}]$, so that
$$[\Bbb{Q}(\alpha):F]=2=[F:\Bbb{Q}].$$
Observation 2: Since $\Bbb{Q}<\Bbb{Q}(\alpha^2)<\Bbb{Q}(\alpha)$ and $\operatorname{irr}(\alpha^2,\Bbb{Q},X)=X^2-2$ is the irreducible polynomial of $\alpha^2$ over $\Bbb{Q}$, we have that $\Bbb{Q}(\alpha^2)$ is an intermediate field.
Observation 3: $\Bbb{Q}(\alpha)$ is a $4$-dimensional $\Bbb{Q}$-vector space with basis $\{1,\alpha,\alpha^2,\alpha^3\}$ and $\Bbb{Q}(\alpha^2)$ is a $2$-dimensional $\Bbb{Q}$-vector space with basis $\{1,\alpha^2\}$. Rearranging the (standard?) basis of $\Bbb{Q}(\alpha)$ so that it is subordinate to the filtration $\Bbb{Q}<\Bbb{Q}(\alpha^2)<\Bbb{Q}(\alpha)$, we have
\begin{align}
\Bbb{Q}(\alpha)=\Bbb{Q}\oplus \alpha\Bbb{Q} \oplus \alpha^2\Bbb{Q} \oplus \alpha^3\Bbb{Q}=\Bbb{Q}\oplus \alpha^2\Bbb{Q} \oplus \alpha\Bbb{Q} \oplus \alpha^3\Bbb{Q} = \Bbb{Q}(\alpha^2) \oplus \alpha\Bbb{Q} \oplus \alpha^3\Bbb{Q}.
\end{align}

Claim: $\Bbb{Q}(\alpha^2)$ is the only intermediate field.
Proof: Suppose there is another intermediate field $F$. Then $F\cap \Bbb{Q}(\alpha^2)=\Bbb{Q}$, and since $F$ is a $2$-dimensional $\Bbb{Q}$-subspace of $\Bbb{Q}(\alpha)$, $\exists a,b,c\in\Bbb{Q}$ not all $0$ such that
$$F=\Bbb{Q}\oplus (a\alpha+b\alpha^2+c\alpha^3)\Bbb{Q}.$$
Regarding the values of $a,b$ and $c$ there are exactly three possibilities:

$b=0$.
$b\neq0,$ WLOG $a=1$.
$b\neq0,$ WLOG $c=1$.

In the first case,
\begin{align}
F\ni &(a\alpha+c\alpha^3)^2=(4ac)+(a^2+2c^2)\alpha^2\in \Bbb{Q}\oplus \alpha^2\Bbb{Q}=\Bbb{Q}(\alpha^2)\\
&\implies (4ac)+(a^2+2c^2)\alpha^2\in F\cap\Bbb{Q}(\alpha^2)=\Bbb{Q}\\
&\implies (a^2+2c^2)=0 \stackrel{a,c\in\Bbb{Q}}{\implies} a=0=c,{\bf\large\unicode{x21af}}.
\end{align}
The other two cases follow similarly: In the second case we have
\begin{align}
F\ni &(\alpha+b\alpha^2+c\alpha^3)^2=(4c+2b^2)+(4bc)\alpha+(1+2c^2)\alpha^2
+(2b)\alpha^3\\
&\implies (4bc)\alpha+(1+2c^2)\alpha^2+(2b)\alpha^3 \in (\alpha+b\alpha^2+c\alpha^3)\Bbb{Q}\\
&\implies 2b=4bc^2 \stackrel{b\neq0}{\implies} c^2=\dfrac{1}{2}\stackrel{c\in\Bbb{Q}}{\implies} \sqrt{2}=\alpha^2\in\Bbb{Q},{\bf\large\unicode{x21af}};
\end{align}
and in the third case we have
\begin{align}
F\ni &(a\alpha+b\alpha^2+\alpha^3)^2=(4a+2b^2)+(2b)\alpha+(a^2+2)\alpha^2
+(2ab)\alpha^3\\
&\implies (2b)\alpha+(a^2+2)\alpha^2+(2ab)\alpha^3 \in (a\alpha+b\alpha^2+\alpha^3)\Bbb{Q}\\
&\implies 2b=2a^2b, a^2+2=2ab^2 \stackrel{b\neq0}{\implies} a^2=1,a=\dfrac{3}{2b^2}>0\\
&\implies a=1, b^2=\dfrac{3}{2}\implies \sqrt{\dfrac{3}{2}}=\vert b\vert\in\Bbb{Q},{\bf\large\unicode{x21af}}.
\end{align}
Hence the overlap of $F$ and $\Bbb{Q}(\alpha^2)$ can not be $1$-dimensional, $\checkmark$.

Note: For further reference this is Exercise V.6.4 from Lang's Algebra (p. 253 of 3e). Since this exercise is before the (official) Galois chapter in the book I believe an argument that does not (explicitly) use Galois theory is what was asked.
Answer: Are you familiar with the Galois Correspondence? Because you could compute the Galois group of the polynomial $x^4-2$ and write all its subgroups, and then by the correspondence you would obtain all the subfields between $\mathbb{Q}(\sqrt[4]{2},i)$ (the splitting field of the previous polynomial) and $\mathbb{Q}$: in particular one of the ramifications would be the subfields of $\mathbb{Q}\sqrt[4]{2}) \subset \mathbb{Q}(\sqrt[4]{2},i)$,
Comment: I'm not familiar with galois theory, but I can read up on it.

Finding all intermediate fields


google youtube data api v3 youtube.videos.insert 503 error

Question: youtube.videos.insert 503 error
yesterday I could upload video files.
but today I cannot upload video files via google api v3
Uploading file...
A retriable HTTP error 503 occurred:
<code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "backendError",
    "message": "Backend Error"
   }
  ],
  "code": 503,
  "message": "Backend Error"
 }
}
</code>
Answer: Sorry not really answering your question but it seems the '503' backend error is around at the moment. I'm having the same issue testing my iOS app using v3 objective-c YouTube API - I hit the same 503 error all the time, only 2-3 uploads out of 20 go through. Even the Google OS X sample app fails constantly. Definetely something in the backend... I've reported a bug to YouTube API a week ago.
Answer: 503 means there was a transient error in YouTube server backend. Now it's working for me. Please try again.


Fourier transformation of cosine

Question: I am trying to do the Fourier transformation of the expression $x(t) = 10 \cos(50\pi t)$; I have used the Euler representation to get as far as:
$$5\int_{-\infty}^{\infty}e^{-j50\pi t}e^{-j50\pi t}dt$$
Comment: Welcome to math.SE. Please avoid links. Proper formatting is expected; for information about writing math at this site see e.g.
[here](/help/notation),
[here](//meta.math.stackexchange.com/q/5020),
[here](//meta.stackexchange.com/a/70559) and
[here](//meta.math.stackexchange.com/q/1773).
Answer: Strictly speaking, this function does not have a Fourier transform. However, if we allow for more generalized functions, the following formula should get you to your answer:
$$
\mathcal F\left[e^{i\omega_0 t}\right] = \int_{-\infty}^\infty e^{i\omega_0t}e^{-i\omega t}dt = 2\pi\delta(\omega - \omega_0),
$$
where $\delta$ is the Dirac delta function.
EDIT: So let me go into more detail about the delta function. The delta function is defined such that $\int_{-\infty}^\infty\delta(x)dx = 1$ and $\delta(x) = 0$ for all $x\ne0$*. Most importantly, the delta function has the property that $\int_{-\infty}^\infty f(x)\delta(x-x_0)dx = f(x_0)$. It is this property that makes the above formula work. If you apply the inverse Fourier transform to $2\pi\delta(\omega - \omega_0)$, you'll see it recovers $e^{i\omega t}$.
*You might notice at this point that no function could have such properties, and you'd be right: the delta function is not a function. But it has many of the same properties of a function so we call it that anyways.
Comment: 2 remarks: I have typed your formula. 2) This transform is in every (even basic) table of Fourier Transforms, so your work is rather facilitated...
Comment: @JeanMarie So is the transform of cosine itself. Should I just post a link to a table as an answer?
Comment: I understand the function and what  the answer should look like the only problem is the delta function, what is that? and how would I substitute it into a real example?
Comment: @eyeballfrog I wrongly posted my comment below your answer. It was in fact uniquely addressed to the OP.
Comment: @AlexChris I have added some extra explanation.

Fourier transformation of cosine


What are the different types of cellos?

Question: When I was looking into buying a cello, I found that there seemed to be different classifications for cellos beyond size (1/2, 3/4, full, etc). For example, some cellos were being called "Stradivarius models," and there was a wide type with a darker timbre whose name I've forgotten- it had a wider body and didn't fit in my case. But the point is, what other models are there? How does the model affect the sound?
(edit for clarification: by model, I mean the shape of a cello, rather than any brand/production name.)
Answer: There are several well-known shapes of cello, based closely on the original designers' instruments.  This includes "Strad," "Cremonese," "MOntagna,"  "Guarnieri," and so on.  To a limited extent the shape will affect the tone - each has slightly different height-width-depth values, different bout shape.  Since the wood selected and the skill of the luthier are far more important overall (at least in my view),  I wouldn't make your choice purely on the design style.
Answer: First of all, you have to decide what size you want.  For example, if it is for a small child, then you might need a half size cello.  If it for an adult, then probably full size would be best.  At the lower end of the price scale, it will probably be made with cheaper materials (laminated wood), and have a painted black fingerboard, rather than using real mahogany.  Don't be fooled by seeing the word Stradivarius.  It is just a marketing ploy.  Don't get too bothered with model types or names.  It either feels right for you or it doesn't.
If you are willing to pay a few thousand, then you will get a good solid quality instrument likely made of spruce, mahogany and maple.  The best guide to finding the right sounding instrument is simply to try out as many as you can, and see what feels right and sounds right for you.  You could end up with a cheaper instrument that feels better for you than a more expensive one.  Trial and error.
Comment: You are wrong and not addressing the question.  "Strad" refers to a specific shape of instrument, roughly modeled after the original Strad cellos.  Same for several other popular shapes of cello.

What are the different types of cellos?


Windows service compartilhando informações com um Rest

Question: É possível um Windows Service trocar informações com um Web Service Rest? Se sim, isso é uma boa prática ou não? Por que a pergunta? É que preciso fazer o seguinte. Quando uma flag no banco é alterada de 0 para 1, deve disparar uma notificação para um App Android. A forma discutida aqui anteriormente é fazer um serviço, colocar um timer para que de tempo em tempo o WS escute essa alteração e dispare uma notificação.
Comment: É possível sim, você pode usar o HttpClient, [aqui](https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client) um exemplo. E é uma pratica completamente normal, na minha opinião.
Answer: É possível sim.
Primeiramente, instale esse NuGet no seu projeto Windows Service.
Após isso, basta fazer uso do System.Net.Http.HttpClient.
Segue abaixo um exemplo de como fazer a chamada de uma maneira bem simples. E também como verificar o status da resposta da sua chamada.
<code>HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://seu_endpoint_aqui/");

HttpResponseMessage response = client.GetAsync("api/allItems").Result;
if (response.IsSuccessStatusCode)
{
    var result = response.Content.ReadAsAsync<ImportResultDTO>().Result;
}
</code>


Is this a block Toeplitz matrix?

Question: What is the name of the following matrix?
$$\begin{pmatrix} a & b & 0 \\
c & d & 0 \\
0 & a & b\\
0& c& d& \\
b & 0 & a \\
d & 0 & c\end{pmatrix}$$
It looks like a Block Toeplitz matrix, but usually one defines those by full shifts by (in this case) $2 \times 2$ matrices. In particular, I'm interested in solving linear equations of this form. Any reference would be appreciated.
Comment: it doesn't just "look" like a block-Toeplitz matrix, it IS one! Simply define the two 2x1 blocks: [a;c] and [b;d]...
Comment: If $A$ denotes your matrix, I assume that you're looking for solutions to the matrix equation $Ax = y$.  Do you have any restrictions on the values of $a, b, c, d$ such that you are guaranteed a solution?  (In general, systems with six equations and only three unknowns are not likely to have a solution.)
Comment: You're definitely going to have to solve your problem the least-squares way (or in general ,minimize with respect to whatever other norm that you're using, but that's more complicated). At first glance I can't see how to modify QR or SVD to exploit your system's structure.
Answer: You could call it block circulant even, which is more restrictive than Toeplitz. A block matrix does not need every block to be the same size. As Laurent wrote above: Just consider the blocks to be $2 \times 1$ matrices instead of $2 \times 2$ and you will be fine.

Is this a block Toeplitz matrix?


How to change the format of Last seen: in author pane in advanced forum?

Question: I have installed Advanced forum and Author pane module. Now, I did found the option of date format for Joined:__________, But not able to find the date format for Last Seen:________, The Last seen option shown very granular details like, Last Seen: 1 min 20 sec ago, I just want like,
Last Seen: 1 min ago

Last Seen: 2 hr ago

Last Seen: 1 day ago

Last Seen: dd/mm/yyyy

Comment: You would have to create your own custom time ago using jQuery
Answer: Here's what you need to use:
function YOUR_THEME_preprocess_author_pane(&$variables) {
  // Get the number of seconds since last login.
  $time_since_last_login = REQUEST_TIME - $variables['account']->access;
  // Custom override of the "last_active" variable.
  //
  // This is just an example; add your rules here.
  if ($time_since_last_login < 120 * 60) {
    // Show 2hr ago for any interval within last 2 hours.
    $variables['last_active'] = t('2 hours ago');
  }
  else {
    $variables['last_active'] = format_date('short', $variables['account']->access);
  }
}

Just add your custom time formatting rules.
Comment: Well, as far as i understand, it will display, 2 hr ago, when last seen time is less then 2 hr. But that is not what I need, It should show 1min-60min, 1hr -24 year, onward--Date. Thanks though for answer, appreciated.
Comment: See [format_interval()](https://api.drupal.org/api/drupal/includes%21common.inc/function/format_interval/7) function; if you don't figure it out, I'll have a look in the morning :)


Assigning cores to VM in vSphere

Question: Complete vSphere newbie here...
Background:
So, I have a 12 core machine with 24 VMs on it. Currently, all the processing power is shared between these VMs equally.
The question:
Can I configure one VM to be given two CPU's worth processing no matter what's happening on the other machines?
My Research:
I tried two things in vSphere...

I set the reservation and limit on one VM to equal the same as two cores. To test if my objective was being reached, I measured the time it would take to gzip a file when other VMs were running nothing and when other VMs were running CPU intensive operations. I expected the time to gzip the file would be the same because this VM gets priority for some processing. Unfortunately, the time taken to gzip the file when other VMs were running something was significantly more than when other VMs were not running anything.
I tried setting the Hyperthreaded Core Sharing mode to Internal hoping that this would mean that my VM would get at least an entire core to itself. This did not work either.

Thanks in advance!
Answer: You can set that machine to have priority over the other machines by setting the shares higher. More info here.
Answer: CPU resource allocation works as followed:
1 virtual socket CPU = a normal share of 1000.
So when you give 2 vCPU, you will have a share of 2000 and that VM will have more priority regarding to the physical host processing than VM with only a share of 1000.
You can trick that configuration on any VM with editing their settings and defining a resource allocation (low, normal, high or even custom) in the Resource tab.

Low    will give you a share amount equals to  500 x nb vCPU.
Normal will give you a share amount equals to 1000 x nb vCPU.
High   will give you a share amount equals to 2000 x nb vCPU.
Custom will give you a share amount equals to what you have typed

It's better to avoid setting VM limitations for that kind of purpose.

Assigning cores to VM in vSphere


Finding all positive integer solutions to $(x!)(y!) = x!+y!+z!$

Question: The equation is $(x!)(y!) = x!+y!+z! $
where $x,y,z$ are natural numbers.
How to find out them all?
Comment: Another post about the same question: http://math.stackexchange.com/questions/1617225/find-all-triples-of-non-negative-integers-a-b-c-such-that-ab-abc
Answer: Here's a start. We may assume $x\le y$. The case $x=1$ is trivial. The case $x=2$ gives $y!=z!+2$, which obviously has no solution. So assume $x\ge3$. Then $x!+z!\ge5y!$, so $z!\ge4y!$, so $z\gt y$. Suppose there is a prime number $p$ with $x\lt p\le y$. Then $p$ divides $y!$ and $z!$ but not $x!$ so we get a contradiction from $x!=x!y!-y!-z!$. So we have shown that if $x\le y$ then there can't be a prime $p$ with $x\lt p\le y$.
Comment: I think let $p=3y!$ in your prove, all things are done. p is not necessary a prime.
Comment: I don't understand. It is not true that $3y!\le y$, and it is not true that $3y!$ divides $y!$.
Comment: Hi, Gerry. I think your argument gives the whole thing. I've seen arguments of this sort, using the $\mbox{ord}_p (n)$ I defined, in contest books.
Comment: Well, my argument (or Ross Millikan's) together with your not-the-least-bit-trivial contribution.
Comment: @WillJagy, I thought you and Gerry might want to take a look at a somewhat simpler solution I just posted (prompted by the posting of a duplicate, linked to in a comment below the OP here).
Answer: Without loss of generality, we can assume $x\le y$.  We can quickly rule out any solution with $x=1$ or $2$, since the equations
$$y!=1+y!+z!\quad\text{and}\quad 2y!=2+y!+z!$$
are easily seen to have no solutions in positive integers $y$ and $z$.
Now suppose we had a solution with $x\lt y$.  Then
$$x!={x!\over y!}+1+{z!\over y!}\implies{z!\over y!}=x!-1-{x!\over y!}\not\in\mathbb{N}$$
hence $z\lt y$ as well.  But that implies $x!\lt1+1+1=3$, which implies $x=1$ or $2$, which have already been ruled out.  Hence any solution must have $x=y\ge3$.
Now suppose we have a solution with $x=y\ge3$.  The equation can now be written as
$$x!-2={z!\over x!}$$
which implies $z\ge x$.  We can rule out $z=x$ since $x!$ cannot equal $3$, so we have
$$x!-2=(x+1)(x+2)\cdots(z-1)z$$
But $x\ge3$ implies $x!-2\equiv1$ mod $3$, and this implies the product $(x+1)(x+2)\cdots(z-1)z$ can only be $x+1$ (with $x\equiv0$ mod $3$) -- that is, any product of two or more consecutive numbers is either divisible by $3$ or leaves remainder $2$ mod $3$.  Thus any solution $(x,y,z)$ must be of the form $(x,x,x+1)$, satisfying the equation
$$(x!)^2=x!+x!+(x+1)!$$
which simplifies to
$$x!=x+3$$
which has $x=3$ as its only solution.  So $(x,y,z)=(3,3,4)$ is the only solution to $x!y!=x!+y!+z!$.
Comment: Got your comment. This is very nice. It helps to know that something is likely a contest type problem; I keep asking people for the source of their question, and getting little cooperation. Today I have this bit of joy: http://math.stackexchange.com/questions/1617264/all-elements-of-this-finite-abelian-group/1617373#comment3296976_1617373
Answer: There won't be very many as the factorials are very sparse.  I suspect you have already listed them all.  We can assume $x \le y$.  If $x!=1$ the RHS is at least $2$ greater than the left.  If $x!=2, y=z$ the RHS is $2$ greater than the left, but there are no factorials with a difference of $2$.  If $x! \ge 6$, divide both sides by $y!$.  The LHS is an integer while the RHS is not unless $x=y$.  Now you are looking for solutions to $(x!)^2=2(x!)+z!$
Comment: You might want to take a look at the solution I just posted (prompted by the posting of a duplicate, linked to in a comment below the OP here).
Answer: Gerry's argument shows, for $3 \leq x \leq y < z,$ that in fact $x=y.$ Otherwise, if we assume $y \geq x+1,$ there is some prime $p | (x+1),$ which might be $x+1$ itself or might be smaller. Suppose we define $\mbox{ord}_p (n)$ to be the largest exponent $k$ such that $p^k | n.$ We have   $\mbox{ord}_p (y!) \geq 1 + \mbox{ord}_p (x!), $ also  $\mbox{ord}_p (z!) \geq 1 + \mbox{ord}_p (x!).$ Indeed, we have a contradiction, since $ x! = x! y! - y! - z!,$ and everything on the right hand side is divisible by $p^{1 + \mbox{ord}_p (x!)}.$
Alright, so $$x=y.$$ We do, indeed, have the solution $x=3, y=3, z=4.$
If $x \geq 4,$ then $\mbox{ord}_2 (x!) \geq 3.$ From $x=y$ we have $ (x!)^2 = 2 x! + z!.$ Now,  $\mbox{ord}_2 (x!)^2 \geq 3 + \mbox{ord}_2 (x!),$ while
 $\mbox{ord}_2 2(x!) = 1 + \mbox{ord}_2 (x!).$ As a result,  $\mbox{ord}_2 (z!) = 1 + \mbox{ord}_2 (x!).$ We cannot have $ z \geq x + 4$ because then there would be two extra even numbers dividing $z!.$ So
$$ z \leq x + 3.$$
However, Stirling's formula shows that, for $x \geq 6, \; z > x + 3$ where we regard $z$ as a real number here. Indeed, for the next few integral $x,$ we get the real solutions $ (4,4,5.833), \; (5,5,7.504), \; (6,6,9.156), \; (7,7,10.814), \; (8,8,12.480), \; (9,9,14.154).$  Stirling's gives me
$$  z > \; 2 x \; \left(  1 - \frac{\log 2}{\log x} \right)   $$
The only solution in natural numbers is $(x=3, \; y=3, \;z=4)$
ADDED: the function I have been calling $\mbox{ord}_p (n)$ is called $v_p(n)$ in Problems from the Book
by Titu Andreescu and Gabriel Dospinescu, available at AOPS or XYZ
EDIT, December 8::This is sensible notation, as the function $v_p$ is the "$p$-adic valuation," see page 25, Definition 2.1.2, of $p$-adic Numbers by "Fernando Q. Gouvea," that being one of  the pen-names of Mariano Suárez-Alvarez. Mariano wanted to  include a letter "i" somewhere in the last name, have the full set, but was told that would seem inauthentic. P_ADIC_BOOK
Comment: Pushing the maximum on edits. $v_p$ is good notation in English, I am not sure what Hensel wrote. Also, 'i' for the full set of vowels. About Fernando and Mariano, see http://math.stackexchange.com/questions/73565/a-resource-for-learning-p-adic-numbers    and  http://math.stackexchange.com/questions/73832/metric-space-where-the-distance-between-arbitrary-points-is-a-constant
Answer: Observe that $x, y, z > 2$. Obviously, $y < z$. By symmetry, assume $x \leqslant y$. Then, we have $x \leqslant y < z$. Let $x = y$. Then, $$x! = 2 + z! / x!.$$ Let $k = z - x > 0$, so the last equality becomes $$x! = 2 + (x + 1) (x + 2) \cdots (x + k).$$ Since $x | x!$, we should have $x | k! + 2$. If $k \geqslant x$, then, we get $x | 2$, which is impossible. Hence $k < x$. This is only possible when $k = 1$, in which case we have $x | 3$. Hence, $x = 3$, therefore, $y = 3$ and $z = 4$.
Now suppose $x < y < z$. Let $\alpha$, $\beta$ and $\gamma$ be the largest powers of $2$ that divide $x!$, $y!$ and $z!$, respectively. Then, $$\alpha + \beta = \min (\alpha, \beta, \gamma)$$ by the original equation, since $x, y, z$ are distinct. But this is impossible since $\alpha, \beta, \gamma > 0$.
Hence, the only solution is $(x, y, z) = (3, 3, 4)$.


Screen shot of background view in iOS

Question: I want to take screenshot of a particular layer (not the one on top) of my iOS application. I am aware it is possible to do that using 'renderInContect' method of CALayer. But all sample code I found is to take screenshot of current screen (layer on top). If you have any idea on this topic, please share.
Thanks
Comment: means do you want to crop a perticuler area?
Comment: Nope. I want to take full screenshot a view which is not on front. Thanks guys for your quick response. I understood the concept.
Answer: There should be no difference whether your view is in the foreground or even not currently displayed. Use:
UIGraphicsBeginImageContextWithOptions(myBackgroundView.bounds.size, YES, 0.0);
[myBackgroundView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Keep in mind that UIGraphicsBeginImageContextWithOptions is only available from iOS 4.0 on, otherwise use UIGraphicsBeginImageContext.
Answer: Hide other views and controls at that time when you want to capture your view screen shot and after that also visible (Unhide) all controls or views which you hide before capture image
- (UIImage *)captureView {

  //hide controls if needed .. here hide another all view which you not want to display
    CGRect rect = [yourBackView bounds];

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [yourBackView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //visible controls if needed .. here visible another all view which you want to display
    return img;

}

Answer: UIGraphicsBeginImageContext(self.view.bounds.size); // You can put your view here.
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = [UIImagePNGRepresentation(image) retain];
UIImage *screenShot = [UIImage imageWithData:data];

Screen shot of background view in iOS


Over an algebraically closed field, is it possible to factor a symmetric invertible matrix $A$ as $X^T X$?

Question: I know that this result is true when the ground field is $\mathbb{C}$. (Though I don't remember why.) Does it also hold for algebraically closed fields? Can someone give me a hint as to why this is true?
Comment: This is apparently a consequence of [Takagi's factorization](http://en.wikipedia.org/wiki/Matrix_decomposition#Takagi.27s_factorization), and this is the first I'm hearing of it.  Neat stuff.
Comment: The reuse of $T$ is confusing. Do you mean to say that an arbitrary matrix $A$ can be written as $A = B^TB$?
Comment: Also, do you specifically mean the transpose as opposed to the conjugate transpose (AKA adjoint)?
Comment: @Omnomnomnom I'm pretty sure that it's just the transpose, since one only specifies that the original matrix $A$ is symmetric.
Comment: @Omnomnomnom This is used in the complex case on page 58 of Miranda's Riemann Surfaces and Algebraic Curves in order to prove that the smooth conics in $P^2$ are isomorphic to $P^1$. I want to prove this for conics in $P^2$ for some arbitrary (algebraically closed) field, so it was natural to ask about this extension. So for my purposes it would really need to be the transpose.
Answer: Your factorization is an immediate consequence of Takagi's factorization, which itself is a corollary of the following theorem:
From Horn and Johnson: (p. 203, first edition)

Let $A \in M_n$ be given.  There exists a unitary $U \in M_n$ and an upper triangular $\Delta$ such that $A = U\Delta U^T$ if and only if all the eigenvalues of $A \overline A$ are real and non-negative.  Under this condition, the main diagonal entries of $\Delta$ may be chosen to be non-negative.

It seems that the answer lies behind this theorem. The question is fundamentally whether it can be extended to handle $A \in M_n(\Bbb F)$ for arbitrary (algebraically closed fields) $\Bbb F$.
Comment: It looks like this might work; [Schur decomposition](http://math.stackexchange.com/a/245669/81360) does seem to extend nicely, along with the notion of an [inner product](http://math.stackexchange.com/questions/185403/do-there-exist-vector-spaces-over-a-finite-field-that-have-a-dot-product).


Como adicionar Diretório à variável Path do Windows durante a instalação?

Question: Desenvolvi uma aplicação do tipo Console em C# com o Visual Studio 2013 e queria que o instalador adicionasse o diretório da solução na variável Path do Windows, durante a instalação. Isso é possível? Qual o procedimento para realizar essa alteração no sistema?
Obs.: Não estou utilizando instaladores de terceiros, apenas o Visual Studio 2013. Notei que o 2010 já tem um gerador de Setup, porém o 2013 só tem o Publish.
Comment: Para que seria o uso disso?
Comment: A minha aplicação é do tipo _Console_.
Comment: O instalador é o do próprio VS ou de terceiros?
Comment: No caso o do VS. Na verdade estou estudando C# agora, e é o meu primeiro programa com o VS, não sei bem se estou procedendo da maneira correta, mas a princípio estou utilizando apenas o VS2013.
Answer: Para o instalador feito via "Inno Setup", poderia ser feito dessa maneira
adicionando a section [Registry].

Setting Environment Variables
Environment variables are stored as string values in the registry, so it is possible to manipulate them using the [Registry] section. System-wide environment variables are located at:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
User-specific environment variables are located at:
HKEY_CURRENT_USER\Environment

Referência: http://www.jrsoftware.org/isfaq.php#env
Comment: Pra mim criar um instalador com o _Inno Setup_ eu compilo meu código e crio o _setup_ com os arquivos compilados, ou ele compila?
Comment: Isso você compila seu código normalmente, ai no inno você adiciona os arquivos que você precisa, Readme, Licença e coisas afim. No inno setup é possivel até checar se tem framework instalado na maquina, e instalar caso seja necessario. Ele é bem simples olha ai: http://www.linhadecodigo.com.br/artigo/1244/criando-um-pacote-de-instalacao-com-o-inno-setup.aspx

@KaduAmaral
Answer: Você pode escrever um aplicativo que faça isso em C#:
Usando Environment.SetEnvironmentVariable:
var originalPath = Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable("PATH", "C:\\Minha\\Aplicacacao\\Console.exe;" + originalPath);

Só funciona se o aplicativo executar em modo elevado.
Se for gerar um .msi usando WiX Toolset, veja a parte de Environment.

EDIT
Aparentemente PATH é um caso especial de variável de ambiente. O recomendado é alterá-la através de modificações no registro do Windows:
string chave = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
string pathAntigo = (string)Registry.LocalMachine.CreateSubKey(chave).GetValue("Path", "", RegistryValueOptions.DoNotExpandEnvironmentNames);

Registry.LocalMachine.CreateSubKey(chave).SetValue("Path", pathAntigo + ";C:\\Minha\\Aplicacacao\\Console.exe;", RegistryValueKind.ExpandString);

Comment: Cigano, obrigado pela ajuda, mas eu vou responder à pergunta com os passos que eu fiz até chegar na parte que você me ajudou, pois está incompleta a resposta, considerando o escopo "durante a instalação" da pergunta.
Comment: Esse modo elevado é como quando o programa é executado em modo de administrador? Esse aplicativo deveria estar junto com minha solução?
Comment: @KaduAmaral Isso mesmo. Se você vai fazer por instalador, é melhor usar o método do instalador, que já faz tudo pra você. A ideia era mostrar que é possível alterar as variáveis de ambiente usando C# também.
Comment: O instalador do VS permite que quando a instalação da solução seja terminada esse "configurador" seja executado (e em modo elevado)? Se sim teria como adicionar os passos pra isso na sua resposta? :)
Comment: Eu reparei que no Visual Studio, em `New > Project > Other Projects Types > Setup and Deployment` possui um tipo "Enable InstallShield Limited Edition" seria possível fazer com ele?
Comment: Acho que sim: http://helpnet.installshield.com/installshield18helplib/IHelpISXSetEnvVariable.htm
Comment: Opa Cigano, eu utilizei desta forma, até criei um arquivo de log, ele adiciona tudo certinho, porém quando eu vou nas propriedades do computador e vou nas variáveis de ambiente, não está a alteração, nem na do sistema nem na do usuário...
Comment: @KaduAmaral Não sei exatamente o que pode ser. Coloquei uma solução alternativa.
Comment: Descobri, eu adicionei o terceiro parâmetro `EnvironmentVariableTarget.Machine` e funcionou... :)
Comment: Cigano pode me dar uma ajuda [nessa pergunta](http://pt.stackoverflow.com/posts/comments/135360?noredirect=1)?
Answer: O visual-studio-2013 não possui um gerador de Setup (Apenas o Publish), conforme tinha o visual-studio-2010. Por isso eu utilizei a extensão Installer Projects.
Após a instalação da extensão, adicionei ao meu projeto um projeto Setup Project localizado em Other Project Types > Visual Studio Installer (opção criada pela extensão).
Adicionei uma nova Classe ao meu projeto chamada InstallerActions.cs:
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;

namespace GiTp
{
    [RunInstaller(true)]
    public partial class InstallerActions : System.Configuration.Install.Installer
    {

        public override void Install(IDictionary savedState)
        {
            base.Install(savedState);
        }

        public override void Rollback(IDictionary savedState)
        {
            base.Rollback(savedState);
        }

        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);

            if (this.Context.Parameters["cpath"] == "1")
                AddPath(this.Context.Parameters["targ"]);
        }

        public override void Uninstall(IDictionary savedState)
        {
            Process application = null;
            foreach (var process in Process.GetProcesses())
            {
                if (!process.ProcessName.ToLower().Contains("gitp")) continue;
                application = process;
                break;
            }

            if (application != null && application.Responding)
                application.Kill();

            RemovePath(this.Context.Parameters["targ"]);

            base.Uninstall(savedState);
        }

        private void AddPath(String path)
        {
            var originalPath = Environment.GetEnvironmentVariable("PATH").TrimEnd(';');
            Environment.SetEnvironmentVariable("PATH", originalPath + ';' + path.TrimEnd('\\'), EnvironmentVariableTarget.Machine);
        }

        private void RemovePath(String path)
        {
            var originalPath = Environment.GetEnvironmentVariable("PATH").TrimEnd(';');

            List<string> paths = new List<string>(originalPath.Split(';'));

            foreach (string p in paths)
            {
                if (String.Compare(p, path, true) == 0)
                {
                    paths.Remove(p);
                    break;
                }

            }

            Environment.SetEnvironmentVariable("PATH", String.Join(";", paths) );
        }
    }
}

O método AddPath(String path) realiza o registro da variável PATH e é chamado no método Commit, que é executado após a instalação do programa.
Os parâmetros this.Context.Parameters["cpath"] e this.Context.Parameters["targ"] são informados na propriedade CustomActionData do Custom Event da extensão, conforme ilustração:

Valor da propriedade: /targ="[TARGETDIR]\" /cpath=[CHECKPATH].
Obs.: A propriedade CHECKPATH é um checkbox de uma tela customizada do Setup.
O método RemovePath(String path) remove o registro da variável PATH e é chamado no método Uninstall, que será executado na desinstalação do programa.
Obs.: A configuração da propriedade CustomActionData é a mesma do Commit, exceto que não é necessário o envio da propriedade CHECKPATH.

Fontes

Creating an MSI/Setup Package for C# Windows Application Using a Visual Studio 2010 Setup Project EN
Resposta do @CiganoMorrisonMendez


Using Boto3 to create loop on specific folder

Question: I am testing the new data feeds as in XML. Those data will be stored in S3 in the following format:
2018\1\2\1.xml
2018\1\3\1.xml
2018\1\3\2.xml
etc.  So, multiple .xml files are possible on one day.  Also, important to note that there are folders in this bucket that I do NOT want to pull.  So I have to target a very specific directory.
There is no date time stamp within the file, so I need to use created, modified, something to go off of.  To do this I think of using a dictionary of key, values with folder+xml file as the key, created/modified timestamp as the value. Then, use that dict to essentially re-pull all the objects.
Here's what I've tried..
i
mport boto3
from pprint import pprint

client = boto3.client('s3')
paginator = client.get_paginator('list_objects_v2')
result = paginator.paginate(
    Bucket='bucket',
    Prefix='folder/folder1/folder2')

bucket_object_list = []
for page in result:
    pprint(page)
    if "Contents" in page:
        for key in page[ "Contents" ]:
            keyString = key[ "Key" ]
            pprint(keyString)
            bucket_object_list.append(keyString)

s3 = boto3.resource('s3')
obj = s3.Object('bucket','bucket_object_list')
obj.get()["Contents"].read().decode('utf-8')

pprint(obj.get())
sys.exit()

This is throwing an error from the key within the obj = s3.Object('cluster','key') line.
Traceback (most recent call last):
  File "s3test2.py", line 25, in <module>
    obj = s3.Object('cluster', key)
NameError: name 'key' is not defined

The Maxitems is purely for testing purposes although it's interesting since this translates to 1000 when run.
Comment: First, s3 is not a "file system", the "folder name" is arbitrary and is part of the object key.  It is using "prefix" filter to select similar arbitrary "folder name".  Second, you can store some meta information inside s3 object "meta".
Lastly,  always copy the exception error (even from your code somebody may already know the coding mistake))
Comment: When you do this `obj = s3.Object('cluster', key)`, do you have a bucket call "cluster" ? And where is your key derived from ?
Comment: I get that it's not a file system but AWS docs state you should be able to use the prefixes in order to get to the "folders" you want keys for.

No bucket is named cluster, I was just using arbitrary names and for some reason didn't use the "ABucket" name form farther up.

My intentions on the second part of the code was to pull the exact keys the paginator was grabbing.  I could be completely off-base here, I'm a SaS.

I added the error.
Answer: NameError: name 'key' is not defined

As far as error is concerned, it's because key is not defined.
From this documentation:

Object(bucket_name, key)
Creates a Object resource.:
object = s3.Object('bucket_name','key')
Parameters
bucket_name(string) -- The Object's bucket_name identifier. This must be set.
key(string) -- The Object's key identifier. This must be set.

You need to assign an object key name to the 'key' you're using in the code
The keyName is the "name" (=unique identifier) by which your file will be stored in the S3 bucket
Code based on what you posted:
import boto3

client = boto3.client('s3')
paginator = client.get_paginator('list_objects_v2')
result = paginator.paginate( Bucket='bucket_name', Prefix='folder/folder1/folder2')
bucket_object_list = []
for page in result:
    if "Contents" in page:
        for key in page[ "Contents" ]:
            keyString = key[ "Key" ]
            print(keyString)
            bucket_object_list.append(keyString)

print bucket_object_list

s3 = boto3.resource('s3')
for file_name in bucket_object_list:
    obj = s3.Object('bucket_name',file_name)
    print(obj.get())
    print(obj.get()["Body"].read().decode('utf-8'))

Comment: Yeah I just set a bucket_object_list =[] at the top of the loop that I want to fill with the keys.

I think my larger issue I'm seeing is when I run the Paginator, I'm not seeing any contents, etc.  It's almost as if it's grabbing no keys(even though I know objects exist).  I updated the code above.
Comment: Got it.   Got some new errors but I think that's more to do with special characters in my objects rather than code
Comment: Yes, this code works with bucket and files I've without any errors. Refer [this](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html#object-key-guidelines) to debug the error you mentioned


Verifying if a given polynomial is primitive polynomial

Question: Given a polynomial:  $f(x) = x^2 + 2x + 2$ over $GF(3)$. I want to know if i can use it to construct $GF(3^2)$.
My approach:

This equation satisfies first condition: A primitive polynomial is irreducible.
The second condition i'm trying to confirm is that i can use it generate $GF(3^2)$.

$\alpha^2 + 2\alpha + 2 \rightarrow \alpha^2 = \alpha + 1$.

$\alpha^1 = \alpha$

$\alpha^2 = \alpha+1$

$\alpha^3 = \alpha*\alpha^2 \rightarrow1 + 2\alpha $

$\alpha^4 = 2 $

$\alpha^5 = 2\alpha$

$\alpha^6 = \alpha+2$

$\alpha^7 = 1$
Now Here $\alpha^8$ should be equal to $1$ instead of $\alpha^7 .$

$\alpha^8 = \alpha$

What i am doing wrong , any help would be great.
Comment: You simply skipped $\alpha^6$. You correctly found out that $\alpha^4=2=-1$ is in the prime field. From this it follows that for all $i$ we have $\alpha^{4+i}=-\alpha^i$ (or $=2\alpha^i$ if you prefer that). So you should have $\alpha^6=2\alpha^2=2\alpha+2$, and only $\alpha^7=2\alpha^3=\alpha+2$. Undoubtedly you multiplied by $\alpha$ twice at that point, and forgot to record the result. Anyway, once you get back to the prime field you can use that to check the rest as above.
Comment: You made an error at $\alpha^6$.  See my answer.  Cheers!
Answer: It strikes me that our OP Khan Saab's calculations of the powers of $\alpha$ are OK through $\alpha^5$, but there is an error in $\alpha^6$.  With
$\alpha^2 = \alpha + 1, \tag 1$
we have, correctly,
$\alpha^5 = 2 \alpha; \tag 2$
then
$\alpha^6 = 2 \alpha^2 = 2 \alpha + 2, \tag 3$
not $\alpha^6 = \alpha + 2$!
Continuing:
$\alpha^7 = 2\alpha^2 + 2\alpha = 2(\alpha + 1) + 2\alpha = \alpha + 2; \tag 4$
$\alpha^8 = \alpha^2 + 2\alpha = \alpha + 1  + 2\alpha = 1! \tag 5$
easy, you know the way it's supposed to be!


Openfiler AD integration and controlled access

Question: I integrated Openfiler with an Active Directory.
I configured a SMB/CIFS share as Controlled Access and set domain admins = PG and domain users = RO. This should give domain users readonly access to the share.
When I open a share from a Vista machine on the domain everything works.
When I try to open the share from a Vista machine that is not on the domain I get the login prompt as expected, but no matter what I enter, I get a message

\192.168.1.51\raided.main.iso is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions.
Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.

When I configure the share as Public guest access it works both ways. Both of these machines are on the same network.
What gives?
Answer: I have resolved the issue, though understanding is still lacking.
It turns out that if you access the SMB share through the NETBIOS name entered in Openfiler's SMB / CIFS Setup screen, Vista is happy.
Doing the same using the IP address does not work.
Most perplexingly, I have a Windows Server 2003 machine (not on the domain) that behaves the other way around, i.e. access is only allowed through the IP address and not through the NETBIOS name.
Answer: From my experience (also mixed environment of Vistas Business and Basic connecting to OpenFiler 2.3) - when the username and password of a user logged in to the Windows not connected to Active Directory is the same as the user included in Active Directory it simply works.
So just create the user in Active Directory, log in to "that" user to the computer not connected to AD and it will just work.
Warning: it sometimes takes time for OpenFiler to read new users and groups from AD. When you add the user to AD first check in OpenFiler's panel if it is synchronized.
Comment: We're doing R&D on a domain completely isolated and secured from the company domain. Project members have their computers added to the company domain yet needs to access our private domain with separate credentials.
Comment: That's a good idea but for the fact that I integrated with AD for the easy maintenance. I can just as well maintain the roaming users in the local Openfiler LDAP server.
Comment: How many computers not connected to domain do you have? In my case it's minority of them, so it's ok to manage their logins and passwords by hand in AD. Also managing users and groups in Active Directory is simply more comfortable and powerful.


Determinant with one parameter, how to deal with this?

Question:
Let $t\in \mathbb R$ be a parameter, and
  $$|A(t)|=
\begin{vmatrix}
a_{11}+t &a_{12}+t &\cdots &a_{1n}+t\\
a_{21}+t &a_{22}+t &\cdots &a_{2n}+t\\
\vdots   &\vdots   &       &\vdots\\
a_{n1}+t &a_{n2}+t &\cdots &a_{nn}+t
\end{vmatrix}
$$
  Prove:
  $$|A(t)|=|A(0)|+\sum_{i,j=1}^{n}A_{ij}$$
  where $A_{ij}$ denotes the cofactor of $a_{ij}$ within $|A(0)|$.

My attempt:
I have tried the two following ways, but both don't seem to work:
1).Induction. The hypothesis is that it holds for $A_k(t)$ of the size $k\times k$ and I am to show it also holds for $A_{k+1}(t)$. I tried expanding $A_{k+1}(t)$ by the first row or column, but the result was too complicated to deal with, although I did obtain a $|A_{k+1}(0)|$ from it.
2).Another thread was to use
$$|A_{k+1}(t)|=
\begin{vmatrix}
1 &t  &t &\cdots&t \\
0 &a_{11}+t &a_{12}+t &\cdots &a_{1,k+1}+t\\
0 &a_{21}+t &a_{22}+t &\cdots &a_{2,k+1}+t\\
\vdots &\vdots   &\vdots   &       &\vdots\\
0 &a_{k+1,1}+t &a_{k+1,2}+t &\cdots &a_{k+1,k+1}+t
\end{vmatrix}
$$
and then substracted the first row from out all the others, I obtained
$$|A_{k+1}(t)|=
\begin{vmatrix}
1 &t  &t &\cdots&t \\
-1 &a_{11} &a_{12} &\cdots &a_{1,k+1}\\
-1 &a_{21} &a_{22} &\cdots &a_{2,k+1}\\
\vdots &\vdots   &\vdots   &       &\vdots\\
-1 &a_{k+1,1} &a_{k+1,2} &\cdots &a_{k+1,k+1}
\end{vmatrix}$$
Then I thought I should proceed to expanding the first row or column, in both cases I also obtained a $|A_{k+1}(0)|$, but the rest was just a terrible mess.
I expect that maybe I need some extra tricks to deal with the second term of RHS, i.e., the sum of all the cofactors of $a_{ij}$. I know the Laplace expansion, but it doesn't seem to suit this case. Could you help me? Best regards.
Answer: Let $v$ be the vector with $1$ on each coordinate. Let $A_i$ be column vectors of $A$. Then :
$$det(A)=det(A_1+tv,A_2+tv,...,A_n+tv)$$
Let us set $B_k^0:=A_k$ and $B_k^1:=v$ then expanding $det(A)$ by multilinearity :
$$det(A)=\sum_{i=0}^n\sum_{E\in\mathcal{P}_i(\{1,...,n\})}t^k.det((B_k^{\chi_E(k)})_{1\leq k\leq n}) $$
But if $i\geq 2$ and $E\in \mathcal{P}_i(\{1,...,n\})$ then for at least two $k$ we have that $B_k^{\chi_E(k)}=v$ then in that case :
$$det((B_k^{\chi_E(k)})_{1\leq k\leq n})=0$$
This means that :
$$det(A)=t^0det(A_1,...,A_n)+t\sum_{r=1}^ndet(A_1,...,A_{r-1},v,A_{r+1},...,A_n)$$
Now (expanding the determinant with respect to the $r$-th column) :
$$det(A_1,...,A_{r-1},v,A_{r+1},...,A_n)=\sum_{j=1}^nA_{j,r}$$
$$det(A)=det(A(0))+t\sum_{r=1}^n\sum_{j=1}^nA_{j,r}$$
Comment: Thanks. But I don't quite know what property  "expanding by multi-linearity " comes from.
Comment: And what does $\chi_E(k)$ denote?
Comment: Yes, it is not as clear as it should be. Do it for $n=3$ : $det(A_1+tv,A_2+tv,A_3+tv)=det(A_1,A_2,A_3)+t(det(v,A_2,A_3)+det(A_1,v,A_3)+det(A_1,A_2,v))+t^2(det(A_1,v,v)+det(v,A_2,v)+det(v,v,A_3))+t^3det(v,v,v)$ then all terms with at least two $v's$ vanish.
Comment: $\chi_E(k)=1$ if $k\in E$ and $0$ if $k\notin E$.
Comment: thanks. Now I seem to follow what you said.
Comment: By the way, does Pi denote permutation or combination?


JS shorthand If doing more than one operations

Question:
a==b? do 'x' : do 'y' ;

works fine
how would you write to do two things for example?
> a==b? do 'x' and do 'z' : do y ;

Comment: I agree with @AlexK.. Leave the shorthand to the code compressors. Write code to be comprehensible.
Comment: The `?` is not a shorthand if statement (well, it is sort of but...) it should be used as an expression i.e. `a = b ? c : d` instead of something like `b ? c() : d();`...
Comment: Shorthand is not always Betterhand.
Comment: This shorthand is called the ternary operator. See the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
Answer: A comma sounds like what you're looking for.
(a == b) ? (x, z) : y

x and z can be variables, in which case their values will just be returned by that expression, or they can be actual operations, and in this case too they'll be evaluated, i.e. executed.
So, if you do:
(true == true) ? (alert('Hey'), alert('there')) : alert('Aw...')

It'll show 2 alerts, the first showing "Hey", and the second - "there".
Also, it doesn't sound like this is very important to you, but it should be noted that the second expression's value (whatever is returned by executing y) will be returned as the result of the complete expression.
Comment: @AndersonGreen: I'm sure he's following the pseudo code given in the question, where `x`, `y` and `z` are replaced with the desired expressions. Either way, reading variables is an operation too.
Comment: `x` and `z` are variables, not operations. This question is asking how to do one or more operations.


Google Maps Marker click event that pulls a line from txt file in Android Studio (Kotlin)

Question: I am currently working on an Android project using Google Maps. I have functionality that allows them to click a marker when they are nearby and it will remove that marker and move it somewhere else nearby. However, I also want them to "collect" something when the marker is clicked. That something is a random line from a txt file that I have stored in my assets folder, but I can't figure out:
1) How to parse that file in the first place
2) How to grab a random line from that file and store it somewhere else when the marker is clicked
Any direction would be greatly appreciated.
Answer: Let me give you another way to do so.
You have a marker, add some information to it. For example, a snippet. And after marker is clicked you store that.
If you want get some info from assets you should initilize random array onMapReady() and do some staff with it.


GEE logit / Poisson versus mixed effects Poisson / logit

Question: There's a way to do Poisson or logit mixed effects and Poisson or logit GEE in R.  What's the difference between GEE and the mixed effects models for Poisson / logistic regression? I heard its the difference between estimating the population level numbers and the individual numbers (public health versus individual patient treatment), that is:

GEE is like what if we gave everyone the treatment in the population including the non-sick, and
mixed effects is like what if we gave individuals (sick and non-sick) the treatment.

Is that right?
(I'm sure lme4, geeglm, glmm has a way to do these.)
I heard GEE is a robust estimator that guards against covariance pattern misspecification, but mixed effects is better for missing data.  Can someone explain that?
Comment: Related: [Difference between generalized linear models & generalized linear mixed models](https://stats.stackexchange.com/q/32419/7290); [What is the difference between generalized estimating equations and GLMM](http://stats.stackexchange.com/questions/17331/); [When to use generalized estimating equations vs. mixed effects models?](http://stats.stackexchange.com/questions/16390/)
Answer: When you have a random intercept, it's like have an exchangeable correlation structure, and when you have random intercepts and slopes, it's like having an AR-1 correlation structure... assuming the random effects are simple rather than cross-nested. These covariance matrices actually cover a few cases that random effects do not. Syntactically they're often specified in a very similar way, which can be misleading.
You will recall that for linear models with identity link, the interpretation of effects for GEE and mixed models is that GEE estimates "population averaged" effects and mixed models estimates "individual level" effects. This convention borrows over to non-identity links such as binomial and Poisson models. The GEE estimates marginal effects, interpreted as
"population averaged" whereas the mixed model estimates "individual effects". Dovetail this with the proper interpretation of effect for logit and poisson models, and the only remaining challenge is actually specifying and fitting these models.
As an example, suppose I was interested in the rate of asthma exacerbations before and after enacting a public policy to reduce air pollution. Suppose this policy is just unbelievably effective: I close all industry and force people to buy electric cars. An inadvertent effect is that severe asthmatics actually move to my city seeking better quality of life. Now I have data on hospitalizations for asthma attacks over time. In my GEE model I say asthma hospitalizations go UP after enacting this policy. In my mixed model, I say asthma hospitalizations go DOWN after enacting this policy. They are both right, it's just that I did not have quite as many severe asthmatics living in my city before cleaning the air. The mixed model is useful because I can predict that those who moved to my city had far worse asthma exacerbations before I ever observed them. The GEE is useful because I know my hospitals will actually have more patients in them seeking treatment for asthma.
Example (in R!)
library(geepack)
library(lme4)
set.seed(1234)

n <- 5000
id.wide <- 1:n
year <- 2000:2010
post <- year > 2007
bl.sev <- sample(0:2, n, prob = c(0.5, 0.25, 0.25), replace=T) ## baseline severity
id.mig <- id.wide > n*0.65 ## the last 30% migrate in
minid.mid <- min(id.wide[id.mig])
bl.sev[id.mig]  <- 2 ## all migrants are severe

id.long <- rep(1:n, each=length(year))
year.long <- rep(year, n)

ae.int <- -4 + c(0, 1.2, 5.3)[bl.sev[id.long]+1] + ## intensity of asthma exacerbation
  -0.1 * (year.long > 2007)

# ae.int <- -4 + c(0, 1.2, 5.3)[bl.sev[id.long]+1]  ## intensity of asthma exacerbation
# ae.int <-  -1 * (year.long > 2007) + 1*(bl.sev[id.long]==2)  ## with an interaction effect (improves mild/moderate only)

ae <- rpois(length(id.long), exp(ae.int))

ae[id.long > minid.mid & year.long <= 2007] <- NA ## drop AEs from severe asthmatics during pre period

post.long <- year.long > 2007

glm(ae ~ post.long, family=poisson)
geefit <- geeglm(ae ~ post.long, id=id.long, family=poisson, corstr = "exchangeable")
mefit <- glmer(ae ~ post.long + (1|id.long), family=poisson)

summary(geefit)
summary(mefit)

The essential parts of the output are:
From the GEE
 Coefficients:
              Estimate Std.err    Wald Pr(>|W|)
(Intercept)    0.54562 0.01561 1221.25   <2e-16 ***
post.longTRUE  0.00304 0.00670    0.21     0.65

From the mixed effects model:
Fixed effects:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)    -1.2041     0.0441  -27.28  < 2e-16 ***
post.longTRUE  -0.0411     0.0123   -3.35  0.00082 ***

Which shows effects of the desired opposite direction. Getting "significant" results is just a matter of ramping up sample size.
Comment: @AdamO: Dimitris makes a valid point, which warrants revisiting your currently misleading statement that "there is no difference between GEE and mixed effects for models for binary or count data (logit / poisson).".  If you leave that statement as it is right now, you risk confusing people who will read your answer, especially since the answer was accepted as the "correct answer".
Comment: In Poisson mixed effects model with *only* random intercepts the fixed effects coefficients for the covariates have a marginal interpretation the same as in a GEE - only the intercept has a different interpretation.
Comment: @IsabellaGhement thanks. you reveal how confusing the statement was because the point was about interpretation of effects, and a third point entirely to Dimitris earlier remark. Please see edit.
Comment: Are you saying given the SAME dataset, GEE says hospitalizations go UP and Mixed Effects says hospitalizations go DOWN? What about the p-values? Are the p-values consistent regardless of estimation method?
Comment: @Germania yes, it's ecological fallacy played out in real time. And yes, the p-values are significant provided you have enough data.
Comment: What if you added a variable into the regression that controls for the confounding effect of migration? Would that make the GEE and Mixed Effects output coefficients have the same sign?
Comment: @Germania What I'm trying to emphasize here is that both models are "right" but they answer different questions, as noted in the interpretation of the findings. As you adjust variables, you shift focus on the questions. Adjusting for migration, or baseline severity, shifts focus to finding individual level effects.
Comment: @DimitrisRizopoulos in my example, I invoke missingness or imbalanced design (equivalently) to lead to different estimates between the two models, as would be found in a linear model as well. You are correct, that the log-link is collapsible and provided there is no missingness, the estimates should be consistent for the same thing. We agree logistic models are a different story due to lack of collapsibility of the odds ratio.
Answer: A couple of points:

When you use the identity link function both the GEE and a (linear) mixed model give you coefficients that have a population/marginal interpretation.
In all other cases where you use a nonlinear link function, such as the logit or the log, there is a difference in the interpretation of the coefficients. Namely, GEEs provide coefficients with a population/marginal interpretation whereas mixed models provide coefficients with a subject-specific interpretation.
The population/marginal interpretation refers to groups of subjects. For example, in the case of a dichotomous outcome and the logit link the GEE will give you a coefficient for the sex variable you that is the log odds ratio between the groups of males versus females.
The subject-specific interpretation on the other hand is at the subject level. Continuing on the previous example, the coefficient for sex from a mixed effects logistic regression would be the log odds ratio if a specific subject changed sex.
It is possible to obtain coefficients with a population/marginal interpretation from mixed models. For example, in the GLMMadaptive package I've written, check function marginal_coefs() illustrated here.
Mixed models provide valid inferences under the missing at random missing data mechanism, whereas the basic version of GEEs only under the more restrictive missing completely at random mechanism.
The sandwich estimator in GEEs better protects against a misspecification of the working correlation structure in restrictive settings, i.e., when you have a balanced design, with few categorical covariates, and many subjects.
Comment: @Germania my public repositories are here: https://github.com/drizopoulos


If $p$ is a prime number of the form $p=8k+3$ show that $2^s\equiv 1,s=(p-1)/2$ is not possible or find a counterexample

Question: Let $p$ be a prime number of the form $p=8k+3$ and $s=(p-1)/2$. Either prove that $2^s\equiv 1$  (mod $p$) is not possible or find a counterexample. I have checked primes under $10^6$ an couldn't find a counterexample.
Answer: A prime of the form $p=8k+3$ does not have $2$ as a quadratic residue (only the
 primes of the form $8k-1$ and $8k+1$ have). By Euler's criterion, it follows
$$2^{\frac{p-1}{2}}\ \equiv\  -1\ (\ mod\  p\ )$$
Comment: Then perhaps $2^{\frac{p-1}{2}}\equiv -1 $ (mod $p$) could be used  as a test for primality for those primes because the smallest pseudoprime I came up with is $476971$. Interestingly this is not a Carmichael number.
Comment: Indeed. The test if $2^{p-1}\equiv 1\ (\ mod\ p\ )$ is based on Fermat's little theorem, and there are several refinements of this test.


Different compilers, different output?

Question: I have a bit of c code that I've been working on in Xcode on my mac. I then wanted to work with it on a Windows machine and compile it with TinyC. When I run it, the output is different.
Is it possible that this is due to using different compilers?
Thanks!

EDIT 1
The code is a simple script that opens up a wav file to throw all the samples into an array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void read_wav_header(unsigned int *samp_rate, unsigned int *bits_per_samp,
                 unsigned int *num_samp);
void read_wav_data(int *data, unsigned int samp_rate,
               unsigned int bits_per_samp, unsigned int num_samp);
int conv_bit_size(unsigned int in, int bps);

int main(void)
// int read_wav(void)
{

unsigned int samp_rate, bits_per_samp, num_samp;
read_wav_header(&samp_rate, &bits_per_samp, &num_samp);

printf("samp_rate=[%d] bits_per_samp=[%d] num_samp=[%d]\n",
       samp_rate, bits_per_samp, num_samp);

int *data = (int *) malloc(num_samp * sizeof(int));
read_wav_data(data, samp_rate, bits_per_samp, num_samp);

unsigned int i;
// for (i = 0; i < num_samp; ++i) {

for (i = 0; i < 100; ++i) {
    printf("%d\n", data[i]);
}

return EXIT_SUCCESS;
    }

   void read_wav_header(unsigned int *samp_rate, unsigned int *bits_per_samp,
                 unsigned int *num_samp)
{
unsigned char buf[5];

// freopen ("/Users/ericbrotto/Desktop/iPhoneData/tmp/Hack.wav","r",stdin);

 freopen ("C:/Documents and Settings/Eric.Brotto/Desktop/Eric_Other/Files/Hack.wav","r",stdin);

/* ChunkID (RIFF for little-endian, RIFX for big-endian) */
fread(buf, 1, 4, stdin);
buf[4] = '\0';
if (strcmp((char*)buf, "RIFF")) exit(EXIT_FAILURE);

/* ChunkSize */
fread(buf, 1, 4, stdin);

/* Format */
fread(buf, 1, 4, stdin);
buf[4] = '\0';

printf("IS THIS WAVE?  -->%s<--\n",(char*)buf);

if (strcmp((char*)buf, "WAVE")) exit(EXIT_FAILURE);

/* Subchunk1ID */
fread(buf, 1, 4, stdin);
buf[4] = '\0';
printf("IS THIS fmt?  -->%s<--\n",(char*)buf);

if (strcmp((char*)buf, "fmt ")) exit(EXIT_FAILURE);

/* Subchunk1Size (16 for PCM) */
fread(buf, 1, 4, stdin);
if (buf[0] != 16 || buf[1] || buf[2] || buf[3]) exit(EXIT_FAILURE);

/* AudioFormat (PCM = 1, other values indicate compression) */
fread(buf, 1, 2, stdin);
if (buf[0] != 1 || buf[1]) exit(EXIT_FAILURE);

/* NumChannels (Mono = 1, Stereo = 2, etc) */
fread(buf, 1, 2, stdin);
unsigned int num_ch = buf[0] + (buf[1] << 8);
if (num_ch != 1) exit(EXIT_FAILURE);

/* SampleRate (8000, 44100, etc) */
fread(buf, 1, 4, stdin);
*samp_rate = buf[0] + (buf[1] << 8) +
(buf[2] << 16) + (buf[3] << 24);

/* ByteRate (SampleRate * NumChannels * BitsPerSample / 8) */
fread(buf, 1, 4, stdin);
const unsigned int byte_rate = buf[0] + (buf[1] << 8) +
(buf[2] << 16) + (buf[3] << 24);

/* BlockAlign (NumChannels * BitsPerSample / 8) */
fread(buf, 1, 2, stdin);
const unsigned int block_align = buf[0] + (buf[1] << 8);

/* BitsPerSample */
fread(buf, 1, 2, stdin);
*bits_per_samp = buf[0] + (buf[1] << 8);

if (byte_rate != ((*samp_rate * num_ch * *bits_per_samp) >> 3))
    exit(EXIT_FAILURE);

if (block_align != ((num_ch * *bits_per_samp) >> 3))
    exit(EXIT_FAILURE);

/* Subchunk2ID */
// fread reads line by line until the end.

fread(buf, 1, 4, stdin);
  buf[4] = '\0';

if (strcmp((char*)buf, "data")) exit(EXIT_FAILURE);

/* Subchunk2Size (NumSamples * NumChannels * BitsPerSample / 8) */
fread(buf, 1, 4, stdin);

const unsigned int subchunk2_size = buf[0] + (buf[1] << 8) +
(buf[2] << 16) + (buf[3] << 24);
*num_samp = (subchunk2_size << 3) / (
                                     num_ch * *bits_per_samp);
 }

 void read_wav_data(int *data, unsigned int samp_rate,
               unsigned int bits_per_samp, unsigned int num_samp)
 {

// freopen ("/Users/ericbrotto/Desktop/iPhoneData/tmp/Hack.wav","r",stdin);
 freopen ("C:/Documents and Settings/Eric.Brotto/Desktop/Eric_Other/Files/Hack.wav","r",stdin);

  unsigned char buf;
unsigned int i, j;
for (i=0; i < num_samp; ++i) {
    unsigned int tmp = 0;
    for (j=0; j != bits_per_samp; j+=8) {
        fread(&buf, 1, 1, stdin);
        tmp += buf << j;
    }
    data[i] = conv_bit_size(tmp, bits_per_samp);
}
 }

 int conv_bit_size(unsigned int in, int bps)
 {
const unsigned int max = (1 << (bps-1)) - 1;
 return in > max ? in - (max<<1) : in; // Supposedly this is not correct: http://ubuntuforums.org/showthread.php?p=10442711
//  return in > max ? in - ((max<<1)+2) : in;

 }

EDIT 2
On my mac it outputs all the samples in the array (ints roughly between -32000 and 32000). Here I get the output you see in the image followed by a few million zeros.
Comment: What is the output, and what code generates it?
Comment: It's entirely possible. It depends what code you are writing. Some code is deemed "implementation dependent", which means that results will vary from one compiler to another
Comment: We'll need the output as well.
Answer: Yes. Even assuming that both compilers comply with the ISO standard (which is not necessarily so), there's still a lot of leeway in that standard.
For example, if your program uses implementation defined or locale-specific behaviour, the output can be different.
If whoever wrote the program used undefined behaviour, then that's also a possibility for different output.
Your best bet would be to show us the code for proper analysis.
If you're interested in the sorts of things that can differ, Annex J of C99 (you can downlaod the draft with TC1, 2 and 3 from the bottom of that page - the differences between that and the final product are minimal) lists the portability issues (unspecified, undefined, implementation-defined and locale-specific behaviour).
One thing you may want to be careful of. This may not apply to Tiny C but I know that the Microsoft compilers I've used are one of that class where "r" and "rb" are treated differently in fopen/freopen. If you just specify "r", translation takes place which may give you the wrong data from a binary file such as a wav file.
Comment: see EDIT 1. I hope it's not too much :)
Comment: are you suggesting that I use rb instead of r?
Comment: @Eric: no, I'm pointing out that it's one _possible_ problem from a cursory glance over your code. There's little chance I'm going to do an in-depth analysis since I normally get paid pretty well for that sort of stuff :-) My advice is to create an incredibly short wav file for debugging so that you're not getting several million zeroes. That will ease your task somewhat. Then it's just a matter of comparing the output.
Answer: Any reasonably simple code (i.e. printf("Hello World!") should behave the same way in both environments.  More exotic expressions are not guaranteed.
Xcode uses gcc, so your code may be using a gnu-specific extension (which is not guaranteed to be portable)

Different compilers, different output?


Cannot start iptables on RHEL 7

Question: I am trying to use iptables on a RHEL7.  I have performed the following:
systemctl mask firewalld
systemctl stop firewalld
yum install iptables-services
systemctl enable iptables
systemctl start iptables

But the last line errors:
Job for iptables.service failed because the control process exited with error code. See "systemctl status iptables.service" and "journalctl -xe" for details.

journalctl -u service-name.service
-- No entries --

and journalctl -xe
Jan 13 12:30:03 localhost.localdomain systemd[1]: Unit iptables.service entered failed state.
Jan 13 12:30:03 localhost.localdomain systemd[1]: iptables.service failed.
Jan 13 12:30:03 localhost.localdomain polkitd[10240]: Unregistered Authentication Agent for unix-process:27798:561438909 (system bus name :1.22082, object path /org/freedesktop/P
lines 1222-1263/1263 (END)

Which only tells me it failed, not the cause, and I don't know what Unregistered Authentication Agent for unix-process means or if it's related.  I believe it is because it always follows the iptables error lines.  But I don't know what this means, or specifically how to remedy it. Nor which is cause and which is effect.
Additionally:
sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   permissive
Mode from config file:          enforcing
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Max kernel policy version:      28

and iptables-restore hangs.
This other post is no help.
Resolved:
I am not sure exactly what was the real cause, handle locks or whatever, but after a couple of reboots and running iptables-restore, I am now able to get the service started.
How to I get iptables services started?
Comment: do you disable ipv6 too?.....
Comment: @JacobEvans - No, but I am not using IPv6 either at the moment.
Comment: did you try `systemctl daemon-reload` before `systemctl start iptables`
Comment: @JacobEvans no but I just tried with same results.
Answer: Short answer I know, but I had a similar issue and a reboot fixed it. The service was started on boot and then I could stop and start as normal.
Comment: After a couple more reboots and restore attempts, everything is now working.  So, I am accepting this as my answer.
Comment: Thanks for the suggestion, but same results.
Comment: Sorry it didn't work
Answer: Run in sequence it worked.
service iptables save
systemctl stop firewalld
systemctl disable  firewalld
systemctl start iptables
systemctl status iptables
systemctl enable iptables

Cannot start iptables on RHEL 7


When I opened the web page I downloaded before ,a http:// get became a file:/// get,why?

Question: I downloaded a web page named map.html which was a web app using Google apis.There was a marker on it.
However,when I opened the local one in the browser,the marker disappeared.And I checked the "developer tools" ,just to find out a get request from http:// had  turned into file:/// .
So it accounted for the html not working .The marker.png was on the  google web server.And apparently it can't be found on my computer.The weird thing was I opend the original web page and found out the marker.png in the "resource" in  developer tools with a link to http://.
The question was how to solve this problem.There was no explicit link to file:// in the html indeed .
Answer: Because earlier you were requesting the page from the server over HTTP and now when you are opening the saved page you are requesting to open the page from your local file system.
For the image, download the image on your computer and then change the HTML code for the image to use the local image. This means you need to modify the "src" attribute of the  tag in your html file.
Comment: Thanks for helping.The question is that there is no img tag at all.It containes some javascript and post requests to google to use the api.  In fact in the resources there are many images all of which on the google server except from this one linked to file://.Is it a flaw of google's map api?


Somar mais um ID ao gerar mais um INPUT via javascript

Question: Eu estou criando um sistema de votações, e antes de a pessoa gerar o input com as opções, a pessoa tem que escolher o número de opções que terá, depois ela vai pra um formulário com as alternativas de acordo com a quantidade que ela escolheu, porém eu quero por algo como Adicionar mais um campo, e eu consegui através do JAVASCRIPT.
Só que ele não está conseguindo fazer a contagem dos campos que vem através do javascript:
Através do javascript ele coloca mais um campo quando a pessoa clica no Botão, depois da div idDiv...

        echo'<form action="valida_enquete.php" method="POST" accept-charset="utf-8">
            Título da sua enquete:<input type="text" name="titulo_enquete">

            Descrição da enquete: <input type="text" name="descricao_enquete">

';

            if(isset($_GET['qtdade_opcoes'])){

                ?>

                <?php
                for ($i=0; $i<$_GET['qtdade_opcoes']; $i++) {

                    $indice = $i+1;
                    echo'opção <input type="text" name="opcao[]">
';
                    echo'imagem <input type="text" name="img[]">
';

                echo' <input type="hidden" name="numero" value="'.$_GET['qtdade_opcoes'].'">';
                }
                echo '

                <input type="hidden" name="reality" value="'.$row['reality'].'">

';
            }

    ?>

Código javascript
window.onload = function () {
$(document).ready(function() {
   var maximo = 5;   //maximo de 5 campos
   var i = 1;
   $('#add_div').click (function(e) {
     e.preventDefault();  //previne novos cliques
     if (i < maximo) {
       $('#idDiv').append('
\
          opção: <input type="text" name="opcao[]"/>
 imagem:  <input type="text" name="img[]"/>\
          Remover\
           <?php    echo' <input type="hidden" name="numero" value="'.$_GET['qtdade_opcoes'].'">';
           ?>
');
           i++;
     }
  });

    // Remove o div anterior
    $('#idDiv').on("click",".remove",function(e) {
      e.preventDefault();
      $(this).parent('div').remove();
      i--;
    });
});
};

Alguém me ajuda, por favor?
Answer: Não é preciso declarar essa variável i = 1 e depois ir incrementando, pode pegar esse valor sempre atualizado no click usando por exemplo esse seletor: var i = $("#idDiv > div").length; ou seja, os divs aninhados dentro de div com id "idDiv", e length para retornar a quantidade.
Simplificando, ficaria assim (inclui uns comentários):

window.onload = function () {
$(document).ready(function() {
   var maximo = 5;   //maximo de 5 campos

   $('#add_div').click (function(e) {
     e.preventDefault();  //previne novos cliques

      // total de divs aninhados abaixo de idDiv
      var i = $("#idDiv > div").length;

     // inverti esse if, para não ficar todo o código aninhado, e sair logo se puder adicionar nos itens
     if (i >= maximo) return;

     $('#idDiv').append('
\
opção: <input type="text" name="opcao[]"/>
 imagem:  <input type="text" name="img[]"/>\
Remover
');

  });

    // Remove o div anterior
    $('#idDiv').on("click",".remove",function(e) {
      e.preventDefault();
      $(this).parent('div').remove();
    });
});
};
#idDiv > div {
   padding: 5px;
   border: solid 1px #ddd;
   background-color: #eee
}

    opção: <input type="text" name="opcao[]">

    imagem: <input type="text" name="img[]">

<button id="add_div">Adicionar</button>
Comment: Mas eu preciso que a quantidade de inputs esteja dentro desse input, que some junto com o $_GET['qtdade_opcoes'] sempre que a pessoa for adicionar mais um input e assim por diante...
Comment: você pode por isso no código, eu removi pq não ia funcionar no exemplo, isso ai é PHP, mas não muda o fato que, se está adicionar/removento elementos com javascript, faz isso do lado cliente, e tanto faz usar aquela variável ou pegar sempre a quantidade de elementos usando um seletor
Comment: eu coloquei e ele não pega a quantidade de itens que o javascript adiciona, como faço pra pegar essa quantidade? essa é a dúvida
Comment: `var i = $("#idDiv > div").length;` essa variável tem a quantidade de "itens" (divs). No seu código, tem um input hidden com a quantidade de opições, basta pegar o valor desse input e subtrair a quantidade de itens que tem se eu entendi bem. Pode ser assim: `var totOpicoes =$('input[name ="numero"]').val()`
Comment: Juro que é a última vez, e como eu faço pra pegar no PHP uma tag do javascript?
Comment: pq esse valor tem q estar dentro do input pra eu somar
Comment: pode perguntar, se fizer `POST` da página, pode fazer assim: `$_REQUEST['numero']`. Agora se quiser o total de campos, sugiro criar outro campo hidden para guardar esse valor, por exemplo ``. Nesse caso, usa o mesmo comando, só usa o nome desse outro input. Agora no javascript é preciso ir atualizando ele cada vez que adicionar ou remover um item. Por exemplo, ao adicionar um item, depois de fazer o `append`, atualiza esse campo: `$('input[name ="totalItens"]').val(i+1)`, "i" é a variável que tem o total de itens, como adicinou mais um, basta somar 1
Comment: DEUUUUUUUU CERTO MTO OBRIGADO!
Comment: Ricardoooo, só mais uma coisa, quando tiver removendo o campo ele tem que tirar -1 de volta, eu coloquei     $('input[name ="totalItens"]').val(i-1) depois do remover, só que ta dando erro
Comment: Copiou o codigo `var i = $("#idDiv > div").length;` para dentro da function que faz delete? pode ser isso
Comment: Simmm muito obrigado, outra coisa, eu estou tentando mostrar o número da opção com o seguitne códgio ' + $("#idDiv > #AlternativaDiv").length'   porém ele ta mostrando do 0, como faço pra começar do 2?


Specific robust measure of scale

Question: Do you know of any outlier resistant measure of scale $R(Y_1, \dots, Y_n)$ with the following property related to the sample standard deviation $S$?
Magic property:
If $S(Y_1, \dots, Y_n) > 0, \text{then } R(Y_1, \dots, Y_n) > 0$
IQR and MAD would not do the trick since they are 0 if the distribution is too discrete (but non-constant!)
Or is this impossible?
Answer: This is possible in a somewhat artificial sense: just adjust $R$ a little whenever $S$ is nonzero, to guarantee $R$ is nonzero in such cases.

"Resistant" means $R$ has a finite breakdown point, but the possibility of a sample with values $(Y, Y, \ldots, Y, Y^\prime \ne Y)$ means that $R$ has to respond to the value of even the most extreme datum. It would seem that such an $R$ could not be resistant.  However, since you have imposed no other conditions on $R$ that might otherwise limit our choices, you could make it resistant by ensuring $R$ cannot change much in such cases.  For example, define it as
$$R(Y_1, \ldots, Y_n) = \text{MAD}(Y_1,\ldots, Y_n) + I(S(Y_1,\ldots,Y_n) \gt 0)/n$$
(using the indicator function $I$).  Because the amount by which this could change the MAD is bounded, $R$ has the same breakdown point as the MAD, making it (strongly) resistant.
This merely adds $1/n$ to the (non-negative) MAD whenever the SD is nonzero, guaranteeing the "magic property."  By adding a quantity that decreases to zero as the sample size increases, asymptotically this $R$ will have the same expectation as the MAD, showing that the artificial correction isn't necessarily all that bad.
Of course you would be concerned about all this only when the $Y_i$ do not have a continuous distribution or are strongly correlated (for otherwise the chance of the SD being zero would be nil).

If you don't want to bias the estimator relative to the MAD you could, for instance, multiply the MAD by
$$1 + \text{sign}(Y_1-Y_2)I(S(Y_1,\ldots,Y_n)\gt 0)/(2n)$$
when the $Y_i$ are iid.  (This trick obviates the need to use a randomized estimator.)
Naturally the MAD could be replaced by almost any resistant estimator of scale.  The additive factor of $1/n$ could be replaced by any bounded nonzero function of $n$ or the multiplicative factors $1\pm 1/(2n)$ by any function with range in a finite interval $[a,b]$ and $a\gt 0$.
Comment: @rvl Wouldn't that have zero breakdown point?  In what sense, then, could it be considered "resistant"?
Comment: Good point. Wouldn't be robust. Could probably drum up an adaptive scheme with the L est as starter...
Comment: This is clever but makes me queasy if you add a view from dimensional analysis. Unless the variable being analysed is itself without dimensions (as a count, for example), adding $1/n$ is adding a quantity with different dimensions and units of measurement. Also, if you change the units of measurement, it's a little messy. My more naive reaction to the question is that such a measure cannot exist universally as even the smallest positive pairwise difference may be unresistant. Example: everything is 7 except for an outlier of 42. So the smallest such difference can equal  the range.
Comment: @whuber I'm being wicked here, as I was playing at allusion too (but at most just expressing a reservation about your solution). But the rules to me imply respect for dimensions and units. I'd want a very good reason to over-ride that in my own work. (Negative variances I think I've seen defended as meaningful, but I have no authority on that kind of issue.)
Comment: Any L estimator (linear comb of order statistics) of scale, having nonzero weights, would have the required property.
Comment: @whuber: I like your idea very much, thank you. Btw non-zero S just means that not every value is equal. This would make the magic condition look more intuitive.
Comment: @Nick I was (elliptically) alluding to such difficulties when I mentioned that the OP had imposed no properties, such as invariance under changes of measurement units. I could dodge that particular problem in several ways, such as by adopting a unit of measure and stipulating that $1/n$ be expressed in terms of it.  I don't think that would add anything to the answer, though.
Comment: Quite. Sometimes we would like to be able to impute what lies beyond the allusions and the ellipses! The plain-speaking answer to the question seems to be "not without bending the rules".
Comment: @Nick I like plain-speaking answers, to be sure: but I don't know what "rules" you might have in mind! As far as I know, I haven't bent any rules for formulating, evaluating, or selecting good statistical procedures. In fact, most of this response was motivated by an effort to point out how the proposed procedure--however strange it might seem--actually *meets* criteria people usually apply to determine good procedures. Although artificial, it's no worse in many respects than other procedures, such as replacing negative estimates of variance (which happens with some estimators) with zeros.
Comment: @Nick Be wicked all you want--it's a great way to eliminate misconceptions! I feel the way you do about strongly preferring invariant procedures, but I keep running across references to non-invariant procedures working well (especially in the data mining area), so I'm keeping an open mind.
Comment: It's also true that conservatism about dimensions was seriously undermined by Hausdorff, Besicovitch, Mandelbrot, etc. not to mention centuries-old work with power laws or functions $ax^b$ for non-integer $b$.
Comment: @NickCox: I was (and still am) thinking a bit like you in your first comment. Still it looks like a real drawback of IQR and MAD!
Comment: The length of the shortest half can also be zero whenever at least half of the values equal one value. If that sounds unusual, note that anything else is exceptional with binary data (scored 0 and 1, say)!
Answer: I will here gather together comments with the import that this is not possible in a simple manner.
Consider an example such as $y = 7, 7, \cdots, 7, 42$ with two distinct values, one of which occurs only once. The singleton in this example, $42$, has outlier flavour. So in broad terms resistant measures of scale are of interest here.
However, as @Michael M points out in the question, for such examples (with positive standard deviation) then IQR and MAD are zero. We could add that so also is the length of the shortest half. But any other alternative to the SD could hardly ignore the value of the smallest pairwise positive difference, i.e. the smallest value of $|y_i - y_j|$ that is positive. Here that is $35$ and for examples of this type it must be equal to the range, and thus quintessentially not robust (or resistant).
Note that for binary data coded $0$ and $1$ similar situations can easily arise, but using the SD as a measure of scale is pretty much universal without discussion. For binary data the IQR and MAD would usually be 0.
Comment: Yes, it got cut off from the comment: Chemometrics and intelligent laboratory systems, 87 (2), 218-225.
Comment: +1. In fact every robust equivariant scale estimator with breakdown at least $m/n$ must be 0 if $m$ observations are tied. This is proven in proposition 1 in *Croux, C.; Filzmoser, P. and Oliveira, M. (2007). Algorithms for Projection-Pursuit Robust Principal Component Analysis.*
Comment: @user603 Thanks; could you add full details for that reference please?
Comment: @user603: perfect! Should it be $n-m$ instead of $m$ tied observations or is it as you state it?
Comment: @MichaelM: yes, n-m!

Specific robust measure of scale


Is this set closed? (Finding the limit points of a set)

Question:
Prove that this set is closed:
$$ \left\{ \left( (x, y) \right) : \Re^2 : \sin(x^2 + 4xy) = x + \cos y \right\} \in (\Re^2, d_{\Re^2}) $$

I've missed a few days in class, and have apparently missed some very important definitions if they existed.  I know that a closed set is a set which contains its limit points (or, equivalently, contains its boundary), but I have no idea how to calculate the limit points of an arbitrary set like this.  The only intuition I have to that end is to fix either $x$ or $y$ and do calculations from there, since doing it in parallel often ends up in disaster.  Besides this, I don't know how to approach this problem.
If there is any other extant definition of closed-ness in a metric space, I welcome them wholeheartedly.
Answer:
Prove that the function $f(x,y) = \sin(x^2 + 4xy) - x\cos y $ is continuous on all of $\Bbb{R}^2$.
The point $0 \in \Bbb{R}$ is closed. (Why?)
Continuous functions take open sets to open sets and so take closed sets to closed sets, because taking the complement of a set commutes with taking the
inverse image.
Conclude.
Comment: I assume you mean the singleton set $\{0\}$ is closed, and that's because its only possible limit point is $0 \in \{0\}$.  I feel like (3) is something very similar to what I missed in class; could you expand on what you mean by 'commutes with'?  Is this just a phrase like 'is likened to' (or similar)?
Comment: For (3) I just mean that if $f : A \to B$ is a function and $D \subseteq B$ then $f^{-1}(D^c) = \left(f^{-1}(D)\right)^c$.
Comment: Oh, gotcha.  Thanks for the clarification :)
Answer: Your set is the preimage of the closed set $\{0\}$ by the continuous function $\Bbb R^2\ni(x,y)\mapsto\sin (x^2+4xy)- x\cos y$, hence it's closed.
Let $f:X\to Y$ a continuous function (between two metric spaces for example) and $F\subset Y$ a closed set, $G=f^{-1}(F)$. Here are two ways of proving that $G$ is a closed set of $X$.

The easiest, evident way : $f$ is continuous, so preimage of open sets are open. Since $F$ is a closed subset of $Y$, $Y\setminus F$ is an open subset of $Y$, and $X\setminus G=f^{-1}(Y\setminus F)$ is then an open subset of $X$, so $G=X\setminus(X\setminus G)$ is a closed subset of $X$.
Using limit points : Let $(x_n)_{n\in\Bbb N}\in G^{\Bbb N}$ a convergent sequence with limit point $x$. You want to prove that $x$ is in $G$. By the definition of $G$, you know that $f(x_n)$ is in $F$ for all $n\in\Bbb N$. By continuity, you (should) know that $\lim f(x_n)=f(\lim x_n)=f(x)$. Since $F$ is closed, it implies that $f(x)$ is in $F$. Again, by the definition of $G$, it means that $x$ is in $G$, so $G$ is closed.


hook_view, hook_theme and Display suite

Question: My module adds further content to a specific node bundle, in the "view" phase, in the following way:

hook_view (under the right conditions) adds these "contents" to the node display array
hook_theme specifies how to render the possible render_array related to the added contents

I followed several tutorials about, and in effect the documentation (of the latter) reports:

The structure of $node->content is a renderable array as expected by
  drupal_render().

Here is an abstract from my code:
/**
 * Implements hook_view().
 * Remember: hook prefix is based on the base of the node type (node-type-specific hook)
 */
function mynode_view($node, $view_mode) {
  $contentWrapper = entity_metadata_wrapper('node', $node);
  $myfield = $contentWrapper->myfield->value();
  if ($view_mode=="full") {
    $node->content["ds_column"] = array(
      '#markup' => theme('ds_column', array(
        'element' => _mymodule_to_render_arrays($myfield, $node->status),
        )),
      '#weight' => 150,
    );
  }
  return $node;
}

As you can see this adds the ds_column to my node content, telling me it has to be rendered by a theme function.
It also passes to the theme function a "render array" (containing the information to be rendered).
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'ds_column' => array(
      // See http://drupal.org/node/224333#theme_changes
      'variables' => array('element' => NULL),
      'template' => 'theme/ds_column'
    ),
  );
  return $theme;
}

This part of my module explain what template file have to be used in order to properly render, in the node (bundle) page, the content I added by the previous hook.
For what I see this is the standard approach. And indeed everything works fine.
The problem description starts here.
The module I described has been installed on an environment using the Display Suite module to define how to show contents for each node type in the node page, but the Display Suite module doesn't allow to see, in the configuration page, the content I added with the code shown above. So now that content doesn't appear in the node page.
I would like just to see the "ds_column" in the Display Suite configuration page for that specific node, in order to place it properly.
I can't figure how to see it (have I to implement also a DS hook? Have I to modify my code in some way?). I just found the "Display Suite Extra" sub-module, but I wasn't able to solve by it.
Comment: Welcome to Drupal Answers! It's not clear what you are saying, mostly because you are using a non-standard terminology and you aren't showing the code of your module. Without seeing any code, it's not possible to tell you if you need to change your code, which is one of the questions you are asking.
Comment: Please check my edit of your question, trying to help you to improve it a bit (and fix some typos). Feel free to further adapt, and if you don't like my edit at all, just perform a rollback. Good luck! PS: don't worry about **anonymous** downvotes ... (only consider those that teach you what you need to do to improve/rework it somehow).
Comment: Thank you @Pierre.Vriens I hope the question will be un-"on hold"ed and someone can help me. :)
Answer: For people interested to the solution, you have to use the hook_field_extra_field() hook.
There you can declare your own "virtual fields" and they will appear as fields also in the Display Suite.
To link them to the content you create, just be sure to use the same name as a key both in the field name and in what you add as a node->content.
To provide you with the solution related to my example:
/**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {
  $extra['node']['my_custom_bundle_type']['display'] = array(
      'ds_column' => array(
        'label' => t('My column'),
        'description' => t('Description is also mandatory'),
        'weight' => 99,
      ),
  );
  return $extra;
}

As you can see ther key ds_column is the same used in the mynode_view (or in any other function implementing a hook able to modify the content render array).

hook_view, hook_theme and Display suite


Captiulo 1, Kotlin in Action, Expecting a top level declaration [Iniciante]

Question: Estou aprendendo Kotlin, não consigo entender porque o problema "Expecting a top level declaration".
O resultado que eu pretendia era que apontasse Bob como o mais velho
data class Person(val name: String,
val age: Int? = null)

fun main(args: Array<String>) {
val persons = listOf(Person("Alice"),
                        Person("Bob", age = 29))
val oldest = persons.maxBy { it.age ?: 0 } }

println("The oldest is: $oldest")

Copiei igualzinho ao livro
mas fica retornando isso abaixo
Expecting a top level declaration
Expecting a top level declaration
Expecting a top level declaration
Expecting a top level declaration
Expecting a top level declaration
Expecting a top level declaration
Expecting a top level declaration
Expecting a top level declaration
Comment: seu println está fora da função main
Answer: Sua função println ficou fora da função main, no caso a chave de fechamento "}" veio antes.
Testei aqui no Intellij e o código funciona.
Como pode perceber a única mudança que fiz nesse código, foi retirar o parâmetro da função "main" para rodar no Intellij.
package testes

data class Person(val name: String, val age: Int? = null)

fun main() {
    val persons = listOf(Person("Alice"), Person("Bob", age = 29))
    val oldest = persons.maxBy { it.age ?: 0 }

    println("The oldest is: $oldest")
}

Resultado: