Is $\mathcal{O} \otimes_{\mathbb{Z}_p} F$ a finite direct product of fields?

Question: Consider the $p$-adic field $\mathbb{Q}_p$ with ring of integers $\mathbb{Z}_p$ and residue field $\mathbb{F}_p$. Let us take a finite  extension $K$ of $\mathbb{Q}_p$, with ring of integers $\mathcal{O}_K$ and $k$ be the residue field of $K$. Let $\pi \in \mathcal{O}_K$ be a uniformizer. Consider the ring of power series $\mathfrak{S}\mathrel{:=}W(k)[[u]]$, where $W(k)$ is the ring of Witt vectors on the residue field $k$. Let $\mathcal{O}:=\widehat{\mathfrak{S}[\frac{1}{u}]}$ be the $p$-adic completion of $\mathfrak{S}[\frac{1}{u}]$. Also let $F$ be finite field.
Then $\mathcal{O} \otimes_{\mathbb{Z}_p} F$ decomposes as a product of fields.
Question:
Is $\mathcal{O} \otimes_{\mathbb{Z}_p} F$ a finite product of fields ? Or an arbitrary product of fields ?
For example, $W(k) \otimes_{\mathbb{Z}_p} W(k)$ is a finite ($[k: \mathbb{F}_p]$ copies) direct product of $W(k)$.
But I couldn't conclude  the question.
Any hints please
Comment: @reuns it's reasonable not to use $\pi$ because $\pi$ doesn't actually get used in the definition of $\mathcal O$ or anywhere else in the actual question being asked. You didn't use $\pi$ yourself in the answer you posted.
Comment: The basic case would be $F=\mathbb F_p$. Do you know what the tensor product is in that case? (Hint: It should be one field.) Then you should derive the general case from there, writing it as tensor product of that basic case, over $\mathbb F_p$, with a finite extension of that.
Comment: @TorstenSchoeneberg, so, when $F$ is finite extension of $\mathbb{F}_p$, the above tensor product would be finite direct product of fields. Isn't it ?
Comment: You didn't use $\pi$ @TorstenSchoeneberg
Answer: Correct me if I'm wrong but $W(k)= O_L=\Bbb{Z}_p[\zeta_{q-1}]$ where $L=\Bbb{Q}_p(\zeta_{q-1}),q=|k|$ is the largest unramified extension $\subset K$ $$\mathfrak{S}[\frac{1}{u}]=O_L[[u]][u^{-1}]=\{ \sum_{n\ge -N} a_n u^n, a_n\in O_L\}$$ whose $p$-adic completion is $$\mathcal{O} = \{ \sum_{n=-\infty}^\infty a_n u^n, a_n\in O_L, \lim_{n\to -\infty} v_p(a_n)=\infty\}$$
Note that $\mathcal{O}/(p)=\Bbb{F}_q((u))$.
For a finite field $F$, when $char(F)\ne p$ then $\mathcal{O}\otimes_{\Bbb{Z}_p}F=\mathcal{O}/(char(F))\otimes_{\Bbb{Z}_p}F=0$,
when $char(F)=p,F=\Bbb{F}_p[x]/(f(x))$ then $$\mathcal{O}\otimes_{\Bbb{Z}_p}F=\mathcal{O}/(p)\otimes_{\Bbb{F}_p}\Bbb{F}_p[x]/(f(x))$$ $$=\Bbb{F}_q((u))\otimes_{\Bbb{F}_p} \Bbb{F}_p[x]/(f(x))=\Bbb{F}_q((u))[x]/(f(x))$$ $$=\Bbb{F}_q((u))[x]/(\prod_j f_j(x))=\prod_j\Bbb{F}_q((u))[x]/(f_j(x))=\prod_j \Bbb{F}_{q^{\deg(f_j)}}((u))$$
Comment: I assume $f_j$ are the irreducible factors of $f$ over $\mathbb F_q$?
Comment: $char(F)\otimes 1 = 1\otimes char(F)=1\otimes 0=0$ so we can quotient by (the ideal generated by) $char(F)\otimes 1$.
Comment: Yes, distinct maximal thus comaximal ideals
Comment: @reuns, Thanks for your nice answer. Can you explain why $\mathcal{O}\otimes_{\Bbb{Z}_p}F=\mathcal{O}/(char(F))\otimes_{\Bbb{Z}_p}F$ ? I think the later tensor product should be over $\mathbb{F}_p$ instead of $\mathbb{Z}_p$.
Comment: @reuns, ohh, nice. Thank you very much


Homomorphism and irreducible polynomials

Question: Let R[x] be a polynomial ring. Let S[x] be another polynomial ring such that $R[x]\subset S[x]$ . Let $\phi: R[x]\rightarrow S[x]$ be an inclusion homomorphism.
Let $f(x)$ be a polynomial in $R[x]$ and $g(x)\in S[x]$ be the polynomial obtained after applying the homomorphism.
If $g(x)$ is irreducible in $S[x]$, what can we be inferred of $f(x)$?
Is $f(x)$ irreducible?
Also 2)I arrived at a condition that,  $\phi: R[x]\rightarrow R[x]$, be such that,  $g(x)=\phi(f(x))$ is irreducible. Does it mean $f(x)$ is irreducible.
Thank you for any hint or help.
Comment: Is $ \phi $ the inclusion map? If not, I don't see how $ R[x] \subseteq S[x] $ is relevant.
Comment: Yes $\phi$ is an inclusion homomorphism, I have corrected it
Comment: If $f=f_1f_2$ where $\deg(f_1),\deg(f_2)>0$ and $\phi$ is the inclusion homomorphism, then $g=\phi(f)=\phi(f_1)\phi(f_2)$ where $\deg\phi(f_1),\deg\phi(f_2)>0$
Answer: Let $ R = \mathbb{Z} $, $ S = \{\frac{a}{2^n} : a \in \mathbb{Z}, n \geq 0\} $, i.e. localization by the powers of 2, and $ \phi $ be the inclusion map. Then $ 6 \in R $ is reducible, but $ 6 \in S $ is irreducible, as in $ S $, 2 is a unit and 3 is irreducible. Then the same counterexample works for $ R[x] $ and $ S[x] $.


Função deletar da lista

Question: Tenho essa função para deletar da lista encadeada pelo valor:
public void deletar(Object valor) {
        Node temp = head;

        while(temp != null) {
            if(temp.getNext().getValor().equals(valor))  {
                temp.setNext(temp.getNext().getNext());
                break;
            } else {
                temp = temp.getNext();
            }
        }
    }

Mas o último elemento sempre causa NullPointerException, não deleta, como soluciono isso?
Answer: O problema é que você está tentando chamar temp.getNext().getNext(), mas a primeira chamada do getNext() pode retornar null, e isto não está sendo checado.
Primeiro devemos checar se a cabeça é não nula
        if(head == null)
            return;

Em seguida, checamos se devemos atualizar o nó raíz.
        if(head.getValor().equals(valor)){
            head = head.getNext();
            return;
        }

Por fim buscamos o valor desejado, atualizando a ligação anterior temp:
        temp = head;
        prox = temp.getNext();
        while(prox != null) {
            if(prox.getValor().equals(valor))  {
                temp.setNext(prox.getNext());
                break;
            } else {
                temp = prox;
                prox = temp.getNext();
            }
        }
    }
}

O Código completo é o seguinte:
public void deletar(Object valor) {
        Node temp, prox;

        if(head == null)
            return;

        if(head.getValor().equals(valor)){
            head = head.getNext();
            return;
        }

        temp = head;
        prox = temp.getNext();

        while(prox != null) {
            if(prox.getValor().equals(valor))  {
                temp.setNext(prox.getNext());
                break;
            } else {
                temp = prox;
                prox = temp.getNext();
            }
        }
    }
}

Função deletar da lista


Computing the dyadic add portion of the Walsh-Fourier spectral density

Question: I am attempting to build a Walsh-Fourier spectral density and it appears that it is first required to compute the logical covariance which in turn involves a dyadic add.
I am not at all familiar with dyadics or their operations and introductory references are hard to come by.
In Stoffer (1988) the logical covariance of a categorical series $X(0), X(1),\dots,X(N-1)$ is described as being:
\begin{align}
\tau(j)=N^{-1} \sum_{j=0}^{N-1} \gamma(j\oplus k-k)
\end{align}
where $j\oplus k$ is the dyadic addition. $\gamma$, is our usual autocovariance, $\gamma(h)=cov\{X(n), X(n+h)\}$.
The Walsh-Fourier spectral density is then:
\begin{align}
f(\lambda)=\sum_{j=0}^{\infty}\tau(j)W(j, \lambda)
\end{align}
where $W(j, \lambda)$ is the $j$th sequency (zero-crossings) with $0\leq\lambda < 1$.
I'm sure a HMM would be great for categorical times series but at the moment I am restricted to spectral analysis so I must continue with this approach. It's not exactly homework. It's a final project that has moved a little beyond the coursework. The professor is a little hard to get a hold of and thus the question is posed here.
Is it just addition? I haven't even been able to confirm that.
Answer: After digging about and reading various papers I discovered that the definition is referenced as given in a paper by R.Kohn in 1980, On the Spectral Decomposition of Stationary Time Series Using Walsh Functions. I
In short there are two definitions depending upon whether or not the values being added are integers or reals. Luckily I am only concerned with the integer case which is a little simpler.
Kohn defines the $\oplus$ operation on integers as follows:
Let $m,n$ be integers and $m_j,n_j$ be restricted to 0 or 1, then
\begin{align}
m=\sum_{j=0}^fm_j2^j \hspace{2mm} \text{and} \hspace{2mm} n=\sum_{j=0}^fn_j2^j
\end{align}
the dyadic sum then is
\begin{align}
m\oplus n=\sum_{j=0}^f|m_j-n_j|2^j
\end{align}
He gives as an example $5\oplus 3=6$. While $f$ isn't defined it appears to mean the 'useful' domain of the function because
\begin{align}
5=2^0*1+2^1*0+2^2*1+\sum_{j=3}^{\infty}0*2^j\hspace{2mm} \text{and} \hspace{2mm} 3=2^0*1+2^1*1+\sum_{j=2}^{\infty}0*2^j
\end{align}
Then
\begin{align}
5\oplus 3=2^0*|1-1|+2^1*|0-1|+2^2*|1-0|+\sum_{j=3}^{\infty}|0-0|*2^j=6
\end{align}
Comment: so basically XOR


C# Reflection at run-time

Question: I want to get information about the fields, functions and threads of a some project, through another project.
As an example project that I want to explore, I created a field int x that initialize to 1.
The Main calls to function that changes the value of x to 2.
I stuck the Main in an endless loop.
I ran this project.
The second project:
Get the path to the EXE file of the first project, and load the assembly.
By reflection, i got the names of departments, functions and fields.
I tried to print the value of the field x by the function getValue. Instead of printing 2, 1 was printed.
i.e., the reflection refers to the values of the compiled-time, instead of the run-time.
what should i do?
Comment: This is not what reflection means in .NET world. I would recommend calling it something different.
Comment: Loading the assembly doesn't run the code. You haven't executed your `Main` and thus never updated `x`. You're trying to access in-memory values from a completely different process, and that's a whole different kettle of fish. =)
Comment: do you mean you need to interrogate a different assembly dynamically?
Comment: Where else would you do reflection, at compile-time?
Comment: I miss read this, you could setup a service endpoint to get the runtime value from another running project.  or just use sockets directly.
Answer: You can't get the new value, that's in memory, in the other process.
With Reflection you can however load that assembly, create an instance of that class and call Main explicitly and then check for the value of the int because then the code would be run by your process.
Do not expect to be able to sniff the values out of the memory space of another application with Reflection, that is not what Reflection does.
Comment: I added a thread that invoked the Main class, but it still does'nt work..   :(
Comment: @OrKedmi Why a separate thread? Try to load the assembly, create an instance, call the Main method and after it's finished, get the value of the field and see. It should show the new value of 2.
Comment: While the first project  is ran, I want to check each interval of time the value of X..
There's no point waiting until he will finish.

C# Reflection at run-time


How to find the distance to pixel ratio in a image.

Question: I am trying to find a estimated distance in a image based on the camera height and angle.
I know how to find the center of the image distance based off of this equation that I am using
Camera Height $= H$
Camera Angle $= A$
Distance $= D$
$D = \frac{H}{\cos(A)}$
Now how do I find the rest of the distances in the image. I tried using the ratio between the distance and the pixel value, but that does not give me good results.I was going to try to change the angle of the camera but I dont know if that would give me the right results as the camera angle has not really changed would this work?
Any suggestions would be appreciated.
Distance CM    PixelValue  Ratio
100            449       0.22
200            296       0.68
300            231       1.3
400            194       2.06
500            170       2.94
576            106       5.43
So this is where I am going with this for now as I know all the distances for each angle, but still don't know how to find the slope or change a ratio for distance. I just don't see a patter here.
Answer: Firstly you will need to do your analysis in 2 angular dimensions. You will need to know a fair bit. There is no pixel to distance ratio. It is nonlinear. The pixel to azimuth is what you are after. It is still nonlinear, but manufacturers will strive for linearity in this.
Comment: But for my particular camera wouldnt there be a way to calculate the distance based off pixel location? There is no slope for the ratio for it to fallow?
Comment: yes your right I was working thought the differences in pixels
2.4m -> 3 is 35pix
3-> 4 is 37pix
4->5 is 27pix
5->5.7 is  64


Force users to go through a proxy server?

Question: I need to force my users on my network to use a transparent proxy server outside my network to access websites. I'm not sure if I can do this with DNS, by setting up my own DNS which redirects them to the proxy server. How can I achieve this?
Answer: One option is to lock the users to a browser that honors the global proxy setting on a system (such as IE on Windows with GPO that applies proxy), but that also requires that you have total control of all clients on your network.
The other option is to redirect every packet destined for HTTP(80)/HTTPS(443) to a Proxy server with transparent support. There are a ton of options here, and we have no idea what kind of router or firewall you have for the redirect part.
One popular solution is WCCP/WCCP2 against Squid.


jQuery ready firing before custom behavior script initializes

Question: Background
I've inherited an ancient web application that has input controls with custom behaviors defined with an old-fashioned HTC (HTML Component) script, e.g.:
<input name="txtFiscalYearEndDay" type="text" value="30"
    maxlength="2" size="5" id="txtFiscalYearEndDay" class="Text1"
    style="behavior:url(/path/js/InFocus.htc);" />

Here are the relevant parts of this HTC file to illustrate the issue:
<PUBLIC:COMPONENT tagName="InFocus">
<PUBLIC:METHOD NAME="setValid" />
<PUBLIC:ATTACH EVENT="ondocumentready" HANDLER="initialize" />

</PUBLIC:COMPONENT>

So, nothing out of the ordinary so far. Additionally, I have some JS that runs on DOM-ready:
$(function() {
    txtFiscalYearEndDay_Validate(document.getElementById('txtFiscalYearEndDay'));
});

And the validation function:
function txtFiscalYearEndDay_Validate(el) {
    ...
}

Note: I'm not using $('#txtFiscalYearEndDay') because then I really can't try to call setValid(true); on the element, nor do I want to have to do $('#txtFiscalYearEndDay')[0].setValid(true);.
The problem
At one point in the validation function, I'm attempting to call a method on the element, the one added by the HTC script:
el.setValid(true);

However, the IE debugger gets sad and complains that setValid() is not a function. Inspecting it in the debugger confirms this:
typeof el.setValid // "unknown"

Of course, once the page has completed rendering (or whatever period of time is needed for the document to actually be ready has passed), the validation function works as expected (because I'm calling the same validation function on change and blur events as well). That is, when the function is called outside of jQuery's on-DOM-ready function, it works just fine.
Do any of you have any ideas at to what might be happening here? Is jQuery's "ondomready" being registered before the HTC script's "ondomready"? Can I somehow change that order?
I'm currently seeing this behavior in all versions of IE.
EDIT: WORKAROUND
I discovered a workaround. If you take the function call out of the jQuery ready function and throw it at the end of the page, it works (i.e.:)
...

Answer: I do not know if HTC counts toward page ready but i suspect they do not.
What you might try is check something that only is tru after the HTC hase finished.
You own script should then start something like this:
function MyFunction() {

 if(!HTCIsreadyTest()) {
    setTimeout(MyFunction, 100);
return;
}

//the rest of your code

}

This basically makes you function check and restart in 100  milliseconds if conditions are not met untill the test succeds.
You could also ad a counter argument increasing it by one for each attempt to have some timeout code trigger if HTC sciprts has not loaded after 2 seconds
Answer: The easiest workaround I could find was to move the validation function call out of the jQuery ready() callback and move it to the end of the page:
...

However, I found a more elegant solution. Because I seemingly need to wait for all page resources to be loaded, I simply needed to move the function call out of the jQuery ready() callback and instead put it in a window load() callback:
$(window).load(function() { // instead of $(function() {
    txtFiscalYearEndDay_Validate(document.getElementById('txtFiscalYearEndDay'));
});

I'm using the latter so I can keep all of the JS code together.


Abrir HTML com link usando NSAttributedString

Question: Eu recebo do servidor um HTML similar a esse:
"
Dummy text
Click Here"

No Click Here deveria ser possível clicar e abrir no Safari. Eu tentei implementar o seguinte código: (sendo textMsg um TextView).
 NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[[self.myServer textHTML] dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
[self.textMsg setEditable:NO];
[self.textMsg setScrollEnabled:NO];
[self.textMsg setDataDetectorTypes:UIDataDetectorTypeLink];
self.textMsg.attributedText = attrStr ;

Tentei também de outras formas similares, mas nenhuma funcionou..
No android existe uma função similar, Html.fromHtml().
Recebendo o link dessa forma, haveria uma maneira de fazer com que ele redirecionasse pro browser?
Answer: A url não é aberta automaticamente no browser porque não é indicado o protocolo. Caso você inclua o protocolo, o link sera aberto no Safari:
@"
Dummy text
Click Here"

Caso queira maior controle sobre a ação ao clicar no link, implemente o método - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange do delegate de UITextView


SQL Server 2014 Disable SSL/TLS

Question: I am running SQL Server 2014 on Server 2012 R2. Both are updated and current. I did a clean install of both and nothing else. I then requested VPN access for an offsite vendor and our security group informed me that SSLv3 and TLSv1.0 needed to be disabled. (No idea how they got enabled, I have done nothing certificate related on this machine.)
I then ran IISCrypto and disabled the two protocols. Passed the security scan and proceeded, I thought everything was good to go. Now having a lot of issues getting the app server to connect to SQL. I think it would be better if I could just disable all of the TLS/SSL stuff on 1433. But when I check SQL Config Mgr Force Encryption = No and no certificates are loaded.
I also tried to disable everything in IISCrypto, but that broke RDP.
When I run this command:
<code>nmap --script ssl-enum-ciphers localhost
</code>
Both 1433 ms-sql-s and 3389 ms-wbt-server have the SSL/TLS stuff, everything else just has the port/tcp open. I would like to know how to get SQL / 1433 to no longer show up as using SSL/TLS and RDP to still work. I do not want to load any certificates or use SQL encrypted. How do I get the flag to go away that is reporting that it's turned on.
Comment: Even if you are not encrypting the entire connection, SQL Server still uses encryption for the initial username/password handshake.  You cannot avoid this.

If your app server is now having problems connecting, then you probably need to update the db driver on the app server.  how is your app connecting to SQL Server?  OLE DB? SQL Native Client?
Comment: Yea. Anytime I disable TLS v1.0 the app stops working. I've patched SQL server up to the latest version and updated both ODBC and SQL Native Client on the app server. I've reached out to the vendor asking what protocol they are using. I can connect via ODBC with ODBC Driver 11 for SQL and SQL Native Client 11 from the app server.
Answer: Your security group probably means "disable SSLv3 and TLSv1.0 because they are old and have known vulnerabilities; use TLSv1.1 or newer instead." This is not the same as disabling all encryption. Check with them first, but I cannot believe they would want you forcing plain-text database connections.
Microsoft products like IIS, Terminal Services, and SQL Server use Windows' SCHANNEL library for doing TLS. You can configure it in the Registry by following the guide in KB187498. More information can be found on this article on the MSDN Unleashed blog.
Comment: @Ty. Then it's the client that doesn't support TLSv1.1 or newer.
Comment: Yea, I've done that. Both manually and with IISCrypto. If I disable TLSv1.0 the app stops working. I guess I thought that the fact it was showing up with nmap that it meant I should have a SSL/TLS certificate loaded and encryption turned on, which isn't the case.

SQL Server 2014 Disable SSL/TLS


$\int \lvert f_n-f\rvert^p g\rightarrow 0$ implies convergence in measure?

Question: I was thinking about whether $\int_{\Omega} \lvert f_n-f\rvert g\rightarrow 0$ implies $f_ng\rightarrow fg$ in measure. Here $f_n$ is a sequence in $L^1(\Omega)$, $f\in L^1(\Omega)$, $g \in C_0(\Omega)$ and $\Omega \subseteq \mathbb{R}^n$ is open and nonempty.
So clearly, $L^p$ convergence implies convergence in measure. In this Case, $g$ might bei negative, so $L^p$ convergence of $f_n$ to $f$ might not be true, even on the support of $g$.
So could there be a counterexample?
Comment: You might look at $f=0$ and $f_n =f_0$ independent of $n$.  This almost becomes the question "If the integral of a function is zero, is the function zero?"
Answer: Counter-example: $\Omega =(-1,1),f(x)=0,  f_n(x)=x^{2} $ for all $n$ and let $g(x)$ be any odd function with compact support, not identically $0$.
Comment: Your $g$ does Not have compact support. That ist what I mean by $C_0$. Maybe I should have clarified
Comment: @Meowdog There is plenty of choice for $g$. You only need it to be an odd function.


regex phone number validation with PHP

Question: This is another question about a previous question I had asked yesterday. I want user to be allowed to type US phone numbers in the following formats.
(800)-555-1212
800-555-1212
and have it only check the database for numbers 8005551212
I've seen that regex like
/^[\+]?([0-9]*)\s*\(?\s*([0-9]{3})?\s*\)?[\s\-\.]*([0-9]{3})[\s\-\.]*([0-9]{4})[a-zA-Z\s\,\.]*[x\#]*[a-zA-Z\.\s]*([\d]*)/
may work but I'm not certain how to implement it into the code from the link I provided
I'm new to php and know nothing about regex. Any help is appreciated.
Comment: why this question is tagged with mysql and mysqli?
Comment: Two things I will never bother validating by format, emails and phone numbers. If it's imperative that the user be contactable by phone, they'll get their number right
Comment: There are many answers.Check these links

http://stackoverflow.com/questions/3357675/validating-us-phone-number-with-php-regex

http://stackoverflow.com/questions/11705507/php-validation-of-us-phone-numbers

http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation
Comment: @YourCommonSense I tagged it with mysql and mysqli because it was part of a project that uses mysql I posted the link in the question.
Comment: @BenP.Dorsi-Todaro But it hasn't anything to do with the question. Keep in mind, that those tags are for the context of the question.
Comment: Well if it would be for the movie tickets project you'd tag it with 'tickets' and 'movie'?
Answer: This function validate a phone number, return true if it validate and false if invalid. This function very simple i was wrote to.

    /**
     * @param $number
     *
     * @return bool
     */
    function validatePhoneNumber($number) {
        $formats = [
            '###-###-####', '####-###-###',
            '(###) ###-###', '####-####-####',
            '##-###-####-####', '####-####', '###-###-###',
            '#####-###-###', '##########', '#########',
            '# ### #####', '#-### #####'
        ];

        return in_array(
            trim(preg_replace('/[0-9]/', '#', $number)),
            $formats
        );
    }

Comment: Be careful. It is not universal validator. It does not handle variants starting with `00` or `+` sign.
Comment: @mikep why you just not add "00 XXX" or "+ XX" ?
Comment: @DonatasNavidonskis because of you already have 12 items in array and to support `+` and `00` variants I should add 2*12 new items = together 36 items which is not so handy.
Comment: @mikep yeah, but this was one of the simple solutions, if you have more complex situation, sure this method is not fit for that situation.
Answer: if javascript is ok can go with

call this function onsubmit of form or onblur of textbox
If you have doubt about your regex you can validate it at http://www.regular-expressions.info/javascriptexample.html
Answer: You can use this pattern
\(?\d{3,3}\)?-\d{3,3}-\d{4,4}
Answer: Try this,
<?php
    $t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
    $arr=preg_match($t,'(800)-555-1212',$mat);
    $arr=preg_match($t,'800-555-1212',$mat);
    print_r($mat);
?>

Tested here
Comment: Works but would need to be $arr=preg_match($t,'8005551212',$mat); not with dashes I'm going to going with @Donatas Navidonskis approach.
Answer: Re: Rohan Kumar's solution
<?php
$t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
$arr=preg_match($t,'(800)-555-1212',$mat);
$arr=preg_match($t,'800-555-1212',$mat);
print_r($mat);
?>

It does address the issue of fake phone numbers such as 800-123-2222. Real phone numbers have a first digit of at least "2". While the other solutions do the format correctly, they don't address the issue of people putting in phone numbers like 800-000-1234, which would be correct in the other solutions provided.

regex phone number validation with PHP


How do I fade in and fade out one item of a list one at a time?

Question: The following code pulls a list from the firebase database, which falls under the div id called 'messagediv'.The CSS on this div id called 'message div' is set to display none.
I then run a javascript script that takes items with that css and fades it in and out. The issue is that it is fading in and fading out the entire list, as oppose to just one item of the list.
For example, it fades in and fades out this entire list:
this is the first item of the list:
this is the second item of the list:
this is the third item of the list:

but I only want it to fade in and out one at a time, so it would fade this first:
this is the first item of the list:

Then it would fade this second:
this is the second item of the list:

Below is the code I have so far that fades in and out the entire list, but I only want it to fade in and out one item of the list one at a time.

Comment: Here's a fiddle, in case anyone's interested in playing with it: http://jsfiddle.net/9TVgu/
Answer: Do you want something like this?
http://jsfiddle.net/prankol57/ZZskf/
Your main problem is that you start to showNextQuote before the quotes are loaded. I've created a variable called started so that the items start fading in as soon as the first one has loaded.
In addition, the length of $(".quotes") is 1. (There is only one div with class "quotes"). I think you wanted the
 elements insided of .quotes. So that is $(".quotes div"). It's possible you wanted each div element that you add to have a class called ".quotes". You'll need to work out the logic if that's what you wanted (should be a trivial change).
Here is the relavent code:
var myDataRef = new Firebase('https://helloworldtest.firebaseio.com');
var started = false;
myDataRef.on('child_added', function (snapshot) {
    var message = snapshot.val();
    displayChatMessage(message.name, message.text);
});

function displayChatMessage(name, text) {
    console.log("before", $(".quotes"));
    $('
').text(text).prepend($('').text(name + ': ')).appendTo($('#messagesDiv'));
    console.log("after", $(".quotes"));
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
    if (!started) {
        // We should only start showing next quote when the message has loaded
        showNextQuote();
        started = true;
    }
};

// The loading procedure needs access to this so we can't use an anonymous function
//(function() {
var quoteIndex = -1;

function showNextQuote() {
    // We get the div elements inside ".quotes"
    var quotes = $(".quotes div");
    ++quoteIndex;
    console.log("Showing next quote", quoteIndex, quotes);
    quotes.eq(quoteIndex % quotes.length)
        .fadeIn(2000)
        .delay(2000)
        .fadeOut(2000, showNextQuote);
}

//})();


Tableau multiple connections type of data change

Question: I am stuck on Tableau trying to put together tables. When joining tables under multiple connections in Tableau, I tried to change the type of data in 2 tables, but after changing it in one it shows me a red line on the joining symbol that doesn't let me change it on the other table, how can I go back to the columns to change the type of data on both?
I changed the type of data on one table and immediately it took me back to connections showing me a red line on one side of the connection, not letting me change the type of data on the other table.
Answer: I'm currently doing the Coursera's course and I found the same issues. The only thing you have to do is to expand the left down area that have columns like "Type, FIeld Name, Physical table etc. Then you will be able to see the the the field you want to convert to other type. enter image description here


When is a symmetric matrix invertible?

Question: My professor always writes on the board:
$A$ is $m \times n$, assuming that the vectors of $A$ form a basis, then $A^TA$ is always invertible.
one thing I know is that $A^TA$ is always symmetric, but I'm not sure about the conditions on a symmetric matrix needed to ensure that it is invertible?
Comment: What do you nean by "the vectors for $A$"?
Comment: There is a [long list of conditions](https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem) that are equivalent to the condition that a matrix is invertible, all of which are equally valid for symmetric matrices.  Are you instead asking for conditions on a matrix $A$ to ensure that $A^TA$ is invertible?
Comment: The words you need are "row" and "column." With $m$ rows and $n$ columns, we find $A^T A$ is a square of size $n.$  When $m \geq n$ and the $n$ columns of $A$ are independent, then $A^T A$ is also of rank $n,$ therefore invertible.
Comment: Sorry, should be "vectors of A" - it's my english.
Comment: @JMoravitz yes, sorry perhaps mis-asked the question, thank you.
Comment: and @WillJagy usually "vector" implies column vector, but i shoulda been more explicitthanks.
Comment: If $A$ forms a basis, then it is full-rank. A matrix and its transpose have the same rank. Then $A^TA$ is full-rank.
Comment: @YvesDaoust "If $A$ forms a basis, then it is full rank...." That is not generally true.  [0,1,0,0] and [1,0,0,1] can both be basis vectors. but obviously a matrix composed of those vectors will not be full rank.
Comment: And, furthermore, if $A$ is composed of those two vectors I just mentioned ([0,1,0,0] and [1,0,0,1]) , then $A^TA$ is symmetric but not invertible.
Answer: A sufficient condition for a symmetric $n\times n$ matrix $C$ to be invertible is that the matrix is positive definite, i.e.
$$\forall x\in\mathbb{R}^n\backslash\{0\}, x^TCx>0.$$
We can use this observation to prove that $A^TA$ is invertible, because from the fact that the $n$ columns of $A$ are linear independent, we can prove that $A^T A$ is not only symmetric but also positive definite.
In fact, using Gram-Schmidt orthonormalization process, we can build a $n\times n$ invertible matrix $Q$ such that the columns of $AQ$ are a family of $n$ orthonormal vectors, and then:
$$I_n=(AQ)^T (AQ)$$
where $I_n$ is the identity matrix of dimension $n$.
Get $x\in\mathbb{R}^n\backslash\{0\}$.
Then, from $Q^{-1}x\neq 0$ it follows that $\|Q^{-1}x\|^2>0$ and so:
$$x^T(A^TA)x=x^T(AI_n)^T(AI_n)x=x^T(AQQ^{-1})^T(AQQ^{-1})x \\ = x^T(Q^{-1})^T(AQ)^T(AQ)(Q^{-1}x) = (Q^{-1}x)^T\left((AQ)^T(AQ)\right)(Q^{-1}x) \\ = (Q^{-1}x)^TI_n(Q^{-1}x) = (Q^{-1}x)^T(Q^{-1}x) = \|Q^{-1}x\|^2>0.$$
Being $x$ arbitrary, it follows that:
$$\forall x\in\mathbb{R}^n\backslash\{0\}, x^T(A^TA)x>0,$$
i.e. $A^TA$ is positive definite, and then invertible.
Comment: Why do you need to use Gram-Schmidt? You can argue directly that $x^T A^T Ax = (Ax)^T (Ax) = \|Ax\|^2$, and the RHS is strictly positive for all nonzero $x$ provided that $A$ has trivial null space (or equivalently, that $A$ has full column rank).
Comment: @asd11 eigen values > 0, which implies $\prod \lambda = det A > 0$
Comment: What is the connection between positive definiteness and the determinant being different from zero?
Answer: @RobertLewis
A Gram matrix is usually defined by giving a set of vectors and then defining the i,j entry as the dot product of the i,j vectors. In doing so, clearly the set of vectors can be thought of as column vectors of A. So saying "the vectors for A" is a completely natural thing to say, and should be unambiguous.
here is an elegant proof
Gram matrix invertible iff set of vectors linearly independent
Comment: In your "counterexample", $A^TA = diag(1, 2)$ is most certainly invertible....
Comment: @Randy I think nundo probably meant to put a transpose on those two vectors, so that **A** is a 4x2 matrix, not 2x4.
Comment: you seem to be saying that the ONLY condition needed on $A$ for $A^TA$ to be invertible is if the column vectors of $A$ are linearly independent.  Please look at the example I gave to YvesDaoust:  if A is composed of those two vectors I just mentioned $([0,1,0,0], [1,0,0,1])$ , then $A^TA$ is symmetric but not invertible.  So, I think that your claim is not entirely true.
Comment: yes that's correct.  thanks

When is a symmetric matrix invertible?


Dispatch Redux action after React Apollo query returns

Question: I'm using React Apollo to query all records in my datastore so I can create choices within a search filter.
The important database model I'm using is Report.
A Report has doorType, doorWidth, glass and manufacturer fields.
Currently when the query responds, I'm passing allReports to multiple dumb components which go through the array and just get the unique items to make a selectable list, like so..
const uniqueItems = []

items.map(i => {
  const current = i[itemType]

  if (typeof current === 'object') {
    if (uniqueItems.filter(o => o.id !== current.id)) {
      return uniqueItems.push(current)
    }
  } else if (!uniqueItems.includes(current)) {
    return uniqueItems.push(current)
  }

  return
})

Obviously this code isn't pretty and it's a bit overkill.
I'd like to dispatch an action when the query returns within my SidebarFilter components. Here is the query...
const withData = graphql(REPORT_FILTER_QUERY, {
  options: ({ isPublished }) => ({
    variables: { isPublished }
  })
})

const mapStateToProps = ({
  reportFilter: { isPublished }
  // filterOptions: { doorWidths }
}) => ({
  isAssessment
  // doorWidths
})

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      resetFilter,
      saveFilter,
      setDoorWidths,
      handleDoorWidthSelect
    },
    dispatch
  )

export default compose(connect(mapStateToProps, mapDispatchToProps), withData)(
  Filter
)

The Redux action setDoorWidths basically does the code above in the SidebarFilter component but it's kept in the store so I don't need to re-run the query should the user come back to the page.
It's very rare the data will update and the sidebar needs to change.
Hopefully there is a solution using the props argument to the graphql function. I feel like the data could be taken from ownProps and then an action could be dispatched here but the data could error or be loading, and that would break rendering.
Edit:
Query:
query ($isPublished: Boolean!){
  allReports(filter:{
    isPublished: $isPublished
  }) {
  id
  oldId
  dbrw
  core
  manufacturer {
    id
    name
  }
  doorWidth
  doorType
  glass
  testBy
  testDate
  testId
  isAssessment
  file {
    url
  }
  }
}

Answer: While this answer addresses the specific issue of the question, the more general question -- where to dispatch a Redux action based on the result of a query -- remains unclear.  There does not, as yet, seem to be a best practice here.
Answer: It seems to me that, since Apollo already caches the query results in your store for you (or a separate store, if you didn't integrate them), it would be redundant to dispatch an action that would also just store the data in your store.
If I understood your question correctly, your intent is to filter the incoming data only once and then send the result down as a prop to the component's stateless children. You were on the right track with using the props property in the graphql HOC's config. Why not just do something like this:
const mapDataToProps = ({ data = {} }) => {
  const items = data
  const uniqueItems = []

  // insert your logic for filtering the data here

  return { uniqueItems } // or whatever you want the prop to be called
}

const withData = graphql(REPORT_FILTER_QUERY, {
  options: ({ isPublished }) => ({
    variables: { isPublished }
  }),
  props: mapDataToProps,
})

The above may need to be modified depending on what the structure of data actually looks like. data has some handy props on it that can let you check for whether the query is loading (data.loading) or has errors (data.error). The above example already guards against sending an undefined prop down to your children, but you could easily incorporate those properties into your logic if you so desired.
Comment: I updated the example to just use a default value for data. Let me know if you still can't get the expected behavior.
Comment: Thanks for this - I've updated my post with the original query but I'll not be able to give your solution a try until I get onto my machine a bit later.


Spherical coordinates in surface integrals

Question: I am stuck on the following problem
Evaluate :
$$I=\iint x^2 y^2 z dS $$
where S is the positive side of lower half of the sphere $x^2 + y^2 + z^2 = a^2$
I tried using spherical coordinates and their jacobians but cannot seem to find the answer which is $$I= \frac {2\pi a^7} {105}$$
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: What means ... positive side of lower half of the sphere?
Answer: Substitute $z=-\sqrt{a^2-x^2-y^2}$ and $dS=\sqrt{1+z_x^2+z_y^2}dA$. which turn $$I=-a\iint_{R} x^2y^2dA.$$ Use polar co-ordinate.$x=r\cos\theta, y=r\sin \theta$. $dxdy=rdrd\theta$. $r$ varies from $0$ to $a$ and $\theta$ varies from $0$ to $2\pi$. Which turn $I=-a\int_{0}^{2\pi}\sin^2\theta \cos^2\theta d\theta \int_{0}^a r^5 dr=\frac{-a^7}{6}\int_{0}^{2\pi}\sin^2\theta \cos^2\theta d\theta  =\frac{-a^7}{24}\int_{0}^{2\pi}\sin^2 2\theta d\theta=\frac{-a^7}{48}\int_{0}^{2\pi}({1-\cos4\theta}) d\theta=\frac{-a^7\pi}{24}$
Comment: I tried this method also ....... I am getting the same answer( a^2 )pi / 24
Comment: your answer must be wrong. power of $a$ must be $7$. It is easy to see.
Comment: Oh sorry my typo error it is (a^7) pi / 24
Comment: Textbook answer is wrong.
Comment: There are other questions also which are not reaching to their correct conclusion..... Should i post them too ?
Comment: And the solutions given are not like total outliers ..... They have the same variables as in the questions
Comment: which textbook?
Comment: Mathematical Analysis by SC Malik and Savita Arora page no. 668
Comment: Use standard books. Thomas Calculus is good.
Answer: Consider the following transformation:
\begin{equation}
\begin{split}
x&=a\sin\phi\cos\theta\\
y&=a\sin\phi\sin\theta\\
z&=a\cos\phi
\end{split}
\end{equation}
where $\theta\in[0,2\pi]$ and $\phi\in[-\frac{\pi}{2},0]$, then $dS=a^2\sin\phi\;d\phi\;d\theta$. Now
$$
\iint_Sx^2y^2z\:dS=a^7\int_{0}^{2\pi}\cos^2\theta\sin^2\theta\;d\theta\int_{-\pi/2}^0\sin^5\phi\cos\phi\;d\phi=a^7\bigg[\frac{\pi}{4}\bigg]\cdot\bigg[-\frac{1}{6}\bigg]=-\frac{\pi a^7}{24}.
$$
Note that
$$\int_{-\pi/2}^0\sin^5\phi\cos\phi\;d\phi=\int_{-\pi/2}^0\sin^5\phi(\sin\phi)'\;d\phi=\bigg[\frac{1}{6}\sin^6\phi\bigg]_{-\pi/2}^0=-\frac{1}{6}
$$


Specifying the length of an integer in hook_schema

Question: Why does Drupal not allow you to specify the integer length with type int in hook_schema?
Answer: Please see the Data Types documentation, I believe you can use tiny, small, medium, big, normal
Comment: My question was related to this issue.http://drupal.org/node/1477514


No GitHub, qual a diferença entre um projeto e um repositório?

Question: No GitHub, vi que posso criar um um repositório, mas também posso criar um projeto. Qual a diferença entre um e outro? Quando devo criar um projeto em vez de um repositório e vice-versa?
Answer: Existe uma confusão com o termo projeto na definição das duas coisas, isso porque geralmente se entende como projeto a pasta criada durante o desenvolvimento que contém os arquivos fontes.
De qualquer forma, aqui estão as definições utilizadas no GitHub:
Repositório
Pode ser comparado à pasta raiz do seu projeto, esteja ele na IDE ou em seu filesystem. Irá conter toda a estrutura de arquivos e documentação de seus fontes, bem como um sistema de versionamento para o mesmo.
É a estrutura mais básica do GitHub, normalmente os Projetos se baseiam no fluxo de atividades ocorrendo no Repositório para a organização das tarefas.

Projeto
Uma estrutura mais complexa que não envolve apenas a visão do código fonte, como a do repositório. Assemelha-se as ferramentas de gerenciamento e acompanhamento de projetos de software, isso envolve desde a criação de tarefas e o acompanhamento de seu andamento.
É bem interessante para manter a rastreabilidade de problemas e pull requests, bem como dividir as atividades e seguir um fluxo de trabalho dentro do GitHub. Conforme imagem abaixo, você pode ver um Kanban com as atividades

Você pode conferir o no glossário o termo repositório, o projeto foi introduzido depois e sua documentação se encontra aqui.
Um detalhe interessante é que projetos podem ser derivados de Repositórios ou Organizações, por exemplo, o repositório do spring-security não possui nenhum projeto, mas a Spring possui um projeto voltado para o time de segurança deles.
Quando devo criar um ou outro?
Caso você esteja buscando apenas versionar seus arquivos de forma simples e direta, vá de repositório.
Se dentro do seu repositório ou organização você gostaria de acompanhar o fluxo de trabalho de projetos (repositórios), bem como propor atividades e acompanhar o progresso das mesmas com seus colaboradores, crie um projeto.
Não existe regra para criação de um projeto, isso vai mesmo da necessidade do time que está trabalhando.


Theorem of perturbation of the identity

Question: I'm having troubles with the last statement of this question:

Let $\phi:A\to \mathbb R$ be a contraction defined in an open set
  $A\subset \mathbb R$. Prove the map $f:A\to \mathbb R$, defined by
  $f(x)=x+\phi (x)$ is a homeomorphism from $A$ to an open set $f(A)\subset \mathbb R$. Besides that, if $A=\mathbb R$, then $f(A)=\mathbb R$.

I need help with $f(A)=\mathbb R$. How can I prove that?
Thanks a lot
EDIT
Following the solution above, I'm trying to prove $f(x)-f(0)\geq (1-q)x$ for $x\gt 0$, where q is the contraction constant, if I prove this, the solution will come easily.
I need help in this part.
Thanks again
Comment: With "for any $x\in\mathbb R$" you probably mean "for all $x\in\mathbb R$", don't you? I think "any" is a bit ambiguous here.
Comment: @ElmarZander thank you
Answer: If you know that $\phi$ is a contraction on $\mathbb R$ you know that $f(x)-f(0)\geq (1-q)x$ for $x>0$, where $q$ is the contraction constant, and something similar for $x<0$. This should enable you to show that for arbitrarily large $M$ there is an $x^+$ such that $f(x^+)\geq M$, and $x^-$ such that $f(x^-)\leq -M$. Now use the fact that $\phi$ and thus also $f$ is an homeomorphism (i.e. continuity) to see that $[-M,M]\subset f(\mathbb R)$.
EDIT: to show the inequalities:
for $x\geq0$ we have $f(x)-f(0) = x + \phi(x) - \phi(0) \geq x - |\phi(x) - \phi(0)| \geq x - q|x| = (1-q)x$
for $x\leq0$ we have $f(x)-f(0) = x + \phi(x) - \phi(0) \leq x + |\phi(x) - \phi(0)| \leq x + q|x| = (1-q)x$, .
Comment: you removed the norm, is it correct? thank you for your answer
Comment: Yes, which is easy to do, since if you know that $|a|\leq b$ with $b\geq0$, then you know that $-b\leq a\leq b$, and the inequality follows by plugging in the definition of $f$ and the contraction inequality.
Comment: Are you sure that $f(x)-f(0)\geq (1-q)x$? I think the correct sense of the inequality is $f(x)-f(0)\leq (1-q)x$
Comment: Please, see my edit on this.

Theorem of perturbation of the identity


Colocar uma linha do GridView com cor vermelha caso uma célula tenha o valor falso

Question: Gostaria de que uma determinada linha de meu GridView fique vermelha caso a célula correspondente da coluna closed esteja com valor falso.
Meu ASP.Net está assim:
div class="GridMain">
                    <asp:GridView ID="gvInformationPeriod" runat="server" Width="100%" CssClass="GridViewUser" AllowPaging="True" CellPadding="4" AutoGenerateColumns="False"
                        GridLines="None" ForeColor="#333333" OnPageIndexChanging="gvInformationPeriod_PageIndexChanging" onrowdatabound ="gvInformationPeriod_RowDataBound" PageSize="100">
                        <AlternatingRowStyle CssClass="GridAlternativeUser" BackColor="White" />
                        <Columns>
                            <asp:BoundField DataField="PeriodID" HeaderText="PeriodID" />
                            <asp:BoundField DataField="SchoolID" HeaderText="SchoolID" />
                            <asp:BoundField DataField="DateOpen" HeaderText="Aberto Em" />
                            <asp:BoundField DataField="UserName" HeaderText="Usuario" />
                            <asp:BoundField DataField="PCName" HeaderText="PC Name" />
                            <asp:BoundField DataField="Closed" HeaderText="Closed" />
                        </Columns>
                        <EditRowStyle BackColor="#2461BF" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#62AFC1" CssClass="GridPagerUser" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#EFF3FB" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                    </asp:GridView>

Meu ASPX.CS carrega o GridView assim:
 private void ListarGridInformationPeriod()
    {
        if (ddlSchool.SelectedValue != "")
        {
            gvInformationPeriod.Visible = true;
            gvInformationPeriod.DataSource = Period.ListOpenPeriod(int.Parse(ddlSchool.SelectedValue));
            gvInformationPeriod.DataBind();
        }
    }

protected void gvInformationPeriod_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (!string.IsNullOrEmpty(ddlSchool.SelectedValue))
        {
            gvInformationPeriod.PageIndex = e.NewPageIndex;
            gvInformationPeriod.DataSource = Period.ListOpenPeriod(int.Parse(ddlSchool.SelectedValue));
            gvInformationPeriod.DataBind();
        }
    }

Pensei em colocar alguma coisa conforme abaixo usando o RowDataBound mas não funcionou
protected void gvInformationPeriod_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Equals("false"))
            {
                e.Row.BackColor = Color.Red;
            }
        }
    }

Tentei usar o conteúdo desse post mas não entendi bem

https://stackoverflow.com/questions/5048762/change-gridview-row-color-based-on-condition-in-c-sharp
Answer: Solução:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           if (e.Row.Cells[1].Text.Equals("false"))
           {
                e.Row.BackColor = Color.FromName("red");
           }
      }
}

Aonde o 1 seria a segunda coluna do seu GridView.
Answer: Você quase acertou faltou falar qual campo vc quer especificar o valor.
Ex: Quando o valor da coluna for false fica vermelho a linha.
ambos em  protected void GridView1_RowDataBound
Modo 1:
Label lbl1= (Label)e.Row.FindControl("Closed");
if(lbl1.Text = "false")
{
e.Row.BackColor = System.Drawing.Color.Red;
}

Modo 2:
DataRow dr = ((DataRowView)e.Row.DataItem).Row;
  if (dr[1].ToString() == false) //o número é o ID da coluna [0,1,2, etc
{
//seu código
}

Comment: manda bala que vai funcionar perfeitamente.
Comment: Eu quero 'pintar de vermelho' toda a linha que contiver o valor na coluna Closed como false. Valeu.


Is it okay to be learning to program for iOS with an iOS 5 book?

Question: I'm learning some iOS development lately, but I'm learning it from an iOS 5 book, as it's well-written and well-received and I can't find many iOS 6 books out yet.
However, with iOS 6 being out, is it smart to be learning a book on iOS 5? I know iOS 4 to iOS 5 was a big jump in terms of APIs, with ARC being introduced and all. This isn't the same thing for iOS 5 - iOS 6, is it?
If I learned from an iOS 5 book would I be missing out on some really radical changes introduced in iOS 6? Or would I likely be fine?
Answer: There are less radical changes to the API, that's true. Auto-Layout it probably the biggest change. The rest are additions that you can check out later, like Pass Kit, Reminders API, UICollectionView or better social integration.
I wouldn't worry too much about an iOS 5 book being out-dated, if it's good. Make sure it teaches ARC and don't spend too much time learning autoresizing masks (not that it would be very complicated, but Auto-Layout is a better choice now).


Area under curve: integration

Question: I am a student. I was recently taught about application of integrals
case 1:
When curve $y=f(X)$ lies above the $X$ axis
the area under curve is calculated using integration

$\text{area} = \int y\,\text dx$ with some limits

Similarly:
case 2:
When the curve $y=f(X)$ lies below the $X$ axis
The area under curve is calculated using integration

$\text{area} = \int -y\,\text dx$ with some limits

So my question here is :
If we have to calculate area bounded by parabola $y^2= 16x$ and its latus  rectum we find the area above the $X$ axis by using the  equation and multiply it by 2
The equation here represents the parabola and integrating the equation with proper limits should give the area of all of the required region
That is region above and below the $X$ axis
Then why we multiply the result of integration by 2.
Answer: When they say

case 1:
When curve $y=f(X)$ lies above the $X$ axis
the area under curve is calculated using integration

$\text{area} = \int y\,\text dx$ with some limits

They actually mean

case 1:
When curve $y=f(X)$ lies above the $X$ axis
the area between the curve and the $x$-axis is calculated using integration

$\text{area} = \int y\,\text dx$ with some limits

So when you're integrating you're only getting half the area:

and naturally, you need to multiply that by $2$ to get all of it.
Also, remember that the actual integrand in question here is not $y^2 = 16x$, because that's not of the form $y = f(x)$ as requested from the cases. It's actually $y = 4\sqrt{x}$, which is only the upper half of the parabola I've sketched above. That makes it a bit more obvious why you don't get all of it; when integrating $y = 4\sqrt x$, your expressions have no way of knowing that it is only half of something bigger, and it especially can't know that the other half is the exact mirror image. So it does the best it can and finds the area down to the $x$-axis instead.
Answer: The curve $y^2=16x$ does not represent a function $y=f(x)$ (it fails the vertical-line test), but it can be broken down into two curves $y=4\sqrt x$ and $y= -4\sqrt x$. Each of these is a function: $g(x) = 4\sqrt x$ is above the $x$-axis and $h(x) = -4\sqrt x$ below.
To find the total area between $g(x)$ and $h(x)$, we need to add the area between $g(x)$ and the $x$-axis to the area between $h(x)$ and the $x$-axis, which would involve computing $\int g(x)dx + \int -h(x)dx$.
Alternatively, we can note by symmetry that these two component areas are the same, so we can just compute one of them and multiply by $2$: use $2\int g(x)dx$. This is where the $2$ comes from
Comment: @ShantanuKaushik You're welcome!

Area under curve: integration


PDO - Insertion (INSERT INTO...) code doesn't work

Question: I'm trying to insert the current date/time to the database as the last time the user logged in. For some reason this doesn't work.
Other insertion scripts running on the very same page work well, and the connection is ok.
I use the same syntax to insert other stuff throughout the whole site, so I don't get what's wrong.
I can guarantee that the else part is being executed when I'm entering my password.
Here's the piece of code I am talking about.
if(!$pwVer){
     // code to execute if the password is incorrect.
} else {

    $dateT = date("Y-m-d H:i:s");

    $up_date = $con->prepare("INSERT INTO tbl_user_test (user_last_login) VALUES (:l_login)");
    $up_date->bindParam(':l_login', $dateT);

    $up_date->execute();

    validateUser($userid); //sets the session data for this user

    header("Location: cart.php");
    $con = null;
    die();
}

Some background:

$pwVer returns `true` if the password is correct.
both `tbl_user_test` and `user_last_login` are written exactly as they're in the database.

Thanks in advance!
Comment: Does the table `tbl_user_test` have only the `user_last_login` column? If you don't insert some info like `user_id`, what dose this table pretend to be?
Comment: Try put `var_dump($up_date->errorInfo());` after the `$up_date->execute();` line, and tell us what it says.
Comment: @xdazz thanks! LOL I completely forgot that this is supposed to be a user specific thing... I should've added a `WHERE` part!
Comment: No, actually this doesn't work as well.
Answer:
I'm trying to insert the current date/time to the database as the last time the user logged in. For some reason this doesn't work.

There is no error visible in your code, so it should be executed. One possible problem could be that PDO is in silent mode, which doesn't tell you what or if an error has occured. Set PDO to fail with an exception.
Also, there's no need to construct the current date yourself; you can use SQL's NOW().
<?php
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try {
    $up_date = $con->prepare("INSERT INTO tbl_user_test (user_last_login) VALUES (NOW());");
    $up_date->execute();
}
catch( Exception $e ) {
    echo $e; exit;
}

header("Location: cart.php");
$con = null;
die();

Comment: Thank you! I solved my problem thanks to your answer :) I think the problem was that I didn't define which row I actually want to update. So I used your code syntax and changed the sql to an `UPDATE` + `WHERE` clause.
Answer: Did you try NOW() for the current date time ?
Answer: Once check with this
$up_date->bindParam(':l_login', $dateT, PDO::PARAM_STR);


Transformar texto de uma string em imagem

Question: Olá, eu estou desenvolvendo um app e preciso, em certo ponto, pegar uma string que contém dados de um comprovante e transformar esse texto em uma imagem do comprovante e em seguida compartilhar essa imagem via whatsapp. Eu nunca fiz algo do tipo e depois de algum tempo pesquisando não cheguei à uma solução satisfatória. O comprovante teria o formato abaixo:

"##########################Central Jogos##########################Apostador: testValor Apostado: R$5Valor Retorno: R$6.15Data Aposta: 19/02/2017 15:07Qtd. Jogos: 1-----------------------------------------Vasco X FlamengoEmpate: 1.2310/03/2017 15:30=======================Cambista: Cambista TesteTelefone: (82) 9977-8877"
Answer: Você pode utilizar o elemento canvas para gerar a imagem, como no exemplo abaixo:

var canvas = document.getElementById("receipt");
var context = canvas.getContext("2d");

const messages = [
  "################################",
  "Central Jogos",
  "################################",
  "Apostador: test",
  "Valor apostado: R$ 5,00",
  "Valor de retorno: R$ 6,15",
  "Data da aposta: 19/02/2017 15:07",
  "Quantidade de jogos: 1",
  "--------------------------------",
  "Vasco X Flamengo",
  "Empate: 1.23",
  "10/03/2017 15:30",
  "================================",
  "Cambista: Cambista Teste",
  "Telefone: (82) 9977-8877"
];

context.font = "12px Courier new";

y = 12;
for (var i in messages) {
  context.fillText(messages[i], 0, y);
  y += 18;
}

document.getElementById("result").src = context.canvas.toDataURL();
h1 {
  font-size: 16px
}

div {
  float: left;
  padding: 20px;
}

Canvas:

  <canvas id="receipt" width="230" height="270"></canvas>

Resultado:

Nota: Ao executar o código acima, será gerada a saída no console no formato data:image/png;base64,.... Para testar, você pode copiar esta mensagem e colar diretamente no navegador. Se tudo deu certo, verá a imagem do recibo em formato PNG.

Basicamente é uma lista com as mensagens, que pode ser gerada dinamicamente. É recuperado o elemento canvas e seu context, definido a fonte Courier New 12px, porque é monospace e gera um resultado melhor visualmente, percorrido a lista e adicionado ao canvas na posição (0, y), onde y é incrementado em 18 para manter um pequeno espaçamento entre as linhas. No final, recupera-se o valor de context.canvas.toDataURL que nada mais é que a imagem gerada.
Porém, fico te devendo como enviá-la pelo WhatsApp, pois isso já saiu do meu conhecimento. Se alguém souber e quiser editar a resposta, fique a vontade.
Comment: Muito obrigado mesmo pela resposta, vou tentar implementar no app e dou o retorno mas testando no navegador já vi que funciona perfeitamente.
Answer: A primeira parte da minha pergunta foi respondida pelo Anderson, já a parte de enviar o base64 pra o WhatsApp eu achei a solução com o plugin phonegap Social Sharing. Dá pra fazer compartilhamento de PDF, imagem, links e etc.


elasticsearch json array field

Question: My field in Elasticsearch is complex JSON array, please see the sample below
[
  {
    "row": [
      {
        "symbol": "777"
      },
      {
        "symbol": "555"
      },
      {
        "symbol": "Jack"
      },
      {
        "symbol": "Jack"
      },
      {
        "symbol": "Queen"
      }
    ]
  },
  {
    "row": [
      {
        "symbol": "Ace"
      },
      {
        "symbol": "Banana"
      },
      {
        "symbol": "999"
      },
      {
        "symbol": "Mouse"
      },
      {
        "symbol": "Milk"
      }
    ]
  },
  {
    "row": [
      {
        "symbol": "999"
      },
      {
        "symbol": "Ten"
      },
      {
        "symbol": "Mouse"
      },
      {
        "symbol": "Fish"
      },
      {
        "symbol": "Banana"
      }
    ]
  }
]

I need to either be able to write a query in Kibana to directly get an access to each count of symbol on each 'row':
or ideally I would like to write a correct es.mapping so I can read the data from ES in Pig script.
I tried the following
data = load 'my_index/my_type' USING EsStorage('es.query:?q=*', 'es.mapping.names=row:row') as (row:map[]);

it doesn't work, please advice.
Answer: It's simple, as row.symbol = '999' in Kibana.
So row.symbol = '999'will do the trick of counting all the documents that contain 999 symbol.

elasticsearch json array field


jQuery, dynamic name change of radio button

Question: Looking for something like:
$("input:radio:checked").previous("name", "original_name").attr("name","new_name");

I tried a few different seen around here but mostly get the error: Object Expected
Any help is appreciated.
Comment: Mind if I ask why you'd like to dynamically change the name of a radio button?
Comment: Why don't you just check to see if the radio button is checked in the cgi? If was checked, then its name would have changed, you're in the same state. Also, what if your users aren't using javascript? Then your page breaks.
Comment: I have two different actions available for the 1 selected input.
Comment: I fail to see how that requires renaming a radio button.
Comment: The input is being sent to a cgi. I need to distinguish the name of the radio button selected with a different submit, for different functionality, don't want more radio buttons on the UI.
Comment: Well, is there a better way? Say you have a selection of radio buttons (yes, can only select one) stock1, stock2, stcok3, stock4. Then the option (submit) to buy more or sell......
Comment: Why don't you have a radio button group for buy/sell and a multiple select box or checkboxes for the stocks?
Comment: "and a multiple select box or checkboxes for the stocks?" <--then that would mean they could select more than 1 stock. Should only be able to select 1
Answer: As Ben S wrote in the comment to your original question, why do you need to change the name?
Let's say you have
<input type="radio" name="myRadio" id="radioChoice1" value="radioChoice1Value" />
<input type="radio" name="myRadio" id="radioChoice2" value="radioChoice2Value" />

If user selects 'radioChoice1' and clicks submit, browser will send
myRadio=radioChoice1Value to your CGI script. You can process this as you desire.
In case you insist on changing the name attribute, I am not sure what is the 'previous' method in your code.
Can you try,
$("input:radio:checked").attr("name","new_name");

And see if it works?
I can imagine that there could be cross browser problems if you try to change the name attribute.
You can create a hidden input and store the name of the radio button selected by the user.
<input type="hidden" id="selectedRadioButton" />

$('#selectedRadioButton').val($("input:radio:checked").attr('name'));

EDIT:
Please post your HTML so that I can tell you what kind of values will be posted to CGI.
For example if you have
<input type="radio" name="transactionType" id="buy" value="buy" />
<input type="radio" name="transactionType" id="sell" value="sell" />

If user clicks on the first radio button 'buy', then in your CGI script value for 'transactionType' will be 'buy'.
Comment: $("input:radio:checked").attr("name","new_name");
object error
Comment: how would the cgi know to execute the buy or sell function with myRadio=radioChoice1Value? What differentiates that?
Comment: That was just an example. Post your HTML so that we can discuss more. Also, I updated my answer with another example.
Answer: Here's a jQuery script that does the job requested. I'm using it to rename all the input=text fields on a form. Though I'm not doing anything with radio or checkbox, I added the relevant case statements. Insert your radio/checkbox transforms as needed.
    function renameTextInputFields(ele) {
        var i = 0;
        $(ele).find(':input').each(function() {
            switch(this.type) {
                case 'text':
                    $(this).attr("name","textFieldNumber"+(++i));
                    break;
                case 'checkbox':
                case 'radio':
            });
    }

Call this method on a DOM element. Myself, I'm making a clone of a div within a form. The div has lots of text fields. I get the base element like so.
var clone = $('.classAssignedToMyDiv').clone();

It runs fine in both IE 8.x and Firefox 3.x
Answer: I agree with the others that there is a better solution than to rename the input.
Having said that, and to answer your original question - I suggest that you assign ids to your radio inputs, and then use this code:
$("#inputId").attr("name","new_name");

I don't understand your use of .previous() - I can't find it in the jQuery documentation.


Exibir tela de dialogo para fazer o download com javascript

Question: Tenho um projeto em MVC onde tem um botão que faz o download de arquivos porém ao clicar no botão é aberto uma nova guia no navegador e os arquivos são baixados automaticamente, como nos exemplos demonstrados nesse link:
https://www.w3schools.com/jsref/met_win_open.asp
O meu código funciona perfeitamente:
var url = "http://10.155.XXX.XXX/site_do_fornecedor/arquivo_para_download.aspx?id="
window.open(url + 10 + '10/12/2019', "_blank", "width=200, height=100");
Porém gostaria que fosse exibida a tela de diálogo onde o usuário decida em que diretório salvar os arquivos.
Exemplo
Quando clico no botão download é executado o código javascript descrito anteriormente e a uma janela do chrome é aberta:

Como faço pra essa janela do navegador não ser exibida ?
Implementei a sugestão muito interessante do Daniel Mendes:
function downloadMP3(_url, _strArrId, _data) {

    fetch(_url + _strArrId + "&Date=09/12/2019")
        .then(data => {
            data.blob()
                .then(blob => {
                    const url = URL.createObjectURL(blob);
                    const link = document.createElement("a");
                    link.href = url;
                    link.download = url;
                    link.click();
                })
                .catch(error => {
                    console.log(error);
                });
        })
        .catch(error => {
            console.log(error);
        });
}

Porém foi exibida a seguinte mensagem de erro:

Pelo que vejo a URL de destino tem que habilitar o CORS é isso mesmo ?
Comment: Por código puro acho que não é possível exibir o diálogo de salvar como. A única maneira que vejo é se o usuário instalar uma extensão no navegador que permita o código chamar o diálogo através da API [downloads](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads).
Answer: Hard,
Se você se refere a dialog do navegador que permite escolher onde salvar o arquivo, isso é uma opção do próprio navegador, onde existe uma configuração que o navegador efetua o donwload de forma automática, sem exibir a dialog e salvando na pasta definida também nas configurações do mesmo:

Existe a possibilidade de você criar a sua dialog de confirmação, porém com isso, o usuário pode acabar tendo que confirmar duas vezes e você não consegue interferir no local onde o arquivo será salvo.
Para essa confirmação, o próprio javascript já tem métodos para isso:

confirm("Efetuar o download?");

https://developer.mozilla.org/pt-BR/docs/Web/API/window/confirm

Agora caso o problema seja a sua própria dialog criada pelo window.open, você pode refatorar o código, removendo a sua dialog e criando por exemplo uma tag  temporária e efetuar o click na mesma, veja um exemplo abaixo:

function download() {
  fetch("https://developer.mozilla.org/static/img/embed/promos/devedition-logo.63846dba2e2f.png")
  .then(data => {
    data.blob()
    .then(blob => {
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");

      link.href = url;
      link.download = "63846dba2e2f.png";

      link.click();
    })
    .catch(error => {
      console.log(error);
    });
  })
  .catch(error => {
    console.log(error);
  });
}
<button onclick="download()">Fazer download</button>
Comment: Isso realmente precisa ser visto, você precisa ver se precisa enviar algum header também etc.
Comment: Olá @Daniel Mendes obrigado pela sua colaboração, mas não é bem essa minha dúvida. Eu atualizei o meu post e adicionei uma imagem.
Comment: veja que quando eu clico no botão Download é executado um javascript direcionando pra uma URL e uma janela do navegador é aberta.
Comment: @hard123 criei um exemplo de download com javascript sem utilizar a window.open, espero que lhe ajude.
Comment: Obrigado! @Daniel Mendes vou implementar e depois dou um retorno aqui sobre o resultado !
Comment: implementei a sua sugestão e pelo erro retornado falta habilitar o [CORS](https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api)


Why is the compiler not optimizing this simple idiom?

Question: I have this code and I'm wondering why the compiler doesn't join the two character compares to a 16-bit compare.
inline bool beginswith (char c0, char c1, const char* s) {
    return (s[0] == c0) & (s[1] == c1);
}

bool test(const char* s) {
    return beginswith('0', 'x', s);
}

I would expect the two versions in my Godbolt link (test and test2) to compile to equivalent instructions. Is there something I'm missing because this seems like a pretty trivial optimization.
Edit: The reason I would like the compiler to do this optimization is so I can write portable code with no undefined behavior and still get full performance.
Comment: My guess is, that the compiler  does not do this optimization because here `*(const short*)s == (c0 | (c1 << 8));` an unaligned access might happen, which can have a huge performance penalty compared to the byte access version
Comment: @Ayxan: Doesn't matter. Compilers are allowed to define and therefore exploit UB; it's just the programmers who are not allowed to.
Comment: I've managed to make GCC output identical assembly with `char const b[]{c0, c1}; return !std::memcmp(b, s, sizeof b);`. MSVC is unphased.
Comment: `beginswith2` is undefined behavior. Depending on the endianess of your machine, you either compare `c0`/`c1` with the msb/lsb of s...
Comment: `const char* s = "_x"; beginswith('x', 'X', s+1);` <- `char` access to `s+1` si faster (at the hardware level, on some archs) than `short` access. The difference in output assembly might reflect that difference.
Comment: @SanderDeDycker Using `&&` introduces a branch so this might be an optimization. See the OP's godbolt, swapping to `&&` gives far worse code, simply because of the required "short circuit evaluation".
Comment: @KonradRudolph, compilers accessing `short *` use word access because usually almost all pointers to `short` aligned at boundary of 2. Even if it is unaligned it usually programmers problem, not compilers. But when you access `char *` you do not have such guarantee. And in unaligned case it will be indeed slower on some (most modern?) architectures than byte access.
Comment: @Ctx I tried __builtin_assume_aligned in gcc and clang and it doesn't change the generated instructions so it doesn't seem to be related to alignment.
Comment: @Ctx isn't `*(const short*)s == ...` UB? You're accessing the object as if it were some other type.
Comment: @YSC Unlikely, given that GCC and clang transform a fixed-sized `memcmp` to the same output as the `short` aliasing compare, rather than performing indexed access.
Comment: @sklott You misunderstood my comment. The compiler transforms `char c[] = {c0, c1}; return memcpy(c, s, 2) == 0;` into the same code as the `short` aliasing compare. Meaning, the compiler determined that the fastest way of implementing the memcmp is *not* via pointer increment, as hypothesised by YSC, but by performing a word-wise compare. This *might* mean that the compiler can prove that the memory is properly aligned for such access, but whether that's the case is irrelevant for my comment; all that matters is that the compiler does this.
Comment: An optimization heuristic to replace multiple comparisons with one `memcmp` doesn't seem to exist.
Comment: Quick question: are you sure the `short` version actually _is_ faster? The `MOV->XOR` dependency chains should be very parallelizable, so I think it ends up only one instruction worse, and it's anyone's guess how long that really takes without benchmarking.
Comment: I can't think of any technical reason. Probably this is just such a rare case that no compiler vendor has bothered to create optimizations for it.
Comment: Dereferencing a pointer with a type other than what it actually points to is undefined behaviour.  You can't make any assumptions as to why is producing code in one way or another. The resulting code can perfectly crash your program or _make demons fly out of your nose_.
Comment: @Lundin : you are of course absolutely right. My gut reaction that the compiler would find it harder to optimize with the `&` was clearly wrong - time to re-calibrate my gut :)
Comment: @Bathsheba - programmers are allowed to write code with undefined behaviour, or that exploits undefined behaviour.   The catches include the standard not providing them any guarantees concerning what happens (by definition) and there is the possibility of their code working differently (or not at all) with different compilers/libraries or versions of compilers/libraries or the phase of the moon.   But, if they accept those consequences, there is nothing preventing them doing it.
Comment: @christianO Kindly stop adding the C tag. According to our cross-tagging rules for C and C++, which you can find under the respective [tag wiki](https://stackoverflow.com/tags/c%2b%2b/info), a program that is compiled as C++ should be tagged C++ only. In this specific case the `bool` type, the character constant type and the type punning rules are _different_ between C and C++. As are `aligas`, `alignof` and misc other stuff that may or may not be relevant.
Answer: It appears that the compilers simply aren't smart enough to treat inlining as a special case here. They generate the very same code as they do when the function has external linkage, in which case there is no connection assumed between the parameters c0 and c1.
Inside the function, c0 and c1 reside in local copies according to ABI calling convention, which isn't necessarily placing them next to each other for aligned access - even though that does happen to be the case in your specific x86 example.
Changing the caller code to alignas(int) char str[2] = {'0', 'x'}; return beginswith(str[0],str[1],s); doesn't make a difference, so alignment doesn't seem to be the (sole) reason either.
However, in case you change the function to this:
inline bool beginswith (char c0, char c1, const char* s)
{
    char tmp[2] = {c0, c1};
    return memcmp(tmp, s, 2);
}

Then you get identical machine code in both cases (godbolt].
test(char const*):
  cmp WORD PTR [rdi], 30768
  setne al
  ret

It should be noted that *(const short*)s in test2 is undefined behavior, a strict aliasing violation. The machine code for that line may not stay deterministic when the program starts to scale up or when optimizer settings are changed. This is mostly a quality of implementation thing, where the standard makes no guarantees and test2 might break at any point.
Comment: The parameter passing is a red herring. You can change the parameters to a `char const (&)[2]` in C++, yet the compiler still doesn't merge the comparisons. there simply seems to be no rule in the optimiser that would merge such comparisons.
Comment: @MaximEgorushkin Not this again... No they _cannot_. You can go from pointer-to-type to pointer-to-char and then de-reference as character type **but not the other way around**. [What is the strict aliasing rule?](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule).
Comment: Yes, but that's only valid if the original buffer really is an array of short. If you have an array of double, and cast that to `char*`, then accessing it as a `short` elsewhere as an optimization could be problematic. Admittedly, unless it gets inlined in a context where it's also being mutated via `double*`, it might not break anything.
Comment: Note: in C you might have been able to dodge that undefined behavior with union type punning, but that isn't possible to do in C++.
Comment: In your alignment example the data pointed to by `s` is still unaligned.
Comment: @MaximEgorushkin From the language standard, namely C11 6.5/7. "An object shall have its stored value accessed only by an lvalue expression that has one of
the following types: ... a character type." This special case exception does _not_ somehow mean that the other way around is suddenly ok too and an object of type char can have its value accessed by any type.
Comment: @MaximEgorushkin Ok so care to tell me how C++11 3.10/10 is any different? "If a program attempts to access the stored value of an object through a glvalue of other than one of the
following types the behavior is undefined: ... a char or unsigned char type." Because that looks pretty much identical to me.
Comment: https://gist.github.com/shafik/848ae25ee209f698763cffee272a58f8
Comment: @MaximEgorushkin All that's saying is that C++ doesn't have the concept of effective type. Which doesn't matter. How exactly does that make accessing a char array through `*(banana_t*)array` well-defined?
Comment: @Lundin Okay, I withdraw my argument.


How to interpret output from forecast package

Question: The forecast package has the function auto.arima and forecast to model time-series. Understanding the output is proving difficult for me. Particularly, the model selection nomenclature.

What does ARIMA(2,0,2)(1,0,0)[12] with zero mean stand for?
Let's be clear, I understand the ARIMA(p,d,q) format. p is the autoregressive component, d is the degree of difference, i.e. integration component, and q stands for the moving-average component. So I understand the basics of what makes up an autoregressive integrated moving-average model.
I am asking specifically about the use of two arima models side by side, [12], and with zero mean. Did auto.arima have a tie with the best models and used both? First a lag of 2 then a lag of one? Then use 12 as the season frequency for annual seasonality and change a regular mean to zero?
Reproducible example:
ts.count <- structure(c(899, 567, 590, 162, -68, -142, -34, -6, 41, 56, 38,
34, 168, 405, 425, 385, 304, 694, 531, 766, 792, 585, 236, 648,
813, 990, 776, 947, 599, 651, 1317, 1066, 1212, 1232, 621, 1945,
2676, 3102, 2798, 2388, 1833, 1533, 2749, 1428, 2272, 2390, 1126,
2634, 3553, 4182, 4553, 4419, 3686, 3380, 3862, 4288, 4850, 4228,
2696, 5109, 8571, 9039, 7997, 6537, 5519, 4722, 5374, 5841, 7290,
5419, 835, 4606, 10823, 15203, 15018, 14147, 13593, 15166, 12813,
16114, 14261, 9933, 7218, 10873, 18894, 30201, 27298, 22505,
13526, 16945, 13409, 27298, 27313, 31355, 29437, 41552), .Tsp = c(2008.08333333333,
2016, 12), class = "ts")

plot(forecast(auto.arima(ts.count)))

Answer:
What does ARIMA(2,0,2)(1,0,0)[12] with zero mean stand for?

You got a seasonal ARIMA (i.e. SARIMA) model with regular orders $(p,d,q)=(2,0,2)$, seasonal orders $(P,D,Q)=(1,0,0)$ and seasonal period 12 (e.g. monthly data). There is no intercept in the model (the intercept was set to zero).

I am asking specifically about the use of two arima models side by side, [12], and with zero mean. Did auto.arima have a tie with the best models and used both? First a lag of 2 then a lag of one? Then use 12 as the season frequency for annual seasonality and change a regular mean to zero?

You got one model, namely, ARIMA(2,0,2)(1,0,0)[12] with zero mean -- not two models side by side.
with zero mean just means there is no intercept in the model and the unconditional mean of the series is modelled to be zero.
[12] is just the seasonal frequency.

See Hyndman & Athanasopoulos "Forecasting: Principles and Practice" section 8.9 "Seasonal ARIMA models". See also this post and this post for mathematical representation of particular seasonal ARIMA models.
Comment: You are very welcome!


How to access web page on a server using the IP 10.0.0.3?

Question: I have three internal servers that will never have any connection to the internet.  I've had to build a local yum repo to set them up with tools like bugzilla and the like.  However, all three are connected together and I connect to them through an ethernet connection that hooks straight into my laptop.
On one of the servers, I would like to run web sites for others to see internally when they also hook into the ethernet connection. I've installed httpd and started it, but going to the a webpage on my laptop and trying to summon 10.0.0.3 does not bring up anything.
I'm assuming that my laptop thinks I'm looking at it's web server and has no idea how to access the other server.  This is a Cent OS server I want to use for internal web pages, btw.  How can I get DNS set up on this air gapped server, only accessible by ethernet so I can server web sites on it?
I've specified the vhost as 10.0.0.3:80 and also have the Listen on 10.0.0.3:80, but I know I'm missing something else that's crucial here.
Answer: have you verified if the IPtables are not blocking the port 80 from streamin outside localhost?
iptables -L

try this and see if you have the port available to the LAN
UPDATE
as Jake mentioned, you can open the port by
iptables -I INPUT -p tcp --dport 80 -j ACCEPT

this should be more then enough.
Comment: That was it!  I always forget about the iptables.  Thanks!
Answer: also, if you are interested in exploiting the DNS option.
I used this link to answer the concern
http://www.broexperts.com/part-3-bind-server-installation-configurations/
Comment: Thanks.  I can't try any of the suggestions until I'm back at work tomorrow, but this ^ looks helpful....
Answer: From the client machines, run NMAP to see if port 80 is open:
nmap 10.0.0.3 -p80

If it is not open, the response will be something like this. Meaning something is blocking port 80:
PORT   STATE  SERVICE
80/tcp closed http

What you want to see is:
PORT   STATE  SERVICE
80/tcp open http


Don't understand cause of TypeError about number of arguments when attempting to create instance of class

Question: Main code that is a BankAccount class that has the following attributes
listed in the function:
class BankAccount():
    #Implementation of __init__ function
    def __init__(self):
        #Declare balance and initialize with 0.0
        self.balance =0.0
        #Declare transaction_history as type of list
        self.transaction_history=[]

    #Implementation of get_balance method
    def get_balance(self):
        #check self.balance is equal to ""
        if self.balance == "":
            #Display an error message through TypeError
            raise TypeError("You must enter a number")
        return self.balance

    def set_balance(self,balance):
        #check balance is equal to ""
        if balance == "":
            #Display an error message through TypeError
            raise TypeError("You must enter a number")

        #check balance is less than 0 or not
        if balance<=0 or not isinstance(balance,float) :
            #raise an error message
            raise ValueError('Error: Not greater than 0')
        else:
            #assign balance to self.balance
            self.balance=balance

    #Implementation of get_transaction_history method
    def get_transaction_history(self):
        #check self.transaction_history is equal to ""
        if self.transaction_history == "":
            #Display an error message through TypeError
            raise TypeError("You must enter a number")
        return self.transaction_history

    #Implementation of set_transaction_history method
    def set_transaction_history(self,transaction_history):
        #check transaction_history is equal to ""
        if transaction_history == "":
            #Display an error message through TypeError
            raise TypeError("You must enter a number")
        self.transaction_history.append(transaction_history)

    #Implementation of get_avg_transaction method
    def get_avg_transaction(self):
        #check length of self.transaction_history is equal to 0
        if len(self.transaction_history)==0:
            #Display an error message through ValueError
            raise ValueError('Error: No transactions have been made\n')

        #return the resultant value of
        # sum(self.transaction_history)/len(self.transaction_history)
        return sum(self.transaction_history)/len(self.transaction_history)

    #Implementation of despost method with parameter amount
    def deposit(self,amount):
       if amount is not None:
           #Display statement
           print("Error: Not greater than 0")

       #Display statement
       print('You must enter a number\n')
       #calculate self.balance
       self.balance = self.balance + amount
       #append the amount to self.transaction_history
       self.transaction_history.append(amount)

    #Implementation of withdraw method with parameter amount
    def withdraw(self,amount):
        if (not isinstance(amount,float) and not isinstance(amount,int)) or amount<=0:
            #Display an error message through ValueError
            raise ValueError('Error: Not greater than 0')
        else:
            #calculate self.balance
            self.balance= self.balance - amount
            #call set_tranasaction_history method
            self.set_transaction_history(-amount)

Test Code:
from Lab5_Error_handling import BankAccount

if __name__ == '__main__':
    # Create the bank account
    print("Creating the bank account:")
    bank_account = BankAccount(100)

    # Attempt to get average transactions
    print("\nGetting the average transactions (first time)")
    try:
        print(bank_account.get_avg_transaction())
    except AssertionError:
        print("Error: No transactions have been made")
    except:
        print("YOU HAVE DONE SOMETHING WRONG; YOU SHOULD NOT BE SEEING THIS")

    # Deposit money
    print("\nDepositing money")
    try:
        bank_account.deposit(-200)
    except AssertionError:
        print("Error: Not greater than 0")
    except:
        print("YOU HAVE DONE SOMETHING WRONG; YOU SHOULD NOT BE SEEING THIS")

    # Deposit money
    print("\nDepositing money")
    try:
        bank_account.deposit("200")
    except TypeError as e:
        print(e)
    except:
        print("YOU HAVE DONE SOMETHING WRONG; YOU SHOULD NOT BE SEEING THIS")

    bank_account.deposit(200)
    # Withdraw money
    print("\nWithdrawing money")
    try:
        bank_account.withdraw("100")
    except TypeError as e:
        print(e)
    except:
        print("YOU HAVE DONE SOMETHING WRONG; YOU SHOULD NOT BE SEEING THIS")

    print("\nWithdrawing money")
    try:
        bank_account.withdraw(100000)
    except AssertionError:
        print("Error: Not greater than the balance")
    except:
        print("YOU HAVE DONE SOMETHING WRONG; YOU SHOULD NOT BE SEEING THIS")

    bank_account.withdraw(100)

    # Get average transactions
    print("\nGetting the average transactions (second time)")
    try:
        print(bank_account.get_avg_transaction())
    except AssertionError:
        print("Error: Not greater than 0")
    except:
        print("YOU HAVE DONE SOMETHING WRONG; YOU SHOULD NOT BE SEEING THIS")

    # Get Balance
    print("\nBalance: ",bank_account.get_balance())

I am getting this error though:
line 6, in <module>
    bank_account = BankAccount(100)
TypeError: __init__() takes 1 positional argument but 2 were given

How would I get rid of this error? Would I need to add something to the __init__() function or is there something wrong entirely with my code?
Comment: Have a look at the BankAccount init method. It always initialises the balance to 0. It doesn't accept a number as an argument. If you want it to do something different, rewrite it to do that.
Comment: you're passing `100` to your `BankAccount` class initialization, but it expects no arguments (`    def __init__(self):`) (or, it expects 1 `self` but it's getting 2, `self` and `100`)
Comment: The short answer is to change `BankAccount(100)` to `BankAccount()` since `__init__()` only declares the `self` argument which is passed in automatically. For a longer answer, what are you trying to do by passing in `100`? The answer to this question will help us give a more complete answer.
Comment: Does this answer your question? [\_\_init\_\_() takes 1 positional argument but 2 were given](https://stackoverflow.com/questions/40312491/init-takes-1-positional-argument-but-2-were-given) (It's the same problem/example with BankAccount class and `__init__ (self)`.)
Comment: Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE).
We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points.  This lets us test our suggestions against your test data and desired output.
The error message is clear, especially after you look up the meaning on line.  Where are you confused.
You posted over 10 lines of code for a 10-line problem; this is excessive.
Comment: @Code-Apprentice the answer to this question is. Creating the bank account:

Getting the average transactions (first time)
Error: No Transactions have been made

Depositing money
Error: Not greater than 0
You must enter a number

Depositing money
Error: Not greater than 0
You must enter a number

Withdraw Money:
Error: Not greater than 0
You must enter a number

Withdrawing money
Error: Not greater than the balance

Getting the average transactions (second time)
50.0

Balance:  200
Comment: Off-topic: The code in your class definition shouldn't have been double spaced like that—it actually makes it less understandable—and many (most?) of the comments it in are either useless or redundant (or both). Strongly suggest you read and start following the [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/).
Answer: The error tells you that you are trying to pass in too many arguments when you create a BankAccount object. There are two possible solutions:

Don't pass in any arguments by changing BankAccount(100) to BankAccount().

Change __init__() to accept another argument. I will assume that this argument represents the initial balance:
class BankAccount():

    #Implementation of __init__ function

    def __init__(self, initial_balance):

        #Declare balance and initialize with 0.0

        self.balance = initial_balance

        #Declare transaction_history as type of list

        self.transaction_history=[]

Here the initial_balance is required. You can use a default value instead if you want it to be optional. I will leave that as an exercise to the reader.
Comment: I have shared the answer in the comments section


Can OPTIONS and STYLES both be used for FusionTableLayer in Google Maps?

Question: When displaying map data from a Google Fusion table onto Google Maps as a layer, there is a very rich set of options available to customize the appearance of map features and the contents of info window. It appears that you can either use your own Style/Info Window generated at run time (i.e. through code on client side), or use the ones that you created in Fusion Tables tool, but not both. It would make sense for the same class of behaviour you are trying to customize for a given map view because there would otherwise be two competing commands for same action. However, I was wondering if I could mix and match it so that Styles is generated on the fly on the client side (using Styles section/directives), but use the "default" Info Window which was set up using Fusion Tables tool.
The following sample code illustrates what I would ideally want to do. Note the presence of both Options and Styles blocks. Options to use the default Info Window. And Styles to customize the appearance of map features.
    layer = new google.maps.FusionTablesLayer({
  ...
  },
  options: {
    //styleID is removed from Options; using Styles below--styleId: 2,
     templateId: 2 //Info Window is left to be the default one.
  }

  //Styles section is used instead of default styleID in "options" above.
  styles: [{
      where: "filter condition",
      polylineOptions: {
          strokeColor: "#ffbf00",
          strokeWeight: "3"
      }
  }]
});

Answer: Yes you can.  The styled infowindow contents is available in the click event.
See the documentation:
FusionTablesMouseEvent object specification

The properties of a mouse event on a FusionTablesLayer.

infoWindowHtml | Type:  string | Pre-rendered HTML content, as placed in the infowindow by the default UI.

example fiddle from your previous question: "WHERE" clauses being ignored in Fusion Table Layer in Google Maps
code snippet:

var geocoder = new google.maps.Geocoder();
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  layer = new google.maps.FusionTablesLayer({
    map: map,
    options: {
      // styleId: 2,
      templateId: 2
    },
    heatmap: {
      enabled: false
    },
    query: {
      select: "geometry",
      from: "1D6d93-0iT2zUCw8IvkbpDPYDx2-jA0ZAWXi07mQD",
    },
    styles: [{
      polylineOptions: {
        strokeOpacity: 0.001,
        strokeWeight: 0
      }
    }, {
      where: "SHIFT_ID = 3",
      polylineOptions: {
        strokeOpacity: 1.0,
        strokeColor: "#FFFFFF",
        strokeWeight: 3
      }
    }, {
      where: "SHIFT_ID = 1",
      polylineOptions: {
        strokeOpacity: 1.0,
        strokeColor: "#FF0000",
        strokeWeight: 3
      }
    }, {
      where: "SHIFT_ID = 2",
      polylineOptions: {
        strokeOpacity: 1.0,
        strokeColor: "#ffbf00",
        strokeWeight: "3"
      }
    }]
  });
  geocoder.geocode({
    'address': "Winnipeg, Canada"
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      map.fitBounds(results[0].geometry.viewport);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}


apache ssl cert issues

Question:
Possible Duplicate:
Hosting 2 different SSL domains on the same IP

I have 2 domains with two different certificates from the same CA. I'm using CentOS and am wondering how to set this up for 2 certificates. In my ssl.conf file, I have:
SSLCertificateFile /etc/pki/tls/certs/domain1.com.crt
SSLCertificateKeyFile /etc/pki/tls/private/domain1.com.key

In my http.conf file, I'm overriding these values for the second domain:
SSLCertificateFile /etc/pki/tls/certs/domain2.com.crt
SSLCertificateKeyFile /etc/pki/tls/private/domain2.com.key

What I get when I try and connect is that the domain does not match the certificate. How can I do this so as to use both domains? If I was using just 1 domain, there wouldn't be a problem.
Comment: Is this a sendmail, or apache issue? You say sendmail in the subject, but state http.conf in the body.
Answer: I'm assuming Apache since those are Apache configuration options.  You're probably hitting the common mistake of trying to run two domains on the same port and IP.  Since SSL happens before the HTTP request is sent, each domain requires a different port and/or different IP address.

apache ssl cert issues