Unable to send e-mail via sendmail, because User is unknown

Question: *hostname.domain.com is substituted throughout for my actual subdomain*

My Setup
I have Drupal 7.14 on an OpenVZ VPS running Ubuntu 11.10 (also tested with 10.04).  Ubuntu has installed the repository versions of Apache2/php5/mysql, (not the LAMP metapackage) with php5.ini configured to dump all error messages to syslog.
My Problem
Consistently, when the site is to send an email to any address, it returns:

Unable to send e-mail. Contact the site administrator if the problem persists.

And the Drupal Error in 'Recent log messages' readds:

Error sending e-mail (from firstname.lastname@example.com to email@example.com).

This Error shows in the Drupal logs no matter what address the email is being sent to.
The email does actually end up sending after a short delay.  Usually 1 second, but also 6 or more seconds.
Contents of Syslog
Sep 21 13:22:34 hostname sendmail[1648]: q8LDMYe9001648: Authentication-Warning: hostname.domain.com: www-data set sender to firstname.lastname@example.com using -f
Sep 21 13:22:34 hostname sendmail[1648]: q8LDMYe9001648: email@example.com, size=649, class=0, nrcpts=1, msgid=<firstname.lastname@example.com>, relay=www-data@localhost
Sep 21 13:22:34 hostname sm-mta[1649]: q8LDMYxB001649: from=<firstname.lastname@example.com>, size=1023, class=0, nrcpts=1, msgid=<email@example.com>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1648]: q8LDMYe9001648: firstname.lastname@example.com, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30649, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (q8LDMYxB001649 Message accepted for delivery)
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: Authentication-Warning: hostname.domain.com: www-data set sender to email@example.com using -f
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: email@example.com, size=465, class=0, nrcpts=1, msgid=<email@example.com>, relay=www-data@localhost
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0G001654: <email@example.com>... User unknown
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: email@example.com, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30465, relay=[127.0.0.1] [127.0.0.1], dsn=5.1.1, stat=User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0G001654: from=<email@example.com>, size=465, class=0, nrcpts=0, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgo001653: q8LDMYgp001653: DSN: User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0I001654: <email@example.com>... User unknown
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgp001653: firstname.lastname@example.com, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=31489, relay=[127.0.0.1] [127.0.0.1], dsn=5.1.1, stat=User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0I001654: from=<>, size=1489, class=0, nrcpts=0, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgp001653: q8LDMYgq001653: return to sender: User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0K001654: from=<>, size=4700, class=0, nrcpts=1, msgid=<firstname.lastname@example.com>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 13:22:34 hostname sendmail[1653]: q8LDMYgq001653: to=postmaster, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=32513, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (q8LDMY0K001654 Message accepted for delivery)
Sep 21 13:22:34 hostname sm-mta[1655]: q8LDMY0K001654: to=root, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=34947, dsn=2.0.0, stat=Sent
Sep 21 13:22:40 hostname sm-mta[1651]: q8LDMYxB001649: to=<firstname.lastname@example.com>, delay=00:00:06, xdelay=00:00:06, mailer=esmtp, pri=121023, relay=fakedomain.com. [126.96.36.199], dsn=2.0.0, stat=Sent (Ok)

Not Understood By Me
There are several seeming anomalies I do not understand, such as:

stat=User unknown
DSN: User unknown
Sep 21 13:22:34 hostname sm-mta[1654]: q8LDMY0I001654: <email@example.com>... User unknown
I can't understand why Drupal's error says from
email@example.com to firstname.lastname@example.com
I can send mail from the command line using sendmail, and it goes through just fine:

Contents of mail.log after sending with the command line on root
Sep 21 16:00:07 hostname sendmail[3283]: q8LFwxIS003283: from=root, size=167, class=0, nrcpts=1, msgid=<email@example.com>, relay=root@localhost
Sep 21 16:00:07 hostname sm-mta[3305]: q8LG07FE003305: from=<firstname.lastname@example.com>, size=487, class=0, nrcpts=1, msgid=<email@example.com>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
Sep 21 16:00:07 hostname sendmail[3283]: q8LFwxIS003283: email@example.com, ctladdr=root (0/0), delay=00:01:08, xdelay=00:00:00, mailer=relay, pri=30167, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (q8LG07FE003305 Message accepted for delivery)
Sep 21 16:00:08 hostname sm-mta[3307]: STARTTLS=client, relay=gmail-smtp-in.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=ECDHE-RSA-RC4-SHA, bits=128/128
Sep 21 16:00:08 hostname sm-mta[3307]: q8LG07FE003305: to=<firstname.lastname@example.com>, ctladdr=<email@example.com> (0/0), delay=00:00:01, xdelay=00:00:01, mailer=esmtp, pri=120487, relay=gmail-smtp-in.l.google.com. [18.104.22.168], dsn=2.0.0, stat=Sent (OK 1348243208 ut4si13805795igb.1)

Comment: There are 2 things to check a) IF the mail server is setup properly. b) Check if the email id exist
Comment: Just try and setup a new linux user on the system with the above email id and then try if it works
Comment: I can send mail through the command line using `sendmail` on the root account.  I have updated the post with the mail.log contents when doing that.
Comment: Now we know the mail server works. For my second question does this email id firstname.lastname@example.com exist ??
Comment: I'm sorry, I don't actually know where to look for or create email ids. (Which means that could be my problem, since all emails except for emails from root@ end up in everyones spam accounts).  Where should I start?
Comment: It depends on what kind of hosting do you use. You should check with your hosting providers. If you are using gmail business accounts then they have an option to add an email id and then you should be ready to go.
Comment: But before you do that I would suggest you trigger it with an email id which already exist and confirm if it is the same issue.
Comment: I've set this Ubuntu distro up myself on my VPS. It's unmanaged.
Comment: Do I have to create the user in my distro in order to email from email@example.com ?
Comment: how is your @domain.com email setup. Are you using some third party tools like gmail and are trying to setup mx records on your server ??
Comment: Also do you have an admin interface or login for your VPS server ?? You should have one
Comment: vePortal, but there are no options for email setup.  Surely this is something to handle from within Ubuntu?  If not, then can you give me a short explanation why not?
Comment: I never set up an MX record on my domain.. is this the problem? If so, why is root allowed to send emails?
Comment: MX record is used if you are using a third party email system like gmail and your domain name to route your emails.
Comment: I'm only using what came with the ubuntu distro, aside from the packages I listed above (and a few other things like wget, php-dev, php-pear, etc)
Comment: I am not a linux guru so I would suggest you look at another stack exchange forum called http://askubuntu.com. Also here is a link to one of the questions which I found http://askubuntu.com/questions/54960/how-do-i-set-up-an-email-server
Comment: Thank you, I have seen that, but have already tried postfix, etc.. and seeing that root can send emails just fine, I'd rather not complicate things until the problem is understood.  I have just used "adduser" and created noreply... everything works fine now.  I will bring this issue to askubuntu now to find out why.  Thanks for your help.
Answer: This error appeared after I've changed my host name from webserver to webserver.com, thus anything sent to *@webserver.com confused sendmail, as it's been searching local user with such name.
Adding a local user won't solve the problem completely, because if you try adding user like firstname.lastname, Linux system will complain.
What I've done though to fix my system, is configuring sendmail properly:

Modify /etc/mail/sendmail.mc by adding following lines to the very end:
define('MAIL_HUB', 'webserver.com.');
define('LOCAL_RELAY', 'webserver.com.');

Run:
sudo sendmailconfig

Optionally reloaded the sendmail by:
service sendmail restart

On some Linux distributions (such as Ubuntu) it may be reloaded automatically.
Comment: I haven't tested this yet, but had finally arrived at the conclusion that this was related to the host name.  This sounds about right, I hadno idea how to set it though, will update after trying this.
Answer: I still do not understand why, but creating a linux user on my Ubuntu VPS named "noreply" fixed this issue.  I am happy it works, but would appreciate an answer from anyone who might have insight or an alternative solution other than creating new linux users for every email id I want to send from.
Special thanks to junedkazi for discussing this with me in comments.
Comment: Also not really sure why this question doesn't deserve credit while some of the others I've seen are practically useless.  Oh well.  :-)
Comment: maybe because this is a sendmail (http://serverfault.com/) question and it doesn't really belong on the drupal site? Anyway sendmail needs a user per account by default to store it's email in ( not sure you can change that ) so that why you needed to create the unix user.


Which climbers have successfully scaled a wall with 15C difficulty?

Question: I have been going through Alex Harrold's podcast in the Tim Ferris show, and there he says that there are only two climbers in the world who have successfully climbed a 15C difficulty wall.
Were there really only two climbers? Which climbers have achieved this?
On a search, I found that one was Adam Ondra. Who else has done so?
Answer: Both Adam Ondra and Chris Sharma climbed La Dura Dura, 9b+/5.15c.
Comment: Kindly add links and/or more information to make the answer helpful to everyone.
Answer: In addition to Sharma and Ondra pre-2018, there have been a few more 15c ascents since then:

Alex Megos did the first ascent of Perfecto Mundo 5.15c in May 2018, and this was repeated by Stefano Ghisolfi and Jakob Schubert

Stefano Ghisolfi repeated Ondra's Change in September 2020

Will Bosi did the first ascent of King Capella 5.15c in March 2021

Also worth mentioning that there are 2 established 5.15d (!) routes as of May 2021:

Silence 5.15d, FA by Ondra in September 2017
Bibliographie 5.15d, FA by Alex Megos in August 2020

Both unrepeated, of course.
Source: Wikipedia
Answer: toasti is correct, here you can find an (excellent) list of the most difficult sport climbing, bouldering and free solo problems (9b+/15C but also 15B/9b etc.). The spreadsheet lists sources for each first ascent (FA). It contains not only FAs but also repeats (and differentiate between proposed and repeaters' grades). Grades are French / Font:
https://docs.google.com/spreadsheets/d/1RndNw9F74rvgvqDA1i512MwxHf7PtacojVD4s7DHVz8/edit?hl=en#gid=0
The source confirms toasti's answer. La Dura Dura in Oliana, Spain, is yet the only 9b+ which has been confirmed by the repeater. There are however two other 9b+ (Change at Flatanger, Norway, and Vasil Vasil at Sloup, Czech Republic) and one 9c (Silence at Flatanger) firstly ascended by Adam Ondra which have not been repeated (and for that reason have not been confirmed).
Update: Since I received a down vote, I want to clarify that I am not the creator of the spreadsheet nor do I know him. Yet, I think this source is an interesting link for everyone who is interested in the question asked (or similar questions).


How to calculate p-value for a parameter given confidence interval when null hypothesis != 0

Question: Given the dataset:
d = structure(list(x = c(22.9362216327734, 24.4504147133069, 23.2710364752618,
  22.5253827558421, 24.8139647577093, 22.8804536162757, 24.3948588709677,
  25.4304112554113, 25.7243410214168, 26.6003943661972, 26.0698382492864
  ), y = c(3.536, 3.867, 4.482, 2.033, 2.912, 3.958, 5.445, 6.973,
  5.115, 8.382, 4.438)), .Names = c("x", "y"), class = "data.frame", row.names = c(16L,
  17L, 19L, 20L, 23L, 24L, 25L, 26L, 28L, 29L, 30L))

I can make a nonlinear fit:
a = nls(y ~ a * exp(b * x), data = d, start = list(a = 1, b = 0.05))

    Formula: y ~ a * exp(b * x)

Parameters:
  Estimate Std. Error t value Pr(>|t|)
a  0.02980    0.05046   0.590   0.5694
b  0.20483    0.06723   3.047   0.0139 *

I am interested in the value of the b parameter:
library(MASS)
confint(a, parm = 'b')

      2.5%      97.5%
0.05583547 0.37719675

I see that the model converged on b as 0.205 with a 95% CI of (0.056, 0.377).
My question is:
How do I calculate the p-value for the following null hypothesis?
H0: b = 0.069
I've seen online the conversion between CI and p-value when the null is zero but I'm unsure of:

how many degrees of freedom exist for this parameter? Is it just nrow(d) - 1 still?
how to calculate p-value with a non-zero null
Comment: See also https://stats.stackexchange.com/questions/169141
Answer: How about estimating this model:
M = a = nls(y ~ a * exp((b + 0.069) * x), data = d, start = list(a = 1, b = 0))

So b == 0 in this model if and only if b == 0.069 in the original model.
The summary for the new model is:
Formula: y ~ a * exp((b + 0.069) * x)

Parameters:
  Estimate Std. Error t value Pr(>|t|)
a  0.02980    0.05046    0.59   0.5694
b  0.13583    0.06723    2.02   0.0741 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.314 on 9 degrees of freedom

Number of iterations to convergence: 20
Achieved convergence tolerance: 3.168e-06

Which gives you the p-values you want.
Comment: Very clever! This makes a lot of sense.
Answer: The Wald statistic for testing the null hypothesis is:
$$W = \frac{\hat{\theta} - \theta_0}{se(\hat{\theta})}$$
your $\hat{\theta}$ is the point estimate $b$:  0.20483  and $se(\hat{\theta})$ is the SE : 0.06723 used to describe the approximate normal sampling distribution of the test statistic when the null hypothesis is true. In this case, the null says: the $\theta_0 = 0.069$. So putting all the pieces together a p-value is obtained with:
pt(abs({0.20483-0.069}/0.06723), lower.tail=F, df=9)*2
which gives the same result as Matthew Drury's answer of:
> pt(abs({0.20483-0.069}/0.06723), lower.tail=F, df=9)*2
[1] 0.0740768

Note the degrees of freedom is nrow(d)-2 because you estimate two parameters.


Dimension of graded module

Question:
Let $R$ be a Noetherian positively graded ring and $M$ a finite graded
  $R$-module. Prove that $\dim M = \sup\{\dim M_p: p\in\operatorname{Supp} M \text{ graded}\}$.

This is the Exercise 1.5.25 in the book: Winfried Bruns and Jürgen Herzog, Cohen-Macaulay Rings, Cambridge University Press, 1998.
I also want to know why there is positively graded ring in the condition.
Answer: First of all i believe that what the authors really meant was the more precise "non-negatively graded" instead of "positively graded".
On to the main problem now. We have that $R = \oplus_{i \ge 0} R_i$ is Noetherian and $M$ finite graded $R$-module. Since $\operatorname{Ann}(M)$  is homogeneous, and by definition $\dim M = \dim R/\operatorname{Ann}(M)$, we may replace $R$ by $\operatorname{Ann}(M)$ and assume that $\dim M = \dim R$.
We will show that for any maximal ideal $m$ of $R$, there exists a homogeneous ideal $q$ such that it has at least the same height as $m$.
So let $m$ be a maximal ideal of $R$ and assume that it is not homogeneous. By Theorem 1.5.8b in B&H, we have that $\operatorname{height}m =\operatorname{height}m^* +1$, where $m^*$ is the ideal generated by the homogeneous components of $m$.
Now $m^*$ is by definition a homogeneous ideal and it can not be maximal because $m^* \subsetneq m$. Define $m_0 = m \cap R_0$. Now $R/m$ is a field and this implies that $R_0/m_0$ is a field (see proof in the comments), thus $m_0$ is a maximal ideal of $R_0$. Next define $q = m_0\oplus \left( \oplus_{i \ge 1} R_i\right)$. Then $q$ is a maximal ideal of $R$ that is homogeneous and additionally it contains $m^*$. Hence $\operatorname{height} q >\operatorname{height} m^* = \operatorname{height}m -1$ and so $\operatorname{height} q \ge \operatorname{height} m$.
Alternative Proof: Let $p$ be any homogeneous prime ideal that is $^*$maximal. Then every homogeneous element of $R/p$ is invertible, and we are in the situation of Lemma 1.5.7 in Bruns&Herzog. Hence either $R/p=k$ or $R/p=k[t,t^{-1}]$, where $k$ is a field. But $R/p$ is positively graded since $R$ is. Hence it must be the case that $R$ is a field and
so $p$ is a maximal ideal of $R$. This shows that every $^*$maximal ideal is maximal. Now let $q$ be such that $\dim M = \operatorname{height} q$. If $q$ is homogeneous then we are done. Otherwise, $\operatorname{height} q^* =\operatorname{height} q - 1$. Since $q^*$ is properly contained in $q$, it is not maximal, and so it is not $^*$maximal. Thus there must exist some homogeneous prime $P$ such that $P$ properly contains $q^*$. This means that $\operatorname{height} P =\operatorname{height} q = \dim M$, and we are once again done.
Comment: @user121097: Take any element $r \in R_0-m_0$. Then this element is nonzero mod $m$, hence it is invertible mod $m$. So there exist $r' \in R$ and $\mu \in m$ such that $rr'+\mu=1$. So the homogeneous part of degree zero of $rr'+\mu$ must be equal to $1$. Now this part is equal to $r r'_0 + \mu_0$, where $r'_0, \mu_0$ are the degree $0$ homogeneous components of $r', \mu$ respectively. Hence we must have $r r'_0 + \mu_0 = 1$. But $r'_0 \in R_0$ and $\mu_0 \in m_0$ and this equation says that $r \in R_0$ is invertible mod $m_0$. You agree?
Comment: Why if $m$ is maximal in $R$ then $m_0=m\cap R_0$ is maximal in $R_0$? (LaTeX tip: use \subsetneq instead of subset\neq in order to get $m^*\subsetneq m$.)
Comment: Thanks for the nice answer, let's discuss more.  @user121097 For the Z-graded rings, the element in R$_1$, R$_2$,..also can have inverse, but the invertible element can not appear in any ideal which is not R, so how does it disturb the main claim? The Lemma 1.5.7 is an extreme case of this type, "totally invertible".

Dimension of graded module


Expected Value of a Determinant

Question: Suppose that I construct an $n \times n$ matrix $A$ such that each entry of $A$ is a random integer in the range $[1, \, n]$. I'd like to calculate the expected value of $\det(A)$.
My conjecture is that the answer is zero, though I could very well be incorrect. Running some numerical experiments with different values for $n$ and a large number of trials, it seems that $\mathbb{E}[\det(A)]$ is normally in the range $[0.25, \, 0.7]$, so I'm starting to lose faith in my intuition that it is zero.
Could anyone lend some advice on how to approach this problem and what strategies I may want to consider applying?
Comment: [This MO post](http://mathoverflow.net/questions/13008/expected-determinant-of-a-random-nxn-matrix) is related and may be of use. In particular it points out that a more interesting question might be $\sqrt{\mathbb{E}((\det A)^2)}$.
Comment: @Clarinetist The $2\times2$ case gets a lot simpler with $\mathbb{E}[ad-bc] = \mathbb{E}[ad]-\mathbb{E}[bc]$. :)
Comment: Is there a typo in the statement "$\det(A)$ is normally in the range $[0.25,0.7]$"?  As $A$ is an integer matrix its determinant must be an integer.
Comment: This seems like it would be a very complicated question. For example, in the $2 \times 2$ case, you would have to compute the expected value of $\left|\begin{pmatrix}a & b \\ c & d\end{pmatrix}\right|$, or $\mathbb{E}\left[ad - bc\right]$. You would need to examine products of uniform random variables and how they are distributed as well... I'll see if I can offer any insight later.

Also, given the fact that they're discrete uniform random variables makes the question harder, in my opinion. But fascinating question nevertheless.
Comment: Oops, I meant $\mathbb{E}[\det(A)]$. Fixed.
Comment: Yes, but the problem is more complicated as you add more rows and columns.
Answer: Rebecca's answer is nice, but here's another solution that might be simpler for some people: Let $f$ be a function that swaps the first two rows. Notice that $f(A)$ and $A$ have the same distribution, and thus
$$\mathbb{E}[\det A] = \mathbb{E}[\det f(A)] = \mathbb{E}[-\det A] = - \mathbb{E}[\det A].$$
Comment: Of course it's nice, which is why she got a "Nice Answer" badge for it ;)
Answer: For $n \geq 2$, we partition the matrices into "orbits" formed by swapping the first two rows:

Orbits of size $1$ have two identical rows, so $\det=0$.
Orbits of size $2$ have matrices of determinants of equal magnitude but opposite sign.

Hence $\sum_A \det(A)=0$ and so $\mathbb{E}(\det(A))=\tfrac{1}{n^{n^2}}\sum_A \det(A)=0$.
Answer: The elements of your matrix appear to be independently and identically distributed random variables, all following a discrete Uniform distribution $a_{ij} \sim U(1,n)$. Then, at the theoretical level, all is nice and clear:
Any $n \times n$ determinant, $n>2$, is decomposed down to a sum (with varying signs of course) of $2 \times 2$ determinants, with multiplying terms in front of them.
One such term, typical in its structure, would be (neglecting the sign)
$$a_{11}\cdot a_{22}\cdot...a_{n-2,n-2} \cdot \left (a_{n-1,n-1} a_{nn} - a_{n-1,n}a_{n,n-1}\right)$$
and, due to independence
$$E\left[a_{11}\cdot a_{22}\cdot...a_{n-2,n-2} \cdot \left (a_{n-1,n-1} a_{nn} - a_{n-1,n}a_{n,n-1}\right)\right]$$
$$=E\left[a_{11}\cdot a_{22}\cdot...a_{n-2,n-2} \right]\cdot \left (E(a_{n-1,n-1}) E(a_{nn}) - E(a_{n-1,n})E(a_{n,n-1})\right)$$
But the variables are also identically distributed, so their expected value is the same. So
$$E(a_{n-1,n-1}) E(a_{nn}) - E(a_{n-1,n})E(a_{n,n-1}) =0$$
in all cases, and so all such terms are zero, and the expected value of the determinant will be zero.
Obviously, if the elements of the matrix are not independent r.v.'s, we cannot break the expected values and the zero result does not hold in general. So perhaps, the way you draw your random numbers makes the elements of the matrix non-independent? Perhaps for each row or column you draw "without replacement"?
But assume that we do draw correctly independent numbers/random variables, and we want to "see with our own eyes" that the "average value" does converge to zero. How do we go about it? For given $n$, the "sample analogue" of the expected value of the determinant is
$$\overline {\det(A)}= \frac 1m\sum_{i=1}^m\det(A_m)$$
where $m$ is the number of matrices generated in the same fashion...
...and the nice clean picture provided by the Expected Value operator and the i.i.d. assumption just vanished, because the sample mean of the determinants is not the average of a sum of independent r.v.'s: the components of each determinant is of course independent from the components of all other determinants, indeed. Each component of each determinant, is comprised of i.i.d r.v.'s indeed (it is a product of i.i.d discrete uniforms). But between certain components of each determinant, there will be dependence since they will have some r.v.'s in common. For example the determinant of the matrix
$$B=\begin{bmatrix}a&b&c\\d&e&f\\g&h&i\end{bmatrix}$$
is
$$|B|=aei+bfg+cdh-ceg-bdi-afh$$
and you can see the various stochastic dependencies.  This makes the fate of simulations for $\overline {\det(A)}$ a rather more complicated issue to determine, get a sense of the rate of convergence, etc. In other words, your conjecture is correct -but seeing it materialize through computer simulation may be another matter.
Answer: Let $A_n$ be an $n \times n$ matrix.
The case of a $1 \times 1$ matrix is a little different than the general case. Since the determinant is just the single entry itself, it follows that since the entry must be one, the determinant is also one.
For $n \geq 2$, you can show that the answer is zero using induction. Consider the case $n=2$ and the corresponding matrix $A_2$. It's determinant is
$$
\det(A_2) = \left| \left( \begin{array}{cc} a & b \\ c & d \end{array} \right) \right| = ad - bc.
$$
In other words,
$$
\mathbb{E}[\det(A_2)] = \mathbb{E}[ad-bc] = \mathbb{E}[ad] - \mathbb{E}[bc] = \mathbb{E}[a]\mathbb{E}[d] - \mathbb{E}[b]\mathbb{E}[c]
$$
where the second equality comes from the linearity of the expected value and the second comes from the fact that $a$, $b$, $c$, and $d$ are independent random variables. It's not hard to see that $\mathbb{E}[X] = (2+1)/2 = 3/2$ for $X \in \{ a, \, b, \, c, \, d \}$. Thus,
$$
\mathbb{E}[\det(A_2)] = \left(\frac{3}{2}\right)^2 - \left(\frac{3}{2}\right)^2 = 0.
$$
Next assume that $\det(A_n) = 0$, where $A_n$ is an $n \times n$ matrix.
For the inductive step, note that $\det(A_{n+1})$ can be written as
$$
\det(A_{n+1}) = \lambda_1\det\left(A_{n}^{(1)}\right) - \lambda_2\det\left(A_{n}^{(2)}\right) + \lambda_3\det\left(A_{n}^{(3)}\right) - \cdots \pm \lambda_{n+1}\det\left(A_{n}^{(n+1)}\right)
$$
by using the usual method to expand the determinant across the top row (or any row/column, really) of the $(n+1) \times (n+1)$ matrix (note that I used the superscripts simply to index the $n \times n$ matrices). Since $\det\left(A_n^k\right) = 0$ for $k = 1, \, 2, \dots, \, n+1$, the determinant is zero for $n \geq 2$, by induction.
Putting these results together, we have
$$
\mathbb{E}[\det(A_n)] = \begin{cases}
1, & n = 1 \\
0, & n \geq 2.
\end{cases}
$$
Note that you can easily extend this result to show that if the entries come from any bounded set, the determinant must be zero for $n \geq 2$.
Comment: [+1] for the idea. But operator $\mathbb{E}$ is missing at different places in the second part of you answer : for example  "Next assume that $\det(A_n)=0$" should be "Next assume that $\mathbb{E}[\det(A_n)]=0$".

Expected Value of a Determinant


How should left and right hand by synchronized in Chopin Nocturne in C# Minor

Question: I have a question about which notes on the right-hand match with which notes on the left hand.
Comment: Related question on the same piece, with a similar answer: [how to coordinate hands when playing very fast](https://music.stackexchange.com/questions/108994/how-to-coordinate-hands-when-playing-very-fast)
Answer: These kinds of ornamental runs do not need to be played in a metrically exact way, so you can match up notes in a way you find musically pleasing.
As a general, personal rule, I like to start runs slower and finish faster. So for the first run, I'd group the notes 2+3+3+3 against the four left-hand notes.
X: 0
T: Nocturne in C# Minor
T: m. 60, beats 3-4
C: Chopin
M: none
K: C# minor
L: 1/16
V:V1
V:V2 clef=bass
%%score (V1 | V2)
[V:V1] AB (3cde (3fed (3cBA |
[V:V2] C,2F,2D2C2 |

However, for the second run, because it's moving into the rallentando and represents a "cooling off" of the piece, I would tend to play slower toward the end. Either 3+4+3+3 or 3+3+4+3.
X: 0
T: Nocturne in C# Minor
T: m. 61, beats 3-4, version 1
C: Chopin
M: none
K: C# minor
L: 1/16
V:V1
V:V2 clef=bass
%%score (V1 | V2)
[V:V1] (3ABc d/2e/2f/2g/2 (3fed (3cBA |
[V:V2] C,2F,2D2C2 |

OR
X: 0
T: Nocturne in C# Minor
T: m. 61, beats 3-4, version 2
C: Chopin
M: none
K: C# minor
L: 1/16
V:V1
V:V2 clef=bass
%%score (V1 | V2)
[V:V1] (3ABc (3def g/2f/2e/2d/2 (3cBA |
[V:V2] C,2F,2D2C2 |


Bootstrap navbar two rows with second row full screen width

Question: I'm working on a responsive 2-row menu with brand logo. So far I have been able to make this using this SO answer but not sure how to make the second row in this menu full width. Currently the second row stops at the brand logo.
I'm trying to get the second row (#quickMenu) to stretch all the way to the left side of window. Tried several things on this element but it just does not go beyond the enclosing flex-column parent.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

            <button class="navbar-toggler mb-2 mr-2" type="button" data-toggle="collapse" data-target="#navbarCollapse">

            </button>

                                Apply

LinkA

LinkB

LinkC

LinkD

LinkE

                                Link1

                                Link2

                                Link3

                                Link4

                                Link5

                                Link6

                                Link7

                            <form action="/site-search/" class="form-inline header-search" method="get">

                                    <input type="search" id="q" name="q" placeholder="Search the site"
                                           class="form-control-sm border-primary" />
                                    <button type="submit" class="btn text-primary">
                                        <svg class="bi bi-search" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                                            <path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z" />
                                            <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z" />
                                        </svg>
                                    </button>

                            </form>

https://jsfiddle.net/4tbf5mgc/
Current:

Desired:
Comment: I'm a little unclear on what exactly should happen, and `#quickMenu` appears to be the first row - do you have a graphic mockup of what you are trying to accomplish?
Comment: I will try to upload a graphic mockup later today.
Answer: I'm not sure if that is what you're looking for - but to stretch the other menu just add flex-fill class to all nav-item-s within it.
Check the result here: https://jsfiddle.net/n39xpawf/

OK then - seem like i didn't get your idea yesterday ;)
To reproduce the desired display as it is on your image just add the CSS below to absolutely position the brand-logo image for screen wider then 767px:
@media (min-width: 768px){
  .navbar.navbar-expand-md .navbar-brand {
    position: absolute;
    z-index: 1;
    top: 5px; /* whatever your logo size will be - adjust positioning here.. */
  }
  #quickMenu {
    padding-left: 3rem; /* ...and left padding here leave enough space for brand-logo */
  }
}

working draft here: https://jsfiddle.net/otzLwemp/
Comment: please see my edit that shows the current setup and desired setup
Comment: @joym8 ok, now i got what you meant - i've extended the answer (under the line) added new solution - hope that is what you need?
Comment: yes this is exactly what i needed. i will test in my code tomorrow!
Comment: I haven't checked your jsfiddle line by line. is it exactly the same as I posted in my question? In other words, the CSS is the only thing I need to add?
Comment: @joym8 yes. just that css in the answer
Comment: I tried this in a local HTML file, outside of JSFiddle, and it's not giving the desired effect. The second row of links is left aligned. In JSFiddle the 2nd row looks justified and is responsive, which is good.
Comment: Compare classes of the `<div id="mainMenu" ..` you might be missing `w-100` class. Anyway the css i gave you is positioning the logo while not doing anything with second menu.


Estimate confidence interval of mean by bootstrap t method or simply by bootstrap?

Question: When estimating the confidence interval of mean, I think both the bootstrap t method and the nonparametric bootstrap method can apply, but the former requires a little more computation.
I wonder what the advantages and disadvantages of bootstrap t over the normal nonparametric bootstrap are? Why?
Are there some references for explaining this?
Answer: Bootstrap-$t$ still relies on assumptions for parametric distributions: If the boostrap distribution of a statistic has a normal distribution, you can use the bootstrap-$t$ method. This will lead to a symmetric CI.
If, however, the sampling distribution is skewed or biased, it is better to use the percentile bootstrap (which allows for asymmetric CIs).
Now, which method should you use?
Concerning the bootstrapped mean:
According to simulations by Wilcox (2010), the percentile bootstrap should not be used for untrimmed means (in this case bootstrap-$t$ works better); starting from 20% trimming, percentile bootstrap outperforms the bootstrap-$t$ (the situation is unclear for 10% trimming).
Another hint comes from Hesterberg et al. (2005, p. 14-35):

The conditions for safe use of bootstrap t and bootstrap percentile inter- vals are a bit vague. We recommend that you check whether these intervals are reasonable by comparing them with each other. If the bias of the bootstrap distribution is small and the distribution is close to normal, the bootstrap t and percentile confidence intervals will agree closely. Percentile intervals, un- like t intervals, do not ignore skewness. Percentile intervals are therefore usu- ally more accurate, as long as the bias is small. Because we will soon meet much more accurate bootstrap intervals, our recommendation is that when bootstrap t and bootstrap percentile intervals do not agree closely, neither type of interval should be used.

--> in case of disagreement better use the BCa-corrected bootstrap CI!

Hesterberg, T., Monaghan, S., Moore, D., Clipson, A., & Epstein, R. (2005). Bootstrap methods and permutation tests. Introduction to the Practice of Statistics, 14.1–14.70.
Wilcox, R. R. (2010). Fundamentals of modern statistical methods: Substantially improving power and accuracy. Springer Verlag.
Comment: I agree with your prescription that the percentile bootstrap should not be used for untrimmed means, but I don't think it is generally true that the bootstrap-t method needs the underlying population to be normally distributed.  See my answer to http://stats.stackexchange.com/questions/39297/is-centering-needed-when-bootstrapping-the-sample-mean/49661#49661.


UIButton selector not working after button tapped within WKWebView

Question: I have a custom titleView with 2 custom UIButtons with arrow images that allow navigation to the next view controller in the paging structure. They work perfectly fine until a button is tapped within the WKWebView. Then they don't work anymore and the selector is not called. Note that other buttons in the nav bar still work (UIBarButtonItems). The buttons work properly again after the user swipes over to the next view controller.
After looking into it some, it looks like a WKCompositingView becomes first responder and if I override becomeFirstResponder() in a WKWebView subclass, the issue goes away. I'm still a little baffled though, and would like to understand the root of the problem.
class NonFirstRespondableWebView: WKWebView {

    override func becomeFirstResponder() -> Bool {
        return false
    }
}

Does anyone have any insight into why this is happening?
Answer: Most UI elements in swift have a UIResponder. Unhandled events are passed up the responder chain to enclosing views. My guess is that the WKWebView is absorbing all touch events once the window has become active. You can learn more about the responder chain here
Regarding a first responder. From the docs:

The first responder is usually the first object in a responder chain to receive an event or action message. In most cases, the first responder is a view object that the user selects or activates with the mouse or keyboard.

Assuming you want to keep interactivity with the WKWebView fully functional (e.g. you need to bring up a keyboard or something), you can use
webView.resignFirstResponder()

To resign the responder at any time.
Otherwise, an extension that would give you the same functionality might look something like this:
extension WKWebView {

    open override func becomeFirstResponder() -> Bool {
        if self.superview?.superview is UIWebView {
            return false
        } else {
            return super.becomeFirstResponder()
        }
    }

}

Comment: Thank you for answering! I still don't understand why the other nav bar buttons would still be functional though. And I also don't understand why this happens in the first place - the buttons that are tapped in the WKWebView aren't bringing up a keyboard (really, any button tapped causes the buttons to be disabled).
Comment: When you tap in the WKWebView the window for whatever website becomes active. Any sibling views next to the webView aren't responsive because the WKWebView then has the first responder for touch events. Navbar buttons won't be effected by that because they are farther up the responder chain (likely they are your root view).


Discrimination between measurements made at different points in time

Question: I would like to ascertain what variables discriminate best between experimental conditions in a repeated-measures experimental design.
I have performed Repeated Measures MANOVA to determine whether the groups of measurements differ significantly at all and found they indeed do. I can get a rough idea of what variables have the highest prediction power, based on their Roy's greatest root value (one could have used another statistic, of course). I would now like to check this via another statistical analysis which would follow the MANOVA.
Speaking loosely, I am looking for a predictive discriminant analysis analogous to repeated measures MANOVA.
From what I have read on Repeated Measures (Longitudinal) Discriminant Analysis, it seems that it is used to discriminate between groups of subjects all of which have been measured on several occasions (Sajobi et al., 2011; Lix and Sajobi, 2010; Komarek et al., 2009; Kohlmann, 2010). On  the other hand, what I am looking for would discriminate between these repeated measures themselves, all of which included all of the participants (a single group).
Brief two paragraphs in McLachlan (section 3.7.5, pp. 83-84) were too compressed to give any insight.

References
Kohlmann, M. (2010). Discriminant Analysis for Longitudinal Data with Application in Medical Diagnostics (Doctoral dissertation, lmu).
Komárek, A., Hansen, B. E., Kuiper, E. M. M., van Buuren, H. R., & Lesaffre, E. (2010). Discriminant analysis using a multivariate linear mixed model with a normal mixture in the random effects distribution. Statistics in Medicine, 29(30), 3267–3283. doi:10.1002/sim.3849
Lix, L. M., & Sajobi, T. T. (2010). Discriminant Analysis for Repeated Measures Data: A Review. Frontiers in Psychology, 1, 1-9. doi:10.3389/fpsyg.2010.00146
McLachlan, G. (2004). Discriminant analysis and statistical pattern recognition (Vol. 544). John Wiley & Sons.
Sajobi, T. T., Lix, L. M., Li, L., & Laverty, W. (2011). Discriminant Analysis for Repeated Measures Data: Effects of Mean and Covariance Misspecification on Bias and Error in Discriminant Function Coefficients. Journal of Modern Applied Statistical Methods, 10(2), 571-582. Available at: digitalcommons.wayne.edu/jmasm/vol10/iss2/15
Comment: I'm trying to grab the gist. You have measurements of several variables on several occassions (t1, t2, t3, ...) on the same group of people. You would like to predict somehow the progress of people, more specifically the progress from t1->t2, t2->t3, t3->.. Is that correct?
Comment: Thanks @spdrnl. It's not a progress, because the (time) sequence is not important. Hence "repeated measures" rather than "longitudinal". The repeated conditions were in random order for different subjects. My task is actually even simpler: I only want to find variables that differentiate (i.e. discriminate) between these occasions most efficiently.
Answer: I ended up using the multiple factor analysis (Pagès, 2004 /pdf/), which can indeed be calculated for repeated measures (Abdi, Williams, & Valentin, 2013).
This is actually an extension of principle component analysis on multiple tables. It can calculate principle components for each of the repeated measures, but also for grouped variables.
So, I calculated principle components that explained the most variance between different repeated measures. In this way, I got a linear combination of variables that best explained the differences between different experimental conditions (i.e. different repeated measures). If I was lucky, the first dimension was straight-forward to interpret, possibly highly correlated with only one of my variables.
The method is implemented in the R package called FactoMineR (examples and detailed instructions are here).
References
Pages, J. (2004). Multiple factor analysis: Main features and application to sensory data. Revista Colombiana de Estadística, 27(1), 1-26.
Abdi, H., Williams, L. J. and Valentin, D. (2013), Multiple factor analysis: principal component analysis for multitable and multiblock data sets. WIREs Comp Stat, 5, 149–179. doi:10.1002/wics.1246


recarregar efeitos do material design

Question: Tenho um site com material design, porém quando atualizo o html da página com XHR o novo conteúdo perde o efeito do javascript como eu poderia fazer para recarregar o mdl?
Para fazer a mudança entre as view, uso duas funções, na primeira passo a url do arquivo, o id do elemento que vai conter o html e um array, opicional, onde posso inserir arquivos javascript
function getView(url, elementId, array = []) {
    let req = new XMLHttpRequest();
    req.open("get", url, true);
    req.setRequestHeader("Access-Control-Allow-Origin","*");
    req.setRequestHeader("Content-Type","text/html");
    req.setRequestHeader("Accept","text/html");
    req.onload = function() {
        document.getElementById(elementId).innerHTML = this.responseText;

        for(let item of array) {
            insertJS(item);
        }
    };
    req.send();
};

function insertJS(url) {
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = url;
    let element = document.getElementsByTagName('script')[0];
    element.parentNode.insertBefore(script, element);
};

Comment: Se possível poste seu código. Caso esteja utilizando `jQuery`, dê preferência por utilizar o método [**.on**](http://api.jquery.com/on/) ou então crie uma função para inicializar os efeitos e toda vez que houver uma atualização, basta executar a função criada.
Comment: Acredito que o código não vá influenciar, mas editei. Não uso jQuery.
Comment: Seria bem legal o codigo inteiro, saber de onde vc esta utilizando o material design, se tem algum framework por traz, alguma outra linguagem sendo utilizada em conjunto, como esta iniciando os componentes, mais referencias no geral.

Nao conseguiremos ajudar, pois sua pergunta mostra apendar 2 funções que sem mais contexto nao poderemos ajudar.
Comment: @CaioKoiti não é usado nenhum framework ou biblioteca, e os arquivos do mdl (css e js) estão sendo chamados no head normalmente ` ` já tentei sem o defer e com async mas não funcionou
Comment: Tente chamando `componentHandler.upgradeDom()` após o Ajax inserir novos elementos na página.
Comment: @dvd funcionou! Adiciona uma resposta ai rapidão pra que possa aceitar e recompensar. Porém ao usar essa função todo a página é rerenderizada né?
Comment: Resposta postada. ;)
Answer: Chame a função componentHandler.upgradeDom() após o Ajax adicionar novos elementos ao DOM. Isso irá atualizar o DOM no Material Design.
Comment: Sabe dizer se isso recarrega todo o DOM ou apenas o que foi modificado pela função?
Comment: Provavelmente todo o DOM. Ao meu ver não tem como saber o que foi modificado.
Comment: Depois vou dar uma olhada na documentação, valeu

recarregar efeitos do material design


Passing javascript variable to php without refreshing the page

Question: I have a 5x5 grid of div boxes (25 of them) and I am using jQuery UI to register when I drop a item in it. It will receive the title of the box it was dropped in and the name of the item, that part works.
I want to pass the title and name to PHP without refreshing the page (because then the items will reset). I get a "success!" but it seems like it doesn't pass the data.
index.php

sessions.php
<?php
   session_start();
if(isset($_POST['box']))
{
   // store session data
   $_SESSION['box'] = $_POST['box'];
}
   //retrieve session data
   echo $_SESSION[box];
?>

How do I pass the title and name to PHP without refreshing the page?
Comment: @Dagon You're far out of line.
Comment: Thanks, you just gave me an idea, i was stuck on it like 3 hours now.
Answer: Try to change the url and your data from this:
url: 'index.php',
data: { box : 'box' }

to this:
url: 'sessions.php',
data: { box : box }

Comment: i feel like a total idiot right now..  oh well thanks. while im at it how do i make it add instead of overwrite the data in session[box] ?
Answer: Given that you're doing this...
box = $(this).attr('title');

I assume you want to pass that variable to the server. However, you're just passing the literal string "box", not the variable box.
In your code, you've written this...
data: { box : 'box' },

which needs to be this, to pass the value in box:
data: { box : box },

As an aside, you've created a global variable box. Instead of box = $(this).attr('title');, you should use var box = $(this).attr('title'); to create a variable local to the function.
Comment: i just tryed that, as before i get "success!" but it dosent get the data. i have  in my index.php to se if the data is there but it dosen't write enything. and thanks for the "var" tip.
Comment: Verify the data is actually being sent. Check the value of `box` or open your browser's developer tools and inspect the AJAX request.
Comment: Felix found the stupidest error i have made ever. But big thanks to you for trying to help


Document mode in ie

Question: I have a header
<code><!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 9]>
<html class="ie ie9" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 10]>
<html class="ie ie10" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 7) & !(IE 8) & !(IE 9) & !(IE 10)]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
</code>
In my virtual box I have a version of IE10 running.
<code>.ie10 body {
 background:blue;
}
</code>
The problem is I have to stick the document into ie9 to get it to pick up the styles. Why is this not working the way I think it should.
Answer: As of IE10, conditional comments are no longer supported.
You'll need to think of a different way to accomplish the result you're after.
Hope this helps...
-- Lance

Document mode in ie


C.I. X bar from mu, sigma and n

Question: Suppose that the size of Wendy's single hamburger is normally distributed with mean 70 grams and standard deviation of 5 grams. If 4 hamburgers are selected at random, find the probability that the same mean is less than 77 grams.
This section is on confidence intervals, and I know the following formulas.
$$P[\bar X<{\frac{Z_{\alpha/2}\sigma_X}{n}+\mu_X}]$$
if the right hand equals 77, then $Z_{\alpha/2}$ = 5.6
But the answer for the probability is .9974.
How exactly do I solve this problem?
The formula for the confidence interval didn't help me with a solution either. Thanks for the help.
Comment: Why would you use a formula for confidence intervals? It's not asking you for a confidence interval
Comment: Please add the self-study tag to this homework problem.
Answer:
The standard error ($\text{SE}$) of the sampling distribution is $\frac{\sigma}{\sqrt{n}}$. It is less than the population standard deviation $\sigma =5$, because taking the mean of a group smooths out extreme values.
The sample mean is a consistent estimator. If they had asked you for the probability of the sample mean being less than $70$, the answer would have been $1/2$ - the lower one-half of the bell's curve.
But the question is "less than $77$". So you have to find the cumulative probability for the quantile $\frac{77-\mu}{\text{SE}}$, corresponding to the normalized $77$ value.

Does it make sense? Yes, you don't even need a calculator to see that this is the case: The $\text{SE}=2.5$ grams, and the value you are interested in is $7$ grams above the mean. So how many standard errors is it above the mean? Almost $3$, right? What is the probability that if you sample a group of $4$ people and measure their height, their average will be shorter than an NBA player, whose height is $3$ standard deviations above the mean? Would you consider betting on it?

C.I. X bar from mu, sigma and n


Question about the proof that a normed space is finite-dimensional if its closed unit ball is compact

Question: I have a question about a minor point in the proof of the following theorem.

Let $B$ denote the unit closed ball in $(V,\|\cdot\|)$. If $B$ is compact then $V$ is finite-dimensional.
Proof. Suppose that $V$ is infinite-dimensional and take $\{x_n\}_{n\geq 1}\subset V$ linearly independent. In particular, any
  finite subset of $\{x_n\}_{n\geq 1}$ will be linearly independent. For
  $m\geq 1$, let $E_m=\mathrm{span}\{x_1,\dots,x_m\}$. This is a linear
  space for each $m\geq 1$ and $E_m\subsetneq E_{m+1}$. Since it is
  isomorphic to $\mathbb R^m$, it is closed and by Riesz's Lemma we take
  $y_{m+1}\in E_{m+1}\setminus E_m$ such that $\|y_{m+1}\|=1$ and
  $\|y_{m+1}-y\|>1/2$ for any $y\in E_m$. Hence, $\|y_{k+1}-y\|>1/2$ for
  any $y\in E_k$ for $k\leq m$. This way, we have constructed a sequence
  $\{y_m\}_{m\geq 1}\subset B$ such that $$m\neq k\implies
\|y_m-y_k\|>\frac12.$$So this has no convergent subsequence and thus
  $B$ is not (sequentially) compact.

Now, I don't really see how we prove that all points in $(y_m)$ are more than $1/2$ apart. In particular, how does the equation in display mode follow from the previous stuff?
Also, why does the fact that $E_m$ is isomorphic to $\mathbb R^m$ imply that $E_m$ is closed. Do isomorphisms preserve closed sets?
Any ideas?
Comment: You know that $\|y_{m+1}-y_{k}\| > 1/2$ for $k=1,2,3,\cdots m$. But you also know that $\|y_{m+1+j}-y_{m+1}\| > 1/2$ for $j =1,2,3,\cdots$. And, yes, isomorphisms preserve closed sets because they preserve open sets, and they preserve set complements.
Answer: $E_m$ is a closed subset of $E_{m+1}$, the Riesz lemma implies that there exists $y_{m+1}\in E_{m+1}$ such that for every $y\in E_m, \|y_{m+1}-y\|\geq 1/2$. In particular if $y=y_l, l\leq m$, $\mid y_{m+1}-y_l\|\geq 1/2$.
$E_m$ is closed, to see this, consider  $e_1,..,e_m$ a base of $E_m$, a sequence $x_i=u^1_ie_1+..u^n_ie_n$ is a Cauchy sequence implies that it is the Cauchy sequence for the norm sup since every norm of a finite dimensional vector space are equivalent. This implies that $(u^l_i)$ is a Cauchy sequence of $R$ thus converges towards $u^i$, thus $(x_i)$ converges towards $u^1e_1+...+u^ne_n$.
https://en.wikipedia.org/wiki/Riesz%27s_lemma#The_result


CentOS and Broadcom Wireless Drivers

Question: I'm tired of reading, tired of trying to find a solution myself, that's why I decided to post my question.
I'm following tutorial located at CentOS Wiki to install driver for my wifi device.
However, I'm facing strange error at the begining of the process.
<code>make -C /lib/modules/`uname -r`/build/ M=`pwd`
make: *** /lib/modules/2.6.18-194.11.3.el5PAE/build/: File not found
</code>
Does anyone know what I'm doing wrong? This is first time when I try to install Linux on my laptop.
Answer: http://www.broadcom.com/docs/linux_sta/README.txt did you try above site for install the driver.
Answer: did you install these packages using follwoing command?
yum install kernel-headers kernel-devel gcc
i have tried it is working fine with this command

CentOS and Broadcom Wireless Drivers


Há como fazer uma div filho, flutuar ao rolar o scroll da div pai?

Question: Tenho uma div primária, e dentro desta, outra div(secundária).
Estou tentando posicionar a div secundária na div primária de modo que, torne uma DIV flutuante(estilo popup) que sobreponha aos demais elementos.
Mas para este caso em especial, quero fazer sobrepor ao conteúdo da div principal e ao rolar o Scroll a div filho deve acompanhar.
Segue abaixo o código.

#Pai {
    position: relative;
    width: 400px;
 height: 200px;
 border: 3px solid blue;
 text-align: center;
 overflow: auto;
}

#Filho {
 width: 100px;
 height: 100px;
 margin-left: -50px;
 /* metade da largura */
 margin-top: -50px;
 /* metade da altura */
 position: absolute;
 top: 50% ;
 left: 50% ;
 background: tomato;
 z-index: 1; // sobrepor
 -moz-opacity: 0.8;
 opacity: .80;
 filter: alpha(opacity = 80);
}

Elemento A

Elemento B

Elemento C

Elemento D

Elemento E

Elemento F

Elemento G

Elemento H

Elemento I

Elemento J

Teria como desenvolver um Script para conseguir este efeito, sem que precise alterar toda sintaxe do CSS?
Por exemplo
var scrolldellay = document.getElementById("Pai");

   scrolldellay.scrollBy = function() {
                  ...
    // Coloque a rotina implementada
                  ...
 }

Comment: Modificando o `position:absolute;` para `position:fixed;` não serve para o seu caso?
Answer: Como o amigo @Cʜᴜɴ comentou, apenas alterando de position:absolute; para position:fixed; a div central(vermelha) se mantem fixa, e alterei a posição(top,left) p/ manter ela no centro.

#Pai {
    position: relative;
    width: 400px;
 height: 200px;
 border: 3px solid blue;
 text-align: center;
 overflow: auto;
}

#Filho {
 width: 100px;
 height: 100px;
 margin-left: -50px;
 /* metade da largura */
 margin-top: -50px;
 /* metade da altura */
 position: fixed; /* alterei aqui */
 top: 30% ; /* alterei aqui */
 left: 200px ; /* alterei aqui */
 background: tomato;
 z-index: 1; // sobrepor
 -moz-opacity: 0.8;
 opacity: .80;
 filter: alpha(opacity = 80);
}

Elemento A

Elemento B

Elemento C

Elemento D

Elemento E

Elemento F

Elemento G

Elemento H

Elemento I

Elemento J

Um script sem precisar alterar o css, utilizando jquery
$("#Pai").scroll(function() {
  console.log($("#Pai").scrollTop());
  $("#Filho").css("top", $("#Pai").scrollTop() + 100);
});

Utilizando o mesmo exemplo, agora a div filho é reposicionada conforme o valor do .scrollTop() da div pai, que retorna a posição vertical atual da barra de rolagem, coloquei +100 simplesmente p/ manter centralizada, tu pode alterar o valor tranquilamente p/ ver como se comporta, nota que ao scrollar o body não afeta a posição da div filho.
Demo - jquery
Comment: @DiegoHenrique, 3 linhas somente no css, ta comentado no código =)
Comment: Um elemento fixo - `fixed` - é posicionado relativamente ao "viewport", isso significa que ele sempre ficará no mesmo lugar mesmo que haja rolagem na página.

Um detalhe aqui é quando um elemento recebe `position:fixed`, ele fica livre/independente não somente do seu parente, mas do documento como um todo.

Ou seja o elemento `position:fixed` se mantém sempre fixo à janela e não ao elemento em que ele está inserido.

Me parece que temos de setar os valores das propriedades `top` e `left` em "pixel" e utilizar o elemento fixo - `fixed`.
Comment: O elemento `position:fixed` não se adequa muito bem à minha necessidade, o `position` que melhor se adequaria seria o `position:absolute`. Mas sua resposta ja ta valendo. =)
Comment: Realmente, se o elemento pai da div pai possuir scroll a div central(filho) vai acompanhar o scroll, p/ esse caso acho que seria interessante colocar uma função $("#Pai").scroll(function() {..}); que ao scrollar a div pai, movimentar a div filho, com position:absolute; obviamente, se tu achar necessário posso implementar na resposta.
Comment: @DiegoHenrique, da uma olhada aqui: https://jsfiddle.net/mathiasfcx/sac5sL3u/ peguei o mesmo exemplo, coloquei position:abosulte na div filho e uma função na div pai, que ao scrollar a div pai a div filho é reposicionada conforme o valor do .scrollTop(); que retorna a posição vertical atual da barra de rolagem, coloquei +100 simplesmente para centralizada, tu pode alterar o valor tranquilamente p/ ver como se comporta,coloquei um body com scroll p/ mostrar que o scroll não vai afetar a div filho, qualquer duvida só chamar.
Answer: você pode usar o evento scroll como mencionou, porém o valor do top deve levar em consideração os 50% iniciais.
Abaixo segue um exemplo.

Modernizr.addTest('csscalc', function() {
    var prop = 'width:';
    var value = 'calc(10px);';
    var el = document.createElement('div');
    el.style.cssText = prop + Modernizr._prefixes.join(value + prop);
    return !!el.style.length;
});

Modernizr.addTest('mozcsscalc', function() {
    var prop = 'width:';
    var value = '-moz-calc(10px);';
    var el = document.createElement('div');
    el.style.cssText = prop + Modernizr._prefixes.join(value + prop);
    return !!el.style.length;
});

var pai = document.getElementById("Pai");
var filho = document.getElementById("Filho");
pai.addEventListener("scroll", function (e) {
  if (Modernizr.csscalc) {
    filho.style.top = "calc(50% + " + pai.scrollTop + "px)"
  } else if (Modernizr.mozcsscalc) {
    filho.style.top = "-moz-calc(50% + " + pai.scrollTop + "px)"
  }
});
#Pai {
  position: relative;
  width: 400px;
  height: 200px;
  border: 3px solid blue;
  text-align: center;
  overflow: auto;
}

#Filho {
  width: 100px;
  height: 100px;
  transform: translate(-50%, -50%);
  position: absolute;
  top: 50%;
  left: 50%;
  background: tomato;
  z-index: 1; // sobrepor
  -moz-opacity: 0.8;
  opacity: .80;
  filter: alpha(opacity = 80);
}

Elemento A

Elemento B

Elemento C

Elemento D

Elemento E

Elemento F

Elemento G

Elemento H

Elemento I

Elemento J

P.S.: você não precisa de uma margem negativa para ajustar a posição da div, para tal você pode usar um translate de -50%.
Comment: @DiegoHenrique qual a necessidade de utilizar um Navegador que foi lançado a 5 anos e não tem mais suporte por parte da Mozilla?
Comment: @DiegoHenrique adicionei um fallback para o Mozilla 11, mas aconselho que atualize o seu browser, ou pelo menos avise que esta usando um Browser pré-histórico na hora de fazer a pergunta.
Comment: Estou a utilizar um Firefox 11 numa plataforma DLinux, e não rolou. Em qual Navegador desenvolveu?
Comment: Estou utilizando o Opera
Comment: Bom, Linux são robusto, mas quando ha necessidade de instalar seus pacotes, muita das vezes ocorre alguns conflito entre bibliotecas. Ai começa a correria pra solucionar, pois em muitos caso temos que compilar tudo na unha. Mas tenho o Slax com Firefox 38, e sei que o Firefox ja esta na sua versão 52+ . Mas para cada nova atualização requer na maioria das vezes uma nova máquina. Infelizmente não é somente eu, mas ha outros usuários sem PC novos, ainda mais na crise. E pensando assim, gosto de programar tudo portável, semântica amplamente compatível com os mais de 40 navegadores
Answer: Com as repostas que obtive de Mathias e seguida de Tobias Mesquita, antes da sua nova edição.
Cheguei a duas alternativa similares, acredito que seja Cross-Browser.
1.ª_Alternativa
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>

Elemento A

Elemento B

Elemento C

Elemento D

Elemento E

Elemento F

Elemento G

Elemento H

Elemento I

Elemento J

Segue Explicação
var A = document.getElementById('Pai'); // Div(primária)

var B = document.getElementById('Filho'); // Div(secundária)

var rolamento = function() {

        var centralizado = A.scrollTop + 100; // Aqui definimos o valor 100 para reposicionar a Div(secundária) conforme o valor scrollTop() da Div(primária)
        B.style.top = centralizado; // Agora vamos automatizar a Div(secundária), para retomar sempre a mesma posição inicial

}

A.onscroll = rolamento; // Escuta o evento da barra de rolagem lateral e dispara a função

NOTA - "Esta 1.ª_Alternativa funcionou perfeitamente no Computador local, mas não teve o mesmo desfeixo quando tentei adicionar como amostra no http://jsbin.com/ e http://jsfiddle.net/. No entanto o Script em si, funciona, estando abaixo do . Qualquer coisa que venha a ser, a causa, é de natureza desconhecida por mim."

2.ª_Alternativa

var A = document.getElementById('Pai');  // Div(primária)
var B = document.getElementById('Filho'); // Div(secundária)
var P = B.scrollHeight / 2;
A.onscroll = new Function("if(B.style.top = A.scrollTop + P + 'px') return true");
body {
    height: 999px;
}

#Pai {
   position: relative;
   width: 200px;
   height: 200px;
   border: 3px solid blue;
   text-align: center;
   overflow: auto;
}

#Filho {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 25%;
    left: 25%;
    margin: 0 auto;
    background: tomato;
}

Elemento A

Elemento B

Elemento C

Elemento D

Elemento E

Elemento F

Elemento G

Elemento H

Elemento I

Elemento J

JSbin - Amostra externa
Explicando
var P = B.scrollHeight / 2;

Estou fazendo a divisão da div(secundária), por seu Tamanho real, ou seja:
Tam.: 100 ÷ 2 = 50
Guardamos esse valor(50) na variável P e lançamos na condição if.
A.onscroll = new Function("
   if(B.style.top = A.scrollTop + P) return true
");

Logo o scroll que esta ligado ao elemento div(primária), for deslizado
A cada "1px" será chamado a new Function() para a execução
Que seguido da condição if, entra em ação pela sua posição
E num piscar de olhos retorna true(reposicionamento realizado).
Pronto!


Arquivo anexo email Oracle plsql vai vazio

Question: Tenho o bloco PLSQL abaixo listado , o email é enviado mas o arquivo que deveria ir anexado chega vazio no email de destino.
Envia um arquivo existente , não ?
O que estou fazendo de errado ?
Grato
declare
  ds_email_origem_w varchar2(30);
  ds_email_destino_p varchar2(30);
  ds_assunto       varchar2(50);
  p_attach_clob    CLOB;
  p_attach_file    varchar2(50);
  /* envio de email com blobs  */
  l_step        PLS_INTEGER  := 4000;--12000;
  ds_smtp_w varchar2(20) := '10.19.1.xx';--informo o ip correto
  --ds_user_id_w varchar2(50) := 'envio_email';
  --ds_senha_smtp_w varchar2(50) := '@@@@@@@';
  /* Abre conex?o SMTP e HTTP */
  CONEXAO UTL_SMTP.CONNECTION;
  vs_origem char(25) := 'email@example.com';
BEGIN
  ds_email_origem_w := '';
  ds_email_destino_p := 'firstname.lastname@example.com';
  ds_assunto         := 'teste attach ' || to_char(sysdate,'yymmddhh24mi');
  for r in (select coluna from tabela) --prencher o email de teste
  loop
    p_attach_clob := ' ' || p_attach_clob || r.coluna;
  end loop;

  /* Abre conex?o com um Servidor SMTP(Simple Mail Transfer Protocol), porta padr?o SMTP e 25 */
  CONEXAO := utl_smtp.open_connection (ds_smtp_w,25);
  UTL_SMTP.HELO (CONEXAO, ds_smtp_w); /* Endereco do servidor de SMTP */
  --utl_smtp.command (CONEXAO, 'AUTH LOGIN');
  --utl_smtp.command (CONEXAO, utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw((ds_user_id_w)))));
  --UTL_SMTP.COMMAND (CONEXAO, UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW((DS_SENHA_SMTP_W)))));
  UTL_SMTP.MAIL (CONEXAO, ('<' || vs_origem          || '>')); /* E-mail de quem esta mandando */
  UTL_SMTP.RCPT (CONEXAO, ('<' || ds_email_destino_p || '>')); /* Para quem vou mandar */
  UTL_SMTP.OPEN_DATA(CONEXAO);
  UTL_SMTP.WRITE_DATA(CONEXAO,'Subject'|| ': ' || ds_assunto || utl_tcp.CRLF);

   UTL_SMTP.write_data(
        CONEXAO,
           'Content-Disposition: attachment; filename="'
        || 'lmeu_arquivo.txt'  --arquivo que existe na pasta UTL padrão
        || '"'
        || UTL_TCP.crlf
    );

  --UTL_SMTP.WRITE_DATA(CONEXAO, utl_tcp.CRLF || ds_mensagem_p);
  FOR i IN 0 .. TRUNC((DBMS_LOB.getlength(p_attach_clob) - 1 )/l_step)
  LOOP
    UTL_SMTP.WRITE_DATA(CONEXAO, /*utl_tcp.CRLF || */ DBMS_LOB.substr(p_attach_clob, l_step, i * l_step + 1));
  END LOOP;
  UTL_SMTP.CLOSE_DATA(CONEXAO);
  UTL_SMTP.QUIT (CONEXAO);
Exception
  when OTHERS then
    utl_smtp.quit (conexao);
    RAISE_APPLICATION_ERROR(-20011,'Nao foi possivel enviar o e-mail devido ao seguinte erro: ' || SQLERRM);
END;

Answer: Veja esse exemplo:
DECLARE
   v_From       VARCHAR2(80) := 'email@example.com';
   v_Recipient  VARCHAR2(80) := 'email@example.com';
   v_Subject    VARCHAR2(80) := 'test subject';
   v_Mail_Host  VARCHAR2(30) := 'mail.mycompany.com';
   v_Mail_Conn  utl_smtp.Connection;
   crlf         VARCHAR2(2)  := chr(13)||chr(10);
BEGIN
  v_Mail_Conn := utl_smtp.Open_Connection(v_Mail_Host, 25);

  utl_smtp.Helo(v_Mail_Conn, v_Mail_Host);

  utl_smtp.Mail(v_Mail_Conn, v_From);

  utl_smtp.Rcpt(v_Mail_Conn, v_Recipient);

  utl_smtp.Data(v_Mail_Conn,
    'Date: '   || to_char(sysdate, 'Dy, DD Mon YYYY hh24:mi:ss') || crlf ||
    'From: '   || v_From || crlf ||
    'Subject: '|| v_Subject || crlf ||
    'To: '     || v_Recipient || crlf ||

    'MIME-Version: 1.0'|| crlf ||   -- Use MIME mail standard
    'Content-Type: multipart/mixed;'|| crlf ||
    ' boundary="-----SECBOUND"'|| crlf ||
    crlf ||

    '-------SECBOUND'|| crlf ||
    'Content-Type: text/plain;'|| crlf ||
    'Content-Transfer_Encoding: 7bit'|| crlf ||
    crlf ||
    'some message text'|| crlf ||   -- Message body
    'more message text'|| crlf ||
    crlf ||

    '-------SECBOUND'|| crlf ||
    'Content-Type: text/plain;'|| crlf ||
    ' name="excel.csv"'|| crlf ||
    'Content-Transfer_Encoding: 8bit'|| crlf ||
    'Content-Disposition: attachment;'|| crlf ||
    ' filename="excel.csv"'|| crlf ||
    crlf ||
    'CSV,file,attachement'|| crlf ||    -- Content of attachment
    crlf ||

    '-------SECBOUND--'         -- End MIME mail
  );

  utl_smtp.Quit(v_mail_conn);
EXCEPTION
  WHEN utl_smtp.Transient_Error OR utl_smtp.Permanent_Error then
    raise_application_error(-20000, 'Unable to send mail', TRUE);
END;
/

Comment: mas o arquivo existe ? Em que pasta ?
Comment: Numa leitura mais atenta depois entendi e funcionou, valeu !


How to display node details and call function in *.html.twig

Question: I work in D8, I create a custom module first_module. By modules create a url and display all nodes by *.html.twig file.
Write code in controller.php
public function contentthree() {

  $connection = Database::getConnection();

  $query = $connection->select('node', 'n');
  $query->fields('n', ['nid', 'type']);

  $groups = $query->execute()->fetchAll();

  foreach ($groups as $group) {
    $events[] = [$group->nid, $group->type];
  }

  return [
    '#theme'  => 'first_module_display',
    '#events' => $events,
  ];
}

In *.module
function first_module_theme($existing, $type, $theme, $path) {

  return [
    'first_module_display' => [
      'variables' => ['events' => NULL],
      'template'  => 'first-module-list',
    ],
  ];
}

function _get_node_details() {

  $output = 'Welcome D8';

  $output .= 'Node Details';

  return $output;
}

and create templates first-module-list.html.twig and display data
{%for key, data in events %}

{%for key1, data1 in data %}

   {{ data1 }}

{% endfor %}

{% endfor %}

work fine and showing data correct. But, my question is how to call function _get_node_details() and how to render node details in first-module-list.html.twig files?
Comment: This is not the right approach. Before tackling a module like this I suggest you spend more time familiarising yourself with the documentation. You should not be working directly with DB connections for a start.
Comment: I agree with @AlfredArmstrong about becoming more familiar with more some of the site building techniques (views) with Drupal as it helps make your site more maintainable. I disagree that using DBTNG is wrong and that may be necessary. For your specific question about rendering text returned from _get_node_details(), you can add to your controller's returned render array with #markup. Additionally your global functions should also be prefixed with the module name.
Answer: I think I would have implemented this feature differently. Let me just answer the specific question, and then I will tell you an alternative approach.
Custom 'functions' in Twig
The easiest thing for you could be to Implement a twig macro.
However, macros could be limiting. To have all the PHP power you can create a twig extension function
If you are in a rush and are into bad practices, then there is the twig tweak php filter, so that you can do this:

     {{ 'return _get_node_details();'|php }}

Alternative implementation using Drupal views

Create a Drupal View, with a Block Display.
Place the new Block, using the Block Layout.
If you need to do a heavy alteration use a hook_views_data_alter().


como fazer asim que a pagina dar refresh minha variavel em js não mudar

Question: eu tenho um código html

 nome

e um js que pergunta o usuário o nome e reescreve a div
var username = prompt('qual seu nome ?');

alert('olá ' + username + ', seja bem vindo <3')

document.getElementById("nome").innerHTML = username;

e queria fazer com que esse código so seja lido a primeira vez que meu usuário entre e que dando refresh na page não reescreva mais a minha div
Comment: Para isso, você precisa salvar esse nome em algum lugar. Nesse caso parece que pode ser no próprio computador de quem está acessando, em um cookie ou no localstorage.
Comment: aplicando um setTimeout.. acredito q resolve..
Answer: Tendo em vista que você está iniciando, recomendo que estudo sobre gerenciamento de estado, padrão muito utilizado no desenvolvimento dos frameworks web, como por exemplo React, Angular e etc.
Porém, neste caso podemos resolver de forma simples, salvando no localStoragea informação.

if(localStorage.getItem("name")){
   alert("Olá " +  localStorage.getItem("name"));
}
else{
   var username = prompt("qual seu nome ?");
   localStorage.setItem("name", username);
   alert("Olá " +  localStorage.getItem("name"));
}
Comment: Poderia melhorar o estilo de codificação obtendo inicialmente `localStorage.getItem("name")` em uma variável e fazer o teste com o valor dessa variável e aproveitar ou não esse valor conforme o teste.


How to check internet connection in dagger 2 module for okhttp3

Question: I am creating module for okhttp3 using dagger 2. Now i want to check internet connection inside network module. What is the best way to achieve that?
Comment: Why would you want to perform that it module? What's the logics behind that?
Comment: I wanted to check internet connection for Okhttp3 cache. As i have created module of okhttp3
Answer: Take a look at any of the answers to this canonical question and simply encapsulate them.
For example, you could have an interface like this:
public interface OnlineChecker {
    boolean isOnline();
}

And then most upvoted implementation:
public class DefaultOnlineChecker implements OnlineChecker {

    private final ConnectivityManager connectivityManager;

    public DefaultOnlineChecker(ConnectivityManager connectivityManager) {
        this.connectivityManager = connectivityManager;
    }

    @Override
    public boolean isOnline() {
         NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
         return netInfo != null && netInfo.isConnectedOrConnecting();
    }
}

The second-most upvoted implementation:
public class ExperimentalOnlineChecker implements OnlineChecker {

    private final Runtime runtime;

    public ExperimentalOnlineChecker(Runtime runtime) {
        this.runtime = runtime;
    }

    @Override
    public boolean isOnline() {
        try {
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 188.8.131.52");
            int     exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        }
        catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }

        return false;
    }
}

Then in its own module or elsewhere just bind the implementation you want:
@Module
public class OnlineCheckerModule {

    @Provides
    public OnlineChecker onlineChecker() {
        Runtime runtime = Runtime.getRuntime();
        return new ExperimentalOnlineChecker(runtime);
    }
}

Now inside your Activity or Fragment you can simply inject using property injection:
@Inject OnlineChecker onlineChecker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super(savedInstanceState);
    //perform injection with Dagger 2 and then you can use your
    //OnlineChecker
}

Answer:
For those who are Following MVVM or Kotlin Coroutines(not necessary) and above api 22 here it is:

With the new implementation of Dagger Android and MVVM.
Before deep dive into it your dagger class graph or object graph is already set, then you have to do something like:
ConnectivityInterceptor Interface
interface ConnectivityInterceptor : Interceptor

ConnectivityInterceptorImpl
You can use Custom Exception class or simply use IOException
To Check the internet connection state of mobile device you've to use connectivity manager and of course enable network state from manifest as well
In the isOnline() there are some of things which were daprecated forapi 28 or api 29 and some method can't be usable if api level is below 22 so i used current state which not going to bother you either if you are above api 22
class ConnectivityInterceptorImpl (
    private var application: Application
) : ConnectivityInterceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        if (!isOnline())
            throw NoConnectivityException() //custom Exception class
        return chain.proceed(chain.request())
    }

    private fun isOnline(): Boolean {
        val connectivityManager = application.getSystemService(
            Context.CONNECTIVITY_SERVICE
        ) as ConnectivityManager
        var res = false
        connectivityManager.let {
            it.getNetworkCapabilities(connectivityManager.activeNetwork)?.apply {
                res = when {
                    hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                    hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                    else -> false
                }
            }
        }
        return res
    }
}

Dagger AppModule
Here comes the Dagger Thing:
As we are using Interceptor for network state which is of course going to act as interceptor in the okHttpClient and Okkhttp is used here to make the network calls following by the retrofitBuilder() which means we are doing something called Singleton, so in that case we have to manage the object graph of Dagger
@Module
abstract class AppModule {

    @Module
    companion object {
        @JvmStatic
        @Singleton
        @Provides
        fun providesConnectivityInterceptorImpl(application: Application):
                ConnectivityInterceptorImpl {
            return ConnectivityInterceptorImpl(application)
        }

        @JvmStatic
        @Singleton
        @Provides
        fun getClient(connectivityInterceptorImpl: ConnectivityInterceptorImpl): ApiService {
            val requestInterceptor = Interceptor { chain ->
                val url = chain.request()
                    .url()
                    .newBuilder()
                    .addQueryParameter("api", KEY)
                    .build()

                val request =
                    chain
                        .request()
                        .newBuilder()
                        .url(url)
                        .build()
                return@Interceptor chain.proceed(request)
            }

            val okHttpClient = OkHttpClient
                .Builder()
                .addInterceptor(connectivityInterceptorImpl) // here it is
                .addInterceptor(requestInterceptor)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build()

            return Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ApiService::class.java)
        }
    }
}

Enum Class
To handle network State
enum class Status  {
    RUNNING,
    SUCCESS,
    FAILED
}

class NetworkState(val status: Status, val msg: String) {
    companion object {
        val LOADED: NetworkState = NetworkState(Status.SUCCESS,"Success")
        val LOADING: NetworkState = NetworkState(Status.RUNNING,"Running")
        val ERROR: NetworkState = NetworkState(Status.FAILED,"Failed")
    }
}

Repository
Do this in the Repository:
if you are using DataSource layer, you can do that in dataSource class
private val _networkState = MutableLiveData<NetworkState>()
    val returnNetworkState: LiveData<NetworkState>
        get() = _networkState
fun networkData(){
CoroutineScope(IO).launch {
            _networkState.postValue(NetworkState.LOADING)
            try {
               //Asynchronous Operation
               _networkState.postValue(NetworkState.LOADED)

            } catch (e: NoConnectivityException) { // custom exception class
                Log.d(TAG, "No Internet Is Available")
               _networkState.postValue(NetworkState.ERROR)

            }
        }
     }

Inside your Activity/Fragment update your UI observing through LiveData accordingly.
myViewModel.returnNetworkState.observe(this, Observer {
          //textView or anything
        })

All Done.


Site really slow for registered users

Question: When I look at the devel query logs of my website I see that views takes up most of the loading time. Anonymous loads of my page are much faster compared to registered loads but how come? Isn't views loaded the same way for every user?
Comment: Hard to say if you don't know the site at all.
Answer: Views supports caching the query and the rendering.
If you have page caching enabled then it's obviously much faster and views isn't involved at all.
There is no silver bullet to improve performance, try to install xhprof to find out where your bottlenecks are.
Using a different cache backend like memcached can help a lot, for a start.

Site really slow for registered users


Read data from Text View Kotlin

Question: I want to read data from text view and navigate to activities.
if text view data = "admin" navigate to main activity
text view data = "user"  navigate to user Activity
Comment: Please edit your question and add your database structure as a screenshot and also show have you have tried so far.
Comment: I found out how to do it @AlexMamo
Comment: Good to hear that, Jash ;)
Answer:
Yes I found the answer

<code>val uid = auth.currentUser?.uid.toString()
    FirebaseFirestore.getInstance().collection("users").document(uid)
        .get()
        .addOnSuccessListener {
            if (it.exists()) {
                val accessLevel = it.get("isAdmin").toString()
                userAccessLevel.text = accessLevel
            }
        }
</code>

Read data from Text View Kotlin


Are shift op codes really 3 times faster than moves? Intel x86

Question: In my Intel x86 Pentium handbook it says that ADD and shifts like SAL/SHR take 1/3 clock compared to things like JMP and MOV that take 1 clock. Is this really true that a bunch of adds and shifts will 3 times faster than a bunch of movs?
I guess I am doubly confused because there is table of "latencies" on the web showing "Pentium M" and none of timings are 1/3, although a few are 1/2. Is this because my book is old and on newer Pentiums shift is the same speed as JMP?
Comment: Original Pentium from 1993? Some things have changed since!
Comment: This is the book I have: http://marketplace.vintage-computer.com/auction_details.php?name=Intel-Pentium-Processor-Family-Developers-Manual-Vol-3-Architecture&auction_id=112800.  This book is the "Intel Pentium Processor Family Developer's Manual Vol 3: Architecture and Programming Manual" dated 1995.
Answer: Don't confuse "latency" with "reciprocal throughput".

Latency is how many cycles it takes to execute one instance of the instruction.
Reciprocal Throughput is how many instructions per cycle that the processor can sustain.

That 1/3 that you are seeing isn't the latency. It's the reciprocal throughput. The processor can sustain 3 ADDs per cycle. (if they are all independent) But each one still takes at least 1 cycle to execute.
If you have latency 1 and reciprocal throughput of 1/3, that means that the processor can execute up to 3 ADDs simultaneously. But each one still takes 1 cycle.

Historically, most Intel processors (since Pentium?) have 3 main execution units that can all do basic operations such as additions and shifts. That's why most of these are 1/3 reciprocal throughput.
Register-to-register MOVs should also be 1/3. But MOVs that touch memory (ie. loads and stores) are historically only 1/cycle. (Recently with Sandy Bridge and later, this has been increased.)
Comment: "since Pentium?" Architectures have changed completely several times since the Pentium, although all changes in Intel processors going back to the Pentium M seems to be rather evolutionary, according to http://www.agner.org/optimize/instruction_tables.pdf
Answer: Assuming this is about the original Pentium (i.e., not a Pentium Pro or newer) the 1/3 does not mean "one third" (or anything like it). It means the instruction has 1 cycle throughput and 3 cycle latency (i.e., you can start one instruction every cycle, and one can finish every cycle, but the instruction takes three pipeline stages, so there's a three-cycle delay between starting and finishing a particular instruction).
The original Pentium had only two execution units and no out of order execution. In a given clock cycle, the next instruction would execute in the U pipeline. If the right conditions were met, the instruction after that could execute in the V pipeline. Under no circumstances did more than two instructions execute in any given cycle, and under no circumstance did more than one instruction execute per clock in a single pipeline.
Later processors (starting with the Pentium Pro) added out of order instruction scheduling, and the ability to execute more than two instructions in a single cycle (could have considerably more "in flight" but was limited to retiring three per cycle). The Pentium IV added the ability to execute 2 extremely simple instructions (register to register AND, OR, NOT, ADD, SUB, single-bit shift) in the same execution unit in a single clock cycle (i.e., it had an execution unit that was actually running at double the rated clock speed, so for example, on a 2.8 GHz processor a small amount of the circuitry was actually running at 5.6 GHz).
Comment: Okay, so are you saying the 1/3 means that a given ADD/SHR will always take at least 3 clocks to execute? If so, this would apparently mean that the ADD/SHR is slower than the JMP/MOV, which would make sense I think.
Comment: @TylerDurden: yes, that's pretty much it. I seem to have a vague memory of a typo in a manual around that time, where something was shown as 1/3 that should have been 1/2 though (i.e., what was shown as three cycle latency was really only 2).


Find last two digits of $33^{100} $

Question: Find last two digits of $33^{100}$.
My try:
So I have to compute $33^{100}\mod 100$
Now by Euler's Function $a^{\phi(n)}\equiv 1\pmod{n}$
So we have $33^{40}\equiv 1 \pmod{100}$
Again by Carmichael Function : $33^{20}\equiv 1 \pmod{100}$
Since $100=2\cdot40+20$ so we have $33^{100}=1\pmod{100}$
So last two digits are $01$
Is it right?
Comment: If you already have $33^{20}\equiv 1$ anyway, then $33^{100}=(33^{20})^5\equiv 1$
Answer: Method$\#1:$
$$33^2=(30+3)^2\equiv3^2+2\cdot3\cdot30\equiv190-1\pmod{100}$$
$$\implies33^{100}\equiv(190-1)^{50}$$
$$(190-1)^{50}=(1-190)^{50}\equiv1-\binom{50}1\cdot190\pmod{100}\equiv?$$
Method$\#2:$
Alternatively, Carmichael Function $\lambda(100)=\cdots=20\implies33^{20}\equiv1\pmod{100}$
As $100\equiv0\pmod{20},33^{100}\equiv33^0\pmod{100}$
Method$\#3:$
As $33\equiv1\pmod4$
Again, $33\equiv8\pmod{25}\equiv2^3,2^{10}\equiv-1\pmod{25}$
$\implies33^{10}\equiv(2^3)^{10}\equiv(2^{10})^3\equiv(-1)^3\equiv-1$
$\implies33^{20}\equiv1\pmod{25}$
$\implies$ord$_{100}33=$lcm$(1,20)=20$
Comment: $3=2\cdot 3\cdot 30$ should be $3^2+2\cdot 3\cdot 30$, I think.
Comment: @TonyK, Exactly. Thanks
Answer: $33^{100} \equiv (33^2)^{50} \equiv 1^{50} \equiv 1 \bmod 4$, because $\varphi(4)=2$.
And $33^{100} \equiv (33^{20})^5 \equiv 1^5\equiv 1 \bmod 25$, because $\varphi(25)=20$.
So $33^{100} \equiv 1 \bmod 100$.
Similarly, $a^{100} \equiv 1 \bmod 100$ for all $a$ coprime to $100$.
Comment: Very efficient !
Answer: By the binomial theorem applied to $(30+3)^{100}$, they are the same as the digits of $3^{100}$.
Then, $\bmod 100$,
$$3^2=9,3^4=81,3^5=43,3^{10}=49,3^{20}=01\implies 3^{20k}=01.$$
Answer: 33^4 = 21 mod 100 ;33^20 = 01 mod 100 ;33^100 = 01 mod 100 ;Yes the
 last 02 digits are 01
Comment: He is asking for the last two digits though. So $mod \: 10$ isnt giving the whole result here.

Find last two digits of $33^{100} $


Supermicro ESXi 5 IPMIView - cant connect to the set IP

Question: So I start from the very beginning: I have a Supermicro X8DT3 running with ESXi 5 which is a host for a VM (old hardware, just for test purposes). Since I'm quite a noob regarding all this, I wanted to train and learn. I installed the Supermicro IPMIView software for monitoring the sensors like FANs and temperature on a local dekstop PC (Win7). I also tried to get SNMPT Traps working which caused the main problem.. I've setup all the necessarry options in the Supermicro BIOS regarding the BMC (setting the IP, gateway and subnet) and everything worked fine. Yesterday I changed the gateway in the IPMIView software from 0.0.0.0 to the same IP of the server.. since then everything is broken. Somehow this change affected the variables in the Supermicro BIOS and now i cant connect to my IPMI host. Since I'm not a native english speaker, I try to explain it with my configuration as good as possible:
Settings BEFORE everything broke:
IPMI IP: 192.168.0.97
Subnet: 255.255.255.0
Gateway: 0.0.0.0
All this made in the Supermicro BIOS in the IPMI menu (the MAC was already set).
After I accidently changed the gateway to the IP adress (dont ask why, it was a long day) nothing worked. So I decided to change the gateway in the BIOS back to 0.0.0.0.. this didnt help. I cant ping the .97 IP. So I decided to change the IP this morning to 192.168.0.197 - same result. No ping, no connection. All the other settings are like before. What did I do? What may have caused this issue? I hope I could explain this issue as good as possible!
Kind regards,
manji15
Comment: Is the machine you are connecting from in the same subnet as the IPMI address? (just because you didn't explicitly state it: is the network cable connected on the IPMI interface?)
Comment: Yes, both have the 255.255.255.0 subnet. The network cable is connected, I've just checked it.
Comment: I was referring to the `192.168.?` part.
Comment: Both have a 0, yes. /add: Maybe it helps if I mention that if i do a /nslookup with the OLD IPMI IP (192.168.0.97), I get the domain (although the .97 IP isnt entered in the Supermicro BIOS), but with the new one .197 nothing works. Do I maybe have to switch the server completely off for some time?
Comment: Still the same issue. I set it to DHCP now.. lets see if that works (bad feeling though).
Comment: Have you tried to reset IPMI from BIOS?
Comment: Unfortunately, there is so such option. Or do you have an idea how? Ive just shut down the server, removed the power cables and waited for about 10 minutes. Will check it now!
Answer: Ok guys, I managed to restore my settings from yesterday - now everything is working great again! The reset of the IPMI was the right thing to do. I did it by shutting down the server and removing the power cables, waited for about 15 minutes and wow, it really worked! Thanks to all!
Comment: By the way, this post helped me as well: https://serverfault.com/questions/470720/ipmi-on-a-supermicro-mothercard?rq=1
Comment: I somehow doubt that a power loss would reset the settings, but if helped you, I'm glad. Regarding your new question, you should post it as a new question. This is not a discussion board.


Python - re.split string

Question: I've been searching for a solution for a few hours now. I have a variable I want to split up in a nested list.
points ="""M445,346c28.8,0,56,11.2,76.4,31.6C541.8,398,553,425.2,553,454s-11.2,56-31.6,76.4C501,550.8,473.8,562,445,562
        s-56-11.2-76.4-31.6C348.2,510,337,482.8,337,454s11.2-56,31.6-76.4S416.2,346,445,346 M445,345c-60.2,0-109,48.8-109,109
        s48.8,109,109,109s109-48.8,109-109S505.2,345,445,345L445,345z"""

newPoints = re.split(r'[A-Za-z-]', points)

It is a multiline var with x and y positions of points from a svg file.
The pattern is that it starts a new item at a letter. I would like to have it ordered something like the following. I've tried some options like above. One of the mail problems is that it keeps deleting my delimiter. :)
[
  [
     [command],
     [x of p1, y of p1],
     [x of p2, y of p2],
     [x of p3, y of p3]
  ]
]

[
[ [M],[445,346] ],
[ [c],[28.8,0],[56,11.2],[76.4,31.6] ]
]

Any pointers are very welcome!
Answer: You can find letters and floats, and then group:
import re
import itertools
points ="""M445,346c28.8,0,56,11.2,76.4,31.6C541.8,398,553,425.2,553,454s-11.2,56-31.6,76.4C501,550.8,473.8,562,445,562
    s-56-11.2-76.4-31.6C348.2,510,337,482.8,337,454s11.2-56,31.6-76.4S416.2,346,445,346 M445,345c-60.2,0-109,48.8-109,109
    s48.8,109,109,109s109-48.8,109-109S505.2,345,445,345L445,345z"""
new_points = [list(b) for a, b in itertools.groupby(filter(None, re.findall('[a-zA-Z]+|[\d\.]+', points)), key=lambda x:re.findall('[a-zA-Z]+', x))]
final_data = [[new_points[i], [int(c) if re.findall('^\d+$', c) else float(c) for c in new_points[i+1]]] for i in range(0, len(new_points)-1, 2)]

Output:
[[['M'], [445, 346]], [['c'], [28.8, 0, 56, 11.2, 76.4, 31.6]], [['C'], [541.8, 398, 553, 425.2, 553, 454]], [['s'], [11.2, 56, 31.6, 76.4]], [['C'], [501, 550.8, 473.8, 562, 445, 562]], [['s'], [56, 11.2, 76.4, 31.6]], [['C'], [348.2, 510, 337, 482.8, 337, 454]], [['s'], [11.2, 56, 31.6, 76.4]], [['S'], [416.2, 346, 445, 346]], [['M'], [445, 345]], [['c'], [60.2, 0, 109, 48.8, 109, 109]], [['s'], [48.8, 109, 109, 109]], [['s'], [109, 48.8, 109, 109]], [['S'], [505.2, 345, 445, 345]], [['L'], [445, 345]]]

Comment: @Tim Glad to help!
Comment: Woah! thanks! That did the trick! I've changes the "final_data" part. It left out the last (odd) value.
I've changed it to:
    final_data = []
    for i in range(0, len(new_points),2):
      try:
        if new_points[i+1]:
            final_data.append([new_points[i], new_points[i+1]])
    except IndexError:
        final_data.append([new_points[i]])

Python - re.split string


Random variable inequality: $(X \le x)$

Question: $(X \le x) = (X \le x, |Y - X| \le \epsilon) \cup (X \le x, |Y - X| > \epsilon) \subset (Y \le x + \epsilon) \cup (|Y - X| > \epsilon)$
I don't understand this at all. Where does the last $\subset$ come from?
Answer: In this case, we can split the inclusion: both
$$(X \leq x, |Y - X| \leq \epsilon) \subset (Y \leq x + \epsilon)$$
and
$$(X \leq x, |Y - X| > \epsilon) \subset (|Y - X| > \epsilon)$$
hold. From this, we achieve the inclusion you're having trouble with. Try to prove both these inclusions separately.
Hint: what can we say about $Y$ is we know that $X$ is at most $x$, and $Y$ cannot differ more than $\epsilon$ from $X$?
Comment: 1) If $X \le x$ and $- \epsilon \le Y - X \le \epsilon$ then that implies $Y \le \epsilon + X \le \epsilon + x$. 2) If $X \le x$ and $|Y - X| > \epsilon$, that will also imply $|Y - X| > \epsilon$, we just drop one condition.
Comment: Yep, looking good!

Random variable inequality: $(X \le x)$


Assembly code returning sum of values in an array

Question: I have been provided the c code that the assembly code pulls from, but I thought I had the correct assembly code however I am unable to get the correct output.
Assembly:
<code>.global countMatches

.text

countMatches:
   MOV R2, R0
   MOV R0, #0
countMatches_loop:
   LDR R3, [R2], #4
   CMP R3, #0
   ADDMI R0, R0, #1
   SUBS R1, R1, #1
   BNE countMatches_loop
     BX LR
</code>
The C code:
<code>#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>

extern uint32_t countMatches(char str[], char toMatch);

#define COUNT 5

int main(void) {
    char str[] = "aabbccddeeffgghhiijjkkllmmnnooppqqrrss";
    printf("Question 8, countMatches: Correct Answer = 2\n");
    printf("Question 8, countMatches: Student Answer = %u\n\n", countMatches(str, 'g'));

return EXIT_SUCCESS;
}
</code>
My current output:
Question 8, countMatches: Correct Answer = 2
Question 8, countMatches: Student Answer = 26
Comment: It looks like you're supposed to be counting matching bytes, but you're loading and comparing 32-bit integers.  Also, why are you comparing against 0, instead of the character you were passed?
Comment: You seem to be using the second argument as a count of characters to be compared, but it's actually the character `toMatch`.  You need to look for a null byte to see when to end the loop.
Comment: It might be a good start to write the desired function in C first and get it working.  It's not clear if your difficulties are from misunderstanding the assembly instructions, or the overall algorithm.  As far as the asm though, are you familiar with the difference between `LDR` and `LDRB`?
Answer: Here's my best guess at what your function would look like in C:
<code>uint32_t countMatches(char str[], char toMatch) {
    uint32_t r = 0;
    while (*str) {
        char c = *str++;
        if (c == toMatch) {
            r++;
        }
    }
    return r;
}
</code>
And here's my version in ARM assembly language:
<code>.global countMatches
.text
countMatches:
  mov     r3, #0
  b       load
loop:
  cmp     r2, r1
  addeq   r3, r3, #1
load:
  ldrb    r2, [r0], #1
  cmp     r2, #0
  bne     loop
  mov     r0, r3
  bx      lr
</code>


jquery slideDown() animation is choppy when in container w/o fixed height

Question: That's pretty much it. I have a hidden div that I want to show using slideDown(also tried jquery UI .slide('blind')). If I set a fixed height on its container, the animation is smooth as a baby's bottom. But if I set it the height to auto and have the the slide animation push the height of the container, like I want to, the animation is choppy - there are maybe five "frames". Is there a workaround for this?
Comment: which browsers have you tested?
Comment: I had the same issue with css min-height.
Answer: Ahhh the culprit was the parent's -moz-box-shadow. Removing it fixed the problem.


Paginação de resultados no SQL Server 2000

Question: Às vezes preciso fazer consultas no SQL Server 2000 e paginar os resultados porém só existe a cláusula TOP que limita o número de registros retornados sem um intervalo (offset) outros bancos como MySQL ou PostgreSQL possuem isso e consulta seria assim:
SELECT * FROM tabela LIMIT 0, 50
ou
SELECT * FROM tabela LIMIT 50, OFFSET 0

Como posso contornar esse problema ou emular essa funcionalidade no SQL Server 2000.
Comment: A partir do SQl Server 2012 temos o Offset que tem exatamente a mesma função do limite. Como o upgrade não é possível ...
Answer: Primeiro de tudo eu recomendaria um belo upgrade, contudo existe uma maneira de induzir a fazer algo semelhante
;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

Nesse artigo do SOEN de maneira bem mais completa, mostra outras possibilidades, além de dar uma explicação mais detalhada
Comment: concordo plenamente com o upgrade porém não sou eu que decido isso. Vou testar, obrigado pela resposta.
Comment: Eu sei como é... triste realidade quando não podemos fazer os devidos upgrades quando queremos né? Tbm sofro com isso, principalmente quando preciso dar manutenção em .NET Framework 2.0 com Access
Answer: A consulta abaixo tem o mesmo resulta do "limit 50, 100", ou seja traz entre do registro 51 até o 100.
SELECT TOP 50 *
FROM tabela
WHERE not ID in (
  SELECT TOP 50 ID
  FROM   tabela
  ORDER BY ID ASC
) a
ORDER BY ID ASC;


Checking the solution to a diffential equation.

Question: Is there a quick way to check that the solution to a diffential equation is correct, I know you can diffentiate it and see if it works but this can take a long time (I want to check my answers in an exam and hense time is not in plentful supply). Hense is there are shorter way? Just for an example to check that $(e^{-t})(Acos(2t)+Bsin(2t))$ is the correct genral solution fo $y^{\prime \prime} + 2y^{\prime} +5y=0$?
Answer: The easiest way is to plug it into the differential equation. Does the solution satisfy the differential equation?
Comment: Yes but is there a quicker ways as with examples more complicated then this, it can be a long method and time consuming?
Comment: If you are just dealing with linear homogenous differential equations, you can always double check your eigenvalues using a calculator or WolframAlpha. Honestly, you could plug your differential equation in. Other than that, there really aren't faster ways to check.