How to iterate through cell content based ranges in VBA

Question: Currently, I want to automate some annoying work in excel and need some help.
I have a huge report which has 200k+ rows and about 500 columns and my task is to find out which cells of a column are never used.
This was fairly easy and I managed it to create a script that works for that so far.
But now I want to distinguish between row types and return for each row type whether there are columns that are never used.
My problem is that I do not know how to iterate through the contents of a cell, so that if the row type changes my script will count the empty columns for the next row type.
I hope you get the idea and can help me. You do not have to give me the full code but maybe an idea of how I can get to the solution :)
This is the vba code I currently have and that gives me the correct solution but without distinguishing between the rowtypes
Public row As Long
Public rowMax As Long
Public startRow As Integer
Public materialType As String
Public filter As String
Public col As Integer
Public colMax As Integer
Public isUsed As Boolean

Sub bestimmeObFelderGenutzt()
    With Sheets("Sheet1")
        filter = "I"
        startRow = 2
        rowMax = Sheets("Sheet1").Cells(.Rows.Count, "F").End(xlUp).row
        colMax = Sheets("Sheet1").Cells(1, .Columns.Count).End(xlToLeft).Column
        materialType = Sheets("Sheet1").Range(filter & startRow).Value

        For col = 1 To colMax
            Sheets("Sheet2").Cells(1, col + 2).Value = Sheets("Sheet1").Cells(1, col).Value
        Next col

        For row = 2 To rowMax
            Sheets("Sheet2").Range("A" & row).Value = Sheets("Sheet1").Range("A" & row).Value
            Sheets("Sheet2").Range("B" & row).Value = Sheets("Sheet1").Range("I" & row).Value
                For col = 1 To colMax
                    If IsEmpty(Sheets("Sheet1").Cells(row, col)) = False Then
                        isUsed = True
                        Sheets("Sheet2").Cells(row, col + 2).Value = 1
                    Else:
                        Sheets("Sheet2").Cells(row, col + 2).Value = 0
                    End If
                Next col
        Next row
    End With
End Sub

Sub findeUngenutzteSpalten()
    With Sheets("Sheet2")
        rowMax = Sheets("Sheet2").Cells(.Rows.Count, "F").End(xlUp).row
        colMax = Sheets("Sheet2").Cells(1, .Columns.Count).End(xlToLeft).Column
        Sheets("Sheet3").Cells(1, 1).Value = "Spaltenüberschrift"
        Sheets("Sheet3").Cells(1, 2).Value = "Jemals benutzt?"

        For col = 3 To colMax
            isUsed = False
            For row = 2 To rowMax
                If Sheets("Sheet2").Cells(row, col).Value = 1 Then
                    Sheets("Sheet3").Range("A" & col - 1).Value = Sheets("Sheet2").Cells(1, col).Value
                    Sheets("Sheet3").Range("B" & col - 1).Value = "Ja"
                    GoTo WeiterCol
                Else:
                    If row = rowMax Then
                        Sheets("Sheet3").Range("A" & col - 1).Value = Sheets("Sheet2").Cells(1, col).Value
                        Sheets("Sheet3").Range("B" & col - 1).Value = "Nein"
                    Else:
                        GoTo WeiterRow
                    End If
                End If
WeiterRow:
            Next row
WeiterCol:
        Next col
    End With
End Sub

Comment: What do you mean by `to iterate through the contents of a cell`? And not sure that I understand what is the `row types`. If you give brief examples of your worksheets - that can make things easier.
Comment: So I have certain materials and each material has its own type which is the row type. For each material type I want to find columns that are unused
Answer: If I understood your task correctly this should work, copy to your module and read comments:
Sub FindUnusedColumnsPerRow()
Dim cellRow As range, cellColumn As range
Dim rowRange As range, columnRange As range
Dim rowsCount As Long, columnsCount As Long
Dim insertRow As Long
Dim listOfEmptyColumns()
Dim i As Long, j As Long
Dim arrayCheck As Integer

    With Sheets("Sheet1") ' I assume that this is your sheet with materials where you want to find unused columns
        rowsCount = .Cells(Rows.Count, 6).End(xlUp).row ' get last row
        columnsCount = .Cells(1, Columns.Count).End(xlToLeft).Column ' get last column

        For Each cellRow In range(.Cells(2, 1), .Cells(rowsCount, 1)) ' going through all rows - here I suppose that material type is in the 1-st column, 1-st row is a header and data starts from 2-d row

            For Each cellColumn In range(.Cells(cellRow.row, 2), .Cells(cellRow.row, columnsCount)) ' for each row looking through all columns - I suppose that data starts from 2-d column
                If cellColumn = "" Then ' if the cell is empty.
                    ReDim Preserve listOfEmptyColumns(i) ' expanding array when needed
                    listOfEmptyColumns(i) = cellColumn.Column ' adding column number to an array, you may change it to = .cells(1,cellColumn.Column) to put a header name instead of column number
                    i = i + 1 ' increment the counter
                End If
            Next

            On Error Resume Next ' a small trick to check whether the array with column numbers is empty
            arrayCheck = UBound(listOfEmptyColumns) ' if the array is empty - an #9 "Subscript out of range" exception will be thrown

            If Err.Number = 0 Then ' error number is 0 - means that there was no error
                With Sheets("Sheet2") ' I suppose this is the sheet to store results
                    insertRow = .Cells(Rows.Count, 1).End(xlUp).row + 1 ' find the row to insert
                    .Cells(insertRow, 1) = cellRow.Value ' put the type to 1-st column
                    j = 2 ' start filling the row of the type with numbers of empty columns

                    For i = 0 To UBound(listOfEmptyColumns) ' populating data from array
                        .Cells(insertRow, j) = listOfEmptyColumns(i)
                        j = j + 1
                    Next
                End With
            End If

            Err.Clear ' clearing the error, because it still holding an error information (if it was thrown)
            On Error GoTo 0 ' don't forget to switch on normal error handling

            Erase listOfEmptyColumns ' reset array before next row as the data is stored on sheet2
            i = 0 ' reset the counter for further use
        Next

    End With
End Sub


How to choose type from some different on compilation time?

Question: I want to do something like this:
template <uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 = (N % 2 == 1 ? v1 : v2);
};

But I can't use (? :) with different types. How I can do this?
Comment: Does this answer your question? [Something like "if constexpr" but for class definition](https://stackoverflow.com/questions/41118861/something-like-if-constexpr-but-for-class-definition)
Comment: Look up template specialisation  (or, US spelling, specialization)
Comment: @AlexLarionov, can you add some info about the way of using this question?
Answer: For example, you can use if constexpr and a lambda function (C++17):
template <std::uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 =
    [] {
        if constexpr (N % 2 == 1)
            return v1;
        else
            return v2;
    }();
};

Another solution with a std::tuple (C++14):
template <std::uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 = std::get<N % 2>(std::make_tuple(v2, v1));
};

Comment: Very nice the `std::get()` solution: works also in C++11/C++14.
Comment: @max66 the `std::get` solution only works at compile time in C++14. C++11 doesn't define `std::get` to be `constexpr`
Comment: @Human-Compiler - D'Oh! You're right: `constexpr` from C++14.
Comment: @max66 Curiously, with GCC and Clang it works even with `-std=c++11`. Probably, they have `constexpr` for these functions in C++11 already.
Comment: @Evg -  Well... from clang I get a compiler error... but I confirm from gcc.... the bad part is that works also adding "`-pedantic`"... I think we should consider this a gcc bug (in case of pedantic).
Answer: If you can use C++17 (but you tagged C++11 and C++14 only) a if constexpr solution based (very elegant the lambda based from Evg) is preferable, IMHO.
Before C++17, I suppose you can try using SFINAE. By example
#include <type_traits>

template <int N>
struct Foo
 {
   static constexpr int v1 = {};
   static constexpr long v2 = {};

   template <int M = N>
   constexpr static std::enable_if_t<M % 2 == 1, int> getV3 ()
    { return v1; }

   template <int M = N>
   constexpr static std::enable_if_t<M % 2 != 1, long> getV3 ()
    { return v2; }

   static constexpr auto v3 = getV3();
 };

int main ()
 {
   static_assert( std::is_same_v<int const, decltype(Foo<1>::v3)> );
   static_assert( std::is_same_v<long const, decltype(Foo<2>::v3)> );
 }

As suggested by Evg (thanks!) you can avoid SFINAE using overloading (good-old tag dispatching). By example
template <int N>
struct Foo
 {
   static constexpr int v1 = {};
   static constexpr long v2 = {};

   constexpr static auto getV3 (std::true_type)
    { return v1; }

   constexpr static auto getV3 (std::false_type)
    { return v2; }

   static constexpr auto v3 = getV3(std::integral_constant<bool, N%2>{});
 };

Comment: Instead of SFINAE, one can also use overload resolution for `std::integral_constant{}`.


Minimum in a non-linear system

Question: I have the linear system:
$$\begin{cases}\dot{x}=y\\
\dot{y}=-ay+x-x^3\end{cases}$$
where $a\geq 0$.
I want to prove that this dynamical system has two minimum.
I found the 3 equilibrium points $(0,0)$, $(1,0)$, $(-1,0)$.
I calculated the jacobian and i don't know how to proceed.
I have read something about minimum points when the Jacobian is positive definitive but these matrices are not.
Comment: What do you mean by "a system has a minimum"?
Comment: The symmetry is clear from the fact that your vector field is symmetric w.r.t. the origin, that is $F(x,y)=-F(-x,-y)$. I guess that the "two minima" refers to the fact that the stationary solutions (equilibrium points) $(-1,0)$ and $(1,0)$ are stable.To check stability you just compute the eigenvalues of the linearized problem, which must be negative or complex with non-positive real part.
Comment: the question is :why this is a system that moves in symmetrical dynamic with two minimum?
Comment: this means that every time i have stable equilibrium points i am gonna have minimum?
Comment: I think a minimum you are referring to can be interpreted as all points you can converge to if you start sufficiently close to them. But I can imagine that this can be confusing, since normally a minimum is defined with respect to some cost function.
PS: it can also help if you [visualize it](https://www.wolframalpha.com/input/?x=-1526&y=-71&i=streamplot%5B%7By,-y%2Bx-x%5E3%7D,%7Bx,-3,3%7D,%7By,-3,3%7D%5D).
Answer: As @GReyes proposed you need to linearize the system at the equilibrium points $\boldsymbol{x}_\text{eq}=[x_\text{eq},y_\text{eq}]^T$, which are $[0,0]^T$ and $[\pm 1,0]^T$.
If we write the system in vector form, by using $\boldsymbol{x}=[x,y]^T$ and $\boldsymbol{f}=[f_1(\boldsymbol{x}),f_2(\boldsymbol{x})]^T$
$$\dot{\boldsymbol{x}}=\boldsymbol{f}(\boldsymbol{x})$$
we can simply get the linarized system matrix $\boldsymbol{A}$ by
$$\boldsymbol{A} = \left.\dfrac{\partial \boldsymbol{f}}{\partial \boldsymbol{x}}\right|_{\boldsymbol{x}=\boldsymbol{x}_\text{eq}}$$
Written out for our problem this is given by
$$\boldsymbol{A}=\begin{bmatrix}
\dfrac{\partial f_1}{\partial x}& \dfrac{\partial f_1}{\partial y}\\
\dfrac{\partial f_2}{\partial x}& \dfrac{\partial f_2}{\partial y}
\end{bmatrix}_{\boldsymbol{x}=\boldsymbol{x}_\text{eq}}$$
$$=\begin{bmatrix}0 & 1\\1-3x^2_\text{eq} & -a\end{bmatrix}.$$
The eigenvalues of this system are given by the characteristic polynomial
$$\chi(s)=s^2+as+(3x^2_\text{eq}-1).$$
If $a>0$ and $3x^2_\text{eq}-1>0$ are fulfilled the system is Hurwitz, hence the equilibrium point is asymptotically stable. You can quickly check these properties for the given equilibrium points. Only the origin is unstable but all other equilibrium points are asymptotically stable in a neighborhood of the equilibrium points.
As @Kwin van der Veen proposed. The phase diagram looks like a landscape with hills (unstable equilibrium points) and valleys (asymptotically stable equilibrium points). If you imagine a ball starting somewhere (initial conditions) in this landscape the ball will converge to one of the asymptotically stable equilibrium points (we exclude the trivial origin as a starting point), by following the dynamics of the system (given by the arrows in the phase diagram provided by @Kwin van der Veen).
The hard part is actually the case $a=0$. For the equilibrium point $[0,0]^T$ you can still use the linearization theorem by Lyapunov. But for the other equilibrium points, you will need to find a Lyapunov function to show stability.
EDIT: I just couldn't resist :D. In order to show the stability of the system at the equilibrium points $[0,\pm 1]^T$ we divide both equations to obtain
$$dy/dx = \dfrac{x-x^3}{y} \implies 1/2y^2-1/2x^2+1/4x^4-c=0.$$
Now, we define $\Phi(x,y)=  1/2y^2-1/2x^2+1/4x^4$ and evaluate this function at the equilibrium points $x_\text{eq}=\pm 1$ to get $\Phi_\text{eq}=-1/4$. Now, we construct a Lyapunov function candidate
$$V(x,y)=\Phi(x,y)-\Phi_\text{eq}=1/2y^2-1/2x^2+1/4x^4+1/4$$
$$=1/4\left[(1-x^2)^2+2y^2\right].$$
You can see that the function $V$ is positive definite in the vicinity of the equilibrium points $[\pm 1,0]^T$ and $V=0$ for the equilibrium points.
It is clear that $\dot{V}=0$. Because $\Phi(x,y)$ and $\Phi_\text{eq}$ are constants. You can also derive this by differentiating $V$ and using the differential equations for $a=0$. Hence, we can conclude that the equilibrium points are stable.
Comment: What is going if I have a system that has no Equilibrium points.For example $\dot{x}$=y and $\dot{y}=-ay-sinx+T, where T>1 and a>=0.Is it stable?
Comment: For nonlinear systems, we do not say if the system is stable or not. For nonlinear systems, we only look at special solutions (equilibrium points, limit cycles or specific solutions) and try to determine if they are stable. We cannot talk about the stability of equilibrium points in this case. The system cannot have limit cycles because that would imply an equilibrium point in the inner region, which we do not have. The last thing that you could check is if there is a stable solution (e.g. if all trajectories escape to infinity in the same fashion). But you will need to find the solution :).

Minimum in a non-linear system


How to find the limit of $\frac{1−\cos 5x}{x^2}$ as $x\to 0$?

Question: What is the right approach to calculate the Limit of $(1-\cos(5x))/x^2$ as $x \rightarrow 0$?
From Wolfram Alpha, I found that:
$$\lim_{x \to 0} \frac{1- \cos 5x}{x^2} = \frac{25}{2}.$$
How do I get that answer?
Comment: Please verify formatting didn't change your question.
Answer: Using the equality
$$1-\cos2y=2\sin^2y$$
we have with $5x=2y$
$$\lim_{x\to0}\frac{1-\cos5x}{x^2}=\lim_{y\to0}\frac{2\sin^2y}{\left(\frac{2y}{5}\right)^2}=\frac{25}{2}\lim_{y\to0}\left(\frac{\sin y}{y}\right)^2=\frac{25}{2}$$
Answer: $$\lim_{x \to 0} \frac{1-\cos 5x}{x^2}\frac{1+\cos 5x}{1+\cos 5x}=\lim_{x \to 0}\frac{1-\cos^25x}{x^2}\frac{1}{1+\cos5x}=$$
$$=\lim_{x\to 0}\left(\frac{\sin5x}{5x}\right)^2\frac{25}{1+\cos5x}=\frac{25}{2}$$
Comment: +1 I just saw this question after [this question](http://math.stackexchange.com/questions/1863366/gre-limit-problem) was marked as a duplicate. This answer is almost identical to mine there.
Answer: $\langle$ Begin of rant $\rangle$ It seems to be an effect of the choice made in some educational systems to inflate the importance of l'Hôpital's rule, that this (at best anecdotal) trick becomes the alpha and the omega of the approach by several MSEers of every question involving the local analysis of a real function. This happens at the expense of several other tools, often more important mathematically and at least as easy to use. As a consequence, let me humbly suggest that the extent of this monopole might be completely disproportionate, and even detrimental to the learning process of the field. $\langle$ End of rant $\rangle$
In the present case, a direct approach uses a quite rudimentary limited expansion of the cosine function at zero, namely, the fact that
$$
1-\cos(u)\sim\tfrac12u^2,\qquad u\to0.
$$
For $u=5x$, the fact that the limit asked about is $\frac{25}2$ becomes obvious.
To come back to the object of the rant, is it unreasonable to ask that anybody interested in mathematical analysis might know the equivalent used above (saying that the graph of cosine looks like a parabola around $0$), and that $\sin(u)\sim u$ and $\tan(u)\sim u$, and a few other similar expansions, say, $\mathrm e^u-1\sim u$ (fundamental) and $\sqrt{1+u}-1\sim\frac12u$ (each saying what is the slope of the tangent to a graph at $0$), rather than the intricacies of a black box called l'Hôpital's rule (whose requirements, by the way, are almost never checked)? Honestly, I do not think so.
Comment: I wholeheartedly agree with the first and the last paragraph. I also concur that the solution of the problem in between is the best and easiest solution of this problem.
Comment: @Did I have nothing against knowing the limited expansions, however, putting the instance you proposed aside, with l'H you have to memorize much less, you can know nothing about expansions and series, a topic that is not frequently taught in high schools, and yet you can answer almost all high school level\early college questions.It is powerful because it lets you to solve lots of problems without knowing much.
Comment: @hhsaffar Really? Please test the "power" of l'H on the limit of $(1-\cos(5x)+\sin(17x)^3-\mathrm e^{-42/x^2})/(x^2+\sqrt[3]{x^7+x^9})$ when $x\to0$.
Comment: @Did : not everyone will be able or willing to memorize the power series expansions of all the functions you think are important.  What about $\tan^{-1}$?  $\ln$?  Where do you draw the line?  L'Hopital's Rule is easy to remember and use (in typical problems, there are no "intricacies").  In addition, few students know what "little-o" notation means.  It, as well as "big-O" notation, are not part of most calculus sequences.  Whether they should be is a separate question.  I do think many students overuse it, and attempt to use it for everything, before trying a little algebra and common sense.
Comment: Actually, an interesting question would be to determine when the place of l'Hôpital's rule began to be so preeminent in certain curricula, which other, previous, expertises it replaced, and how the move was justified (if it was perceived) at the time by its proponents.
Comment: However, I think you missed the big picture. Some students in high school know nothing about Maclaurin series, and therefore the use of the limited expansions isn't always advisable. These limits are mainly met in high school.
Comment: honestly, to understand that $$\sin x \sim x$$,  and that $$x^2 + x \sim x$$ (x -> 0) is trivial, it does not involve mac Laurin, and it does simplify enourmously the calculations.. I would teach that in high school
Comment: .../... to rely on "a little algebra and common sense". I could not agree more with this formulation.
Comment: I think the inflation in the perception of importance of l'Hôpital's rule is mostly caused by its power(at least in solving lots of popular problems) rather than the choice of educational system. When I was in high school at some time we were banned(!) to use the rule, but everybody was secretly using it to check his answer!
Comment: In your last edit, you introduced an orthographic Gallicism (fondamental).
Comment: @DanielFischer Oops, thanks.
Comment: @Chris'ssis Thanks for your reaction. Note that Maclaurin series are not even mentioned in my post and that they are off-topic. I rephrased, to emphasize that only some basic equivalents are at stake here, that is, knowing what the graphs of some of the most common functions *look like* around zero.
Comment: @StefanSmith Thanks for your reaction. I fail to recognize the content of my post in the dilemnas you say. Little-o and big-O are quite inessential here (btw, I rephrased my remark in terms of simple equivalents). List of functions: already the ones mentioned in the post, plus $1/(1-x)$ and the logarithm, would allow to go a long way. Importantly, you do not mention that many of these equivalents are *intimately related*. To learn by heart a huge list of expansions would be stupid (and it is not the way things are presented in the curricula I know which escape l'H's obsession). Rather, .../...
Comment: .../... what happens is that to be at ease with a few of these expansions/equivalents allows to reinforce one's understanding of the subject. For example, the expansions of the exponential, the sine and the cosine are really one result, *plus the relations between these functions*. Knowing the former makes one aware of the latter, thus I strongly object to your *memorize*. Precisely, l'H's rule has morphed into a recipe students try to *memorize* (more or less accurately), which effectively prevents them to *think*, that is, to do some actual maths, or, in your words, .../...
Answer: Use L'Hopital's Rule:
Since the limit evaluates to the form $\frac 00$ as is, we can take the derivative of the numerator and denominator, and then evaluate the limit as $x\to 0$; if it still evaluates to the form $\frac 00$, take the derivative of the numerator and denominator again, and evaluate the resulting limit as $x\to 0$. Etc: Here, we apply L'H twice:
$$\lim_{x \to 0} \frac{1-\cos 5x}{x^2} \quad \overset{L'H}{=} \quad \lim_{x \to 0} \frac{5\sin 5x}{2x}\quad \overset{L'H}{=}\quad \lim_{x \to 0} \frac{25 \cos 5x}{2} \quad = \quad\frac{25}{2}$$
Comment: It should be $\lim_{x \to 0} \dfrac{1-\cos 5x}{x^2} = \lim_{x \to 0} \dfrac{5\sin 5x}{\mathbf{2}x} $
Answer: We can use L'Hôpital's rule, where $f(x) = 1-\cos 5x$ and $g(x)=x^2$, as
$$\lim_{x \to 0} (1-\cos 5x) = \lim_{x \to 0} x^2 = 0,$$
and $g'(x) = 2x \neq 0$ for all $x\in\mathbb{R}\backslash\{0\}$.
Then we get
$$\lim_{x \to 0} \frac{1-\cos 5x}{x^2} = \lim_{x \to 0} \frac{5\sin 5x}{2x} = \lim_{x \to 0} \frac{25 \cos 5x}{2} = \frac{25}{2},$$
where we apply L'Hôpital's rule twice.
Comment: It should be $\lim_{x \to 0} \dfrac{1-\cos 5x}{x^2} = \lim_{x \to 0} \dfrac{5\sin 5x}{\mathbf{2}x} $
Comment: @K.Rmth: of course, fixed. Thanks.
Comment: $$ \lim_{x \to 0} \frac{5\sin 5x}{2x} = \frac{5}{2}  \lim_{x \to 0} \frac{\sin 5x}{x} $$ is just the definition of the derivative of $\sin(5x)$ at $0$... So the second L'H use is circular logic....
Answer: $\cos(2\alpha) = 1-2\sin ^2 \alpha$
Therefore
$\frac{1-\cos (5x)}{x^2}=\frac{2 \sin ^2 \left( \frac{5x}{2}\right)}{x^2} = \frac{25}{2} \left( \frac{\sin \frac{5}{2}x}{\frac{5}{2}x} \right)^2 \rightarrow \frac{25}{2}$
Answer: There is a really easy way of doing this, take derivatives. Namely:
$$ \partial_{5} \frac{1- Cos(5x)}{x^{2}} =\frac{xSin(5x)}{x^{2}}=\frac{Sin(5x)}{x} \to 5$$
Now, since we took a derivative w.r.t 5, we must take the integral with respect to 5:
$$\int 5 \mathrm{d}5=\frac{5^2}{2}=25/2$$
Answer: L'Hospital's Rule, twice. You will have a $25cos5x$ in the num, and a 2 in the denom, supporting your answer


how to execute app as system user?

Question: I want to write in /sys/class/camera/rear_flash but I don't have a permissions, the file has read and write permissions as user "system" and any user within the group "radio" (rw- rw- r--). Can I launch my app as "system" user or user within "radio" group without being root?
Answer: To run your App as System you have install it as follow:
Copy your APK in SD Card and executing these adb commands
<code>adb shell
su

cd sdcard/
mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
cat YOURAPP.apk > /system/app/YOURAPP.apk

chmod 644 /system/app/YOURAPP.apk
reboot
</code>
Comment: The problem I see is that I need to have a rooted device. Without root, could I do it?
Comment: No, You don't... It should be rooted... I'm sorry

how to execute app as system user?


HTTP/2: speed vs. security

Question: As a measure for speeding up of webpage loading times i recommended to switch over from HTTP1.1 to HTTP/2 protocol. And just today, firtsly in my experience since HTTP/2 rising, i've heard as the argumentation for non-switching to HTTP/2, that

HTTP/2 would be not secure enough and would have such weighty security issues,
  that they make any speed boost not worthy.

As the source of those thinking i've got this article.
My state of information doesn't allow me to judge about how weighty are riscs, mentioned in this article. I could suppose, that they are from pretty rare nature - it is just a guess, based on my own monitoring of special media about website performance, which could be (very) holey.
Could somebody explain me:

what is in general about security issues of HTTP/2?
are these issues enough cause to not to switch to HTTP/2?
Comment: That document is from 2016. I don't believe the security issues mentioned there are still relevant today. I don't think HTTP/2 is insecure as the major players are all moving towards it (FB, Google...)
Comment: That document is outdated, and also that quote does not appear anywhere in it.
Comment: @MichaelHampton the quote is not from the doc, but from the person, who was talking to me.
Answer: HTTP2 is new so may well have security issues. More likely to do with bad implementations than the protocol itself.
HTTP/1.1 is old and battle tested. And definitely has issues, despite this. Some of these are vulnerabilities in the protocol (e.g.  being text based rather than binary based it is possible to use HTTP header splitting/ header smuggling to fool web servers) and many more are due to implementations.
So I would say neither is secure. Neither is anything online. Nor walking out of your house :-)
I don't think security concerns are a reason to hold off upgrade to HTTP/2 and in many ways (see example above) it is MORE secure than HTTP/1.1. Saying that the main aim of HTTP/2 was to improve performance not security.

HTTP/2: speed vs. security


estou fazendo um exercício de Javascript onde preciso retornar um numero recebido ao contrário e em um array

Question: Estou fazendo um exercício de Javascript onde preciso retornar um numero recebido ao contrário e em um array. porém dentro da função não consigo utilizar .split() e nem toString(), quando passo o mouse aparecem como 'any'.

function reverte(n) {
  let viraString = n.toString()
  return viraString.split('').reverse()
}
console.log(reverte(123456));

Fiz para teste basicamente o mesmo código fora da função e funcionou.

let teste = 123456
let v = teste.toString()

let teste2 = v.split('').reverse()

console.log(teste2);
Comment: Coloquei o seus códigos como executáveis e ambos os fragmentos retornam o mesmo resultado portanto não sendo possível reproduzir o erro alegado com as informações fornecidas na pergunta. Está exibindo `ANY`, talvez esteja usando Typescript ao invés de Javascript, verifique. Não publique nada que não seja tecnicamente relacionado com a pergunta, por exemplo cumprimento ou justificativas de qualidade. Para saber mais sobre o funcionamento do site visite nossa [help].
Answer: No JavaScript, o tipo "any" é usado para representar um valor que pode ser de qualquer tipo.
O seu código não apresenta erro. Se você estiver usando VsCode, ao passar o mouse ele mostra o "any" pois quando o tipo não é declarado, ele assume que o tipo é "any", que nesse caso refere-se ao tipo do argumento que você passou:
function reverte(n: any) {...}
Isso começa a ficar mais claro quando começar usar TypeScript, mas por enquanto é isso.
Espero ter ajudado :)
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Show that $N(H):=\{g\in G; gHg^{-1}=H\}$ is subgroup of $G$

Question: Let $G$ be a group and $H$ subgroup of $G$, $N(H):=\{g\in G; gHg^{-1}=H\}$
I need to prove that $N(H)$ is subgroup of $G$.
It's almost the same question like :How to show $\forall g \in G, gHg^{-1} = H \Leftrightarrow \forall g \in G, gHg^{-1} \subseteq H$?
But I need the inverse direction of the answer.
Attempt:
The inverse of $gHg^{-1}$ is:
$$\begin{align}(gHg^{-1})^{-1}&=(g^{-1})^{-1}Hg^{-1}=gHg^{-1}=H \\&\implies (gHg^{-1})^{-1}=gHg^{-1} \\&\implies \text{the inverse of element is the element}\end{align}$$
Is it true?
Comment: The inverse of a set!? Be careful, what you need to prove is that the inverse of each **element** that lives in $N(H)$ lives in $N(H)$ too,
Answer: The elements of $N(H)$ aren't $gHg^{-1}$ but $g \in G$ such that $H$ has that property.
If $g, g' \in N(H)$ then $$gg' H (gg')^{-1} = g(g' H g'^{-1})g^{-1} = gHg^{-1} = H$$ then $g\dot \,g' \in N(H)$
If $g \in N(H)$ then $g^{-1} H (g^{-1})^{-1} = g^{-1} H g = H$, because $gHg^{-1} = H$, then $g^{-1} \in N(H)$.
And you're done.
Answer: You will need that $H$ is subgroup of $G$. Note that if $e\in G$ is the identity, then $e\in N(H)$ because $eHe = H$. Next, you want to show that if $g\in N(H)$ then $g^{-1} \in N(H)$. Equivalently, for all $h\in H$, $(ghg^{-1})^{-1}\in H$. But $(ghg^{-1})^{-1} = gh^{-1}g^{-1}$ is indeed in $H$ because $h^{-1} \in H$ and $g\in N(G)$.


Display all the values for every date in JSON

Question: I have the following JSON:
{
    "groups" : [
      {
        "values": "21",
        "date": "2013-02-22"
      },
      {
        "values": "25",
        "date": "2013-02-22"
      },
      {
        "values": "20",
        "date": "2013-02-22"
      },
      {
        "values": "19",
        "date": "2013-02-22"
      },
      {
        "values": "42",
        "date": "2013-02-10"
      },
      {
        "values": "30",
        "date": "2013-02-10"
      },
      {
        "values": "11",
        "date": "2013-02-10"
      }

    ]
}

I have the values and the date already extracted in a Ruby Class. I want to find the "highest" and "lowest" value for every date. How do I do that?
Also I want to create parallel arrays for the same. For instance:
low = [12, 22, 11, 45]
high = [34, 50, 15, 60]
dates = ["2013-02-22", "2013-02-10", "2013-02-06", "2013-02-01"]

I would also like to display all the values for every date.
Could someone please give me some direction for this?
Comment: What have you tried? The [`group_by`](http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-group_by) function is super helpful here.
Comment: Welcome to Stack Overflow. It's important to give us minimal input data, the expected output, and the minimal code necessary to reproduce the problem you're seeing. That last part, the minimal code necessary to reproduce the problem helps us NOT try everything possible but focus on how you're attacking the problem. As is, it seems like you haven't tried and want us to try for you, or explain how to do it, neither of which are how SO works.
Comment: When you give an example in a question (generally a very good thing to do) it is important that the input be valid Ruby objects. As you know, JSON objects are strings, so you need to add single quotes `'{...}'`, or use `%s[...]` or a heredoc. Also, you should assign all input values to variables, so they can be referenced in answers and comments without having to define them. For example, `str = `'{...}'`.
Answer: If str is your JSON string:
require 'json'
arr = JSON.parse(str)["groups"]
  #=> [{"values"=>"21", "date"=>"2013-02-22"},
  #    {"values"=>"25", "date"=>"2013-02-22"},
  #    {"values"=>"20", "date"=>"2013-02-22"},
  #    {"values"=>"19", "date"=>"2013-02-22"},
  #    {"values"=>"42", "date"=>"2013-02-10"},
  #    {"values"=>"30", "date"=>"2013-02-10"},
  #    {"values"=>"11", "date"=>"2013-02-10"}]

by_date = arr.each_with_object(Hash.new {|h,k| h[k] = []}) { |g,h|
  h[g["date"]] << g["values"].to_i }
  # => {"2013-02-22"=>[21, 25, 20, 19], "2013-02-10"=>[42, 30, 11]}

dates = by_date.keys
  #=> ["2013-02-22", "2013-02-10"]
min_vals, max_vals = *by_date.map { |_,vals| vals.minmax }
  #=> [[19, 25], [11, 42]]
min_vals
  #=> [19, 25]
max_vals
  #=> [11, 42]

The method Enumerable#each_with_object takes an argument that is the initial value of the object that will be constructed and returned by the method. It's value is given by the second block variable, h. I made that argument an empty hash with a default value given by the block:
{|h,k| h[k] = []}

What is the "default value"? All it means is that if the hash h does not have a key k, h[k] returns an empty array. Let's see how that works here.
Initially, h #=> {} and each_with_object sets the first block variable, g equal to the first value of arr:
g = {"values"=>"21", "date"=>"2013-02-22"}

and block calculation is performed:
h[g["date"]] << g["values"].to_i
  #=> h["2013-02-22"] << 21

Since h does not have a key "2013-02-22", h["2013-02-22"] is first set equal to the default value, an empty array:
h["2013-02-22"] = []

then
h["2013-02-22"] << 21
  #=> [21]
h #=> {"2013-02-22"=>[21]}

When the next value of arr is passed to the block:
g = {"values"=>"25", "date"=>"2013-02-22"}

and h is as above. So now the block calculation is:
h[g["date"]] << g["values"].to_i
  #=> h["2013-02-22"] << 25
  #=> [21, 25]
h #=> {"2013-02-22"=>[21, 25]}

The default value is not used this time, as h has a key "2013-02-22".
One other thing may require explanation: the "splat" * in:
min_vals, max_vals = *by_date.map { |_,vals| vals.minmax }

We see that:
by_date.map { |date, vals| vals.minmax }
  #=> [[19, 25], [11, 42]]

If *by_date.map { |date, vals| vals.minmax } is on the right side of an equality, the splat causes the two elements of [[19, 25], [11, 42]] are assigned to variables on the left side of the equality using parallel assignment. The weird and wonderful splat operator needs to be in every Rubiest's bag of tricks.
Since I'm not using date in the block calculation, I've drawn attention to that by replacing date with the local variable _.
Edit: To answer the question you posted in a comment, if:
id   = [1,1,1,2,2,3,4]
high = [100,100,100,90,90,100,100]
low  = [20,20,20,10,10,30,40]

and I understand your question correctly, you could first compute:
indices = id.each_with_index.to_a.uniq(&:first).map(&:last)
  #=> [0, 3, 5, 6]

Then the three arrays you want are:
id.values_at(*indices)
  #=> [1, 2, 3, 4]
high.values_at(*indices)
  #=> [100, 90, 100, 100]
low.values_at(*indices)
  #=> [20, 10, 30, 40]

Comment: Excellent. Well done. Just what I'd have posted. `by_date.map{ |k, v| [k, v.minmax] }.to_h` is also useful.
Comment: Cary, thanks for the answer. It really helped. What if I already have the high/low values in the json and I'm able to create an array with it? Say, I have, `high = [100,100,100,90,90,100,100]   low = [20,20,20,10,10,30,40]`. Also I have an identifier for a group of elements. `id=[1,1,1,2,2,3,4]`. How do I split this based on the identifier? I want the result to be `high = [100, 90,100,100] low = [20, 10, 30, 40] id = [1,2,3,4]`.
Comment: You'll have to be more specific. Probably best to post another question.
Comment: Cary, I have edited the above comment to be more specific. Do you get my question ?
Comment: I just saw your comment but have to leave. I'll address it later today.
Comment: doesey, my apologies for the delay in answering the question you posted in the comment. I answered that with an edit to my answer. Please let me know if I misunderstood what you are looking for.
Answer: You can group_by :date and iterate through the dates. Then create an array of :values in the group.
Then use minmax to get the proper values and transpose the final array to get your arrays and assign to dates, low and high.
json = {
  "groups": [
    { "values": "21", "date": "2013-02-22" },
    { "values": "25", "date": "2013-02-22" },
    { "values": "20", "date": "2013-02-22" },
    { "values": "19", "date": "2013-02-22" },
    { "values": "42", "date": "2013-02-10" },
    { "values": "30", "date": "2013-02-10" },
    { "values": "11", "date": "2013-02-10" }
  ]
}

dates, low, high = json[:groups].group_by { |g| g[:date] }.map do |date, grouped|
  values = grouped.map { |group| group[:values] }
  [date, *values.minmax]
end.transpose
# => => [["2013-02-22", "2013-02-10"], ["19", "11"], ["25", "42"]]

dates
# => ["2013-02-22", "2013-02-10"]
low
# => ["19", "11"]
high
# => ["25", "42"]

Comment: @CarySwoveland I understand that but I believe someone new to a language have to be always reading the documentation and try all methods in answers to see what happens and learn from that.


Example of infinite , compact, path connected metric space $X$ which is homeomorphic to $X \times X$?

Question: Does there exist a compact, path connected metric space $X$, with more than one point , such that $X \times X$ is homeomorphic with $X$ ?
Answer: Yes, consider e.g. $X=[0,1]^\omega$.
Comment: Just on a side note ... In your case , is $X \times X$  bijectively isometric with $X$ ?
Comment: I'm not sure right now that we can pose such a metric on $X$..
Comment: $X \times X$ is metrizable if $X$ is ... just take the taxicab type metric  ...
Comment: Let me make it more explicit by asking :does there exist a metric $d$ on $X$ and $e$ on $X \times X$ in your example such that those metrics give the usual topology on $X$ and $X\times X$ resp. such that with those metrics, the spaces are bijectively isometric ?
Comment: I don't know.. $ $


Actionscript 3 Removing multiple childs

Question: Basically, I want to remove my play/pause buttons on a condition when someone goes to a new page, but at the same time, if my video is active, it will remove it as well.
Currently this is my code to remove them.
    if (header.text == "Gallery") {
    myvid.stop();
removeChild(myvid);
trace("stuff got removed")
removeChild(iplaybtn); removeChild(istopbtn); removeChild(iplaybtn2); removeChild(istopbtn2);
removeChild(play0); removeChild(stop0); removeChild(play1); removeChild(stop1);

}else{
trace("gallerybutton has been click.");
myvid.stop();
removeChild(myvid);

}

Problem is, it works, as in, it will remove the video and THEN the buttons, but the issue is, if the video isnt active, it doesn't remove the buttons =/.
Can't figure out how to make a conditional statement which will apply to both, but it will check if both have been complete or just do both.
GAAAH help!
Answer: Not sure what you mean with "if the video isnt active"
Also, i don't know what the header.text is, but i assume a textfield.
I think you just want a OR statement, like this:
if (header.text == "Gallery" || <>) {

Answer: The previous answer looks correct, you're probably looking for logical operators. These are the operators you can use:
|| (OR operator) will run the code if any condition is true.
&& (AND operator) will run the code if all conditions are true.
! (NOT operator) will run the code if the condition is not true (i.e. false!)

You can find more information on operators and their usage here: http://www.adobe.com/devnet/actionscript/learning/as3-fundamentals/operators.html
I'm not sure if you're removing everything or just some things on stage, but if you're looking to remove everything you can also use:
for (var i:int = (numChildren - 1); i >= 0; i--) {
  removeChild(getChildAt(0));
}

or alternatively
while (numChildren > 0) {
  removeChildAt(0);
}

Actionscript 3 Removing multiple childs


mysql select if sum greater and group by

Question: I have two mysql tables.
First table:

cost_id| cost_customer_id | cost_total | cost_date
 1     |      1           |     50     | 2019-01-03
 2     |      2           |    120     | 2019-02-03
 3     |      1           |     70     | 2019-03-21
 4     |      2           |     35     | 2019-04-03
 5     |      3           |     14     | 2019-05-07
 6     |      1           |     84     | 2019-06-03

Second table:
inv_id | inv_customer_id  | inv_total  | inv_date
 1     |      1           |    150     | 2019-01-05
 2     |      2           |     20     | 2019-02-06
 3     |      1           |     90     | 2019-03-21
 4     |      1           |      3     | 2019-04-03
 5     |      3           |     94     | 2019-05-09
 6     |      2           |     11     | 2019-06-08
 7     |      1           |     99     | 2019-07-06
 8     |      2           |     71     | 2019-08-04
 9     |      1           |     45     | 2019-09-02

So what I would want returned is:
customer_id | sum_inv_total | sum_cost_total  | balance     | avg_inv_date
     1      |      387      |     204         |   183       | 2019-05-31
     2      |      102      |     155         |   -53       | null
     3      |       94      |      14         |    80       | 2019-05-09

ie, to get average inv_date for each customer after deducting costs ordered by inv_date, for example for customer #1; average inv_date of open invoices:
    inv_id | inv_customer_id  | inv_total  | inv_date    | status
     1     |      1           |    150     | 2019-01-05  | closed (still below cost)
     3     |      1           |     90     | 2019-03-21  | open (reached total cost: 204)
     4     |      1           |      3     | 2019-04-03  | open
     7     |      1           |     99     | 2019-07-06  | open
     9     |      1           |     45     | 2019-09-02  | open

I can try following query but it takes too long time to finish and for only one customer:
SELECT
    sum_cost_total,
    SUM(inv_total_str) AS sum_inv_total ,
    FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(inv_date_str))) AS avg_inv_date
FROM
(
    SELECT
        o1.inv_total AS inv_total_str, o1.inv_date AS inv_date_str,
        (
            SELECT SUM(cost_total)
            FROM company_costs
            WHERE cost_customer_id = o1.inv_company_customer_id
        ) AS sum_cost_total
    FROM invoices o1
    INNER JOIN
        invoices o2 ON o2.inv_id <= o1.inv_id AND o1.inv_company_customer_id =  o2.inv_company_customer_id
    WHERE
        o1.inv_company_customer_id = 1 AND
        o1.inv_total > 0
    GROUP BY
        o1.inv_id,
        o1.inv_total
    HAVING
        SUM(o2.inv_total) > sum_cost_total
) t

Comment: "average inv_date for each customer after deducting costs ordered by inv_date"  . . . I just have no idea what this means.
Comment: @Gordon Linoff Ok, edited now.
Answer: Just group cost & invoice separately to have 02 subqueries, then join results to get final result
select cost_customer_id as customer_id, sum_cost_total, sum_inv_total, sum_inv_total- sum_cost_total as balance, avg_inv_date from (
select cost_customer_id, sum(cost_total) as sum_cost_total from
company_costs
group by cost_customer_id
) as c_total
inner join (
select inv_customer_id, sum(inv_total) as sum_inv_total, DATE_FORMAT(FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(inv_date))), '%Y-%m-%d') AS avg_inv_date from
invoices
group by inv_customer_id
) as i_total
on c_total.cost_customer_id = i_total.inv_customer_id

You should have this result:

Improve the condition with sum_inv_total > sum_cost_total in case of need.


ASP/NET MVC: Test Controllers w/Sessions? Mocking?

Question: I read some of the answers on here re: testing views and controllers, and mocking, but I still can't figure out how to test an ASP.NET MVC controller that reads and sets Session values (or any other context based variables.)
How do I provide a (Session) context for my test methods? Is mocking the answer? Anybody have examples?
Basically, I'd like to fake a session before I call the controller method and have the controller use that session. Any ideas?
Answer: Check out Stephen Walther's post on Faking the Controller Context:
ASP.NET MVC Tip #12 – Faking the Controller Context
[TestMethod]
public void TestSessionState()
{
    // Create controller
    var controller = new HomeController();

    // Create fake Controller Context
    var sessionItems = new SessionStateItemCollection();
    sessionItems["item1"] = "wow!";
    controller.ControllerContext = new FakeControllerContext(controller, sessionItems);
    var result = controller.TestSession() as ViewResult;

    // Assert
    Assert.AreEqual("wow!", result.ViewData["item1"]);

    // Assert
    Assert.AreEqual("cool!", controller.HttpContext.Session["item2"]);
}

Comment: I had to dig for this url, so here it is: http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx
Comment: It might not be obvious, but FakeControllerContext is a custom class. You can see the source for that here: http://stephenwalther.com/Downloads/Tips/Tip12/Tip12.zip
Comment: [http://web.archive.org/web/*/http://stephenwalther.com/Downloads/Tips/Tip12/Tip12.zip](http://web.archive.org/web/*/http://stephenwalther.com/Downloads/Tips/Tip12/Tip12.zip)
Comment: The source link above seems to be dead.. anyone have a copy?
Comment: Jacob, you are a Hero Among Men. The code still works wonderfully, as long as you use Controllerbase instead of Icontroller
Comment: Why do you have to create a FakeControllerContext  when a real ControllerContext exist in the Framework ?
Comment: For anyone else looking for the source to the `FakeControllerContext` and related classes: https://github.com/sergejusb/DotNetGroup/tree/master/Tests/Fakes
Answer: The ASP.NET MVC framework is not very mock-friendly (or rather, requires too much setup to mock properly, and causes too much friction when testing, IMHO) due to it's use of abstract base classes instead of interfaces.  We've had good luck writing abstractions for per-request and session-based storage. We keep those abstractions very light and then our controllers depend upon those abstractions for per-request or per-session storage.
For example, here's how we manage the forms auth stuff. We have an ISecurityContext:
public interface ISecurityContext
{
    bool IsAuthenticated { get; }
    IIdentity CurrentIdentity { get; }
    IPrincipal CurrentUser { get; set; }
}

With a concrete implementation like:
public class SecurityContext : ISecurityContext
{
    private readonly HttpContext _context;

    public SecurityContext()
    {
        _context = HttpContext.Current;
    }

    public bool IsAuthenticated
    {
        get { return _context.Request.IsAuthenticated; }
    }

    public IIdentity CurrentIdentity
    {
        get { return _context.User.Identity; }
    }

    public IPrincipal CurrentUser
    {
        get { return _context.User; }
        set { _context.User = value; }
    }
}

Answer: With MVC RC 1 the ControllerContext wraps the HttpContext and exposes it as a property. This makes mocking much easier. To mock a session variable with Moq do the following:
var controller = new HomeController();
var context = MockRepository.GenerateStub<ControllerContext>();
context.Expect(x => x.HttpContext.Session["MyKey"]).Return("MyValue");
controller.ControllerContext = context;

See Scott Gu's post for more details.
Answer: I found mocking to be fairly easy. Here is an example of mocking the httpContextbase (that contains the request, session and response objects) using moq.
[TestMethod]
        public void HowTo_CheckSession_With_TennisApp() {
            var request = new Mock<HttpRequestBase>();
            request.Expect(r => r.HttpMethod).Returns("GET");

            var httpContext = new Mock<HttpContextBase>();
            var session = new Mock<HttpSessionStateBase>();

            httpContext.Expect(c => c.Request).Returns(request.Object);
            httpContext.Expect(c => c.Session).Returns(session.Object);

            session.Expect(c => c.Add("test", "something here"));

            var playerController = new NewPlayerSignupController();
            memberController.ControllerContext = new ControllerContext(new RequestContext(httpContext.Object, new RouteData()), playerController);

            session.VerifyAll(); // function is trying to add the desired item to the session in the constructor
            //TODO: Add Assertions
        }

Hope that helps.
Comment: Wow, that's a lot of work just to mock one method :)  This is clearly the "too much setup" smell, and it's a result of using abstract base classes rather than interfaces as dependency seams.
Comment: Sure, I have seen a few projects where they put the setup code in a "helper" class and use it over and over again.
Comment: FYI, if your test needs so much setup that you need a 'helper' class, you're going to have pain and friction down the line.
Answer: Scott Hanselman has a post about how to create a file upload quickapp with MVC and discusses moking and specifically addresses "How to mock things that aren't mock friendly."
Answer: I used the following solution - making a controller that all my other controllers inherit from.
public class TestableController : Controller
{

    public new HttpSessionStateBase Session
    {
        get
        {
            if (session == null)
            {
                session = base.Session ?? new CustomSession();
            }
            return session;
        }
    }
    private HttpSessionStateBase session;

    public class CustomSession : HttpSessionStateBase
    {

        private readonly Dictionary<string, object> dictionary;

        public CustomSession()
        {
            dictionary = new Dictionary<string, object>();
        }

        public override object this[string name]
        {
            get
            {
                if (dictionary.ContainsKey(name))
                {
                    return dictionary[name];
                } else
                {
                    return null;
                }
            }
            set
            {
                if (!dictionary.ContainsKey(name))
                {
                    dictionary.Add(name, value);
                }
                else
                {
                    dictionary[name] = value;
                }
            }
        }

        //TODO: implement other methods here as needed to forefil the needs of the Session object. the above implementation was fine for my needs.

    }

}

Then use the code as follows:
public class MyController : TestableController { }

Answer: Because HttpContext is static, I use Typemock Isolator to mock it, Typemock also has an Add-in custom built for ASP.NET unit testing called Ivonna .


Error in the link navigation

Question: I am experiencing a navigation error on my site. When you click the nav item for the second time it does not work. e.g. If you click 'Team' it will take you to that section, but once you click a nav item for the second time it is a dead link.
Here is the site - http://evolvedengineering.com.au
Any help would be much appreciated! Thanks.
Comment: From JS console: `TypeError: jQuery.easing[jQuery.easing.def] is not a function`
Comment: @phts while this is correct, surely this would apply on page load rather than applying only after the first link has been clicked?
Comment: Anyway it's better to create fiddles and try to fix/reproduce such errors in a limited environment rather than finding bugs in a production code on a shipped site
Answer: Another JS console error:
<code>SyntaxError: missing ; before statement
</code>
Related to
<code>!function ($) {
    //=================================== scroll  ===================================//

$body.scrollspy({
      target: '#navbar-main',
      offset: navHeight
    })

    $window.on('load', function () {
      $body.scrollspy('refresh')
    })

    $('#navbar-main [href=#]').click(function (e) {
      e.preventDefault()
    })

});
</code>
Obviously something wrong with it. Where is it from?
Maybe should it be like this:
<code>!(function ($) {
    //=================================== scroll  ===================================//

    $body.scrollspy({
      target: '#navbar-main',
      offset: navHeight
    });

    $window.on('load', function () {
      $body.scrollspy('refresh')
    });

    $('#navbar-main [href=#]').click(function (e) {
      e.preventDefault()
    });

})(jQuery);
</code>

Error in the link navigation


How to use barssince function since specific time

Question: Is there a way I can use the barssince function to return the number of bars since a specific time occurring each day?
Answer: Yes you can.

Code:
<code>//@version=4
study("Time test")
specificTime = hour == 14 and minute == 0
plot(barssince(specificTime))
</code>


Taxonomy term block linked to a view

Question: I have a list of Authors listed as taxonomy terms .
 I also have a view list of Contents named Topics
I need to display the taxonomy terms of Authors in a View block (lets say in the home page).
and then link each term to its related content view page (displayed as List).
Thanks in advance.
Comment: It sounds like you want to use a contextual filter for the taxonomy term, and if none is present, to present a summary. Does that get you close to what you are trying to build?
Comment: Thank for your reply , yes i guess you got me right. I'll give it a try also..
Answer: You need to have 2 views:
First view: Author's content:

View should be a page.
Add all the required field.
set path to be like author/%/content.
Add a contextual filter for the content taxonomy term field (author).

Second view: Authors list

View should be a block.
Add field with term ID (author ID) and mark it to be excluded.
Add field with term name (author name).
Mark the term name output field to be overridden as a link.
Set author name as link text
Set author/[tid]/content as link path. (You can find correct value for term id in token replacements)

P.S. If you use panels it will be a bit different.
P.P.S. You can use standard taxonomy/term/% for the "First view: Author's content" view.
Comment: Thanks for your good explanation, i am afraid i have to bother your as i have been stuck with this issue for months without any solution, and i think what you kindly mentioned seems to be the nearest one to what i am looking for. i am stuck in step five and forward ...... Regards
Comment: can you add what you tried and what is the problem now to do to the task description?
Comment: i could not find  step 5. Set author name as link text and step 6. also.

Taxonomy term block linked to a view


Como Comparar Datas

Question: Tenho este código para fazer um save dos dados introduzidos, Dia, DiaInicio e DiaFim.
protected void btnSavePontuacao_Click(object sender, EventArgs e)
    {
        decimal id_TipoDia = 0;
        string Dia = txtDay.Text;
        string DiaInicio = txtStartDate.Text;
        string DiaFim = txtEndDate.Text;
        DateTime DtInicio, DtFim;

        if (!string.IsNullOrEmpty(Dia) && DateTime.TryParse(DiaInicio, out DtInicio))
        {
            bool result = false;
            DateTime? DtFimNullable;

            if (DateTime.TryParse(DiaFim, out DtFim))
            {
                DtFimNullable = DtFim;
            }
            else
            {
                DtFimNullable = null;
            }

            if (CheckIfRatesRangeValuesAreValid(id_TipoDia, DtInicio, DtFimNullable))
            {
                if (id_TipoDia > 0)
                {
                    result = FlowCreditTaxasProdutoExtensaoPrazoProviderManager.Provider.UpdateProdutoAmortizacaoCreditoDias(id, Dia, DiaInicio, DtFimNullable);
                }
                else
                {
                    result = FlowCreditTaxasProdutoExtensaoPrazoProviderManager.Provider.InsertProdutoAmortizacaoCreditoDias(Dia, DiaInicio, DiaFim);
                }
            }
            else
            {
                result = false;
            }

            if (result)
            {
                ShowMessageJS("sucesso");
            }
            else
            {
                ShowMessageJS("fail");
            }
        }
        else
        {
            ShowMessageJS("");
        }
    }

No

CheckIfRatesRangeValuesAreValid

gostaria de saber como posso fazer uma validação das datas, ou seja se a data de fim for inferior a data de inicio
Comment: A sua publicação não faz o mínimo de sentido se comparado com a sua dúvida real. Além disso, não tem como saber o que você quer fazer. Converter uma data para inteiro? De que forma? Qual informação da data você pretende usar para colocar num número?
Comment: Esse código nem compila. Não existe conversão implícita de `DateTime` pra `int`.
Comment: Certo! Agora eu gostava era de saber se dá e como converto isso?
Comment: Tudo editado! Pode ser que assim de para entender melhor. :)
Comment: Não entendo qual a relação deste código com o anterior e, pra ser sincero, ainda não dá pra entender nada.
Comment: Este código é a criação de botão salvar os dados introduzidos, certo? agora a questão é eu necessito de validar se a data esta correta ou nao. através do CheckIfRatesRangeValuesAreValid. o objetivo é fazer o insert na bd
Comment: @jbueno, esta resolvido pode-se fechar. Obrigado pela tentativa de ajuda
Answer: Você pode utilizar o método Método Compare do DateTime https://msdn.microsoft.com/pt-br/library/system.datetime.compare(v=vs.110).aspx.
int result = DateTime.Compare(date1, date2);

Como Comparar Datas


SQL Error: ORA-01861: literal does not match format string 01861

Question: I am trying to insert data into an existing table and keep receiving an error.
INSERT INTO Patient
(
  PatientNo,
  PatientFirstName,
  PatientLastName,
  PatientStreetAddress,
  PatientTown,
  PatientCounty,
  PatientPostcode,
  DOB,
  Gender,
  PatientHomeTelephoneNumber,
  PatientMobileTelephoneNumber
)
VALUES
(
  121,
  'Miles',
  'Malone',
  '64 Zoo Lane',
  'Clapham',
  'United Kingdom',
  'SW4 9LP',
  '1989-12-09',
  'M',
  02086950291,
  07498635200
);

Error:
Error starting at line : 1 in command -
INSERT INTO Patient (PatientNo,PatientFirstName,PatientLastName,PatientStreetAddress,PatientTown,PatientCounty,PatientPostcode,DOB,Gender,PatientHomeTelephoneNumber,PatientMobileTelephoneNumber)
VALUES (121, 'Miles', 'Malone', '64 Zoo Lane', 'Clapham', 'United Kingdom','SW4 9LP','1989-12-09','M',02086950291,07498635200)
Error report -
SQL Error: ORA-01861: literal does not match format string
01861. 00000 -  "literal does not match format string"
*Cause:    Literals in the input must be the same length as literals in
           the format string (with the exception of leading whitespace).  If the
           "FX" modifier has been toggled on, the literal must match exactly,
           with no extra whitespace.
*Action:   Correct the format string to match the literal.

Just not sure why this keeps happening I am learning SQL at the moment, any help will be greatly appreciated!
Comment: can we see your table structure? I suspect it is the phone numbers that are `VARCHAR2` or something and you're inserting them as `NUMBER`
Comment: `PatientHomeTelephoneNumber` is varchar2, you're inserting it as `NUMBER`, it should be surrounded by `''` and I don't see `PatientMobileTelephoneNumber` in your create statement.
Comment: @MikeBurton   CREATE TABLE Patient
(
 PatientNo CHAR(5) NOT NULL PRIMARY KEY,
 InvoiceNo CHAR(5) NOT NULL,
 PatientFirstName VARCHAR2(20) NOT NULL,
 PatientLastName VARCHAR2(20) NOT NULL,
 PatientStreetAddress VARCHAR2(40) NOT NULL,
 PatientTown VARCHAR2(20),
 PatientCounty VARCHAR2(20),
 PatientPostcode VARCHAR2(8) NOT NULL,
 DOB DATE NOT NULL,
 Gender CHAR(1) CONSTRAINT pat_g_nn NOT NULL,
 PatientHomeTelephoneNumber VARCHAR2(11) CONSTRAINT pat_phtn_nn );
Comment: I bet it's the `DOB` column. If that's the case, try using the `TO_DATE` function to parse the date string `'1989-12-09'` properly.
Answer: Try replacing the string literal for date '1989-12-09' with TO_DATE('1989-12-09','YYYY-MM-DD')
Comment: Or since it's in the right format, you could use a date literal as `date '1989-12-09'` instead of using `to_date()`.
Comment: @LizzyPooh - you can store an appointment date/time as a `DATE`, populating it with `to_date('2014-03-21 09:15:00', 'YYYY-MM-DD HH24:MI:SS')`, or `timestamp '2014-03-21 09:15:00.0'` - [read more](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements003.htm#sthref364).
Comment: Thanks guys, one more question, if you was to do time eg. appointment time, would you have to put something in front of the time if its formatted as '17:43:09'??
Comment: @alexpoole is it the same way for a time aswell ??
Comment: There's no time data type in Oracle, it'll still be `date` and I think you'll need to include the date part of it as well.
Comment: In general this error happens when we provide a value different to format we have defined in to_date
Comment: @AlexPoole How do you know it's the right format as both month and day are not greater than 12?
Comment: @PiotrDobrogost - that's the [ISO date format](https://en.wikipedia.org/wiki/ISO_8601); so it's a small assumption but using YYYY-DD-MM would be non-standard and cause great confusion. One of the great advantages of the ISO format is that it is unambiguous. Also the format mask in the answer is YYYY-MM-DD...
Comment: @AlexPoole You should check date format using `SELECT  *  FROM V$NLS_PARAMETERS`
Comment: @Alex78191 - the point of the answer using an explicit format mask (or of using a date literal) is that you don't rely on the NLS settings - which the developer can't assume will be the same for whoever runs the code. The original error means the OP's NLS settings didn't match the (apparently ISO) format in the insert anyway. Other answers refer to changing the supplied literal to match NLS settings, but it's still not a good idea to rely on those.
Answer: The format you use for the date doesn't match to Oracle's default date format.
A default installation of Oracle Database sets the DEFAULT DATE FORMAT to dd-MMM-yyyy.
Either use the function TO_DATE(dateStr, formatStr) or simply use dd-MMM-yyyy date format model.
Comment: The answer is incorrect and misleading. There's no Oracle's default date format. Default date format depends on NLS settings and will vary between sessions for a single Oracle instance. The order of priority: 1. Explicit format in `to_date`. 2. Explicitly set `NLS_DATE_FORMAT` and `NLS_LANGUAGE`. 3. `NLS_DATE_FORMAT` derived from explicitly set `NLS_TERRITORY`/`NLS_LANGUAGE`. 4. `NLS_DATE_FORMAT` derived from explicitly set `NLS_LANG` environment variable (via values of `NLS_TERRITORY`/`NLS_LANGUAGE` derived from `NLS_LANG`).
Comment: 5. `DD-MON-RR` in English if no above options are set (derived from `AMERICAN_AMERICA.US7ASCII`, see [Setting Up a Globalization Support Environment](https://docs.oracle.com/en/database/oracle/oracle-database/19/nlspg/setting-up-globalization-support-environment.html#GUID-86A29834-AE29-4BA5-8A78-E19C168B690A)).
Answer: You can also change the date format for the session.  This is useful, for example, in Perl DBI, where the to_date() function is not available:
ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'

You can permanently set the default nls_date_format as well:
ALTER SYSTEM SET NLS_DATE_FORMAT='YYYY-MM-DD'

In Perl DBI you can run these commands with the do() method:
$db->do("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD');

http://www.dba-oracle.com/t_dbi_interface1.htm
https://community.oracle.com/thread/682596?start=15&tstart=0
Answer: ORA-01861: literal does not match format string

This happens because you have tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.
You can overcome this issue by carrying out following alteration.
TO_DATE('1989-12-09','YYYY-MM-DD')

As a general rule, if you are using the TO_DATE function, TO_TIMESTAMP
  function, TO_CHAR function, and similar functions, make sure that the
  literal that you provide matches the format string that you've
  specified
Answer: Use a date literal. Ex. DATE '1989-12-09'
Comment: Are you sure that's valid syntax for Oracle?
Comment: Your answer already appears in this [comment](https://stackoverflow.com/questions/22542882/sql-error-ora-01861-literal-does-not-match-format-string-01861/22543299#comment34308577_22543299) (from Alex Poole). I think you could improve your answer if you add a link to the relevant [documentation](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Literals.html#GUID-8F4B3F82-8821-4071-84D6-FBBA21C05AC1) - which does **not** appear in the comment.


How to prove that an absolutely continuous function space on a finite closed interval is a separable space in this norm sense?

Question: $\quad$ Let a finite closed interval be $[a,b]$. Consider the absolutely continuous function space $\mathrm{AC}([a,b])$ on it, with a norm as follows:
$$\|f\|_{\mathrm{AC}}=\sup_{x\in[a,b]}|f(x)|+\|f'\|_{\mathcal L^1([a,b])}$$
$\quad$ How to prove that $\mathrm{AC}([a,b],\|\cdot\|_{\mathrm{AC}})$ is separable?
$\quad$ I already know that this space is Banach, and I want to find a countable dense subset of it. I've tried using Weierstrass approximation theorem, and found polynomials whose coefficients are rational, but I can't say that $\|f'-p'\|_{\mathcal L^1([a,b])}<\varepsilon$. Although I know that this is equal to the total variation of a function, it doesn't help a lot. Is there a problem with my direction? If yes, how do you find such a subset?
Answer: Since continuous functions are dense in $L^{1}$ Weierstrass Theorem shows that  there is a  polynomial $q$ such that $\|f'-q\|_{L^{1}}<\epsilon$. Let $p(x)=f(a)+\int_a^{x}q(t)dt$. Then $p$ is a polynomial, $p'=q$ and $\|f'-p'\|_{L^{1}}<\epsilon$. Also, $|f(x)-p(x)|=|[f(a)+\int_a^{x}f'(t)dt]-[f(a)+\int_a^{x}q(t)dt]|\le \int_a^{b}|f'-q|<\epsilon$ for every $x$. Now approxinate $p$ by a polynomial with rational coefficients.
Comment: Seems like a reasonable answer! However, there seems to be a slight typo at the end. That will be $|f'-q|$ instead and seems to have overlooked an absolute value sign. I hope you can correct it. I can accept the answer.
Comment: @daidaitx Thanks for catching the typos!


Javascript. Convert MD5 hash into an integer

Question: Is it possible in Javascript to convert something like this: d131dd02c5e6eec4 693d9a0698aff95c 2fcab58712467eab 4004583eb8fb7f89, which is the result of an MD5 hash function, into an integer ?
Comment: In the article describing the protocol it says "The consistent hash function assigns each node and key an m bit
identifier using SHA-1 as a base hash function. A node's
identifier is chosen by hashing the node's IP address [...]". So I can arrange these values 'around a circle', just by comparing the strings, but later on it says that each node has a list of successors: "s = successor(n+2^i), where 0 <= i <= m-1 (and all arithmetic is modulo 2^m)." m in the case of MD5 (which I'm using) is 128. I might be wrong, but I need to be able to perform modulo on the hash function. o.O
Comment: What do you want the integer for? You could convert it to a string, but not a JavaScript number (accurately, anyways).
Comment: I'm trying to implement the Chord protocol.
Comment: The only way you could even begin to cast it as an int is by using some form of substitution to replace the letters with a number, which creates a whole set of other issues...
Comment: @AndreiBogdan: So, to implement the Chord protocol, what calculation do you need to do on the hash (as an integer)?
Comment: I need to have integers to find out which successors are at +1 +2 +4 +8 .... "n" above should be a number ... o.O I'm starting to think that there's something I'm not getting here, but I can't figure out what exactly.
Answer: May not be perfect, but this suited my needs
export function stringToIntHash(str, upperbound, lowerbound) {
  let result = 0;
  for (let i = 0; i < str.length; i++) {
    result = result + str.charCodeAt(i);
  }

  if (!lowerbound) lowerbound = 0;
  if (!upperbound) upperbound = 500;

  return (result % (upperbound - lowerbound)) + lowerbound;
}

Comment: I really like this solution for the fact that it's simple and (since it relies on ASCII codes) can be easily reproduced on the server, but what's missing for me in it is that I would want the probability distribution to be guaranteed to be uniform between the two bounds, assuming the input is a uniform-random-choice string.
Answer: ES6 version, string to integer between 0-9:
string.split('').map(i => i.charCodeAt(0)).reduce((a, b) => a + b, 0) % 10

Answer: Maybe this one https://github.com/lovell/farmhash ?
const farmhash = require('farmhash');
const hexDigest = crypto.createHash('md5').update().digest('hex');
farmhash.fingerprint64(hexDigest);

Answer: That looks like a hexadecimal number, so you could try using the parseInt function and pass in a base of sixteen:
var num = parseInt(string, 16);

Edit:  This method doesn't actually work.  See the comments for details.
Comment: Should this answer really be accepted? It seems the comments suggest this is NOT the right approach or am I misunderstanding something?
Comment: If you need a nonce, you can take a substring of the hash (8, 12 octets) and then parseInt().
Comment: It returns a number in my console...   A huge number, but it's something.  I'm not sure how precise it ends up being though.
Comment: Very imprecise. Or, if you kept the spaces in, just the first part.
Comment: When I do `a = 'd131dd02c5e6eec4693d9a0698aff95c2fcab58712467eab4004583eb8fb7f89'`

`b = parseInt(a, 16)` is
`9.462148622078087e+76`

Then `b % 2` returns `0` and `b % 3` returns `2`, so wouldn't that mean it has precision about the lower digits?  Or is it lying or doing something weird?
Comment: It's lying.  `parseInt`: ~9.462148622078087e+76. Actual value: 94621486220780871705971335405839374945966571586290374999485260302979719462793, which is evenly divisible by 3 and not by 2.
Comment: No, you're right.  I just edited the answer to say it's wrong.
Comment: Agree with epx. Do you really need EVERY digit in the result? This is not reversible.


Lightweight webserver with SSPI authentification

Question: I'm looking for a fast, lightweight web server (for example nginx or lighttpd) which supports authentication to a Microsoft Kerberos authentication server (SSPI). This webserver must run under Windows and Linux.
There is a nice module for the Apache server (sspi_auth_module), but the performance gain of lightweight webservers seems very promising.
Modules I've found for the nginx server:

http-gsspi-auth-nginx-module which needs a recompilation which needs recompilation of the webserver (Might not work again with newer server versions?)
spnego-http-auth-nginx-module which does not support SSPI but only GSSAPI. I'm not shure if the authentication works over GSSAPI as the Microsoft documentation only explains the GSSAPI authentication in the other direction.

Are there other options? What would be your choice?
Comment: No.  You're responding to an auto-generated comment created when I voted to close this question.
Comment: This question appears to be off-topic for multiple reasons.
Comment: Could you please be a bit more precise?
Answer:
but the performance gain of lightweight webservers seems very promising.

While nginx is certainly faster than Apache, it ain't that much faster. Web applications usually take up 90%+ of the processing time, meaning the web server is usually the last place you want to go looking for performance if you want to make an appreciable difference.

Are there other options? What would be your choice?

My choice would be working with what I'm already familiar with, or what I know I can get to work.


How can I make a view that shows users all the who have flagged a single user?

Question: Background
I want to add a tab to the user profile that shows the logged in user which other users have viewed his/her profile.  I want to control this list in Views.
Until recently, I have been using the User Visits module.  However, this module does not integrate with Views and is no longer actively maintained.
I started building this using Views, Rules, and Flag.  Specifically, I created a flag Viewed profile, and then made a Rule to automatically flag a profile when a user visits another user's profile.
I then created a view of users with two displays.
My View
The first display, Profiles I visited, has a relationship to the Viewed profile flag and simply lists all profiles flagged (visited) by the current user.  Easy.
Now I want to create a second display, Users who have visited me.  In this case, I want to display all the users who have flagged the  current user.  However, I can't figure out how to do this.
I can add a relationship, Flags (by any user), but there could quickly be 10,000+ such flags on my site, so I am worried about the performance implications of loading all the flags like that.  Also, even if I load all the flags, I don't see how to easily filter them to users who have flagged the current user.
Instead, it seems like it would be easier to create a second flag, User who viewed me, and attach both flags (Viewed profile and User who viewed me) with a rule at the same time when a user visits a profile.  However, this seems like unnecessary duplication of information to me, since both flags link the same two users at the same time.  Is there a more elegant way to display this data in Views that will not lead to performance issues down the line?
Comment: I have a similar question about viewed comments: http://drupal.stackexchange.com/questions/88529/how-to-create-a-view-of-unread-comments-on-own-nodes-for-the-users-profile-page. I think both solutions will be quite alike.
Answer:
Add a relationship, Flags: User's flaggings for your flag.  Uncheck Include only users who have flagged content.
Add a contextual filter, Flags: Content ID and set Provide default value to User ID from logged in user.

This was not intuitive, but it appears to do the trick.


Readymade restful text-storing web service solution

Question: I want to build a simple client app for filtering and redirection of requests to simple web services. The platform is Linux, the interface is command line, the data is plain-text quotes, the primary commands will be as follows:
pull quotes <service> <filter>
export quotes <filter> <file>
import quotes <filter> <file>
push quotes <service> <filter>

I need a web service to serve as a source of plain-text data with simple RESTful interface like:
http://www.iheartquotes.com/api/v1/random?source=starwars

But with more capabilities - i need ability to search and filter through url/http-request thoroughly, at least like:
http://www.someservice.com/api/v1/quote?filter=churchill+war&max=25&order=most_popular

And get plain-text as a result. Add/remove capability would be very handy too.
Please, direct me:
(1) Are there readymade text storage web services with good ~restful interface (like above)?
(2) If not, is there a good framework in C++ or python?
I`ve tried:
(1) Wikia API - I would have to write a good web crawler to get something useful from there, which is not the purpose.
(2) MoinMoin wiki - I deployed it on VM, yet I found that it generates web page content dynamically and doesn`t expose necessary restful api.
Answer: In fact, there is one.
After long search, i found it - snipp.io
That doesn't make me stop wanting to make my own, however.


Simulated annealing on regression model

Question: I want to optimize adjust the parameters $\alpha, \beta, \gamma, \sigma²$ for a nonlinear regression model with the Maximum Likelihood estimator through Simmulated annealing, this is the model:
$$y = \alpha X_1 + \frac{\beta}{X_2 -\gamma} + \epsilon , \epsilon \sim N(0, \sigma²)$$
I know that simmulated annealing is an optimization method, and in order to optimize the MLE for this model I need to build a target function, but I have no idea on how to build the target function for this case, how should I do it? Also, after having a target function I'll need to generate the SA algorithm, but I also don't have any idea on how should I do it. Any hints or advices are more than welcome.
Comment: Why do you want to use simulated annealing for this problem, as compared to any of a number of algorithms that are likely to be much faster?
Answer: The objective function in non-linear least squares for fitting $y\approx f(\vec{x})$ is $\sum_i(f(\vec{x}_i) - y_i)^2$, which is in your case
$$Q(\alpha,\beta,\gamma) = \sum_{i=1}^n \left(\alpha x_{i1} +\frac{\beta}{x_{i2}-\gamma} -y_i\right)^2$$
As jbowman commented, for this particular (well behaved) objective function, there are better algorithms than simulated annealing. See, e.g., the docs of the GNU Scientific Library for an overview.

Simulated annealing on regression model


How to write Oracle Sql Query combining multiple tables

Question: I have 4 tables called A, B, C, C_History. Below is what is each table contains. cust_id is the common identifier for all tables.
A - cust_id,status,cust_type
B - cust_id,acnt_nmbr,acnt_systm
C - cust_id,email,mod_date
C_History - cust_id,email,mod_date(Same as C, used to insert rows which were deleted/updated in C).
I need to write a query combing all above tables to pull A.cust_id, B.acnt_nmbr,C.email(As New Email),C_History(As Old Email).
Caveat here is that, A and B tables will have only one record for a cust_id, but C and C_History can have multiple email records for a cust_id.
So from C table, i just need single email which was latest by using mod_date (TIMESTAMP datatype),
And from C_Hisory also, i just need single latest email using mod_date, but one more condition is that, whichever latest email picked from C_History, should not be same as  the latest email picked from C.
Please help with this as i am banging my head from 2 days trying to figure this out.
Thank you legends in Advance.
Comment: What SQL have you tried?
Comment: I am using oracle sql developer, and the database is Oracle 12c
Answer: <code>SELECT A.cust_id
    ,B.acnt_nmbr
    ,C.email
    ,C_History.email
FROM A
    ,B
    ,(
        SELECT cust_id
            ,MAX(email) KEEP (
                DENSE_RANK LAST ORDER BY mod_date
                ) OVER (PARTITION BY cust_id)
        FROM c
        ) c
    ,(
        SELECT cust_id
            ,MAX(email) KEEP (
                DENSE_RANK LAST ORDER BY mod_date
                ) OVER (PARTITION BY cust_id)
        FROM c_history
        ) c_history
WHERE a.cust_id = b.cust_id
    AND c_history.cust_id = a.cust_id
    AND c.cust_id = a.cust_id
</code>
Comment: Thanks Rama, but the above query didnt work.


proving inequality $P\left( {\exists i \in \left\{ {1,...,n} \right\}{Y_i} \geqslant t} \right) \leqslant nP(Y \geqslant t)$

Question: let $(Y_i)_i$ i.i.d random variables ($Y$ is positive).
for $n\geq 1$ and $t\geq 0$ , show that :
$P\left( {\exists i \in \left\{ {1,...,n} \right\} : {Y_i} \geqslant t} \right) \leqslant nP(Y \geqslant t)$
i have no idea, some help please.
Answer: The inequality may be more familiar to you in this form
$$\Pr\left(\bigcup_{i=1}^n (Y_i\geq t)\right)\leq \sum_{i=1}^n \Pr(Y_i\geq t).$$
Comment: Much better than mine!
Comment: yes, yes, i remember this formula. thanks
Comment: @AndréNicolas Well, more natural to a probabilist anyway. ;)
Comment: @johnalex Glad I could help!
Answer: The probability there is an $i$ such that $Y_i\ge t$  is equal to $1$ minus the probability that all the $Y_i$ are $\lt t$.
So if $p=\Pr(Y\ge t)$, then the probability not all the $Y_i$ are $\lt t$ is
$$1-(1-p)^n.$$
But by the Bernoulli Inequality, we have $(1-p)^n \ge 1-pn$, and therefore $1-(1-p)^n \le pn$.


Correct way of finding Sum of Ratios

Question: This is more of a statistical question rather than Excel Related. In the attached image, im trying to find out the ratio of Profit/Sales and then calculating overall Profit/Sales
Please let me know which one is correct.
Comment: Actually, this is less a statistical question -- since both approaches are *statistically* correct -- than a financial one. Therefore, any decision depends on the environment in which the calculation is being used. Note that once scaled up beyond this simple "toy" data example, the two approaches have hugely differing financial implications and consequences.
Answer: In the first method you're equal weighting each time period. In the second method, you're weighting by sales.
Let $p_t$ be profit in period $t$. Let $s_t$ be sales in period $t$. Let $y_t =\frac{p_t}{s_t}$ be profit to sales in period $t$.
First method:
Your first method of calculation is to take the sample mean of $y_t$.
$$ \bar{y}^{(1)} = \frac{1}{T}\sum_{t=1}^T y_t $$
Since $T=5$, every observation gets weight $\frac{1}{5}$. You're equal weighting each period.
Second method:
The second method is:
\begin{align*}
\bar{y}^{(2)} &= \frac{\sum_t p_t}{\sum_t s_t} \\
&= \frac{\sum_t s_t y_t}{\sum_t s_t}\quad \quad \text{since } y_t = \frac{p_t}{s_t}\\
&= \sum_t \left( \frac{s_t}{\sum_t s_t} \right) y_t
\end{align*}
In summary, your second method is equivalent to:
$$\bar{y}^{(2)} = \sum_{t=1}^T w_t y_t\quad \quad w_t = \frac{s_t}{\sum_{t=1}^T s_t}$$
Instead of equally weighting each time period (i.e. $\frac{1}{T}$), you're taking the average of the profit to sales ratio $y_t$ where you weight each period $t$ by sales.
Which makes more sense?
That's going to depend a lot more on context. If $t$ represents a month and you're thinking about overall, annual profitability, then method 2 is going to be more robust against all kinds of time series issues.
Imagine I'm a ski resort. Basically all my sales occur in Dec, Jan, and Feb. Taking the average where I give December the same weight as September is going to be VERY different than taking the average where I weight Dec 20x as much as September because December has 20x the sales.

Correct way of finding Sum of Ratios


Primefaces Schedule EventSelect - Method Not Found'

Question: Why isn't my method being found?
I'm using Primefaces 3.2 with Schedule, and after a lot of trouble managed to get some data into the event. I'm now trying to pass the data to an event and got some help in this post. Now I can't call the method to try and do something with the data (redirect to a page)

Java:
public void onEventSelect(SelectEvent selectEvent) throws IOException {
    ScheduleEvent event = (ScheduleEvent) selectEvent.getObject();
    id = (String) event.getData();
    redirect("lead/" + id + "/edit");
}

Trace:
Nov 27, 2013 11:08:09 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: Method not found: email@example.com(org.primefaces.event.ScheduleEntrySelectEvent)
javax.el.MethodNotFoundException: Method not found: firstname.lastname@example.com(org.primefaces.event.ScheduleEntrySelectEvent)
    at com.sun.el.util.ReflectionUtil.getMethod(ReflectionUtil.java:155)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:231)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:47)
    at org.primefaces.event.ScheduleEntrySelectEvent.processListener(ScheduleEntrySelectEvent.java:42)
    at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:102)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:760)
    at javax.faces.component.UIData.broadcast(UIData.java:1093)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:558)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1366)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:70)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337)
    at co.beek.pano.filters.SessionSharingFilter.doFilter(SessionSharingFilter.java:20)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337)
    at co.beek.pano.filters.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:21)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337)
    at co.beek.pano.filters.SessionSharingFilter.doFilter(SessionSharingFilter.java:20)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337)
    at co.beek.pano.filters.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:21)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:486)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:520)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:973)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:417)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:907)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
    at org.eclipse.jetty.server.Server.handle(Server.java:350)
    at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:442)
    at org.eclipse.jetty.server.HttpConnection$RequestHandler.content(HttpConnection.java:941)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:801)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:224)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:51)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:586)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:44)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:598)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:533)
    at java.lang.Thread.run(Unknown Source)

Any ideas?
Answer: Fixed with update of Primfaces to 3.5


Windows 10 Firewall Blocking Incoming VPN Traffic

Question: Client accesses Windows Server file share and is successful..
<code>[Local IP] 192.168.1.62
[VPN IP]   192.168.15.101     --->     [Server IP] 192.168.15.10
                             Success
</code>
Server side access windows 10 file share and is blocked by the Windows 10 Windows firewall..
<code>[Local IP] 192.168.1.62
[VPN IP]   192.168.15.101     <---     [Server IP] 192.168.15.10
                             Blocked
</code>
The SSL VPN application is identified as a public network by Windows 10.
Inbound firewall rule for the application has been automatically added by the application for itself for all public and private networks.
Disabling Windows 10 Windows firewall works.
Can anyone please advise on allowing this without disabling the firewall? Thanks.
Answer: In Windows 10 firewall, find all the enabled (ticked) rules that start with "File and Printer Sharing...", and individually go into each, and under the "scope" tab change from "Local subnet" to "Any IP Address"


QRect of full Virtual Desktop on Qt6

Question: How to get QRect of a full Virtual Desktop?
For example, for putting a window on a whole Virtual Desktop (multimonitor system).
The obsolete Qt5 function is:
QApplication::desktop()->geometry()

Answer: Something like this:
QRect desktopRect()
{
  QRegion virtualGeometry;
  for (auto screen : QGuiApplication::screens())
  {
    virtualGeometry += screen->geometry();
  }
  return virtualGeometry.boundingRect();
}

Answer: In PySide6 v6.4.0,
QApplication.primaryScreen().virtualGeometry()

returns PySide6.QtCore.QRect(-1920, 0, 3840, 1080).
I guess something similar can be done in Qt.
From the documentation:

virtualGeometry : const QRect
This property holds the pixel geometry of the virtual desktop to which this screen belongs
Comment: `primaryScreen().virtualGeometry()` is coordinates of the primaryScreen, but not the full Virtual Desktop, that could include other screens. Do you have ultrawide 32:9 monitor?
Comment: @yalov no, I have two 1920x1080 screens next to each other. This is why I considered `primaryScreen().virtualGeometry()` to be the full virtual desktop.

QRect of full Virtual Desktop on Qt6


Show $\|f-1_{[0,1/2]}\|_{\infty} \geq 1/2$ for any continuous function $f:[0,1] \to \mathbb{R}$

Question: Show that for any continuous map $f$ on $[0,1]$, the indicator map on [$0$,$1/2$] and $f$ has norm difference at least $1/2$.
I have been trying to prove it using the intermediate value property of R,but to no avail.Also I have seen a similar question being discussed in this website,but it gives a solution almost neglecting the "almost everywhere" condition.So I shall highly appreciate if anyone can provide a complete proof of the above statement.Thanks for any help.
Comment: If $f$ is continuous, then why do you mention that it is essentially bouned ? And what kind of norm difference do you want ?
Comment: Ah!You are right.I am only considering everything in the infinity norm.
Comment: by infinity norm you mean uniform (or $\sup$) norm ?
Comment: the infinity norm of f I am talking about is inf{M>0:|f|<=M a.e}
Comment: since our $f$ is already continuous function, then considering $L_{\infty}$ norm is the same as uniform norm, right ?
Comment: Not exactly,because the indicator function is not continuous and we want the distance between f and the indicator function.
Answer: Let $f,g: [0,1] \to \mathbb{R}$ be arbitrary functions and $x,y \in [0,1]$. It follows from the (inverse) triangle inequality that
$$\begin{align*} |f(x)-g(x)| &\geq |g(x)-g(y)|- |g(y)-f(x)| \\ &\geq |g(y)-g(x)| - \underbrace{\big| |g(y)-f(y)| - |f(y)-f(x)| \big|}_{\leq |g(y)-f(y)| + |f(y)-f(x)|} \\ &\geq |g(y)-g(x)| - |g(y)-f(y)| - |f(x)-f(y)|. \end{align*}$$
Hence,
$$|g(y)-g(x)| - |f(y)-f(x)| \leq |f(x)-g(x)| + |g(y)-f(x)| \leq 2 \|g-f\|_{\infty}.$$
Now set $g := 1_{[0,1/2]}$ and let $f$ be a continous function. Since $[0,1]$ is compact, $f$ is uniformly continuous, i.e. for any $\varepsilon>0$ we can pick $\delta>0$ such that $$|x-y| < \delta \Rightarrow |f(x)-f(y)| \leq \varepsilon.$$ In particular, if choose $y \in (1/2,1]$ and $x \in [0,1/2]$, $|x-y| < \delta$, we get
$$2 \|g-f\|_{\infty} \geq \underbrace{|g(y)-g(x)|}_{1} - \underbrace{|f(y)-f(x)|}_{\leq \varepsilon} \geq 1- \varepsilon.$$
Since $\varepsilon>0$ is arbitrary, we can let $\varepsilon \to 0$ and obtain
$$2 \|g-f\|_{\infty} \geq 1.$$
Comment: Note that the inequality "...<=2||g-f||" does not hold good everywhere
Comment: @Ester Why? It's the supremum norm. Note that the inequality $$|f(x)| \leq \sup_{y \in [0,1]} |f(y)| = \|f\|_{\infty}$$ is trivially satisfied.
Answer: I think you can go for a bit of an easier proof. Let $a$ be your indicator function and denote by $b(x) = \frac12$ for all $x$, so that $|a(x)-b(x)| = \frac12$ for all $x$. Consider a continuous function $f$ and suppose that $|a(x)-f(x)|<\frac12$ for all $x$, in particular $f\geq b$ on $[0,\frac12]$ and $f\leq b$ on $(0,\frac12]$, but then by intermediate value theorem $f  = b$ at some $\hat x$, hence $|f(\bar x) - a(\bar x)| = \frac12$: contradiction.

It uses intermediate value theorem as I wasn't sure your to no avail means you can't use that, or you can but did not know how.
Comment: I meant that I could not use it with success.
Comment: @Ester: nice, then now you can. The only trick is that in such problems you shall find a continuous function which is far away enough from the original one, and apply the IVT to that continuous function, not to the original discontinuous one.\
Comment: Both the proofs also has the same problem as I mentioned in my question as the totally neglected the "a.e formulation".For example in the last proof if you take the '"a.e consideration" then you do not get a contradiction at the last step.
Comment: @Ester: what do you mean by a.e. formulation? I do not see any a.e. formulation in your question - can you be more precise, please?
Comment: Look at the comments I have made above regarding the norm function of f.
Comment: @Ester: well, take a ball of small radius then - wanna do this yourself, or get a more elaborate hint?
Comment: @Ester: sure, are you joining?


In a Rails controller creating a new index in a 'map.do' loop fails, yet it's fine in Ruby

Question: I have a bunch of records from a database using select id, parent_id.... and loop over them using map.do creating a new index on each row.
records = results.map do |row|
    row['childs'] = {}
    comments[row['id']] = row
end

This works fine when called from the command-line but when placed in the Rails context I get the following error:
>ActiveModel::MissingAttributeError in CommentsController#index
can't write unknown attribute `childs'

Any idea what this would work in Ruby at the command line and not Rails? What am I missing about how Rails works?
Answer: row is not a hash, but an ActiveModel object instance, so you can't just add/assign new attributes to it like a key to the hash. In your model, you can use attr_accessor to initiate setters(writing) and getters(reading) for childs attribute.
Comment: Thanks for the reply, unfortunately adding the attr_accessor didn't work.
Comment: @user3096851: post what the whole method then, and tell, what `results` and `comments` contain
Comment: Sorry my last comment was so brief.  Here's the code in one full script.
Comment: results = client.query("SELECT id, parent_id, title, votes, popularity FROM >comments WHERE thread_id = 1 order by popularity desc, posted asc")
    comments = {}
    records = results.map do |row|row['childs'] = {}
  comments[row['id']] = row
end
comments.map do |k, v|
 if v["parent_id"] != 0
  #puts v["parent_id"]
  comments[v["parent_id"]]['childs'][k] =  v
 end
end
comments.map do |k, v|
 if v["parent_id"] != 0
  comments.delete(k)
 end
end
Comment: def display_comments(comments, level = 0)
 comments.map do |k,v|
  puts '-' * (level + 1) + " " + comments[k]["title"] + " (id: " + comments[k]["id"].to_s + ")\n"
  display_comments(comments[k]['childs], level + 1)
 end
end
display_comments(comments)


Mvcontrib.MVC3.Testhelper UpdateModel NullReferenceExceuption during Unit Test

Question: I am trying to unit test an edit action on my controller in ASP.NET MVC 3.
I have installed Mvcontrib.MVC3.TestHelper via nuget to mock out my controller Context but I am still getting a NullReferenceException
my code looks like this:
<code> [TestMethod]
    public void it_should_redirect_to_index_after_editing_a_something_successfully()
    {
        var something= new SomeThing
        {
            ID = Guid.NewGuid(),
            CreatedAt = DateTime.Now,
            LastModified = DateTime.Now,
            Owner = "Me",
            Status = "new",
            Title = "my Title",
            Attachments = new List<Attachment>()
        };

        var repo = new FakeRepository();
        var controller = new SomethingsController(repo);
        new TestControllerBuilder().InitializeController(controller);

        var result = controller.Edit(something) as RedirectToRouteResult;
        result.AssertActionRedirect().ToAction<SomethingsController>(x => x.Index());
    }
</code>
Production code looks like this...
<code> [HttpPost]
    public ActionResult Edit(SomeThing something)
    {
        if (ModelState.IsValid)
        {
            var _something = _repository.GetDocumentByID(something.ID);
            TryUpdateModel(_something);
            _something.LastModified = DateTime.Now;
            _repository.SaveChanges();
            return RedirectToAction("Index","Somethings");
        }
        return View(something);
    }
</code>
And even if I use UpdateModel or TryUpdateModel it alwas crashes with a NullReferenceException...
Any help, pointers would be fantastic...
Answer: Here's how you could proceed:
<code>public class Something
{
    public Guid ID { get; set; }
    public DateTime LastModified { get; set; }
    public DateTime CreatedAt { get; set; }
    public string Owner { get; set; }
    public string Status { get; set; }
    public string Title { get; set; }
}

public interface ISomeRepository
{
    Something GetDocumentByID(Guid id);
    void SaveChanges();
}

public class HomeController : Controller
{
    private readonly ISomeRepository _repository;
    public HomeController(ISomeRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Edit(Something something)
    {
        if (ModelState.IsValid)
        {
            var _something = _repository.GetDocumentByID(something.ID);
            TryUpdateModel(_something);
            _something.LastModified = DateTime.Now;
            _repository.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
        return View(something);
    }
}
</code>
and the test:
<code>// arrange
var something = new Something
{
    ID = Guid.NewGuid(),
    CreatedAt = DateTime.Now,
    LastModified = DateTime.Now,
    Owner = "Me",
    Status = "new",
    Title = "my Title",
};
var somethingElse = new Something();
var repo = MockRepository.GenerateStub<ISomeRepository>();
var controller = new HomeController(repo);
new TestControllerBuilder().InitializeController(controller);
repo.Stub(x => x.GetDocumentByID(something.ID)).Return(somethingElse);

var formValues = new FormCollection()
{
    { "Owner", "some owner" },
};
controller.ValueProvider = formValues.ToValueProvider();

// act
var actual = controller.Edit(something);

// assert
repo.AssertWasCalled(x => x.SaveChanges());
actual
    .AssertActionRedirect()
    .ToAction<HomeController>(x => x.Index());
</code>
Comment: Thanks for your help in my case it was ValueProvider which throws the exception and controller.ValueProvider = new FormCollection(); did the trick for that test... Thanks for the pointer
Comment: I have been searching for a while now. ValueProvider was the key!