Are there any generic thinking approaches for providing mathematical proofs to a given theorem

Question: To produce mathematical proofs for theorems we should have the required knowledge in that area. But even having adequate knowledge, people like me struggle a lot for writing down the proofs for any given theorem.
Is there any way I can improve these skills? Are there any generic thinking approaches for providing mathematical proofs to a given theorem?
Comment: Why the downvote? I think this is a valid question. Too bad I can't think of any other answer than "you just try things you've seen before and then you start staring into space".
Comment: @Tim: To come up with a proof for a theorem you've seen before, you can *remember* the basic idea of the proof you saw before. For something you expect to be true, the reason you *expect* it to be true will likely guide you in the direction of an argument. Research, especially at its beginning stage, is much more tentative. One has different approaches, depending on whether one is trying something very close to what one has seen before (or something *exactly* like what one has seen before), and something entirely new.
Comment: @poddroid Please make your question more precise. Do you want to have references for improving your problem-solving skills? Do you want information on automated theorem proving which is something quite different? In both cases it is quite helpful if you give some background about your knowledge.
Comment: I would suggest getting your hands dirty with some examples.  Working through why the result works in an example is often very instructive about why it should hold in general.
Comment: By "given theorem", do you mean a theorem you've seen before, things you expect to be true for some reason, or are you talking in general about how one goes about doing mathematical research? These have all very different answers!
Comment: e.g. Are you interested in general advice like "regard small cases", "generalize", "specialize", "draw conclusions from the result" or are you interested in collections of problems on a specific topic like "101 problems in polynomial factorizations with complete solutions".
Comment: @Arturo: How  different are a theorem we've seen before, things we expect to be true for some reason, and how one goes about doing mathematical research?
Comment: [Here](http://math.stackexchange.com/a/290380/68107) is a good answer to a related question.
Answer: In the absence of more information I will give a generic answer.
Some general resources on the topic:

http://www.tricki.org (wiki-style collection of proof techniques)
Pólya: How to solve it (this book is a classic on the topic)
Engel: Problem-Solving Strategies (another classic with lots of problems)
Solow: How to Read and Do Proofs (also highly recommended)
Houston: "How to Think like a Mathematician" (introductory and nice companion to Engel's)

Some general strategies for attacking a problem that is better understood with examples:

Try small (to medium sized) cases
Generalize
Specialize
Combine Generalize-Specialize by adding assumptions and weakening conclusions freely during your first proof attempts, then try to remove or weaken assumptions and to strengthens the conclusions
Draw conclusions from the result
Put it away and look at it again later

Strategies to improve your skills:

Try to solve lots of problems
Read solutions after spending time trying
Discuss your thoughts with others
Become teaching assistant or tutor, as teaching/explaining a topic to others helps your understanding a lot
Rewrite your proofs until they have textbook quality
When reading proofs in textbooks, first check that the proof is correct and complete by verifying each step, then lean back to get the full picture by extracting the key ideas and finally look again at the details to learn the techniques how to write down precisely a maybe vague idea
Reflect why you did not find a particular solution
If your strategy of proving something fails, ask yourself whether there is any reason that your strategy had no hope of working (e.g. because the same strategy would have proven a stronger result, which is in fact false).

(This post has been wikified in case someone wants to add.)
Comment: Thanks a lot. And sorry for being too generic in my questioning. Yes. your guess is correct...I want to improve my theorem proving skills. Actually I never guessed there will be a book for helping out in this scenario. Sure I will buy the book and follow all your instructions. And if possible please post some more book references.Wish this is the good beginning to fulfill the dream of becoming a researcher in Artificial Intelligence field :-)
Comment: Sometimes generic questions are useful.  It's hard to be more specific about what one is looking for when one is not familiar with the terrain.  It's a good question, though. I'd suggest exploring different modes of proof (direct proof, indirect proof, proof by contradiction, combinatorial proofs, etc) within a field you're comfortable with, so you can focus more on the proofs/methodologies involved than having to also try to learn/understand the content. Of course, the goal is that developing some facility with proofs can then facilitate conceptual understanding in unfamiliar domains in math.
Comment: [Zeitz's](http://www.amazon.com/dp/0471789011) is also nice...
Comment: Thanks to all for your elaborated answers
Comment: There are actual books for this stuff. I suppose that should have been obvious. But then I had been of the impression proofs came from some place near the palace of the wizard of oz - a place pretty out of the reach of my kin.
Answer: As others have indicated, it would be much easier to answer this question if you gave a better indication of the level at which you are currently studying mathematics/trying to prove theorems.  (High school, undergrad, doctoral student, professional, ... ?)  Nevertheless, here is some general advice, which is similar
to the advice I give my own students at the advanced undergrads/beginning doctoral student level.
Let's begin with what professional mathematicians do: they prove new theorems, results that have never been proved before.  Doing this has one obvious difficulty: until the theorem is proved, you can't even be sure that it is true.
So you have the problem of trying to guess at what might be true before you can
be sure that your guess is correct.  The way that people do this is by some kind of intuition built up with experience.  As a general rule, it is probably best to postpone trying to do this until you have had time to build up the necessary intuition and experience; typically that time would be some point during the course of your doctoral studies.
Prior to trying to prove new theorems, the best thing to do is to practice proving theorems which you already know are true.  One source of these is
homework problems assigned in the courses you are studying, but it sounds from your question as if you might be having trouble with those.
A good way to improve your theorem proving skills, then, is to do the following:
go back to a (theoretical) course you studied some time ago, and whose results you feel comfortable with.  For a lot of people this would be a first course in
group theory, or maybe a course in elementary number theory. Then try to prove the major theorems from the course without looking at your notes or textbook.
The point of this is that you are hopefully fairly familiar with the statements
of the results, having used them a lot of times since then, and are probably reasonably familiar with the techniques of the course too.  But on the other hand, you probably don't remember all the proofs exactly.  So it is a good place to practice: your past experience with the course, and the advantage of having seen the results proved carefully before, should help serve as an intuition which can guide you in trying to reprove the results yourself.
If you can't work out how to prove a result after some time, you can look back in your notes or in the text.  But try not to look at the whole argument.  Just look to find the point in the argument where the author deals with the point on which you are stuck.  Once you have seen what general technique they use to get past this sticking-point, stop reading!  See if you can use that technique yourself to finish the proof.  In this way, you will begin to learn the different techniques and how they are used in arguments.
This is the process I used (and continue to use) myself as practice for proving
theorems, and I highly recommend it.  The more theorems you prove yourself, the better you will get at it!  Once you have gone back over a course in this way, you will also understand the results and techniques of that course much better than you did before.
Comment: Great idea! I always enjoyed proving Jordan's normal form theorem from Linear Algebra.
Comment: Thanks for spending your time and giving such a great answer. I completed graduation a long time back (10 years back) with Mathematics, Statistics as majors. But one sad thing was that the way we studied the course i.e. understanding the definitions but just trying to remember the proof's (which I feel as most sin thing..). So atleast now I wanted to avoid this thing. After seeing your answer I got a clear idea of the approach I should take in improving my proof giving skills.
Comment: @poddroid: Dear poddroid, Thank you for your comment.  I'm glad my answer is of some help. Regards,
Answer: In some precise sense, people conjecture that there is no general method for proving theorems. More than that, they even conjecture that in general, we can't expect theorems to have short proofs. If you want to learn more, you can try reading about Proof Complexity.
Comment: I agree that there is no ONE general method for constructing proofs: that is, there is no *formula* how to construct a proof.  By *general*, I'm assuming the user is asking for some *standard* approaches which are used frequently enough such that understanding the logic of such approaches will enable one to prove, or read/understand proofs, the kind of proofs one first encounters.  E.g.: understanding inductive proofs, direct proofs, indirect proofs (proofs by contradiction), proving the contrapositive, etc. and knowing when each of such approaches is particularly valuable, would be helpful.
Comment: I agree with Amy that this answer is off-topic.
Comment: Every provable theorem is proved in finite time by an search algorithm.
Comment: @Quanta: The question is how long can we expect the proof to be. People think that there is no polynomial bound on the length of proofs. So for example it could happen that there is no "shortcut" for proving exact values of Ramsey numbers.
Comment: This may not be relevant, but if you specify a given logic, there may well be a decidable proof system for it. If you can translate your human theorem into a particular logic, it may very well be provable decideably and automatically. Of course, what logic you choose may define a particular complexity class, which may be terribly difficult (i.e. slow). But we're presumably not talking about machine proofs but human proofs.
Comment: The conjecture I mention is about any *efficient* proof system for the propositional calculus (with any connectives). A proof system is efficient simply if there's an efficient way to syntactically verify that a proof is valid.
Answer: Perhaps you misunderstand the activity of proving theorems. A great portion of the time is spent figuring out just what theorems to prove. In the process, you adapt hypotheses and conclusions as you struggle to prove preliminary versions which happen to be false. In other words, the theorems are not given for your to prove; they must be found first. And for finding theorems, the only way is to prove simpler theorems, to improve your theorem-finding skills.
Comment: I agree with everything here except the first sentence.
Answer: A lot of mathematics is about abstraction, but abstract principles are hard. It may help to work with a more concrete object. For example, if are working with rings, you may want to play with various rings defined on the integers.
I had a graduate level course in algebra which went very slowly. In most of the year, we covered about 10 or 12 pages in book. No one was doing well. We really didn't know what it was all about. Then one day the professor (who may have been a great theoretical mathematician but was not a good teacher) told us that the motivating example was based on polynomials. Well, gee, you could have told us that a long time ago. The professor was happy with the abstraction, but the class needed an example.
Answer: Simply put: if you get the picture, you can do the math. A good strategy is to break up one big problem you can't solve (yet) into smaller ones you can. In other words: simplify complicated things. An almost archetypical example of this is of course the cosine law that you can proof by breaking up the given bigger triangle into two smaller ones which each have a 90 degree angle.


Name for bounded piecewise linear function?

Question: Is there a name for the bounded piecewise linear function
$$ f(x) = \begin{cases}
x,& x\in [-1,1] \\
-1,& x < -1, \\
1,& x > 1.
\end{cases} $$
It resembles the tanh function but does not have continuous derivatives.
Comment: On what reason the question should be closed? It's just a valid question by a newby.
Comment: It is not a "linear function" in any conventional sense, although it is a *piecewise llinear* continuous function (first-degree spline).  It more closely resembles the (discontinuous) "signum" function $$\operatorname{sgn}(x) = \begin{cases} 1 &\text{when } x \gt 0 \\ 0 &\text{when } x = 0 \\ -1 &\text{when } x\lt 0 \end{cases}$$
Answer: It is a ramped step function.
You may express $$f(x) = \begin{cases}
x,& x\in [-1,1] \\
-1,& x < -1, \\
1,& x > 1.
\end{cases}$$
as a heaviside function.
On the positive reals your function is $$f(t)=t-(t-1)H(t-1)$$ and on the negative reals it is $$g(t)=-f(-t).$$
Comment: Doesn't provide an answer.
Comment: Thanks. I see that f(x) = max(0,x) is called the "ramp" function in Wikedia. The reason I asked the question is that I want to define the function in some computer code and wanted to know what to name it.
Comment: Thanks for the comment. I have seen ramp function used before.
Answer: In the deep learning (artificial neural networks) literature, the function is known as the "hard tanh" function. In their course notes https://cs224d.stanford.edu/lecture_notes/LectureNotes3.pdf for "CS 224D: Deep Learning for NLP", Rohit Mundra and Richard Socher state that "The hard tanh function is sometimes preferred over the tanh function [as an activation function for neural networks] since it is computationally cheaper."


Linear Algebra: Finding the span inside of 4 vectors in $\mathbb{R}^3$ Why do we ignore the other equations after finding a row of zeros through EROs

Question: I will post the original question that was done as an example in a linear algebra lecture followed up by my confusions / additional questions :)
Original Question:
What is the span inside $\mathbb{R}^3$ of
$$\underline{u_1} = \begin{pmatrix} 1\\ 1\\ 1 \end{pmatrix}, \underline{u_2} = \begin{pmatrix} -1\\ 0\\ 2 \end{pmatrix}, \underline{u_3} = \begin{pmatrix} 0\\ 1\\ 3 \end{pmatrix}, \underline{u_4} = \begin{pmatrix} -1\\ 1\\ 5 \end{pmatrix}$$
We want to find vectors $\underline{b}$ such that:
$$ \underline{b} = \lambda_1 \underline{u_1} + \lambda_2 \underline{u_2} + \lambda_3 \underline{u_3} + \lambda_4 \underline{u_4} = A \underline{\lambda} $$
So we write:
$$ \left[ \begin{array}{cccc|c} 1&-1&0&-1&b_1\\ 1&0&1&1&b_2\\ 1&2&3&5&b_3 \end{array} \right] $$
Through elementary row operations we reach:
$$ \left[ \begin{array}{cccc|c} 1&0&1&1&b_2\\ 0&1&1&2&b_2-b_1\\ 0&0&0&0&2b_1-3b_2+b_3 \end{array} \right] $$
Thus it is consistent when $2b_1 -3b_2 + b_3 = 0$ which is the equation of a plane. So the span of the 4 vectors is this plane.
My question:
Why, once we reach RREF of the augmented matrix are we able to to just ignore the other two equations. Sure the row of zeroes if definitely more interesting but how do we know that the other two equations don't restrict the span at all?
Comment: It is because, regardless of the $b_1, b_2$ values on the previous two rows, we can always find $\lambda_1, \lambda_2, \lambda_3, \lambda_4$ that satisfy the requirements. Namely: $\lambda_1 = b_2$, $\lambda_2 = b_2-b_1$, $\lambda_3=\lambda_4=0$. So for any $(b_1, b_2, b_3) \in \mathbb{R}^3$ that satisfies $2b_1 -3b_2+b_3=0$, we can find $\lambda$ so that $A\lambda = (b_1,b_2,b_3)$.
Comment: @Retsek for me it's unclear what does $b_i$ stands for and why $2b_1-3b_2+b_3=0$ is a plane.
Comment: @Alexey I'm going to be completely honest I don't completely understand myself, these are just my notes from the lecture. It looks like 2x - 3y + z = 0 which is a plane in 3-dimensions.
Answer: Suppose $2b_1-3b_2+b_3=0$. Then whatever values you choose for $b_1$ and $b_2$, the linear system is solvable. The two equations add no relevant information.
However you can use the RREF of the matrix formed with the four vectors to draw other conclusions. For instance that $u_1$ and $u_2$ form a basis of the span and that
$$
u_3=u_1+u_2,\qquad u_4=u_1+2u_2
$$
because elementary row operations don't change linear relations between columns. So, since clearly the third column of the RREF is the sum of the first two, also the third column in the original matrix is the sum of the first two. Similarly for the fourth column. Since the first two columns in the RREF are linearly independent and form a basis of the span of the RREF's columns, the first two columns of the original matrix are a basis of the span of the four columns.


Single row fetch when two records are common

Question: Fromjourney ToJourney   KM
Delhi       Mumbai      1000
Mumbai      Delhi       1000
Gurgaon     Noida       50
Noida       Gurgaon     50
Ghaziabad   Faridabad   60
Faridabad   Ghaziabad   60
Delhi       Meerut      80
Meerut      Delhi       80

I have three column from, To and KM.
I want single row data when From To have same city
like From- Mumbai, To-Delhi
     To- Delhi, From-Mumbai
Ι want single row of this data
Comment: Have you tried anything so far to solve the problem?
Comment: Which rdbms you are using? Oracle/sql-server/mysql - Always add proper tags. Anyways, it looks like it does not matter for your question. Go through these SQL tutorials https://www.w3schools.com/sql/
Answer: select T1.Fromjourney,T1.ToJourney
  ,T2.*
from TestTable T1
left join TestTable T2
  on T1.Fromjourney = T2.ToJourney
  and T1.ToJourney = T2.Fromjourney
  and T1.Fromjourney < T2.Fromjourney
where T2.Fromjourney is not null

| Fromjourney | ToJourney | Fromjourney | ToJourney |   KM |
|-------------|-----------|-------------|-----------|------|
|       Delhi |    Mumbai |      Mumbai |     Delhi | 1000 |
|     Gurgaon |     Noida |       Noida |   Gurgaon |   50 |
|   Faridabad | Ghaziabad |   Ghaziabad | Faridabad |   60 |
|       Delhi |    Meerut |      Meerut |     Delhi |   80 |

DEMO - SQL Fiddle
Answer: I would do this as:
select t.*
from testtable t
where Fromjourney < ToJourney
union all
select t.*
from testtable t
where Fromjourney > ToJourney and
      not exists (select 1
                  from testtable t2
                  where t2.Fromjourney = t.ToJourney and t2.ToJourney = t.Fromjourney);


Integral / Fourier Series

Question: Why is the following integral written with Fourier series development like this?
$\displaystyle h_i\sum_{k,l=1}^{\infty}a_k a_l \int_0^1 \sin(k\pi t)\sin(l\pi t) \,dt = \frac{h_i}{2}\sum_{k,l=1}^{\infty} a_k a_l \delta_{kl}$
What is used to move from left limb to right limb?
Thanks! :)
Comment: $\int_0^1\sin(k\pi t)\sin(l\pi t)dt=0$ if $l\neq t$ and $\frac{1}{2}$ if $l=t$.
Answer: It is simply because, when $k\neq l$, we have
$$
\int_0^1 \sin (\pi  k t) \sin (\pi  l t) \, dt = \frac{l \sin (\pi  k) \cos (\pi  l)-k \cos (\pi  k) \sin (\pi  l)}{\pi  k^2-\pi  l^2} = 0
$$
And when $k=l$, we have
$$
\int_0^1 \sin (\pi  k t) \sin (\pi  k t) \, dt = \frac{1}{2}-\frac{\sin (2 \pi  k)}{4 \pi  k} = \dfrac{1}{2}
$$
Hence
$$
\int_0^1{\sin \left( k\pi t \right)}\sin \left( l\pi t \right) \,dt = \dfrac{1}{2} \delta_{kl}
$$
Thus your relation holds.

Integral / Fourier Series


RowVersion value is not getting binded in form data, mvc 5

Question: I am trying to implement concurrency using EF6 in MVC 5.
 @Html.HiddenFor(model => model.RowVersion)

On my edit page I am able to see the rowversion value in input type hidden.
 <input id="RowVersion" name="RowVersion" type="hidden" value="AAAAAAAAF3M=">

But on $('form').serializeArray() I am not getting RowVersion data, on posting the form also I am getting null value of RowVersion property.
I had added RowVersion column in database table later and updated the edmx after that, I have set concurrency mode to fixed in the primary key column property my table in edmx.
Is there something extra that needs to be done for rowversion ?
Any help would be appreciated.
Update : adding html code
Jquery : I am checking it in console using : $('form').serializeArray()
html output from browser :
        <form action="/Master/EditBookMaster/13" method="post"><input name="__RequestVerificationToken" type="hidden" value="Y04ae_LHgfG9Tw9hy2TcHIYbxk_EX_vykyphV7Sm9Wwiz6_f8PpGUY2SULyiZbCdJv4fgBloOlx_QRUz1FQNvXTZUorLt6_EvA9XLxcFsxbQqUlmY9XOCduHa__q1kdRQJpFAx4wOuj5tRu48TLh9A2" />

BookMaster

                <input data-val="true" data-val-number="The field BookMasterId must be a number." data-val-required="The BookMasterId field is required." id="BookMasterId" name="BookMasterId" type="hidden" value="13" />

                    BookName

                        <input class="form-control text-box single-line" id="BookName" name="BookName" type="text" value="C Programming" />

                    Count

                        <input class="form-control text-box single-line" data-val="true" data-val-number="The field Count must be a number." data-val-required="The Count field is required." id="Count" name="Count" type="number" value="10" />

                    Publisher

                        <input class="form-control text-box single-line" id="Publisher" name="Publisher" type="text" value="Dennis-Ritchie" />

                    Subject

                        <select class="form-control text-box single-line" data-val="true" data-val-number="The field SubjectId must be a number." data-val-required="The SubjectId field is required." id="SubjectId" name="SubjectId"><option value="1">Fiction</option>
        <option value="2">Biography</option>
        <option value="3">Science</option>
        <option value="4">Research</option>
        <option selected="selected" value="5">Software developement</option>
        </select>

                    AvailableCount

                        <input class="form-control text-box single-line" data-val="true" data-val-number="The field AvailableCount must be a number." id="AvailableCount" name="AvailableCount" type="number" value="8" />

                        <input type="submit" value="Save" class="btn btn-default" />

        </form>

 Back to List

  <input id="RowVersion" name="RowVersion" type="hidden" value="AAAAAAAAF3M=" />

Comment: Post HTML and Javascript code.
Comment: @SlavaUtesinov added it
Comment: And where is RowVersion input and Javascript code?
Comment: updated it, rowversion input type is beneath the form closing tag(i think it should have been inside)
there's no javascript code, I am checking the output in $('form').serializeArray() in console only for test.
Comment: Simply put rowversion input inside form tag.
Comment: yep, it worked.... you solved it in just 10 minutes from I guess 10000 miles away...thanks
Comment: @Rajdeep: Simply put the hidden field inside the form tag
Answer: $(":input,:hidden").serialize();

code instead of
$('form').serializeArray()


OpenGL Segfaulting on glDrawArrays

Question: I'm making a game in OpenGL on Windows using Code::Blocks (C++) and MinGW. All the drawing and logic is fine, the game works perfectly. Until, suddenly, it doesn't. After some random amount of time, the game Segfaults. As is typical with GL segfaults, the stack trace is unhelpful. The only thing I got was that the segfault occurred in the vendor's implementation of OpenGL. I've tested this on multiple graphics cards from different vendors, and they ALL do this, so the problem is on my end.
I ran the program though gDEBugger and got the same unhelpful stack trace. Lol. I also used GLIntercept, but nothing jumped out at me. So I set about finding the segfault the manual way (BuGLe refuses to compile...) and basically write trace messages to a log. I've narrowed it down to one call to glDrawArrays. I've done a lot of poking around the internet and tried a lot of the fixes I found.
Because this game wasn't coded for portability, I've been hesitant to run it in wine and valgrind. Before I go messing with that wonderful mess, I'd appreciate it if you could look at my code and find the error. (I'm sure it's something obvious...)
(Note: For readability, I've removed all of my trace lines)
<code>void PlayerShip::Render()
{
    glPushMatrix(); //Save the current state

    glTranslatef(m_PosX, m_PosY, 0);
    glRotatef(vect.Rotation - 90, 0, 0, 1); //Matrixes are applied in reverse order

    double xl = m_SizeX / 2, yl = m_SizeY / 2; //Get values to add/subract to the midpoint for the corners
    glEnable(GL_TEXTURE_2D); //Redundant
    TextureManager::Inst()->BindTexture(TexIDs::Playership01); //Bind the texture

    glEnableClientState(GL_VERTEX_ARRAY); //These enables and disables are redundant here
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);

    GLdouble* Verts;
    Verts = new GLdouble[12] { -xl, -yl, -.5,    xl, -yl, -.5,
                           xl,  yl, -.5,    -xl, yl, -.5}; //Calculate quad vertices
    GLdouble* Texs;
    Texs = new GLdouble[8] {0, 0,    1, 0,   1, 1,    0, 1}; //Calculate texture vertices

    glVertexPointer(3, GL_DOUBLE, 0, Verts);
    glTexCoordPointer(2, GL_DOUBLE, 0, Texs);

    glDrawArrays(GL_QUADS, 0, 12);

    delete [] Verts;
    delete [] Texs;

    glPopMatrix();
}
</code>
The interesting thing is that this code works... for awhile. I've printed the values of all variables, they're all correct, the pointers aren't null, glGetError calls spaced throughout the code always return NO_ERROR. Frankly, I'm at a loss.
A note to any who suggest I do something different: I need to use vertex arrays to support legacy (1.4) GL implementations, and I'm declaring my arrays as pointers so that I can (in the future) reuse them for drawing multiple primitives at one time (say, having exhaust come out of the ship)
Answer: Your last argument to glDrawArrays should be 4 (number of elements), not 12 (number of floats).
You're trying to draw 12 elements (= 36 floats), and accessing past the bounds of your array.
Comment: Wow. I feel stupid. Any idea why it was rendering OK for awhile, THEN seg'd?
Comment: Might only segfault if there was something else in the memory area that it was trying to access. If it was free space the memory bounds checks might not have noticed it. That could explain the random nature of it.
Comment: Makes sense because it faulted quicker on systems with less memory... Thanks to you, I can sleep easy... for tonight at least.
Comment: Is this still the case? The documentation [here](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glDrawArrays.xhtml) states that `count` is "the number of *indices* to be rendered."

OpenGL Segfaulting on glDrawArrays


Learning instrument recognition

Question: I want to be able to identify instruments when played. For example, if I'm listening to some symphony, I want to be able to identify the oboe from the bassoon, the viola from the violin, etc. I have searched software for learning instrument recognition, but I haven't found anything yet. Do you know any method for learning this ? (software or not).
Comment: I think this is a fine question.
Comment: Just listen to them. Try Peter and the Wolf for a great lesson in instrument identification. I don't think this is a good question for this site though.
Comment: Might I also suggest following along in the score. imslp.org has many public domain music scores. Find one and listen along.
Comment: As for viola vs. violin, [that's easy](http://www.mit.edu/~jcb/jokes/viola.html)...
Comment: youtube: [Bing Crosby and Louis Armstrong *That's Jazz*](http://www.youtube.com/watch?v=G6q2hyXooXA).
Comment: Best way I can think of is to play in an orchestra. That's how I learned. :)
Comment: A related question, specific to trombone and tuba, but with the same instrument recognition goal: [Looking for jazz tracks that use the trombone and the tuba](https://musicfans.stackexchange.com/questions/10692/looking-for-jazz-tracks-that-use-the-trombone-and-the-tuba)
Answer: I suggest you find a recording of Benjamin Britten's "The Young Person's Guide To The Orchestra". There are versions on YouTube, iTunes etc. and any classical music shop will stock it on CD or DVD.
It was composed specifically to demonstrate the various sections and instruments of the orchestra in turn.
It is sometimes recorded with a narration, and sometimes without.
Your options:

use a narrated version, and just listen
use a non-narrated version, and follow a score, or a written copy of the narration script
watch a video or live performance, so you can see what instrument is making which sound
Answer: I think that the best way to do this is to listen to music at concerts with a score so that you can see which instrument is playing which sound.
Comment: Obviously this requires, that the instruments are visually recognized reliably. So the first step would be to click through orchestral instruments in wikipedia first (string, woodwinds and brass for the beginning), where the sound clips may give a first idea.

Learning instrument recognition


What does Opt. S.D. mean?

Question: I was looking at the sheet music for the Star Spangled Banner arranged for the U.S. Marine Band, and I saw that each instrument has an Opt. S.D. in the beginning.

What does it mean?
Answer: "Optional Snare Drum"
What you're seeing is a cue for an optional instrument. The Star-Spangled Banner may begin with or without snare drum.
Comment: It's more likely to be a military roll at the start, just a long sustained sound.
Comment: I guess it's a roll, looking at the tremolo note. Just like the U.K. National Anthem.  On those dots, it looks like a 2 beat rather than an unmeasured roll, but it's probably optional, as it says. Optional instrument, or optional beats.
Comment: @Tim Actually measured / unmeasured has nothing to do with beat length, but rather whether or not the percussionist's hands are subdividing the roll rhythmically, or non-rhythmically.

What does Opt. S.D. mean?


Large data variable selection

Question: I'm looking for some methods of variable selection on large datasets.The number of variables are around 30-40, but the number of observations is quite large (around      36000000)
Any methods which I know of like stepwise regression or orthogonal matching (or rather their implementation in libraries like scikit-learn) can't really handle such data. The first  problem is they always try to fetch all of the data in memory. I didnt get past that to know if there will be more problems.
Does anyone know of any libraries which maybe able to handle such datasets.
Even broader methods for  selection is fine ( not necessarily a stepwise regression).
Related to
Variable selection in large datasets
(As pointed out by Richard hte terms may cause confusion, hence rewording the question a little)
Comment: As barmaley.exe said. Just sample it. The first rule of big data is to select a representative sample and work with that. This speeds all the rest of your analysis and investigation. You might therefore consider writing classes for performing the sampling that slot into scikit_learn and therefore allow you to iterate over different samples of your data rather than using single card coded sample.
Comment: SAS, if you have it, is usually good at this sort of stuff.  SAS has a unique way of processing data (via the program data vector) making it very memory efficient.  Otherwise you can still do this in R or similar language (though it requires more thought).  In any case it helps to know if your data is stationary and ergodic, or better yet i.i.d.  If you don't know you can sample your data to find out.  If your data is and you are using R, random sampling may be the easiest way to go, another option may be to program your own regression function that reads only parts of your data at a time.
Comment: Do you really need all the data? Why don't use just a sample?
Comment: It would help to disentangle the different aspects of the problem. First, what do you mean by a large number of samples? Is it one large sample (very long time series or very wide cross section) or many copies of (not-so-large) samples? If there are multiple (not-so-large) samples, what trouble does that cause? Can't you handle each sample separately? Second, do stepwise regression and the other methods fail because the way they are implemented they can't handle large amounts of data? I guess the methods are fine in general but a particular implementation might fail. Please be more specific.
Comment: I should have been more careful with terminology.By no of samples is large I mean the number of observations (as you said one long time series). @Richard Theoretically I think these methods being not exponentially complex can handle any amount of data, but yeah the problem I faced immediately is memory constraint. Since it didnt procced further can't really say. Depdninf on how inversion is done maybe matrix inversion will be difficult/unstable (not really sure about this). But first concern is really on R or python trying to pull all data into memoey
Comment: Now that it is clearer what the actual problem is, I don't think I can help much more. I suggest you highlight the actual bottleneck even more (put in bold or something) so that it is clear for every new reader what it is. You could also indicate more precisely how long your time series are so that we would know better how large a sample we are talking about.
Comment: You might want to investigate vowpal wabbit which can certainly handle this data size because it works iteratively loading data as it goes
Comment: The thread on building large regression models at http://stats.stackexchange.com/questions/7815 augments the good advice already given by @seanv507.
Answer: This may not be an answer you want to see. But I will try.
You have a data set with 40 variables (features) and huge number of observations. You want to select a subset of variables from the 40 variables you have. I guess this is a "supervised" feature selection problem e.g., select subset of variables so as to minimize prediction errors on some variable.
First thing to try is to subsample the observations. Then run your favorite feature selection algorithm. If you cannot subsample (say they are not independent), here are a few things to try. Let k be the number of features you  want to have.

Variable ranking. Evaluate each variable independently with a scoring function. Rank and select top k features. This does not take into account feature interaction or feature redundancy. This assumes data slice from considering just one feature fits in memory.
Forward search. Start from an empty set. Greedily add one feature at a time so that some measure (e.g. prediction error) defined on the current set of variables is minimized. Redundancy is taken into account but not feature interaction. This assumes data slice from considering k features fits in memory.

Without further details on your data, I cannot say much. Page 3 of this paper gives a sequence of checklist you might want to check.

Large data variable selection


How Can I add Email Verification Functions For WooCommerce

Question: I would like to add Email verification procedure when user registers in WooCommerce. WordPress then emails a verification link to user's email. If link is clicked, it then activates the user's account. How would I do that?
Comment: Stack Overflow isn't meant to write code for you. You have to give very specific details about what the problem is. Code. Screenshots. Expected and actual results. A good question should rarely be 1 sentence.
Comment: No I can't because you haven't provided enough detail. Without details it's VERY hard to answer your question because we can't find the answer until you give details.
Comment: Sorry but I'm not going to register. You need to take the time to provide more details. :) once you do that I would be more then happy to look at your question and see if I have a solution for you.
Comment: you do not need to do download plugin from Github its may be the problem with your download just go directly to this link to download plugin https://wordpress.org/plugins/woo-confirmation-email/
Comment: But there is a problem in this plugin not adding user in wordpress.
Comment: This is my site http://www.thesincitystore.com/my-account/ you can register and check the error.
Comment: But site is not my its my client so can't give details . thank you Charlie for reply my Question.
Answer: I have used the code provided by Amit Kayshap and refined it to include extra checks and functions like automatically logging a user in after their account has been activated, resulting in a much smoother user experience.
Update: Unlike the original code, this one will not require any existing user to confirm their email address as well.
Like the code I based it upon, it is designed to run on a WordPress installation running WooCommerce. It also works if you have disabled the standard WordPress registration page.
You'll need an empty page with the URL yoursite.com/verify/ that builds on a template that contains <?php wc_print_notices(); ?> within its content container. It'll replace the /sign-in/ destination from the original code and will handle almost all messages created by this code.
Next, add this code to your theme's functions.php:
function wc_registration_redirect( $redirect_to ) {     // prevents the user from logging in automatically after registering their account
    wp_logout();
    wp_redirect( '/verify/?n=1');                       // redirects to a confirmation message
    exit;
}

function wp_authenticate_user( $userdata ) {            // when the user logs in, checks whether their email is verified
    $has_activation_status = get_user_meta($userdata->ID, 'is_activated', false);
    if ($has_activation_status) {                           // checks if this is an older account without activation status; skips the rest of the function if it is
        $isActivated = get_user_meta($userdata->ID, 'is_activated', true);
        if ( !$isActivated ) {
            my_user_register( $userdata->ID );              // resends the activation mail if the account is not activated
            $userdata = new WP_Error(
                'my_theme_confirmation_error',
                __( 'Error: Your account has to be activated before you can login. Please click the link in the activation email that has been sent to you.
 If you do not receive the activation email within a few minutes, check your spam folder or ID.'">click here to resend it.' )
            );
        }
    }
    return $userdata;
}

function my_user_register($user_id) {               // when a user registers, sends them an email to verify their account
    $user_info = get_userdata($user_id);                                            // gets user data
    $code = md5(time());                                                            // creates md5 code to verify later
    $string = array('id'=>$user_id, 'code'=>$code);                                 // makes it into a code to send it to user via email
    update_user_meta($user_id, 'is_activated', 0);                                  // creates activation code and activation status in the database
    update_user_meta($user_id, 'activationcode', $code);
    $url = get_site_url(). '/verify/?p=' .base64_encode( serialize($string));       // creates the activation url
    $html = ( 'Please click here to verify your email address and complete the registration process.' ); // This is the html template for your email message body
    wc_mail($user_info->user_email, __( 'Activate your Account' ), $html);          // sends the email to the user
}

function my_init(){                                 // handles all this verification stuff
    if(isset($_GET['p'])){                                                  // If accessed via an authentification link
        $data = unserialize(base64_decode($_GET['p']));
        $code = get_user_meta($data['id'], 'activationcode', true);
        $isActivated = get_user_meta($data['id'], 'is_activated', true);    // checks if the account has already been activated. We're doing this to prevent someone from logging in with an outdated confirmation link
        if( $isActivated ) {                                                // generates an error message if the account was already active
            wc_add_notice( __( 'This account has already been activated. Please log in with your username and password.' ), 'error' );
        }
        else {
            if($code == $data['code']){                                     // checks whether the decoded code given is the same as the one in the data base
                update_user_meta($data['id'], 'is_activated', 1);           // updates the database upon successful activation
                $user_id = $data['id'];                                     // logs the user in
                $user = get_user_by( 'id', $user_id );
                if( $user ) {
                    wp_set_current_user( $user_id, $user->user_login );
                    wp_set_auth_cookie( $user_id );
                    do_action( 'wp_login', $user->user_login, $user );
                }
                wc_add_notice( __( 'Success: Your account has been activated! You have been logged in and can now use the site to its full extent.' ), 'notice' );
            } else {
                wc_add_notice( __( 'Error: Account activation failed. Please try again in a few minutes or ID.'">resend the activation email.
Please note that any activation links previously sent lose their validity as soon as a new activation email gets sent.
If the verification fails repeatedly, please contact our administrator.' ), 'error' );
            }
        }
    }
    if(isset($_GET['u'])){                                          // If resending confirmation mail
        my_user_register($_GET['u']);
        wc_add_notice( __( 'Your activation email has been resent. Please check your email and your spam folder.' ), 'notice' );
    }
    if(isset($_GET['n'])){                                          // If account has been freshly created
        wc_add_notice( __( 'Thank you for creating your account. You will need to confirm your email address in order to activate your account. An email containing the activation link has been sent to your email address. If the email does not arrive within a few minutes, check your spam folder.' ), 'notice' );
    }
}

// the hooks to make it all work
add_action( 'init', 'my_init' );
add_filter('woocommerce_registration_redirect', 'wc_registration_redirect');
add_filter('wp_authenticate_user', 'wp_authenticate_user',10,2);
add_action('user_register', 'my_user_register',10,2);

If you are running a multilingual site, you can make the code translation-ready very easily. Just change the text strings like this: __( 'Text you want to translate', 'your-theme' ) This allows translation plugins like WPML to add the string to a translation table in the your-theme text domain.
Note that any string containing a variable like .$url. will generate a new string every time a different user activates its function. To circumvent this (and prevent string spamming into your database), we can translate them directly in the code:
if(ICL_LANGUAGE_CODE=='de'){
    wc_add_notice( __( 'German error message' ), 'error' );
} else {
    wc_add_notice( __( 'English error message' ), 'error' );
}

In this example, the german message will be output if the user's language code is detected as de (Also works if it is a variation like de_DE_formal), else it will output the english message.
Edit: I updated the code to not require an existing user to retroactively confirm their email address.
Comment: This works great but took me a while to figure out the "an empty page that builds on a template" thing. It makes perfect sense after I found the following: https://stackoverflow.com/a/2810723/1358863
Comment: There is a small security issue in the code: anybody can deactivate any account by simply following a link like /?u=1. So need to check if the user is already activated, for example on line 58. I submitted an edit.
Comment: I have 2 registration options on my WC shop: usual and Facebook. Will this code affect users who register with Facebook?
Comment: @DemuriCelidze This code hooks into the WordPress core with `user_register`, `init` and `wp_authenticate_user` and into WooCommerce with `woocommerce_registration_redirect`, so unless your Facebook registration hooks into the WooCommerce process instead of directly into the WordPress core, the code probably won't work with the Facebook registration.


Calculating a large factorial division on pen and paper

Question: Context: In January I will be taking a concurrent programming examination, part of which will involve calculating the number of interleavings based on a formula which divides two sets of factorials.
The problem I have is that calculators are prohibited, so it must be calculated on pen and paper, so I wonder what the best strategy is here?
The professor's suggestion was to simplify the factorial division, but the example he used didn't show how he simplified it, but also the numbers he was using were smaller.
One example I worked on is as follows:

12! / (6! x 6!)

The smallest I can simplify this to is as follows (although let me know if it can be simplified further as I may be wrong):
(2 *  11 * 10 * 3 * 4 * 7) \ (5 * 4)
This still seems like an excessive calculation for pen and paper (the question will be worth a single mark, also).
What would you suggest as a strategy for calculating the division of two factorials on pen and paper? (the goal being to come up with a strategy which takes the least amount of time to work out using pen and paper).
The result must be expressed as a single number, so using this example the result would be 924.
Thanks
Answer: You can immediately cancel the $2\times10$ on the top with the $5\times4$ on the bottom, leaving $11\times3\times4\times7$.
$$11\times3\times4\times7=11\times12\times7=84\times11=924$$
The calculation shouldn't be too hard: $3\times4$ is easy, $12\times7$ is also pretty easy, and multiplication by $11$ is simple: If the two digits are $xy$, then $11\times xy=x(x+y)y$  (potentially carrying digits), which is easy to do mentally. For example, $11\times 23=253$. How big are these factorials going to be exactly?
Comment: @CiaranG Then this'll probably be as complicated as it'll get. You have the right idea for simplifying it. Just note that since the result will always be an integer, you can always cancel enough to get rid of the denominator. Do that first and then just carry through the remaining multiplications. It might be a little tedious, but it shouldn't be too bad that way.
Comment: I think what the professor said was that the result would be no larger than 1,000 (or something to that effect), so there shouldn't be any excessive calculations.


What data structure to use for my cluster analysis or what cluster analysis to use for my data?

Question: I have a large dataset of categorical variables. The data consists of shoppers who purchased two items during a single trip to a store.
There are approximately 75,000 cases and 1,500 different products. I plan on clustering the data using TwoStep cluster analysis (I know it it is for large data; though I'm not sure that is the best solution, yet; I may consider other clustering methods as well).
The raw data was collected like this (respondent 1 purchased two items on three separate visits):

What is the best shape for this data to be in for clustering if I want to cluster users who purchased similar products? I know I'll need a single row/case per respondent. So, I was thinking that this would suffice (option 1):

However, I continually receive a one cluster solution (based on auto clustering) and poor solutions when I specify the number of clusters. I'm not sure if that's actually the case or if my data is not shaped correctly.
The other option would be to shape the data like this (option 2):

But I'm not sure what data implications that brings up. One benefit I can think of with option 2 is that I could potentially try additional clustering techniques, such as K-means or Hierarchical.
Answer: It is obvious that using "option 1" dataset you virtually declare that similar respondents are those respondents who bought (or stole) the same items at the same turn or visit. I don't believe this is your research goal. In addition, problematic NA responses arise.
"Option2" dataset is what you should use, but do recode 2 into 1, to make the data binary. You then can take these variables in TwoStep as categorical variables. But here arises another doubt. TwoStep is for nominal categorical variables only; and you probably will not want to treat the binary variables as dichotomous nominal. Treating them as nominal means that, for you, respondents who did not buy the same item are as similar with each other as those who did bought the same item. Rather, you'll want to treat those "0 and 0" respondents as neither similar nor dissimilar, - this suggests using similarity measures such as Jaccard measure. But this in turn precludes using TwoStep and requires using Hierarchical clustering or other clustering methods apt for binary data (those other, unfortunalely, are not found in SPSS).
But you can't do hierarchical clustering of 75000 respondents - its too many, both practically and theoretically, for hierarchical method. You see - you've got trapped.
One way out will be to look for clustering algorithms (outside SPSS) which are for big (large) sparse binary data. Search this site for this word combination: you'll get a few related questions, to read.
Another way out may be to do hierarchical clustering on random subsets of your data (subsets of size, say, 500 respondents). Clustering of subsamples and cross-validation is beneficial, as it escapes overfitting threat. But, in the context of clustering, it is quite a big work. I recommend you to read papers on cluster analysis by subsamples.
A third and the easiest way will be to do K-means clustering of your data. It solves the problem of big dataset. However, K-means is often seen as theoretically inappropriate for binary as well as count variables. They say that because the method involves computation of floating point geometric centroids, it requires interval, ideally - continuous, variables. That said, people use K-means with binary or count data "all the time". It appears to me that in high-dimensional settings such as yours (1500 variables) the relative contributions of "continuety" and "dimensionality" to the formation of centroids shifts towards dimensionality anyway - even if you had quite fine-grained Likert scale variables. That seems to excuse, to an extent, applying K-means to a wide binary dataset as yours.
If you choose K-means then I recommend you to normalize each row (respondent) in the dataset to unit sum-of-squares (= unit sum, since the data are binary) prior clustering. Why to do it? According to this, when you normalize vector magnitudes (L2 norms) you make the euclidean distance between the vectors directly reflect cosine similarity between them: $d^2=2(1-cos)$. And it is cosine similarity (= Ochiai binary measure) which is a justifiable alternative to Jaccard measure I mentioned in the 2nd paragraph above. Both Jaccard and Ochiai treat "0 and 0" respondents as neither similar nor dissimilar - that is what you need. So, using K-means on such way normalized data is in a sense analogous to using hierarchical clustering on Ochiai measure.
Comment: What implications need to be considered if the variables in option 2 were treated as discrete variables? I may be overthinking here, but I would think that a respondent who purchases many t-shirts would be more like another respondent who purchases many t-shirts than a respondent who just purchases one.
Comment: Well, you meant to say "count variables". It is possible, and you would prefer then cosine similarity measure. But the problem that your dataset is too big for hierarchical method remains. Therefore I added the discussion of K-means as a possible alternative.
Comment: This is really helpful. Thank you! For those interested:

R Package which includes Jaccard similarity measure: http://cran.r-project.org/web/packages/vegan/index.html


Is there a reason to retain .cmo or only .cma?

Question: Say, I have mylibrary.ml which provides wrappings to library.c and I want to bytecode-compile and provide mylibrary.ml as a library for other ocaml code. Compiling this to bytecode (and I am not considering compiling ocaml to native code here) produces a number of files, and I am wondering if there is any reason to keep them all? Or to provide them all to other users of the library?
I (so far) understand that I need the bytecode library object mylibrary.cma so that I can use mylibrary in the ocaml toplevel as
ocaml mylibrary.cma

or that I can
#load "mylibrary.cma";;

from an ocaml script. Then also the compiled interface mylibrary.cmi, and the dllmylibrary.so (which contains the C parts of the code) are needed for the above to work. And the non compiled interface definition file mylibrary.mli is nice to keep for documentation purposes.
But is there any reason to retain also the mylibrary.cmo file, if I have the mylibrary.cma file? In what kind of case would someone like to have that, too?
EDIT: I mean, I need to construct the .cmo in the makefile and then use that to construct the .cma, but I was thinking to remove .cmo after this, to keep the directory marginally cleaner.
Answer: So, apparently the purpose of different files are (when limiting this to bytecode compiler):
mylibrary.mli - human readable interface definition (not strictly needed, compiler only needs .cmi)
mylibrary.cmi - compiled interface, needed when compiling code calling mylibrary
library.o - C object file
dlllibrary.so - shared library object made of the .o
dlllibrary.a - static library object made of the .o
mylibrary.cmo - bytecode object compiled from mylibrary.ml
mylibrary.cma - bytecode library
Then, mylibrary.cma (with mylibrary.cmi and dlllibrary.so) are needed when loading mylibrary from the toplevel:
#load "mylibrary.cma";;
OR
One could compile a bytecode program that dynamically links with mylibrary.cma (mylibrary.cmi and dlllibrary.so also needed):
ocamlc mylibrary.cma <program>.ml
OR
dynamically linking with bytecode object, instead of the bytecode library (files needed: mylibrary.cmo, mylibrary.cmi, dlllibrary.so):
ocamlc dlllibrary.so mylibrary.cmo <program>.ml
(Note: then run the bytecode with: ocamlrun -I . <program>, assuming dlllibrary.so is in the current directory.)
OR
statically linking with objects (files needed: mylibrary.cmo, mylibrary.cmi liblibrary.a)
ocamlc -custom liblibrary.a mylibrary.cmo <program>.ml
OR
statically linking with library objects (files needed: mylibrary.cma, mylibrary.cmi, liblibrary.a)
ocamlc -custom -I . mylibrary.cma <program>.ml
So depending on how one is going to use the library in the future, different files are needed. Except .mli is only needed for human readers, and the object file.o compiled from the C library is not needed (but would be needed when compiling to native code in some cases).
Answer: You should even keep the source code of the library. Very often when upgrading the Ocaml compiler (e.g. from 3.12 to future 3.13), you previous *.cmo or *.cma files won't be able to work without recompilation.
Assuming you can always clean and recompile things (e.g. you have the two traditional targets clean and all to make) you can only keep the *.cma
Comment: Yes, of course I will keep the source. I was just thinking, is there any case where somebody would like to use the .cmo instead of the .cma.


how to get rid of awstat www-data daemon?

Question: I have successfully installed awstats on my webserver. I have created a cron job that runs as root every third hour. And it works perfectly, but i keep receiving "mails" every 10 minutes saying that www-data tried to update and did not have the right permissions for it.

Message 58:
From www-data@cosmos Sun Aug 21 23:20:02 2016
Envelope-to: root@cosmos
Delivery-date: Sun, 21 Aug 2016 23:20:02 +0200
From: root@cosmos (Cron Daemon)
To: root@cosmos
Subject: Cron  [ -x /usr/share/awstats/tools/update.sh ] && /usr/share/awstats/tools/update.sh
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env:
X-Cron-Env:
X-Cron-Env:
X-Cron-Env:
X-Cron-Env:
Date: Sun, 21 Aug 2016 23:20:02 +0200

Error while processing /etc/awstats/awstats.****.***.conf
Create/Update database for config "/etc/awstats/awstats.****.***.conf" by AWStats version 7.2 (build 1.992)
>From data in log file "/var/log/apache2/access.log"...
Error: Couldn't open server log file "/var/log/apache2/access.log" : Permission denied
Setup ('/etc/awstats/awstats.****.***.conf' file, web server or permissions) may be wrong.
Check config file, permissions and AWStats documentation (in 'docs' directory).
Error while processing /etc/awstats/awstats.conf
Create/Update database for config "/etc/awstats/awstats.conf" by AWStats version 7.2 (build 1.992)
>From data in log file "/var/log/apache2/access.log"...
Error: Couldn't open server log file "/var/log/apache2/access.log" : Permission denied
Setup ('/etc/awstats/awstats.conf' file, web server or permissions) may be wrong.
Check config file, permissions and AWStats documentation (in 'docs' directory).

(END)

The problem is that i can`t find the cron job and delete it. I am aware that it is possible to stop getting "mails", but i want to stop the process from running every 10 minutes. Do anyone know where this cron job lives? Or how to stop it?
BTW: i am running debian 8.2
Comment: Check in `/etc/cron.d`.
Answer: If you use dpkg to see the package contents, you will see a cron file:
<code>$ dpkg -L awstats
/etc/cron.d/awstats
</code>
Comment out the lines in that file, eg. with
<code>sed -r -i "s/^([^#])/#\1/" /etc/cron.d/awstats
</code>


Interpreting output from a linear regression model?

Question: I've done a linear regression model to determine the effect of personality position on a scale and changes in reaction time. I adjusted for age as a confounding factor. I've got the output, but there are so many p-values that I don't know what each of them mean.
Here is the output:

More importantly, what does the p-value 0.03158 at the end signify?
Comment: Maybe see [here](https://statisticsbyjim.com/regression/interpret-f-test-overall-significance-regression/)
Answer: Let's go through each part one-by-one.
Call
The call section simply spits the formula back at you that was used when modeling your regression. There isn't really much to say about that other than it gives you what you already know.
Residuals
Recall that residuals are the errors in your model, or how badly your model guesses. These are standard for regression like the one you have. The minimum is the furthest your residuals are below the regression line, in other words how much your regression line overshoots it's prediction. The maximum is the opposite, which shows the value which undershoots the prediction the most. 1Q and 3Q are just quartile ranges of these residuals. The median should usually be somewhere close to zero (rarely is it exactly zero), as the average residuals should over time be close to where the regression line is fit.
Coefficients
These are simply all of the terms entered in the model. These usually include the intercept and your slopes (from the predictors you entered). The intercept for a Gaussian family regression such as this is generally understood as a conditional mean which is contingent upon the other terms in the model. We normally don't invest a lot of time in the point estimates in this row, as they don't usually in this case provide a lot of value.
Your slopes however tell you whether or not your predictors have some utility. For the "personality" predictor here, the estimate is the slope. For every $1$ unit increase in this predictor, we get a $-.005$ decrease in your outcome of "change RT". The standard error and t value here are both used to derive the significance of the slope, which is indicated by the last output in the row. For "personality" the p value is $.7329$ and consequently is not significant. Age however has a low p value and can be deemed "significant" (though this doesn't say much about how strong that effect is).
These coefficients can also be used to build a linear equation. Now that we have all of our coefficient values, we simply put them together into an equation like so:
$$
RT = .074 + (-.005 * Personality) + (.006 * Age)
$$
Signif. Codes
You can ignore these, as they simply designate which values are significant and are self-evident.
The Rest...
I imagine your confusion is the bottom output. The residual standard error is essentially how "precise" the model's predictions are. A lower RSE is generally more precise, indicating your model is good at predicting. Multiple $R^2$ is the proportion of variance in the outcome explained by the predictors in your model. We typically use the adjusted $R^2$ instead if we have multiple predictors, as the first value can be inflated by simply adding a bunch of predictors in the same model. Here we can see in either case that the model predicts very little variance in the outcome. The bottom values are the model significance terms, which show the f value and degrees of freedom, which are used to test overall model significance. As indicated by Dimitri's link:

"The F-test of overall significance indicates whether your linear
regression model provides a better fit to the data than a model that
contains no independent variables."

So this should give you an idea of what your output here is saying.


(400) Unknown metric(s): ga:socialNetwork'

Question: I need get acquisition->channels info. I think I can get it using "ga:socialNetwork" dimension. But when I use it I get the following error:
(400) Unknown metric(s): ga:socialNetwork

However, ga:socialNetwork dimension exists: https://developers.google.com/analytics/devguides/reporting/core/dimsmets
My service call:
$service->data_ga->get('ga:xxxxx', '2010-01-01', '2015-01-15', 'ga:socialNetwork', $optParams);

Comment: Just to get the obvious out of the way: The error message suggests you are trying to use ga:socialNetwork as a metric (not a dimension), so can you check this is not just a typo in your code ?
Comment: @Eike Pierstorff, I have edited my question adding my service call
Answer: ga:socialNetwork is a dimension not a metric. You are attempting pass in a dimension to the parameter that expects a metric.
Attempt the following to correct your code:
$optParams = array(
    'dimensions' => 'ga:socialNetwork',
    'sort' => '-ga:sessions');

$service->data_ga->get(
  'ga:xxxxxx',
  '2010-01-01',
  '2010-01-15',
  'ga:sessions',
  $optParams);

ga:sessions is a metric where ga:socialNetwork is a dimension, this help center article should help clarify the difference.


When application close, will DB connection close instantly?

Question: This is something I has been always wonder.... will it?
Because whenever I write code to use DB connection, I always somehow have to ensure is closed before process to next piece.
But when if the I have a ChildWindow that open a connection in its constructor and not close it until it hits the Save Button or Cancel Button.  Then if the whole Application got closed, will the DB connection close instantly?  Or it has to wait for the timeout and will close automatically?
EDIT:
So I am trying to keep a live connection open for logging all errors on my application:
public App()
{

   ErrorHelper errorHelper = new ErrorHelper(); // Will open DB connection
   AppDomain currentDomain = AppDomain.CurrentDomain;
   currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);

}

///
/// For catch all exception and put them into log
///
void currentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{

    errorHelper.WriteError(e.ExceptionObject as Exception);

}

Because I don't like how I open connection everytime log a single error, so I want to keep connection open all the time.  This is similar as the OP I was describe. In this situration, it keeps connection open all the time.  But will the DB connection close instantly after it exits?
Comment: @Oded,  I don't see anything hypothetical about the behavior of an exiting application.
Comment: @Oded as requested, I putted something I am working on.  But like mikerobi said, I want to know about the behavior of exiting the application.  Not workaround to ensure the connection close.
Answer: Short and simple answer: always use your connection in a using statement:
using (var db = new Connection())
{
    ...
}

and then you won't have to worry - it will just close when it goes out of scope, be it end of method, exception, or application shut down.
Comment: True, but not answering the question.
Comment: I think it depends on how your application is running under IIS - in its own application pool or not, etc. What's sure is that ADO.NET handles cleanup, so eventually (sooner or later) all connections will be closed and deleted, even in the connection pool.
Comment: But your question is not clear - what are you trying to accomplish? Knowing IF the connection will close? Knowing WHEN the connection will close? You told to @Oded that your question is not hypothetical. Be specific.
Comment: @OferZelig I just want to know if the application close, all the opened DB connection will instantly be close?  So I don't have to worry about if there is chance the DB connection will holds for long time.  (Say the application ran by 1000 users, if the connection will not be close instantly after application exit, but wait for a while to timeout and close. There are chance that many unused connection will be hold.)  Sorry, maybe some people will think I am complicate the problem.  But I just want to have clear idea what will happen.
Answer:
Because I don't like how I open connection everytime log a single error, so I want to keep connection open all the time.

That's what connection pooling is for.  Have you measured your performance or have you identified strong evidence that this is a problem?
Open and close the connection with a using block and let the connection pool do it's job.
If your process exits, your connection will be closed.
Comment: @King Chan ADO.NET has connection pooling. http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx
Comment: `Using` block is basically just `try{...}finally{ obj.Dispose() }`. I remember when I was using NexusDB(yeah, not famous), Open connection with ADO everytime I write is much slower than Open connection once and write everything.
Comment: @dotjoe Ooooh, I see. After reading it. I just wrote a small program to test the performance with ADO open connection (with MsSQL) all the time and open when when it need.  It around the same.  Strange...then how come when I test with NexusDB is much slower... +1


Segmentation error when trying to append to linked list, c++

Question: I have a struct defined as such:
struct Node {
    int day = 0;
    int number = 0;
    Node* next = nullptr;
};

and wrote a create function
Node* ll_create(int day, int number){
    Node* p = new Node;
    p->day = day;
    p->number = number;
    p->next = nullptr;
    return p;
}

but my append function always end up in a segmentation error
void ll_append(Node* head, int day, int num, int len){
    Node* new_cnode = ll_create(day,num);

    Node* last = head;
    while (last->next != nullptr)
        last = last->next;

    last->next = new_cnode;

}

can someone tell me how to fix this?
Comment: Check if head is null
Comment: Can you post how you use ll_append()? Basically, you can not append to a null list.
Comment: You need to extract a [mcve] from your code and provide that as part of your question. While at it, please also remove the trailing ", c++", which is much better represented using language tags. As a new user, also take the [tour] and read [ask].
Comment: You have several problems. If it is the first node, presumably `head` is `nullptr` at that point (or worse uninitialized) and it isn't handled in `ll_append()`. If it is set elsewhere and `head` will never change -- then, and only then, can passing `head` by-value to `ll_append()` work. Always better to pass a reference.
Answer: Most probably the root cause of the issue is missing error handling.
i.e. A basic rule can be followed that : before any pointer is dereferenced, it should be validated.
void ll_append(Node* head, int day, int num, int len){
    Node* new_cnode = ll_create(day,num);

    Node* last = head;
    while (last->next != nullptr) //Here, last (i.e. head) can be nullptr.
        last = last->next;

    last->next = new_cnode;

}

The decision can be taken wheather the caller to ll_append shall ensure the head or the ll_append itself can validate.
The first solution could look like below :
void ll_append(Node*& head, int day, int num, int len){
    Node* new_cnode = ll_create(day,num);
    //Case 1 : When head is pointing to empty list, you can create the first node.
    if(not head)
    {
       head = new_node;
       return;
    }
    //Case 2 : When head is pointing to a valid list (i.e. at least one node is present)
    Node* last = head;
    while (last->next != nullptr)
        last = last->next;

    last->next = new_cnode;

}

Comment: `head = new_node;` would only modify the local variable `head`, you can pass `head` as `Node*&` to affect the passed value.


What is an instance of SQL?

Question: My company is considering purchasing software that requires "at least one instance of SQL". I'm not sure what that means. Would I have to buy SQL Server 2008 for example?
Comment: have a look on here http://serverfault.com/questions/33238/ms-sql-server-single-or-multiple-instances
Answer: It's someone confusing the language with the software. It means an instance of MS SQL Server of some indeterminate version running on your network.
Comment: So this is software I would load on the server - not on my PC?
Comment: Generally database engines are meant to be installed on a server, not a client. There are a few exceptions (SQLite, MSDE, Access), but this is not one.
Answer: Yes you would, basically when you install MSSQL2008 you are installing a single instance of that software, it'll have a name and can hold databases etc. You may find later that on the same machine you'd like to run more instances, each one is separate from each other - but running on the same physical server. You can think of it a little like a virtual machine you'll see in virtualisation. People usually use them to divide either customers or very separate systems (say finance dept and HR dept). There is a not-inconsiderate overhead incurred for every instance over and above the first one.
Basically just buy MSSQL2008 and don't worry too much more ok.
Comment: if the software is capable of running on SQL 2008 Express, then there is no need to buy SQL at all...check with the software vendor to make sure you need a full version of SQL before buying it as it can get expensive depending on the version.
Answer: You would need to get SQL Server, yes. Note that there are free editions available, which may or may not be something you can use with that software.
An 'instance' just refers to a single, running 'copy' of SQL Server. It's a bit more involved than just running it twice like, say, Microsoft Word (including licensing requirements and network connectivity), but that's the basic idea.
Answer: Also bear in mind if you are purchasing any edition of SQL Server apart from the Express versions that there are different forms of licensing.
Processor licences (one licence per processor in your server) which will allow any number of connections
CAL (Client Access Licences) where you buy the software and a number of licences equal to the number of users that will be connected to the server.

What is an instance of SQL?


Como criar uma função igual a Array.Copy do C# no C++

Question: Gostaria de criar uma função parecida com a Array.Copy do C# no C++.
Essa função tem o protótipo assim:
public static void Copy(
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length
);

E gostaria de fazer uma função que fizesse a mesma função em C++.
Eu tentei fazer utilizando um for, porém não consegui fazer funcionar com o destinationIndex.
Meu código:
template <T> void Buffer <T> ::copy(T * src, int indexSrc, T * dst, int indexDst, int elements) {
    for (int srcAux = indexSrc, dstAux = indexDst, int aux = 0; aux != elements; srcAux++, dstAux++, aux++) {
        dst[indexDst] = src[srcAux];
    }
}

Comment: Poste o que você já fez.
Comment: Minha função ficou assim:
`template
void Buffer::copy(T *src, int indexSrc, T *dst, int indexDst, int elements){
    for(int srcAux = indexSrc, dstAux = indexDst, int aux = 0;aux != elements;srcAux++, dstAux++, aux++){
        dst[indexDst] = src[srcAux];
    }
}`
Answer: O C++ já tem algo pronto que faz isto com std::copy():
std::copy(std::begin(src), std::end(src), std::begin(dest));

Coloquei no GitHub para referência futura.
Tentar traduzir o código de uma linguagem para outra sem entender a linguagem não dá certo. Cada linguagem tem sua especificidade e jeito de fazer cada operação.
Nossa tag c++ tem informações de como começar aprender C++.


How do I choose a database?

Question: I am NOT a developer or DB guy but a webmaster who has manipulated mysql successfully for several wordpress sites. I know how to use the command line tool and also to run things via phpmyadmin. I know how to perform basic administrative mysql functions and occasionally to make a custom query.
I am setting up a  drupal7  site on a VPS where I will already have a wordpress-mysql instance. But it occurred to me that there's nothing really stopping me from installing another db -- postgresql, SQLite, MariaDB. I am less interested in power than ease of use -- but obviously better performance would be welcome. I would probably need some management tool with a web interface. As I said, I wouldn't expect to be doing a lot of DB work; just the routine maintenance and rescue operations that occasionally are necessary.
The site should be a low or medium traffic site with not a lot of writes, but probably a lot of reads. There would probably not be enough traffic to do load balancing or clustering. (It's for a magazine site).
Is there any rule of thumb for which db to choose? Sticking with mysql seems to the obvious and easy solution; I'm just wondering if there's any reason to think differently in 2013.
Comment: You might want to try this over at [Database Administrators](http://dba.stackexchange.com/) too :)
Answer: Well choosing a database for your site depends on many ways,
I prefer MySQL to keep it quite simple.
MySQL is preferable PHP sites because:

Drupal 7 now comes with default table engine which is InnoDB(advantages over MyISAM) for
MySQL
MySQL has choice of table types for better read performance.
Drupal has PHPMyAdmin Web Interface for MySQL.
WAMP,XAMP comes with MySQL so it makes life easier when you use MySQL
Drupal's much better tested with MySQL

http://drupal.org/node/37268
Answer: If you've got the choice I'd go with MariaDB.
It's a drop-in, transparent replacement for MySQL; any client connecting to it would think it's just accessing a regular old MySQL database. But you get advanced features and performance improvements out-of-the-box. It also has a very fast drop-in replacement for InnoDB.
It was written by the original MySQL developers (before Oracle got their hands on it) so it's a solid bet.
I've been using it for a little while and have been very happy with it.

How do I choose a database?


Create NSDate for today at a particular hour and minute

Question: How can I create an NSDate with today's date and an hour, minutes, and seconds of 5, 0, and 0 respectively? I.e. the date will be 07/02/2010 05:00:00
Comment: It is easier to use NSCalendar.
Answer: //Gives us the current date
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit fromDate:[NSDate date]];
[components setHour:5];
NSDate * date = [gregorian dateFromComponents:components];
[gregorian release];

Something along those lines should do the trick.


Compute $\int_0^\infty \frac{e^{-tx}\sin(x)}{x}dx$

Question: I have to compute$$\int_0^\infty \dfrac{e^{-tx}\cdot \sin(x)}{x}dx$$
This is following a helping problem $$\int_0^\infty e^{-tx}\cdot \sin(x)dx$$ which using IPB two times turned out to be $$\dfrac{1}{1+t^2}$$
I think there must be a substitution to get to the first problem, but I just cannot see it. Any hint appreciated.
Answer: We can compute $\int_0^{\infty}e^{-tx}\sin x/x dx$ for a positive $t$. Indeed, define
$$F(t,x):=\frac{\sin x}xe^{-tx}.$$
If $\delta$ is a positive number, then for any non-negative $x$, $$\sup_{s\geqslant \delta}\partial_tF(s,x)|\leqslant e^{-\delta x}.$$
Since the map $x\mapsto e^{-\delta x}$ is integrable on $[0,\infty)$, we can take the derivative under the integral.
Answer: Define
$$
I = \int \limits_0 ^\infty e^{-tx}\frac{\sin(x)}{x}dx
$$
then
$$
\dfrac{dI}{dt}=-\int \limits_0 ^\infty e^{-tx}\sin(x)dx = -\frac{1}{1+t^2}
$$
hence
$$
I = -\arctan(t) + D
$$
We fix $D$ using $I(0)=D=\dfrac\pi 2$, easily obtainable through complex analysis.
Comment: You don't need to use complex analysis. Simply note that $I(\infty)=0$ to find $D$. (Now you can plug in $t=0$, giving $I(0)=\frac\pi2$ without complex analysis.)
Comment: @columbus8myhw That's true, easily obtained from $ 0\leq I \leq \int\limits_0^{+\infty}e^{-tx}dx $
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\large\tt\mbox{With}\quad t > 0}$:

\begin{align}
&\color{#00f}{\large\int_{0}^{\infty}{\expo{-tx}\sin\pars{x} \over x}\,\dd x}
=\int_{0}^{\infty}\expo{-tx}\pars{\half\int_{-1}^{1}\expo{\ic kx}\,\dd k}
=\half\int_{-1}^{1}\int_{0}^{\infty}\expo{\pars{\ic k - t}x}\,\dd k
\\[3mm]&=\half\int_{-1}^{1}{1 \over t - \ic k}\,\dd k
=t\int_{0}^{1}{\dd k \over t^{2} + k^{2}}
=\int_{0}^{1/t}{\dd k \over 1 + k^{2}}= \arctan\pars{1 \over t}
\\[3mm]&=\color{#00f}{\Large{\pi \over 2} - \arctan\pars{t}}
\end{align}
Answer: $$
\begin{aligned}
\int_{0}^{\infty} e^{-tx} \frac{\sin x}{x} \, \mathrm{d}x &= \int_{0}^{\infty} e^{-tx} \sin x \int_{0}^{\infty} e^{-zx} \,\mathrm{d}z\,\mathrm{d}x\\
&= \int_{0}^{\infty}\!\!\int_{0}^{\infty} e^{-x\left(z+t\right)} \sin x\,\mathrm{d}x\,\mathrm{d}z\\
&= \int_{0}^{\infty} \frac{\mathrm{d}z}{\left(z+t\right)^2 +1}\\
&= \left[\lim_{N\to\infty}\arctan(N+t)\right] - \arctan t \\
&= \frac{\pi}{2} - \arctan t\\
&= \operatorname{arccot} t
\end{aligned}
 $$
Comment: Note: We can say that $ \displaystyle{\frac{1}{x} = \int_{0}^{\infty} e^{-zx}\,\mathrm{d}z} $ because we are integrating over the interval $(0, \infty)$, i.e., $x>0$, so the integral converges.


Exercise 8.3.E in Vakil FOAG : equivalence of union of $\operatorname{Spec} (k(\mathcal{O}_{Y,p}))$ with smallest closed subscheme containing $X$

Question: As explained in 8.3.9 of http://math.stanford.edu/~vakil/216blog/FOAGnov1817public.pdf, we consider $X^{set}$ a closed subset of $Y$ and attempt to define a canonical scheme structure $X$ on $X^{set}$.
There are three proposed ways of doing so:
$(1)$ On each affine open $\operatorname{Spec} B$ of $Y$, we take the restriction of $X$ to this affine to be $\operatorname{Spec} B/I(X^{set})$ (the part of $X^{set}$ that intersects the affine) and then glue them together to get a unique scheme via the exercise $8.1.H$.
$(2)$ Define $W$ to be the disjoint union of all of the points of $X^{set}$, where the point corresponding to $p$ in $X^{set}$ is Spec of the residue field $\mathcal{O}_{Y,p}$. Let $W\longrightarrow Y$ be the canonical morphism sending p to p and giving an isomorphism on residue fields. Then the scheme structure $X$ is the scheme-theoretic image of that map.
$(3)$ Define $X$ as the smallest closed subscheme whose underlying set contains $X^{set}$.
We are asked to show the equivalence of these three constructions. I understand somewhat how I could show $(1)\Longleftrightarrow (3)$. But how to begin to show equivalence of either of these to $(2)$?
Comment: A brief typographical comment: \operatorname{Spec} produces good formatting for $\operatorname{Spec}$, and I've upgraded your post with this change. There appears to also be a small typo in 2) - you said "residue field" but wrote $\mathcal{O}_{Y,p}$.
Answer: The key is in the properties of the scheme-theoretic image, discussed in section 8.3. If $f:X\to Y$ is a morphism with $X$ reduced, then the scheme-theoretic image can be computed affine locally (theorem 8.3.4). Since $W$ in part 2 is reduced, this means that the computation of the scheme-theoretic image is the same as the computation of $\operatorname{Spec} B/I(X^{set})$ in part 1. Alternatively, by corollary 8.3.5, the underlying set of the scheme-theoretic image is the same as the closure of the set-theoretic image, which is just $X^{set}$, so we're looking for the smallest closed subscheme containing $X^{set}$ in both parts 2 and 3.
Comment: Sorry I donthave 15 reputation I wanted to upvote. Thank you for the answer.


How to align a div to top left on flexed div

Question: I want to make a image (inside a div) to the most left of the bottom div and I don't how to do this.
For example I have this image

.container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.applicationimage {
    width: 60px;
    height: 60px;
    border-radius: 100%;
}

.settings {
    display: flex;
    width: 80%;
    height: 40rem;
    background-color: white;
    align-self: center;
}

                    hi

I'm new to html & css so I will appreciate your help making this image to the most left of his bottom div.
Answer: If you know the width of the div, it's easy. You can give the .applicationinfo element align-self: flex-start; and margin-left: 10%; (10% is calculated by this formula: (100% - widthOfDiv) / 2)

body {
  background: black;
}

.container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.applicationinfo {
    align-self: flex-start;
    margin-left: 10%;
}

.applicationimage {
    width: 60px;
    height: 60px;
    border-radius: 100%;
}

.settings {
    display: flex;
    width: 80%;
    height: 40rem;
    background-color: white;
    align-self: center;
}

                    hi

Answer: remove the  flex direction, here's it
   display: flex;
   justify-items: flex-end;
   align-items: flex-end;}

Answer: You can do it by positioning applicationinfo since you haven't styled it.
you can add parent position: relative; then child to absolute; then give child top: 0; left: 0;

.container {
  display: flex;
  height: 80vh;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  align-items: center;
  position: relative;
  background: #222;
  border: 1px solid yellow;
}

.applicationinfo {
  width: 80%;
  top: 0;
  left: 0;
  border: 1px solid green;
}

.applicationimage {
  width: 60px;
  height: 60px;
  border-radius: 100%;
  border: 1px solid blue;
}

.settings {
  display: flex;
  width: 80%;
  height: 80%;
  background-color: white;
  align-self: center;
}

        hi


How to give Permissions to User based on taxonomy selected while creating a content?

Question: I have a taxonomy called Projects and it has terms like Project1, Project2 etc.
I have added a user called ProjectUser1, and assigned a new role called ProjectRole with it.
Now I want to give Permissions to ProjectRole so that when ProjectUser1 logins, he can only see the content that has Project1 taxonomy and he can Publish, Unpublish, Edit or Delete only those content. He shouldn't be able to see the contents which doesn't have Project1 taxonomy.
Can anyone help?
Comment: I have a pretty in depth answer here: http://drupal.stackexchange.com/questions/118878/edit-content-if-taxonomy-country-united-kingdom/118898
Answer: I think you are looking for Taxonomy Access Control
Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Three node access permission types: View, Update, Delete.

Comment: I tried this, but non-admin user can still edit the other content which doesn't have that particular taxonomy, or he couldn't edit any content. Can you please help me with this?
Answer: Instead of using taxonomy and roles, you should use the Organic Group Module.
- Turn a new content type, for instance ProjectGroup, into a private group
- Make content type Project a group content
- Assign Projects and Users into their ProjectGroups
In order to give non-admin users the permission to publish and unpublish content, you can use the Publish module
Comment: I can't create new content type or taxonomy, I have to use the existing ones. Can you explain this please in more detail?
Suppose I have content type called `Event`, Taxonomy vocabulary "Country" and term "United Kingdom". Now I want to give permission to non-admin user if a content has Country = United Kingdom, then he can edit, publish, delete that particular content, but in general he can see all the contents.
Comment: I'm afraid using the Organic Group Module without being able to create a new content type isn't possible, sorry.


Need better resources and explanation to the Weierstrass functions

Question: I have been looking at Wikipedia's description of Weierstrass functions (see https://en.wikipedia.org/wiki/Weierstrass_functions) and they come across quite brief or terse.
I would like to see some examples of Weierstrass Zeta function (along with Eisenstein series) and Weierstrass Sigma function.

https://en.wikipedia.org/wiki/Weierstrass_functions#Weierstrass_zeta_function
https://en.wikipedia.org/wiki/Eisenstein_series
https://en.wikipedia.org/wiki/Weierstrass_functions#Weierstrass_sigma_function

Had a look at Wolfram, they seem to go into even more details but not working out an example.
Resources like programs (with source) or graphs or animations explaining them will certainly help.
Comment: How about looking in books on complex analysis or elliptic curves (of which there are many) rather than the Internet? Or clarify what "working out an example" means for you.
Comment: Godement's *Analysis IV* contains a wonderful account of all these classical functions.
Comment: Thanks both for your replies.

>> working out an example
-- Means just like the wiki page says this is what the formula/equation is and what we want is the derivative of it, etc... and we need to express it using Eisenstein series. I would like to see what values are used for the various limits.

Is _Godement's Analysis IV_ available for free online? I'll do a search.
Comment: To clarify further I'd like to know what range of valid values I can insert into each of the variables to get a result. In some cases its ranges of values that give out ranges of output.
Answer: There are several books now on the topic of elliptic functions, but 100 years ago almost all of them were not in English. A notable exception is Harris Hancock's Lectures on the Theory of Elliptic Functions published in 1910, but reprinted by Dover Publications. It gives a detailed explanation of both the Jacobi and Weierstrass versions of Elliptic Functions with the relations between them.
Online handbook sources include Abramowitz and Stegun Handbook of Mathematical Functions, also reprinted by Dover Publications, with a chapter on Weierstrass elliptic
functions. Its modern version, the NIST Digital Library of Mathematical Functions (DLMF) chapter 23 is comparable.
Comment: One site that has also come to help recently is [Wolfram Alpha](https://www.wolframalpha.com/).
Comment: Thanks @somos for your feedback.
Answer: Thanks @somos for your detailed reply.
At the moment I'm looking for clarification on the following:

what does the inverted V symbol (capital letter Lambda) symbolise, how do you represent it in terms of numbers, series? pairs? matrix of numbers? (these two questions applied to both the Weierstrass Sigma and Zeta functions)
what is the output of this function/formula, again is it a single number or a series of them, a matrix of numbers?
with regards to the zeta function, I would like to know how to apply this function, particular not sure how to generate Eisenstein series and the notations in https://wikimedia.org/api/rest_v1/media/math/render/svg/bbd16a21a70d1bc62b04c8ac8b0c0b101b49d71a - I'm not familiar with them:
G2k+2 * (Lambda) * z raise to 2k+2

G2k+2 - is this just a notation to express Eisenstein series of weight 2k+2? and takes input from the Lambda set? What does this set contain, and which range of numbers? I was reading its a lattice / pair of values - would like to see some examples of this.
Any help with explaining or clarifying what the math notations mean will be also helping in starting to understand these two functions, and also Eisenstein series.
Comment: You could upvote my answer. The $\Lambda$ should have been defined as a complex lattice. That is $\lambda\in\Lambda$ means $\lambda=n\omega_1+m\omega_2$, a $\mathbb{Z}$-linear combination of two linearly independent periods. My advice is don't try to understand too much too soon.
Answer: I have actually partly been able to answer my questions from above, after finding these links:

https://en.m.wikipedia.org/wiki/Weierstrass%27s_elliptic_functions
https://www.maplesoft.com/support/help/errors/view.aspx?path=Weierstrass

Maplesoft has a library of math functions and semi-okay documentation on how to use them, which helped me clarify about inputs and outputs (some examples on the docs page).
The Elliptic functions page also helped understand the Sigma & Zeta functions better. This page & the Maplesoft docs helped understand about Eisenstein series a bit more.
So I have been able to find out how to solve one of the two functions. I have still a couple of questions about the explanation on the Maplesoft docs, I'll take it up with them, but would be great if someone else could help me answer them in case they don't get back in time.


Compatibilidade de Assembly e arquiteturas

Question: Eu não tenho experiência nenhuma com a linguagem de baixo nível Assembly.
O que é necessário para obter o máximo de cross platform com essa linguagem?
Digo, se me focar apenas na AMD64 (x86-64) obterei compatibilidade com todos os computadores atuais?
Comment: Obrigado,mas não entendi onde estou incitando opinião.Eu não entendo de assembly.Gostaria apenas saber sua capacidade de cross platform.
Comment: @Andrey e Weslley, ok. Retirei o voto para fechar.
Comment: @Segio Não entendo de Assembly, mas ele só está perguntando sobre compatibilidade mesmo. Não é preciso fechar a pergunta.
Comment: Desculpem minha inexperiência no stack,espero que com a ultima edição tenha evidenciado minha real duvida.
Comment: Sim, melhorou e estou respondendo.
Answer: Cada arquitetura de processador tem sua própria linguagem Assembly, é assim desde o início dos computadores modernos na década de 40. A única forma de explorar melhor uma arquitetura é criando uma forma de usá-la de uma forma bem específica. Assembly não é cross platform por definição. Se isto for necessário, use C.
Bom, na verdade cada arquitetura tem um código de máquina diferente, o que faz com que o Assembly seja diferente. É possível ter sintaxes diferentes para a mesma arquitetura.
Atualmente existem centenas ou até mesmo milhares de arquiteturas em uso. Claro que ninguém aprende todos. O mais comum é aprender só um ou dois, quem sabe três.
Aprender várias linguagens Assembly não é difícil. Difícil é ser muito bom em várias. E não há muito espaço no mercado para quem não é muito bom. Lembremos que hoje quase não se usa mais Assembly em qualquer tarefa.
E mesmo que se foque em uma arquitetura pode ser que precise aprender sintaxes diferentes de Assembly. Há assemblers que preferem uma sintaxe diferente para fazer a mesma coisa. Para x86 há a sintaxe Intel e a sintaxe AT&T. Mas a sintaxe é a menor das preocupações.
As arquiteturas mais utilizadas hoje são disparadamente o x86_64 (maioria dos desktops) e o ARM (maioria dos mobiles). De uma certa forma o segundo até já ultrapassou o primeiro.
Todas as outras arquiteturas somadas não chegam perto destas duas. Mas algumas podem ser mais importantes para Assembly. Arquiteturas de dispositivos embarcados, que normalmente não são muito usados, ainda continuam usando Assembly como linguagem principal. Isto tem mudado bastante. Cada vez mais se usa C ou C++ mesmo nestes casos mas o Assembly é comum.
A linguagem Assembly tem vínculo absoluto com o processador e nada mais. Sistemas operacionais não afetam o Assembly em si. Claro que talvez você tenha que lidar com especificardes deles mas por outros motivos e não pela linguagem. Exemplo:

Se você não estiver usando um assembler (duvido) terá que saber o formato do arquivo executável do sistema operacional.
Acessar a API (processos, arquivos, GUI, etc.) do sistema operacional é sempre feita de forma específica para ele mas não pertence à linguagem.

Note que se você não estiver escrevendo um backend de um compilador, saber só o Assembly é a ponta do iceberg. Mesmo neste caso, o Assembly é apenas um parte do conhecimento necessário.
Aprender Assembly é muito útil para entender o funcionamento do computador, para ter um hobby mas hoje sua utilização prática reduziu enormemente. Raramente se usa mesmo para produzir sistemas operacionais ou drivers. Fora compiladores/JITters (mesmo assim, não todos os tipos), bootstrap e alguma arquitetura que não possua outra linguagem, Assembly é absolutamente desnecessário.
Coloquei no GitHub para referência futura.
Comment: Obrigado,abriu horizontes.


looping to make new variables R

Question: is there a cleaner way to do the following using a loop solution in R? As of now, I am resorting to cutting and pasting, which changing the reference column as I want to result to be attached to an existing data set as a new variable. Thank you in advance.
library(tm)
library(SnowballC)
data <- data.frame(c("asd"), c(3))
list <- c("eat", "drink")

text <- c("I would like to eat and drink all day")

text <- Corpus(VectorSource(text))
text <- tm_map(text, content_transformer(tolower))
text <- tm_map(text, removePunctuation)
text <- tm_map(text, removeNumbers)
text <- tm_map(text, removeWords, stopwords('english'))
text <- tm_map(text, stemDocument)
text <- tm_map(text, stripWhitespace)
text <- as.data.frame(text)
text <- text$text
text <- strsplit(as.matrix(text), ' +')
text <- lapply(text, lapply, function(z) paste0(' ', z))
text <- lapply(text, unlist)

implode <- function(..., sep='') {
  paste(..., collapse=sep)
}

wordProportion <- function(x, corpus) {
  y <- length(grep(corpus, x))
  return(y/ length(x))
}

estimateProportion <- function (corpus, domain) {
  x <- as.data.frame(extractCorpus2(domain)) %>% distinct(text)
  x <- implode(x$text, sep=" | ")
  x <- unlist(lapply(corpus, wordProportion, x))
  x <- findInterval(x, quantile(x[x > 0], seq(0, .9, .1)))
}

data$topic_1 <- estimateProportion(text, list)

Comment: This question appears to be off-topic because it is about how to use R without a reproducible example.
Comment: My apologies gung. I will work up a workable example. And didn't think I was in cross-validated still. Thank you for catching my errors.
Comment: Could you add some data to go along with your code? I would like to see more how you have your data set up so that I can try to make it better. I am thinking a little bit of `lapply` and `cbind` would do the trick. Talk to you latter @user2300643 .
Comment: Thanks for adding some more code.
Comment: I get an error when I run your code. `> text <- as.data.frame(text)
Error in as.data.frame.default(text) (from test.R!4384e6I#16) :
  cannot coerce class "c("VCorpus", "Corpus")" to a data.frame`
Comment: Sorry, Jarrod. I've cleaned it up by starting a fresh session.
Answer: Here is a loop, you have to add the column titles later because you can't use the $ this way
for (i in 1:n) {
 train[,(i + y)] <- estimateProportion(train_corpus, train_lda_term[, i])
 # where y is the number of preceding columns and n is however many columns you want to add
}
colnames(train[(1+y):(n+y)] <- paste0("TOPIC_0",1:n)

edit: unless train is a list, then replace train[,(i + y)] with train[(i + y)] and colnames with names
Comment: Thank you, JeremyS. I received the following:
Error: unexpected '}' in:
"  train[,(i + 5)] <- estimateProportion(train_corpus, train_lda_term[, i]
}"
Comment: there is a missing `)`

looping to make new variables R