Prove that a vector is in the span of a linearly independent set of vectors iff coefficients = 0

Question: Here is the question I have been given.
Let S = {~v1, ~v2, ~v3) be a set of three vectors in R4.  Assume S is
linearly independent. Show that there are numbers a,b,c,d so that

~x=[x1,x2,x3,x4] is in the Span of S
iff ax1+bx2+cx3+dx4=0

I know that because S is linearly independent, that means that the only solution to
 c1v1+c2v2+c3v3=~0 is if c1=c2=c3=0.

I am just wondering how I should apply this to the problem. It seems to simple to say that because S is linearly independent, and that if ~x spans S, then ~x must be a linear combination of S. I am not sure where to go from here.
The idea that I have is that because S is linearly independent, if ~x does span S, then the equation
c1~v1+c2~v2+c3~v3+c4~x=~0

must be true iff
c1=c2=c3=c4=0

Comment: Can't you simply use the definition of the span of $S$ as the set of all linear combinations of the vectors?
Answer: This question has a clean geometric interpretation. Consider the space $A$=span($S$). It is a $3$-dimensional subspace of $\mathbb{R}^4$. So the subspace orthogonal to $A$ is $1$-dimensional. Call it $P$ for perpendicular and suppose that it is spanned by the vector $p$. Now, it is "geometrically clear" that any vector orthogonal to $p$ is in $A$. That's the idea. And then you can take $$p=\begin{bmatrix}a\\b\\c\\d\end{bmatrix}$$.
Now, how do you find $p$ given $A$? Simple, since $p$ is orthogonal to every vector in $A$, in be in the null space of $A^T$.
Now you have your $a,b,c,d$ and I will leave it up to you to work through the IFF logic!
Answer: If $(a,b,c,d)$ are such that the conditions are satisfied, then we can note that because each $\tilde v_i$ is in the span of $S$, we should have
$$
a\,\tilde v_i(1) + b\,\tilde v_i(2) + c\, \tilde v_i(3) + d\,\tilde v_i(4) = 0 \quad i = 1,2,3
$$
where $\tilde v_i(j)$ denotes the $j$th entry of the vector $\tilde v_i$.  This gives us a system of equations on $(a,b,c,d)$.  In particular, we have $Vy = 0$ where $y$ is the column vector $y = (a,b,c,d)$ and $V$ is the matrix whose rows are the vectors $\tilde v_i$.
Note that $V$ is a matrix with $3$ linearly independent rows, so there must exist a non-zero element $y$ of its nullspace.
Now, for such non-zero $y = (a,b,c,d)$, we want to show that the set of solutions of
$$
ax_1 + bx_2 + cx_3 + dx_4 = 0
$$
contains the entire $3$-dimensional subspace spanned by $S$, and nothing more.  To do so, it suffices to show that the nullspace of the (row-)matrix $[a\;b\;c\;d]$ (i.e. the solution space to the above equation) is $3$-dimensional; we already know that it contains the vectors $v_i$.


Boostrap 4 spacing for mobile

Question: Bootstrap has spacing classes such as m-sm-1 and m-md-1. It seems that it has for mobiles also as its written in its documentation: Spacing utilities that apply to all breakpoints, from xs to xl. However, m-xs-* does not work. I could not find such a class in its source-code too
Does bootstrap 4 have spacing utility classes for mobiles?   How can I apply mt-xs-2 on a button ?
Answer: The -xs- variant was removed in Bootstrap 4 everywhere.  For most utility classes (as well as the Grid) behavior is as follows:

class-*
class-sm-*
class-md-*
class-lg-*

So for the Margin utility class you could do something like:

Hi!

At the smallest breakpoint m-1 would apply and it would work its way up from there.  You can learn more about this from the very same link in your original post:
https://getbootstrap.com/docs/4.0/utilities/spacing/

The classes are named using the format {property}{sides}-{size} for xs
  and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.
Comment: @mahan - There is no such thing as 'mobile only'.  `m-1` applies to the smallest breakpoint (mobile) *and up* unless a larger breakpoint (ex: `m-md-1`) exists.
Comment: I have used `mt-3` together with  `mt-sm-0` and it seems that the element has `margin-top` on mobiles only.
Comment: Thanks for the answer. But I want for mobile only

Boostrap 4 spacing for mobile


Use results from two-sample Kolmogorov-Smirnov to compare methods

Question: Let say I observe a phenomenon an I get its PDF. Then I come up with two models to simulate this phenomenon. From these models, I can get a PDF and I want to know which model is better.
I am not interested in the $Q_2$ of the model. Here the objective is to get the PDF to assess threashold exceeding or to see how the phenomenon responds to uncertainties for instance. Maybe there is a bi-modal structure, particular values with particular level of probabilities, etc. This is for exploratory so no particular quantile is targeted and thus I need the PDF from the model which represents best the PDF from the real observations.
So let's say I have:

One sample from observation giving PDF1,
One sample from the first model giving PDF2,
One sample from the second model giving PDF3.

I am not a statistician, so from my findings I have to use a Kolmogorov-Smirnov test to assess if two PDFs can be considered "equal".
Thus, I compute two-sample Kolmogorov-Smirnov test with PDF1 vs PDF2 giving pvalue1 and from PDF1 vs PDF3 giving pvalue2.
Can I compare the two pvalues? If pvalue1 < pvalue2, can I say that the first model is better?
Or maybe this approach is wrong, so how to tell which model is better at getting the PDF (only the PDF, I know about Q2 and this is not what I am looking for)?
Comment: @Y0da whuber was not being rude, but rather trying to help you solve your problem. You have posted a question in the form of an [XY problem](https://meta.stackexchange.com/a/66378/202463) (see also [wikipedia](https://en.wikipedia.org/wiki/XY_problem)) - asking about an attempted solution to a problem (simulating and using two sample KS tests) rather than explaining the problem itself. Your attempted approach is clearly unsuitable but you don't explain your underlying situation clearly enough to really offer good advice about what you should do instead..
Comment: Search first, though, as whuber advised way back near the start of these comments.
Comment: What would the two samples be?  So far your description implies only one sample: namely, your observations.
Comment: @whuber there is the observation and then using each model you have new predictions. Is that clear?
Comment: Yes, but why are you going about it this way?  The one-sample K-S test specifically compares a sample to a distribution: there's no need to generate a new artificial "sample" to run the test.  Your basic problem is that when you generate a model from data, it's not valid to test the model against the same data: the logic is circular and, even though you can carry out the K-S calculations, its p-value won't be meaningful.  If you're concerned about predictive validity, then the K-S test is practically irrelevant anyway.
Comment: @whuber I am using the two sided test because I just have samples from the observation. My understanding is that the one sample KS requires a distribution and some sample. Here I have two sets of sample. Hence the two sided test. The goal of all this is to find which model is better at finding the observed PDF. So I thought that comparing pvalues could do this.
Comment: We seem to be going back and forth.  As far as I can tell, you have never described more than one actual sample: everything else comes from some model you have created.  There's no need to sample from a model in order to compare it to data.  Rather than insisting on this approach, you would be better off abandoning it and changing your question so that it formulates a clear objective, describes the information you have, and asks how to achieve that objective.  You will likely discover that our site has a great many threads about model selection and comparison, so consider searching.
Comment: @whuber why being so rude!? It is not because I am not using the right wording and that you do not get what I à asking that you can bully. And your reputation here does not give you this right either. So going back to the question. I have two different surrogate models trying to predict some physics and the objective is to compute the PDF. So I do not care here about the predictivity coefficient Q2. So now, how to say that model A is better than model B to get the PDF. Given that I have the budget to get the empirical PDF by doing a large sampling.
Comment: I am sorry you find this exchange rude--I'm only trying to assist you in formulating an effective question.  Of course I'm not fully understanding, but that's a sign many others who might be in a position to help you might fail to understand or even misunderstand what you're after. You're certainly welcome to keep your question up, but my impression is that in its present form it's not likely to get answers that truly help, and the comments haven't clarified much.
Comment: @Glen_b I am not a statistician at all. From my search, I found that KS test would be the way to assess if two PDFs can be considered equal. Maybe this is not the correct approach, but I just don't know why. As I said in my last comment to whuber, I want to tell which model give me the best PDF.
Comment: Thanks for your efforts, you're getting closer to an answerable question that has a hope of giving you useful advice, but a little more is needed. "Best" is not defined yet. If you don't have an operational definition of 'best' for your problem (essentially, an algebraic formula or something from which one could be derived) - and I suggest you don't attempt one - you'll require advice about what might at least do fairly well in your circumstances. The problem is we shouldn't be suggesting any if we don't have a good understanding of what you'll be doing with it (i.e. without the circumstances)
Comment: @Glen_b I do not have any more context than comparing two surrogate model's  capabilities to recover a PDF. Best here means that on overall the PDF from one surrogate would be closer than with the other surrogate. So there is no particular focus on some specific quantiles.
Comment: 1. What's the point in estimating a pdf? It's not normally a goal in and of itself -- after you estimate a pdf, you're using that estimated pdf to do *something*, right? It's *that* that you should seek to do well at. 2. Closer measured *how*? With two values there's an infinite number of ways to define a distance between them.  But these are two *functions*. You're simply substituting one undefined term (closer) for another (best).
Comment: @Glen_b the goal is the PDF. In risk analysis for instance, they are interested in the probability to exceed a threashold. And sometimes you just do not have any threashold but you are interested to know how the system responds (uncertainty quantification). I am in this framework. I need to have a mean to compare the ability of a surrogate to retrieve the PDF.
Comment: It would be a good idea to put your most recent comment in the question.  "The probability to exceed a threshold" is certainly a goal. One way to get it is to try to identify a pdf, but it's often not the best way to achieve that goal  (in part it depends on how far into the tail the threshold is). If I were nevertheless going to try to identify a pdf for that purpose, I probably wouldn't be  using K-S distance but something that would do better in the tail. Then, if you were nevertheless to use KS distance anyway, you don't do it the way you were trying to do it (as whuber explained). ...ctd
Comment: ctd... You can also get a good idea how a system behaves without identifying a distributional form for data, since you have the ECDF itself
Comment: @Glen_b thanks I updated the question. But I do not understand how a can use the one sided KS here. Or maybe I just do not get the real difference between these two tests.
Comment: It's not the *one sided* version of the KS test that's at issue, it's the *one sample* version. But you can't use it directly if you're estimating parameters
Comment: @Glen_b That's my understanding and this is why I wanted to use the two-sample version. So is this correct?
Comment: No, the two-sample version has *exactly* the same problem (it's wrong if you do parameter estimation), plus it has a number of additional issues. It's worse than doing the one-sample test which is already wrong.  I think there's now enough here for the question to be more or less answerable, but most of the issues here are addressed in other questions already on site.
Comment: @Glen_b OK... I really do not get this then. Thanks for your time. Any advice then about the way I should compare my models?
Comment: Now that's a good question to ask -- and a reasonable answer is too long for a comment. Why not post that one? You can leave this one if you like; I'll try to turn my comments into an answer here.
Comment: @Glen_b OK I will do this and let you know when the question is out thanks.
Comment: @Glen_b indeed I see this one https://stats.stackexchange.com/q/25923/140570
Comment: It doesn't have an answer though. If you have tried a number of searches but can't find any answers, you can post it.
Answer: A two-sample Kolmogorov-Smirnov test comparing data to values simulated from a model is not a good way to see whether a distributional model fits the data.
In the case where you have not estimated any parameters, it's simply a much less efficient way of doing a one-sample K-S test. You can improve its efficiency by drawing a larger simulation sample. As the sample size goes to infinity, guess what you end up with? The one-sample K-S test!
Neither test is suitable (as is) if you estimate parameters, though.
One of the things you're after is to be able to estimate the probability to exceed a threshold. One way to get it is to try to identify a pdf, but it's often not the best way to achieve that goal  (in part it depends on how far into the tail the threshold is). If the thresholds are near the middle, you may, for example, be better to estimate these directly from the data.
if those threshholds are not mostly near the middle, it may make sense try to identify a pdf for that purpose, but then I probably wouldn't be using K-S distance to assess fit, but something that would do better in the tail.
(You can also get a good idea how a system behaves without identifying a distributional form for data, since you have the ECDF itself)
However; if you need information about the extreme tail (beyond almost all the data) then the data isn't much use; you need some assumptions as well.
Now lastly, none of this is necessarily of the greatest use for deciding between two competing models.
Comment: The last question (which you added yesterday) makes this question overly broad. If you deny any specific purpose and offer no explicit loss function there's not much to say (other than "when you have a loss function, minimize it"). This issue was explained in comments. I have given examples of the sort of considerations that come into designing a loss function for some purpose. If you want to use KS distance as a loss you can do so but (besides it appearing to be arbitrarily chosen), the problem is you cannot reasonably compare models with different numbers of parameters that way. ... ctd
Comment: Some points, but this answer does not answer the last question. If this method is not good, what to use? As I explained I really want the PDF. I want to know which model of my creation will be better at estimating the PDF (and when I have the model, I can create an near to infinite sample). This is for exploratory reason. Threashold exceeding is just an example and prior to getting the PDF, we just don't know what we want to do with the problem.
Comment: ctd... You might try out of sample loss (via cross validation perhaps); this would make particularly good sense if your problems in the future were mostly predictive in nature
Comment: that is the whole point of my question. Is this valid to use KS as a metric. From what you say now the answer is yes although you say this metric would be arbitrary (I just do not understand what are the parameters). But this is true for all metrics, all are arbitrary chosen. In this case I wanted to know if the community had came up with a standard way of doing this or not as I did not find it in the literature. Again, in uncertainty propagation you want the whole PDF and this is the final result. So if you are able to compare your model with a database you want a metric for that.
Comment: No, not all metrics are arbitrary; if they're chosen to suit what you're doing they're not arbitrary. There are a variety of ways people use to choose between competing distribution choices -- many questions on site relate to this.
Comment: I guess I will leave this here... you guys are playing with words and I explained several times in different ways my problem. I spoke with leading experts in uncertainty analysis today and they understood right away the issue and did not see fundamental objections with this method. So thanks anyway for your time. I guess this community is really not for me as you guys just speaks with each other's and want to answer your questions and not mines... Just a tired guy speaking


An equation for Fibonacci numbers

Question: Let $F(n)$ be $n$-th Fibonacci-number. Then the following holds:
$$F(n)^2+F(n+1)^2=F(2n+1).$$
I have proved, but I want a brief proof.
Do you know anything about it?
Comment: I hardly believe there's a shorter proof than induction on this, basically because I don't think this can follow by a combinatorial argument
Answer: I can do a pretty neat proof ... though it does require a bit of set-up.
In particular, it's easily proven by relating the Fibonacci numbers to the following problem:

Suppose that you want to go up some flight of stairs and at every step you can take either one or two stairs: in how many ways can you get up the stairs?

Well, if we say that there are $n$ stairs, then it turns out there are $F_{n+1}$ ways to do it.
A very easy inductive proof shows why:
Base cases: If there is $1$ stairs, you can do it in only $1$ way, and indeed $F_{1+1}=F_2=1$.  If there are $2$ stairs, then there are two ways: either take two steps of $1$, or take one step of $2$. And indeed, $F_{2+1}=F_3=2$
Inductive step: Say you have $n >2$ stairs. For your first step you can either go one up or two stairs up. By inductive hypothesis, there are $F_{n}$ ways to finish climbing the $n-1$ stairs after having taken a step of $1$ stairs, and there are $F_{n-1}$ ways to finish climbing the $n-2$ stairs after having taken a step of $2$ stairs. So, there are $F_{n}+F_{n-1}=F_{n+1}$ ways to climb $n$ stairs.
OK, so now that we have made a connection between the Fibonacci numbers and the number of ways to climb stairs in this way, we can prove your desired result very quickly:
Let's climb $2n$ stairs. We now know we can do this in $F_{2n+1}$ ways. But note that there are two different possibilities for us climbing those $2n$ stairs: The first way is that we climb the stairs and that at some point we will have climbed exactly $n$ stairs. If this happens, then there are $F_{n+1}$ ways to climb the first $n$ stairs, and also $F_{n+1}$ ways to climb the other $n$ stairs. The second way is that at some point we will have climbed exactly $n-1$ stairs, which can be done in $F_{n}$ ways, after which we take a step of $2$ stairs, and then finish climbing the remaining $n-1$ stairs,  which can be done in $F_{n}$ ways. So, it must be true that:
$$F_{2n+1} = F_{n+1} \cdot F_{n+1} + F_{n} \cdot F_{n}$$
Comment: Great proof! Minor correction: "We now know we can do this in $F_{2n+1}$ ways"
Comment: Thank you so much. I think this proof is very wonderful and interesting!!
Comment: @RayMIZUSAWA I'm glad you like it! Yeah, it makes you wonder what other results involving Fibonacci numbers can be quickly proven with this conceptual connection. :)
Comment: @Jonathan Glad you like the proof. Thanks for pointing out the typo!
Comment: HCP16 should read this :)
Comment: @ama Well, I still used induction to make the connection ...  But yes, the induction for that was trivial, while trying to apply induction directly to this problem (as the OP presumably did) would be more laborious.
Answer: My favorite Fibonacci technique is
the matrix formulation, which is well worth knowing and easily proved:
$$
A^n=
\begin{pmatrix}1&1\\1&0\end{pmatrix}^n=
\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix}
$$
Therefore,
$$
\begin{pmatrix}F_{2n+1}&F_{2n}\\F_{2n}&F_{2n-1}\end{pmatrix}
=A^{2n}
=(A^n)^2
=\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix}^2
=\begin{pmatrix}F_n^2+F_{n+1}^2&*\\*&*\end{pmatrix}
$$
The omitted terms give other identities,
such as $F_{2n} = (F_{n-1}+F_{n+1})F_n$.
Comment: That also sounds good!! Thanks for answering.

An equation for Fibonacci numbers


How can I use Ultimate Guitar tabs for backing

Question: I would like to record a song with tabs I find in ultimate guitar. It export tabs as GP5, but no midi files.
I want to record my guitar playing, but use drums/bass automatically generated via DAW.
I have Garageband and Ableton Live. Do I need guitar pro? Can it record guitar? Or is there a way to make Garageband ot Ableton read GP5?
Comment: Do the GP5 files contain accompaniment information? Is there notes for drums and bass, or guitar only? Do you need the computer to generate backing tracks that go together with a given guitar tab?
Comment: There are notes for all. I need computer to generate audio for given notes for drums ans bass.
Answer: According to the video "How to Import A Guitar Pro File into MuseScore" by Traveling Guitarist (below), you can just drag and drop a GP5 file into the MuseScore UI. This is demonstrated in the video.
From there, MuseScore allows for saving as a MIDI file. Just select File -> Export... and then choose MIDI from the selection of file types.


How to call a function when bytes of an array changes?

Question: If have a very large array, Arr [255]. I'm writing a function which should perform a task whenever any one or more byte in this array has been updated by other functions. Could you help me with the best possible method?
For any change in first 3 bytes of Arr, I can call the function Task() like the following.
int main (void)
{
   while (1)
   {
       CheckArrayUpdated ();
   }
}

void CheckArrayUpdated (void)
{
    static char ArrPre [3];

    if (
       (ArrPre [0] != Arr [0]) ||
       (ArrPre [1] != Arr [1]) ||
       (ArrPre [2] != Arr [2])
       )
    {
        Task ();

        ArrPre [0] = Arr [0];
        ArrPre [1] = Arr [1];
        ArrPre [2] = Arr [2];
    }
    else;
}

How can I do this for the entire array, without consuming much of processing time and increasing the length and size of code?
Comment: Can you modify `Task()` to return a list of changed indexes?
Comment: Hi Jongware, I have no idea which index of the array is getting changed.
Answer: Don't access the array directly but use getters/setters:
static char arr[255];

char read_arr(int index) {
    return arr[index];
}

void write_arr(int index, char value) {
    if (arr[index] != value) {
        Task();
        arr[index] = value;
    }
}

The change is detected as soon as a new (different) value is written to the array, and the Task() can be executed immediately. You don't have to check the whole array periodically anymore.
Comment: Hi dlask, I've no clue where this array is getting written. All I have is an array whose bytes are getting changed frequently
Comment: What's your actual environment? A microcontroller program where the array content is modified from interrupt handlers? A multithreading application? What exactly?
Comment: Yes, a microcontroller project in which array content is modified after an interrupt occurs and is written in a seperate .c file. Since I don't know too much about the coding of that particular file, I don't want to disturb that part of the code where the array is getting modified.
Comment: Then you have to use your original approach with a copy of the array. Just the change detection can be simplified in this way: `memcmp(ArrPre, Arr, sizeof(Arr))`. This function returns zero when both arrays are identical, and it returns non-zero if there is a difference.
Comment: Yeah, 'memcmp'. That was really helpful. Lemme check if my compiler support the function. Thanks alot dlask :-)


Fleming's "right-hand rule" and cross-product of two vectors

Question: I have been throwing around hand gestures for the past hour in a feeble attempt at trying to solve this question involving a cross product of two vectors $a$ x $b$. So far, I haven't found any satisfactory explanation on the internet as to how this rule is supposed to help me find out whether the components of $a$ and $b$ are positive, negative or zero. E.g., James Stewart explains it as though it is obvious (it isn't):

If the fingers of your right hand curl through the angle $\theta$ from $a$ to $b$, then your thumb points in the direction of $n$

What does he mean by "curl"? Sorry if this is a dumb question but I am getting really frustrated trying to use this "rule" to solve what is seemingly a really elementary question. I imagine it would be more intuitive if someone could just "show" me how to do it, but since that is not possible, if anyone could offer an explanation that is more helpful than the above, I would appreciate it.
(This question is specifically in reference to Exercise #4, Chapter 9.4 in Stewart's Single-variable calculus book, 4th edition.)

The figure shows a vector a in the xy-plane and a vector $b$ in the direction of $k$. Their lengths are $||a|| = 3$ and $||b|| = 2$.
     a) find $||a$ x $b||$
     b) Use the right-hand rule to decide whether the components of a x b are positive,         negative or zero

I am stuck on part b).
Comment: Have you tried searching for some videos on this? E.g. at [youtube](http://www.youtube.com/results?search_query=cross+product+hand+rule).
Comment: Think of the natural way your right hand would move when you want to slap someone. That's also the way fingers of your right hand curl. Sorry if this is a dumb answer.
Comment: The RHR is supposed to help you visualize the result of a cross product. I don't see how cross products are relevant to finding out "whether the components of $a$ and $b$ are positive, negative or zero." You also refer to "this question" but don't tell us what it is.
Comment: I guess I am not understanding what it means in terms of the angle. What does it mean to "curl through an angle"?
Comment: I am sorry, I guess your confusion is really a reflection of my own in that I don't have any clue how this rule is supposed to help me solve this question. I will post the question, but I don't know how to include the actual graph... hopefully it will still help.
Answer: You're supposed to curl your hand like so:
$\hskip 1.3in$
Your knuckles are supposed to form an angle while your fingers are otherwise straight, and your knuckles themselves point in the direction of $a$ while your fingertips point in the direction of $b$.
Using this, part (b) presumably wants you to use RHR to figure out which of the 8 octants $\vec{n}$ lies in (or between!), which would determine the sign of the components. I can't say much without seeing the picture of $a$ and $b$ though...

Update (sorry, MSPaint...):
$\hskip 1in$
I assume $a$ is on the $xy$ plane, so your thumb is too. This implies $z=0$. Moreover, the thumb is still close enough to the positively oriented $x$-ray (haha, pun) that it has positive $x$ component, but far enough from the positively oriented $y$-ray to have negative $y$ component.
Comment: @Dylan: Visually the $x$-axis has a positive ray and a negative ray; same with the $y$-axis. Between the two rays is a perpendicular plane (namely, the $yz$ plane between the $x$-rays and the $xz$-plane between the $y$-rays). Which side of these planes a vector is on determines whether its component is positive or negative (and if it is actually *on* the plane, it has component $0$). Remember we're trying to analyze $a\times b$, which is the thumb. The thumb is closer to the negative $y$-ray (not actually shown) than the positive one, and we're not investigating $a$'s components.
Comment: After your explanation, it is much clearer now. Thank you.
Comment: Added an image above. I understand the explanation, but I don't understand how it relates exactly to the graph (i.e. how to position my hand, how it lines up with a and b vectors).
Comment: @Dylan: I've updated my answer.
Comment: I think I am getting closer... I see now how to orient my thumb with respect to a given vector. However, I am not sure I understand your explanation of positive versus zero versus negative. When you say "it's close enough to be positively oriented $x$-ray[...]", what does that mean precisely? Because, visually speaking, vector $a$ looks much closer to $y$ in terms of the angle between them than it is to $x$.
Comment: Deserves a (+10) but I can only give (+1).


Second class is throwing Null Pointer exception for TestNG

Question: I've created different classes for each webpage using TestNG. My first class is working fine but the second class is throwing Null Pointer Exception. The same script if I combine in only one class It's working without any issues.
Below is my baseclass
package Test;
import org.testng.annotations.Test;
import Pages.FM_login;
import org.testng.annotations.BeforeTest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
public class Baseclass {
  WebDriver driver;
  FM_login  objLogin;
  @BeforeTest
  public void setup() {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\****\\Downloads\\chromedriver.exe");
        String url = "http://vatlookup.cloudfront.net";
          driver = new ChromeDriver();
          driver.manage().window().maximize();
          driver.get(url);
          driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
          String Title = driver.getTitle();
          System.out.println(Title);
          System.out.println("Application Launch successful");
          // Accept the cookie policy
          driver.findElement(By.xpath("//a[@class='cc-btn cc-allow']")).click();
  }
  @Test
  public void Login() {
      objLogin = new FM_login(driver);
      objLogin.GoToLoginScreen();
      objLogin.loginToFleetMatch("abc", "123");
      System.out.println("Login Successful");
  }
 @AfterTest(enabled=false)
  public void teardown() {
      driver.close();
}

This is another class
package Test;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

import Pages.FM_Profile;

public class Profile {
    WebDriver driver;
    FM_Profile objProfile;

     @Test
      public void Skip_Tutorial() {
          objProfile = new FM_Profile(driver);
          driver.getCurrentUrl();
          objProfile.SkipTutorial();
      }

      @Test(enabled=false)
      public void edit_profile() {
          objProfile.edit_profile();
      }
}

below is the page object for a second class
package Pages;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class FM_Profile {

    WebDriver driver;
    By company_name = By.xpath("//p[@id='company-name']");
    By plan_details = By.xpath("//p[@id='current-plan']");
    By End_tour = By.xpath("//button[@class='driver-close-btn']");
    By edit_profile = By.xpath("//span[contains(text(),'Edit')]");
    By Description = By.xpath("//textarea[@id='mat-input-10']");
    By Upload_image = By.xpath("//div[@class='upload-btn continental-book ng-star-inserted']");
    By Save_profile = By.xpath("//button[@class='save-btn continental-book mat-stroked-button mat-button-base mat-primary editMode cdk-focused cdk-mouse-focused']");

    public FM_Profile(WebDriver driver) {
        this.driver = driver;
    }

    public void SkipTutorial() {
        driver.findElement(End_tour).click();
    }

after executing it's showing java.lang.NullPointerException for second class
error
java.lang.NullPointerException
    at Test.Profile.Skip_Tutorial(Profile.java:16)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:135)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
    at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
    at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
    at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:821)
    at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:588)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
    at org.testng.SuiteRunner.run(SuiteRunner.java:286)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1214)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1136)
    at org.testng.TestNG.runSuites(TestNG.java:1066)
    at org.testng.TestNG.run(TestNG.java:1034)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Comment: Unrelated, yet important: you should follow the Java Naming Conventions: variabele names and method names should be written in camelCase and class names in PascalCase.
Answer: In your Profile class the driver object is not initialized. The driver object that you are initializing is in BaseClass and instance of that class. You need to initialize driver object in Profile class as well
Answer: WebDriver is never initialised.
WebDriver driver = new WebDriver();
Comment: It's showing error, I've given WebDriver driver = new ChromeDriver();

org.testng.TestNGException:
Cannot instantiate class Test.Profile


OSX chown problems after creating users with dscl

Question: Alright, so I've made a user and a group using dscl as follows:
dscl . -create /Users/deadline
dscl . -create /Groups/deadline
dscl . -append /Groups/deadline GroupMembership deadline

Now I'm trying to chown things like so:
mkdir /tmp/stuff
chown deadline:deadline /tmp/stuff

But the problem is that it sets the user and group to nobody instead of this user 'deadline'. What magic voodoo property do I need to add to the user and group to have it set the unix permissions properly?
Also, why must Apple hate me and my Unix background :(
Answer: You created the user record, but didn't give it any settings so it's using defaults.
sudo dscl . -append /Groups/deadline PrimaryGroupID 100
sudo dscl . -append /Users/deadline UniqueID 1000 PrimaryGroupID 100

You might want to look at the output of things like:
dscl . -read /Users/$USER
dscl . -read /Groups/admin

to see what attributes can be set.
Answer: Actually, you'd run into more-or-less the same problem on any unix system: you haven't assigned user & group IDs to the new user & group, so there's no way to identify their files.  Solution: assign IDs.  See this previous question, especially palmer's and my answers; if you put them together, it's a fairly complete process for creating a new user (although it's standard to make new users on OS X have a PrimaryGroupID of 20 [staff] instead of 80 [admin]).
Groups are fairly similar, but their PrimaryGroupID should be uniquely generated (and they don't need UserShell, UniqueID, NFSHomeDirectory, or a password.
Adding users to groups is also a bit more complicated than you're used to.  To do it properly, you should both add the user's RecordName to the group's GroupMembership list AND add the user's GeneratedUID to the group's GroupMembers list.  Doing this with dscl is a pain, but you can do it easily with:
dseditgroup -o edit -a username -t user groupname

(Note: dseditgroup can also create groups, but I don't think it's particularly easier than dscl.)
Comment: Excellent info Gordon. Thanks for the dseditgroup suggestion, I wouldn't have found that on my own.


JSON Data loading Issue local storing

Question: I'm trying to make an incremental game for learning purposes, and I'm facing a problem when saving users data locally.
For example, when I click on a button, it saves the value from the var "Food" :
localStorage.setItem("food",JSON.stringify(food));

And another button to load the save, linked to this function :
function loadFood() {

document.getElementById("food").innerHTML = JSON.parse(localStorage.getItem("food"));

}

However, my value Food is changing only when I press on the button. The value changes for like 1 second and then it goes back to 0.
Is there any way to fix this?
Comment: it looks like you have your 'loadfood' LHS and RHS of the `=` around the wrong way.. im assuming you want to assign the getItem('food') value into the element.. so just switch the order and you should be set
Comment: Why are you going to store JSON at first place?
Comment: Is `localStorage.getItem('food')` set somewhere else? Also, if you want to observe the value of `food`, you should use `console.log(localStorage.getItem('food'))` and see it in developer console (right click, Inspect Element).
Comment: The fact that the value changes back to zero suggests to me that you are executing code where you aren't expecting it (for example initializing food to 0 even after having set it to something else.  Without more code, this is difficult to diagnose.
Comment: Thank you all for answering. I've kinda solved the problem : It shows me now the right value, and it stays. But when I press on another button used to add 1 food each time I click, its starting from 0 again, its not taking care of the number saved :/
Answer: JSON.parse(localStorage.getItem("food")) = document.getElementById("food").innerHTML;

Should be this -
 document.getElementById("food").innerHTML = JSON.parse(localStorage.getItem("food"));

Comment: Just checked my code, I wrote it this way , idk why I switched when I asked here :o anyway, the problem is still present :/
Comment: Try to print JSON.parse(localStorage.getItem("food")) like this -- console.log(JSON.parse(localStorage.getItem("food"))); and see if it actually has a value in it? and are you sure localstorage is supported in your browser?
Comment: It shows me a value in the console and at the same time Undefined in my web page , and I'm on the last version of Chrome it shouldnt be a problem :o

JSON Data loading Issue local storing


The free-space Green's function for the Stokes flow

Question:
The Green's functions of Stokes flow
  represent solutions of the continuity
  equation $\nabla\cdot {\bf u}=0$ and the
  singularly forced Stokes equation
  $$-\nabla P+\mu
\nabla^2{\bf u}+{\bf g}\delta({\bf x-x_0})=0 \tag{*}$$
where ${\bf g}$ is an arbitrary constant,
  ${\bf x_0}$ is an arbitrary point, and
  $\delta$ is the three-dimensional
  delta function. Introducing the Green's function ${\bf G}$, we write the solution  of (*)
  in the form
  $$u_i({\bf x})=\frac{1}{8\pi\mu}G_{ij}({\bf x,x_0})g_j$$

The following is how to find $G_{ij}$ in the free-space infinite unbounded flow from C. POZRIKIDIS's Boundary Integral and Singularity Methods for Linearized Viscous Flow
Replace the delta function with
$$
\delta(\hat{x})=-\frac{1}{4\pi}\nabla^2\left(\frac{1}{r}\right) \tag{1}
$$
where $r=|\hat{x}|$, $\hat{x}=x-x_0$. Recalling that the pressure is a harmonic function, and balancing the dimensions of the pressure term with those of the delta function in (1), we set
$$
P=-\frac{1}{4\pi}g\cdot\nabla\left(\frac{1}{r}\right) \tag{2}
$$
Substituting (1) and (2) into (*) we obtain
$$
\mu\nabla^2 u=-\frac{1}{4\pi}g\cdot(\nabla\nabla-I\nabla^2)\left(\frac{1}{r}\right)\tag{3}
$$
Next, we express the velocity in terms of a scalar function $H$ as
$$
u=\frac{1}{\mu}g\cdot(\nabla\nabla-I\nabla^2)H \tag{4}
$$
It will be noted that the continuity equation is satisfied for any choice of $H$. Substituting (4) into (3) and discarding the arbitrary constant vector g we obtain
$$
(\nabla\nabla-I\nabla^2)\left(\nabla^2H+\frac{1}{4\pi r}\right)=0\tag{5}
$$
Clearly, (5) is satisfied by $\nabla^2H=-1/(4\pi r)$. Using (1), we have $\nabla^4H=\delta(\hat{x})$. Thus
$$
H=-\frac{r}{8\pi} \tag{6}
$$
Substituting (6) into (4) we find
$$
u_i(x)=\frac{1}{8\pi\mu}G_{ij}(\hat{x})g_j
$$
where
$$
G_{ij}=\frac{\delta_{ij}}{r}+\frac{\hat{x}_i\hat{x}_j}{r^3}
$$

There are several places I don't understand:

Why can we write the pressure function $P$ in (2)? What does "Recalling... we set" mean?
Why can we express the velocity $u$ as (4)? How do we know it can be of this form?
What's the difference between $\nabla\nabla$ and $I\nabla^2$?
Answer:
(2) is obtained by taking the divergence of the whole equation, using that $u$ is divergence free, and (formally) inverting the Laplacian (by which I mean that you get an expression like $\nabla^2 P = g\cdot\nabla (\nabla^2)\frac1r$ from which you formally "cancel" out the $\nabla^2$ from both sides).
The sentence "Recalling..." is horribly written and factually wrong. In the free Stokes flow with no source term, the pressure is a harmonic function. But when driven by a source, the pressure solve a Poisson equation and is not harmonic any more. What the author meant by "balancing dimensions" is basically counting the derivatives, and is the same as the "cancelling the Laplacian" trick I gave above.
Expression (4) is called an "ansatz". Basically you guess that the solution can be written in that form, and see where that logically leads you. If you don't run into any contradictions, then you are gold (but note that this only gives you one of the possibly many solutions). As to how this ansatz is made: if $\mathscr{P}$ is a partial differential operator, and $\mathscr{Q}$ is another partial differential operator, and if $\mathscr{P}\mathscr{Q} = \mathscr{Q}\mathscr{P}$ (that they commute), then a solution $u$ to the equation
$$ \mathscr{P}u = \mathscr{Q}f $$
can be found if we can write $f = \mathscr{P}h$. For in this case, $u = \mathscr{Q} h$ will solve the equation. This is an analogue of the classic integrability condition for differential forms (in which case $\mathscr{P} = \partial/\partial x$ and $\mathscr{Q} = \partial/\partial y$, which commute since they are both partial derivatives).
Note: An ansatz doesn't always work. It is sort of like puzzle-solving or detective work by inference. When it works, you write it down, wait for people to ask how you saw the ansatz, and smile smugly. When it doesn't, you toss the paper into the trash bin and hope no one finds out. <code>:-)</code> For example, it could be that in the above example, the function $f$ is in fact not possible to be written as $\mathscr{P}h$, in which case the ansatz will fail. A trivial example for this is if $\mathscr{P} = \mathscr{Q} = d$, the exterior derivative. Let $f$ be a one-form such that $df \neq 0$. Then we violate the integrability condition and so we cannot write $f = dh$. On the other hand, the equation is trivially solvable by setting $u = f$.
$\nabla\nabla$ is the double gradient. $I\nabla^2$ is the Laplacian times the identity matrix. Given a function $F$, $\nabla\nabla F$ is a matrix valued function, whose components are
$$ \left( \nabla\nabla F\right)_{ij} = \frac\partial{\partial x_i}\frac{\partial}{\partial x_j} F $$
where $I\nabla^2 F$ is also a matrix valued function whose components are gived by
$$ \left( I\nabla^2 F\right)_{ij} = (\nabla^2 F) \delta_{ij} $$
where $\delta$ is the Kronecker symbol.
Comment: Physically the interpretation is that pressure $P$, which is like a force, can be written as the gradient of a "potential".
Comment: $\nabla^2$ may have a kernel. Think back to linear algebra: if $A$ is not invertible, then $Ax = Ay$ does *not* imply $x = y$. You only get $x = y + k$ where $k$ is some vector such that $Ak = 0$. In ordinary derivatives: $\frac{d}{dx}\left( x^2 + 3\right) = \frac{d}{dx}\left(x^2 + 10\right)$, but $x^2+3\neq x^2 + 10$.
Comment: "Can I think that this is the very difference between doing math and writing math?" Yes. The quote from Abel applies: the mathematician 'is like the fox, who effaces his tracks in the sand with his tail.'
Comment: Your answer is really helpful, especially your explanation about the "ansatz"(It's from German, isn't it?). It reminds me that reading math sometimes (or large amount of time?) is not easy --- at least for an inexperienced student --- it is not easy to find the underlying ideas. I have never known one can write an "ansatz" this way.
Comment: Yes, [ansatz](http://en.wikipedia.org/wiki/Ansatz) is from German, originally meaning something like "approach" or "starting point". (Though t.b. can probably give you a better definition.)
Comment: What do you mean by "**formally**" cancel out the "$\nabla^2$" from both sides? Isn't it the way to obtain (2) as you said?
Comment: Right, so formula (2) is still an ansatz since it is deduced from "formally" canceling out the "$\nabla^2$", which may not be logically right?
Comment: Well... the statement (2) is true, if only in hindsight. It is *its method of derivation* (or at least the version I gave of it) that is on slightly shaky grounds. But this is getting to issues in epistemology.
Comment: Ok. Can I think that this is the very difference between *doing* math and *writing* math? As I understand so far, the derivation is like the following: "*formally* we set the statement(2), it's not that convincing though. And finally we can *prove* that (2) is indeed true." I haven't see this kind of derivation before due to my ignorance. The version you gave in answer to that [question](http://math.stackexchange.com/q/42714/9464) seems much more straightforward and understandable to me.
Answer: Responding to (3) only,
Griffiths does a really good job explaining the nature of the laplacian in the first chapter of Introduction to Electrodynamics.
He uses the del ($\bigtriangledown$) operator to create a few different double combinations of the Del (gradient operator):
$$\bigtriangledown \bullet (\bigtriangledown F) = \bigtriangledown^2$$
$$\bigtriangledown \times  (\bigtriangledown F)$$
$$\bigtriangledown(\bigtriangledown F)$$
Only the first one is the Laplacian in $R^3$.   The laplacian is n-dimensional though...but I've seen $\bigtriangledown^2$ used to refer to the laplacian in n dimensions, even though I think $\bigtriangledown$ is primarily an operator in $R^3$.  In Griffiths, he describes the second one as the Curl of the gradient or something...I don't remember, but it is useful for describing magnetic fields given an electric one, or something like that.


Sidekiq multiple workers?

Question: I have a question regarding Sidekiq. I come from the Resque paradigm, and in the current application I launch one worker per queue, so in the terminal I would do:
rake resque:work QUEUE='first'
rake resque:work QUEUE='second'
rake resque:work QUEUE='third'

Then, If I want more workers, for example for the third queue, I just create more workers as:
rake resque:work QUEUE='third'

My question is...
With Sidekiq, how would you start with multiple workers? I know you can do this:
sidekiq -q first, -q second, -q third

But that would just start one worker that fetches all those queues. So, how would I go to start three workers, and tell each worker to just focus on a particular queue? Also, how would I do that in Heroku?
Comment: Neither of the answers understood the question. I believe the actual answer lies in placing workers on separate processes and specifying which workers go with which queue. Did you figure something out for this?
Answer: You could use a config file in config/sidekiq.yml :
# Sample configuration file for Sidekiq.
# Options here can still be overridden by cmd line args.
#   sidekiq -C config.yml
---
:verbose: true
:pidfile: ./tmp/pids/sidekiq.pid
:concurrency: 15
:timeout: 5
:queues:
  - [first, 20]
  - [second, 20]
  - [third, 1]
staging:
  :verbose: false
  :concurrency: 25
production:
  :verbose: false
  :concurrency: 50
  :timeout: 60

That way you can configure exactly what you want, and to answer precisely your question the concurrency value is what you are loking for, it defines the number of concurrent workers executed.
More info here : https://github.com/mperham/sidekiq/wiki/Advanced-Options
Answer:
So, how would I go to start three workers, and tell each worker to
  just focus on a particular queue?

You can define on the worker-level in which queue it should be placed via sidekiq_options.
To place for example your worker in a queue called "first" just define it with
class MyWorker
  include Sidekiq::Worker
  sidekiq_options :queue => :first
  ...
end

Comment: This answer talks about setting up queue per worker, but the question is talking about separating workers and theirs queues on different processes.

Sidekiq multiple workers?


Relation between singular values of matrices and their products

Question: Is there any explicit relation between the singular values $\lambda_X$ and $\lambda_Y$ of two same size matrices $X$ and $Y$, respectively, and the singular values $\lambda_{XY^t}$ of the matrix $XY^t$?
Otherwise said, is there a function $f$ such that $\lambda_{XY^t}=f(\lambda_X , \lambda_Y)$?
Thank you
Riadh
Comment: What is $\lambda_X$ for a given matrix $X$?
Answer: Denote the $i$-th largest singular value of a matrix $A$ by $\sigma_i(A)$. Then for any two complex $m\times n$ matrices, we have the following inequality:
$$
\sigma_{i+j-1}(XY^\ast)\le\sigma_i(X)\sigma_j(Y) \ \text{ when }\ i+j\le\min(m,n)+1.
$$
See p.423 of Horn and Johnson's Matrix Analysis, Cambridge University Press.
As matrices are not completely characterized by their singular values, it is hard to believe that the singular values of $XY^T$ in general can be expressed as a function of the singular values of $X$ and $Y$. For example, consider $X=\operatorname{diag}(1,0),\,Y_1=X$ and $Y_2=\operatorname{diag}(0,1)$. Then $Y_1$ and $Y_2$ have identical singular values but $XY_1^T$ and $XY_2^T$ do not.
Comment: A good answer, but I want to point out that matrices are also not completely characterized by their determinants, and yet $\det(AB)=\det(A)\det(B)$.


Tool to trace mac address back to a switch port

Question: To make a long story short, I have some newer off-brand switches in just a few locations.  The main feature I'm missing on these switches vs our nicer (but old) 3Com equipment is the ability to trace a mac address down to a specific port in the address tables.  The off-brand switches do support snmp.  Can someone recommend a good (and cheap/free) software tool (probably snmp-based) that will allow me to trace a mac address down to a specific switch port?
Comment: That 3Com feature was very good; CPU by port is a lifesaver sometimes too..
Comment: make/model please?
Comment: There's 3 different model switches - one netgear, one dlink, and one (sigh) tplink.  I'm hoping for something generic that pulls the info via snmp.
Comment: What do you mean by "off-brand"?
Comment: I mean a brand that's traditionally more consumer focused rather than top-tier enterprise like cisco or 3com/hp.
Answer: Are there cli tools?  You could do something like (I know it's cisco, bear with me):
switch>ping 192.168.101.1

Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 192.168.101.1, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 1/1/1 ms
Then search the arp for the IP:
switch>show arp | include 101.1
Internet  192.168.101.12         37   0020.6b61.a83d  ARPA   Vlan101
Internet  192.168.101.1           -   001d.09fd.71c0  ARPA   Vlan101
Now that you know the MAC address, search the mac address table:
switch>show mac-address-table | include 71c0
*    1  000d.662f.71c0    static  No           -   Router
*   10  001d.09fd.71c0   dynamic  Yes         20   Gi2/43
Voila! Port 43 on the second internal switch.
Answer: I have no idea whether or not Netdisco supports your devices, but that's the tool I've turned to in the past for keeping track of the physical location of MAC addresses on my networks.
Answer: I agree with him, you need to find the mac address first, and look for it ini your 3Com switch.
I have 3Com SuperStack III 4200 series, you need to login to your switch, and use these command: bridge --> addressDatabase --> summary to display all mac address on your switch.
Comment: I can do that on the 3Coms... this question about how to do it on the non-3Com switches that don't have that feature.


My Homepage Footer is Cut-off

Question: I'm having issues with my website's footer (theniftynerd.com). I installed a new Weebly theme a couple days. When I installed, everything was fine and looked good. All of a sudden yesterday, my homepage footer appeared broken. It does not span the full 100% width of the screen -it's like it's stuck at the width of the main body. The footer is completely fine on every other page though.
The only edits I made to the new theme were to widen the sidebar of my blog pages using this code:
blog-sidebar { width: 250px; } .column-blog { float: left; width: 235px; margin: 0; padding: 0; }

I also changed the background color of the theme's buttons -literally only changed the hex color value (the site was fine after both of these edits). I don't understand how the homepage footer broke and why the other pages are fine.
Here's what the footer code looks like in the CSS (I only have access to editing the CSS):
/* Footer */
  .footer-wrap .container {
    padding: 0;
  }
  .footer-wrap .wsite-footer {
    width: 100%;
    padding: 40px 20px;
    box-sizing: border-box;
  }
  .footer-wrap td.wsite-multicol-col {
    margin-bottom: 25px !important;
  }
  .footer-wrap td.wsite-multicol-col:last-child {
    width: 100% !important;
  }

I'm not the most code savvy, so any assistance is greatly appreciated! Thank you
Comment: You may make use of some tools like `http://www.aliciaramirez.com/closing-tags-checker/` to check this. :D
Comment: @Panther I enter all the code I have access to within Weebly and it says all my items are closed.
Answer: The issue is that there is some unclosed tag in
 and because of it the footer gets into this
 while it mustn't. So, find a tag inside
(the one in
) that has no it's closing pair and the issue will be solved)
Comment: Thanks Dmitry, but I'm not seeing it. I didn't edit this, so why would it be broken? And why only on the homepage?
Comment: I can access the div tags under my 5 heading types:
For example, here's one of them
Landing:
  `

{content}

{footer}

`
Comment: The answer in the {content} part - I guess you edit this part with some online editor, don't you? So, open the content of this page and try to find the missing closing tag. Actually, I can't say why this happened, but, I guess, that it could be cache that persisted the page in a normal state after previous changes and after a while it revealed. First of all, save the content of the page somewhere, then, delete it from the site and check if the things get to the proper state - if so, you can be sure, that it is the content to blame for footer disappearance.

My Homepage Footer is Cut-off


What is the `sshd_config` parameter to set the time between password prompts?

Question: If I attempt a logon with bad credentials to an sshd server, I am greeted with Access denied after about a 2 second pause.
Is there a way to increase the time it takes to return the password entry prompt?
Note that I already have LoginGraceTime set to a value of 20s.
Answer: This can be controlled with the pam_faildelay.so PAM module (man).
Under RHEL 6, the following file applies to sshd:
/etc/pam.d/sshd:
#%PAM-1.0
auth       required     pam_sepermit.so
auth       optional     pam_faildelay.so delay=[N time in microseconds]
auth       include      password-auth

account    required     pam_nologin.so
account    include      password-auth

password   include      password-auth

# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    required     pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open env_params
session    optional     pam_keyinit.so force revoke
session    include      password-auth

If you don't want to set the delay within the pam module config you can set it in:
/etc/login.defs:
 FAIL_DELAY    [N time in seconds]

Note that, oddly, FAIL_DELAY accepts the time in seconds.
To apply this to console logins, modify /etc/pam.d/password-auth and/or /etc/pam.d/system-auth.  Also note, you must include the pam_faildelay.so line BEFORE any other auth lines (particularly pam_unix.so).


Converting American to Canadian

Question: Paid \$1012 American for a group of items, which worked out to \$1248.99 Canadian. How do I calculate the conversion rate so I can figure out the total cost Canadian of each item?
Comment: So...what is the question exactly?
Comment: Do I have to divide $1248.99 by $1012? This seems easy I know by for some reason it has me stumped
Comment: Which of the numbers is in Canadian dollars?  Your question has both of them American.
Comment: for instance 1 item cost $158 American. All I have for information is I paid $1248.99 Canadian for the total bill of $1012 American. So I need to figure out what the exact exchange based on that math would be.
Comment: If you get confused and can't figure out whether the conversion factor is $\dfrac{1248.99}{1012}$ or $\dfrac{1012}{1248.99}$ — it's definitely one or the other! — take a moment to think about which currency is more valuable. In your example, Canadian dollars are less valuable, so it should take more of them to purchase any individual item.
Answer: $\require{cancel}$Since the currencies are denominated using the same symbol, \$, I'll use the ISO 4217 currency codes USD and CAD.
We know from your receipt and bank statement (or whatever) that
$$1012 \text{ USD} = 1248.99 \text{ CAD}.$$
To convert from USD to CAD, we must multiply an amount by the conversion factor in CAD/USD, which is
$$\frac{1248.99 \text{ CAD}}{1012 \text{ USD}} \approx 1.234 \text{ CAD/USD},$$
which we can also write as $$\frac{1.234 \text{ CAD}}{1 \text{ USD}}.$$
So, for example, converting the cost of the 158.00 USD item mentioned in the comments gives that in CAD, it cost
$$158.00 \text{ }\cancel{\text{USD}} \cdot \frac{1.234 \text{ CAD}}{1 \text{ }\cancel{\text{USD}}} = (158.00 \cdot 1.234) \text{ CAD} \approx 195.00 \text{ CAD}.$$
Comment: Use \require{cancel} \cancel{some math} in math mode.
Comment: Cheers, @GabrielH!
Comment: Is there a way to strike through text (e.g., to emphasize cancellation) in MathJax?
Comment: This is the right way to look at things, but I would have taken it one step further: from the equation
$1012$USD = $1248.99$CAD, I would have solved for either "USD" or "CAD", depending on which way you were going. You would get, for instance USD$=1.234$CAD, so that any time you saw a price in US dollars, you make the substitution (for "\$") and get an answer in Canadian dollars.
Answer: The conversion is linear, so if \$1012 American is worth \$1248.99, each American dollar is worth $\dfrac{1248.99}{1012}= 1.23418$ Canadian.  Multiply any American dolar amount by that and you get the equivalent amount in Canadian dollars.

Converting American to Canadian


how to Print Source code of a page using curl nad simple_html_dom

Question: Hi i am trying to print a source code of HTML page but it is not working , can someone please help.
Here is the code :
$curl->get('https://google.com');
$response = $curl->getRawResponse();
$html = new simple_html_dom();
$html->load($response);
$source = stream_get_contents($html);
echo $source;

Comment: What exactly is not working?
Comment: `$html` is not a stream.
Answer: A Simple HTML DOM object is not a stream, you can't use it as the argument to stream_get_contents().
The opposite of the load() method is save(). It returns the contents of the object as a string, or writes it to a file if given a filename argument. So you should use:
$source = $html->save();


Sketch curve $y = (4x^3-2x^2+5)/(2x^2+x-3)$

Question: I'm trying to sketch the curve
$$
y = (4x^3-2x^2+5)/(2x^2+x-3).
$$
I tried to find the first and second derivative but I don't know how to find the roots of these.
\begin{align}
y' &= \frac{-5-8 x-38 x^2+8 x^3+8 x^4}{(-3+x+2 x^2)^2}
&&\text{Fermat Theorem}\\
0 &=  -5-8 x-38 x^2+8 x^3+8 x^4
&&\leftarrow\text{Stuck}\\
y'' &= \frac{34+276 x-24 x^2+64 x^3}{(-3+x+2 x^2)^3} \\
0 &= (-5-8 x-38 x^2+8 x^3+8 x^4)(-3+x+2 x^2)
&&\leftarrow\text{Stuck}
\end{align}
I am currently learning Calculus I.
Comment: Could you include latex in your question? It's unclear (at least to me) what you're trying to do.
Comment: @IndyZa: Are you familiar with finding the roots of a cubic and quartic function http://en.wikipedia.org/wiki/Cubic_function and  and http://en.wikipedia.org/wiki/Quartic_function? Both of these do not factor nicely. The cubic has one real root and two imaginary, the quartic has two real and two imaginary. You can plot the numerator of the cubic and quartic to see where they are or use the web sites above for the approach to finding the roots. Here is a plot courtesy of [*Wolfram Alpha*](http://www.wolframalpha.com/input/?i=plot+%284x%5E3-2x%5E2%2B5%29%2F%282x%5E2%2Bx-3%29) Regards
Comment: @Amzoti I have never done the intermediate value theorem on the cubic function before I'll try take a look on it. Thanks :).
Answer: You don't need the second derivative.

Factorise the denominator to find vertical asymptotes.
Ask yourself what happens when $x \to \pm \infty$ to find the horizontal asymptotes.
Put $x=0$ to find the $y$-intercept.
Look for the roots of the numerator to give you the $x$-interecepts.
Solve $y'=0$ to give yourself the turning points.

Once you have all of these the sketch should be straightforward.


Configurar CakePHP para enviar emails pelo gmail

Question: Estou tentando configurar o cakephp para enviar emails através do gmail, já fiz algumas pesquisas e ainda não tive êxito no resultado, alguém poderia me ajudar?
Answer: No seu arquivo app/Config/email.php você precisará criar a classe EmailConfig.
O arquivo app/Config/email.php.default é um exemplo de como ele deve ficar.
Você deverá criar uma nova configuração chamada gmail com o seguinte código
public $gmail = array(
    'host' => 'ssl://smtp.gmail.com',
    'port' => 465,
    'username' => 'email@example.com', // seu email no gmail
    'password' => 'senha', // sua senha no gmail
    'transport' => 'Smtp'
);

Para conexões tls você precisará incluir 'tls' => true na sua configuração;
Answer: Se o seu cakephp for 2.3.0 ou superior use:
public $gmail = array(
    'host' => 'smtp.gmail.com',
    'port' => 465,
    'username' => 'firstname.lastname@example.com',
    'password' => 'secret',
    'transport' => 'Smtp',
    'tls' => true
);

Veja que ele usa o tls=>true, para versão anterior use:
public $gmail = array(
    'host' => 'ssl://smtp.gmail.com',
    'port' => 465,
    'username' => 'firstname.lastname@example.com',
    'password' => 'secret',
    'transport' => 'Smtp'
);

Isso na classe /app/Config/email.php conforme documentação do cakephp:
http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
Comment: Não esqueça de  colocar a config na classe ao chamar $Email = new CakeEmail(); $Email->config('gmail');
Comment: irei testar, valeu.


Entity Framework auto incrementing field, that isn't the Id

Question: I know this isn't the most ideal solution, but I need to add an auto incrementing field to one of my EF Code First objects. This column id NOT the Id, which is a guid.
Is there anyway for me to define the auto incrementing field in code, or would creating the column myself and defining in the DB that its auto incrementing work?
Comment: [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Answer: You can annotate that property with DatabaseGenerated(DatabaseGeneratedOption.Identity). EF allows only single identity column per table.
public class Foo
{
    [Key]
    public Guid Id { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Bar { get; set; }
}

Comment: I had seen the DatabaseGeneratedOption.Identity but tbh I had been lazy and hadnt read into it, I just assumed that it made that column the PKey field.
Thanks, I will give it a go.
Comment: I need both to be type `int`, but it doesn`t work with your code. The Primary key is always 0. Any ideas why this is?
Comment: Is this will still work with Multitenant Databases ?
Comment: @Ahmad It will not work if each tenant has its own seed
Comment: I have my Entity class same like this. If I try to update `Foo` Entity. I getting Error like `Cannot Update Identity column Bar`. Any idea about this?
Answer: Old post thought I would share what I found with Entity Framework 6.1.3.
I created a simple data layer library using C# and .NET Framework 4.6.1, added a simple repository/service class, a code first context class and pointed my web.config file to a local SQL Express 2014 database.
In the entity class I added the following attribute constructor to the Id column:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

Then I created a new migration by typing the following in Visual Studio 2015 Package Manager:
Add-Migration
Give the migration a name and then wait for the DbMigtation class to be created. Edit the class and add the following CreateTable operation:
CreateTable(
"dbo.Article",
    c => new
    {
        Id = c.Guid(nullable: false, identity: true),
        Title = c.String(),
        Content = c.String(),
        PublishedDate = c.DateTime(nullable: false),
        Author = c.String(),
        CreateDate = c.DateTime(nullable: false),
    })
    .PrimaryKey(t => t.Id);
}

The above table is an example the key point here is the following builder annotation:
nullable: false, identity: true

This tells EF to specifiy the column as not nullabe and you want to set it as an identity column to be seeded by EF.
Run the migration again with the following command:
update-database

This will run the migration class dropping the table first (Down() method) then creating the table (Up() method).
Run your unit tests and/or connect to the database and run a select query you should see your table in its new form, add some data excluding the Id column and you should see new Guid's (or whatever data type your choose) to be generated.
Answer: For those stumbling onto this question for EF Core, you can now create an auto-incrementing column with your model builder as follows:
builder.Entity<YourEntity>().Property(e => e.YourAutoIncrementProperty).UseNpgsqlIdentityAlwaysColumn();

Reference: https://www.npgsql.org/efcore/modeling/generated-properties.html


Error Correction Model & Trend Stationarity

Question: I'm familiar with a traditional Error Correction Model (ECM) of the form
$$Y_{t}-Y_{t-1}=\Pi Y_{t-1}+\sum_{i=1}^{p-1}\Gamma_{i}\left(Y_{t-i}-Y_{t-i-1}\right)+\varepsilon_{t}
 $$
where $\Pi=\alpha\beta'$, $\alpha$ is the long-run adjustment, $\beta$ is the matrix of cointegrating vectors, and $\beta'Y_{t-1}$ is stationary.
For the data set I am looking at (includes economic variables, interest rates, and stock prices), I was testing cointegrating vectors and found that some are stationary and some are trend stationary. I think I should include the trend stationary ones, but I'm not entirely sure what's the best way to proceed.
For instance, one approach is to estimate the model $$y_{t,i}=a_{i}+b_{i}t+x_{t,i}
 $$ to de-trend each variable and then apply the above ECM to $X_{t}$.  However, I wonder if it is better to keep everything in terms of $Y_{t}$.
Hence, I was thinking about estimating
$$Y_{t}-Y_{t-1}=A+Bt+\alpha F_{t-1}+\sum_{i=1}^{p-1}\Gamma_{i}\left(Y_{t-i}-Y_{t-i-1}\right)+\varepsilon_{t}
 $$ where $F_{t}=\beta' Y_{t}$ and $\beta$ includes all significant cointegrating vectors (including trend stationary ones). Whereas the traditional ECM is stationary since you are adding stationary series, this is a linear combination of a deterministic time trend, trend stationary series, and stationary series. Is this what should be done? Should I de-trend $F_{t}$ if I include the deterministic time trend, and vice-versa if left out?
Answer: I was able to find the answer in Pitfalls and Opportunities: What Macroeconomists Should Know About Unit Roots by Campbell and Perron. They suggest a model of the form
$$
Y_{t}-Y_{t-1}=A+\alpha Y_{t-1}^{*}+\sum_{i=1}^{p-1}\Gamma_{i}\left(Y_{t-i}-Y_{t-i-1}\right)
$$
where $Y_{t}^{*}=\beta' Y_{t}-\delta t$.


How do I push latest code into auto scaling group

Question: How do I push latest code into auto scaling group's machines
I trying to run  production servers on AWS with auto scaling framework.
I wonder how can I deploy the new published code into running production servers.
I don't care the down time currently.
I run the web server with nginx with reverse proxy to  puma
What's the common practice to do this task ?
I think to login AWS console find all the servers IP and SSH into it. Update the codebase and restart the puma web server is not a good way to maintain quality product
Comment: You could look into ElasticBeanstalk https://aws.amazon.com/elasticbeanstalk/
Answer:
I wonder how can I deploy the new published code into running
  production servers.

Easy: you don't.
Instead, either update the AMI that the ASG instances are started from or update the launch configuration to include new code that gets deployed on boot.
Answer: CodeDeploy has a really good integration with ASG groups at the moment, if you do choose to use it, just ensure that you are either baking the CodeDeploy agent into the AMI of your ASG or using user data to install the agent.  If you are baking into your AMI, just be aware that you will need to update the AMI every so often so it doesn't get over loaded with updates.
There are also extra scripts that AWS provides for ASG integration that will prevent autoscaling activities from replacing the instance while it's offline during an update and if you are using an ELB, it will also de-register it to prevent the ELB from sending traffic towards it.
http://docs.aws.amazon.com/codedeploy/latest/userguide/auto-scaling-integ.html
As other posters have mentioned, Elastic Beanstalk is also an option.


About the cases when $N=N(\epsilon)$ is bounded or unbounded

Question: The limit of the sequence $(x_n)$ is $x$ if for each $\epsilon >0$ there exists a positive integer $N=N(\epsilon)$ such that $|x_n−x|<\epsilon$ for all $n≥N.$
I am asking about the cases when $N=N(\epsilon)$ is bounded or unbounded, i.e., when $\epsilon$ tending to zero. I can find examples such that $N=N(\epsilon)$ is bounded or unbounded. But I am interested on the general case.
Comment: It is very unclear what you want here. I'm voting to close until you can ask a clear question.
Comment: @Rhys: I am asking about the nature of the number $N$ when $ε→0$.
Comment: That is so strongly dependent on the nature of the sequence that no general statements can be made. You've already said that you can find examples where is is bounded and unbounded. What, specifically, do you want to know?
Comment: @Rhys: Ok. You said that no general statements can be made. This is the answer I am looking for.
Comment: General statements can be made, I'm working on it.
Answer: In general, if we have a sequence $(x_{n})$ converging to some $x$ and we take $N(\varepsilon)$ to be the smallest integer such that for all $n\geq N(\varepsilon)$ we have $|x_{n}-x|<\varepsilon$, then $X=\{N(\varepsilon):\varepsilon>0\}$ is bounded if and only if there exists an $N\in\mathbb{N}$ such that $x_{n}=x$ for all $n\geq N$.
First suppose that $X$ is a bounded set. Then $X$ is finite, so we can find a $\varepsilon'$ such that $N(\varepsilon')=\max X$. In particular, for all $0<\varepsilon<\varepsilon'$ we have $N(\varepsilon)=\max X$, as
$$\max X\geq N(\varepsilon)\geq N(\varepsilon')=\max X.$$
Hence for all $n\geq\max X$ we have
$$|x_{n}-x|\leq\lim_{\varepsilon\downarrow0}\varepsilon=0,$$
so $x_{n}=x$.
Now suppose that there exists and $N\in\mathbb{N}$ such that for all $n\geq N$ we have that $x_{n}=x$. Then for all $\varepsilon>)$ we have that $N(\varepsilon)\leq N$, so $X$ is bounded.
Answer: In general you cannot determine the behaviour in $\epsilon$ of the sharpest $N(\epsilon)$. By sharp I mean that $N(\epsilon)$ is such that $|x-x_n|<\epsilon$ if $n\geq N(\epsilon)$ and $|x-x_n|\geq\epsilon$ if $n<N(\epsilon)$.
Put it differently, $N:(0,+\infty)\to\mathbb{N}$ defined as $N(\epsilon)=\inf\{N\in\mathbb{N}:|x-x_n|\leq\epsilon\text{ whenever }n\geq N\}$ is monotone but not necessarily unbounded. However, asking this sharp condition on $N(\epsilon)$ is a surplus with respect to the definition of limit: "it exists an $N(\epsilon)$" means that you have the freedom of the choice of it, since you are interested in an asymptotic behaviour of the sequence. Therefore, in $N(\epsilon)$ is the sharpest value for a given $\epsilon>0$, also $N(\epsilon)+1000$ is acceptable in the definition of the limit. This means that, recursively, you can always made your choice of $N$ growing faster and faster, and made it unbounded. The reverse is clearly non possible.


Legality of custom windows installation discs

Question: I sell custom built computers in a niche market. I include specific software pre-loaded on the systems for my customers. If the customer ends up needing to reinstall the OS then the pre-loaded software is all gone. I have had requests to include recovery media that includes this stuff.
I am aware of the technique behind building a custom windows installation disc and we already do this to image the computers when we finish building them. However, would it be legal to burn a copy of this disc and include it with the system?
Comment: You want legal advice, ask a lawyer.  Licensing advice, ask Microsoft (and/or the other companies who make the software your pre-load).  Either way, don't rely on free advice from strangers on the internet for this, as that guarantees it will end badly.
Comment: Any idea who to even contact at Microsoft to get the answer to this question? Seems like an endless pit of confusion.
Comment: You're right about that... honestly, there are MS licensing questions that even MS doesn't know the answer to.  However, I think Mark's answer is a nifty way around the whole problem.  I think I'd go with that.
Comment: You're supposed to be including the OEM System Builder media and COA with these PCs. You can make custom discs if you sign an appropriate agreement with Microsoft. Contact Microsoft for further information.
Answer: Is it legal?
I don't know. Even if I did know, I wouldn't trust free legal advice from strangers on the Internet.
Is there a better way?
Run the built-in Windows Image Backup immediately after installation. This will make a bootable image-based backup to optical or removable media. This allows you to avoid potential legal issues while also leveraging built-in tools.
Comment: I wouldn't trust paid advise from just one Lawyer either.
Answer: You need an OEM License for each computer you sell.  An OEM license from Microsoft says that you must provide support for your users and that the license can't be transferred to another machine.  You must place the sticker on the machine's case.  You can call a reseller, like SHI or NewEgg for advice on the OEM License.
If you want to figure it out for yourself, Microsoft has a a page for System Builders.
Update - The answer is no.:  After browsing the FAQ section from the link above, you are not allowed to supply an image DVD with your computer, but you can provide recovery on a fixed disk.


Getting "500 unrecognized command" when telnet to mail server from Windows - works fine from Linux

Question: I've seen the answer here to a similar question, but my situation is different in that it works fine when I telnet to the mail server from a Linux box, but I get this "500 unrecognized command" error when I telnet from Windows.
Windows:
<code>C:\Users\Administrator>telnet
Microsoft Telnet> OPEN 192.168.1.7 25
220 ****************************************************************************
****************
EHLO
500 unrecognized command
</code>
Linux:
<code>[me@mybox log]$ telnet 192.168.1.7 25
Trying 192.168.1.7...
Connected to 192.168.1.7 (192.168.1.7).
Escape character is '^]'.
220 ********************************************************************************************
EHLO me
250-mail1.mycorp.com Hello me [192.168.0.61]
250-SIZE 52428800
250-8BITMIME
250-PIPELINING
250-AUTH PLAIN LOGIN
250 XXXA
</code>
Can anyone help diagnose this issue on Windows?
Comment: Can you do the telnet localhost on the server, or did you not administrate that? I have seen that this error is sometimes cause by firewall features and / or some local software installed on the PC.
Comment: No, I don't have access to the mail server, and the guy who does isn't around this week unfortunately.
I noticed that trying e.g. smtp.gmail.com 25 has the same result - what could that mean?
Comment: Apologies, my last comment is incorrect. When I try to connect to gmail, I get:
Connecting To smtp.gmail.com...Could not open connection to the host, on port 25
Answer: There is a Cisco PIX/ASA involved somewhere. That is a firewall blocking the SMTP traffic. Odd behaviour when its SMTP scanning features are turned on.
Doesn't matter that the behaviour is different - the simple fact is the feature is enabled and needs to be turned off.
It is so common an issue that there is even a KB article from Microsoft about it! https://support.microsoft.com/en-gb/help/320027/
Comment: What is the downside to turning off this feature? I need to be fully prepared to explain a change like this to my firewall guy!
Comment: As far as I am concerned, there is no downside. Email will work correctly, without delivery problems. I have never understood why the feature was used and it gives so much hassle that turning it off is the best option.
Comment: The link is dead. Can you please update it? Thx
Comment: The article has been pulled by Microsoft it would appear. However if you Google for fixup SMTP then you will find plenty of other referenced.
Comment: Did you see [this post](https://serverfault.com/questions/974733/getting-error-500-when-sending-1st-command-to-exchange) - what can it be? Especially, the fix for PuTTY is interesting.
Answer: In my experience this error is often caused by a firewall feature which is blocking/scanning the SMTP traffic.
You should check that with your firewall administrator (if he can switch that off). You can also try to find a connection which isn´t using this firewall to double check that.
Comment: Did you see [this post](https://serverfault.com/questions/974733/getting-error-500-when-sending-1st-command-to-exchange) - what can it be? Especially, the fix for PuTTY is interesting. How can the `Passive Mode` _disable_ any firewall settings so it works? I see [here](https://documentation.help/PuTTY/config-ptelnet.html) the difference but I don't understand why it should help.


Render image or entity in a custom block!

Question: I want to render product content type in a custom block with a custom view mode. I have a field product_teaser in my article content type that reference the product that is I want to render in the custom block using advert view mode
The content type to be rendered: "product"
The view mode to be rendered with: "advert"
The product teaser only contains an image and a buy=now button I can easily place using twig. So placing only the image in the render of the custom block should be enough for this to work But I have been trying to render the image for a while and I could not do it.

This is my first approach to do this, Rendering the whole product advert.
<code>  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $view_mode = 'advert';
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
      $pre_render = $view_builder->view($product, $view_mode);
      $render_output = render($pre_render);
      return $render_output;
    }
    return [];
  }
</code>
Render output is an empty string for some reason. $pre_render has got view mode and node array having all the product fields, everything looks good except that render($pre_render) return an empty spaces string.
This is the error being output from this approach "Argument 1 passed to Drupal\Core\Render\Element::isEmpty() must be of the type array, object given"

My second approach was to get the image URI of the product advert and render it manually
<code>$build= array();
    //Gets current node to check for which product to be displayed.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $product_advert_url = $product->field_teaser->entity->url();
    }

    $build['image'] = [
      '#theme' => 'image_style',
      '#style_name' => 'thumbnail',
      '#uri' => $product_advert_url
    ];

    return $build;
</code>
This is the error being output from this approach "Class name must be a valid object or a string in Drupal\image\Entity\ImageStyle->buildUri()"

How to fix these errors ??, I prefer the first method because it will be easier if I needed to add anything to the product teaser later.
Answer: You can do this in a View block. Add a contextual filter for the content id and configure it to provide the default value "Content ID from URL":

The view mode Teaser would be in your case a custom view mode (for the content type "article") only containing the product teaser field, configured to render the target entity in a second view mode "advert" (now for the content type "product").

If you want to do this in code, then get the node from a context plugin (see this great answer from @Berdir https://drupal.stackexchange.com/a/188629/47547) and build the render array (if you use the view modes mentioned above you only need one line of code). Very important, never render in Drupal 8, always return unrendered arrays.
Comment: I tried to do it in a view, with no luck, the contextual filter was not working i am trying to do this condition in the filter (( Product id == article.field_product_teaser ))
Comment: My suggestion is about a simple contextual filter for the article and then render it again, but in a different view mode only containing the product teaser field.
Comment: I got the view setup to render max 3 adverts of products but it's not rendering any I think my contextual filter is wrong, I choose the " Content: Product teaser (field_product_teaser) " but I cannot figure out how to make it do {{ Product id == article.field_product_teaser }}, sry haven't dealt with contextual filters too much
Comment: My suggestion was to configure the most basic contextual filter for the current node. What you are trying to do is to join both content types in a relationship. You might consider asking a question about this, I think someone here can help if you provide more details.
Comment: I am sorry can you elaborate more on your suggestion, I cannot understand how should I configure the most basic contextual filter, could I use the contextual filter to do what I need? I added a relationship to get the field_product_teaser from the article data type but I am not sure how I could advance?
Comment: I've added a screenshot.


Help for planning a neuroscience experiment

Question: I'm new here. I am planning a neuroscience experiment. I will be measuring brain signals from about twenty subjects. I will present the subjects four different kinds of stimuli. After all the data processing, I will have four power spectrums for each participant (one per stimulus type). That is, I will see the magnitude (power) of each frequency (something like this but calculated from the brain data). There is also a fifth stimulus type, which is rest (no stimulus; used as as control measure or "baseline" in neuroscience jargon).
From each of the power spectrums, I will pick two frequency bands and calculate the average power in each band. The first band is 8-12 Hz ("alpha" in neuroscience jargon) and the other 16-22 Hz ("beta" in neuroscience jargon).
I am expecting to observe four phenomena:

For stimulus type 1, alpha is larger than beta. Both are larger than baseline.
For stimulus type 2, beta is larger than alpha. Both are larger than baseline.
For stimulus type 3, alpha is larger than baseline activity. Beta is equal to baseline.
For stimulus type 4, beta is larger than baseline activity. Alpha is equal to baseline.

How should I do my statistical tests? Is my experimental design sufficient? Note that the power of beta is always less than the power alpha in the rest state.
I am asking this because our field appears to have some problems regarding the rigour of statistical analyses (see e.g. http://www.nature.com/neuro/journal/v14/n9/full/nn.2886.html).
Comment: Can you make more precise predictions than "larger"?
Comment: Yes. Let's say for example that the difference in power should be at least a few decibels (dB).
Comment: The thing is that the patients will probably differ from session to session (unless you have data that baseline activity is very stable), so even eg Stim4 alpha==baseline alpha is not really a plausible hypothesis. You have stimulus effect + inter-individual differences + intra-individual differences + measurement error. Choosing a reasonable statistical hypothesis to test is a crucial part of the process that most people overlook. Sometimes we simply do not know enough about the system to do so, in that case exploratory analysis and parameter estimation is appropriate.
Comment: Can you do all 5 stimuli in one session for each subject? Even better is to do Baseline-Stimulus1-Baseline-Stimulus2-etc. Then for each subject you should see the power spectrum change then return back to baseline. This would be very convincing even with a single subject.
Comment: The power spectrums are calculated over ~10 minutes of data. The system records 1000 samples per second, so the power spectrums are calculated from 1000 * 60 * 10 = 600000 samples. (Actually, it's 1000 samples per second per channel, I average the data from 4-5 channels). There is very heavy signal processing for removing all sorts of artefacts. The intra-individual variance should be small.
Comment: Yes, all data from one subject is collected in one session.
Comment: So I assume there is some kind of washout procedure and then you do the interleaved baseline measurements between stimuli? "Fatigue" would be indicated by a trend in the baseline measurements?
Comment: Fatigue would result in an increase of alpha power (though in another brain region, but due to the conductivity properties of the skull, it would affect the target site as well). The experiment is designed so that the fatigue of subjects is minimized.
Comment: Do you have a prediction about baseline alpha vs baseline beta? Also alpha3 vs alpha1, etc.
Comment: What I'm getting at is that you have 10 measurements. Although just higher/lower individual predictions don't mean much, taken together the overall rank order of all these measurements consists of a precise prediction it would be surprising to observe if there was nothing to your theory.
Comment: Do you already know what time windows to investigate? Are you interested in whole-epoch mean power, or in event-related desynchronisation? That's important because it means you'd have to worry about multiplicity or circularity in another dimension (time).
Answer: I don't have the time to write out a full length proper answer for this at the moment, so the short version of this is as follows.
An excellent book on this is "Design and Analysis of Experiments" by Montgomery, so I would strongly suggest you take a look at it for all the details. What I think you're probably looking to do is a "fractional factorial" experiment or a full factorial experiment. Your expectations will guide you in setting up the hypothesis testing.
Answer: Am I right that your design and expected results look something like this?

B stands for baseline.


Show that $im(L_{I_n+A}) = E_1(A)$

Question: Hi I'm having trouble with this homework question:
"Let $F$ be a field and let $A ∈ M_{n×n}(F)$.
Suppose that $F = Q, R$ or $C$ and that $A^2 = I_n$.
$i)$ Show that if $λ$ is an eigenvalue of $A$ then
$λ = 1$ or $λ = −1$.
$ii)$ Show that $ker(L_{I_n+A}) = E_{−1}(A)$ and that $im(L_{I_n+A}) = E_1(A)$ where $E_\lambda$$(A)$ denotes the eigenspace of $A$ with eigenvalue $\lambda$ and $L_{I_n+A}=A+I_n$"
I have managed to do part $i)$ and show that $ker(L_{I_n+A}) = E_{−1}(A)$ fairly easily but I'm having trouble with the last part where it asks you to show $im(L_{I_n+A}) = E_1(A)$. I used this as the definition of the image: $im(L_{A+I_n})=${$y$ : $L_{A+I_n}(x)=y$} $=$ {$y$ : $(A+I_n)(x)=y$}.
Any help with this would be very much appreciated.
Answer: OK, here we go!
I'll discuss this problem in the more general context of fields $F$ such that $char F \ne 2$.  Certainly Q, R, C and any other field of characteristic zero all satisfy this criterion.
Since the underlying vector space $V$ upon which $A$ operates has not been explicitly specified in the question text, I will take $V = F^n$.
Part (i):  Let $\lambda \in F$ be an eigenvalue of $A$; that is, there exists a non-zero vector $v \in F^n$ such that
$Av = \lambda v; \tag{1}$
then, since $A^2 = I$, we have
$\lambda^2 v = \lambda(\lambda v) = \lambda (Av) = A(\lambda V) = A(Av) = A^2v = Iv = v, \tag{2}$
whence
$(\lambda^2 - 1)v = 0; \tag{3}$
since $v \ne 0$ we conclude that
$\lambda^2 - 1 = 0.  \tag{4}$
The roots of (4) are $\lambda = 1$ and $\lambda = -1$; since $char F \ne 2$ they are distinct (note that if $1 = -1$ in $F$, $2 = 1 + 1 = -1 + 1 = 0$ in $F$, contradicting the hypothesis $char F \ne 2$).  This shows every eigenvalue of $A$ is in the set $\{-1, 1 \}$.
The preceding remarks answer Part (i.).
We observe in passing that, provided $A \ne \pm I$, both cases $\lambda = \pm 1$ actually occur as eigenvalues of $A$.  For if, say, $1$ does not occur as an eigenvalue of $A$,  then
$Av \ne v = Iv \tag{5}$
for any non-zero $v \in F^n$.  Thus $v \ne 0$ implies
$(A - I)v \ne 0 \tag{6}$
as well.  Now for any $w \in F^n$ we see that
$(A - I)(A + I)w = (A^2 - I)w = 0, \tag{7}$
whence by (6) we find
$(A + I)w = 0  \tag{8}$
or
$Aw = -Iw  ;\tag{9}$
thus
$A = -I; \tag{10}$
a parallel argument shows that if $-1$ does not occur as an eigenvalue, $A = I$.
Now, as for Part (ii.):
Suppose $v \in \ker (A + I)$; then
$Av + v = Av + Iv =(A +  I)v = 0, \tag{11}$
whence
$Av = -v, \tag{12}$
that is,
$v \in E_{-1}.  \tag{13}$
Steps (11)-(13) may be easily reversed to shown that (13) implies $v \in \ker (A + I)$.  Thus we see that $\ker (A + I) = E_{-1}$.
To see that $im (I + A) = E_1(A)$, suppose that $y \in im (I + A)$; then
$y = (I + A)x \tag{14}$
for some $x \in F^n$.  Then
$Ay = A(I + A)x = (A + A^2)x = (A + I)x = y, \tag{15}$
i.e.,
$y \in E_1(A). \tag{16}$
Finally, if (16) binds, so that
$Ay = y, \tag{17}$
we have
$(A + I)y = Ay + y = y + y = 2y, \tag{18}$
or, since $char F \ne 2$ so that $2^{-1}$ exists, we may write
$y = (2^{-1}2)y = 2^{-1}(2y) = 2^{-1}(I + A)y = (I + A)(2^{-1}y), \tag{19}$
showing
$y \in im (I + A). \tag{20}$
And we are done.
Comment: Wow thank you so much this is far more than I ever expected.
Comment: @Thomas:  my pleasure sir!

Show that $im(L_{I_n+A}) = E_1(A)$


Find det A if A is 3 × 3 and det(2A) = 6.

Question: So i was given this question.
Find det A if A is 3 × 3 and det(2A) = 6.
Trying to solve this i tried to use the fact that
If A is an n × n matrix, then $det(uA)$ = $u^ndetA$ for any number u.
So for this case if i was given the det(uA) would i just divide the 2, so the answer is 3?
Comment: $2^3=8$$ \ \ \ \ \ \ \ \ \ \         $
Answer: Hint : If $A$ is a $3\times 3$-matrix, then $det(2A)=8\ det(A)$
Comment: Is the n the matrix, so it would be 2^3?
Comment: Yes.  Notice that the rule reads, "If $A$ is an $\mathbf{n \times n}$ matrix..."


How do I invert this 3×3 matrix?

Question: I've been following Khan Academy to try and teach myself how to invert matrices, howevever I tried to invert a 3×3 matrix and I am not sure where I have gone wrong.
Picture of my answer:

I tried to invert $A$ but my answer is wrong. I would appreciate any help given.
Link of KhanAcademy tutorial I was following: https://www.khanacademy.org/math/algebra-home/alg-matrices/alg-determinants-and-inverses-of-large-matrices/v/inverting-3x3-part-1-calculating-matrix-of-minors-and-cofactor-matrix
Comment: Your original matrix has "2" but you use "-2" in calculating the determinant!  Your original matrix has "1" but you use "10" in calculating the determinant!  The determinant  of the matrix you show is 10, not -100.
Comment: Your mistake: You need to calculate the determinant of $A$ which is $10$.
Comment: You need the determinant of the original matrix, not of the cofactor matrix.
Answer: Note that $A$ is diagonal. Convince yourself that merely taking reciprocals of the diagonal entries yields the inverse:
$$A^{-1}=\begin{bmatrix}
\frac12&0&0\\
0&\frac15&0\\
0&0&1\end{bmatrix}$$
Comment: @AlanPiggott Yes. I also need to mention that **diagonal matrices are just lovely to work with**.
Comment: So all I actually had to do was get the reciporcals of those numbers? Was all the work i did irrelevant or did I just go wrong somewhere. Thanks
Comment: @AlanPiggott Well if the matrix was not diagonal you would have to go through the process you have showed. As pointed out in the comments, you made your error in the determinant; it is 10 and not 100, and can be calculated with Sarrus's rule. As well as that, the middle entry in the cofactor should have been 2 and not -2, as pointed out in the comments. Those aside, your working is correct.
Comment: Ok I understand that thanks. I am still confused however on why the determinant is 10 and not 100. At the top right of my page that I have labeled ' matrix of numbers', I got 2x5 in the bottom right. Then I multplied 5x2x10. Where did I go wrong here? Thank you.
Comment: @AlanPiggott It's not the determinant of $C$ you should take, it's the determinant of the original $A$.
Comment: Ah yes I understand now. So if it was  not a diagonal matrix and I fixed the mistakes you have mentioned, everything I have done would be ok?
Answer: Just another note, it seems like you multiplied the central element of your matrix by $-1$ in the second line, which you're not meant to do - the diagonal elements are multiplied by $+1$ according to the Khan Academy tutorial.

How do I invert this 3×3 matrix?