Where is this singleton included from?

Question: I recently inherited some IOS app code containing a singleton static objective C class that contains the data shared between various classes in the app. It is very nifty design pattern and I have already taken advantage of it for my additions to the code. The structure of the singleton is very similar to this post
There is just one thing about it that sort-of freaks me out. None of the Objective C Objects that use this singleton import its header file; but they all have access to it's implementation declared interface. This looks a little like "spooky interactions from a distance" to me. Type the name of the singleton and xcode helpfully suggests completions for your code statement. When compiled the compiler, smiles on and never complains about a missing declaration.
Yes, I have checked for imports that import the header, none of them do. I made a simple test class that only included its own header yet there in the methods I can place the singleton's name and access anything in it.
So my question is who or what is doing this automatic import? Xcode? Objective C? Little green aliens?
Comment: Is it included in the `.pch` file?
Comment: What Brian said, you will most likely find it in your projects pre-compiled header. It should be in the Supporting Files group with a name like `-Prefix.pch`.
Comment: You nailed it Brian, want to phrase it as an answer? I'd happily check you.
Comment: Also, being that pch is a generated file, any chance it will be re-generated in the project's lifetime?
Comment: It'll be regenerated when you modify the .pch, or when you clean the project (⌘K)
Comment: Cyrille,, I checked this, the application's pch source file is not re-generated on a clean. Perhaps you meant that the object code is regenerated?
Answer: Its in there somewhere, you can use
<code>find . -type f -exec grep -n -H "Beer.h" {} \;
</code>
in your projects directory, where Beer.h is the filename of your Singleton.
Comment: ... or just Xcode "search navigator" (⌘3), looking for `Beer.h`
Comment: add a -r to that grep Pétur and you don't need the find
Comment: No @gjpc find provides the list of files in all subdirectories to grep.
Comment: True, but `grep -r "Beer.h" *` does just the same.
Comment: I tried searching for Beer in my Xcode and didn't find any.  What am I missing?
Comment: @HotLicks All the fun.
Comment: @HotLicks: I think you need to fax a scan of your driver license to Apple first and wait 2-3 weeks for them to check it.
Comment: Enough to make one want to break out of jail.

Where is this singleton included from?


Is my attempt at using normal approximation of binomial wrong?

Question: Suppose 80% of all drivers wear seat belts, and a SRS of 100 drivers were recorded. What is the probability that more than 75 of the selected drivers will be wearing a seatbelt?
Since n is large enough, I can say that the distribution of the sample mean ~ N(80, 4). Then look at z table for P((75-80)/4 < z), which gave me a probability of 0.1056. However, this is wrong, as the answer is 0.87. I'm just wondering how did I get such a massively different number?
Comment: @Tyberius V(X) = npq = 16
Comment: Where does the 4 come from? Are you given the standard deviation or am I missing something obvious?
Answer: You picked the wrong tail of the standard normal distribution, i.e., you looked up $P(Z < (75-80)/4)$. To get the desired probability you just subtract from $1$.
Note this gets you 0.8944, which is not the official answer. To get 0.87, you use the continuity correction, which means you calculate the probability that a $N(80,4)$ variable exceeds 75.5. Why 75.5? Remember you want the probability that more than 75 drivers wear a seat belt, which means 76 or more. The continuity correction imagines a block of unit width centered at the endpoint 76, which means the block starts at 75.5.
Performing the standardizing, this probability is $$P\left(Z > \frac{75.5-80}4\right) = P(Z > -1.125) = 0.8697.$$
Comment: @LtotheV Exactly! For discrete distributions the continuity correction gets you a better normal approximation.
Comment: Oh, so is this correction to account for the fact that the binomial is a discrete and normal is continuos, and for a continuos distribution equal and more than is just the same as equal, while for the discrete it's not??


Odd Schedule Group C at the FIFA World Cup 2014

Question: Having seen the schedules for the different groups in the group stage, at the FIFA World Cup 2014, I noticed in Group C an odd starting time.
It is match number 6 on the 14th of June 2014, between Ivory Coast and Japan, that starts at 22.00 (UTC-03).
Why is that?
Answer: According to the fifa website, four matches are scheduled on Saturday 14 June:

Colombia vs Greece at 13:00 (local time),
Uruguay vs Costa Rica at 16:00 (local time),
England vs Italy at 18:00 (local time),
Côte d'Ivoire vs Japan at 22:00 (local time)

Four matches are needed on Saturday 14 June because only one match will be played on Thursday 12 June after the opening ceremony.
The late starting time is needed in order to observe 3 hours between every starting time


Como simplificar o código com ForEach do List?

Question: Como utilizar o ForEach() do List na implementação abaixo
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<Pessoa> pessoas = new List<Pessoa>();
        pessoas.Add(new Pessoa(){Nome = "José" , Sexo = "M"});
        pessoas.Add(new Pessoa(){Nome = "Pedro", Sexo = "M"});
        pessoas.Add(new Pessoa(){Nome = "João" , Sexo = "M"});
        pessoas.Add(new Pessoa(){Nome = "Maria", Sexo = "F"});

        bool temMulher = new VerificaSeHaMulher(pessoas).Verifica();
    }
}

class VerificaSeHaMulher
{
    List<Pessoa> pessoas;

    public VerificaSeHaMulher(List<Pessoa> pessoas)
    {
        this.pessoas = pessoas;
    }

    public bool Verifica()
    {
        foreach(Pessoa pessoa in pessoas)
          if(pessoa.Sexo.Equals("F"))
            return true;

        return false;
    }
}

class Pessoa
{
    public string Nome;
    public string Sexo;
}

No caso, quero deixar mais limpa a implementação do método Verifica.
Comment: A confusão faz sentido. Veja: http://pt.stackoverflow.com/q/79894/101 e http://pt.stackoverflow.com/q/22265/101 e http://pt.stackoverflow.com/q/14212/101
Comment: Tem algo específico que acha que está ruim? Parece que está bem simples. Há necessidade de ser uma classe? Nada errado com isto, desde que precise disto. Talvez esteja usando um *strategy pattern* ou variação dele em algum lugar. Mas se estiver usando por acidente, deveria simplificar isto mesmo. Fora isso eu só mudaria a sintaxe da comparação para não ficar com cara de Java. Onde *lambda* entra nessa estória?
Comment: Havia colocado o lambda por ignorância. Ajustei
Comment: @GuilhermeSilva, te aconselho à ler ["foreach" vs "ForEach"](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx) e [Where is List.ForEach()](https://social.msdn.microsoft.com/Forums/en-US/758f7b98-e3ce-41e5-82a2-109f1df446c2/where-is-listtforeach?forum=winappswithcsharp).
Comment: Uma opção para simplificar código é a utilização do resharper é um componente pago mais é bom para esse tipo de ajuda. https://www.jetbrains.com/resharper/
Answer: Eu mudaria algumas coisas mais por estilo. Mas é o meu gosto, não quer dizer que é claramente melhor.
Fora isto eu pensaria se este método não deveria estar dentro de outra classe. Tem utilidade em usar desta forma, dependendo dos seus requisitos, mas se você não conseguir dizer qual o motivo disto ser uma classe, está enfeitando o pavão.
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var pessoas = new List<Pessoa>() {
            new Pessoa() {Nome = "José" , Sexo = "M"},
            new Pessoa() {Nome = "Pedro", Sexo = "M"},
            new Pessoa() {Nome = "João" , Sexo = "M"},
            new Pessoa() {Nome = "Maria", Sexo = "F"}
        };
        bool temMulher = new VerificaSeHaMulher(pessoas).Verifica();
    }
}

class VerificaSeHaMulher {
    private readonly List<Pessoa> pessoas;
    public VerificaSeHaMulher(List<Pessoa> pessoas) => this.pessoas = pessoas;

    public bool Verifica() {
        foreach (var pessoa in pessoas) if (pessoa.Sexo == "F") return true;
        return false;
    }
}

class Pessoa {
    public string Nome;
    public string Sexo;
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Se quiser usar LINQ basta fazer isto:
return pessoas.Any(p => p.Sexo == "F");

Veja funcionando no .NET Fiddle.
Documentação do Any().
Comment: Cara, era isso que eu precisava, obrigado.


What is the volume of this 3d shape?

Question: I'm wondering if there is an equation that represents the volume of an arbitrary 3d primitive
matching this description:
1.) Point at center of sphere
2.) Each edge is the length of the radius
3.) 3 flat sides, 1 arc side
Image:

So it's kind of a sector of a sphere, but instead of a conical shape it's more of a tetrahedral shape, but with a curved end.
Answer: The volume of your figure is $\frac13rA$, where $r$ is the radius of the sphere, and $A$ is the area of the curved end, which is a spherical triangle. A simple formula for $A$ is $r^2(\alpha+\beta+\gamma-\pi)$, where $\alpha$, $\beta$, and $\gamma$ are the angles of the spherical triangle in radians, which are the same as the dihedral angles between the flat faces of your figure. Beyond that, the formula you get will depend on how the three faces or three edges of your figure are specified.
Comment: In this answer I assumed that by "3 flat sides" you meant that the three faces of the figure that contain the origin are planar, and the remaining curved face is a part of the sphere.
Answer: The volume is $\frac13\Omega r^3$, where $\Omega$ is the solid angle subtended at the centre. Wikipedia has several formulas for the solid angle, including the one in Rahul's answer.
Comment: Ooh, that formula for $\tan\frac\Omega2$ is beautiful.

What is the volume of this 3d shape?


Ordinal Regression or Multivariate Analysis?

Question: I want to test whether an individual's grouping (categorical of which there are 4 separate groups) together with their response to another question (likert type, so  assumed ordinal) affects their preference for a range of strategies (which they individually ranked from 1-6)
Would either ordinal regression or multivariate analysis be suitable to test this? My data is not normally distributed, so would need to use non-parametric tests.
Comment: Sounds like two have two categorical variables, and you want to test association. Anything wrong with chi-square test?
Comment: In your question, you don't have enough variables for multivariate analysis. But you can just use the ordinal as response for a ordinal regression model.
Comment: Thank you - yes I realised after I posted that for a multivariate analysis I would need two DVs, and I only have one, so you would say ordinal regression is best to use for influence of two IVs (together) on one DV?
Comment: From the OP I understand there to be 6 dependent variables:  each strategy that receives a rank.
Comment: @rolando2 Maybe. That could also be a single ordinal variable, with values from 1-6.
Answer: As noted in the comments, multivariate analysis isn't possible here.
When the dependent variable is ordinal (as yours is) then ordinal logistic regression is a good starting point, at least, but it makes an assumption of proportional odds. If that assumption is violated, then the most common choice is multinomial logistic regression, but there are some other choices too, such as the partial proportional odds model.
You might also try a tree, or one of the methods based on trees.


How to create additional drupal sites with a drush script

Question: I'm using drush site-install for my initial site, and everything works great, but when I go to try create another site (using table prefixes so I can use the same database), drush attempts to drop and recreate the database, so I loose all the table from my first site. I know how to target drush to a particular subsite, but I'm not sure how to tell the drush site-install command not to drop the database tables.
Is there a better way to do this if I want to setup a initial site with 2 additional sites?
Answer: Drush has very limited support for table prefixes; site-install is just one of the ways that Drush can fail.  sql-sync has similar problems.  It would take a lot of work to fully support table prefixes everywhere; it is best and safest to just use multiple databases when using Drush.


In the context of a MCMC: how to create/interpret a trace for a matrix?

Question: In a Metropolis-Hastings algorithm, I'm drawing a matrix from a proposal. The accepted matrices should constitute draws from a posterior.
If it were just a parameter, I would know how to interpret its trace.
However, now I have a matrix. I'm thinking of just evaluating the accepted draws using a density from a matrix distribution, and then see how the plot varies. However, what should I be looking for?
Comment: I will amend my answer below to account for any additional specifics you can provide, e.g., requirements for the model or the matrix or likelihood/data.
Answer: I hope I understand you correctly: you are trying to find a matrix that optimizes a model for a given set of data.  I am led to believe that the matrix you are varying is the full statement of the model and so represents all of the parameters that aren't otherwise fixed by some conditional statement. You choose Metropolis Hastings to sample from the posterior of model space, viz., matrix space. It also follows that there is some likelihood function defined for your data that will be maximized by a good choice of your model matrix. But as usual there is some wiggle room, and M-H will indeed sample the posterior of your model space (space of matrices) based on your data and the likelihood, and reveal all of the wiggle room in the process.
It would be sensible to follow the standard M-H MCMC algorithm by making small/incremental steps in matrix space. If your matrix is positive definite, your small steps should not violate requirement. I suggest gently rescaling your matrix by multiplying it by a diagonal matrix with diagonal elements close to and centered around 1. You will also want to rotate your matrix gently by multiplying it by a randomly selected rotation matrix with a small angle centered at zero. Other options, like flipping the sign of an eigenvalue, are bolder and will help you move around in matrix space a lot fast and go a lot farther, but you may lose some essential matrix property that you should try to hold invariant, like the trace. But I really don't know what problem you are trying to solve, so it really depends on those details.
What should you be looking for? An acceptance ratio of 30-50%. Constancy of whatever invariants you hold dear. A familiar-looking distribution of your data's likelihood values, or perhaps the negative log likelihood, which is usually what you calculate and can interpret most directly (as energy/$k_BT$, for instance, in physics.) And you should make sure that the time-course of parameter values (matrix elements, trace, what-not) has an autocorrelation function with a characteristic decorrelation time much, much less than the duration of your simulation. That is, you should just be looking at all the standard diagnostics of M-H MCMC. The fact that your parameter space constitutes a set of matrix elements doesn't change any of this.
Comment: Hi Peter, thanks for the answer. The matrix I'm trying to draw does not represent the full model. The remaining parameters mix well. This matrix is being drawn from an Inverse-Wishart, whose mean/mode is located at previous one plus a matrix taken at random (also from a IW): $\mu_{-1}+s_1*M$, where $s_1\sim \text{Unif}(0,1)$
Comment: It seems that you *might* be modeling a covariance matrix. Covariance matrices are positive semi-definite; the set of positive semi-definite matrices is convex, so you are at liberty to perform the affine transformation you suggest. I'd still set $s_1 << 1$ small rather than random uniform $runif(0,1)$. Otherwise, you'll be jumping all over matrix space. Your acceptance rate will be low & you'll miss the wonderful "thermal equilibrium" sampling feature that M.-H. does best. A small $s_1$ means your selection of $M$ from the Inverse-Wishart can be unrestricted. Let the randomness reside there.
Comment: Yes, it's a covariance matrix. I went back to my programme to check what I did. I misreported. I do fix $s_1$. I do $\mu_{-1}+s_1*M$, where $M\sim \text{IW}$. I still not sure I understood your suggestion for a rotation. Where do you multiply the rotation to $\mu_{-1}$, or $M$? In what direction/angle, randomly (uniformly?) selected?

Could you please write in latex a formula? Thanks ;)


Insert multiple DB rows from listview - VB.NET MYSQL

Question: I have a listview that can contain up to roughly 2,000 listview items
I need to loop through the listview and insert each item into a mysql database
is there a better, bulk way, to insert the data instead of doing an insert for each item like follows:
for each itm ...
  insert into whatever ( id ) values ( itm.text ) ...
next

Thanks
Answer: You could build up a file containing the changes and then use the 'LOAD DATA INFILE' functionality -
http://dev.mysql.com/doc/refman/5.0/en/load-data.html


Spivak, Ch. 18, Problem 36: Understanding solution manual "easily" showing $\frac{1}{b-a}\int_a^b \log{f}\leq\log(\frac{1}{b-a}\int_a^b f )$

Question: The following problem is from Chapter 18 of Spivak's Calculus

(a) Let $f$ be a positive function on $[a,b]$ and let $P_n$ be a partition of $[a,b]$ into $n$ equal subintervals. Use Problem 2-22 to
show that

$$\frac{1}{b-a}L(\log{f},P_n)\leq\log\left(\frac{1}{b-a}L(f,P_n)\right )$$
(b) Use the Appendix to Chapter 13 to conclude that for all integrable
$f>0$ we have
$$\frac{1}{b-a}\int_a^b \log{f}\leq \log\left (\frac{1}{b-a}\int_a^b
 f\right )$$

The Appendix to Chapter 13 contains one theorem which says

Suppose $f$ is integrable on $[a,b]$. Then for every $\epsilon>0$
there is a $\delta>0$ such that if $P=\{t_0,...,t_n\}$ is a partition
of $[a,b]$ with $t_i-t_{i-1}<\delta$ for all $i$ then
$$\left | \sum\limits_{i=1}^n f(x_i)\Delta t_i-\int_a^b f(x)dx\right |<\epsilon$$

which basically says that any Riemann sum can be made arbitrarily close to the integral (which is defined in terms of lower and upper sums being equal).
The solution manual solution to part $(b)$

Theorem 1 shows that if $f$ is integrable then for every $\epsilon>0$
there is a $\delta>0$ such that
$$\left | \sum\limits_{i=1}^n f(x_i)\Delta t_i-\int_a^b f(x)dx\right
 |<\epsilon/2$$
for any partition $P=\{t_0,...,t_n\}$ of $[a,b]$, and choices $x_i$ in
$[t_{i-1},t_i]$, for which all $t_i-t_{i-1}<\delta$. It is easy to
conclude that we then have
$$\left |L(f,P)-\int_a^b f(x)dx \right |<\epsilon$$
for such partitions (we need to increase $\epsilon/2$ to $\epsilon$
since $m_i$ may not actually be $f(x_i)$ for any $x_i$ in
$[t_{i-1},t_i]$).

I'm not sure how the relationship between $\epsilon/2$ and $\epsilon$ was reached. Why do we increase $\epsilon/2$ to $\epsilon$?
All I came up with was that since
$$L(f,P)\leq \int_a^b f\leq U(f,P)$$
for all partitions $P$, and by definition of integrability of $f$
$$\forall\epsilon, \exists\text{ partition } P, 0<U(f,P)-L(f,P)<\epsilon$$
then
$$0\leq \int_a^b f - L(f,P)\leq U(f,P)-L(f,P)<\epsilon$$
$$|L(f,P)-\int_a^b f|<\epsilon$$
What does this have to do with Theorem 1?

In particular
$$\left |L(\log{f},P_n)-\int_a^b \log{f} \right |<\epsilon$$
$$\left |L(f,P_n)-\int_a^b f \right |<\epsilon$$
For $n$ sufficiently large. The desired result then follows easily
from part $(a)$.

I don't think I've ever been so frustrated with the use of the word "easily". How does this last step follow from part $(a)$?
Answer: Your proof of $|L(f,P_n)-\int_a^b f|<\epsilon$ is OK, which doesn't have to do with Theorem $1$. Now you have: for each $\epsilon>0$, there is a partition $P_n$ such that
$$\left |L(\log{f},P_n)-\int_a^b \log{f} \right |<\epsilon,$$
$$\left |L(f,P_n)-\int_a^b f \right |<\epsilon.$$
We first prove the desried result from here. This may be not easy for some students. Denote $S=\frac1{b-a}\int_a^b f$.
\begin{align*}
\frac1{b-a}\int_a^b\log f-\log\left(\frac1{b-a}\int_a^b f\right)=&\frac1{b-a}\int_a^b\log f-\frac1{b-a}L(\log f, P_n)\\
&+\frac1{b-a}L(\log f, P_n)-\log\left(\frac{1}{b-a}L(f,P_n)\right )\\
&+\log\left(\frac{1}{b-a}L(f,P_n)\right )-\log\left(\frac1{b-a}\int_a^b f\right).
\end{align*}
We have
$$\frac1{b-a}\int_a^b\log f-\frac1{b-a}L(\log f, P_n)<\frac\epsilon{b-a},$$
$$\text{part (a) }\ \ \Longrightarrow\frac1{b-a}L(\log f, P_n)-\log\left(\frac{1}{b-a}L(f,P_n)\right )\leq0,$$
$$\log\left(\frac{1}{b-a}L(f,P_n)\right )-\log\left(\frac1{b-a}\int_a^b f\right)\leq \log\left(S+\frac\epsilon{b-a}\right)-\log(S).$$
So, we have: for each $\epsilon>0$,
$$\frac1{b-a}\int_a^b\log f-\log\left(\frac1{b-a}\int_a^b f\right)\leq \frac\epsilon{b-a}+\log\left(S+\frac\epsilon{b-a}\right)-\log(S).$$
Letting $\epsilon\to0$ gives that (here we use the continuity of $x\mapsto\log x$)
$$\frac1{b-a}\int_a^b\log f-\log\left(\frac1{b-a}\int_a^b f\right)\leq0,$$
which completes the proof of part (b).
Now, I'll try to explain the $\frac\epsilon2\mapsto \epsilon$ thing, although we don't have to use that in our proof. The key point is that we want $L(f, P_n)=\sum m_i \Delta t_i$, but we only have the Riemann sum $\sum f(x_i) \Delta t_i$, and there may not exist $x_i$ such that $f(x_i)=m_i$. Generally speaking, we can only pick $x_i$ such that $f(x_i)$ is arbitrarily close to $m_i$. This procedure, which is a kind of taking limit, needs another $\frac\epsilon2$-room. Therefore, we need to change $\frac\epsilon 2$ to $\frac\epsilon 2+\frac\epsilon 2=\epsilon$. This is a informal explanation, which can be converted to a rigorous analysis argument.
Rigorous proof:
Given $C>0$ arbitrarily. Since $\displaystyle m_i=\inf_{[t_{i-1}, t_i]} f$, we can find $x_i\in[t_{i-1}, t_i]$ such that $$0\leq f(x_i)-m_i<C\frac\epsilon{(b-a)}.$$
Now we have
\begin{align*}
\left|\sum m_i\Delta t_i-\int_a^b f\right|&\leq \left|\sum m_i\Delta t_i-\sum f(x_i)\Delta t_i\right|+ \left|\sum f(x_i)\Delta t_i-\int_a^b f\right|\\
&<\sum |m_i-f(x_i)|\Delta t_i+ \frac\epsilon 2\\
&<C\frac\epsilon{(b-a)}\sum \Delta t_i+ \frac\epsilon 2\\
&= C\epsilon +\frac\epsilon2.
\end{align*}
If we choose $C=\frac12$, then we will get what the solution manual said. The key point is not $C=\frac12$, but $C>0$. $C>0$ is needed due to the reasons I mentioned above: there may not exist $x_i$ such that $f(x_i)=m_i$  and we can only pick $x_i$ such that $f(x_i)$ is arbitrarily close to $m_i$.
Hope this helps!
Comment: I understood the proof of part (b). However, regarding the $\epsilon/2$ explanation I still do not. I understand that $L(f,P)$ represents some lower sum, and that a Riemann sum for the same partition is larger and thus closer to $\int_a^b f$. However, I don't understand why we specifically doubled the $\epsilon$. How do we know this is the required proportion?
Comment: @evianpring See my editted answer. English is not my mother language. So, when it comes to explain something, I often cannot express my ideas very well. I hope that the rigorous proof I added in my answer can speak more than itself.
Comment: @evianpring It might be worth emphasising that if $f$ is continuous, such $m_i=x_i\in[t_{i-1},t_i]$ *can* always be found. This analysis just covers the cases where $f$ is integrable but not everywhere continuous
Answer: If you are just trying to prove the result, here is an easier way:
Note that since $\log$ is concave, for any $y,y_0>0$ we have
$\log y \le \alpha(y) = \log y_0 + {y- y_0 \over y_0}$.
Let $y_0 = {1 \over b-a} \int_a^b f$ and then note that
${1 \over b-a} \int_a^b \log f \le {1 \over b-a} \int_a^b \alpha = \log y_0 = \log ( {1 \over b-a} \int_a^b f )$.
Comment: In the Spivak text referred to, the proof you've given is part (c) of the question which evianpring is asking about part (b) of.
Comment: Why the downvote?


How to self teach myself guitar?

Question: I didn't see any post of where I can find a site that have good program for free to learn how to play a guitar.
i have seen only those:
How do I choose my first guitar for self-learning?
How to learn to play guitar with a slide?
both links treats to how pick your first guitar but none says how you can learn yourself play it.
Comment: If you have a Mac then GarageBand has some good introductory lessons.
Comment: https://www.guitartricks.com/ is a good resource with both free and paid videos on it.
Answer: These days you really don't need a program, entire training courses are available for free on Youtube.
The general advice given here, though, is that even if you wish to learn entirely on your own, you should still aim to have a few one-to-one sessions with an instructor as they can spot mistakes you may not be able to identify from a video.
You will find a lot of the info you require tagged guitar and learning - here, such as this one on learning your way round the fretboard, or this one on software which will listen to you.
Answer:
Comment: @horatio: How is something mean-spirited today that was considered emancipating and liberating in the seventies? The point I was trying to make, and the point the Sideburns Fanzine was trying to make (in its Dec. 1976 issue, from which the image is copied) is this: there is no special esoteric knowledge or wisdom needed to create music. The most important thing is to start _somehow_, even if it's with three chords. This attitude is deeply rooted in Andy Wahrhol's conviction that what matters is creativity and imagination, not technique. If we forget that, our culture is in big trouble.
Comment: At least teach him D so he can play "Hey hey what can I do" by Zeppelin!
Comment: LOL andy warhol. Nice try.
Comment: @horatio: You know nothing about the history of Punk and Andy Warhol's role in it, do ya? Probably haven't heard of The Velvet Underground and The New York Dolls. Or, you're just an old Hippie who still hasn't gotten over it.
Comment: @horatio: You still haven't answered my question how my original answer was mean-spirited.
Comment: It's not snark, but I can see how @horatio could have been confused, because he clearly didn't know the context. It's probably worth putting that context into the answer.
Comment: ... and by the way: http://music.stackexchange.com/questions/4941/a-total-newbie-wants-to-learn-how-to-write-songs-what-does-he-need/4943#4943 :D
Comment: I agree with @TheChaz2.0 . You need a D in there otherwise you're excluding loads of blues and all of status quo lol
Answer: Start here: http://www.justinguitar.com/
Or here if you figure "free" isn't a necessity: http://www.learnandmaster.com/guitar/
I've used both (mainly the latter) and they worked for me. It's been three years since I started and I can play a lot of songs now and I know the theory to go with it.
Answer: I would just start out with tab, that is how I started out. I have hundreds of guitar pro / other files saved on my computer. If you actually have enough interest in guitar, then you can start working into basic chord theory and stuff like that (major and minor triads, etc).. That's how I have been doing it, and after three years of playing guitar it enabled me to join a jazz band, where I am playing chords that I had no idea existed.
Answer: Buy a "How to play guitar" book. In the scheme of what you'll spend on guitars and accessories, $20 on a book is a great investment.
I don't want to recommend any particular book, because different people have different ambitions and learning styles. If you want to shred heavy metal solos, you'll buy a different book to if you want to strum folk ballads. Browse in a bookshop or music shop, and pick one that appears to suit you. You could also start with a library book.
Any good book will start by showing you how to hold the instrument properly, then move on to well graded exercises and tunes to play.
If you can afford a few lessons, it's money well spent. Failing that, it's great to have a friend or family member to mentor you.
Once you're able to strum a few chords, also get a songbook -- one with songs you know and love, with lyrics and chords. This might seem like a waste of money, when you can find guitar chords on the Internet. But it's useful to have them on paper, and the tabs and chords on the internet are very often not quite right.
Then you can split your time between technique (from the "how to" book), and repertoire (from the songbook etc.)
As soon as you think you can play to an audience, do. It's a great incentive to keep learning and improving.
Answer: Starting with a beginner's book is a great idea. This can teach you many of the super basics that you would get from an in-person teacher, like the hand technique to shoot for, parts of the guitar and some basic musical theory that's helpful.
Having patience with yourself is a key quality when you're first starting out— and that's one of the big advantages of having a live teacher, they can talk you through problems that you may not even see. Building up the physical skill to make the chord shapes with your hand and hold down the strings properly is not easy at first.
I remember being SO frustrated trying to make the same chord shape and strumming to hear a lot of buzzing and barely-notes. Anything you can do to keep it fun and interesting is good. Talk to other guitar players. Find the tabs to a song you really like and learn it.
Hearing yourself play the first few parts of a song you love is so worth it.
Keep in mind that building your skills is great, but no matter where your skill is you can still make a song that communicates something. I like to reference the advice from David Fair in his article How To Play Guitar:

You can learn the names of notes and how to make chords that other people use, but that's pretty limiting. Even if you took a few years and learned all the chords you'd still have a limited number of options. If you ignore the chords your options are infinite and you can master guitar playing in one day.
Answer: i think it depends what you want:
if you want to learn proper technique (ie hand position, music theory, etc) you must look for a good school or mentor. and learn the sagreras book (for example) like a bible. i dont think this can be selftaught
or if you just want to learn some songs to impress girls :P (no classical overcomplicated stuff) what worked for me was practice, practice, practice and the way i found it most rewarding and entertaining was learning to read tabs (it takes a few minutes), practicing barre chords(so daunting at first) and then trying to learn my favorite songs, most of them will be too hard at first, its ok, just choose the passages you can play until you can play along with a record.
 you may want to check the site songsterr.com i could spend literally hours there
practice, practice, have fun!

How to self teach myself guitar?


Como fazer um alert em php

Question: Da para fazer um alert ou outro tipo de mensagem após o usuário errar a senha na pagina de login por exemplo ? tentei fazer desta maneira:
    unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header('location:index.html');
echo '';

mas não funcionou, ele volta pra tela, mas nao da alert algum
Comment: A sua linha `header("Location")` redireciona o usuário para a página `index.html` e todo o ressto do código será ignorado pelo navegador. Se a intenção é mostrar o alerta e não redirecionar, retire essa linha.
Comment: Inclusive, é bom eliminar totalmente o alert. Ponha um intervalo de tempo no location, como solução provisória. , assim seu alert continua intrusivo (como todo alert) mas funciona
Answer: Envie parâmetros com query string para index.html e em index adicione o script de alert.
<?php
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header('location:index.html?info=error&msg=1');

E em index.html adicione o script:

A função getParameterByName foi extraída daqui:
https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
O seu código não executa porque ao redirecionar a página com o header location no PHP o código abaixo em javascript não é executado pelo navegador
Comment: Quando você redireciona o javascript recupera as variáveis na url, pesquise sobre expressões regulares (é a parte magia negra), isso sempre confunde mesmo, mas o que importa mesmo é você entender o que aconteceu, PHP não executa javascript ele encaminha para o browser do cliente executar, o que fizemos foi apenas encaminhar variáveis para o javascript tratá-las e exibir o `alert` ou não.
Comment: Funcionou, mas achei bem complexo, e n entendi esse script para pegar a url da pagina

Como fazer um alert em php


Linear least squares question

Question: I want to solve the following least squares problem:
$$
x = \textrm{argmin} || f(x) ||^2
$$
where $x \in \mathbb{R}^n$, $f(x) \in \mathbb{R}^m$. I know that it is a linear least squares problem, i.e.
$$
\frac{\partial f}{\partial x} = A
$$
where $A \in \mathbb{R}^{m \times n}$ is not a function of $x$. Assume also that $A$ is full rank so that $x$ is unique. I am given $f$ and $A$ and I need to find $x$. Since it is a linear problem, I know that
$$
f = A x + b
$$
for some $b$ but I don't know what $b$ is. Using this form, the usual least squares solution is:
$$
x = \textrm{argmin} || Ax + b ||^2 = -(A^T A)^{-1} A^T b
$$
Inserting $b = f - Ax$ into this gives
$$
x = -(A^T A)^{-1} A^T b = -(A^T A)^{-1} A^T f + x
$$
which implies that $f = 0$ which is certainly not the case. Can anyone see the error here?
Alternatively, if I plug the solution for $x$ into $f = Ax + b$, I find
$$
f = -A (A^T A)^{-1} A^T b + b = \left( I_m - A (A^T A)^{-1} A^T \right) b
$$
so that
$$
x = -(A^T A)^{-1} A^T \left( I_m - A (A^T A)^{-1} A^T \right)^{-1} f
$$
which appears to give me the solution in terms of the known quantities $A$ and $f$. However, for my problem, this approach is not practical since $m >>n$ and the matrix $A (A^T A)^{-1} A^T$ will be too large to fit in my RAM. Does anyone see a clever way to simplify this expression and avoid the need to compute the large $m \times m$ matrix?
The $n \times n$ matrix $A^T A$ is of modest size and can fit in my memory ok.
EDIT: it seems that the matrix $I - A(A^T A)^{-1} A^T$ is singular, so my formula for $x$ won't work.
Comment: You need to know $b$ and then you can solve for $x$. Consider the minimization of $\Vert Ax+b \Vert^2 = (Ax+b)^T(Ax+b) = x^TA^TAx+2A^Tb+b^Tb$ is a quadratic function of $x$ when you know $f,A,b$. $f$ is the observation variables, $A$ is the measurement matrix and $b$ is the bias parameter. If these conditions hold true, you have a standard least squares problem. Here we don't know $b$
Comment: Yes we don't know $b$. Perhaps we should call it a "nonstandard" least squares problem.
Comment: Can you evaluate $f(0)$? This should give you $b$
Comment: The identity $\ (A^TA)^{-1}A^Tf=0\ $ merely implies that $\ f\ $ lies in the $\ m-n$-dimensional nullspace of $\ A^T $, not necessarily that $\ f=0\ $.  In fact $\ f\ $ must be $\ b-b^\perp\ $, where $\ b^\perp\ $ is the perpendicular projection of $\ b\ $ onto the column space of $\ A \ $.
Answer: First, lets clarify the notation by noting the difference between $x_{min}$ which is the solution to $x_{min} = \textrm{argmin} || f(x) ||^2$ and $x$ which is just a variable and has no specific value.
Thus the puzzle on the value of $f(x)$ is resolved: you actually have
$x_{min} -x=(A^TA)^{-1}A^Tf(x)$ for arbitrary $x$.
Setting $x=0$ will give  you $x_{min}=(A^TA)^{-1}A^Tf(0)$
which is consistent with
$x_{min}=(A^TA)^{-1}A^Tb$
since $b=f(0)$
Answer: As I understand it, the $\ f\ $ that you know is the value $\ f=Ax^* + b\ $ at the minimising value $\ x^*\ $, which must satisfy the equation $\ Ax^*=-b^\perp\ $, with $\ b^\perp\ $ the perpendicular projection of $\ b\ $ onto the column space of $\ A\ $.  If this is the only function of $\ b\ $ that you know, however, then your minimising value could be any $\ x\in \mathbb{R}^n\ $ so you have no way of determining a minimiser from that information alone.
Let $\ x^\dagger\in \mathbb{R}^n\ $ and $\ \beta=f-Ax^\dagger\ $ then $\ \|Ax^\dagger+\beta\,\|^2= $$\min \|Ax+\beta\,\|^2\ $, and $\ f=Ax^\dagger+ \beta\ $. Since $\ x^\dagger\ $ here can be arbitrary, just knowing $\ f\ $ and $ A\ $ gives you no information about it.

Linear least squares question


How to simplify $\sqrt[3]{a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}+\sqrt[3]{a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}$?

Question: How to simplify this?
$$\sqrt[3]{a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}+\sqrt[3]{a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}$$
Comment: You can use MathJax to write equations in your questions; see https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Raise it to the third power.
Comment: Use the fact that $a^3+ b^3= (a+ b)(a^2- ab+ b^2)$
Answer: $s=\sqrt[3]{a+\frac{a+1}3\sqrt{\frac{8a-1}3}}=\sqrt[3]{a+b}$
$t=\sqrt[3]{a-\frac{a+1}3\sqrt{\frac{8a-1}3}}=\sqrt[3]{a-b}$
$\bbox[5px,border:1px solid]{s^3+t^3=2a}$
$\displaystyle (st)^3=(a+b)(a-b)=a^2-b^2=a^2-\frac{(a+1)^2(8a-1)}{27}=-\frac {(2a-1)^3}{27}$
$\bbox[5px,border:1px solid]{-3st=(2a-1)j^k}\quad$ with $j^3=1$ and $k=0,1,2$
$(s+t)^3=(s^3+3s^2t+3st^2+t^3)=(s^3+t^3)+3st(s+t)$
So if we set $X=s+t$ then $X$ is solution of $X^3-3stX-(s^3+t^3)=0$
$\bbox[5px,border:1px solid]{X^3+(2a-1)j^kX-2a=0}$
The case $k=0$ is simple :
$X^3-X+2a(X-1)=X(X-1)(X+1)+2a(X-1)=(X-1)(X^2+X+2a)=0$
$X=1$ or $\displaystyle X=\frac{-1\pm\sqrt{1-8a}}2$
According to the graph in real values:

It seems $X=1$ for $a\in[-1,\frac 12]$ and $X=\frac{-1-\sqrt{1-8x}}2$ for $a<-1$.
However I suspect the grapher to take particular branches of $\sqrt[3]{}$.

In fact among the $9$ possible values for $s+t$ (three roots for $s$ and same for $t$ gives $9$ possibilities for $s+t$), I think that $1,j,j^2$ are always reachable by some combination.
When trying manually with the help of a CAS, $s,t=(\frac 12\pm x\sqrt{y})j^k$ so this is possible to get $1=\frac 12+\frac 12$ and the other values I get for instance with the green curve above, is just $s+t$ with a $k_s$ and $k_t\neq 0$.
But I have no idea how to present a clean argument for this observation.
Comment: Finally I found it. I let this answer, for people who want some history on how I reach my other solution.
Comment: Hi, you lost me at the part −3st=(2a−1)j^k why do we need j^k. Also how did you come up with solving this lol? Is there like a formula or rule or something I haven't yet come across. By the way I am only still in high school.
Comment: This is the same than when we have $x^2=c^2$ we can say $x=\pm c$. Here $x^3=c^3$ leads to $x=c$ or $x=cj$ or $x=cj^2$ where $j$ is a third root of unity. But this answer is incomplete, you'd better have a look at the other one.
Comment: is j pretty much the imaginary root and is related to de moivre's theorem ? So for example, imaginary root = 1+2i = j then j^2 is the conjugate as well as the other root so j^3=1? or does it only apply with x^3=1
Comment: In general roots of unity are written $\omega$, thus if $\omega^n=1$ then $\omega=\exp(i\frac {2\pi}{n})$ and $w^k$ for $k=1..n$ are all the other roots. When $n=3$, for historical reason we also use $j=\omega=\exp(i\frac{2\pi}{3})=\frac 12+i\frac{\sqrt{3}}2$ which verifies $j^3=1$ or $j^2+j+1=0$. So when you solve $x^n=y^n\iff x=\omega^k\,y$ for $\omega$ a n-root of $1$ in the same way that $x^2=y^2\iff x=(-1)^ky$ with $\omega=-1$ is a square root of unity. Here for $x^3=y^3$ we have $x=j^ky$
Answer: after the hint above we get
$$\left(\sqrt[3]{a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}+\left(\sqrt[3]{a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}\right)\right)\left(\left(\sqrt[3]{a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}\right)^2-\sqrt[3]{a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}\sqrt[3]{a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}+\left(\sqrt[3]{a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}\right)^2\right)=a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}+a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}$$
can you simplify this?
Answer: $s=\sqrt[3]{a+\frac{a+1}3\sqrt{\frac{8a-1}3}}$
$t=\sqrt[3]{a-\frac{a+1}3\sqrt{\frac{8a-1}3}}$

Let's have $\begin{cases}
\displaystyle X=\frac  12\pm\frac 12\sqrt{\frac{8a-1}3}=x\pm x\sqrt{y}\\\\
\displaystyle x=\frac 12,\quad\displaystyle y=\frac{8a-1}{3}\end{cases}$

$\displaystyle X^3=(x^3\pm 3x^3\sqrt{y}+3x^3y\pm x^3y\sqrt{y})=x^3(3y+1)\pm x^3(3+y)\sqrt{y}$
$\displaystyle X^3=\frac 18(8a)\pm \frac 18\bigg(\frac{9+8a-1}3\bigg)\sqrt{y}=a\pm\frac{a+1}3\sqrt{\frac{8a-1}3}$

Thus the complex roots for $s,t$ are $Xj^k$ with $j^3=1$ and $k=0,1,2$.
Note that if $8a-1<0$ then the complex part of $(s+t)$ which resides in $\sqrt{y}$ cancels if we choose the same $k$ for $s$ and $t$.
In such a case, we have $s+t=2xj^k=j^k$ and for $k=0$ the special value $\bbox[5px,border:2px solid]{s+t=1}$
If we want to be complete there are in fact $9$ possible values :
$\displaystyle X(k,\sigma)=j^k\bigg(\frac  12+\sigma\frac 12\sqrt{\frac{8a-1}3}\ \bigg)$
Then the $9$ values are $\{X(k_1,1)+X(k_2,-1)\mid 0\le k_1,k_2 \le 2\}$

Edit: a note on how I found $X$.
I had a doubt on my previous answer, and starting playing with Maple, I figured out that roots of $s,t$ seems to share this form  $(\frac 12\pm x\sqrt{y})j^k$.
So I calculated $(\frac 12+x\sqrt{y})^3$ and by identification I found the constraint $\bbox[5px,border:1px solid]{12xy^2=8a-1}$
From there, I went on redacting this actual answer.
Answer: Let
$$x=\sqrt[3]{a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}+\sqrt[3]{a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}$$
Take the cubic power of both sides
$$x^3=2a - (2a-1)x$$
or
$$(x-1)(x^2+x+2a)=0$$
Thus
$$x=1=\sqrt[3]{a+\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}+\sqrt[3]{a-\frac{a+1}{3}\sqrt{\frac{8a-1}{3}}}$$


Why is that a Cauchy sequence in $L^2(\mathbb{P})$, by $(1)$?

Question: I quote Øksendal (2003).

Let $\mathcal{V}=\mathcal{V}(S,T)$ be the class of functions $f(t,\omega):[0,\infty)\times\Omega\to\mathbb{R}$ such that $(t,\omega)\to f(t,\omega)$ is $\mathcal{B}\times\mathcal{F}$-measurable (where $\mathcal{B}$ denotes the Borel $\sigma$-algebra on $[0,\infty)$), $f(t,\omega)$ is $\mathcal{F}_t$-adapted and $\mathbb{E}\bigg[\int_{S}^T f(t,\omega)^2 dt\bigg]<\infty$. [...]
Starting from a probability space $\left(\Omega,\mathbb{P},\mathcal{E}\right)$ and a Brownian motion $\left(B_t\right)_{t\ge0}$, if $\phi(t,\omega)$ is bounded and elementary, then
$$\mathbb{E}\left[\left(\int_S^T\phi(t,\omega)dB_t(\omega)\right)^2\right]=\mathbb{E}\left[\int_S^T\phi(t,\omega)^2 dt\right]\tag{1}$$ [...]
If $f\in\mathcal{V}$ one can show that it is possible to choose elementary functions $\phi_n\in\mathcal{V}$ such that:
$$\mathbb{E}\left[\int_S^T|f-\phi_n|^2 dt\right]\to0\tag{2}$$
Then, define
$$\mathcal{I}\left[f\right](\omega)=\int_S^T f(t,\omega)dB_t(\omega)=\lim_{n\to\infty}\int_S^T\phi_n(t,\omega)dB_t(\omega)\tag{3}$$
The limit exists as an element of $L^2(\mathbb{P})$, since $\left\{\int_S^T\phi_n(t,\omega)dB_t(\omega)\right\}$ forms a Cauchy sequence in $L^2(\mathbb{P})$, by $(1)$.

What I cannot understand is the statement in bold above. Why is that true?
Answer: Note that (2) implies:
$$\mathbb{E}\left[\int_S^T|\phi_n(t)-\phi_m(t)|^2 dt\right]\to0. \tag{4}$$
Thus
\begin{align}
E \left|\int_S^T \phi_n(t)dB_t-\int_S^T \phi_m(t)dB_t \right|^2 &=E \left|\int_S^T (\phi_n(t)-\phi_m(t))dB_t \right|^2  \\
&=E \int_S^T |\phi_n(t)-\phi_m(t)|^2 dt \rightarrow 0.
\end{align}
The last equality follows from the Ito isometry and the convergence to zero follows follows from (4).
This proves that $\{\int_S^T \phi_n(t)dB_t \}$ is a Cauchy sequence in $L^2$.
Edit: proof that (2) implies (4):
\begin{align}
E\left[\int_S^T|\phi_n(t)-\phi_m(t)|^2 dt\right]&=E\left[\int_S^T|\phi_n(t)-f(t)+f(t)-\phi_m(t)|^2 dt\right] \\
&\leq E\left[\int_S^T 2|\phi_n(t)-f(t)|^2+2|f(t)-\phi_m(t)|^2 dt\right]  \\
&= 2E\left[\int_S^T |\phi_n(t)-f(t)|^2dt\right]+2E\left[\int_S^T|f(t)-\phi_m(t)|^2 dt\right] \rightarrow 0.
\end{align}
The '$\leq$' follows from the inequality $(a+b)^2 \leq 2a^2 + 2b^2$ and the convergence to zero from (2).
Comment: Sorry, I was accidentally calling $\phi$ what it was suppose to be $f.$ I fixed it in the answer.
Comment: Why does $(2)$ imply $\mathbb{E}\left[\int_S^T|\phi_n(t)-\phi_m(t)|^2 dt\right]\to0$?
Comment: @Strictly_increasing: I edited my previous answer, hope it helps.
Comment: But $(2)$ establishes that $\mathbb{E}\left[\int_S^T|f-\phi_n|^2 dt\right]\to0$ for $f\in\mathcal{V}$, and not that $\mathbb{E}\left[\int_S^T|\phi-\phi_n|^2 dt\right]\to0$, doesn't it?


Add rel = "dofollow" to internal links

Question: I wanted to add rel = "dofollow" to all internal links only like menu links, title links, user links etc. I managed to add rel = "nofollow" to comments and user posted contents. But I am not able to add rel = "dofollow" attribute to internal links.
Any suggestions how can I do this?
-- Thanks
Comment: AFAIK "dofollow" doesn't exists, and is the same as having no rel attribute, so there is no need to add it.
Comment: Thanks for your response. Can you give me some more information/link about nonexistent of dofollow. It would be much better.
Answer: What some people call a "dofollow" link is just a normal link - i.e. a link that is not tagget with the rel="nofollow" attribute.
In other words, this what a dofollow internal link looks like:
target

There is no dofollow (or similar) attribute you can add to the link.  The absence of nofollow is what you're looking for.

Add rel = "dofollow" to internal links


$2$ tourists came from $M$ and $N$ places to meet each other at same time

Question: $2$ tourists came at the same time from $M$ and $N$ places to meet each other, the distance between $M$ and $N$ in $33 km$. After $3$ hour and $12$ minutes distance between them reduced to $1km$, after $2$ hour and $18$ minutes First tourist's distance to cover till reaching $N$ place was $3$ times more than second tourist's distance till reaching $M$ place, find the speed of each tourist.
I've tried something like this,
$v=32/3.12$ thinking it would give me average speed of both tourists then I divided it by $3$ to get the speed of first tourist but obviously got wrong numbers.
Correct answers are : $4,5km/h$ and $5,5km/h$
I've been at this problem for an hour now and still interested in how to solve this, please help.
Comment: You first talk about "the speed of each tourist", which seems to imply that there is exactly one speed per tourist, i.e., that the tourists are moving with uniform speed. But then later you talk about "average speed of both tourists", which only makes sense if their speed changes. As far as I can tell, there's no hope of solving this problem without the assumption of uniform speeds, so I suspect it's the part where you talk about the average speeds where you're mistaken.
Comment: Just to be 100% clear, do the tourists walk in a straight line in exactly the opposite directions, or a triangle?
Comment: should be straight line in opposite directions
Comment: I don't know how to approach this problem anyway
Answer: After 3 hours and 12 minutes, the total distance was reduced by $33 - 1 = 32$, which, given the speeds $v_1$ and $v_2$ for the first and second tourist respectively, tells us that:
$$v_1 + v_2 = \frac{33 - 1}{3.2} = 10 \iff v_1 = 10 - v_2$$
We also know that, 2 hours and 18 minutes later:
$$33 - (3.2 + 2.3) v_1 = 3(33 - (3.2 + 2.3)v_2) \iff v_1 = 3v_2 - 12$$
Combining both, we find:
$$10 - v_2 = 3v_2 - 12 \iff v_2 = 5.5$$
$$v_1 = 10 - v_2 = 4.5$$


Fazer uma busca para meu site em duas tabelas

Question: Estou precisando de fazer uma busca para meu site em que me retornassem primeiro as empresas que possuem algo semelhante ao digitado e, logo em baixo, mostrassem todos os produtos registrados com algo semelhante ao digitado.
Tenho duas tabelas:
tbl_empresas
`id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(100) NOT NULL,
  `descricao` longtext,
  `imagem` varchar(255) DEFAULT NULL,
  `data_cadastro` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)

e
tbl_produtos
`id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(70) NOT NULL,
  `descricao` longtext,
  `aplicacao` varchar(255) DEFAULT NULL,
  `imagem` varchar(255) DEFAULT NULL,
  `codigo_original` varchar(50) NOT NULL,
  `data_cadastro` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `tbl_categoria_id` varchar(11) NOT NULL,
  `tbl_empresa_id` varchar(11) NOT NULL,
  PRIMARY KEY (`id`)

Tentei realizar uma pesquisa usando JOIN, porém ele me retornaria as duas tabelas juntas, dessa maneira não conseguiria separa o que é produto e o que é empresa na visualização da pesquisa.
Eu queria que minha pesquisa mostrassem primeiro as empresas, depois os produtos (sem relacionamento) e que fosse possível fazer uma paginação depois.
Isso seria possivel?
Se sim, como eu precisaria de fazer?
Comment: Fazer o select na tabela de empresa e depois usar o UNION com o select ta tabela de produtos te ajudaria?
Comment: eu não tinha tentado UNION, vou fazer um teste aqui
Answer: Você pode unir o resultado de dois selects usando o UNION ALL
Exemplo:
SELECT nome, descricao, 'empresa' AS tipo FROM tbl_empresas
where descricao like 'palavra%';

UNION ALL

SELECT nome, descricao, 'produto' AS tipo FROM tbl_produtos
WHERE descricao LIKE 'palavra%';

Veja funcionando no SQLFiddle
Comment: o select funcionou, porém eu consigo fazer a distinção dessas tabelas ao mostrar na visualização? ou ficaria tudo junto mesmo?
Comment: Pode fazer a distinção por uma coluna, vou editar a resposta.
Comment: @Lucas funcionou?
Comment: esta quase funcionando, falta juntar com o where
Comment: Mas é só colocar o `where`, jovem. Editei a resposta
Comment: consegui fazer com where, porém tive um problema de "Undefined index: descricao" ao mostrar
Comment: Ok, muito obrigado!
Answer: select nome, descricao from (
  SELECT nome, descricao, 1 ordem FROM tbl_empresas
  where descricao like 'palavra%'
  UNION
  SELECT nome, descricao, 2 ordem FROM tbl_produtos
  WHERE descricao LIKE 'palavra%'
)
order by ordem;


ESX Server Setup cannot detect my LAN card

Question: I want to install esx server on my system that has LAN card, (Realtec RTL-8110sc)
How to install it?
thanks
Answer: It's quite likely that the Realtec card is not on VMware's Hardware Compatibility List.
Comment: Wow, Is there any way to install with unsupported cards?
Comment: You can use the above link to check if the card is supported or not. If it is not, then you're out of luck with regards to that specific card. At that point, you would need to consider adding a PCI/PCIe card that is supported by VMware.
Comment: No. The ESX hypervisor is monolithic. You can't add in extra drivers or customise it. Fortunately, NICs with compatible chipsets are widely available and consumer-priced options are available.


build user chroot on first login

Question: I'm using ldap for remote user authentication and I basically need to either figure out how to:
a.  chroot a user on machine b from machine a via nfs,(which doesn't seem possible without mounting more directories than I'm comfortable with)
or -------
b.  After adding a user to the ldap db on machine a, force a script to be executed on machine b during the users login that will auto chroot the user before they are allowed to do anything upon their first login.

I'm thinking my second option is probably the best bet, and was thinking along the lines of using pam_exec.so to call the script.  However, I have a few concerns about this approach.  First, I'm not sure if the script that will be run will have root permissions which it will need to perform the chroot.  Second, I'm not sure if pam_exec happens early enough in the login process to be an effective option.  Lastly, I need to make sure that the code works in both pam.d/ssh and pam.d/su to consider it a valid solution.
Are my concerns valid or does it seem like this would be a good solution?  Or is there a better approach to this problem.
Comment: Can you explain in more detail the requirements for doing this? is this about _security_? limiting the ability of the user to execute commands? any other reason?
Comment: @dawud Basically,I want the users on the remote machine to be chrooted for the slight bit of security that chrooting offers.  However, I don't want to have to login into 2 different machines every time I add a user.  Does that make sense?
Answer: First of all, arguably, chroot might not be considered a security feature. There are opinions in the other direction, as well.
Arguably, what you need to implement is a reproducible, auditable method of limiting the ability of the user to perform actions other than the strictly allowed.
If you register your users in LDAP, surely you have already deployed the mechanisms to perform LDAP authentication on any machine connected to this LDAP, be it by means of sssd or using any other PAM module, it is not relevant to the rest of the solution, and is assumed to be already in place (in my case, I'm using freeIPA and sssd).
To implement this scenario, what I currently do is the following (be aware that this kind of restrictions requires that several conditions are met, otherwise the restriction can be easily circumvented):

The users do not belong to the wheel group, the only one authorized to use su (enforced via PAM). Usually, a non-LDAP user (sysadm) exists to allow trusted administrators performing actions in cases of disaster recovery or LDAP unavailability.
The users are given a properly secured rbash with a read-only PATH pointing to a private ~/bin, this ~/bin/ directory contains links to all allowed commands, for example:
$ ll ~/bin
total 0
lrwxrwxrwx. 1 root dawud 14 Sep 17 08:58 clear -> /usr/bin/clear*
lrwxrwxrwx. 1 root dawud  7 Sep 17 08:58 df -> /bin/df*
lrwxrwxrwx. 1 root dawud 10 Sep 17 08:58 egrep -> /bin/egrep*
lrwxrwxrwx. 1 root dawud  8 Sep 17 08:58 env -> /bin/env*
lrwxrwxrwx. 1 root dawud 10 Sep 17 08:58 fgrep -> /bin/fgrep*
lrwxrwxrwx. 1 root dawud  9 Sep 17 08:58 grep -> /bin/grep*
lrwxrwxrwx. 1 root dawud 10 Sep 17 08:58 rview -> /bin/rview*
lrwxrwxrwx. 1 root dawud 13 Sep 17 08:58 rvim -> /usr/bin/rvim*
lrwxrwxrwx. 1 root dawud 13 Sep 17 08:58 sudo -> /usr/bin/sudo*
lrwxrwxrwx. 1 root dawud 17 Sep 17 08:58 sudoedit -> /usr/bin/sudoedit*
lrwxrwxrwx. 1 root dawud 13 Sep 17 08:58 tail -> /usr/bin/tail*
lrwxrwxrwx. 1 root dawud 11 Sep 17 08:58 wc -> /usr/bin/wc*

the users are given a restricted, read-only environment (think of stuff like LESSSECURE, TMOUT, HISTFILE variables). This is to avoid shell escapes from commands like less or vim.
if MAC restrictions are in place (the specific GNU/Linux distribution you are using has SELinux enabled), the users are mapped to the SELinux user staff_u and given rights to execute commands as other user as required via sudo. The specific sudorules allowed need to be carefully reviewed to prevent the user from circumventing these limitations, and can also be deployed in your existing LDAP infrastructure (this is one of freeIPA features).
the users' /home, /tmp and possibly /var/tmp are polyinstantiated via /etc/security/namespace.conf:
/tmp       /tmp/.inst/tmp.inst-$USER-     tmpdir:create   root
/var/tmp   /tmp/.inst/var-tmp.inst-$USER- tmpdir:create   root
$HOME      $HOME/$USER.inst/              tmpdir:create   root

Polyinstantiation of directories is not a new feature, it has been available for quite a long time now. As a reference, see this article from 2006. As a matter of fact, a lot of modules already use pam_namespace by default, but the default configuration at /etc/security/namespace.conf does not enable polyinstantiation.
Also, /etc/security/namespace.init should make all skeletal files read-only for the users and owned by root.

This way you can choose whether the users can execute any command on their own behalf (via a link in the private ~/bin directory, provisioned via /etc/skel, as explained above), on behalf of other user (via sudo) or none at all.
Comment: this is very informative and definitely worth of a +1, but it  doesn't really answer my quetion.  Unfortunately, I'm not in charge of the security policy so I'm stuck using the chroot for now.  I think that we are using chroots to hide / limit users seeing/effecting other users actually, which would be handled by proper permissions like th article you posted says....sigh.
Comment: That is precisely what a polyinstantiated `/home` plus a properly secured `rbash` accomplishes. A user cannot see another user's home directory.
Comment: even with that being said, I still need to figure out how to trigger a script to be run by pam_exec or some other solution, as I have a script that will not only chroot users but automatically build control groups for them.  So even if I threw out the chrooting, still need the cgroups to automatically be built.
Comment: Sure, you can use `/etc/security/namespace.init` to provision `cgroups`.
Comment: ok, ok.  you've sold me.  I did ask if there was a better approach after all.  Had to look up what polyinstantiated directories are for and am looking at the relevant /etc files.  Now I just have to make the case to my boss :)  .  In case someone is frustrated by me accepting this approach, realized I could just use a subshell from the ldap server to trigger a script the remote server when adding the ldap user if I wanted to...
Comment: I've been using this kind of deployment in sensitive environments where users' access is quite limited, and so far it's been successful. Before you jump into it, though, take the time to spawn a virtual machine and test all these for your use case.
Comment: actually, I'm using Fedora, and I don't think it will support polyinstantiation of directories until version 21 :(
Comment: See my last edit.
Comment: the concept that Chroot is not a security feature is actually very outdated. If you actually read that article, it implies that the way you could break out of a chroot requires either a vulnerable daemon server process, or idomatic human error. the simple fact is that chroot provides file system visualization. this is the very same thing that systems like openvz uses. infact openvz is just a Chroot, but that which covers all the implied security provisions needed to also seperate the process table. to simply separate users, chroot is MORE than sufficient.
Comment: if your chroot is used to seperate users. if you do NOT run a daemon in the chroot. if you do not mount the /proc and /sys file systems, and if you severely limit and audit all available binaries available to the user, then an attacker would have to compromise the kernel. the same could be so for any real virtualisation technology, like proxmox and openvz. this is why sshd server, apache2, dovecot, sendmail, openVPN, and just about every server software has Chroot built in AS A SECURITY FEATURE
Comment: The article I've linked above is from a year ago. Granted, that can be a _long ago_ in technological time.
Comment: @RapidWebs it would be interesting if you share your thoughts on this question in an answer.
Comment: http://serverfault.com/questions/559463/why-running-namedbind-in-chroot-is-so-important-for-security-or-maybe-it-is-n/591833#591833

build user chroot on first login


Is it the case that that $E(X_i) = 0 \implies \sum_{i=1}^n E|X_i| < \infty$?

Question: Is it the case that that $E(X_i) = 0 \implies \sum_{i=1}^n E|X_i| < \infty$? If so, what's the proof? Here $X_1, X_2, ...$ are random variables.
I considered Jensen's inequality, i.e. $E|X_i|\geq |E(X_i)|$ but that doesn't help. Also, I "know" it's supposed to be true but I couldn't find a proof.
Answer: This is true because $\mathsf{E}|X_i|$ is finite for each $1\le i\le n$ (otherwise, either $\mathsf{E}X_i=\pm\infty$ or $\mathsf{E}X_i$ doesn't exist).
Comment: $\mathsf{E}X_i=0$ is possible only if $\mathsf{E}|X_i|<\infty$.
Comment: Thank you for answer. I understand that if $E|X_i|$ is finite then the sum is finite as well. But could you be a little more explicit why $EX_i < \infty \implies E|X_i| < \infty$. I see what you write in parenthesis but this is not totally clear to me (sorry if obvious).


sort the solr search result. give error can not sort on multivalued field: name

Question: I am newer to the Apache Solr search.
I am trying to sort the result set in the Solr query.
Query : name:abc* AND hidden:false & sort=name desc
It's showing the error :
can not sort on the multivalued field: name
Solr version is: 7.2.1
Comment: If you don't intend to have the field `name` represent multiple values, you probably want to make the field single valued (i.e. define `multiValued="false"` for the field).
Answer: If you're using recent versions of the Solr (>5.3) you should be able to use min or max functions to do sorting on multivalued fileds like this:
<code>sort=field(field_to_sort_on,min) asc
</code>
The only requirement to achieve this is to use DocValues on this field - so finding minimum/maximum on multivalued field could be achieved efficiently


Webpack + Firebase: Disable parsing of Firebase

Question: I am working on a web app that uses Webpack to bundle modules.  For whatever reason, the introduction of Firebase into the app is causing Webpack to throw an error.  This error is occurring when Webpack attempts to load the Firebase module.
How do I go about excluding Firebase from Webpack, but can still call
import Firebase from 'firebase';
from within my JS files?
Here are some screenshots of the error.
pic1
pic2
Comment: It might expect global context. It's hard to say exactly without checking out Firebase code. See https://github.com/webpack/docs/wiki/shimming-modules#imports-loader for one way to deal with it.
Answer: tl;dr Exclude /node_modules/ from the babel-loader paths.

Your 2nd pic shows the error on firebase-web.js:12:
Uncaught TypeError: Cannot read property 'navigator' of undefined

Unfortunately, firebase-web.js is minified, so it's hard to tell exactly what's going wrong. Let's beautify firebase-web.js using http://jsbeautifier.org:

Now it's plain to see that the script is trying to access aa.navigator, but aa is undefined. You can see at the top of the file:
var h, aa = this;

We can see what the script is trying to do now: it expects this === window so it can access window.navigator.
But why is this undefined? It's because, at some point, the script is being put into strict mode, which causes this === undefined instead of this === window. We can see that in the webpack-generated main.js:

It turns out that the "use strict" is being prepended by babel-loader, so we should be able to disable babel-loader for firebase-web.js to solve the problem:
...
module: {
  loaders: [
    {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}
  ]
}
...

Good, now there's no more "use strict" and the error no longer occurs!
(Full disclosure: I worked on the same project that @kashiB is working on and have access to the source code.)
Comment: Thank you so much ... I have spending a week trying to figure out the error on window.navigator, on a another context but with babel. great !!
Comment: The **tl;dr** comment is what helped me. Turns out, I was doing this: `exclude: '/node_modules/'`. I removed the quotes and everything started working. Now only if I could get those 3 days back!
Comment: I was using rollup and `exclude: '/node_modules/**'` alone did not fix the issue. I had to add `useStrict: false` to my rollup config also
Comment: @lukejacksonn `'/node_modules/**'` is wrong. The slashes are the JS delimiters of a RegEx expression. If you add quotation marks (`'`) you turn it into a regular string. `'node_modules'` on the other hand should work as well as `/node_modules/` does.
Comment: I am a babel noob. I am working on a react-native project, what file I am placing this in?
Comment: react-native does not use webpack
Comment: I hope everyone realizes `import Firebase from 'firebase';` is not es6, just yet another Angular trap. There are two errors: import does not take a semi, and the path needs to have both a .js and at least a ./ or other relative/absolute path. And I hope some of us are finally going simple, using es6 Modules and avoiding legacy workflow. Webpack is a curse .. avoid it.


Redirecionamento de URL em IIS

Question: Estou tendo problemas com redirecionamento aqui na empresa, é o seguinte:
Tenho um servidor IIS onde tenho o site atual da empresa e dentro deste site tenho webservices rodando, utilizando um dominio ???.com.br na porta 80.
Minha dúvida é que contratei uma empresa para criar um novo site e o site da minha empresa vai ficar em um subdomínio desta empresa que contratei e gostaria que quando alguém digitar www.???.com.br (meu domínio) ele seja redirecionado para o subdomínio da empresa que contratei para desenvolver o novo site, problema maior é que ao digitar o meu domínio o usuário vai ter que vir no meu IIS para depois ser redirecionado, pois não posso redirecionar meu domínio para o subdomínio da empresa que fez o novo site pois tenho os meus webservices rodando no mesmo domínio www.???.com.br
Alguém pode me dar uma luz de como resolver este problema? Meio confusa a explicação mais acho que deu pra entender.
Answer: Há muitas formas de se fazer o redirecionamento para outra página, independente delas estarem no mesmo domínio.
1) Se seu domínio apontar para uma página HTML, por exemplo, você pode incluir a tag meta abaixo dentro do  head:
<meta http-equiv="refresh" content="0;http://subdominio.dominio.com.br">
Provavelmente é o melhor método, pois é simples e funciona mesmo que o browser cliente esteja com o Javascript desabilitado.
2) Você pode redirecionar utilizando Javascript:

3) Se a página for ASP você pode utilizar:
<% Response.Redirect ("http://subdominio.dominio.com.br") %>
4) Se a página for PHP você pode utilizar:
<?php header('location: http://subdominio.dominio.com.br');
Dentre outras formas.

Redirecionamento de URL em IIS


Deep deterministic policy gradient : which network do I have to use for testing?

Question: We know that Deep deterministic policy gradient (henceforth ddpg) is characterized by two kind of neural networks: one related to the critic $Q$ the other to the actor $\mu$ with parameters $\theta^\mu$ and $\theta^Q$ respectively. For stability issues, Lillicrap et al introduced two additional neural networks i.e. the critic target and the actor target with weights ${\theta^Q}^{'}$ and ${\theta^\mu}^{'}$ respectively.
Following the DDPG protocol, for each timestep the weights associated with the target networks actor get slowly updated i.e. :
${\theta^\mu}^{'} \leftarrow \tau {\theta^\mu} + (1-\tau){\theta^\mu}^{'}$
${\theta^Q}^{'} \leftarrow \tau {\theta^Q} + (1-\tau){\theta^Q}^{'}$
slowly because $\tau <<1$.
My question is: when my training is over, that is to say that the action provides a certain reward satisfying (if any) other conditions, which kind of neural network should I use for testing what I have just got? The actor or the target actor ?
Answer: The actor network should be used for the test/validation phase since the the actor weights get optimized both in the critic and the actor loss (see of course [1]).
It is also true that at the end of the training there is no a huge difference between the actor and target actor because of the slow update.
[1] Lillicrap, Timothy P., et al. "Continuous control with deep reinforcement learning." arXiv preprint arXiv:1509.02971 (2015).


Quantifying applicability domain for predictive models?

Question: I have a big dataset and I want to build a classification model (svm, rf, ann etc.). Then I split the original dataset into training set and test set. I build the model using training set. After it was done, I use the model to predict the test set. Here, the training set and test set should be similar in data structure, that means they are located in the same data domain, right?
If the test set is not located the data domain of the training set, then the prediction result for the test set should be worse than those in the train set domain. it is right to express this?
So, how can I quantify the applicability domain for a predictive model? that means, when I have the new dataset, how can I check if it located in the applicability domain of the model?
some links:
http://en.wikipedia.org/wiki/Applicability_domain
http://www.moleculardescriptors.eu/tutorials/T7_moleculardescriptors_ad.pdf
Any points are appreciated.
Answer:
If the test set is not located the data domain of the training set, then the prediction result for the test set should be worse than those in the train set domain. it is right to express this?

Yes and no: usually the if the test data is outside the training domain, then the results usually are worse. But keep in mind that this is a symptom of overfitting your model to the training domain. The thing that matters is the quality of the predictions for your application domain (it needs to be fit for purpose). So the testing needs to check the desired application domain, and it often makes sense to test various aspects of that in a more detailed manner.
You can then think and judge how closely the training domain needs to match the application domain.
In certain ways, predictive models are usually applied outside the training domain, while for other aspects the predictions are done inside the training domain.
Consider a model that predicts some analyte concentration of clinical relevance as a function of some kind of measurement (e.g. spectroscopic).
The application domain will be spectra of new (unknown and measured in the future) patients. For training I may get away with preparing calibration samples*. However, as the application domain are patients, I need to test also patient sample predictions against reference values. Even if I train on patient samples, I need to test for the application domain of unknown patients.
In addition, I need to establish how often the calibration needs to be redone. I.e. I need to test the application domain of unknown patient samples acquired and measured hours, days, weeks after the training data.

So, how can I quantify the applicability domain for a predictive model? that means, when I have the new dataset, how can I check if it located in the applicability domain of the model?

I may be able to specify from the training spectra limits of the distribution that I want to restrict my predictions on. This would be the training domain in the spectra ($\mathbf X$) space and often guided
- either rather closely by the training data ("do not extrapolate outside the calibrated signal range")
- or by external knowledge, e.g. requiring 0 $\leq$ absorbance $\leq$ 1 in a spectra quality test.
This is one way of specifying applicability.
For other aspects of applicability, the reasoning is usually the other way round: you specify how much deterioration of the predictive quality you are willing to tolerate, and then look e.g. for how long you can use the same calibration. So you end up with a specification "redo calibration weekly", or you specify that test samples should be run every so often.
These arguments work exatcly the same for a classification instead of regression/calibration. (Just that measuring the predictive ability of a classifier is more difficult.)
From your tags I assume you ask about QSAR. Also in that case, the model is typically built in order to predict the activity of compounds unknown to the model, i.e. outside the training data. Meaning whatever selection of compounds you train on, you need to test with compounds unknown to the model. You can then go on an slice the test results according e.g. to different groups of compounds. You may also exclude whole groups of compounds from training and check how that model does for this group.
Comment: @Kevin: this sounds to me as if you need to find proper consulting. Your links state that there is no procedure to define the applicability domain for QSAR models that is universally agreed upon. In other words, you need to think what properties your application needs and from that conclude how to verify that your QSAR model is fit for purpose (= valid) and which definition(s) of the applicability domain can be used. My guess is that this is much less a problem of coding than of thoroughly understanding the application. But that's my 2 ct, and I don't have any first hand experience in QSAR.
Comment: Thank @cbeleites. One more thing is that can you give an example to explain how to apply your anwser, best in R code? and can you do some work for finish the calculation of AD shown in the above url? since for people like me, it is difficult to change the statistical equation to R code, and for me I often apply the existing approach to solve my problem. so thank you for your help. and Yes, my question is about QSAR and AD in QSAR has some definition as I list in the url and some others. but the existing applications are scarce, especially in R. so I hope you and other statistician can help.
Comment: thank you. You are right. For me, it is true to understand the application well. I am learning some literatures for this.


getting rid of negative predictions in linear regression

Question: I'm working on a linear regression formula for a forecasting model. My model requires non-negative predictions.
The model works well when predictors have big values; however, I get negative predictions pretty often when predictors have small values.
I was hoping to find a solution whereby the model wouldn't be linear but somewhat exponential to converge to 0, but not getting there unless the variables are both 0.
This is an example of my constant and coefficients for two variables:
<code>CONST   -202,4356389
COV        0,741149304
USERS    369,5808457
</code>
Comment: Can you define what you mean "as accurate"? Accurate measured how? What sort of thing is the response measuring? Is it counts? Some kind of measurement? Times? A monetary amount?
Comment: Don't do that then. To ensure positive predictions, which is the issue here, you need to use a logarithmic link (in generalized linear model terminology). In fact Poisson regression works well even for non-counted variables. See  http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/
Comment: You mean negative regression coefficients? Why do they need to be "non negative"? What do you mean by "big variables"?
Comment: I've edited presentation rather heavily (it's evident that English is not your first language) but do check that I have your meaning correctly given.
Comment: I don't mean the coefficients have to be positive, I only want the results to be positive, I'm currently using excel to generate the coefficients, I would like a way to convert my model in such a way to always give positive values and still be as accurate.
Comment: I'm measuring traffic in Terabytes, so far the forecast gives realistic results, however at the start of the forecast when the dependant values are low the forecast is negative.
I'm only starting in this field so I would please like more detailed answers.
Answer: As @Nick Cox points out in a comment, if you want your predicted values to always be positive, you don't want linear regression. If the dependent variable is a count (and maybe even if it is not) you could use Poisson regression or negative binomial regression. If it is bounded, you can transform it to 0-1 and then use beta regression. There are other options too.
Or it might be that you want to transform your dependent variable. If your DV is never negative then you can take the log.  Then the predicted values on the raw score would never be negative.


I want to show that, ${\Phi\tan{9^\circ}-\phi\tan{27^\circ}\over \sin^2{9^\circ}-\sin^2{27^\circ}}=4$

Question: $\phi$: golden ratio, $\Phi={1\over \phi}$
I want to show that,
$${\Phi\tan{9^\circ}-\phi\tan{27^\circ}\over \sin^2{9^\circ}-\sin^2{27^\circ}}=4$$
Using $\sin^2{x}={1\over 2}(1-\cos{2x})$
$${\Phi\tan{9^o}-\phi\tan{27^o}\over \cos{54^\circ}-\cos{18^\circ}}=2$$
As for numerator
$${\sqrt5(\tan{27^\circ}-\tan{9^\circ})-\tan{27^\circ}-\tan{9^\circ}\over \cos{54^\circ}-\cos{18^\circ}}=4$$
exact trig values
if I was to plug in the corresponding values it would be a lot of work to simply and might not even get to the result.
Any idea would help me to simplify the LHS?
Comment: I think you simplified the numerator incorrectly, even after your edit. It should be: $$\Phi \tan(9^\circ)-\phi \tan(27^\circ)=\frac{\sqrt{5}-1}{2}\tan(9^\circ)-\frac{1+\sqrt{5}}{2}\tan(27^\circ)=\frac{\sqrt{5}(\tan(9^\circ)-\tan(27^\circ))-\tan(9^\circ)-\tan(27^\circ)}{2}$$
Comment: In the intermediate step, you have a factor of $\frac{1}{2}$ in the denominator, so when you multiply that factor out, you should get $4\frac 1 2=2$ on the right side. You still get $4$ in the end, but I'm going off the intermediate step in my answer, so putting the correct $=2$ instead of the incorrect $=8$ on that step is important.
Answer: Noting that
$$ \phi=2\cos(\frac{\pi}{5})=2\sin(\frac{3\pi}{10}), \Phi=2\sin(\frac{\pi}{10})$$
from https://en.wikipedia.org/wiki/Golden_ratio, so one has
\begin{eqnarray}
{\Phi\tan{9^\circ}-\phi\tan{27^\circ}\over \sin^2{9^\circ}-\sin^2{27^\circ}}&=&{2\sin(\frac{\pi}{10})\tan(\frac{\pi}{20})-2\sin(\frac{3\pi}{10})\tan(\frac{3\pi}{20})\over \sin^2(\frac{\pi}{20})-\sin^2(\frac{3\pi}{20})}\\
&=&2{2\sin(\frac{\pi}{20})\cos(\frac{\pi}{20})\tan(\frac{\pi}{20})-2\sin(\frac{3\pi}{20})\cos(\frac{3\pi}{20})\tan(\frac{3\pi}{20})\over \sin^2(\frac{\pi}{20})-\sin^2(\frac{3\pi}{20})}\\
&=&4{\sin^2(\frac{\pi}{20})-\sin^2(\frac{3\pi}{20})\over \sin^2(\frac{\pi}{20})-\sin^2(\frac{3\pi}{20})}\\
&=&4.
\end{eqnarray}


Why the definition of productive economy in Leontief Open Model is such?

Question: Answered on Economics Stack Exchange: https://economics.stackexchange.com/questions/45802/why-the-definition-of-productive-economy-in-leontief-open-model-is-such
The Leontief Open (Production) Model is a simplified economic model for an economy in which consumption equals production, or input equals output.
In this model, the entries in the consumption matrix represent non-negative monetary values (in some arbitrary monetary unit) of various types of outputs (such as commodities or services). Every $(i,j)$th entry in the consumption matrix is the monetary value of the output of $i$th industry needed by the $j$th industry to produce one monetary unit of its own output. It means that arbitrary consumption matrix, commonly denoted $C$, can be represented in the form of an input-output table:

For example, in order to obtain a unit of output from industry 3 it takes $c_{13}$ units of output from industry 1, as well as $c_{23}$ of output from industry 2, and $c_{33}$ of output from industry 3 (i.e. itself).
The open sector, in this context, refers to the external consumer whose demands are required to be satisfied and its demands are represented in the model by special kind of column vector where each $i$th entry corresponds to the non-negative monetary value of the output required by the external consumer from the $i$th industry. Such column vectors are called demand vectors and such individual vectors are often denoted $D$ (capital "d") or $\textbf{d}$ (boldface lower case "d").
Total production associated with a particular consumption matrix $C$ and some demand vector $D$ in this model is represented by a column vector where every $i$th column is a non-negative monetary value of the output of $i$th industry required to be produced to satisfy the needs of the external consumer. Such column vectors are called production vectors and are commonly denoted $X$ or $\textbf{x}$.
These triplets of associated matrices (production vector $X$, consumption matrix $C$, and demand vector $D$), based on the assumption that production equals to the sum of internal and external demand/consumption, are related by the matrix equation
\begin{equation}
  X = CX + D
 \end{equation}
where $CX$ is the internal consumption.
In this model, an economy is productive by definition if for its consumption matrix $C$ exists Leontief inverse $(I-C)^{-1}$ and $(I-C)^{-1} \geq 0$.
Here comes the weird part.

A consumption matrix C is said to be productive if $(I − C)^{−1}$
exists and $(I − C)^{−1}$ ≥ 0

The matrix $(I-C)^{-1}$ even has its own name, Leontief inverse, yet it is still unclear to me why it is even needed to exist.
According to Derrick Chung,

An economy is productive if it can meet any external demand.
In other words, for any
D, there is an X such that X − CX = D with X ≥ 0 (i.e. X contains only non-negative entries)

and right below there is an analogous definition with Leontief inverse. Why can't an economy be considered productive if $X(I − C) = D$ (without requiring matrix $(I-C)$ to be invertible)? Or, equivalently, why should the relation between $X$ and $D$ be bijective? Or does it have something to do with the eigen-values?
Answer: You are correct that the English

An economy is productive if it can meet any external demand.

does not seem to require $I-C$ invertible, only surjective.
However, each input to the economy is another industry's output.  In mathematical terms, this implies that $C$ (and thus $I-C$) is square.  And square matrices (on finite-dimensional spaces) cannot be surjective without being invertible.
So saying $(I-C)^{-1}$ exists is equivalent to what you expect.


Cardinal arithmetic confusion: What is $|\Bbb R|+|\Bbb N|$?

Question: I do not understand how to calculate addition two cardinals.
I know that the formula as follows:
if $\alpha$ and $\beta$ are two cardinals, then
$\alpha + \beta= |\{(a,0):a\in \alpha\}\cup\{(b,1):b\in\beta\}|$.
If $\alpha=\mathbb{R}$ and $\beta=\mathbb{N}$, what's cardinals of $\alpha+\beta$?
Answer: What is the cardinality of $\Bbb R\times\{0\}\cup\Bbb N\times\{1\}$? You can notice that this is a subset of $\Bbb R\times\{0,1\}$, whose cardinality is $|\Bbb R|+|\Bbb R|$.
This gives you an upper bound, and if you can calculate it, it will also give you a lower bound for the cardinality of $|\Bbb R|+|\Bbb N|$.
As a final remark, you might want to distinguish between a set and its cardinal.
Answer: Hint: Try using Schroder-Bernstein to show that $|\mathbb{R}|+|\mathbb{N}|=|\mathbb{R}|$.  To do this, let $X=\{(a,0):a\in\mathbb{R}\}\cup\{(b,1):b\in\mathbb{N}\}$; you want to find injections $\mathbb{R}\to X$ and $X\to\mathbb{R}$.  The first one should be fairly easy; the second one will require some cleverness.
Comment: Can I deduce that $\alpha+\beta=\max\{\alpha,\beta\}$?
Comment: That is true in this particular case, but the argument does not generalize.  Using the axiom of choice, it is possible (but nontrivial!) to prove that $\alpha+\beta=\max(\alpha,\beta)$ as long as at least one of $\alpha$ and $\beta$ is infinite.  Without the axiom of choice, addition of infinite cardinals can be quite difficult to understand (in particular, there exist infinite cardinals such that $\alpha+\beta\not=\max(\alpha,\beta)$ because "$\max(\alpha,\beta)$" does not even exist!).


Delete rows that contains no information on Tweet text on pandas

Question: I´m  trying to remove rows containing blank texts or in tweet texts column. But I have tried in different ways counting the rows that only contain whitespace or counting the leading spaces and trailing spaces but to get a criterion to eliminate it.
ID    tweet           WhiteSpaceCount HaveWhiteSpace
0    this is a text        0              False
1                         0              False
2   Hello im fine         0              False

I want to delete all the rows that don´t have any information on the tweet column.
Code here:
def extractAndSave(api, name):
    # Creamos una lista de tweets:
    previous_date = date.today() - timedelta(days=1)
    query_date = date.today()
    name = name
    tweets = API_EXTRACTOR.search(q=name + "-filter:retweets", result_type='recent', timeout=999999, count=200,
                                  end_time=previous_date, tweet_mode='extended')
    # Podemos crear un dataframe como sigue:
    tweet_list = []
    for tweet in tweets:
        tweet_list.append(tweet.full_text)
    datos = pd.DataFrame(data=tweet_list, columns=['TWEETS'])

    # CREANDO COLUMNA DE ID
    id_list = []
    for id in tweets:
        id_list.append(id.id)
    id = pd.DataFrame(data=id_list, columns=['ID'])

    # CREANDO COLUMNA DE ID
    creado_list = []
    for creado in tweets:
        creado_list.append(creado.created_at)
    creado = pd.DataFrame(data=creado_list, columns=['FECHA_CREACION'])

    # CREANDO COLUMNA DE nombre de usuario
    user_list = []
    for usuario in tweets:
        user_list.append(usuario.user.screen_name)
    usuario = pd.DataFrame(data=user_list, columns=['USUARIO'])

    # CREANDO COLUMNA DE FUENTE
    fuente_list = []
    for fuente in tweets:
        fuente_list.append(fuente.source)
    fuente = pd.DataFrame(data=fuente_list, columns=['FUENTE'])

    # CREANDO COLUMNA DE ME GUSTA
    like_list = []
    for like in tweets:
        like_list.append(like.favorite_count)
    like = pd.DataFrame(data=like_list, columns=['ME_GUSTA'])

    # CREANDO COLUMNA DE RT
    rt_list = []
    for rt in tweets:
        rt_list.append(rt.retweet_count)
    retweet = pd.DataFrame(data=rt_list, columns=['ME_GUSTA'])

    # CREANDO COLUMNA DE IDIOMA
    idioma_list = []
    for idioma in tweets:
        idioma_list.append(idioma.lang)
    idioma = pd.DataFrame(data=idioma_list, columns=['IDIOMA'])

    # CREANDO COLUMNA DE IDIOMA
    quote_list = []
    for quote in tweets:
        quote_list.append(quote.is_quote_status)
    quote = pd.DataFrame(data=quote_list, columns=['CITADO'])

    # CREANDO COLUMNA DE IDIOMA
    location_list = []
    for location in tweets:
        location_list.append(location.user.location)
    location = pd.DataFrame(data=location_list, columns=['LOCACION'])

    # CONCATENANDO DATAFRAMES
    datos = pd.concat([datos, id, creado, usuario, fuente, like, retweet, quote, idioma, location], axis=1)

    # Dropear toda la fila si la columna tweets viene vacia.
    datos['pass/fail'] = np.where(datos['TWEETS'].astype(str).str.fullmatch(r"\s*"),'FAIL','PASS')

    datos['CONTEO_ESPACIOS']= (datos['TWEETS'].str.startswith(" ") | datos['TWEETS'].str.endswith(" ")).sum()

    # Hora de publicación
    datos['HORA_PUBLICACION'] = datos['FECHA_CREACION'].dt.hour
    datos['DIA_SEMANA'] = datos['FECHA_CREACION'].dt.day_name()

    # Extrayendo solo los tweets del día anterior
    datos['FECHA_CREACION'] = pd.to_datetime(datos['FECHA_CREACION']).dt.date
    datos = datos[datos['FECHA_CREACION'] == previous_date]

    print(datos)

    # Guardando en dataframe.
    return datos

Comment: Please include the code you wrote that is not working
Comment: I've moved your code from your (now deleted) answer into the question so everyone can see it. In general if you have more to add to your question you can press the [edit](https://stackoverflow.com/posts/69635564/edit) button under the question. The "Post Your Answer" button should only be used to provide an answer to a question.
Answer: Instead of removing rows that you don't need, keep only the ones you do need:
df = df[df["tweet"].str.strip().str.len()>0]

>>> df

   ID           tweet  WhiteSpaceCount  HaveWhiteSpace
0   0  this is a text                0           False
2   2   Hello im fine                0           False


Linear Map that maps the disk of radius 2 to the lower half plane

Question: Is their a general procedure to find a linear transformation that maps $\Delta(n)$, the disc of radius $n\in\mathbb{N}$, to the lower half plane? For example, how can I find linear map that maps $\Delta(2)$ to the lower half plane of $\mathbb{C}$? I am aware that I somehow have to use the cross ratio and define the map at three points but still don't understand how one achieves this.
Answer: Well, people do use the cross-ratio, but I just do it by guess and by golly. Here's my method:
I'm going to try to send the topmost point $ni$ of the boundary of the disk to the origin, and the two real points $-n$ and $n$ on the boundary to $-1$ and $1$, respectively. I'm going to hope that $-ni$ goes to $\infty$, too.
Just dealing with $ni\mapsto0$ gives me
\begin{equation}z\mapsto\frac{z-ni}{Cz+D}\,,\end{equation}and I want to choose $C$ and $D$ so that the two real points go to $\pm1$.
\begin{matrix}
\text{For }-1:&\frac{-n-ni}{-nC+D}&=-1&\text{so}&nC-D=&-n-ni\\
\text{For }1:&\frac{n-ni}{nC+D}&=1&\text{so}&nC+D=&n-ni
\end{matrix}
Thus we get $C=-i$, and $D=n$. Our fractional-linear map should be
\begin{equation}z\mapsto\frac{z-ni}{-iz+n}\,,\end{equation}
in which the denominator does indeed become zero under $z=-in$. Just to check, let's see where the origin goes: $0\mapsto-ni/n=-i$, which indeed is in the lower half-plane. That's it!
Comment: Thank you for you nicely explained answer!
Comment: I learned this way back in the days when stones were soft, in a wonderful course taught by Ahlfors. It was my first year of grad school, and at first I thought all this fiddling with fractional-linear functions was some kind of baby-talk. But it gave me a great deal of geometric understanding.


Degree of the map $X\to \Bbb{C}_\infty$ Bezout theorem

Question: I was reading Miranda's Riemann surface book, there is a key intermediate lemma in proving the Bezout theorem in page 142:
Let $X$ be a smooth projective curve in $\Bbb{P}^2$ with defining homogenuous polynomial $F$ of degree $d$, assume further that $[0:0:1] \notin X$, therefore $[x:y:z]\in X$ can not have $x,y$ vanish simultaneously, we can define the meromorphic function $h([x:y:z]) = x/y$ on $X$, which is the same as a holomorphic function $H:X\to \Bbb{C}_\infty$.

the question is about the degree of the map $H$ above. I want to prove the degree is $d$.
consider $\lambda \in \Bbb{C}$ such that $\lambda \ne 0$, then the points on the preimage $H^{-1}(\lambda)\subset X$ can not have both $x$ and $y$ component being zero, therefore the preimage are set of points $[\lambda:1:w]\in \Bbb{P}^2$ satisfies the equation $F(\lambda,1,w) =0$.
By the fundamental theorem of algebra, we know it has $d$ solution, then Miranda says that for a general $\lambda$ these solutions are distinct, and $H$ has multiplicity one at all of those solutions.
I know since $X$ is compact the branch points are discrete, therefore for general $\lambda$ they have multiplicity 1, however, I don't understand why the solution are distinct.

I found the same question in this post and the solution seems does not answer the question ?
Answer: Claim: $F(x,1,z)$ is irreducible in $\mathbb{C}[x,z]$.
Proof: if $F(x,1,z)=Q(x,z)R(x,z)$ is a nontrivial factorization write $\tilde{Q}(X,Y,Z)=Y^qQ(X/Y,Z/Y)$ where $q$ is the degree of $Q$ and same for $\tilde{R}$. Then we formally have $F=\tilde{Q}\tilde{R}$ with $\tilde{Q},\tilde{R}$ homogeneous. As $F$ is smooth, it is irreducible, and we get a contradiction.
Now, by assumption, $F(\lambda,1,X)=cX^d+\sum_{0 \leq k < d}{P_k(\lambda)X^k}$ where $P_k$ has degree at most $d-k$ and $c \neq 0$ is a constant.
It follows (assuming $d \geq 2$) that $F_X=\partial_X F(\lambda,1,X)$ is not a unit and of lower degree with respect to $X$ than $F_1=F(\lambda,1,X)$, so these polynomials have no common divisor in $\mathbb{C}[\lambda,X]$.
By Gauss lemma, these polynomials as coprime (where the field of coefficients is $\mathbb{C}(\lambda)$): it follows that there are polynomials $A(\lambda,X), B(\lambda,X), C(\lambda) \neq 0$ such that $AF_1+BF_X=C$.
In particular, if $C(\lambda) \neq 0$ (which happens for all but finitely many $\lambda$) $F(\lambda,1,X)$ is coprime with its derivative (wrt $X$) and has degree $d$, so it has exactly $d$ pairwise distinct roots.
Comment: It's not a silly question at all! This is because $F$ is homogeneous of degree $d$ and $F(0,0,1) \neq 0$: the only monomial of degree $d$ that doesn't vanish at $(0,0,1)$ is $Z^d$, so it must non-trivially appear in $F$. The degree (edited, I made a slight mistake) is because, $F$ is homogeneous of degree $d$, so $F(\lambda,1,X)$ has total degree at most $d$.
Comment: thank you @Aphelli , may I ask a silly question why  in the expression $F(\lambda,1,X)=cX^d+\sum_{0 \leq k < d}{P_k(\lambda)X^k}
$ , $c$ is non zero and $P_k$ has degree $d-k$?
Comment: got it thank you Aphelli