Is it possible to find the least common divisor of a two numbers that are not relatively prime in polynomial time?

Question: As the question states:
Is it possible to find the least common divisor of two number that are not relatively prime in polynomial time? If so, how?
Thanks!
Comment: You can find the $\gcd$ in polynomial time, and then the task is to find the smallest prime factor of some number in polynomial time. If the $\gcd$ happens to be prime, or have a small prime factor, that's easy. In general, that would mean you have a fast factorisation algorithm. As far as I know, there is no known algorithm to find the smallest prime factor of a number in polynomial time.
Comment: If we had a good "least common divisor $\gt 1$" algorithm, applying it to $(N,N)$ where $N$ is big would give us a good factoring algorithm.
Comment: "least" common divisor?
Comment: Least common divisor other than one?
Comment: Yes, least common divisor greater than one.
Comment: Smallest common prime factor, in other words.
Comment: Exactly. Can that be calculated in polynomial time?
Comment: Ahh okay, thank you very much.
Comment: @AndreNicolas : why don't you make that into an answer, and combine it with the fact that (I am pretty sure) no one knows if such an algorithm exists?
Comment: @Stefan Smith: It is already implicitly contained in the comment by Daniel Fischer. If no one answers for a fair while, and I can find the question again, I can make a CW answer.
Comment: @StefanSmith, I think it's pretty much certain that if anyone had published such an algorithm then we'd all have heard about it. Of course, that doesn't mean the NSA doesn't have one hidden away somewhere.
Answer: In short, the answer is no. There is a heuristic why it should be hard in general. Namely, the least common divisor divides the greatest common divisor. The greatest common divisor is calculable in log time. We then would want to calculate the smallest divisor $> 1$ of the gcd. But if the gcd is a hard to factor number, we're out of luck.
More generally, if we had such a technique, then we would also be able to factor in polynomial time. While this might yet be possible (in the sense that we haven't proved it's impossible), it's not likely and certainly not currently known. As Andre Nicolas said in the comments, we would apply the least-common-divisor operator to $(N,N)$, which would spit out a factor. Repeating, we could completely factor $N$.
As an aside, it is sometimes common for factoring algorithms to take the gcd of $N$ and the product of the first $40$ primes or so, to get all the small primes out of the way. This is fast, and so we can find small prime divisors quickly. But this is a different question.


Graphical Interpretation of the Trigonometric identity $A\cos(\theta)+B\sin(\theta)$

Question: I have been  taught how to manipulate any expression given as
$$A\cos(\theta)+B\sin(\theta)$$
and then getting useful results by writing it as
$$\sqrt{A^2+B^2}\left(\frac{A\cos(\theta)}{\sqrt{A^2+B^2}}+\frac{B\sin(\theta)}{\sqrt{A^2+B^2}}\right)$$
Now we just made an right angled Triangle with sides $$A,B,\sqrt{A^2+B^2}$$
Now in this triangle one angle was taken as $\phi$..and so the expression above was rewritten as
$$(\sqrt{A^2+B^2})(\sin(\phi)\cos(\theta)+\sin(\theta)\cos(\phi))$$ or popularly as $$\sqrt{A^2+B^2}(\sin(\theta+\phi))$$...
while this is very clear to me but I haven't been able to get the idea of $\phi$ in the question ..it wasn't even in the question after all...it was like we just made it up!!..I think the triangle means something on the graph of sine or cosine or something like that.. so.does anybody know the graphical or intuitive or physical interpretation of the triangle and angle $\phi$ ??it must be having some special meaning..in the graph..atleast intuitively..
Comment: Use `\sqrt{bla+bla}` to produce $\sqrt{bla+bla}$.
Comment: [The picture in this answer](http://math.stackexchange.com/a/856600/409) may be helpful. A more-elegant rendering is [here](http://trigonography.com/2015/09/30/combining-sine-and-cosine/).
Comment: Sorry to be pedantic, but if a line of mathematics does not have an equals sign ("$=$"), it is not an equation. You are working with an *expression*. Equations may at times be solved, while expressions may be simplified, or expanded, or (what you want) transformed.
Comment: Note that $\phi$ should satisfy $\tan\phi=A/B$
Comment: @MPW I think that is clear to everyone by looking at the triangles picture ..
Comment: But does it mean anything graphically or intuitively??..please read the question..
Comment: @Lubin ..Oh!!sorry..that is a very huge mistake on my part...I bet any 6th standard student will laugh at me for this big mistake ..will correct it now..Thnx for pointing out..
Comment: Please, we all slip up. Don't feel so abashed!
Answer: The basic intuition that I apply to this question is that
we are dealing here with various sinusoidal functions with period $2\pi$.
The function $\theta \mapsto \sin(\theta)$ is one such function,
and $\theta \mapsto \cos(\theta)$ is another such function.
In fact, every sinusoidal function of $\theta$ with period $2\pi$ is either
$\sin(\theta)$ or some stretched-and/or-translated version of $\sin(\theta)$,
such as $2 \sin(\theta)$ (whose graph has peaks and valleys twice as far from the $\theta$-axis as the graph of $\sin(\theta)$)
or $\sin\left(\theta - 1\right)$ (whose graph looks exactly like the graph of $\sin(\theta)$ except that it is shifted one unit to the right).
The cosine function also is a sinusoidal function with period $2\pi$:
$$\cos(\theta) = \sin\left(\theta + \frac\pi2\right).$$
The fact is that if you take any linear combination of sinusoidal functions
with period $2\pi$, you get a new function that also happens to be a
sinusoidal function. For example, consider the function
$$f(\theta) = \frac12 \sin(\theta) - \frac32 \cos(\theta).$$
As we can see from the graph of this function, the result of combining the
sine and cosine functions in this way is a graph that looks just like the
graph of the sine function, but with higher peaks and shifted slightly to the right.
If we want to talk about a linear combination of sine and cosine in
the most general way, we can write
$$g(\theta) = A\cos(\theta)+B\sin(\theta)$$
which says that $g(\theta)$ is a function formed by taking some linear
combination of sine and cosine, literally any linear combination that you like.
(Just pick any real-numbered values to plug in for $A$ and $B$!)
The fact that
$$A\cos(\theta)+B\sin(\theta) = \sqrt{A^2+B^2}(\sin(\theta+\phi))$$
is a fact that is proved via the manipulations you have shown.
That is, these manipulations show that the function $g(x)$ is basically
a sine function, except that it is stretched vertically by a factor
of $\sqrt{A^2+B^2}$ and it has been shifted to the left by $\phi$ units
(or to the right by $-\phi$ units; those are two ways of describing
the same movement).
In other words, we prove that
$\theta \mapsto A\cos(\theta)+B\sin(\theta)$ is a sinusoidal function
by finding out how much we have to stretch and shift the sine function
in order to get something equal to $A\cos(\theta)+B\sin(\theta)$.
And $\phi$ is just a symbol that we use to mean
"how far we have to shift the function".
Comment: The "phase angle" is basically just an ordinary thing, as you say, and it is the same as the $\phi$ that appears in your question and this answer. For Fourier decomposition of a periodic function you generally need to add together functions with various different time periods, but for each time period you _could_ just use one function (sine _or_ cosine) with a suitable coefficient (scaling factor) and a suitable phase angle. For that particular application, though, I think people found it's more convenient to just have two coefficients rather than one coefficient and a phase angle.
Comment: so when Fourier said "***any periodic function can be expressed as a superposition of sine and cosine functions of different time periods with suitable coefficients"*** he could also have said ***any periodic function can be expressed either as a sine function or cosine function with suitable coefficients*** right??
Comment: And oh!! One of the answers given below talks about $ \phi$ being the phase angle..and on searching for phase angle it leads to frequencies.. Simple harmonic motion..electricity..and all that ..so do know you know of anything like this...is this ***phase angle*** just an ordinary thing (by looking at your fantastic explanation it does seem very simple indeed!!).with a very complicated frightening name!! At least from mathematical point of view...
Answer: In fact, $\phi$ is not arbitrary! You should find a $\phi$ in the interval $[0,2 \pi)$ for given values of $A$ and $B$ such that
$$\eqalign{
  & \sin \phi  = {A \over {\sqrt {{A^2} + {B^2}} }}  \cr
  & \cos \phi  = {B \over {\sqrt {{A^2} + {B^2}} }} \cr} $$

Example
Consider $A={1 \over \sqrt3}$ and $B=1$. Then you get
$$\left\{ \matrix{
  \sin \phi  = {{{1 \over {\sqrt 3 }}} \over {\sqrt {{1 \over 3} + 1} }} = {1 \over 2} \hfill \cr
  \cos \phi  = {1 \over {\sqrt {{1 \over 3} + 1} }} = {{\sqrt 3 } \over 2} \hfill \cr}  \right.\,\,\,\,\, \to \,\,\,\,\,\phi  = {\pi  \over 6}$$
Here is an image comparing the graph of $\sqrt {{A^2} + {B^2}} \sin \left( {\theta  + \phi } \right)$ in $\color{green}{green}$ with the graph of $\sqrt {{A^2} + {B^2}} \sin \left( \theta  \right)$ in $\color{blue}{blue}$. The length of the $\color{red}{red}$ line equals the angle $\phi$ in radian.
Comment: @Freelancer: So I don't really get you by your question! :) You said in question that "but I don't think $\phi$ is just too arbitrary after all". I think you have stated your question badly! Try to shorten your last discussions and make a clear question at the end! :)
Comment: I have edited the question..
Comment: @Freelancer: See the image I added. :)
Comment: @Freelancer: Oh god! No! It is its geometrical interpretation! The length of the line equals the angle in radian! :)
Answer: This is coming from the sin of sum formula.
A nice geometric proof of this is given by Nelson in "Proofs without words", see picture below:
To understand it, construct the following picture around your triangle:

In the first picture above replace the pink triangle by your triangle with sides $A,B, \sin{A+B}$ and draw two triangles with angle $\alpha=\theta$.
Now calculate the lengths of the rectangle in terms of $A,B, \theta$, and then look at the white triangle.
Added about the graphical part This can be done easily but you need to work with complex numbers, and then you lose insight as graphs of complex functions cannot be drawn to well: Consider $A,B \in \mathbb R$.
$$A\cos(\theta)+B\sin(\theta)= \frac{A-Bi}{2} [\cos(\theta)+i \sin(\theta)]+ \frac{A+Bi}{2} [\cos(\theta)-i \sin(\theta)]$$
Graphically, $\frac{A-Bi}{2} [\cos(\theta)+i \sin(\theta)]$ rotates the complex number $\frac{A-Bi}{2} $ by an angle of $\theta$ and $\frac{A+Bi}{2} [\cos(\theta)-i \sin(\theta)]$ rotates the number $\frac{A+Bi}{2}$ by $-theta$.
To get the formula, all you need to see is that if you start from the complex number $z =A+Bi$, you rotate $\frac{\bar{z}}{2}$ by $\theta$,  rotate $\frac{z}{2}$ by $-\theta$, and add them together, you get the imaginary part of ( $z$ rotated by $\theta$).
Comment: @Freelancer Intuitively i think that this picture explains well what happens there. As for the graphical question, which graph do you really mean? Do you mean $A \sin(\theta), B \cos(\theta),  A \sin(\theta)+B \cos(\theta)$ or $\sin(\theta+\phi)$? Note that the question really boils down to the following: When we add two graphs together why do we get the third graph? And adding graphs is very hard to do "graphically"...


Any way to test if the association between X and Y could be causal, reverse-causal or non-causal (just correlation)?

Question: I'm doing a regression between Institutional Investment and Total Debt for 500 companies over 2000-2022. Basically, it's panel data. I get the results of the regression and I see that the two are correlated. Now, please guide me as to how I check if that correlation is also a causation with X affecting Y or Y affecting X?
I read over the internet and I found that causality can be checked only if there is a exogenous shock to the system. In my case, I could say that the 2008 Crisis and COVID Crisis were outside shocks to the system. The data for 2007-2009 and 2020-2022 has the effect of those shocks.
However, how do I use this information statistically and reflect it in data to arrive at an conclusion? My apologies for not being precise in my question as I'm new to statistics. Thank you!
Answer: As has been discusssed extensively, evidence for causation does not come from data.  It comes from understanding the data generating process, the meaning of the measurements, the subject matter context, the study design, and in short on the ability to rule out alternative explanations.
Comment: That might be used to RULE out causality: If X follows Y, then X cannot cause Y (although even there, there might be exceptions that I am not thinking of), but it is possible for X to follow Y with no causal relationship at all.

But, in the real world, things are rarely so simple, certainly not in subjects like economics (your example), psychology, sociology etc.   It could even be causal in one direction in one company and the other direction in another company.
Comment: I think "follows" refers to temporality here - you know the temporal sequence of events you're interested in. From that sequence you know which things happened before and after X -and you know the latter could not have caused X, you don't need a statistical test for that.
Comment: Thank you for the instant response. I understand your point that data can not be used to conclusively prove causality. However, what if I were to say I want to see whether X follows Y or vice-versa without taking causality into account. For example, in a 10 year data for X and Y, X always shows a drop after a drop in Y and a rise after a rise in Y. This can be observed from data. Right? How do I make a similar deduction in my above case?
Comment: @PeterFlom That clears a lot of questions in my mind. Thank You. However, if I remove causality from the equation, is there a way to establish whether X follows Y or vice-versa through a statistical method? Being able to rule out causality is also helpful in my case.
Comment: Lack of correlation is also not proof of non-causality. Data alone cannot answer this type of question @wolterskluver
Answer: To argue that this relationship is causal, you need an exogenous shock which only affects X and does not directly affect Y. Moreover, the shock should not affect other factors related to Y, otherwise the effect you will measure will be that of X and other factors. This is something that as Frank Harrell says cannot be proved via data, but about which you have to persuade your audience.
For example, if I want to measure the effect of working from home on wages, Covid (an exogenous shock) might be an interesting idea, since many people suddenly started working from home. However, Covid changed a number of things, for example forcing children to learn from home, which might in turn lower people's productivity. I will have trouble persuading people that this is a useful exogenous shock, since Covid changed a large number of factors affecting productivity (out of which working from home is just one). Perhaps I can focus on people without children to rule out this particular rival theory, but there will be many others I have to think of.
Finally, if you want to strengthen your argument about causality (rather than just correlation), it might be helpful to propose a mechanism -- through what channel does X affect Y? For example, once it was understood how exactly certain chemicals in cigarettes degraded the body, the case that smoking actually causes lung cancer became much stronger (it took 3 decades from first studies until policymakers and the public were persuaded of a causal link).
Good luck with your study!
Comment: You can't "find" an exogenous shock variable in the sense I think you mean. The only way to provide evidence of one variable causing changes in another is to design an experiment. No statistical method can extract causality from your data if your data is not from a well-controlled experimental design. (cont.)
Comment: Hi @wolterskluver, I am not sure what your exact setting is, but perhaps [Instrumental variables](https://en.wikipedia.org/wiki/Instrumental_variables_estimation#Interpretation_as_two-stage_least_squares) could be of use to you, or this discussion about some successful [natural experiments](https://www.nobelprize.org/uploads/2021/10/popular-economicsciencesprize2021-3.pdf).
Comment: @wolterskluver please accept an answer if you found it satisfactory, thank you!
Comment: Thank you very much! Beautifully explained. Now, assume I find an exogenous shock that effects only one variable. How do I proceed? What statistical methods and techniques would you suggest I use. I'm sorry for asking such basic questions. I've just started studying Statistics.
Comment: ...however, is you have data with, say, long follow-up with the same variables measured many times during different time periods, and you observe changes in X every time right after you observe changes in Y, I think most of your fellow researchers would be willing to agree it's a reasonable theory that Y changing has something to do with X changing, all other things being equal.


Using Mathematica to Automatically Reveal Matrix Structure

Question: I spend a lot of time looking at larger matrices (10x10, 20x20, etc) which usually have some structure, but it is difficult to quickly determine the structure of them as they get larger.  Ideally, I'd like to have Mathematica automatically generate some representation of a matrix that will highlight its structure. For instance,
(A = {{1, 2 + 3 I}, {2 - 3 I, 4}}) // StructureForm

would give
{{a, b}, {Conjugate[b], c}}

or even
{{a, b + c I}, {b - c I, d}}

is acceptable.  A somewhat naive implementation
StructureForm[M_?MatrixQ] :=
  MatrixForm @ Module[
    {pos, chars},
    pos = Reap[
           Map[Sow[Position[M, #1], #1] &, M, {2}], _,
           Union[Flatten[#2, 1]] &
          ][[2]];  (* establishes equality relationship *)
    chars = CharacterRange["a", "z"][[;; Length @ pos ]];
    SparseArray[Flatten[Thread /@ Thread[pos -> chars] ], Dimensions[M]]
  ]

works only for real numeric matrices, e.g.
StructureForm @ {{1, 2}, {2, 3}} == {{a, b}, {b, c}}

Obviously, I need to define what relationships I think may exist (equality, negation, conjugate, negative conjugate, etc.), but I'm not sure how to establish that these relationships exist, at least in a clean manner. And, once I have the relationships, the next question is how to determine which is the simplest, in some sense?  Any thoughts?
One possibility that comes to mind is for each pair of elements generate a triple relating their positions, like {{1,2}, Conjugate, {2,1}} for A, above, then it becomes amenable to graph algorithms.
Edit: Incidentally, my inspiration is from the Matrix Algorithms series (1, 2) by Stewart.
Comment: Might be hard in general. For structure checking e.g. is it Hermitian with symbolic variables assumed real, could use as a utility something like SameQ[mat,ComplexExpand[Conjugate[Transpose[mat]]]]. If you work with explicit Re and Im then built in HermitianMatrixQ may also be of some use. Likewise SymmetricMatrixQ.
Comment: @Daniel, I knew it wasn't easy, but I thought I'd ask. Both `HermitianMatrixQ` and `SymmetricMatrixQ` are nice, and would be useful in displaying matrices with only those types of symmetry. Unfortunately, as is often the case, the matrices I work with usually have more complicated symmetries, in addition to be Hermitian, and I'd like a tool that can display such structure. Definitely not a simple request.
Comment: @Daniel, also, `MatrixPlot` and `ArrayPlot` are sometimes useful, but they don't reveal the structure of symbolic matrices, and it is difficult to use them to determine hermiticity. Ideally, I'd like to perform one test to more clearly reveal the structure, and the current tools require multiple tests.
Comment: I wonder, if two pieces of the matrix have some _numerical similarity_ that does not necessarily imply they are part of the same _structure_, does it? See  RotationMatrix[a] // structureForm
==> {{"a", "b"}, {-"b", "a"}}, whereas RotationMatrix[\[Pi]/4] // structureForm ==> {{"a", -"a"}, {"a", "a"}} and  RotationMatrix[\[Pi]/8] // structureForm ==> {{"a", "b"}, {-"b", "a"}}
Comment: @Sjoerd, in the examples you gave, all the matrices are [orthogonal](http://en.wikipedia.org/wiki/Orthogonal_matrix), so they have the same structure. Therefor, the pieces of the matrix must have some prescribed numerical similarity.
Comment: @rcollyer This is not what I meant. The current methods tend to equate numerical equality to structural equality. However, numerical equality can occur by chance without implying any structural relationship. In the above example I think the _structure_ should be {a,b} not {a,a} (with b possibly, but not necessarily equal to a).
Comment: @Sjoerd, you're correct that it could be accidental. Except in your examples, they not. The Pi/4 rotation is special in that it turns the axes into `y==x` and `y==-x`, so having `b==a` in that case is not surprising.
Comment: @rcollyer Indeed, I chose the angle specifically for the purpose of making b==a. It makes the _values_ the same but of course doesn't change anything in the _structure_ of the matrix. Anyway, nuf said about the example. My main point is still numerical equality =!= structural equality.
Comment: @Sjoerd, the more I think about it, the more I'd have to agree.  But, I think the statement is that structural equality is more strict than numerical equality, as numerical equality would miss the additional condition that the determinant of an orthogonal/unitary matrix is `PlusMinus[1]`. Then, structural equality implies some form of numerical equality, but numerical equality cannot fully imply structural equality, only hint that it may exist.
Answer: We can start by defining the relationships that we want to recognize:
ClearAll@relationship
relationship[a_ -> sA_, b_ -> sB_] /; b == a := b -> sA
relationship[a_ -> sA_, b_ -> sB_] /; b == -a := b -> -sA
relationship[a_ -> sA_, b_ -> sB_] /; b == Conjugate[a] := b -> SuperStar[sA]
relationship[a_ -> sA_, b_ -> sB_] /; b == -Conjugate[a] := b -> -SuperStar[sA]
relationship[_, _] := Sequence[]

The form in which these relationships are expressed is convenient for the definition of structureForm:
ClearAll@structureForm
structureForm[matrix_?MatrixQ] :=
  Module[{values, rules, pairs, inferences}
  , values = matrix // Flatten // DeleteDuplicates
  ; rules = Thread[Rule[values, CharacterRange["a", "z"][[;; Length@values]]]]
  ; pairs = rules[[#]]& /@ Select[Tuples[Range[Length@values], 2], #[[1]] < #[[2]]&]
  ; inferences = relationship @@@ pairs
  ; matrix /. inferences ~Join~ rules
  ]

In a nutshell, this function checks each possible pair of values in the matrix inferring a substitution rule whenever a pair matches a defined relationship.  Note how the relationship definitions are expressed in terms of pairs of substitution rules in the form value -> name.  Matrix values are assigned letter names, proceeding from left-to-right, top-to-bottom.  Redundant inferred relationships are ignored assuming a precedence in that same order.
Beware that the function will run out of names after it finds 26 distinct values -- an alternate name-assignment strategy will be needed if that is an issue.  Also, the names are being represented as strings instead of symbols.  This conveniently dodges any unwanted bindings of the single-letter symbols names.  If symbols are preferred, it would be trivial to apply the Symbol function to each name.
Here are some sample uses of the function:
In[31]:= structureForm @ {{1, 2 + 3 I}, {2 - 3 I, 4}}

Out[31]= {{"a", "b"}, {SuperStar["b"], "d"}}

In[32]:= $m = a + b I /. a | b :> RandomInteger[{-2, 2}, {10, 10}];
         $m // MatrixForm
         $m // structureForm // MatrixForm

Comment: +1, clever. I like the use of `Tuples` with `Select` to avoid go over some pairs twice. Incidentally, the use of `DeleteDuplicates` obviates the need for equality `Relationship`, but it is just a nit. What I like about the use of `Relationship` is that a set of functions could be passed in to `structureForm` taking 2 params that would become the condition on the `Relationship`. Additionally, the display could be passed in alongside the conditions. I'm going to give it a couple of days more, but this looks good.
Comment: @rcollyer The equality relationship definition is only necessary to the extent that the semantics of equality differ from `PatternMatchQ`.  Try deleting the definition and then evaluating, for example, `structureForm[{{1.0, 1}, {1.0, 1}}]`.  This may or may not be an issue in any particular application.  If the matrices can contain symbolic expressions, I was imagining that the equality relationship definition would be more elaborate, perhaps involving `Reduce`.
Answer: Have you tried looking at the eigenvalues? The eigenvalues reveal a great deal of information on the structure and symmetry of matrices and are standard in statistical analysis of datasets. For e.g.,

Hermitian/symmetric eigenvalues have
real eigenvalues.
Positive semi-definite matrices have
non-negative eigenvalues and vice versa.
Rotation matrices have complex eigenvalues.
Circulant matrices have eigenvalues that are simply the DFT of the first row. The beauty of circulant matrices is that every circulant matrix has the same set of eigenvectors. In some cases, these results (circulant) can be extended to Toeplitz matrices.

If you're dealing with matrices that are random (an experimental observation can be modeled as a random matrix), you could also read up on random matrix theory, which relates the distributions of eigenvalues to the underlying symmetries in the matrix and the statistical distributions of elements. Specifically,

The eigenvalue distribution of symmetric/hermitian Gaussian matrices is a [semicircle]
Eigenvalue distributions of Wishart matrices (if A is a random Gaussian matrix, W=AA' is a Wishart matrix) are given by the Marcenko-Pastur distribution

Also, the differences (spacings) between the eigenvalues also convey information about the matrix.
I'm not sure if the structure that you're looking for is like a connected graph within the matrix or something similar... I presume random matrix theory (which is more general and vast than those links will ever tell you) has some results in this regard.
Perhaps this is not really what you were looking for, but afaik, there is no one stop solution to getting the structure of a matrix. You'll have to use multiple tools to nail it down, and if I were to do it, eigenvalues would be my first pick.
Comment: @rcollyer: You're right that eigenvalues are immensely helpful in numerical cases. However, I disagree that the eigenvalues are less useful in symbolic matrices. Yes, the equations become messier and as the size of your matrix grows, it'll probably get harder. But for smaller sizes, as in your examples, they're still worth a shot. The eigenvalues of a matrix are the roots of the characteristic polynomial, `|A-λI|`. Mathematica has a built in function `CharacteristicPolynomial` that will give you the expression for your matrix. Now you have a nice polynomial in terms of your variables(contd...)
Comment: and you can always use the `Discriminant`, `Δ` to set bounds on what the variables should be for it to be a particular structure... If `Δ>0`, the polynomial has real roots -> eigenvalues are real -> Hermitian/symmetric. If `Δ=0`, multiple root -> matrix is not full rank and `Δ<0`-> complex eigenvalues. These are particularly helpful if you have a symbolic matrix and you want to poke at what would happen if you were to change some of the variables. There are some more algebraic results that you can use to narrow down on the sign of the roots, which will tell you about the positive definiteness.
Comment: @RM, you are absolutely correct in the the eigenvalues/vectors are the way to go, if the matrix is purely numerical. If the matrix is symbolic, however, the eigenvalues are less useful because of the complexity of the formulas. And, sometimes just being able to look at how the values are laid out is helpful. I realize that it can't be the only tool used, but it would be nice to have.
Comment: @RM, at least in v. 6 (I haven't tried recently), calculating the `CharacteristicPolynomial` for an 8x8 matrix would peg my CPU and take nearly 20 mins. Something about the symbolic nature of the matrix would cause it to go haywire. Personally, I'm more a fan of decomposing it according to its irreducible representations.
Comment: @RM, did not know about `Discriminant`, will have to play with it. Okay, v.7 is much better on speed, however the `CharacteristicPolynomial` isn't necessarily that revealing with that large number of terms. While it obeys the same symmetries as the matrix, the structure can easily hide in the result.
Comment: @rcollyer: I agree that `CharacteristicPolynomial` chokes up the machine even for small matrices. `Discriminant` can be quite a pain too, and will refuse to work even for "nice" polynomials. To get the discriminant out, you can use `GroebnerBasis` to eliminate the implicit polynomial and its derivative to get the discriminant. I remember a talk where the speaker reduced a matrix to the simplest tree form possible for that matrix, and then some nice combinatorics results could be easily applied (something which would not have been obvious from the matrix form). Let me see if I can find it...
Comment: @RM, any luck in finding the talk?
Comment: @rcollyer: I couldn't find the talk, but I did find [the paper](http://fr.arxiv.org/pdf/math-ph/9911002), upon which the talk was based. However, on re-reading the article, I really think it is overkill for what you wanted to do in your question (I can't even begin to think how to go about doing it in mma!). So, don't get your hopes too high :)
Comment: @RM, I'll look it over, and even if it is overkill, thanks for the effort.
Comment: @RM, might be interesting for some of the many-body calcs I do, but for the most part, looks like more trouble than its worth. Thanks, though. I appreciate it.
Comment: @yoda, apparently I'm clueless, I didn't notice the name change.
Comment: @rcollyer :) had a marathon run of all 6 recently and changed in a huff... I think I'm going to stick with it though.
Comment: Recently, I've been attracted to the idea of automatically generating the symmetry operations under which a matrix remains invariant. Doing so would reveal the matrix structure via the group of symmetry ops. Generating the ops should be straight forward, the group structure, not as simple, but doable. Thoughts?


How can I change the name of migration database in database array?

Question: For a Drupal migration from d7 to d8, I have to define my source database to be called 'migrate' in the settings.php as below. My question is: how can I define the source as something other than 'migrate',  where is that set up?
`$databases['default']['default'] = array(
  'database' => "db",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);

$databases['migrate']['default'] = array(
  'database' => "drupal7",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);`

Comment: Probably in the migrate module. Probably hard-coded. Why would you need to have it named differently?
Answer: migrate is the default key used by the SqlBase class which is the base for the D7 source plugins. Its documentation explains in detail how it determines what key to use and how it can be changed. Of relevance:

As described above, the default source database is $databases['migrate']. If the source plugin needs another source connection, the database connection parameters should be added to the $databases array as, for instance, $databases['foo']. The source plugin can then use this connection by setting 'key' to 'foo' in its configuration.

So update the source.key value in your migration configuration to foo then re-import that configuration to change the default key used for that migration source.


tableView.registerClass in swift is fatal error

Question: I use Xcode7
i register the cell in viewDidLoad()
 let SLQHomeTableViewCellID = "SLQHomeTableViewCellID"
 self.tableView.registerClass(SLQStatusCell.self, forCellReuseIdentifier: SLQHomeTableViewCellID)

then the dataSouce like below:
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
  return statuses?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(SLQHomeTableViewCellID, forIndexPath: indexPath) as! SLQStatusCell
    let status = statuses![indexPath.row]
    cell.status = status
    return cell
}

i also override init()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    // 初始化UI
    setupUI()

}

but when i run in simulator ,it's a  fatal error in register cell
,this line is the error appeared
 self.tableView.registerClass(SLQStatusCell.self, forCellReuseIdentifier: SLQHomeTableViewCellID)

fatal error: unexpectedly found nil while unwrapping an Optional value

i want to why,i run the program in using OC is all right.
Comment: Which line is causing the error?
Comment: self.tableView.registerClass(SLQStatusCell.self, forCellReuseIdentifier: SLQHomeTableViewCellID)
Comment: Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu)
Comment: no, the error is appear on this line
self.tableView.registerClass(SLQStatusCell.self, forCellReuseIdentifier: SLQHomeTableViewCellID)
Answer: If the line with the registerClass method call is causing that error, then chances are good the tableView IBOutlet is not connected.  That is the most likely thing on that line of code that would be nil, as it probably has a type of UITableView! which is being implicitly unwrapped.
You can test this by setting a breakpoint and inspecting the value of self.tableView or with a simple print("Table view: \(self.tableView)") statement put above the existing registerClass line.
Comment: i am not using any xib or storyboard ,so using registerClass,and an print the class like below
> + SLQHomeTableViewCellID
fatal error: unexpectedly found nil while unwrapping an Optional value

it cannot see any useful info


Let f be whole such that $z_0$, $z_1$ $\in\mathbb{C}$ $\mathbb{R}$-independant, with $f(z+z_0)=f(z)=f(z+z_1)$ $\forall z\in\mathbb{C}$

Question: I have to show that, if the title is true, then f is constant.
I can't find the way to approach this. I thought using the fact that, since f is whole, $f(z)=\sum_{n=0}^\infty a_nz^n$ for some $a_n\in\mathbb{C}$. Then $f(0)=a_0=f(z_0)=f(z_1)$. I wanted to show that $g(z) = f(z)-a_0$ trying to build a convergent sequence of zeros of $g(z)$ using the $z_0$ and $z_1$ so I could use the identity principle.
I tried it less, because I couldn't find a way to use it, but tried showing that using the $g$ defined above, $g^{(n)}(0)=0$ $\forall n\in\mathbb{N}$
Thanks in advance
Comment: You are right. I didn't find it. Thanks
Comment: Note that what you call "whole function" is usually called an "entire function".
Comment: Thanks. The translation problem
Answer: If $z_0$ and $z_1$ are $\mathbb{R}$-independent, for any $z \in \mathbb{C}$ you can write $z = (n + r_0) z_0 + (m + r_1) z_1$ for some $n,m \in \mathbb{Z}$ and $r_1, r_2 \in [0,1)$. Then we have:
$$\begin{align*}
f(z) & = f((n + r_0) z_0 + (m + r_1) z_1) \\
& = f(r_0z_0 + r_1z_1)
\end{align*}
$$
Thus, we have that$f(\mathbb{C}) \subseteq f(\Omega)$ where $\Omega$ is the set of all linear combinations of $z_1$ and $z_2$ with coefficients in $[0,1]$. That is, $\Omega$ is a closed parallelogram. $\Omega$ is clearly compact, and thus the image $f(\Omega)$ is bounded. Then by the above inclusion, $f$ is a bounded entire function, and hence is constant by Liouville's theorem.


Tricky measure subset problem

Question:
Hi, I am unable to solve the first part, I have tried  many things such as creating an infinite sequence of sets yet cannot seem to prove that they tend to infinity
Answer: Let the RHS of expression be $A'$. This case is trivial $\mu(A)< \infty$.  If $\mu(A)=\infty$. Suppose $A'$ is finite. Prove the following:

Exists $B_n \subseteq A \in \mathcal{A}$ such that $\mu(B_n) \rightarrow A'$.
Modifying 1. Exists $B'\subseteq A \in \mathcal{A}$ such that $\mu(B') = A'$.
Then $\mu(A \setminus B') =?$ Does this yield a contradiction?

Tricky measure subset problem


ITCSS - Onde ficam os arquivos de animações?

Question: Estou estudando ITCSS como uma maneira de estruturar melhor as minhas pastas e arquivos CSS - estou usando em conjunto com RSCSS.
À principio eu estava colocando as animações junto com os componentes ou objetos que seriam animados, mas pensei que a melhor forma seria separar eles em arquivos diferentes e salvar em uma pasta para serem reutilizados.
Answer: Felipe, se formos para o lado teórico da coisa acredito que o correto é colocar as animações em Tools (Ferramentas), vou explicar pq.
Uma vez que vc pode transformar um animação @keyframes em um @mixin e que de acordo com a documentação os @mixins devem ficar na pasta Tools o correto seria colocar as animações em Tools.

Tools
  É o lugar onde você vai guardar seus mixins e funções necessárias para a construção de seus layouts. Pode ser qualquer coisa, desde mixins de font-face, até mixins de animações, etc.

Fonte: https://willianjusten.com.br/organizando-seu-css-com-itcss/#tools
A ideia é que separando as animações em toos depois vc pode usa-las em qualquer elemento por exemplo. Veja que a classe é independente do elemento em si

Exemplo de @mixin com animação
@mixin keyframes( $animationName ) {
    @keyframes $animationName {
        @content;
    }
}

//Uso

@include keyframes( incrediblehulk ) {
    0% {
        color: #f8d2c0;
        // you can also use mixins inside this mixin!
        @include transform( scale(1) );
    }
    100% {
        color: #0f0;
        @include transform( scale(3) );
    }
}

E aqui tem link bem interessante de como criar uma biblioteca de animações
http://brandonbrule.github.io/scss-animation-keyframe-mixin/
Comment: Obrigado, Hugo! Entendi perfeitamente o uso =)
Comment: @FelipeOliveira sem problemas meu caro!


Submitting Data / Updating Data into Webform programmatically

Question: I have an existing WebForm in which I want to submit information through a Custom Page. Any idea how I can do that?
Also, there is another page where I want to update couple of fields in the WebForm through sid (submission ID) in a custom page.
Any Idea how to achieve that?
Comment: See the solution [here](https://stackoverflow.com/a/55273754/2016870) with a particular description how to get data into submission fields.
Answer: You can do this by adding following code in your custom module
<code>  // Submit a webform
  module_load_include('inc', 'webform', 'webform.module');
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  // Load node by webform id
  $node = new stdClass();
  $node = node_load($webform_nid);
  // Get next serial number
  $serial = _webform_submission_serial_next_value($webform_nid);

      $data = array(
        1 => array('Guest user'),
        2 => array('firstname.lastname@example.com'),
        3 => array('Final testing of webform'),
      );

  $submission = (object) array(
    'nid' =>$webform_nid,
    'uid' => 0,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'serial' => $serial,
    'data' => $data,
  );

  $sid = webform_submission_insert($node, $submission);
</code>


Proving $(p∨q)∨(p∨¬q)$ is a tautology

Question: I am trying to prove that $(p∨q)∨(p∨¬q)$ is a tautology.
This is a relatively easy problem because it is easy to tell that the statement will be true whenever p or q or ¬q are true. I have never written proofs before, however and I am wondering what the correct way to prove this would be.
I used the distributive law initially so that my problem could be rewritten as
p∨p ∨q∨¬q which can then simplify to $p∨q∨¬q.$
What law can I use to say from here that this is a tautology due to the fact that p or q or ¬q will always be true?
Comment: The distributive law doesn't apply, because it involves a combination of $\vee$ and $\wedge$; here is only $\vee$.
Comment: Consider that $(q \lor \lnot q)$ is always TRUE and thus the disjunction amounts to $p \lor T$. Then apply the truth table for $\lor$.
Answer: Use associativitiy and commutativity: Your statement has $q ∨ ¬q$ which is always true.
Answer: $(p∨q)∨(p∨¬q) \equiv p \lor p \lor q \lor \lnot q\quad$ due to associativity and commutativity.
$\equiv p \lor (q \lor \lnot q)\quad$ Simplification, associativity.
$\equiv p \lor (T)\quad$ due to the fact that $q \lor \lnot q$ is always true (the law of the excluded middle).
$\equiv T$ because $p \lor T $ is always true.
Therefore, the initial proposition is a tautology.
Comment: Good to help us learning again and again this concept.
Comment: Very well, @RobArthan.
Answer: An alternative approach using $\lor$ introduction and elimination rules.
\begin{array}{l}
 q\lor\neg q \\
 q\rightarrow(p\lor q)\\
 (p\lor q)\rightarrow (p\lor q)\lor(p\lor\lnot q) \\
 \lnot q\rightarrow(p\lor\neg q) \\
 (p\lor\neg q)\rightarrow(p\lor\neg q)\lor(p\lor q) \\
 (q\lor\lnot q)\rightarrow(p\lor\neg q)\lor(p\lor q) \\
 (p\lor\neg q)\lor(p\lor q)
\end{array}

Proving $(p∨q)∨(p∨¬q)$ is a tautology


Rewrite url facet by taxonomy term machine name

Question: I have a multi-facet search page, with those 2 facets : poste and type_de_contrat (= internship, open-ended contract...)
It's working fine, but I'd like to rewrite the url, because it looks like this : <code>?f[0]=poste%3A131&f[1]=type_de_contrat%3A89</code>, i want to rewrite the taxonomy IDs by the taxonomy machine name.
I've created and activated a ProcessorHandler to achieve this.
<code>/**
 *
 * @FacetsUrlProcessor, which can be configured on the Facet source.
 *
 * @FacetsProcessor(
 *   id = "mymodule_processor_handler",
 *   label = @Translation("Gestion 'Type de contrat' preprocess"),
 *   description = @Translation("Permet de preprocess la facette type de contrat."),
 *   stages = {
 *     "pre_query" = 99,
 *     "build" = 99,
 *   },
 *   locked = false
 * )
 */
class TypeContratProcessorHandler  extends ProcessorPluginBase implements BuildProcessorInterface, PreQueryProcessorInterface, ContainerFactoryPluginInterface {

  /**
   * The actual url processor used for handing urls.
   *
   * @var \Drupal\facets\UrlProcessor\UrlProcessorInterface
   */
  protected $processor;

  /** @var \Symfony\Component\HttpFoundation\RequestStack*/
  protected $request;

  /**
   * Constructs a new object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RequestStack $request) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('request_stack')
    );
  }

  /**
   * Gets the Processor.
   *
   * @return \Drupal\facets\UrlProcessor\UrlProcessorInterface
   *   The Processor.
   */
  public function getProcessor() {
    return $this->processor;
  }

  /**
   * {@inheritdoc}
   */
  public function preQuery(FacetInterface $facet) {
  }

  /**
   * {@inheritdoc}
   */
  public function build(FacetInterface $facet, array $results) {
    $current_request = $this->request->getCurrentRequest();
    if ($current_request === NULL) {
      return $results;
    }
    $taxo_name = "type_de_contrat";
    $filter_key = 'f';
    $facet_url_alias = $facet->getUrlAlias();
    /** @var \Drupal\facets\Result\Result $facetResult */
    foreach ($results as &$facetResult) {
      $url = $facetResult->getUrl();
      if ((int) $facetResult->getRawValue() == '') {
        $facetResult->setActiveState(TRUE);
        $url->setRouteParameters([$facet_url_alias => '']);
      }
      else {
        // rewrite here.
        $taxo = Term::load($facetResult->getRawValue())->get('machine_name')->value;
        $url->setRouteParameters([$facet_url_alias => $taxo]);
      }

      $query = $url->getOption('query');
      $facet_list = $query[$filter_key];
      foreach ($facet_list as $index => $item) {
        if (strpos($item, $facet_url_alias) !== FALSE) {
          unset($query[$filter_key][$index]);
        }
      }
      if (empty($query[$filter_key])) {
        unset($query[$filter_key]);
      }
      $url->setOptions(['query' => $query]);
      $facetResult->setUrl($url);
    }
    return $results;
  }

}
</code>
But with this, when selecting the facet type_de_contract, it's always the same selected taxonomy machine name (type_de_contrat=internship), and the facet isn't making any filter anymore...
Answer: I used the facets pretty paths contrib module for things like this.
It can be configured like this:


Selecting 's over several rows and even tables with jquery

Question: I'm trying to build a selectable calendar that show's me some kind of availability.
My first attempt worked great. I just used rows to show me a date and I could easily use nextUntil - but it got a little more complicating after breaking it down into several tables each representing a month.
Now my problem is that I can only select the 's from one row at a time and I can't think of a way to go to the next row without shredding my until statement.
It is very important, that a "booked" class would stop my tool from selecting a td beyond that point.
I hope my question came out kinda clear since english is not my mother tongue.
Thanks a lot to everyone for at least reading through it :D
Now here's the code so far: In this fiddle
Answer: Think this is what you want: http://jsfiddle.net/petersendidit/MEeXV/8/
Cleaned up things a lot.  Make sure to cache your selectors if you are going to use them again.
I also switched to a delegated event for the click handler.
Now when you click on a day it takes the list of all the days and then uses indexes to find all the next and previous days. It make sure to stop when it hits a booked day.
The click handler could probably be split up to make the code cleaner and DRYer, but this will get you on your way.
Comment: Thanks for this. I started working on an answer yesterday, but I think yours is better than mine would have been.


Como retirar comentários automáticos gerados pelo Compass?

Question: Escrevo o código em SCSS, e quando gero o CSS ele vem com comentários de onde está a Class ou ID no meu SCSS.
Alguém sabe como posso retirar esses comentários gerados pelo compass do meu arquivo CSS?
Answer: Altere as configurações no seu config.rb.
Você pode definir a variavel output_style para :compressed por exemplo. No comentário da linha desta variável, por padrão vem escrito outras opções, você pode testar elas para ver qual se encaixa melhor na sua necessidade.
Answer: Você pode desativar os line comments. Eles são geralmente usados pra ajudar a debugar e resolver problemas em projetos grandes, com muitos arquivos SASS.
no config.rb você adiciona:
line_comments = false


Prove that $A$ is regular matrix and find $A^{-1}$ if $A,I\in M_{n\times n}(\mathbb{R})$ and $(A+I)^3=O$

Question: Expansion of a binomial gives:
$$A^3+3A^2+3A+I=0$$
We know that the matrix is regular if squared and has inverse ($detA\neq 0$).
Is it possible to determine from above equation that $detA\neq 0$?
Answer: you can see from $$A(-A^2 - 3A - 3I) = I  $$ that $$A^{-1} = -A^2 - 3A - 3I $$
since $(A+I)^3 = 0$ only eigenvalue is $-1,$ therefore the determinant of $A$ is $(-1)^n.$
Answer: You are basically done.
Take $A^3+3A^2+3A+I=0$ and rearrange it to get $I = -A^3 - 3A^2 - 3A$.
We then have that
$A(-A^2-3A-3I)=I$
and so $A$ is invertible and its inverse is
$A^{-1}=-A^2-3A-3I$
Answer: Yes. Since: $A^3+3A^2+3A+I=0$, So the minimal polynomial of $A$, is a factor of $(x+1)^3$. Thus, the only eigenvalue of $A$ is $-1$. So, $det(A)=(-1)^n\neq 0$.
Comment: The constant term of the minimal polynomial is not equal to $\det A$ in general. (Even for $A$ satisfying the conditions of this problem) For example, if $A=\begin{pmatrix} -1 & 0 & 0\\0 & -1 & 0\\ 0 & 0 & -1\end{pmatrix}$, then the minimal polynomial of $A$ is $x+1$, which has constant term $1$. But $\det A = -1 \neq 1$. We can, however, conclude that $A$ is invertible because the constant term of the minimal polynomial is not $0$.
Comment: While it is true for matrices $A$ which satisfy $(A+I)^3=0$ that the constant term of the minimal polynomial is $(-1)^n \det A$, it is still not true in general. It is only true in this case because all of the eigenvalues of $A$ are $-1$, and so the determinant of $A$ is $(-1)^n$. If we consider $B=\begin{pmatrix} 1&0&0\\0&2&0\\0&0&2\end{pmatrix}$, though, then the minimal polynomial of $B$ is $(x-1)(x-2)$ which has constant term $2$. But $\det B=4$. So while what you have written is true specifically in the context of this problem, it is not true in general.
Comment: I think that you may be thinking about the result which says that the determinant of a matrix is equal to the constant term of the *characteristic* polynomial. Fortunately, we do not need to know exactly how the determinant of $A$ relates to the constant term of the minimal polynomial, just that if the constant term of the minimal polynomial is not $0$ then neither is the determinant.


Deleting rows in a numpy array iteratively

Question: My program needs to find the product of all the terms in a vector save for one row i, which is determined by a for loop. The numpy.delete function will not accept i as an input, only a number. Is there a workaround for this?
Example:
for i in range(some_range):
    arr=[some vector]
    section=np.delete(arr,i,axis=0)
    return prod(section)

This returns a ValueError: invalid entry message. The code works fine when I replace the i with 1. Is there any way to perform this operation while retaining the for loop?
Comment: Is your indentation correct? The way you have it here with the `return` inside the loop, it will only run once (making the loop pointless).
Answer: No need to delete anything. Just multiply the two subproducts (the elements before i and the elements after i):
In [10]: import numpy as np

In [11]: arr = np.arange(1, 10)

In [12]: i = 3

In [13]: np.prod(arr[:i]) * np.prod(arr[i+1:])
Out[13]: 90720

Like with your original code, you need to make sure that i is a valid index (if you don't, you'd get the product of the entire array).


Preliminary crosstabs in survival analysis?

Question: I am new in survival analysis. I have been taught that you analyze using survival because you have a special dataset: one with censored data. And that if I work only with not censored data, I can have severe bias.
But now, when working with a dataset collected for a survival analysis, I am required to crosstab some dichotomous risk factors and death/censored data.  I also have seen advice in internet to use logistic regression to predict death with the risk factors. This is supposed to be preliminary work to the real survival analysis.
My questions are: ¿Is it a good idea to run crosstabs? Why not univariate Cox if you want crude ratios?
Or exploring the data, why not Kaplan Meier instead of crosstabs?
(I am not a native english speaker. Please excuse my bad english).
Thanks in advance.
Florentino Menéndez
Comment: You probably mean "Life tables", do you? They are proper tabulations for survival analysis.
Comment: Also, some applications of logistic regression *are* (properly) survival analysis (i.e. discrete time logit hazard models), so can you edit your question to amplify on what you mean by "use logistic regression?"
Answer: Crosstabs are used for exploratory data analysis because they're quick and easy to create and have the potential to reveal a lot about the data. They can point the way to what you want to do in the "real" data analysis, i.e. Cox, Kaplan Meier, etc.


Laravel Jensseger Mongodb belongsToMany returns empty array

Question: I am trying to use a belongsToMany relation, in the following way:
Model with belongsToMany relation:
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class Notification extends \Jenssegers\Mongodb\Eloquent\Model
{
    use Notifiable, HasApiTokens;
    protected $collection = 'myDb.notifications';
    protected $fillable = [ ];
    protected $hidden = [  ];

    /**
    * List of involved users
    */
    public function participants()
    {
      return $this->belongsToMany(User::class);
    }
}

Creating a model:
$notification=new Notification();
....
$notification->participants()->attach(["5b13fb4393782d5e9010835d","5b13146f93782d29254c8cb2"]);
$notification->save();

Gives:
{
    ......
    "user_ids": [
        "5b13fb4393782d5e9010835d",
        "5b13146f93782d29254c8cb2"
    ],
    "updated_at": "2018-06-07 12:32:19",
    "created_at": "2018-06-07 12:32:19",
    "_id": "5b1925d393782d24b4514a16"
}

So ids are attached correctly, however, when I try to eager-load them with:
Notification::where('_id','=','5b1925d393782d24b4514a16')->with(['participants'])->get()

I get an empty array for the relation:
[
    {
        "_id": "5b1925d393782d24b4514a16",
        ....
        "updated_at": "2018-06-07 12:32:19",
        "created_at": "2018-06-07 12:32:19",
        "participants": []
    }
]

I have also verified that the given users actually exist, and should be "loadable", using:
User::whereIn('_id',["5b13fb4393782d5e9010835d","5b13146f93782d29254c8cb2"])->get()

Which gives the two users as expected....
Comment: Did you solve this?
Answer: Apparently we need two-way relationship, i.e. we need ids in BOTH tables.
We also need to set keys manually (or perhaps not, but I'm not sure what's right convention)
class Notification extends ...
{
    public function participants()
    {
      // NOTE: we set keys manually here:
      return $this->belongsToMany(User::class, null, 'notification_ids', 'user_ids');
    }
}

class User extends ...
{
    public function notifications()
    {
      // NOTE: we set keys manually here:
      return $this->belongsToMany(Notification::class, null, 'user_ids', 'notification_ids');
    }
}

Considering objects have following properties (fields):
User:
{
   ...
   notification_ids: []
}

Notification:
{
   ...
   user_ids: []
}

(both array of strings (ids))
Using attach should update both tables properly, for example:
$user->notifications()->attach($notification->id)
Answer: I think there is a problem with the relation, can you try something like :
return $this->belongsToMany('App\User');

Comment: I have tried... gives the same result... I also tried specifying the attribute with ->belongsToMany(User::class,null,'user_ids'); but still empty array...


How can I change page title in search results page?

Question: When user search Drupal 7 site, output page's title becomes:
"Search | example.com"
But i want to make page title as:
"Search: keyword1 keyword2 .. | example.com"
I installed "Page Title" module but i couldn't change it by it.
Is there a module to convert page title regarding to this?
Thank you very much
Answer:
Install and enablde Page manager and Panels.
Go to admin/structure/pages, on the line "search-node", click enable, then edit.
Add new variant -> Create variant -> Choose any suitable layout -> Continue twice.
On the final page in the Wizard, expand "Substitutions". You should see two keywords in there, copy "%keywords:raw" to the empty "Title" field above
Below the keywords, click a cog in any suitable region, in the popup click Widgets, and select "Search form".
Repeat step 6 for "Search results".
Click "Create variant", followed by "Update and save".

Take variations for choosen layout into account, and your configuration should now look something like this
Comment: Thank you very much for detailed answer, i made the steps :)   But the node title changed. Can't i change page title? I didn't see "search form" in Page Title module's content type column.
Comment: I believe some definitions are in order. I see no reasonable way this could case any node-title to have changed, so please define more precisely what titles you speak of.
Comment: Regarding to http://drupal.org/files/images/page-title.png with "page title" i mean the title of page in web browser. (i need this because search motor results show the pages without keywords)
Answer: The module "pageTitle" can infact be used for the just named purpose.
After installing and enabling the module you go to the pageTitle configuration page. Here you can define default patterns, but you can also check the box "show field" for the desired content type, taxonomy or whatever. If a basic page is what you have chosen to show this field on, you just go to a node of that type. Added to the vertical tabs at the bottom of the page can now a new tab be found called "Page title setting". This is where you can set the pageTitle that appears in the browser tab and search results.
Answer: In Drupal 7, you can do this in your theme's template.php :
function MYTHEME_process_page(&$variables) {

    if (arg(0) == 'search' ) {
        $keys = arg(2);
        if (!$keys) $keys = $_REQUEST['keys'];
        if ($keys) $variables['title'] = 'Search for "'.$keys.'"';
    }

}

I dont know where your " Search | example.com" title comes from .. but this will probably remove that.
2$c,
*-pike
Answer: In Drupal 7, you can do this in your theme's template.php :
function hook_preprocess_search_result(&$variables) {
  $node_title = $variables ['title'] ;
  .
  .
  .
  $variables['title'] = $title;
}

Comment: Wrong solution. In hook_preprocess_search_result is not a 'title' item in $variables.


Let $L$ be a (topological) complement of $G$. Is $\dim G = \operatorname{codim} L$?

Question: Two Hamel bases of the same vector space have the same cardinality, so we define the dimension of a vector space as the cardinality of one of its Hamel basis.
Could you confirm if my below understanding is fine?

Let $E$ be an infinite-dimensional Banach space. Let $G$ be a closed subspace of $E$. Let $L$ be a (topological) complement of $G$, i.e., $L$ is a closed subspace of $E$ such that $G\cap L = \{0\}$ and $G+L=E$.

By cardinal arithmetic, $\dim G +\dim L = \dim E$. This identity implies a result (for Hilbert spaces) in this question.
By rank-nullity theorem, $\operatorname{codim} L + \dim L = \dim E$.

Then $\dim G = \operatorname{codim} L$ follows from below Lemma.

Lemma Let $A, B, C$ be non-empty sets. If $|A|+|B| = |A|+|C|$, then $|B|=|C|$. Here $|A|$ is the cardinality of $A$.

As indicated in a comment, above Lemma is not true. I would like to ask if $\dim G = \operatorname{codim} L$ still holds.
Comment: The Lemma does not hold for infinite cardinalities. For example, if $A$ is infinite, $|B|=1$ and $|C|=2$, then $|A|+|B| = |A| = |A|+|C|$ but $|B| \neq |C|$.
Answer: Thanks to this enlightening comment by Jochen, I have come up with below proof.

We need some results from Brezis' Functional Analysis, i.e.,

Theorem 2.10. Let $E$ be a Banach space. Assume that $G$ and $L$ are two closed linear subspaces such that $G+L$ is closed. Then there exists a constant $C \geq 0$ such that
$$
\left\{\begin{array}{l}
\text { every } z \in G+L \text { admits a decomposition of the form } \\
z=x+y \text { with } x \in G, y \in L,\|x\| \leq C\|z\| \text { and }\|y\| \leq C\|z\|
\end{array}\right.
$$
Definition. Let $G \subset E$ be a closed subspace of a Banach space $E$. A subspace $L \subset E$ is said to be a topological complement or simply a complement of $G$ if
(i) $L$ is closed,
(ii) $G \cap L=\{0\}$ and $G+L=E$.
We shall also say that $G$ and $L$ are complementary subspaces of $E$. If this holds, then every $z \in E$ may be uniquely written as $z=x+y$ with $x \in G$ and $y \in L$. It follows from Theorem 2.10 that the projection operators $z \mapsto x$ and $z \mapsto y$ are continuous linear operators. (That property could also serve as a definition of complementary subspaces.)

Let $\pi:E \to G$ be the continuous linear projection map defined in above paragraph. Then $\pi$ is surjective homomorphism such that $\ker \pi = L$. By first isomorphism theorem for groups,
$$
\operatorname{im} \pi \cong E / \ker \pi.
$$
It follows that $G \cong E/L$ and thus $\dim G = \dim (E/L) =: \operatorname{codim} L$.


Agent traning Failed

Question: Every time while saving training phrases for intent get following message.

Agent training failed
  Internal error occured: 3643ac92-3137-44a0-bb39-ab85ce4c9af0
Agent traning Failed
  Internal error occured :1013c13d-625b-4e84-811c-4ec57fd1854b

Any help would be appreciated.
Answer: I fixed the issue following the below approach:

Go to Google developer console(https://console.cloud.google.com)
Delete the maps project linked to our agent.

I am still curious about how this worked. Tried different things, but could not come to any conclusion. I guess that's the price I have to pay for using third party NLP service. I integrated maps prebuilt agent, and since then this behavior started appearing. Later removed the map project from the console, and it started working again.
I am curious to know if you have succeeded in resolving yours.

Agent traning Failed


When to move past POP3 servers, and what next?

Question: My company has ~40 employees, all using POP3 mail accounts on a shared host.  They allow up to 200 email boxes, have no limit on the # of outgoing/incoming e-mails/hour, and we've never had really big problems with them (plus, they're REALLY cheap).
However, we suspect that at some point before we reach the 200 email limit we'll need to upgrade ... but this is honestly just a baseless suspicion due to so many other companies our size using Exchange or other mail servers.  My question - how should we guage the right time to upgrade, and what should be our criteria for the next solution?
Answer: Consider your need for:

shared calendaring
shared meeting room/resources
shared contacts
Active Directory integration

If these features appeal to you, you may with to consider moving to an Exchange setup. You don't have to purchase/license Exchange and all the servers, however. There are a handful of good Exchange hosts out there that can really help your bottom line (if you pick the right one for your needs).
Shared/hosted Exchange means that you don't have to worry about:

uptime, 24/7 power and internet connectivity
spam filters
server performance(RAID, memory problems)

I've taken onboard the task of integrating Exchange into the SMB, and it's something that needs a bit of research and a good resource. It can be expensive (depending on your budget), and if it's not in your core competency, or I.T. isn't in your company's core competency, it'll be a challenge to convince the CFO/Controller to dish out the cash. You may have to prove out the benefits, or have the users complain loudly enough.
Run the Numbers!
Perhaps run the hosted Exchange scenario through a spreadsheet. Costs of purchasing and running inhouse vs. hosted. Run it for 2, 5 and 10 years. Remember to include your company's expected headcount in those time periods.
Keeping the POP3 Status Quo
If the users aren't screaming for the features of 'Outlook' like they had in their last job, and you can manage the above issues, then perhaps the move to Exchange isn't for your organization yet. Nothing wrong with that!
Comment: Out of curiosity, what is a typical per user cost for hosted exchange?  Shared calendaring and such is attractive, but not essential.  Our current cost is $50/month, meaning our per user cost is ~$1/month and dropping.
Comment: I've been hearing this company sponsor a few podcasts that I listen to, so I'll give them an unqualified plug: www.dnamail.com
Comment: Run the numbers. Always. Always. Always run the numbers. And don't just run your favorite numbers, run all the numbers... you're looking for total cost of ownership including admin time, not just short-term expenses.
Comment: Shared hosting typically runs from $10 to $30 per month depending on features.  Backup and support are key features to investigate.
Answer: Even if the answer is already excepted, I'd like to mention IMAP. I don't understand why people still use POP3 these days. I think nowadays most people work on more then one machine (e.g. at home and at work) or read their mails on a mobile device or via a webinterface. Keeping the mails on the server is a good idea when you want to access them from everywhere.
If you want IMAP support, a great webinterface, Calendar, InstantMessage and so on, you should definitely take a look at Google Apps. It's free for up to 50 users and cheap enough if you want more.
Comment: We looked at this, but "$50 / user account / year" doesn't exactly seem cheap.  We have 50-odd e-mail accounts for our ~40 users, which equates to $2500/year.  We currently pay 600/year for 200 e-mail addresses, and POP3 allows the users to keep mail on the server for a couple days.

Google's solution looks great, it's just not economical for us at this point.  Even Exchange seems cheaper ($700 license + bandwidth).
Comment: I still think it's cheap. If you pay your employees something between 30,000 and 100,000$ a year, you buy them a new 2000$ Laptop every two years and so on, 50$ are just a piece of cake.
Comment: Our employees would LOVE a new laptop every 2 years. Our newest laptop is almost 5 years old. Most employees are running on old Dell Optiplexs that we picked up for $100 apiece, with all licenses, on Craigslist ($2500 for 25 of them). For us, $50 is a HUGE deal.
Comment: I see, just wanted to mention it. Nevermind.
Answer: The time to consider moving is when you start getting pressure to support more features, or the same mailbox on multiple devices, such as a desktop AND a Blackberry. But if you're not getting pressure to move, then doing so proactively isn't required in my opinion.
Comment: Retain on server? Don't beat POP into thinking it's IMAP :(
Comment: Thanks - we've actually kludged together a solution with POP3 that allows full support for multiple devices ... most of our sales guys use Blackberry, a desktop, and a laptop.  Works surprisingly well.
Comment: @LuckyLindy Nice work!
Answer: Run the numbers and features on Open Source email solutions as well.  You don't have anything really integrated with a Microsoft ecosystem so you will not lose out.  They may not be the way you want to go or the integration features offered by an exchange solution might outweigh the benefits of OSS but you won't know until you look.
Check with you users regularly, see if there are complaints or issues starting to crop up or if people are beginning to feel limited by what you have.  Also take into account your technology strategy, what can you see people doing in 2 or 3 years?


Stationary solution to a inhomogeneous differential equation.

Question: Use the Transfer function to determine the stationary solution.
Given:
$$y'''(t) +4y''(t)+9y'+10y(t) = 2e^{-3t}\cos(t)$$
I have determined the transfer function to
$$H(s)=\frac{2}{s^{3}+4s^{2}+9s+10}$$
I have attempted to use the theory below to determine the stationary solution but without any success. I would appreciate some help to figure this out. What I have tried does not give me the correct solution.
Correct solution:
$$y_{p}(t)=-0.04615384615 \cdot e^{-3t} \cdot \cos(t) +0.1692307692 \cdot e^{-3t} \cdot \sin(t)$$
Answer: The right side of your equation is the real part of $2e^{(-3+i)t}$. The transfer function does not contain parts of the right side, it is just $H(s)=(s^3+4s^2+9s+10)^{-1}$, so that your solution is obtained as the real part of $2H(-3+i)e^{(-3+i)t}$. What remains is to compute the complex numbers in that expression, giving something like $\frac{2e^{(-3+i)t}}{-3+11i}$, then make the denominator real and read off the real part.
Comment: Thank you for explanation I finally it understand now ! Good day to you !


Playing tennis without ball boy. Any tips to avoid collecting the balls so often?

Question: I used to use all the balls that I have, only if there is no one playing at the area.
But if there are other people playing at the area, I don't want the balls mixed up with others, or stolen by their kids (it happens). So I'd use just 5 to 10 balls.
The fenced-in area is big enough (3 courts). With only 10 balls, collecting the balls is really burdening us.
If any of you have the same experience, what will you do to avoid collecting the balls so often?
Answer: One very simple solution - buy a set of balls in an uncommon colour. I have one set in neon orange - which I haven't seen anyone else use. Doesn't matter where they end up - I can see them.
If you can't do that - you could try initialling them with a Sharpie.
Golfers use marked balls - you can too.
Comment: http://www.jpricebath.co.uk/page5.html for coloured balls. Marked balls still show the mark for a couple of months in the summer, which is pretty useful.
Comment: Rory - what brand of neon orange balls are you playing with? It doesn't adversely affect visibility for you? Also, depending on when you mark the ball (new or after some use) it's likely to be gone after a while of hitting.
Comment: Ah, I'm guessing you live over there? (UK). Are you saying you play with the same balls for a couple of months at a time? I could never have a ball last me near that long. The maximum number of times I use the same balls is 2 times out (about 2-3 hours each time out). By then most of the fuzz is gone and they hardly bounce anything like new balls do. Typically I open up a new can every time I play.
Comment: I can understand marking may not work for you (I am a complete amateur when it comes to tennis :-) - there are places that sell coloured balls to the US, but they do all seem to ship from China. Visibility is fine on most courts I play on - mostly grass or dark all-weather surfaces. Haven't tried on clay - might be difficult against orange/red clay...
Answer: There really is no good answer for this. If you have options on where to play, I would say play at some courts that have decent dividers (screens, fencing, whatever) between courts. The only other thing I could recommend is if a ball is hit wide off the court to try and track it down and grab it then, instead of letting it go and potentially rolling even further away.
Most places I play at, if the ball from another court comes onto my court I hit it back to them to help out and vice-versa by them - it's kind of an unwritten rule/courtesy while you're playing. But I understand younger kids sometimes don't do this and don't even think to give you the ball back so it's tough.
By the way, are you playing sets or just rallying/practices/drilling ?
Comment: to be honest, I just realized that we ignore the balls coming to our court and vice-versa. I think that the unwritten rule/habit is a really good thing to start from ourselves :)
Answer: Try just using two or three balls max. It's an excellent exercise in consistency (which should be part of any practice session, unless you don't really care). After emphasizing not missing and safer shots for a while, you'll be great at just playing with one or two balls only.
Comment: Absolutely - even if you're playing a match you should only need 3-4 balls (a can's worth, right?).  Also, if you miss your first serve, make sure it goes over the net, otherwise you might have to go pick it up before your second serve (if it rolls back from the net) - guaranteed to put you off!
Answer: Hit with only slice. The balls won't run away as much. :D
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Parse XML with PHP for email returning the number 1

Question: I am using a scorm quiz that can export data to my server as xml. I am trying to parse that data so that I can use some of it to send in a php email. What I am trying right now returns the number 1 and I can't figure out how to make it work. Help?
<?php

$version = $_POST['v'];
$points = $_POST['sp'];
$passing_percent = $_POST['psp'];
$gained_score = $_POST['tp'];
$username = $_POST['sn'];
$email = $_POST['se'];
$quiz_title = $_POST['qt'];
$detailed_results_xml = $_POST['dr'];

$xml_string = <<<_XML
print "<?xml version="1.0" encoding="iso-8859-1"?>" . $detailed_results_xml;
_XML;

$xml = simplexml_load_string($xml_string);
$emailtest = print_r($xml);

mail("email@example.com",$quiz_title,$emailtest,"From: fromname <firstname.lastname@example.com>");

?>

If I email the $detailed_results_xml to myself it comes through like this:
<quizReport xmlns="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults  quizReport.xsd" version="1">
<quizSettings quizType="survey" timeLimit="0"/>

<variables>
  <variable name="USER_NAME" title="Name" value="mike"/>
  <variable name="USER_EMAIL" title="Email" value="firstname.lastname@example.com"/>
</variables>

  <questions>
     <fillInTheBlankSurveyQuestion id="{BE7284DD-B731-409B-9198-A782499EECA9}" status="answered">
      <direction>Exercise 1: Current Sleep Habits (Night 1)
    In this exercise, think about the last few nights of sleep. Write the amount of time you slept per night and rate the quality of your sleep on a scale of 1 to 5, with 1 being bad and 5 being great. This will give you snapshot of your current sleep habits.
    Example:
    Day of Week
    Sunday
    Time to Bed At Night
    11:30 pm
    Time in Bed Before As!
    leep (estimate)
    1 hour
    Time Awake in the Morning
    6:30 am
    Quality of Sleep (1 to 5)
    3
    Total Time Sleeping
    6 hours </direction>

    <text>
      <![CDATA[Day of Week]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time to Bed At Night]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time in Bed Before Asleep (estimate)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time Awake in the Morning]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Quality of Sleep (1 to 5)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Total Time Sleeping]]>
    </text>
    <blank userAnswer=""/>

</fillInTheBlankSurveyQuestion>
<fillInTheBlankSurveyQuestion id="{F52AC41C-C149-4B8D-9976-5F380B1A7851}" status="answered">
  <direction>Exercise 1: Current Sleep Habits (Night 2)
    In this exercise, think about the last few nights of sleep. Write the amount of time you slept per night and rate the quality of your sleep on a scale of 1 to 5, with 1 being bad and 5 being great. This will give you snapshot o!
    f your current sleep habits.
    Example:
    Day of Week
    Sunday!

    Time to Bed At Night
    11:30 pm
    Time in Bed Before Asleep (estimate)
    1 hour
    Time Awake in the Morning
    6:30 am
    Quality of Sleep (1 to 5)
    3
    Total Time Sleeping
    6 hours </direction>

    <text>
      <![CDATA[Day of Week]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time to Bed At Night]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time in Bed Before Asleep (estimate)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time Awake in the Morning]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Quality of Sleep (1 to 5)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Total Time Sleeping]]>
    </text>
    <blank userAnswer=""/>

</fillInTheBlankSurveyQuestion>
<fillInTheBlankSurveyQuestion id="{4F33A341-308C-493E-BF98-E13927064BC5}" status="answered">
  <direction>Exercise 1: Current Sleep Habits (Night 3)
    In this exercise, think about the last few nights of sleep. Write the amount of time you slept per night and rate the quality of your sleep on a scale of 1 to 5, with 1 !
    being bad and 5 being great. This will give you snapshot of your current sleep habits.
    Example:
    Day of Week
    Sunday
    Time to Bed At Night
    11:30 pm
    Time in Bed Before Asleep (estimate)
    1 hour
    Time Awake in the Morning
    6:30 am
    Quality of Sleep (1 to 5)
    3
    Total Time Sleeping
    6 hours </direction>

    <text>
      <![CDATA[Day of Week]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time to Bed At Night]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time in Bed Before Asleep (estimate)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time Awake in the Morning]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Quality of Sleep (1 to 5)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Total Time Sleeping]]>
    </text>
    <blank userAnswer=""/>

</fillInTheBlankSurveyQuestion>
<fillInTheBlankSurveyQuestion id="{324BFC55-6E6D-48EF-9B0F-341131988317}" status="answered">
  <direction>Exercise 1: Current Sleep Habits (Night 4)
    In this exercise, think about the last few nights!
    of sleep. Write the amount of time you slept per night and rate the qu!
    ality of your sleep on a scale of 1 to 5, with 1 being bad and 5 being great. This will give you snapshot of your current sleep habits.
    Example:
    Day of Week
    Sunday
    Time to Bed At Night
    11:30 pm
    Time in Bed Before Asleep (estimate)
    1 hour
    Time Awake in the Morning
    6:30 am
    Quality of Sleep (1 to 5)
    3
    Total Time Sleeping
    6 hours </direction>

    <text>
      <![CDATA[Day of Week]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time to Bed At Night]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time in Bed Before Asleep (estimate)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time Awake in the Morning]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Quality of Sleep (1 to 5)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Total Time Sleeping]]>
    </text>
    <blank userAnswer=""/>

</fillInTheBlankSurveyQuestion>
<fillInTheBlankSurveyQuestion id="{96C36841-A582-4059-A408-8D8EA0CC09E6}" status="answered">
  <direction>Exercise 1: Current Sleep Habits (Night 5)
    !
    In this exercise, think about the last few nights of sleep. Write the amount of time you slept per night and rate the quality of your sleep on a scale of 1 to 5, with 1 being bad and 5 being great. This will give you snapshot of your current sleep habits.
    Example:
    Day of Week
    Sunday
    Time to Bed At Night
    11:30 pm
    Time in Bed Before Asleep (estimate)
    1 hour
    Time Awake in the Morning
    6:30 am
    Quality of Sleep (1 to 5)
    3
    Total Time Sleeping
    6 hours </direction>

    <text>
      <![CDATA[Day of Week]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time to Bed At Night]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time in Bed Before Asleep (estimate)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Time Awake in the Morning]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Quality of Sleep (1 to 5)]]>
    </text>
    <blank userAnswer=""/>
    <text>
      <![CDATA[ Total Time Sleeping]]>
    </text>
    <blank userAnswer=""/>

</fillInTheBlankSurveyQuestion>
  <essayQuestion id="{C91C6866!-63A1-4BE5-84DD-1A0F8C34FB1F}" status="answered">
  <direction>Exercise 2:!
    Regulate the Body's Clock through Daily Routine
    Some people use a morning routine to help them wake up and a bedtime routine of relaxing activities to prepare their bodies for sleep. These activities of daily living act as "cues†to signal the brain to fall into biological rhythms.
    In this exercise, consider for a minute what you did last night before bed and what you've done so far today.
    Take a moment to describe your daily routine and activities starting with last night.
    Evening activities at work, school, community or home: </direction>
  <userAnswer>asdfasdf</userAnswer>
</essayQuestion>
  <essayQuestion id="{AFE522F8-6D34-4434-BC41-61E7121615FD}" status="answered">
  <direction>Relaxing activities before bedtime: </direction>
  <userAnswer>asdfsasdf</userAnswer>
</essayQuestion>
  <essayQuestion id="{50E422B5-7705-49D6-9CFC-CF1E97389D10}" status="answered">
  <direction>
  Sleep Routine (time to bed, personal care activities, medication, and time, if awoken): </direction>
  <userAnswer>asdfsdfads</userAnswer>
</essayQuestion>
   <essayQuestion id="{6DF65956-6976-446F-87DD-02CD0A88FA14}" status="answered">
  <direction>Wake up routine (time awake, personal care activities, medication time): </direction>
  <userAnswer>asdfdfasdf</userAnswer>
</essayQuestion>
  <essayQuestion id="{CF38A3C2-E538-41B1-92C1-15011126231D}" status="answered">
  <direction>Morning activities at work, school, community or home: </direction>
  <userAnswer>asdfdfasdf</userAnswer>
</essayQuestion>
  <essayQuestion id="{CAA971E7-4722-4900-9667-4CF7B283A95C}" status="answered">
  <direction>Afternoon activities at work, school, community or home: </direction>
  <userAnswer>asdfasdf</userAnswer>
</essayQuestion>
<essayQuestion id="{2A64580E-A99C-4525-8435-2C57ECCBCEFB}" status="answered">
  <direction>Exercise 3: Planning for Improvement
    In this brief exercise, you'll consider all that you've come to realize about your own habits and routine and take a moment to reflect on some small changes that might!
    benefit you.
    Use the space below to make a short list of small chang!
    es you can make to your own routine that might prevent sleep loss. As you're doing this, consider some of the following questions:
    What changes, if any, have I made in the past that have worked for me? </direction>
  <userAnswer>asdfsad</userAnswer>
</essayQuestion>
<essayQuestion id="{6EB6CCF7-045A-4E8B-AFA0-794F00FEB658}" status="answered">
  <direction>Are there some changes that have not worked? </direction>
  <userAnswer>asdfsasdf</userAnswer>
</essayQuestion>
<essayQuestion id="{99CBF95D-7427-4999-BF93-6D727D607B0A}" status="answered">
  <direction>A few small changes I can make to improve my sleep and health: </direction>
  <userAnswer>asdfsasdf</userAnswer>
</essayQuestion>
<essayQuestion id="{E3621400-19BD-4200-A8A2-DE6544EFAD65}" status="answered">
  <direction>If I make this change, how might it impact my life/Life Goals? </direction>
  <userAnswer>asdfasdfa</userAnswer>
</essayQuestion>

Sorry if the formatting got messed up on the xml bit but you should get the idea from it I think. So the xml bit is what gets generated by $detailed_results_xml and I need to parse some pieces of it to html to send in an email, but right now I am only seeing a number 1. Any help is greatly appreciated!
Comment: Was there something amiss?
Comment: Hello, I am having the same problem. How did you parsed the data?
Answer: print_r return 1 (as integer). You must pass a second boolean parameter for it to return a string.
the line is:
$emailtest = print_r($xml);

That is why you're getting 1 as the $message parameter for mail. And probably you are sending the wrong message (email() 3rd parameter), I think you wold want to:
mail("email@example.com", $quiz_title, $xml, "From: fromname <email@example.com>");

For parsing the XML there are many ways :
functions
object oriented


Binary to decimal conversion

Question: The binary number $1000111$ converted in decimal is equal to $71$ or to $-71$? The binary number has $1$ as the first left number so I thought it could mean that in decimal it is negative.
Also, the two's complement of $1000111$ is $0111001$. $0111001$ is equal to $57$ or $-57$?
I hope someone can clarify this for me.
Comment: "The binary number has 1 as the first left number so I thought it could mean that in decimal it is negative."  All numbers have a one as their first digit, not counting leading zeros, and obviously not counting zero (which has no value besides leading zeros).  So the idea that one represents negative is clearly false.  (What is true is that a leading one indicates a negative number if that one is in a specific location, such as the first spot of an 8-bit or 16-bit number, and if there is a convention that identifies that location should be treated like a sign bit.)
Answer: Without any assumptions, the number is $1000111_2 = 2^6+2^2+2^1+2^0 = 71$. If you wanted $-71$ it would just be $-1000111$. $1000111$ is no more negative than $99$.
That said, in practice we have a fixed number of bits we can use. Nevertheless this still doesn't tell you that $1000111$ is $-71$ because it could be an unsigned representation.
Additionally, there are other ways to represent negative numbers besides two's complement.
Finally, even if this were two's complement and this was the maximum number of bits available it still wouldn't be $-71$ since that's not how we interpret negative numbers in two's complement. If you want to know what the "negative" of this number is, you invert all the bits and add 1. So $-1$ in a four-bit representation would be $0001\rightarrow 1110 + 1 = 1111$. With this in mind, the arithmetic inverse of your number would be $0111000 + 1 = 111001_2 = 57$ as you indicate towards the end of your post. Therefore our original number $1000111$ in 7-bit two's complement is $-57$
Comment: Nice, covers everything.
Answer: "The binary number has  1 as the first left number so I thought it could mean that in decimal it is negative. "
Why would you think that?
We can make up any rules to for what the terms in a binary string mean that we want.  We can make the increasing powers of two be increasing right to left or left to right or interspersing in odd vs even places.
So it wouldn't surprise me if there is some programming convention that to represent negative numbers if the leftmost digit is $1$.  If heard of conventions where the the strings $00000000$ to $01111111$ represent the numbers $0$ to $127$ whereas $10000000$ to $11111111$ represent the numbers from $-128$ to $-1$.
I have never heard of a system where $01$ represents $1$ and $1$ represents $-1$ and $011$ represents $3$ while $11$ represent $-3$ and $01000111$ represents $71$ while $1000111 but such a system could exist and would be consistent.
But as far as MATHEMATICS goes, the rule is simply that the powers of $2$ increase for right to left and $1000111=01000111$ is $71$ and there is no way to represent negatives except with a negative sign.
So, what programming convention are you using.
Comment: The programming convention that you mention exists and is called "two's complement": https://en.wikipedia.org/wiki/Two%27s_complement
Comment: Not quite.  two's complement is a fixed length to would only be a 1 in the eighths (or furthest left of a fixed length) place that indicate negative and that would be the negative of the *complement* not the number.  That would be the system in my fourth paragraph.  I've never heard of the system in my fifth paragraph or as described by the OP and I doubt it exists.  I guess it couldn't because if 0 = off 1= on there is nothing for non-existant so 01x and 1x can never be distinguished.
Answer: The definition for converting a number from base 2 (binary) to base 10 (decimal) is as follows: We consider the string of $1$'s and $0$'s from $right$ to $left$. We start at the right most digit and apply the rule:
Let $a_n a_{n-1} ... a_2a_1$ represent the binary form of a decimal number $a$. Then we have to consider n cases.
Case 1: If $a_1 = 1$, then we count it as $2^0$. Otherwise if $a_1 = 0$, we count it as $0$.
Case 2: If $a_2 = 1$, then we count it as $2^1$. Otherwise if $a_1 = 0$, we count it as $0$.
In general,
Case n: If $a_n = 1$, then we count it as $2^{n-1}$. Otherwise if $a_1 = 0$, we count it as $0$.
Finally, we sum over all $n$ cases for the decimal conversion.
As per your example, $(1000111)_{2} = (2^{0} + 2^{1} + 2^{2} + 0 + 0 + 0 + 2^{6})_{10} = (71)_{10}$

Binary to decimal conversion


Why are duplicate rows not allowed in a relational database?

Question: In this introductory tutorial on JDBC and Relational Databases, it is stated,

Integrity Rules
Relational tables follow certain integrity rules to ensure that the
  data they contain stay accurate and are always accessible. First, the
  rows in a relational table should all be distinct. If there are
  duplicate rows, there can be problems resolving which of two possible
  selections is the correct one.

But if the rows are duplicate, it means all the fields in both the rows hold the same values; and when they are completely same (duplicate), how does the question of one being correct and the other being incorrect arise? How does the duplication of a row harm the data integrity?
Comment: When you have to change one of the values of the row, which row changes?  Why do you have duplicate rows in your table?  What does the duplication represent?
Comment: Pedantically, duplicates are a bad idea in an operational database (like an e-commerce store), but are fine in a data warehouse, both of which can use a relational database.
Answer: That is a kind of a philosophical question. But I think you might be putting too much into it. I would say that the problem is really "How does the data base know which row is the correct to fetch". In one of the first systems I set up, I messed with the keys and managed to get duplicate rows in the table. Then the problem was how to tell the db which rows to get rid of (20 years ago, using postgres 5.x I think). It does per se not harm the data integrety, but it harms "accurate and always accessible" as it is not possible to fetch just the one row that you need.
An example: if someone makes a person table like
create table person(
   name varchar not null,
   dateofbirth date not null,
   town varchar not null);

it is clear that you are going to get duplicate records sooner or later. I know that the first John Smith born 31.08.67 living in Oslo is my old class mate, whereas the second John Smith born 31.08.67 living in Oslo is the colleague I met first time a week ago. But I have no possibility to tell them from each other in the data base and I have no possibility to handle them separately. So if i later do a
alter table person add connection;

then I would not have any possibility to put the correct data into the database system.
Answer: The main reason could be:

Wastage of space for maintaining duplicate records which doesn't make sense.
Unnecessary wastage of memory space (main memory) when you select data in your application.
Normalization Constraint: if your table has duplicate records then it's not a normalized table at all.
If 2 record exists for a single person then it's really confusing cause there could be one more customer with same name, address etc. Example: Bank customer.

So if you don't define a way to distinctly identify the person then how will you say that the account X belongs to which person.
Answer: Data integrity, the question one would have to ask is why would two identical records be allowed in a table, for what purpose does that serve.
How would you know which record your talking about? Lets take identical twins for example, they may match in every way but their names, in this way we can identify to which person we are talking to.
duplication of rows breaks data integrity because it breaks the founding rules set up by RDBMS.
if duplication occurred, you would not be able to relate to a specific set of data, which is the stated objective of RDBMS as stated in your question post.
technically you can have multiple rows with the same data, the caveat is that you must include a primary key which differentiates your rows.
Hope this makes sense and helps


Javascript animated background not covering whole screen

Question: I have used javascript to create an animated background to my website https://coolio85.com
This is my HTML Code where the color shifting is meant to take place

<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="UTF-8">
<title>Welcome to coolio85.com</title>

This is the css to position the background to fit the full page
#gradient {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}

This is the java script code to use the DIV Id
$('#gradient').css({
    background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
    background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

There is a black bar from the solid background color that the background is originally set at the top of the screen.
Comment: as a side note you cannot animate linear-gradient like this
Comment: Hi. Did you try to set the height of the body to 100vh ?
Comment: @TemaniAfif Sorry i'm new to this. What do you mean by that?
Comment: i mean that linear gradient cannot be animated by changing color .. so if you expect an animation, it won't happen
Comment: ok i see your issue ... it's not with the animation, and i has nothing to do with gradient also
Comment: it's the margin of h1 collapsing with body ... use `h1{margin:0}`
Comment: Thank you so much that worked @TemaniAfif
Answer: As I said in a comment, you can do something like that :
body {
  height: 100vh;
}

#gradient {
  height: 100%;
}