Regression on wavy angular data?

Question: I'm a newbie at stats/machine learning so please bare with me.
This plot is a result of an experiment that attempts to find the perceived angle of a stimulus.

The stimulus is placed at a position (see the X axis of the plot) and participants reply with the perceived angle (see the Y axis)--in other words, the question is "what direction do you think it's coming from?" Perceived angles therefore range from 0 to 360.
The plot shows this strange sinusoidal pattern about the best fit line (in blue). How would I go about capturing that wavy pattern in a regression? I would like to obtain an equation for perceived angle as a function of position.
A linear regression is not a bad approximation, but I would like to see if there's anything better. I also tried to do a regression with a few added polynomial terms, but I couldn't get a reasonable fit (perhaps I just messed up).
Thoughts/advice appreciated.
Comment: LOWESS wouldn't be a terrible choice. The R call is `lowess`.
Comment: The circular linear regression is well studied in literature, if you like R you can use the
circular package and the function lm.circular.
Comment: If the period is known, this is [relatively simple](http://stats.stackexchange.com/questions/60500/how-to-find-a-good-fit-for-semi-sinusoidal-model-in-r/60504#60504); if it's unknown (leaving the period as another parameter) then it's a [nonlinear problem](http://stats.stackexchange.com/questions/60994/fit-a-sinusoidal-term-to-data). There's also periodic splines.
Comment: @user777 lowess was a great suggestion and worked great, thanks.
Comment: @niandra82 FWIW, I also (fruitlessly) searched for the answer that Glen_b linked to. Depending on your research goals, that answer might be better suited for your purposes.
Answer: If a predictor is angular, it's clear how to do this; but that's not the case here. I think there is a power of suggestion going on here: because you have angular response values, you have trig on your mind. You do have some departure from linearity, but maybe it's not sinusoidal. If you plot the residuals instead of the data, it may not look as sinusoidal.
I thought maybe a transformation might help, but reconsidered since I don't think zero has any particular meaning here.
So maybe it's a good time to remember what George Box said -- all models are wrong, but some are useful. In your plot, it's clear that the straight-line model does in fact explain the lion's share of what is going on, and maybe you should just be happy with it. It's simple and easy to explain -- and that's worth something because the goal of statistics is to explain things.
If the polynomial fits don't work, maybe there is some kind of nonlinear model. But I can't think of a natural one here.
Comment: Great suggestions. I should have just called it "wavy" from the beginning instead of calling it sinusoidal the first time. I used lowess (thanks to a comment by user777) and will find the worst-case difference in predictions to evaluate if a linear model is good enough. Thanks.

Regression on wavy angular data?


Remark on Turán's Theorem

Question: In my notes, Turán's Theorem is stated as follows:
Theorem: Let $G$ be a graph on $n$ vertices. Then $e(G) > e(T_{r-1}(n)) \implies G \supset K_r $.
There are then several remarks on the theorem, one of which I don't follow:
Remark: If we knew $G$ was $(r-1)$-partite, then we are done by some kind of AM-GM inequality. But there's no reason why $G$ should be $(r-1)$-partite: e.g. $C_5 $ is $K_3$-free, but not bipartite.
Firstly, am I correct in saying that the reasoning for the above is that if we knew $G$ was $(r-1)$-partite, then it couldn't contain a $K_r$, and so we'd aim to prove (using "some kind of AM-GM inequality") that $e(G) < e(T_{r-1}(n))$?
My main problem is that I don't quite know what "some kind of AM-GM inequality" actually means. Could someone show me explicitly what is meant here?
My thoughts: I can sort of see what's going on: we aim to show that the largest number of edges an $(r-1)$-partite graph can have without containing $K_r$ occurs when the vertex classes are as equal in size as possible (as per the definition of Turán's graph). I don't see how AM-GM comes into it though.
Thank you.
Answer: Assume that $G$ is $(r-1)$-partite. (You are right in observing that $G$ does not contain $K_r$ as a subgraph.) Let the sizes of the $(r-1)$ vertex classes be $n_1, n_2, \ldots, n_{r-1}$. Then the number of edges is maximised when $G$ is a complete $(r-1)$-partite graph on these vertices.
The number of edges in a complete $(r-1)$-partite graph on these vertices is
$$
\frac{n(n-1)}{2} - \sum_{i=1}^{r-1} \frac{n_i (n_i-1)}{2}.
$$
(Of the $\frac{n(n-1)}{2}$ edges in a complete graph, we should remove the edges lying inside each of the $(r-1)$ parts.) This can be simplified to
$$
\frac{n^2}{2} - \sum_{i=1}^{r-1} \frac{n_i^2}{2}
$$
since $\sum_i n_i = n$. Maximizing this quantity is equivalent to minimizing
$$
\sum_{i=1}^{r-1} n_i^2
$$
subject to the condition $\sum_i n_i = n$. By Cauchy-Schwarz, we have
$$
\begin{align*}
(r-1) \cdot \left( \sum_{i=1}^{r-1} n_i^2 \right)
&\geqslant  \left( \sum_{i=1}^{r-1} n_i \right)^2
\\ &= n^2,
\end{align*}
$$
with equality when all the $r-1$ numbers $n_1, \ldots, n_{r-1}$ are equal. Since these numbers are integral, we want them to be as equal to each other as possible.

Remark on Turán's Theorem


What is the concept of a limit in simple terms

Question: I'm 14 just starting high school and I got interested in all the new math so I took a little dive into calculus but I can't wrap my head around the concept of a limit and for which uses it is applied to an equation and when I should use a limit.
Comment: You are asking for the equivalent of a couple of weeks' worth of Calculus lectures, which is not what this website is suited for. But do look for earlier questions tagged *limits*, as you may find some to be useful.
Comment: To get an intuitive explanation, I recommend 3b1b 's [Essence of Calculus](https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr)
Comment: Using limits is **a way to deal with infinity** (there are others...). A very simple case : if I consider the sequence of numbers $0.9, 0.99, 0.999, 0.9999 \cdots$, its limit is $1$, and this is a correct way to say that $0.99999...$ with an "infinity of decimals" is in fact $1$, this "infinity of decimals" arguing being questionable... (I could have written neatly this issue as $\lim_{n \to \infty} (1-\tfrac{1}{10^n})=1$).
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: In many situations, we want to evaluate a function at a point where it's not defined. In some of these situations the limit, if it exists, is a good candidate for that value. Let me illustrate with a few examples.
As in Jean Marie's example in the comments, often the function is defined at positive integers and we want to know what happens "at infinity". In the specific example, think of the function that takes $n$ to $$0.\underbrace{999\dots9}_n = 1 - \frac{1}{10^n}.$$ As $n$ gets bigger this quantity gets arbitrarily close to $1$, so we define the expression $0.999\dots$ with "infinitely many" $9$'s to be the $1$, which is precisely the limit of $1 - 1/10^n$ as $n$ goes to $\infty$. This is also how limits of sequences and infinite series work.
Here's another example where the details are harder to check but the idea using a limit is similar. Suppose you know that the circumference of a unit circle (a circle with radius $1$) is $2\pi$ and want to find its area. If you divide up the circle into $n$ equal sectors, then for large $n$ each is approximately a triangle with base $\approx \frac{2\pi}{n}$ and height $\approx 1$. So the total area of these sectors is $\approx n \times \frac12 \times \frac{2\pi}{n} \times 1 = \pi$. As $n$ gets large the approximations get better and the limit is exactly $\pi$.
Sometimes, instead of integer inputs, the functions is defined near some value $a$, but not at exactly $a$. This is the case in the calculus definition of tangents (or derivatives). Consider the graph of $y = x^3$, and the secant line joining the point $(0, 0)$ to another point $(t, t^3)$ on this graph. As long as $t \ne 0$, this line is uniquely defined and has slope $t^3/t = t^2$. But if $t = 0$, the point $(t, t^3)$ is the same as $(0, 0)$, so there isn't a unique line joining them. But it's clear, either from this calculation of the slope or visually, that for $t$ near $0$, the secant line gets arbitrarily close to being horizontal. The tangent line therefore should be horizontal, ie have slope $0 = \lim_{t \to 0} t^2$.
Another useful (but again harder) example is the definition of $10^x$ for real $x$. For positive integer $x$ this can be defined by repeated multiplication, and then it extends to negative integers and rational $x$ by extrapolating the rule $10^{x + y} = 10^x \times 10^y$. Then we can define the value $10^x$ at irrational $x$ to be
$$\lim_{\substack{y \to x\\ y \in \mathbb{Q}}} 10^y ,$$
ie the limit of $10^y$ as $y$ approaches $x$ through rationals, where we have already defined $10^y$. This is not the only way to extend the definition of exponentiation to real exponents, but it always involves taking limits in some sense.


Anyone please do have Netflow data using nfdump in csv file?

Question:
I had collected data using tcpdump but i want data from nfdump as a csv file.
Answer: <code>nfdump -r /tmp/nfcapd.201712052349 -o csv > /var/log/netflow/test.csv
</code>
Comment: I don't know why this was voted down it works just fine.


SD probability problem involving chi-square distribution

Question: Preparing for an exam in statistics, I have been pondering the following problem:

Given that in country X 14% of people hold a university degree, find the probability that for a random sample of size 200 the standard deviation is less than 20.

Trying to compute this resulted in ridiculously high values for the chi-square-distribution.
Any input would be warmly welcomed.
Comment: OK, I'm still not sure I understand the question. What conditions would constitute a standard deviation of 20 on the sample? Would you be measuring the square root of 200*p*(1-p), where p is the percentage of people in the sample who hold a university degree and compare that number to 20?
Comment: I'm sure I'm misunderstanding this problem. Are you sure you don't mean "the number of people with a degree is less than 20?" This is a binary variable, I don't see how standard deviation would apply?
Comment: no, it's how I put it. If it was phrased like your problem, we could use the normal approximation to the binomial distribution.
Answer: Sometimes on exams you just have to answer them literally as written.  It helps to explain and justify your interpretation.  In this case presumably the question refers to the university degree as coded with a binary ($0/1$) variable.  Let's assume it really does ask about samples with a standard deviation less than $20$.
There are just $201$ possible samples, parameterized by their total, $k$.  The mean of such a sample is $k/200$ and therefore its variance (without assuming any bias correction factor) is the average squared deviation from this mean, equal to
$$V(k) = \frac{1}{200}\left(k(1 - k/200)^2 + (200-k)(0 - k/200)^2\right) = k - k^2/200.\tag{1}$$
This attains its maximum when $k=100$, at which point it equals
$$V(100) = 100 - 100^2/200 = 50.$$
Since a standard deviation of $20$ corresponds to a variance of $20^2 = 400$, it is certain that the standard deviation will be less than $20$.  The answer, then, is $1$.

Using $1/199$ instead of $1/200$ as the factor in formula (1), to correct for bias, will not change this answer.


Interpret $\prod_{n=3}^\infty 1- \frac{1}{n\choose 2}$ as a probability

Question: Find the infinite product
$$\prod_{n=3}^\infty 1- \dfrac{1}{n\choose 2}$$
It is quite simple to expand and cancel alternating terms to obtain $\frac13$ as the answer.
However, notice how the expression looks the product of "not" probabilities of some event iterated over different sample spaces. All I want is a simple probabilistic proof of this evaluation.
One can do this by finding a bijection between this expression and that event. For example, I thought of the situation as having bags having $2,3,4,\dots$ balls respectively. Now we select $2$ balls from each bag one by one, and write the probability of not coming up with a specific pair of balls from each bag. This is exactly equal to the given expression.
Update: Check @Ian's answer for such a bijection. Now the problem remains to connect it to 1/3.
Answer: A simple interpretation: you have a bag containing two red balls and a blue ball. You draw two balls, at least one is blue. You replace the balls you drew and throw in another blue ball. You draw two balls, at least one is blue. Your quantity is the probability of this chain continuing forever, instead of being terminated by drawing both of the red balls at some point.
Comment: @Ian I think they are trying to say that they want a probability space and event $E$ where the equalities $P(E)=\prod (1-\binom{n}2^{-1})$ and $P(E)=1/3$ are both obvious. In your situation, only the first is obvious. That is, they want a clever, probabilisitic proof that $\prod (1-\binom{n}2^{-1})=1/3$.
Comment: @user567629 I don't understand your meaning at all.
Comment: Yeah good... but let's search for a way to write this probability as some other workable expression.  i.e., LHS = Situation = RHS, where LHS is the question and RHS is a rewritten workable "answer".
Comment: @MikeEarnest I'm not sure how easy that's going to be to do...consider that the analogous situation where there is just one red ball has a completely different outcome (in that case the limiting probability is zero, a consequence of the divergence of the harmonic series).


Customize Windows Form Scrollbar

Question: I have searched the world wide web without a proper answer.
In my Windows Form application, i want to change the width of a scrollbar that belongs to a FlowLayoutPanel.
The Scrollbar is added "automatically" since the content of the Flow Layout Panel is larger the Form.
From what I've found on the web, it seems to be tricky.
Is there any solution to this?
Cheers!
Answer: No, there's no way to change the width of a scrollbar displayed on a single control (although there is a system-wide setting that will affect all scrollbars in all applications).
The ugly truth is that the lowly scrollbar control is far more complicated than it looks. Basically, the scrollbars on the FlowLayoutPanel are drawn by Windows itself (rather than the .NET Framework) because of the WS_HSCROLL and/or WS_VSCROLL window styles that are set for the control behind the scenes. The FlowLayoutPanel doesn't provide any facility to change or modify how these built-in scrollbars are drawn. Unlike other more advanced modifications in WinForms, there are no such messages we can send to the control's window procedure. And to make matters worse, the scrollbars are drawn in the non-client area of the FlowLayoutPanel, which means we can't just override its Paint event and handle drawing the scrollbars ourselves.
Unfortunately, if you really want to customize your scrollbars, you're going to have to hide the built-in scrollbars and roll your own. It's not quite as difficult as it sounds, though, if you're up for it. This article on CodeProject provides a good walk-through on creating your own skinnable scrollbar as a user control and use it as a replacement in the container control of your choice.
Comment: Thank you very much for the answer Cody Gray! I will look into the Article you linked. I hope this help others that are looking for the same information.
Comment: @Anders: I just realized that the article is in C# and your question is tagged as VB.NET, but converting between the two is relatively straight-forward. If you run into trouble, try one of the online converters [like the one provided by DeveloperFusion](http://www.developerfusion.com/tools/convert/csharp-to-vb/). I'm glad I could help!
Comment: Yeah, well thats not a problem :) If i can just get the logic for it i'll do it myself. Can't be lazy you know! ;) Thanks for the heads up though!
Answer: Cody Gray's answer is 100% correct, though I wanted to add more reference material on the subject matter.
Background
The way that Windows Forms creates scrollbars is through using the window styles WS_HSCROLL and WS_VSCROLL. Respectively, these styles are responsible for enabling the horizontal and vertical scrollbars for a given HWND. An HWND is a native resource handle to a "window", which in .NET lingo corresponds to a Control.
Thinking from a Windows API perspective, we must set window styles at the time we create the HWND. This is done through a call to CreateWindow, CreateWindowEx, or SetWindowLong. Naturally, we may begin to think about using P/Invoke to help us out, but this would be quite a burden as it means we would need to re-implement Windows Forms from scratch.
Fortunately, Windows Forms exposes a property, CreateParams, that can be overridden to specify the exact window styles, among other Control creation parameters. This property is in turn consumed by the .NET framework so that it can create the HWND with the appropriate styles when the Control is instantiated.
Customizing the Scrollbar
Replacing the Windows API functionality for a scrollbar is actually simpler than it may seem; however, this isn't obvious (well for me anyways, I had to sift through .NET source to find the answer). To do this, we must choose the appropriate Control to inherit from to create our own custom ScrollableControl. If we observe the source code for System.Windows.Forms.ScrollableControl, we see the following styles are used:
CreateParams cp = base.CreateParams;

if (HScroll || HorizontalScroll.Visible) {
    cp.Style |= NativeMethods.WS_HSCROLL;
}
else {
    cp.Style &= (~NativeMethods.WS_HSCROLL);
}
if (VScroll || VerticalScroll.Visible) {
    cp.Style |= NativeMethods.WS_VSCROLL;
}
else {
    cp.Style &= (~NativeMethods.WS_VSCROLL);
}

So, in short, when we extend from ScrollableControl, the native horizontal and vertical scrollbars are enabled based on its internal logic. We could access the ScrollableControl's window handle and then call SetWindowLong to hide the scrollbars; however, we would need to keep track of all places that ScrollableControl interacts with the Windows API. In fact, there is an internal function Control.UpdateStylesCore() that is called based on whether or not the scrollbars should be shown. This function effectively reapplies the windows styles above, and it would likely be best not to fight with it. It would be a much cleaner approach to steer away from the Windows API and extend directly from Control. We can then provide whatever API's we desire to have.
This means we would be looking at re-implementing:

Updating scrollbars for mouse wheel events.
Updating scrollbars based on clicking the custom scrollbar buttons and tracks/thumbs.
Updating scrollbars based on adding/removing/moving/resizing child controls.
Creating auto-scroll margins.
Constraints on the client area that affects when scrollbars are visible.
And so on...

Alternatively, a simple approach might be to create a new UserControl. This would allow us to use the Visual Studio designer to simplify configuring our scrollbar buttons and tracks.
Whichever path is taken, it will be necessary to see how ScrollableControl works internally in order to provide a comfortable user-experience.
Answer: This if for C# and in relation to the Article Posted in Accepted Answer by Cody Gray https://stackoverflow.com/a/4326046/4342139 .I'd comment directly there but I'm missing reputation for that.
If you are like me and following the article from Cody Gray's answer, then to hide the scroll bar you'd be using inner and outer panels. This is not optimal solution and quite frankly 'weird and hacky'.I stumbled upon similar problem with horizontal scroll bar and managed to find a solution, and the same thing worked for vertical scroll. It is a bit less hacky way (but not by a lot) and can be achieved with the code below:
    panel1.AutoScroll = false;

    panel1.VerticalScroll.Maximum = 0;
    panel1.VerticalScroll.Visible = false;

    panel1.HorizontalScroll.Maximum = 0;
    panel1.HorizontalScroll.Visible = false;

    panel1.AutoScroll = true;

Notes: Pick Veritcal or Horizontal or both from the code above.
It is critical to have AutoScroll Set to false and then to true as otherwise settings are not applied or AutoScroll is disabled.
Setting Vertical/Horizontal Scroll Maximum to 0 seems to be only thing that is needed, but throwing Visible to false does not appear to hurt it(doesn't appear to work at all but maybe I am missing something).

Customize Windows Form Scrollbar


Where is my loop evaluating wrong?

Question: I'm writing a Visual Basic program to emulate a Tic Tac Toe game. I have a method that, to my knowledge, should correctly draw the board and fill it with Xs and Os appropriately. However when I test it, it will only draw them in the same row.
"Sub board" draws everything, testing for existing values of "x" and "o" and respectively calls "drawX" or "drawO", passing the coordinates to draw.
Sub Main()
    Dim start As String = String.Empty
    Dim x As ArrayList = New ArrayList
    Dim o As ArrayList = New ArrayList
    Dim choice As String = String.Empty
    o.Add("1")
    o.Add("5")
    o.Add("9")

    While True
        board(x, o)
        pause()
    End While
End Sub

Sub pause()
    Console.WriteLine("Press enter to continue...")
    Console.ReadLine()
End Sub

Sub board(x As ArrayList, o As ArrayList)
    Console.ForegroundColor = 8
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("**********************************************************")
    Console.WriteLine("**********************************************************")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("**********************************************************")
    Console.WriteLine("**********************************************************")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")
    Console.WriteLine("                  **                  **                  ")

    Dim ver As Integer = 1
    Dim hor As Integer = 4
    Dim vSpace As Integer = 11
    Dim hSpace As Integer = 20
    Dim vPos As Integer = 0
    Dim hPos As Integer = 0
    For i As Integer = 1 To 9
        If 1 <= i <= 3 Then
            vPos = ver
            Select Case i
                Case 1
                    hPos = hor
                Case 2
                    hPos = hor + hSpace
                Case 3
                    hPos = hor + (hSpace * 2)
                Case Else
            End Select
        End If
        If 4 <= i <= 6 Then
            vPos = ver + vSpace
            Select Case i
                Case 4
                    hPos = hor
                Case 5
                    hPos = hor + hSpace
                Case 6
                    hPos = hor + (hSpace * 2)
                Case Else
            End Select
        End If
        If 7 <= i <= 9 Then
            vPos = ver + (vSpace * 2)
            Select Case i
                Case 7
                    hPos = hor
                Case 8
                    hPos = hor + hSpace
                Case 9
                    hPos = hor + (hSpace * 2)
                Case Else
            End Select
        End If
        Select Case True
            Case x.Contains(CStr(i))
                drawX(hPos, vPos)
            Case o.Contains(CStr(i))
                drawO(hPos, vPos)
        End Select
    Next i
End Sub

Sub drawX(hPos As Integer, vPos As Integer)
    Console.ForegroundColor = 6
    Console.SetCursorPosition(hPos, vPos)
    Console.Write("**      **")
    Console.SetCursorPosition(hPos, vPos + 1)
    Console.Write(" **    **")
    Console.SetCursorPosition(hPos, vPos + 2)
    Console.Write("  **  **")
    Console.SetCursorPosition(hPos, vPos + 3)
    Console.Write("   ****")
    Console.SetCursorPosition(hPos, vPos + 4)
    Console.Write("  **  **")
    Console.SetCursorPosition(hPos, vPos + 5)
    Console.Write(" **    **")
    Console.SetCursorPosition(hPos, vPos + 6)
    Console.Write("**      **")

End Sub

Sub drawO(hPos As Integer, vPos As Integer)
    Console.ForegroundColor = 3
    Console.SetCursorPosition(hPos, vPos)
    Console.Write("  ******")
    Console.SetCursorPosition(hPos, vPos + 1)
    Console.Write(" ********")
    Console.SetCursorPosition(hPos, vPos + 2)
    Console.Write("**      **")
    Console.SetCursorPosition(hPos, vPos + 3)
    Console.Write("**      **")
    Console.SetCursorPosition(hPos, vPos + 4)
    Console.Write("**      **")
    Console.SetCursorPosition(hPos, vPos + 5)
    Console.Write(" ********")
    Console.SetCursorPosition(hPos, vPos + 6)
    Console.Write("  ******")
End Sub

Answer: I'd be looking at this type of construct:
If 1 <= i <= 3 Then

I'm pretty certain that would evaluate 1 <= i and then compare the result of that with 3. Since the result of a boolean expression is either -1 for true or 0 for false, that expression would always evaluate as true.
You should instead opt for something like:
If 1 <= i And i <= 3 Then ' could also use AndAlso '

(and ditto for the other similar lines).
Comment: Thank you! Can't believe I didn't think of that haha... I spent more time in java than vb and I thought it always worked in java. Anyway I adapted this to i<4, i<7, else
Answer: The line of code below (and other lines like it) does not do what you think:
If 4 <= i <= 6 Then

What actually happens here is that first just the 4 <= i expression is evaluated. Then the boolean result from that expression is used for the <= 6 comparison. To make this comparison, the boolean must first be converted to an integer. The boolean conversion back to integer results in either a 0 (false) or -1 (true) (reference). Both of those are less than 6, and so this full line of code will always result in True.
You need to write it like this, instead:
If 4 <= i AndAlso i <= 6 Then

BTW, are you sure Option Strict is turned on? Because it should be, and if it were I'd expect a compiler error when you try to compare a boolean to an integer. Don't write code without Option Strict, or at least Option Infer. They help greatly to avoid mistakes like this.
Answer: While the answers given so far are correct - you should be using AndAlso - there is another way of looking at the issue.
Your entire For i As Integer = 1 To 9 loop can be simply replaced by this:
    For Each i In x
        drawX(hor + hSpace * ((i - 1) Mod 3), ver + vSpace * ((i - 1) \ 3))
    Next
    For Each i In o
        drawO(hor + hSpace * ((i - 1) Mod 3), ver + vSpace * ((i - 1) \ 3))
    Next

This is more directly computing the position of the letter.
I would even go further and rewrite your code like this:
Option Strict On

Module Module1

    Sub Main()
        Dim x = New List(Of Integer)() From {2, 4, 7}
        Dim o = New List(Of Integer)() From {1, 5, 9}
        While True
            board(x, o)
            pause()
        End While
    End Sub

    Sub pause()
        Console.WriteLine("Press enter to continue...")
        Console.ReadLine()
    End Sub

    Sub board(x As List(Of Integer), o As List(Of Integer))
        Console.ForegroundColor = ConsoleColor.DarkGray

        Dim vSpace As Integer = 11
        Dim hSpace As Integer = 20
        Dim ver As Integer = 1
        Dim hor As Integer = 4

        For i = 1 To 2
            For j = 0 To 3 * (vSpace - 1)
                Console.SetCursorPosition(i * hSpace - 2, j)
                Console.Write("**")
            Next
        Next

        For j = 1 To 2
            Console.SetCursorPosition(0, j * vSpace - 2)
            Console.Write("".PadRight(3 * hSpace - 2, "*"c))
            Console.SetCursorPosition(0, j * vSpace - 2 + 1)
            Console.Write("".PadRight(3 * hSpace - 2, "*"c))
        Next

        For Each i In x
            drawX(hor + hSpace * ((i - 1) Mod 3), ver + vSpace * ((i - 1) \ 3))
        Next
        For Each i In o
            drawO(hor + hSpace * ((i - 1) Mod 3), ver + vSpace * ((i - 1) \ 3))
        Next

    End Sub

    Sub drawX(hPos As Integer, vPos As Integer)
        drawLetter(hPos, vPos, ConsoleColor.DarkYellow,
        {
            "**      **",
            " **    **",
            "  **  **",
            "   ****",
            "  **  **",
            " **    **",
            "**      **"
        })
    End Sub

    Sub drawO(hPos As Integer, vPos As Integer)
        drawLetter(hPos, vPos, ConsoleColor.DarkCyan,
        {
            "  ******",
            " ********",
            "**      **",
            "**      **",
            "**      **",
            " ********",
            "  ******"
        })
    End Sub

    Sub drawLetter(hPos As Integer, vPos As Integer, color As ConsoleColor, letter As String())
        Console.ForegroundColor = color
        For i = 0 To 6
            Console.SetCursorPosition(hPos, vPos + i)
            Console.Write(letter(i))
        Next
    End Sub

End Module

Comment: While I likely won't be revising my code to this extent for this particular program, I like your suggestions and will keep them in mind for future developments. =) I also have to say thank you for the time and effort you put into this response.
Comment: @user3582362 - No trouble. It was a fun exercise in refactoring. I hope that you might be able to use some of the techniques in the future.

Where is my loop evaluating wrong?


Automorphisms of the field of rational functions $\Bbb C(t)$

Question: Given the field of rational functions $\Bbb C(t)$, how do we show that a certain function defines an automorphism. I ask because I read here https://nptel.ac.in/courses/111101001/downloads/problemset8.pdf. That $\sigma(t)=wt$, defines an automorphism but automorphisms must be isomorphisms which implies that $\sigma(u*v)=\sigma(u)*\sigma(v)$. But it seems to me $\sigma(uv)=wuv\neq w^2 uv=\sigma(u)\sigma(v)$.
What I think might be the case :
We're dealing with $\Bbb C(t)=\{\tfrac{f(t)}{g(t)}|f,g \in \Bbb C[x], g(t) \neq0 \}$.
So we should then apply our element as follows :
$\sigma(\tfrac{f(t)}{g(t)})=\tfrac{f(\sigma(t))}{g(\sigma(t))}=\tfrac{f(wt)}{g(wt)}$.
But then in terms of showing this is an automorphism , I'm not sure how to proceed , $f,g$ are just arbitrary functions so I don't understand how could manipulate such functions to show $\sigma(\tfrac{f(t)}{g(t)}\tfrac{h(t)}{k(t)})=\sigma(\tfrac{f(t)}{g(t)})\sigma(\tfrac{h(t)}{k(t)})$.
Could anyone clarify this point for me ?
Note: The link isn't from a course I'm in , I just found it while searching for information on Galois theory.
Comment: You have only been given one value of $\sigma$. Namely $\sigma(t)=1/t$. You need to extend this to a full definition such that the extension is an automorphism. Try to see what would be the value of $\sigma$ at some particular cases. For example $\sigma(t^n)$, or $\sigma(p(t))$ for $p$ a polynomial. Then try to prove that you will need to have $\sigma(r(t))=r(1/t)$ for any rational function $r$.
Comment: In both cases you are being given only one value of each automorphism: $\sigma(t)=wt$ and $\tau(t)=1/t$. Yes, this implies that $\tau(r(t))=r(1/t)$, which follows from the properties that an automorphism must satisfy. Likewise $\sigma(r(t))=r(wt)$, instead of multiplication by $w$, as in $wr(t)$.
Comment: @user647486 It was actually supposed to be $\sigma(t)=wt$, but I'm sure your comment still stands. But I'm afraid I don't understand what you mean Shouldn't we always have that $\sigma(r(t))=r(1/t)$, simply by the fact that it will always act on the indeterminate t in r(t). Or is what you mean that we must show that we must show it acts on the intederminate t but keeps the ground field $\Bbb C$ fixed ?
Comment: Yes, $\sigma(r(t))=r(wt)$. A nitpick: it was left out from the description that rules like $\sigma(t)=1/t$ and $\sigma(t)=wt$ define a unique $\Bbb{C}$-automorphism of $\Bbb{C}(t)$. This means that $\sigma(z)=z$ for all $z\in\Bbb{C}$. Anyway, if $\sigma(t)=wt$ then $\sigma(t^2)=(\sigma(t))^2=w^2t^2$ et cetera.
Comment: In other words, $t$ is not an arbitrary element of the field $\Bbb{C}(t)$. It is the prescribed transcendetal element, a generator of the extension $\Bbb{C}(t)/\Bbb{C}$. What's going on here is not at all unlike the fact that a $\Bbb{Q}$-automorphism $\sigma$ of $\Bbb{Q}(\sqrt2+\sqrt3)$ is fully determined once you specify $\sigma(\sqrt2+\sqrt3)$. A difference here is that $t$ is not algebraic. So its image $\sigma(t)=q\in\Bbb{C}(t)$ is only constrained by the fact that we must have $\Bbb{C}(t)=\Bbb{C}(q)$ (for otherwise the resulting mapping won't be bijective). That's for the next lecture!
Answer: Presumably $w$ is a non-zero complex number.
The definition of $\sigma$ means that $$\sigma(f)=f\circ\psi,$$where $$\psi(t)=wt.$$That should make it clear that $\sigma(f+g)=\sigma(f)+\sigma(g)$, etc.


Como num listener, atribuído a mais de um Spinner, saber quem o chamou?

Question: Eu estou usando 4 spinners em uma única activity e preciso receber a informação de cada Spinner. A questão é que pra usar o Spinner é usado o método "onItemSelected", e deve atribuir o valor de uma variável a "parent.getItemAtPosition(position).toString();".
A questão é que eu tô usando 4 spinners dentro desse mesmo método, e preciso atribuir o "parent.getItemAtPosition(position).toString();" em 4 variáveis diferentes, porém, tá atribuindo o mesmo spinner às 4 variáveis.
Como faço pra diferenciar os spinners sendo que estão sendo usadas no mesmo método?
Answer: Primeiramente, é sempre melhor colocar o código que você chegou a fazer, ou pelo menos uma representação, se não for possível colocar o código original.
De qualquer forma, vou assumir que você está implementando a interface OnSelectedItemListener na sua Activity e passando essa instância para seus Spinners:
public class MainActivity implements OnItemSelectedListener {

(...)

spinner.setOnItemClickListener(this);

Acontece que, dessa forma, você só tem um listener para 4 Spinners, quando na verdade você precisa de 4 listeners.
Uma forma de implementar esses 4 listeners seria:
spinner1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 1
    }
});

spinner2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 2
    }
});

spinner3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 3
    }
});

spinner4.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // tratar cliques do Spinner 4
    }
});

Comment: Eu tinha feito isso mesmo e funcionou, esse era o problema.
Valeu amigo! :)
Answer: O método onItemSelected recebe, no parâmetro parent, o Spinner cujo item foi seleccionado.
Para saber qual é esse Spinner basta verificar o seu id .
Qualquer coisa assim:
public void onItemSelected(AdapterView<?> parent, View view,
        int pos, long id) {
    if(parent.getId() == R.id.spinner1){
        variavel1 = parent.getItemAtPosition(position).toString();
    }
    else if(parent.getId() == R.id.spinner2){
        variavel2 = parent.getItemAtPosition(position).toString();
    }
    ...
    ...
}

Eventualmente, por uma questão de organização, manutenção e/ou melhor legibilidade, poderá ser preferível ter um listener por cada um dos Spinner.


How To Initialize Foundation 3 To Use Orbit?

Question: I am trying to use a script I found in this question to run Orbit in Foundation 3, but I can not get it to initialize properly. I added this script in the footer and Foundation.min.js in the header. I get a no method 'foundation'  error on line 3 in my console it doesn't work.
Answer: The script in that SO thread you linked to will not work for your because it uses Foundation 4. Orbit is initialized differetly in Foundation 3 (F3). So suppose you have an element with id orbitX. You initialize it like this:
$("#orbitX").orbit();

In the other SO question you asked

where would you add additional settings?

You do it when you initialized your orbit element like this:
$("#orbitX").orbit({
    bullets: false; // to hide the bullets
});

Here is the complete set of options
$('#orbitX').orbit({
  animation: 'fade',                  // fade, horizontal-slide, vertical-slide, horizontal-push
  animationSpeed: 800,                // how fast animtions are
  timer: true,                        // true or false to have the timer
  resetTimerOnClick: false,           // true resets the timer instead of pausing slideshow progress
  advanceSpeed: 4000,                 // if timer is enabled, time between transitions
  pauseOnHover: false,                // if you hover pauses the slider
  startClockOnMouseOut: false,        // if clock should start on MouseOut
  startClockOnMouseOutAfter: 1000,    // how long after MouseOut should the timer start again
  directionalNav: true,               // manual advancing directional navs
  captions: true,                     // do you want captions?
  captionAnimation: 'fade',           // fade, slideOpen, none
  captionAnimationSpeed: 800,         // if so how quickly should they animate in
  bullets: false,                     // true or false to activate the bullet navigation
  bulletThumbs: false,                // thumbnails for the bullets
  bulletThumbLocation: '',            // location from this file where thumbs will be
  afterSlideChange: function(){},     // empty function
  fluid: true                         // or set a aspect ratio for content slides (ex: '4x3')
});

Comment: You're welcome. [This](http://foundation.zurb.com/old-docs/f3/javascripts.php) maybe what you're looking for.
Comment: Thanks again for all of your help Von. I found [this page](http://foundation.zurb.com/docs/javascript.html) on initializing Foundation 4's Javascript buried in the docs. Do you know of a similar file for Foundation 3?


Acoustic strings on electric guitar

Question: new here.
I needed new strings, being a newbie I just told the clerk that I needed some 11's, one pair for my electric and one for my acoustic western. When I came home I saw that I got two pairs of acoustic strings. My question: Does it really matter, the strings I got were these:
RotoSound JK11
RotoSound TB11
Any of these that a better suited for a strat type guitar? or is it so bad i should go back and get other strings? .. Help much appreciated
Answer: To elaborate on Tim's accurate answer - electric guitars have magnetic pickups which detect the movement and vibration of the strings (as Tim said).  Therefore electric strings usually use a nickel winding around a steel core so the magnet will "pick-up" the vibration of the strings.
Both of the acoustic sets you linked use a bronze alloy (as do most acoustic strings) for the winding on the wound strings - which will not respond very well to a magnet ("non magnetic") and will insulate the magnetic steel core of your wound strings from the pickups.
The phosphor bronze set (JK) will have a more mellow sound on an acoustic and the TB set is an 80/20 Bronze which will have a brighter more present sound.  Neither will work well on your electric.
The unwound steel strings are the same material on electric sets and acoustic sets so they are basically interchangeable.  Where the difference comes in is on the wound strings.  Nickle winding works best on electric for responding to the magnetic pickup but does not sound so great acoustically.  But that is not a problem on electric guitars because the sound comes from the amplifier and you don't have to worry about what they instrument sounds like acoustically.
As an interesting related aside, you can get "zebra" strings which have alternate Bronze and Nickel Windings if you have an acoustic guitar with a magnetic pickup.  Most acoustic guitar pickups do not use magnets but there are some that do.  The idea behind the "zebra winding" is a compromise to allow for a better acoustic sound than nickel wound strings would provide - while still allowing the magnetic pickups to react to the string vibration.
Answer: Strings specifically made for acoustic guitar don't work well on electric guitars in my experience. The pick ups are designed to pick up(!) the movement of steel strings, and since these have little or no steel in them, they'll be very, very quiet. Need to change them in the shop.
Comment: Okay thanks for the answer, then i suppose that i only have 1 question... Which of the above string would you put on your acoustic ?
Comment: I wouldn't be putting either set on my acoustic, as I use .008 - .042. and they would be too tight for what I've got used to. But for you, either will feel the same, it's really the sound that's going to differ, but that then becomes a personal choice. Suggest keeping both sets, one for spare until it's time to change, then compare their sounds. One really should have a spare set for any guitar one has.

Acoustic strings on electric guitar


Chi-square analog for context-dependent distributions

Question: Lets imagine that we have some experiments. Each experiment may result in one of the outcomes: A, B, C. So we have probabilities distribution for each experiment $P_A, P_B, P_C$ which is context-dependent.
E.g.:

$Context_1 \Rightarrow \{P_A^1, P_B^1, P_C^1\},$ experimental outcome is A
$Context_2 \Rightarrow \{P_A^2, P_B^2, P_C^2\},$ experimental outcome is B
$Context_3 \Rightarrow \{P_A^3, P_B^3, P_C^3\},$ experimental outcome is A
$Context_4 \Rightarrow \{P_A^4, P_B^4, P_C^4\},$ experimental outcome is C

This probabilities are calculated by some function $F:Context\rightarrow \{P_A, P_B, P_C\}$
I want to estimate an absolute trust rate of this function. In other words, I want to be able to say "we can trust this function on 86%" like we do when we deal with Pearson's chi-square test.
Any suggestions?
Comment: How many contexts do you have and how many data points per context?
Comment: The problem is that there are a lot of contexts and only one data point per context in common case.
Comment: I am not sure that you can do statistics on the player's strategy without more data. Either you have enough data and you can train a machine learning algorithm, or you don't and you have to do assumptions on the underlying model you want to use.
Comment: Well you can try but I would not be very confident with the results. Do you want to invest real money into this strategy?
Comment: @fRed I have machine learning algorithm, but I'm not sure about its reliability. No real money, this is an academic research.
Answer: Sounds like you'll need a HMM to do that.
Have you read
Lawrence R. Rabiner (February 1989). "A tutorial on Hidden Markov Models and selected applications in speech recognition"
There are a few examples of models parameters discovery on page 259.
The question is how do you plan to update the probabilites? Maybe you can use a kind of success ratio? (if the player has not managed to win much recently using one of the 3 strategies, he may use it less and try more the two others...)
Comment: Sorry now that you have reformulated your question, my answer is not really appropriate
Comment: That's ok! The first formulation was not clear enough, my bad.
Answer: I may be misunderstanding your question (and falling into the same misunderstanding as fRed despite your explanation), in which case I apologize.  It seems to me like you are saying you already know the various P_A, P_B, and P_C values for each context.  I assume P_A + P_B + P_C = 1? Given those priors and the actual outcome you want to characterize the accuracy of the already established P values?
One approach might be simulation.  Given the various P_A, P_B, and P_C values for each context you could generate guesses from the model at the probabilities indicated by each P value and then compare that to the obtained data.  Averaging over many simulations you should get a sense of the average hit-rate of the model.


Surjective Morphism of affine algebraic variety

Question: I am not able to show explicitly if $X\rightarrow Y$ is a surjective morphism of affine algebraic varieties then the dimension of X is at least as large as the dimension of Y. Need geometric interpretation also. thank you
Answer: If we are talking maps between affine domains.
Let $A\to B$ be an inclusion of domains which are finitely generated $k$-algebras.
Since dimension of affine domain is equal to its transcendent degree.
And $A\to B$ will give an injection $Q(A)\to Q(B)$, we win.
If just a map of finitely generated $k$-algebras, say $A\to B$ also.
Since the set map $\operatorname{Spec} B\to \operatorname{Spec} A$ is surjective, it follows that the kernel of $A\to B$ consists of nilpotents. So we may assume $A\to B$ is injective. Now the dimension of $A$ is equal to its transcendental degree, it gives that $\operatorname{dim}B\geq\operatorname{dim}A$.


Doubt about Probability measure in Lebesgue Inegral exercise.

Question: I am working my way through the book Basic Stochastic Processes from Springer Undergraduate Mathematics Series and there is a step in one of the excerices' solutions that I can not understand.
The exercice 1.9 goes like this:
Show that if $\eta: \Omega \rightarrow [0,\infty)$ is a non-negative square integrable random variable, then
$E(\eta²)=2\int_0^\infty tP(\eta>t)dt.$
The solution starts as follows:
Let $F(t)=P\{\eta\leq t\}$ be the distribution function of $\eta$. Then
$E(\eta²)=\int_0^\infty t²dF(t).$
Since $P(\eta>t)=1-F(t)$, we need to show that
$\int_0^\infty t² dF(t) = 2\int_0^\infty t(1-F(t))dt$
The next step and the one I do not understand is this one:
$\int_0^a t² dF(t) = \int_0^a t² d(F(t)-1)$
After this it goes on with integration by parts which I can follow.
Any help would be appreciated, I do not understand how $dF(t)$ seems equivalent to the same probability measure minus 1. I am obviously missing something.
Comment: $dF(a,b])=F(b)-F(a)$ . The increments define the integral with respect to $dF(t)$. If we call $G(t)= F(t)-1$, then  $dG((a,b])=G(b)-G(a)=F(b)-F(a)$. In other words the Stieljes integral is the same.
Comment: Wow, how could I miss that? Can you put that as an answer so I can accept it @FOE?
Answer: $dF(a,b]=F(b)-F(a)$.
The incrementa define the integral with respect yo $dF(t)$.
If we call$$ G(t):=F(t)-1 $$then the stieljes integrals with respect yo F and G Will ve the same because $dF(a,b] $clearly is equal to $ dG(a,b].$
A sidenote: the notation $ d(F(t)-1) $ can ve tricky, You are not translating the measures , maybe that was the confusión.


How to parse Javascript object in redis lua script

Question: I am using node_redis npm package to call lua function. I want to pass javascript object to lua.
Below is sample json object:
var feeds=[];
var feed ={};
feed.uId ="Zqr6jfu6pgqNpAKaf";
feed.kIds =[];
feed.kIds.push("2557f730-e7a9-11e6-a2e7-49a45a663faf");
feed.kIds.push("224ec110-f9cc-11e6-8f0c-cb2069561ad8");
feeds.push(feed);

I am calling eval function to execute my lua script:
client.eval(
scriptId, //lua source
0,
feeds,
function(err, result) {
console.log(err+'------------'+result);
}
);

In Lua How I can parse this object to insert all kIds in sorted set key of feed.UId ??
Answer: Those are two different languages, you'd have to implement some interface using the low level commands of their respective VMs.
Alternatively, you could convert your object to text and eval it in lua, there seems to be package for that already. String eval is a slow operation, however.


Site-to-Site VPN between a Cisco router and a Linux box

Question: SITE A

A Cisco router (877W), configured for incoming VPN IPSec client connections
Some servers, in a 192.168.0.0/24 network

SITE B

A Linux box with a physical NIC and a vpnc client (tun0/220.127.116.11, sent by the Cisco router of Site A), routing is enabled
Some workstations, in a 192.168.1.0/24 network

The problem
While Site B can successfully access the servers of Site A with their LAN address, servers in Site A can only ping the Linux box with his VPN address. They are unable to access the workstations in the 192.168.1.0/24 LAN.
Cisco router configuration
crypto isakmp policy 1
 encr 3des
 authentication pre-share
 group 2
crypto isakmp client configuration address-pool local dynpool
!
crypto isakmp client configuration group groupxxx
 key xxxx
 pool dynpool
 acl 105
crypto isakmp profile ciscocp-ike-profile-1
   match identity group groupxxx
   client authentication list ciscocp_vpn_xauth_ml_1
   isakmp authorization list ciscocp_vpn_group_ml_1
   client configuration address respond
   virtual-template 2
!
!
crypto ipsec transform-set ESP-3DES-SHA esp-3des esp-sha-hmac
!
crypto ipsec profile CiscoCP_Profile1
 set transform-set ESP-3DES-SHA
 set isakmp-profile ciscocp-ike-profile-1

access-list 10 permit 192.168.1.0 0.0.0.255
access-list 10 permit 22.214.171.124 0.0.0.255
access-list 10 permit 192.168.0.0 0.0.0.255
access-list 105 permit ip 184.108.40.206 0.0.0.255 192.168.0.0 0.0.0.255
access-list 105 permit ip 192.168.0.0 0.0.0.255 188.8.131.52 0.0.0.255

Thanks by advance.
Answer: Add
ip route 192.168.1.0 255.255.255.0 220.127.116.11

on the cisco router and see if that works.
Edit:
And do you have any kind of NAT in the mix?
Comment: Already tried that, with no success. Yes, there's NAT on the Cisco, some port-forwarding rules and an overload to permit Internet access to servers on Site A.


Custom field not saving updates

Question: I've created a widget which has two textfields and a hidden uniqid. One of these fields is for the name of an item, the other is the number of people who can be involved in that item. These save without any problem, and they re-populate on the edit page correctly, but if I change the values, they do not update correctly.
I am not a Drupal expert, so I am uncertain how much code will be required for diagnosis. These seem to be the most relevant parts, but there is a volunteers_field_is_empty, volunteers_field_validate, volunteers_schema, and a volunteers_field_formatter_view, as well as empty volunteers_field_insert, volunteers_field_formatter_prepare_view, and volunteers_preprocess_node.
function volunteers_field_info() {
  $t = get_t();
  $fields = array();
  $fields['volunteers_item'] = array(
    'label' => $t('Volunteer item'),
    'description' => $t('A position for volunteers'),
    'default_widget' => 'volunteers_field_widget',
    'default_formatter' => 'volunteer',
    'settings' => array('length' => 255)

  );
  return $fields;
}

function volunteers_field_widget_info() {
  $t = get_t();
  return array(
    'volunteers_field_widget' => array(
      'label' => $t('Volunteers widget'),
      'field types' => array('volunteers_item'),
      'settings' => array(),
      'behaviors' => array(
        'default value' => FIELD_BEHAVIOR_NONE
      )
    )
  );
}

function volunteers_field_schema($field) {
  $schema = array();
  switch($field['type']) {
    case 'volunteers_item':
      $schema['columns'] = array(
        'position_title' => array (
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE
        ),
        'position_count' => array (
          'type' => 'int',
          'sortable' => TRUE,
          'default' => 1,
          'unsigned' => TRUE
        ),
        'unique_id' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE
        )
      );
      break;
  }
  return $schema;
}

function volunteers_field_widget_form_alter(&$element, &$form_state, $context) {
  $type = $context['field']['type'];
  $lang = $context['langcode'];
  $delta = $context['delta'];
  if($type == 'volunteers_item' && isset($context['items'][$delta])) {
    $item = $context['items'][$delta];
    $element['position_title']['#value'] = $item['position_title'];
    $element['position_count']['#value'] = $item['position_count'];
    $element['unique_id']['#value'] = $item['unique_id'];
  }
}

function volunteers_field_widget_form(&$form, &$form_state, $field, $instance,
  $lang, $items, $delta, $element) {

  $t = get_t();
  $type = $instance['widget']['type'];
  switch ($type) {
    case 'volunteer_field_widget':
    case 'volunteers_field_widget':
      $element['position_title'] = array(
        '#type' => 'textfield',
        '#length' => 255,
        '#title' => $t('Position name'),
        '#weight' => 0,
        '#delta' => $delta,
        '#size' => 'big'
      );

      $element['position_count'] = array(
        '#type' => 'textfield',
        '#weight' => 1,
        '#length' => 10,
        '#delta' => $delta + 1,
        '#title' => $t('Number of participants'),
      );

      $element['unique_id'] = array(
        '#type' => 'hidden',
      );
      break;
  }

  return $element;
}

function volunteers_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if($field['type'] == 'volunteers_item'){
    foreach($items as &$item) {
      // setting default values.
      $count = $item['position_count'];
      if(!$count) $count = 1;
      $item['position_count'] = $count;
      if(!isset($item['unique_id'])) {
        $item['unique_id'] = uniqid(rand(),1);
      }
    }
  }
}

Answer: The problem is with volunteers_field_widget_form and volunteers_field_widget_form_alter. volunteers_field_widget_form_alter was preventing updates. If I set the default_value of the relevant elements appropriately in volunteers_field_widget_form, Drupal both allows updates and displays correctly.
$element['position_title'] = array(
  '#type' => 'textfield',
  '#length' => 255,
  '#title' => $t('Position name'),
  '#default_value' => isset($items[$delta]['position_title']) ? $items[$delta]['position_title'] : null,
  '#weight' => 0,
  '#delta' => $delta,
  '#size' => 'big'
);

Answer: In case anyone coming here with trouble of fields not being saved, try removing conditional fields. Sometimes conditional fields might clear fields before saving if not configured correctly.

Custom field not saving updates


Extension "IntelliSense for CSS class names in HTML" not work on file .cshtml

Question: I create project MVC.Net Core by VSCode and VSCode have extension "IntelliSense for CSS class names in HTML". The problem is when I type class like "btn btn-primary" IntelliSense not show, I have to press Ctrl+Spacebar everytime when I type class.
How to solve this problem?
Answer: You can try to click Ctrl+Shift+P,and choose cache css definitions,and then click to cache it like this:


Redirect all pages to a form unless the user has filled out some information (Drupal 7)

Question: I need to bring up some sort of dialog or form to collect user information when they first login. Is there anyway that the user can be redirected to a form that they must fill out before they can proceed when they first login?
I need to do this because we need to collect information from users who have already created accounts and will not have entered the information that we are adding to the user node.
EDIT: I really want to force the user to fill out this form if they have not, so what I am really looking for is a way to redirect all pages on the Drupal site to this form unless they have filled it out.
Comment: Have you looked into using the rules module for this? The 1st pseudo rule might be when user logs in if form field does not have value redirect to form page. Then if they navigate away from saving something along the lines of if user looks at page and field does not have value redirect to form. This is assuming you're using some sort of field on the user profile.
Comment: +1 @pokermoneyclips suggestion, use rules. If the form is not filled out, redirect back to the form.
Answer: This should do it. although there might be a module that already does this as well.
https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_login/7
Comment: This is a helpful hook but if this hook just redirected to my form they could just navigate away without filling out the form. I am wondering if there is a way to basically redirect all pages to the form until they fill it out?


Is it possible to profile for file system interaction in Ruby?

Question: Is it possible to profile a Ruby application to see how much it interacts with the file system?
Background: In the past I've written code that reads files within a loop when it only needs to do so once. I'd like to make sure that I eliminate all such code.
Comment: Well, you know, if it's spending too much percent of wall-time in unnecessary I/O, you'll see it pretty quick with a few random halts. Of course, if you're looking for I/O that *doesn't* take much time, it won't help you there.
Comment: @Mike: I'm in the latter situation.
Comment: Something more like a trace, perhaps, on file opens? Sorry, not much help.
Answer: There are already perfectly capable programs for this purpose out there, that you don't need to duplicate. I don't think you should complicate your program with special logic checking for a relatively obscure programming error (at least, I've never accidentally committed the error you describe). In such cases, the solution is to check a performance characteristic from outside the program. Assuming you are on Linux, I would turn to a test/spec that exercises your code and watches iostat (or similar) in a seperate thread.
Answer: Sure, you can simply require 'profile at the top of a script:
# myscript.rb
require 'profile'
Dir.entries(".").each  { |e| puts e}

$ ruby myscript.rb

(list of filenames...)
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
  0.00     0.00      0.00        1     0.00     0.00  Dir#open
  0.00     0.00      0.00        1     0.00     0.00  Dir#each
  0.00     0.00      0.00        1     0.00     0.00  Enumerable.to_a
  0.00     0.00      0.00        1     0.00     0.00  Dir#entries
  0.00     0.00      0.00       56     0.00     0.00  IO#write
  0.00     0.00      0.00       28     0.00     0.00  IO#puts
  0.00     0.00      0.00       28     0.00     0.00  Kernel.puts
  0.00     0.00      0.00        1     0.00     0.00  Array#each
  0.00     0.01      0.00        1     0.00    10.00  #toplevel

Or you can just pass in an option on the command line:
$ ruby -r profile myscript.rb

If you want finer control over what to profile, take a look at the ruby-prof library.
Answer: I'm a sucker for brute force.
File.open(path, 'r') do |file|
  ...
end
File.mv(path, path + '.hidden')    # Temporary

If the code tries to open the file twice, it won't find it the second time.  After the test, you can reverse the rename with a shell one-liner.  In Bash (and probably in other *nix shells as well):
for i in `ls *.hidden` ; do mv $i ${i%.hidden} ; done


Inverting a negative correlation

Question: is it appropriate to take the absolute value of a correlation coefficient to include in analyses? I am planning a meta-analysis and some of the hypothesized outcome variables might have a negative relationship. To include in one model, would it be okay to use the absolute value of the correlations to be consistent with other coefficients?
Edit: to clarify, I want to include correlation coefficients in a random-effects model for meta-analysis. If the majority of the correlations are positive, could I use the absolute values of the negative correlations if such correlations would have been positive had one of the measures been reverse scored?
Comment: Can you tell us a little more about what you are trying to use these correlation coefficients in? You mention a model -- are you using correlation coefficient as a covariate in another model, and if so, can you say a bit more about that?
Comment: If they would have been reversed, then yes, reverse them. E.g. if one study measure is 'happiness' and another measure is 'depression' then you should reverse them so they are all the same direction. But you shouldn't reverse them just because they are negative.
Comment: Yes, so long as you explain what you are doing.
Answer: If you know that one of the measures was reverse scored, you can do this, because $-\mathit{cor}(X, Y) = \mathit{cor}(-X, Y) = \mathit{cor}(X, -Y)$.
First, notice that the variance of a random variable is unchanged by negation, due to $x^2 = (-x)^2$ and linearity of expectation:
\begin{align}
\text{var}(X)
& = \mathbb{E}\left[X^2\right] - \mathbb{E}\left[X\right]^2 \\
& = \mathbb{E}\left[(-X)^2\right] - (-\mathbb{E}\left[X\right])^2 \\
& = \mathbb{E}\left[(-X)^2\right] - \mathbb{E}\left[-X\right]^2 \\
& = \text{var}(-X)\\
\end{align}
Combining this with the definition of correlation coefficient and linearity of expectation again, we have:
\begin{align}
-\text{cor}(X, Y)
& =
  -\frac{
    \mathbb{E}\left[(X - \mathbb{E}\left[X\right])(Y - \mathbb{E}\left[Y\right])\right]
  }{
    \text{var}(X)\text{var}(Y)
  } \\
& =
  \frac{
    \mathbb{E}\left[(-X - \mathbb{E}\left[-X\right])(Y - \mathbb{E}\left[Y\right])\right]
  }{
    \text{var}(-X)\text{var}(Y)
  }\\
& =
\text{cor}(-X, Y)
\end{align}
However, I would not blindly take the absolute value; this only goes through if you know that $X$ from one study was measured as $-X$ in another study.

Inverting a negative correlation


How to override node comment form template?

Question: I usually override a form template this way.
<code>/**
 * Implementation of hook_theme().
 */
function MODULE_theme() {
  return array(
    'user_login' => array(
      'render element' => 'form',
      'template' => 'user_login',
      'path' => drupal_get_path('module', 'MODULE').'/templates',
    ),
  );
}
</code>
I create templates/user_login.tpl.php in my module folder; then, I can override the form.
I tried overriding a node comment form this way, but it didn't work: The node comment form didn't use my custom template file.
I have googled a lot, but I got nothing about overriding a node comment form template.
How can I force Drupal to use a template file for the node comment form?
Answer: In Drupal 7, and in the case of the user login form, your trick works because the form doesn't set the #theme property; in that case, Drupal will use the theme function whose machine name is equal to the form ID. (For the login for, that is user_login.)
That is not true for the comment form, for which its form build (comment_form()) sets the #theme property.
<code>$form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');
</code>
There isn't a match between the machine name of the theme the form builder wants to use, and the comment-edit form ID; the latter is comment_node_CONTENT_TYPE_form, not comment_form__node_CONTENT_TYPE. If you were defining a comment_form theme function, that should work.
In Drupal 6, there is no #theme property for comment_form, which is the form ID of the comment edit form.
Comment: first, thanks your edit my question to chang some english grammar problem. My english is so terrible. I have read your reply many times. Your idea is : the form_id for node comment form , I should use comment_form ?
Comment: `theme_comment_form()` should be the theme function that Drupal would use for the comment edit form.
Answer: Following code will allow you to use comment-form--node-forum.tpl.php template:
<code>/**
 * Implements hook_theme().
 */
function hook_theme($existing, $type, $theme, $path) {
  return array(
    "comment_form__node_forum" => array(
      'render element' => 'form',
      'template' => "comment-form--node-forum"
    )
  );
}
</code>
Replace 'forum' to your content type.


Matrix probability question

Question: In a book I have been reading recently a question as follows came up as a problem and I am unsure how to solve it:

Two quantities are represented by the matrices
$$   \text{M = }    \left[\begin{array}{rrr}
     3 & 0 & -i \\
     0 & 1 & 0\\
     i & 0 & 3   \end{array}\right] $$
$$   \text{N = }    \left[\begin{array}{rrr}
     3 & 0 & 2i \\
     0 & 7 & 0\\
     -2i & 0 & 3   \end{array}\right] $$
The possible values of the quantity represented by M are 1, 2 and 4.
What are the possible values of the quantity represented by N?
Explain how you know that.

Any help would be greatly appreciated!
Comment: What book is this from?  As stated, the problem is underspecified (and reminds me of the "what comes next in this sequence" type of puzzle).
Comment: [Quantum Mechanics in simple matrix form](http://www.amazon.com/Quantum-Mechanics-Simple-Matrix-Physics/dp/0486445305)
Comment: @Fixee Also, as I'm a beginner, could you elaborate on how the problem is underspecified?
Comment: Without the context given by the book, "quantity represented by $M$" is really vague.  In fact, even **with** the book, it's unclear what this means.  And it's certainly not standard language in mathematics.
Answer: Note that the matrices $M$ and $N$ are self-adjoint. Given that you're reading a book on quantum mechanics, it makes sense to look at their spectrum (set of eigenvalues).
The spectrum of $M$ is $\{1,2,4\}$ and the spectrum of $N$ is $\{1,5,7\}$.
Comment: This is a good suggestion; you can read a substantial portion of the book on Amazon's preview, including the problem the OP asks (on pg 59).  However, in my opinion, the book is just awful.  It introduces matrices assuming the reader has not seen them, and introduces other very elementary ideas (including $i$ as $\sqrt{-1}$) so it's a huge leap to assume the reader would know about eigenvalues, if that was the author's intent.
Comment: See also: http://en.wikipedia.org/wiki/Hamiltonian_%28quantum_mechanics%29
Comment: This sounds like the correct answer, thank you very much! I would agree with Fixee that for the book to spring Eigenvalues on me when it has not even mentioned it yet is a huge leap to expect from readers especially as it is only supposed to assume a basic knowledge of algebra. Thank you all!
Comment: Also, out of interest is there a good web page describing how to calculate the Eigenvalues of 3x3 matrices? From what I've read I'm guessing it comes down to a cubic equation which has to be solved which gives the 3 possible values.
Comment: @Joshua: unfortunately, I don't know one that I can vouch for: try the [Wikipedia page](http://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors) and maybe [this lecture](http://khanexercises.appspot.com/video?v=PhfbEr2btGQ) from Khan Academy helps. In this case I just "saw" the eigenvalues and eigenvectors: the eigenvectors are $\begin{pmatrix} 0 \\ 1 \\ 0\end{pmatrix}$ and $\begin{pmatrix} 1 \\ 0 \\ \pm i\end{pmatrix}$. I would recommend looking at a good linear algebra text, as e.g. one of those [suggested here](http://math.stackexchange.com/questions/87362/linear-algebra-textbook)
Comment: Here's a (less instructive) way to get the eigenvalues: http://www.wolframalpha.com/input/?i=eigenvalues+%5B%7B3%2C0%2C-i%7D%2C+%7B0%2C1%2C0%7D%2C+%7Bi%2C0%2C+3%7D%5D
Comment: Thanks for all the input, @Fixee :)
Comment: @t.b. Thanks for the suggestion, the wikipedia page was of help and I also found another [Khan Academy lecture which focusses specifically on getting the Eigenvalues of a 3x3 matrix](http://www.youtube.com/watch?v=11dNghWC4HI) which was extremely helpful.
Comment: @Fixee I'll certainly use that method when I don't have the energy to do it myself! :)

Matrix probability question


What do we hook in Drupal 6 for inbound URL rewrites?

Question: Where conditional rewrite is desired, not supported by existing path modules, and where we'd prefer to stay out of .htaccess, where might we hook in Drupal 6?
Along the lines of Drupal 7 hook_URL_inbound_alter, I think.
Answer: hook_URL_inbound_alter was introduced as part of a contributed module in Drupal 6 (URL alter), and was moved to core with Drupal 7.
Answer: In Drupal 6, the equivalent of hook_url_inbound_alter() is custom_url_rewrite_inbound() which is not a hook, but a function to put in the settings.php file used by Drupal.
The URL alter module defines that function, and call any implementation of hook_url_inbound_alter() defined from other modules, allowing modules to use the same code for Drupal 6, and Drupal 7.
The same is true for custom_url_rewrite_outbound(), and hook_url_outbound_alter().


How do I add the file size to a view?

Question: After reading and searching through related topics, I have not seen any clear answer about how to show the file size in a Views created file list. Im using Drupal 7 and having File 7.14 field installed.
I was expecting to select a field in Views in order to show it as a third column in a list of files that can be downloaded (after Title and File).
I am not a programmer, and the only related issues I've seen so far is about editing php files.
Currently, as administrator, I see the file size when I edit the node containing the file. Why can this value not be used other than in edit mode?

To be complete I've added the query how it is now:
<code>SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language,   file_managed_file_usage.filesize AS file_managed_file_usage_filesize, 'node' AS  field_data_field_file_node_entity_type
FROM
{node} node
LEFT JOIN {file_usage} file_usage ON node.nid = file_usage.id AND file_usage.type = 'node'
LEFT JOIN {file_managed} file_managed_file_usage ON file_usage.fid = file_managed_file_usage.fid
WHERE (((node.status = '1') AND (node.type IN  ('file'))))
ORDER BY node_title ASC
LIMIT 50 OFFSET 0
</code>
Comment: Did you ever get the issue resolved for file sizes on multiple files? I too have that same issue.
Comment: Hi Adrew. No the issue is still there, but I have to admit that after my additional question about that was deleted here, I didn't put much effort in investigation this further. I had to post another questions at http://drupal.stackexchange.com/questions/45292/how-to-show-filesize-when-content-type-contains-more-than-one-file and received one reply from someone that got this working.
Answer: Try creating a reference to the file.
Under Advanced in your View, and add a relationship (select File Usage: File).  If you now go to add a new field in your view, you should see a few more options under File, one of them being File: Size.
Comment: Thank you for your great explanation which get me to put a third column containing file sizes. However, some of my content types contain 2 files. In the view only the filesize of the first file is shown, not the other ones. Any idea how to fix that?

How do I add the file size to a view?


Where to start with creating the theme for selling?

Question: I have the task to create the Drupal theme from the existing Wordpress theme that will be sold on ThemeForest.
This is the first time that I'm doing something like this, up until now I was doing the themes for concrete clients according to PSD files, but I think that I need different approach for this.
Until now I usually did the themes as Omega sub-theme, can I create the Omega 4 sub-theme in this case? Can I use base theme at all or I must create theme from scratch?
I noticed that a lot of themes are based on Bootstrap, is that maybe the best way for creating the theme or you suggest some other way (I know this is maybe the question for opinion but I'm looking for the simplest way for creating the theme and Bootstrap is maybe one of the most complicated ways, so because of that I need your opinion and suggestion).
It would be really helpful if you could direct me to some page or tutorial where I can find more information and choose the way in which I will create this theme.
Comment: Sorry, but as it's impossible to provide an objective answer to this it's off-topic. Whether Bootstrap (or any theme) is the best for you depends on your knowledge, experience, and how quickly you learn. Similarly, whether you'll personally find it easier to use a base theme or create one from scratch depends on too many unknown factors to be reasonably answered. There's simply no right or wrong answer, and the last thing we want is to create a list of people's personal favourites, as we lose any sense of impartiality. Compiling such lists just isn't something we do here
Answer: Themeforest audience is mostly end users. So, it does not matter what base theme you use as long as it makes you more productive.
That said, unlike Wordpress where you just upload the theme files zip, you will have to create your own distribution with the latest stable Drupal core, the set of contrib modules you want to theme, the base theme(if you are using one) along with your theme files and assets.
I suggest you start with a base theme of your choice rather than roll out from scratch. Its a huge time saver and most base themes come with sensible defaults, especially Omega 4.
Comment: Creating a Drupal theme doesn't require creating a distribution.
Comment: As such, that's true. But if the theme needs to be distributed in Themeforest, it needs to be packed into a distribution.


Is there a way to get NTH_VALUE with a variable N? (SQL - BigQuery)

Question: With a Bigquery table as such:
{"name": "parent_id", "type": "STRING", "mode": "REQUIRED"},
{"name": "parent_x", "type": "INTEGER", "mode": "REQUIRED"},
{"name": "thing_id", "type": "STRING", "mode": "REQUIRED"},
{"name": "created_at", "type": "TIMESTAMP", "mode": "NULLABLE"}

Assuming we have one row per "thing_id" with an associated "created_at"
I'm trying to fetch, for each parent id, the Nth "created_at" where the Nth "thing_id" is registered in my table.
I can use NTH_VALUE() but I want my N to be variable based on parent_x, more specifically I want the MIN("literal integer", parent_x) to be N. The problem is that NTH_VALUE() only accepts a literal or query parameter.
How could I get around this?
The result table I'm looking for is:
{"name": "parent_id", "type": "STRING", "mode": "REQUIRED"},
{"name": "nth_created_at", "type": "TIMESTAMP", "mode": "NULLABLE"}

Comment: I'm a little baffled by your data model.  Can you provide sample data in a *tabular text* format?
Comment: @GordonLinoff row example:

{"user_id": "John","max_friends": 10, "friend_id": "Alice", "became_friends_at": "01-01-2020"}
Answer: You could use row_number() and a window min() as follows:
select parent_id, created_at nth_created_at
from (
    select
        t.*,
        row_number() over(partition by parent_id order by created_at) rn,
        min(parent_x) over(partition by parent_id) tn
    from mytable t
) t
where rn = tn

Answer: The simplest method is probably row_number():
select t.* except (seqnum)
from (select t.*, row_number() over (partition by parent_x order by timestamp) as seqnum
      from t
     ) t
where seqnum = 1;

Comment: @JurgenPalsma . . . I noticed that you unaccepted this answer.  Is there something wrong with it?


$A^2$ has a fixed point implies $A$ has also a fixed point

Question: Let $X$ be a Banach space and $A:X\to X$ a bounded operator. Assume that $A^2$ admits a fixed point in $X$ i.e. there exists $x_0\in X$ such that $A^2x_0=x_0$. Does this mean that $A$ has also a fixed point ?
Comment: I assume you want $x\neq 0$ for this?
Comment: $0$ is a fixed point of any linear operator.
Answer: Other than $0$?  No.  Try $A = -I$.


Perfect matching in a graph

Question: Assuming I have a bipartite graph with the following property:
for each subgroup of nodes $s \subseteq {V} $ :
$$
  \sum_{v\epsilon N(S),z\epsilon N(N(S)) }{} {(v,z) \geq 2\left \| S \right \|}
$$
Where $N(S)$ is the neighbourhood of $A$.
i.e. if you go over each of $S$ neighbors and count the edges coming out from each one. the number of edges is grater than or equal to twice the size of the subgroup S.
How can I show that this graph has a double matching, where double matching is a graph with 2 different perfect matching.
I know it is true by intuition but I can't seem to find a way to prove it formally.
EDIT:
I tried to use Hall's theorem, but it doesn't seem to be correct, because I am counting the number of edges and as a result I am not getting the size of the |N(S)|, because some of the vertices counted more than once.
assuming I have the graph $V= \{v_1, v_2 , u_1, u_2\}$. and $v_1$ is connected to $u_1$ and $u_2$, and $v_2$ is connected to $u_1$ and $u_2$. this graph has the property I mentioned above, and it's pretty obvious that there is a double matching in here.
But if you look at the size of the neighborhood of $S=\{v_1, v_2\}$, it will be $|{u1,u2}| = 2$
and not $2|S|= 4$ as Hall's theorem requires (because when you are counting the vertices you count $u_1$ and $u_2$ twice. once as $v_1$1 neighbors, and once as $v_2$ neighbors).
Also if I try to use Hall's theorem I nned to 1. choose a first perfect matching 2. remove it, and see that there is still a perfect matching (i.e. the is a double matching)
but in this case we can choose a perfect matching that will leave us without a choice for the second matching.
Please advice..
Answer: Edit:
Ok, I was wrong, I think that your conjecture is false. As mentioned in comments, I assume the following property
$$\sum_{v\in N(S),\ z\in N(N(S)) }(v,z) \geq 2 |S| \tag{$\spadesuit$}$$
Consider the following bipartite graph (obviously it doesn't even have a single matching):

Let $S_\bullet$ be the part of $S$ that contains black vertices, and $S_\circ$ the rest. If $S_\bullet$ is not empty, then sum contains at least all the blue edges, hence $8 \geq 2 |S_\bullet|$. Also, if $S_\circ$ contains any of the first two white vertices, then again $8 \geq 2 |S_\circ|$ because of the blue edges. Moreover, if $S_\circ$ does not contain any of the first two white vertices, then $4 \geq 2 |S_\circ|$. Finally, because of how the left-hand side sum is stated, the blue edges induces by $S_\circ$ and $S_\bullet$ will be counted appropriate number of times, that is one for $v \in N(S_\bullet)$ and one for $v \in N(S_\circ)$, hence, condition $(\spadesuit)$ is satisfied.
I hope this helps now ;-)
Comment: @user844541 The basic problem with condition $\spadesuit$ is that it counts somebody's else edges, for example it does not enforce that a vertex has to have more than one edge (even with counting edges once, you could make the graph similar to mine with $\Theta(n^2)$ blue edges). Moreover, besides number of edges, you would need that these edges spread is good (among others, there's no situation analogous to the two red edges). My intuition thinks that there are many possible ways to fix it, but those could be summed up to: make the condition more Hall's-theorem-like.
Comment: @user844541 They heavily depend on the fact that the matrix is doubly stochastic. In other words, sum of any row is $1$, therefore sum of $k$ rows is $k$, that is, $\sum_{v \in A,\ w \in N(A)} \omega(v,w) = |A|$. Your line does the same for columns, i.e. sum of any column is $1$, hence any $k$ columns sum up to $k$. The inequality $|N(A)| \geq |A|$ comes from the fact that $N(A)$ contains all non-zero terms of rows of $A$.
Comment: This is exactly what I tried to do, but I don't think this is correct. Hall's theroem is reffering to vertexes and here I am counting the number of edges.
Comment: I changed my question, can you see my edit?
Comment: @user844541 I don't have time right now, I will look at your question in more detail later. Just to let you know, I thought that in your notation $\|S\|$ also includes vertices, because if it doesn't, then a graph with no edges satisfies your property, i.e. $0 \geq 2\cdot 0$.
Comment: Thanks! |s| is the number of vertices in the subgroup S
Comment: @user844541 What is the precise definition of $\|S\|$?
Comment: |S| is The size of the group S. where S is a subgroup of the nodes.
Comment: @user844541 There is a difference between $|S|$ and $\|S\|$, which one do you mean (i.e. in your post there is double bar).
Comment: You are right. I meant |S| (cardinal number)
Comment: @user844541 Sorry for the delay. See the edits, if you have any further questions let me know.
Comment: Thank you very much. so actually what you are saying is that my argument is false?
Comment: but if we define S as the group that contains all the vertices, then in this case the argument is not satisfied, because |V|=8 while number of edges is 10 < 2*|V|=16.
Comment: @user844541 Observe that your sum would count edges twice, so $20 \leq 16$.
Comment: Is there a way to change the definition to make it work?
Comment: Thank you!Basically what I am trying to achieve is to convert this prove:  http://planetmath.org/proofofbirkhoffvonneumanntheorem  so it will hold for a 2-regular matrix. but I can't understand the following line: $|N(A)| = \sum_{v\epsilon N(A),z\epsilon N(N(A)) }{} {(v,z)}$ because I can't understand how the size of the neighborhood of A is the sum of the edges. so I thought that maybe it is enough just to count the edges. but as you had shown this is incorrect. also I know there is a double matching in the graph because of what you said regarding subgraph which is 2-regular

Perfect matching in a graph


How to display User profile fields to anonymous visitors?

Question: Currently I am developing an application in Drupal 7 , and my requirement is to display User profiles(profile image,DOB,Course,Year of joining etc.,) to anonymous users . I have used profile2 module to store them in the Database. The same information I wanted to display when a visitor clicks any of the User link. But i stuck in this part.
Please assist me in solving this...!
Thanks in advance
-Syam Kumar
Answer: Normally this is simply done within the permissions admin section (/admin/people/permissions if I remember right). Simply give anon users the permission to view profiles and those fields.
Maybe the module you are using causes the fields to be hidden. Check the permissions of that module as well.
Answer: If you use some custom module by your own you can always use this:
profile2_load_by_user($UID, 'MACHINE_PROFILE_NAME');

use some of preprocess function and attach that data to your view page.
You can add this also in your template.php file or you can add it to any other .tpl.php template file.
I always use custom link and past user UID to it, get all fields what I need and show in custom template file.


Laravel: Route [login] not defined

Question: I am creating an application in Laravela and when I try to visit my url, for example: http://example.com  it is returning this weird error? This only happens when I am not visiting /login?
InvalidArgumentException in UrlGenerator.php line 304:
Route [login] not defined.

Code:

use App\Http\Controllers\Frontend;

Route::group(['domain' => 'localhost', 'namespace' => 'Frontend'], function() {

    Route::group(['middleware' => 'guest', 'namespace' => 'Guest'], function() {
        Route::get('/', function() { return Redirect::to('/login'); });
        Route::get('/login', 'LoginController@getView');
        Route::post('/login', 'LoginController@onPost');
    });

    Route::group(['middleware' => 'auth', 'namespace' => 'User'], function() {
        Route::get('/', function() { return Redirect::to('/home'); });
        Route::get('/home', 'HomeController@getView');
        Route::get('/logout', 'LogoutController@performLogout');
    });
});

Route::group(['domain' => 'admin.localhost'], function() {
    Route::get('/', function() {
        return 'Housekeeping will be making an appearance soon!';
    });
});

Here is my LoginController:
<?php
namespace App\Http\Controllers\Frontend\Guest;

use Auth;
use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Redirect;
use Illuminate\Http\Request;
use App\Database\Frontend\User\Player;
use App\Database\Frontend\WebsiteLogin;

class LoginController extends Controller
{
    public function getView()
    {
        return view('frontend.login');
    }

    public function onPost(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mail'     => 'required|email|exists:users',
            'password'  => 'required'
        ]);

        if ( $validator->fails()) {
            return Redirect::to('/login')->withErrors($validator->messages());
        }
        else {
            if (!Auth::attempt(['mail' => $request->input('mail'), 'password' => $request->input('password')])) {
                $this->addNewWebsiteLogin($request, Player::where('mail', $request->input('mail'))->pluck('id')->first(), "0");
                return Redirect::to('/login')->withMessage('Email and password do not match')->withColor('danger');
            }
            else {
                $this->addNewWebsiteLogin($request, Auth::user()->id, "1");

                $user = Auth::user();
                $user->last_online = time();
                $user->save();

                /*if (config('frontend.government_only') && (Auth::Guest() || Auth::user()->roleplay->government_id == 0)) {
                    Auth::logout();
                    return Redirect::to('/login')->withMessage(config('frontend.site_name') . ' is only open to government individuals at this moment, too bad.')->withColor('danger');
                }*/

                return Redirect::to('/home')->withMessage('Welcome back!');
            }
        }
    }

    private function addNewWebsiteLogin(Request $request, $userId, $status) {
        $websiteLogin                    = new WebsiteLogin;
        $websiteLogin->user_id           = $userId;
        $websiteLogin->request_ip        = $request->ip();
        $websiteLogin->request_system    = 'TODO';
        $websiteLogin->request_browser   = 'TODO';
        $websiteLogin->login_status      = $status;
        $websiteLogin->save();
    }
}

Answer: Looks like you're using route('login') to create a link to the login page or in form.
If you're using it in a link, just name get() route:
Route::get('login', ['as' => 'login', 'uses' => 'LoginController@getView']);

If you're using the route() helper in a form, do this for the post() route.
Comment: I have accepted your answer as the `'as' => 'login'` solution worked, thanks.
Comment: I have updated my question, could you please take a look at my LoginController? I am pretty new to Laravel.
Comment: @LilSav I don't see a usage of the `route()` helper here. Maybe you're doing it in some view?
Comment: I'm not using the route() helper anywhere in my code from what I can see.
Comment: @LilSav do a full text search on your project. Search for `route('login`
Answer: You can use the artisan comp php artisan make:auth to scaffold the authentication pages needed.
You can find the documentation for that here, https://laravel.com/docs/5.4/authentication
Comment: Thank you my friend, I was looking for this.
Answer: if you have, login route like this:
Route::post('login', ['middleware' => 'guest', 'uses' => 'UserController@postLogin',]);

just need to add :
->name('login');

at the end of your route s.th like this.
your result s.th like this:
Route::post('login', ['middleware' => 'guest', 'uses' => 'UserController@postLogin',])->name('login');

Laravel: Route [login] not defined