MVC3 - Why doesn't the GET method in controller get called when rendering partial?

Question: I created a partial view, abc in my Views/Home
added this to my controller
[HttpGet]
public ActionResult abc()
{
return View();
}

and I call the partial view like this
@Html.Partial("~/Views/Home/abc.cshtml")

I'm able to see the partial view but the controller method does not get called. How can I render a partial view and call the controller get method?
Comment: You could pass the model to the PartialView (or via ViewBag)... to avoid needing the abc controller (the logic will be in the parent controller). This way is a bit messy but it works.
Answer: I think you are looking for the Html.Action method (on MSDN):
View:
@Html.Action("abc", "Home")

Controller:
[HttpGet]
public ActionResult abc()
{
    return PartialView();
}

Answer: A controller renders a view.  You clearly have a controller that is rendering your parent view (the one that has the @Html.Partial in it.  Partial simply merges the partial view with the current view, so no additional controller is accessed.
Think about it.  You are not actually specifying an action, now are you?  You're only specifying a view.  Views cannot be rendered by themselves.
What you want is @Html.Action(), which renders based on a controller action.
Comment: Partial Views are like views.  There's no real difference.  It's just that Partial merges one view with another.  Views are templates, they have nothing to do with controllers.  So when you render a partial in your view, it's just merging two templates.  No controller access is performed
Comment: Great, thanks I misunderstood PartialViews. I was treating them like Views too.


Change columns order by dates

Question: I have several columns, each has first cell with an Excel date serial number (ex. 42767 which is equal to 2017-02-01). I have to reorder all columns ascending by those dates.
Comment: have you tried the sort button on the Data ribbon? Or do you want to do this programmatically?
Comment: using vba, posted an answer below (I managed to record macro)
Answer: NVM, posting an answer to my own question:
<code>Range("B1").Select
Range(Selection, Selection.End(xlToRight)).Select
ActiveWorkbook.Worksheets("Arkusz1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Arkusz1").Sort.SortFields.Add Key:=Range("B1:C1") _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Arkusz1").Sort
    .SetRange Range("B1:C8")
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlLeftToRight
    .SortMethod = xlPinYin
    .Apply
End With
</code>

Change columns order by dates


Unknown Notation in Pokémon Theme

Question: I just purchased a copy of the Pokémon Theme and I came across this note which I'm not sure how long to play it.
Can someone please help me?
I'Ve attached an image of the one (or two) note/s below

Update
I've also uploaded an image of the full bar (or at least most of it) to avoid any confusion
Comment: Could you provide an image that includes more of the surrounding music, including text (if there is any)?
Comment: You have to borrow another cellphone from a friend, so you can hold one phone in each hand and capture both notes simultaneously ;)
Comment: Your edit has shown that Tim's answer is correct; look there! The different syllables in the text are shown with these different rhythms in the music.
Answer: More than likely it shows note timing for another verse, where there are different words which need to be sung/played in a slightly different rhythm.There doesn't seem to be a hard and fast rule as to whether the tail on the smaller note follows the main note's tail or goes in the opposite direction, but it makes sense that the value of each note will be different - otherwise the timing for each word in each verse would be the same.
EDIT: now we can see the bar proper, it seems to me that strictly speaking, there should also be a small quaver rest,at the beginning, to signify verse two starts on the second beat (as there is already a quaver rest, not shown, at the beginning of verse one). Call me pedantic - some versions will have that.
Comment: Probably not.  Where there are two verses of lyrics, no further explanation is required, or normally provided.

ALWAYS provide context with a question of this sort rather than zooming in on what you think is the material detail!
Comment: @LaurencePayne - I guess the comment is for Dedwards - if so, it will only be aimed at him, and read, if you start with '@'.
Comment: I think this would normally include a text instruction below like "(2nd time)", which might not be shown in this image. Correct?
Comment: @LaurencePayne, yes that's a little more apparent now that the zoomed out image has been added.
Comment: Yes, there is a quaver rest at the start of the stop bar. I'Ve just posted an image of the bar in its entirety, so I'm hoping that there'all be no more confusion...
Comment: That's just what we needed! Thanks.There's technically a missing crothet rest (small) at the beginning of the bar, to show second verse rest, but as it's pretty obvious, it's not included. Although some versions will show it, I guess.
Comment: Hi @Tim, I'Ve just posted my own answer on this. Can you please have a look and tell me what you think?
Comment: @LaurencePayne Ok, I wasn't aware of that, I'll keep that in mind :)
Comment: I comment on the topic and on points raised, not particularly to any individual.
Comment: @Dedwards, yes there is no text instruction saying anything like (2nd time) the only other "text" in this sheet music is the copyright notice at the bottom of the 1st page, the title, composers name and the rest of the chord symbols like shown in the image above.
Answer: Depending on context this may mean a number of different things:

it could be a used in a different verse as Tim suggest, but since you state "pokemon theme" I have some doubts, whether any text exists
it could be some sort of embellishment (grace note), where the big note indicates the dotted quarter as total duration and the small says, that it is supposed to played as separate eigth and quarter note. Typically a slur would he lead to the main note, however.
it could be a cue note, indicating that some other instrument starts at this time with an eigth (typically then the name of this instrument can be found nearby)
it could be a more ornamented alternative (if further smaller printed notes follow under the dotted quarter)
Comment: If it was a grace note, with a slur, it would look more like a tied note, apart from which, the grace note would differ from the following note. So don't think an ornament is it. A cue note? on a piano score, in a place like that, maybe not.The theme does in fact have words.
Answer: I'm going to post my own answer on my question based on what a piano teacher said.
He said that since the song goes two times through that the note with the stem up (big crotchet note) gets played first and then after the first ending, play the one with the stem down (smal quaver note).
Please share your opinion on this...
Comment: Pretty well what I put. Big note, first time (1st verse), little note instead, 2nd time (2nd verse). I think the red herring was the missing information on the original question. This sort of writing is all over songs - it won't happen in purely instrumental pieces. So was I right all along?
Comment: @Tim Hi Tim, Yeah, I'm probably going to mark off your answer as correct.
Answer: I found one of these too. Basically, just playing it as if they were tied together. The composer probably wrote it like that because they wanted you to emphasize that particular note. Hope this helped!
Answer: It's a grace note. You play the first note quickly before the second without adding time to the length of the bar and then finish out the allotted time for the second note with the second note.
Comment: How can it be? It's the same note sound as the bigger one.
Comment: yes i think it's a grace note!  baBAAAAAA
Comment: Grace notes are about rhythm - not pitch. The first note comes a little bit before the second note. Think about the "Ta-Da!" rhythm. The first note is the "ta".
Comment: Yes, they are. But usually pitched differently from the main note. However this isn't one of them!

Unknown Notation in Pokémon Theme


How to show filtered content as suggestion of "reference autocomplete field" based on a field value of reference content

Question: Say, one content type is "CONCEPT" and it has a field named 'STATUS'.
Another content type is "Article" and it has a node-reference auto-complete field named 'CONCEPT FROM'.
Now I want to see only "CONCEPT" contents whose status value is "ACCEPTED" as a suggestion of "CONCEPT FROM" auto-complete field.
Comment: You have to create a view & apply filter on them that "Show CONCEPT whose STATUS is ACCEPTED"
Answer: Thanks @shawn-conn
His answer is perfect but I can't give vote because of minimum reputation. See following solution in details:
Step 1:
First create one entity reference view
Note: In this view include referenced content type (e.g.: CONCEPT) and it's filter/condition field (e.g.: STATUS)
Step 2:
From MANAGE FIELDS of the required content type (e.g.: PROJECT), Add field that FIELD TYPE will be Entity Reference and WIDGET will be autocomplete then click on the SAVE button.
Step 3:
Now choose Views: Filter by an entity reference view option in MODE field and choose your views that is created in Step 1 in View used to select the entities field from ENTITY SELECTION section of the field settings page.

Step 4:
Click on the Save settings button to save changes.
Answer: If you're using the entity reference module, what you can do is autocomplete from an entity reference view. You can add a filter on your entity reference view that filters nodes of type CONCEPT with a status field value of ACCEPTED. Once your view is created, you can select it under the Entity selection fieldset.


Problema para usar o return (Python 3)

Question: Estou começando agora e tentei fazer de acordo com a explicação do meu professor, mas não estou conseguindo rodar a função. Quero que retorne para o começo se o usuário responder errado ao invés de apenas encerrar.
def paintcalculator():
    print("What measurement unit do you use?")
    unit = int(input("What measurement unit do you use?\n1 - Meters \n2 - Centimeters \n3 - Inches \nOption number:"))

    if unit == 1:  #meters
        height = float(input('What is the  height of the wall? '))
        width = float(input('What is the width of the wall? '))
        layers = float(input('How many layers do you want to use? '))
        area = height * width
        liters = 2 * area * layers
        print('You will need aproximately {:.2f} liters of paint.'.format(liters))

    elif unit == 2:  #centimeters
        height = float(input('What is the  height of the wall? '))
        width = float(input('What is the width of the wall? '))
        layers = float(input('How many layers do you want to use? '))
        area = (height*0.01) * (width*0.01)
        liters = 2 * area * layers
        print('You will need aproximately {:.2f} liters of paint.'.format(liters))

    elif unit == 3:  #inches
        height = float(input('What is the  height of the wall? '))
        width = float(input('What is the width of the wall? '))
        layers = float(input('How many layers do you want to use? '))
        area = (height*0.0254) * (width*0.0254)
        liters = 2 * area * layers
        print('You will need aproximately {:.2f} liters of paint.'.format(liters))

    else:
        print('Please, answer correctly.')
        return paintcalculator()

Comment: Ao contrário do que a resposta abaixo sugeriu, chamar a função `paintcalculator` dentro dela mesma não é a melhor opção, pois isso é um uso indevido de [recursão](/q/21551/112052) e isso pode causar problemas (além de ser uma complicação desnecessária). O melhor é usar um *loop* (como o `while` por exemplo). Como não ficou claro pra mim quando é para sair e quando é pra continuar, segue uma sugestão/palpite: https://ideone.com/bBFNp0
Answer: Boa tarde
Bom pelo que eu não acho tão legal chamar a função dentro dela mesmo, no caso de sua aplicação criar uma estrutura de repetição infinita como whle True: já estaria funcionando, assim bastaria criar uma opção para encerrar o menu
segue a alteração feita:
def paintcalculator():

while True:
    print("What measurement unit do you use?")
    unit = int(input("What measurement unit do you use?\n1 - Meters \n2 - Centimeters \n3 - Inches \nIf you want break this program press number [9] \n\nOption number: "))

    if unit == 1:  # meters
        height = float(input('What is the  height of the wall? '))
        width = float(input('What is the width of the wall? '))
        layers = float(input('How many layers do you want to use? '))
        area = height * width
        liters = 2 * area * layers
        print('You will need aproximately {:.2f} liters of paint.'.format(liters))

    elif unit == 2:  # centimeters
        height = float(input('What is the  height of the wall? '))
        width = float(input('What is the width of the wall? '))
        layers = float(input('How many layers do you want to use? '))
        area = (height * 0.01) * (width * 0.01)
        liters = 2 * area * layers
        print('You will need aproximately {:.2f} liters of paint.'.format(liters))

    elif unit == 3:  # inches
        height = float(input('What is the  height of the wall? '))
        width = float(input('What is the width of the wall? '))
        layers = float(input('How many layers do you want to use? '))
        area = (height * 0.0254) * (width * 0.0254)
        liters = 2 * area * layers
        print('You will need aproximately {:.2f} liters of paint.'.format(liters))

    elif unit == 9:
        break

    else:
        print('Please, answer correctly.')

paintcalculator()
assim você apenas chama a sua função quando deseja utilizar ela.
espero ter ajudado!
Answer: Boas, primeiramente gostaria de o informar que devia explicitar em que cenário exato ocorre o erro que refere. Dito isto, percebi que o seu problema ocorre depois do utilizador escolher uma opção no menu e não respeitar o tipo de valor inserido.
Coisas a fazer para resolver o problema e melhorar o código:

Cada opção do menu deveria corresponder a uma função mesmo que o código seja simples.
Recorrer ao mecanismo de try e except existente no python.
Apesar na solução apresentada não o fazer, deve ser pensada uma maneira de resolver a repetição existente em height, width e layers. Talvez um objeto auxiliar que guarde a informação nos seus atributos.

Aqui fica um exemplo de solução

def optMeters():
    height = float(input('What is the  height of the wall? '))
    width = float(input('What is the width of the wall? '))
    layers = float(input('How many layers do you want to use? '))
    area = height * width
    liters = 2 * area * layers
    print('You will need aproximately {:.2f} liters of paint.'.format(liters))

def optCentimeters():
    height = float(input('What is the  height of the wall? '))
    width = float(input('What is the width of the wall? '))
    layers = float(input('How many layers do you want to use? '))
    area = (height*0.01) * (width*0.01)
    liters = 2 * area * layers
    print(
        'You will need aproximately {:.2f} liters of paint.'.format(liters))

def optInches():
    height = float(input('What is the  height of the wall? '))
    width = float(input('What is the width of the wall? '))
    layers = float(input('How many layers do you want to use? '))
    area = (height*0.0254) * (width*0.0254)
    liters = 2 * area * layers
    print(
        'You will need aproximately {:.2f} liters of paint.'.format(liters))

def paintcalculator():
    try:
        unit = int(input(
            "What measurement unit do you use?\n1 - Meters \n2 - Centimeters \n3 - Inches \n4 - Exit \nOption number:"))
        if unit == 1:  # meters
            optMeters()

        elif unit == 2:  # centimeters
            optCentimeters()

        elif unit == 3:  # inches
            optInches()
        elif unit == 4:  # exit opt
            return
        else:
            print('Please, answer correctly.')
            paintcalculator()  # No return needed
    except:
        print('Invalid input detected')
        paintcalculator()

Comment: Eu tentei rodar seu código, só que o que aparece no terminal é só o local onde o arquivo está no meu pc, o que tenho que fazer? Gostei bastante do seu, me disseram pra usar a função while True, eu usei e deu cerrto, mas eu prefiro muito mais a ideia de transformar cada opção em uma função, ou classe, não sei
Comment: @LFHarada Vc pode muito bem combinar as 2 coisas: separar em funções **e** usar o `while` em vez de chamar a função dentro dela mesma...
Comment: @LFHarada o while é também uma ótima opção controlar o fluxo do código e bastaria usar um break para sair do loop, sobre o problema que descreve deve precisar de chamar a função no código (pensava que o que apresentou não era o código completo). Experimente adicionar paintcalculator() no final do código.

Problema para usar o return (Python 3)


What are counter examples for these statements?

Question:
Question 1.
Let $\{T_i\}_{i\in I}$ be a family topologies on a set $X$.
Provide an example that $\bigcup T_i$ is not a topology on X.

>

Question 2.
Let $X$ be a compact space and $Y$ be a topological space.
Let $f:X\rightarrow Y$ be a continuous bijection.
Provide an example that $f$ is not a homeomorphism.

What are these two counter examples?
For Question 1, I think two non-comparable(for the order $\subset$) topologies should be given, but I cannot think of one since every finite dimensional normed space has the unique topology under any norm. I cannot think of an example that is not a finite-dimensional topological space.
For Question 2, $Y$ must not be Hausdorff. Likewise above, I cannot think of an explicit example which is not Hausdorff...
Comment: @Servaes:  Intended to use "the null set trick" only once per example, so intended $X = \varnothing, I \neq \varnothing$.  No biggie.
Comment: Oh, by the way, this is the 294,000th question on this site.
Comment: There is a three element solution to question 1.
Comment: @EricTowers I don't get what you mean/... Would you please be specific?
Comment: There is a set with three elements having two topologies each containing three elements whose union is not a topology.
Comment: For question 2, $X$ and $Y$ are equivalent as sets, so you might as well look for examples $f:X \rightarrow X$.  Then the only possible difference is two different topologies on the same set.
Comment: @Eric Towers: There is even a zero element solution to question 1!
Comment: @Servaes:  True.  $I = \varnothing$ is such.  Doesn't work for $X = \varnothing$ though since all topologies on $\varnothing$ have one element.  Not nearly so symmetric as my quip above...  :-)
Comment: @Eric Towers: It does work for $X=\varnothing$, because $\bigcup_{i\in I}T_i=\varnothing$ if $I=\varnothing$, which isn't a topology on any space, including $X=\varnothing$.
Answer: A non-trivial example for question one: let $X = \{1,2,3\}$.
Take $T_1 = \{\emptyset,\{1\},X\}$, and $T_2 = \{\emptyset,\{2\},X\}$.  Note that $T_1 \cup T_2$ is not a topology.
Answer: For question one take $I=\varnothing$.
For question two take $X=Y=\{0,1\}$ with the discrete resp. trivial topologies, i.e.
$$T_X=\{\varnothing,\{0\},\{1\},\{0,1\}\}\qquad\text{ and }\qquad T_Y=\{\varnothing,\{0,1\}\}.$$
Then taking for $f:\ X\ \longrightarrow\ Y$ the identity will do.


Difficulty Understanding Application of the Multiplication Principle

Question: While leafing through "Introduction to Probability" (Hwang, Blitzstein), I encountered the following problem.

A standard deck of cards is shuffled well. Two cards are drawn randomly, one at a time without replacement. Let $A$ be the event that the first card is a heart, and $B$ be the event that the second card is red. Find $P(A|B)$.

I'm having difficulty formally determining $P(B)$. Intuitively, I know it's $\frac{1}{2}$, but I'm having difficulty formalizing my intuition.
Here's what the book says about $P(B)$,

$$P(B) = \frac{26\times 51}{52 \times 51} = \frac{1}{2}$$
since there are 26 favorable possibilities for the second card and for each of those the first card can be any other card.

I kind of understand this. The book says, "chronological order is not needed in the multiplication rule", but here I don't see exactly how the multiplication rule can even be used.
After all, order does seem to matter, since by the time the second card is being drawn there are only 51 possibilities not 52. So how can we apply the multiplication rule backwards here?
Comment: Usually, drawing a diagram of the events is helpful.  See https://stats.stackexchange.com/a/113353/919 for an illustration.  In particular, note that in such diagrams, time (sequence) plays no role.
Answer: Why can we apply the multiplication rule backwards?
The easiest way of thinking about it is that all of your events are of the form $(c_1,c_2)$ where the $c_i$ are cards and $c_1 \neq c_2$.
For example $(5 \text{ hearts}, 10 \text{ diamond})$ is a valid event but $(5 \text{ hearts}, 5 \text{ hearts})$ is not.
Computing the value of $p(B)$ is now equivalent to computing

What is the number of events/draws $(c_1,c_2)$ such that $c_2$ is red?

Well for each $c_2$ for a red there is 51 possibilities for $c_1$
that satisfied the condition so that
\begin{equation}
N(B)= \sum_{c_2 \text{ is red}} \#(c_1 \neq c_2) = \sum_{c_2 \text{ is red}} 51 = 26 \cdot 51
\end{equation}
Now counting all of the possible draws we have that
\begin{equation}
N(\text{All draws})= \sum_{c_2 } \#(c_1 \neq c_2) = \sum_{c_2 } 51 = 52 \cdot 51
\end{equation}
so that probability is
\begin{equation}
P(B) = \frac{N(B)}{N(\text{All draws})}= \frac{26 \cdot 51}{52 \cdot 51} = 1/2
\end{equation}
Okay but, Why can we apply the multiplication rule backwards?
Well go through the whole argument and replace $c_2$ with $c_1$ and heart with red and it is still valid.

Rigorously We have that we are actually considering all of the two subsets of the set $C$='cards"=$\{1,...,52\}$; so that for example counting all of the ways that you can get $\{x,2\}$ for any $x$ is the same as counting all of the ways that you can get $\{2,x\}$ for any $x$.

Don't let the language confuse you; the most important strategy in proble-solving is to strip away the language of all the misleading details; i.e.

Find the right abstraction. Get rid of unnecessary details that cloud the mind and find good notation/definitions that make this possible.

I personally recommend Feller's introduction to probability theory; the whole first volume is discrete combinatorial probability theory and the book is considered a treasure amongst mathematicians.


Finding equilibrium points for the system $y'=Ay$

Question: Given a matrix $A= \begin{pmatrix} 8 & 4 \\ -10 & -5 \end{pmatrix}$, I am supposed to find all of the equilibrium points for the system $y'=Ay$
I find the eigenvalues are 0 and -3, and the corresponding eigenvectors $(1,-2)^T$ and $(4,-5)^T$
I am not sure what equilibrium points they want, are we particularly choosing $\lambda=0$?
Comment: Well, what *is* an equilibrium point?
Comment: nullspace of $Ay=0$?
Comment: probably when $y' = 0$ i.e. $Ay=0$. This justifies the choice of $\lambda=0$...
Answer: $y_0$ is an equilibrium point $ \iff Ay_0=0 \iff y_0= t (1,-2)^T$ for some $t \in \mathbb R.$


Integration and Riemann sum

Question: Query 1
Using the formula
$$
\sum_{j=1}^{n} \sin(jt) = \frac{\cos\frac{t}{2}-\cos\left(\left(n+\frac{1}{2}\right)t\right)}{2\sin\frac{t}{2}}
$$
evaluate $\int_{0}^{\frac{\pi}{2}} \sin(x) \space dx$ as the limit of a Riemann Sum.
$\underline{Attempt}$
\begin{align}
\int_{0}^{\frac{\pi}{2}} \sin(x) \space dx &= \frac{\pi}{2n} \lim_{n\to \infty} \sum_{j=1}^{n} \sin\left(j\frac{\pi}{2n}\right) \leftarrow(\textit {Let $t$ = $\frac{\pi}{2n}$)}
\\ &= \frac{\pi}{2n} \lim_{n\to \infty} \frac{\cos\frac{\pi}{4n}-\cos\left(\left(n+\frac{1}{2}\right)\left(\frac{\pi}{2n}\right)\right)}{2\sin\frac{\pi}{4n}} \\ &=  \lim_{n\to \infty} \left(\frac{\pi}{2n}\right)\frac{\cos\frac{\pi}{4n}-\cos\left(\frac{\pi}{2}+\frac{\pi}{4n}\right)}{2\sin\frac{\pi}{4n}} \\ &= \lim_{n\to \infty} \left(\frac{\pi}{2n}\right)\frac{\cos\frac{\pi}{4n}-\sin\frac{\pi}{4n}}{2\sin\frac{\pi}{4n}}
\end{align}
Query 2
Using the result
$
\forall k \in \mathbb Z^+ ,$
$$ \\ \sum_{j=1}^{n} j^k = \frac{n^{k+1}}{k+1}+\frac{n^k}{2}+P_{k-1}(n),
$$
where $P_{k-1}$ is a polynomial of degree at most $k-1$, deduce the result:
$$
\int_{0}^{a} x^k \space dx = \frac{a^{k+1}}{k+1}
$$
$\underline{Comment}$ : I do not understand why only the first portion of the summation result is used.
Thanks!
Comment: Use *\begin{align}* and *\end{align}*. and use *&* on that part of the line where you want to align...
Comment: @KingTut: Thanks! Previously I used &=& to align at the equal sign, instead of &= like you recommended. This used to work in Latex, but not here on Mathjax.
Comment: Netuser I think first you need to find the sum of sines whose phase are in arithmetic progression. Consider imaginary part of $e^
{ix}$
Answer: Hint for Query 1:
$$
\left(\frac\pi{2n}\right)\frac{\cos\left(\frac\pi{4n}\right)-\sin\left(\frac\pi{4n}\right)}{2\sin\left(\frac\pi{4n}\right)}
=\frac{\overbrace{\cos\left(\frac\pi{4n}\right)}^{\to?}-\overbrace{\sin\left(\frac\pi{4n}\right)\,}^{\to?}}{\underbrace{\dfrac{\sin\left(\frac\pi{4n}\right)}{\frac\pi{4n}}}_{\to?}}
$$
For the denominator, see this answer.

Hint for Query 2:
$$
\int_0^ax^k\,\mathrm{d}x\ \ \overset{\text{Riemann Sum}}\longrightarrow\ \ \sum_{j=1}^n\left(\frac{aj}n\right)^k\frac an
$$

Integration and Riemann sum


Reading date as a character in googlevis

Question: so this is in reference to an earlier question: Using a ordered factor as timevar in Motion Chart but it wouldn't let me leave this as a comment :/
So, I am having the same error the person earlier was having, thing is, according to the answer: "the documentation says that timevar argument can't handle factor. It can handle character if and only if they are in a particular format, that is (for example): 2010Q1." Thing is, I already have my data formatted like that, in a csv file: http://www.filedropper.com/texasgdp
Time      GDP
2006Q1    500
2006Q2   1000
2006Q3   2000
2006Q4   2600....etc

So, if this is the character format, why am i still getting the same error? Is there a way I could just have rstudio reread that entire column as a "character" rather than a factor?
Answer: Yes, you can use this as you read the data in:
read.csv('file path',stringsAsFactors=FALSE)

Or you can convert the column to a character vector after reading the data:
df$Time <- as.character(df$Time)


Why do I get a "no such file" error message from Rails' generate?

Question: Why do I get a "no such file" error message when I run this command?:
$ rails generate controller Pages home contact
c:/Users/Michele/rails_projects/sample_app/config/application.rb::in 'require': no such file to load -- sprockets/railtie (LoadError)
        from c:/Users/Michele/rails_projects/sample_app/config/application.rb:8
        from c:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.11/ lib/rails commands.rd:15
        from c:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.11/ lib/rails commands.rd:15
        from script/rails:6:in 'require'
        from script/rails:6

Answer: looks like you don't have all Rails required libs installed.
try to run gem install rails command
or, maybe, you have borken rails app tree - try to create new rails app with rails new my_app_name


iii9 - I progression in Bach?

Question: In the last of his 15 Sinfonias (aka Three-Part Inventions), Bach uses quite a daring approach to the tonic chord. Occurring in a sequential progression by downward thirds, it can be described most plainly as a V7-iii9-I cadence.

Analyzing a similar example from the WTC, Walter Piston, or rather his editor DeVoto, interprets the A as an anticipation, resolving with change of octave to the A in the alto (Harmony, 4th ed., p.128) which seems rather far-fetched.

Have more recent theorists got anything of sense to say about the idiom? And are there precedents from the 17th century, before the congealment of functional harmony?
Comment: Thanks for all the insightful answers! I somehow didn't see them when I joined Music.SE and posted this question four years ago.
Comment: And by the way, if anyone's interested in the history, I think this is a peculiarly "German" kind of figuration: I've found comparable examples in Hassler's toccatas, but none in French or Italian Baroque music.
Answer: If I may offer a different analysis of the excerpt in question, it appears to me that the progression moves as thus:
I6/3 - ii - V6/5 - I
Intermediary arpeggiations are upper-tertian embellishment that essentially just serves as smooth harmonic leading between chords.  This is a very common progression for the period and a very common progression for JS Bach.  A iii9 is such a weak chord that, as others have mentioned, its use would be negligible, and it certainly wouldn't stand up in a background Schenkerian Analysis.
Having played through all of JS Bach's 371 Harmonized Chorales, I can tell you that I cannot recall a time where he ever used a iii chord in a cadence, or even as part of an anticipation.  Anticipation suggests non-chord tones and/or dissonance.  A iii chord is merely an upper-tertian extension of a I chord, and therefore is glossed over aurally.  I think it would be very difficult to distinguish a iii as a plausible anticipation aurally.
Did JS Bach use iii chords at all?  Absolutely.  Sometimes to prolong I, sometimes to serve different connective functions, but I would say never at a cadence; not unless it was re-purposed as a secondary dominant/leading tone chord
As you might already know, mediant and chromatic mediant relationships did not become popularly in music until at least Beethoven (moving from I to bVI in developments! Of course, you can reason that he went to the relative major of the subdominant minor - two ways of getting to the same place.) If someone has an earlier example than Beethoven, feel free to share!
I mention this because it is important to remember the time period.  During the 17th century, composers were not in the habit of thinking vertically.  Yes, they were conscious of vertical intervals (you must be to resolve your counterpoint correctly), however, composers did not think in vertical blocks like so many composers do today.  By and large, composers thought linearly, and creating their harmonic progressions as embellishments of a 1st-Species framework (Hint: this is one reason why Schenkerian analysis works in this period!). Apart from the larger, intended harmonic motion (note the first beat of each measure in the example), the motion in between facilitates the prolongation of chord tones through upper-tertian harmony, and as such, should be seen moreover as an extension of those larger, horizontal harmonic shapes.
If you took this thought literally, the passage is reduced to a progression of I6/3-ii-I which, in Schenkerian analysis, the ii would be seen as a passing tone between F# and D, with the whole passage resulting in a prolongation of I.
As this is only an excerpt and we are not analyzing the entire piece or movement, it is difficult to determine exactly how important any of the chord outlines are in the excerpt. Because of this reasoning and the given excerpt, I am not being strict in my thoughts concerning harmonic downbeats, and, as I mentioned above, inserted the V6/5 in my analysis above.
Answer: I'm inclined to agree with @dwn. The relative major here isn't particularly tonicised: it is just emphasised a bit by melodic motion through the upper auxiliary, and a slowdown of harmonic rhythm. It is otherwise just a natural conclusion to the preceding sequence. It's the next 2 bars that start to look a bit more like a conventional cadence, only Bach reinterprets D in the second half of the 2nd bar as the seventh of a dominant 7th on E and moves to A, and thence to E, using the figuration of the last bar of your example.
The nature of the piece is very much "toccata": Bach isn't going to make any cadences before the end that aren't undercut in some fashion, and the easiest way to end a sequence without stopping is just to change the figuration (and harmonic rhythm in this case), and start a new sequence.

As for the WTC example, I think it is proper to say that the entire bass figuration after the tie is an anticipation. Look at the outline it takes up to and including the low F: E-A-C-F. Then take a look at how he delays the resolution of the suspension over the F to emphasise the IV7 sonority.
The A in specific is an anticipation of a note that isn't there: if he had continued the melodic sequence (up a 3rd, down a 5th) in the bass, the note immediately following F would have been A. That, however, wouldn't have confirmed F as the root as well as C does, and wouldn't have allowed the ascending scale segment to set up ii6 (which is anticipated on the 4th beat of the bar). The setup in the second half of the bar, as he has it, can be read as IV7, vi6, ii, vi 6-4 (and thence ii6), and also more simply as an elaboration with passing notes of IV7 - the ambiguity, I think, is deliberate, but would have been somewhat broken if he used A in the bass after the low F. There's even a little ambiguity as to whether the D [semiquaver] in the descant [in the figuration] on the 4th* [3rd] beat is a neighbouring* [passing] tone or a resolution of the suspension, which throws the real weight of resolution onto the start of the next bar* [beat].
Now here's the interesting notion: what happens immediately after the low F is suggesting a harmonic continuation of the "up a 3rd, down a fifth" movement with its suggestion of vi and ii. Notice too that there is a pattern working through the entire bar, that of anticipating the following harmony by a variety of means. I haven't analysed the entire prelude, but I would not be surprised to see that pattern showing up a lot.
The A in question is thus something of an anticipation of a "pensato", and yeah, I think Bach was sneaky enough to do something like that. I don't think there's any question that the harmony in the first half of the measure is the dominant 7th on C: the A in question doesn't have enough weight (unprepared, on the 4th [semi]quaver of the bar* [2nd beat]) to become a root.
The main point to take away from all this, I think, is that Baroque composers, including Bach, didn't necessarily see all the voice leading as a figuring of the bass: a lot of notes (even in the bass) would be considered non-harmonic tones, and those could be used both freely and motivically, as was done here. The A in question can be seen as a kind of nota cambiata that helps to trace a broken chord on F and anticipates the following harmony through melodic means.
Edit: The last sentence of the fourth paragraph (2nd after the break) should read "There's even a little ambiguity as to whether the D semiquaver in the descant in the figuration on the 3rd beat is a passing tone or a resolution of the suspension, which throws the real weight of resolution onto the start of the next beat."
The last sentence of the 6th paragraph should read "I don't think there's any question that the harmony in the first half of the measure is the dominant 7th on C: the A in question doesn't have enough weight (unprepared, on the 4th semiquaver of the 2nd beat) to become a root."
This is the problem of doing an analysis of this sort in the wee hours of the morning: I become innumerate. <wry grin>
Answer: It's easy to see a figure consisting of a stack of thirds, and think that this represents the chord. But this isn't necessarily the case. The figures here could more plainly be seen as merely ornamenting a central pitch with upper and lower auxiliary tones, a third above and below. It may seem odd to think of notes a third away as neighbors, since that term is technically used only for stepwise motion, but the key is that this is a rapid figuration, and it is always the first note of each group which is repeated (thrice), and is always on the beat. The other notes act primarily as unaccented decorations or ornaments, and would certainly be seen as non-functional if they were only a step away, instead of a third.
I'm trying to be careful about calling them "non-functional" rather than "non-harmonic" because they notes may indeed be harmonic (and usually are, though not always), but they are less important in determining the harmony. IOW, the harmony does not depend on these ornaments.
Thus I would progressively simplify the figure as follows (again, I'm using N and P -- Neighbor and Passing tones, in a very loose, and technically wrong manner):

Based on this reading, I've prepared a series of four reductions (separated by double bars) which demonstrates my analysis. Note that I've also included the measure preceding the three that you posted, as it helps to indicate the linear nature of this progression. I've also converted the meter to a more straightforward 3/4 for no particular reason. You'll probably have to right-click -> View Image in order to read the thing at full size.

For the most part, all I've done here is replace the elaborate figure with a simpler dotted figure that emphasizes the functional accented note, and the falling thirds motif. You'll note the clash in the penultimate beat between the stepwise A-G-F♯ in the R.H. and the skipwise (A-F♯-D) in the L.H.
In the R.H., I've removed the repeated-octave notes in the third beat of each bar (incorporating them into the previous note an octave lower), and I've lengthened the accented notes where they bleed into the next chord. With those actions done, it was natural to view the R.H. as consisting of two voices: the second imitates the first a beat later and a fifth lower, and the remaining sixteenth notes act as upward resolutions for implied suspended sevenths. In the L.H. I've merely removed the unaccented tones, as if they were passing tones. This reveals the passage progresses in fifths, instead of thirds.
In the R.H. I've removed the unaccented sixteenth notes (which were doubling the bass notes), and I've made the previously implied 7-6 suspensions explicit. In the L.H., I've also gotten rid of the repeated octaves. This represents what I see as the pure 3-voice counterpoint that underlies this progression.
I've further removed the alto voice, and the third beat of the bass (which is always the fifth of the following note) in order to emphasize the linear nature of the progression.

My harmonic analysis comes from levels 2 and 3, and allocates one chord per beat. I'll leave off the implied sevenths from the chord symbols, since they aren't actually written (except for the final A7).
G Em/G C♯dim | F♯m  D/F♯  Bm | Em C♯dim/E A7 | D
IV (ii6) vii | iii (I6) vi | ii (vii6) V7 | I
You'll notice that within each bar, the chords are dropping by a third each beat, then raising a fourth across the bar lines. If you were to remove the intermediate chords on beat two (in parenthesis) -- which are all first inversion chords that retain the same bass note as the previous chord -- then you're left with a simple circle of fifths progression. If you further remove the third beat chords, you're left with a simple descending scale, as in reduction 4:
IV - iii - ii - I

From the harmonic analysis, we can also see why the confusion arises: most of the time, when the figure occurs, it is ornamenting the third of the current chord. For example, in the first measure, in the first beat, it occurs on the B, which is the third of the G chord. On the second beat it occurs (in the bass) on the third of the E minor chord (which happens to be in first inversion, so the ornamenting notes a third below end up conveniently playing the root. On the third beat, the figure occurs on the E in the R.H. (which is the third of the C♯ diminished). But in that third beat, it also occurs on the chord root in the L.H., so the decorating notes end up being a third beneath the root. For the most part, this note a third beneath the root doesn't interrupt the flow of the harmony too much (it actually helps to stabilize the diminished chord) but in the penultimate measure, it does slightly weaken the dominant harmony there, by having that F♯ that clashes with the rest of the A7 chord.
Comment: To clarify for other readers, you're suggesting that the tertian figurations are mostly not actually functional chord tones, but ornamentations that prolong chord tones? In your 2nd level analysis, you incorporate the V7 but drop it in level 4. Are you arguing that the passage in question resolves in a Plagal cadence through passing-tone motion?
Comment: @jjmusicnotes A sort-of-yes to the first question, with the caveat that, while the chords don't necessarily depend on those notes, in *most* cases, the thirds do end up belonging to the chords -- except for the lower thirds in the last beat of the bass. As to the 2nd question, I hadn't thought of it as a plagal cadence. The overall piece is in Bm, but in the previous 4 bars, there's a Bm-E-A-D Co5's progression, which this section extends and accelerates, modulating to D. At a very high level, I see Co5 prog's as just a decorated form of a scale: Bm-(E)-A-(D)-G-(C#dim)-F#m-(Bm)-Em-(A7)-D.
Answer: I'm not well versed, but to me it just looks like a sort of not-yet-rooted tonic, with the G (last treble note in the 2nd measure) being a neighbor tone. I'd agree that the effect of mediant as anticipation seems negligible.
Answer: You can interpret this as a circle of fifths progression. Taking each six note arpeggio as its own chord, you get F♯m, Bm, Em, A, D. The Em lasts 2 measures, as does the A. And yes, the F♯ creeps in in that last group. But you can just call that the F♯ of a D triad, which is what it is landing on. Not a three chord.
But honestly, it's much easier to just see it visually on the piano, because I think that's how Bach would've come up with it.

iii9 - I progression in Bach?


Extracting triplets from a sentence in Python

Question: I am trying to extract triplets (subject - Predicate - object) from a given sentence using stanford dependency parser in Python. Can someone guide me through this.
Thanks in advance
Answer: You can refer to the following links for triples extraction from sentences.

https://github.com/tdpetrou/RDF-Triple-API
http://nlp.stanford.edu/software/openie.html
https://github.com/philipperemy/Stanford-OpenIE-Python


How to use Terraform modules for code re-use?

Question: Terraform v0.12.x
I thought I understood Terraform modules for code re-use after reading the docs, but apparently not.
Say I want to build a target group+EC2 instance infrastructure. I have this directory structure.
/terraform
/terraform/green.tf
/terraform/blue.tf
/terraform/module_ec2/ec2.tf
/terraform/module_tg/tg.tf

For example, /terraform/module_ec2/ec2.tf has this
resource "aws_instance" "ec2" {
  ami               = var.ami
  availability_zone = var.availability_zone
  ....
}

and /terraform/module_tg/tg.tf has
resource "aws_lb_target_group" "tg" {
  name = var.tg_name
  ...
}

I want blue.tf and green.tf to build their respective target group+EC2 infrastructure by using module_tg and moodule_ec2 and just passing to them the respective key/value pairs each module needs. How can I do this, that is, what would be contents of blue.tf and green.tf?
Comment: yes you can have multiple modules in each file. no, you cannot run green and blue independently from each other, they are in the same directory and therefore belong to same deployment.
Comment: https://www.terraform.io/docs/configuration/modules.html: `module "ec2" { source="./module_ec2" ... } ...`
Comment: Can I have several modules in the `blue.tf` and `green.tf` files? If so, how can I just then build the `blue.tf` and not `green.tf`, and visa-versa?
Comment: Ah I see, so how can I refactor my directory structure so I can run `blue` and `green` targets separately, but still have code re-use for the other modules? Maybe you can put this in an answer, because it all makes sense. Note that I have files (non-modules) common to both `blue` and `green` deployments. Thanks!
Comment: Also what if I need an output from the `green` run that I need in the `blue` run? For example, if the `green` run creates an EBS volume, how can the `blue` run get it?
Answer: Consider breaking up your terraform configurations along lifecycle boundaries. The lifecycle of a set of resources is the time starting when you run terraform apply and ending when you run terraform destroy.
In your example and comments, you bring up an EBS volume which should be available to both green and blue stacks. The EBS volume or any other dependencies that outlive either stack should be in a separate folder.
To access details of the EBS volume or other longer-lived dependencies from each of your stacks there are a few options:

use a terraform_remote_state data source pointed at the remote state of your dependencies configuration.
employ a naming convention so the dependencies can be discovered using specific data sources
a variation on item 1, create an output module in a subfolder of your dependency configuration which includes a terraform_remote_state and exposes only the outputs of the configuration.


.setEnabled only seems to be able to be toggled once

Question: Is there a reason that .setEnabled() only seems to work once? I wish to toggle it on and off multiple times during an activity lifecycle depending on the content. i've tried wrapping it in switch statements.
<code>        GAME_STATE_INPLAY = true;
        if (GAME_STATE_INPLAY = true) {
            explainButton.setEnabled(false);
        }
    ....
        if (c.getString(7).toString().length() > 0) {
                explainButton.setEnabled(true);
        }
</code>
Comment: Is it if (GAME_STATE_INPLAY == true) ?
Comment: Elaborate please. What activity life cycle are you using?
Comment: no no, i didn't mean to be so specific with the lifecycle part.i just meant over the course of when the user needs that (trivia game screen open) and that boolean is just some arbitrary something i made up cause i was hoping that the problem would be fixed if it wasn't placed in on create all by itself.
Answer: try to get the btn by id again:
<code>   if (GAME_STATE_INPLAY = true) {
        Button explainButton =(Button) findViewById(R.id.button);
        explainButton.setEnabled(false);
    }

    if (c.getString(7).toString().length() > 0) {
            Button explainButton =(Button) findViewById(R.id.button);
            explainButton.setEnabled(true);
    }
</code>
Comment: when you setEnabled to false the first time, the explainButton value stored didn't change, it changed programmatically on the display. so when you wanted to set it true again, the value was already true.
Comment: crazy. it totally worked. is there something else i should i know about it? so i don't make the error again?


Convolution with Gaussian, without dstributioni theory, part 3

Question: I only know basic $L^p$ theory (nothing about distributions) and am trying to prove the following:
Let $t>0$, $f\in L^{p}(\mathbb{R}^n,m)$, $\Gamma(t,x)=(4\pi t)^{-n/2}e^{-|x|^2/4t}$ and
$$
u(t,x)=\int_{\mathbb{R}^n}\Gamma(t,x-y)f(y)dy.
$$
If $p=\infty$, then $u(t,\cdot)\to f$ a.e. as $t\to 0$.
I've shown that $||u(t,\cdot)||_p\leq ||f||_p$ for $1\leq p\le\infty$ but haven't gotten anywhere from here. Could someone please give some hints or suggest a reference (these seem to be very well-known and widely applicable results).
(This is the first, and this is the second part of my question.)
Comment: Well, it seems that Folland's Real Analysis contains a Theorem that applies in this case: My edition is the Second One, so you might look at Thm. 8.15 for an idea for the proof for an even more general setting (the same problem is true if you only require that $p \in [1,+\infty]$).
Comment: I wrote at the first post that the solution was lenghty, but I don't know whether there are simpler proofs. Right now I'm looking for a good reference for you.
Answer: Well, it seems that Folland's Real Analysis contains a Theorem that applies in this case: My edition is the Second One, so you might look at Thm. 8.15 for an idea for the proof for an even more general setting (the same problem is true if you only require that $p\in [1,+\infty]$).


ssl certificate installation on tomcat

Question: I am trying to create a new certificate for my scala play framework on ubuntu but I cannot import my key with keytool. I haven't been able to figure out what is causing it so I thought I'd see here if anyone recognizes my problem.
I first create my private key using
keytool -genkey -alias tomcat -keyalg RSA -keystore tomcat.keystore

Then I generate my CSR
keytool -certreq -keyalg RSA -alias tomcat -file my-csr-file.csr -keystore tomcat.keystore

copy and paste the generated CSR into godady
select the tomcat server on godaddy and i received godaddy new certification.i get 3 files:
28042ad1aadd20.crt
gd_bundle-g2-g1.crt
gdig2.crt

Installing Root and Intermediate Certificates
wget https://certs.godaddy.com/repository/valicert_class2_root.crt –no-check-certificate
keytool -import -alias root -keystore tomcat.keystore -trustcacerts -file valicert_class2_root.crt

wget https://certs.godaddy.com/repository/gd_cross_intermediate.crt –no-check-certificate
keytool -import -alias cross -keystore tomcat.keystore -trustcacerts -file gd_cross_intermediate.crt

Second intermediate (gd_intermediate.crt):
wget https://certs.godaddy.com/repository/gd_intermediate.crt –no-check-certificate
keytool -import -alias intermed -keystore tomcat.keystore -trustcacerts -file gd_intermediate.crt

Installing SSL Certificate
keytool -import -alias tomcat -keystore tomcat.keystore -trustcacerts -file my-csr-file.csr

Here I receive the following error
keytool error: java.security.cert.CertificateParsingException: java.io.IOException: ObjectIdentifier() -- data isn't an object ID (tag = 49)

Anyone recognize the problem?
or any other way to install godaddy ssl certificate for tomcat server using ubuntu
Comment: This can be due to several different things, namely: absent JCE, parsing errors in your cert (if ASCII, remove unneeded headers before `---BEGIN CERT---`). Try `keytool -printcert` on your cert to see a full error report.
Comment: `gd_cross_intermediate.crt` and `gd_intermediate.crt` *used to be* correct, but in 2014 all major CAs including GoDaddy **changed to SHA-256** for certs instead of SHA-1; for GoDaddy **these are called "G2"**. `gdig2.crt` is the new G2 intermediate for clients that have the GoDaddy G2 root, which now (in 2015) most do. `gd_bundle-g2-g1.crt` is the new cross-chain if clients have only old GoDaddy root; either split out the first two certs and add them separately, or concatentate at least those two after your leaf cert and import that chain against the privatekey alias.
Answer: The CSR is used to generate a CRT, you need to go to godaddy and paste the CSR value from this keystore, this will generate the CRT - which you then import. At present, you are trying to add the CSR not a CRT.
Comment: OP did paste the CSR to Godaddy and "get 3 files" of which `28042ad1aadd20.crt` is obviously the cert. He just needs to *use* that file -- and with the correct chain, see above.

ssl certificate installation on tomcat


Corporate Wireless policies

Question: Our corporate laptops are restricted to only allow internet access through our proxy (connection profile in Internet Explorer pushed through a GPO). On a remote/3rd party connection this is allowed by creating a VPN back to the corporate network (Cisco VPN Client -> Cisco ASA), at which point the proxy is available and we route all internet traffic through that.
We have recently had the question raised by one of our users who was attempting to use a Wireless connection on a train. The train company requires that the user fills in a form hosted on their own network.
The problem we had was that the user wasn't able to get to the train companies internal page as the proxy wasn't available. They couldn't connect the VPN as they hadn't completed the train companies logon page.
We considered that we could specify this page in the 'bypass proxy for this address...' which would allow a connection to only that page, this was rejected as we would then have to start adding every train company, hotel, public hotspot that works in this way (which must be a list of thousands)
Second suggestion was to allow connections to any local network range (10.* or 192.*) but the implications with regards to security seemed to dangerous. Plus the page offered up by the train company would be http://virginrailwifisignup page and not http://192.168.1.1
At which point we were stumped. The now familiar cry went up in the office "we can't be the only ones who have had this problem" but I haven't been able to find anyone who has mentioned a useful solution.
So I ask you, Server Fault, how have you managed this?
Worth noting, we provide all our mobile users with 3G connections for when they are out and about, they VPN back in over that but its flaky as hell on a train.
Comment: Are you an end user or do you manage the VPN/network systems described above?
Comment: @Chopper3 I'm the administrator
Comment: What proxy server are you using?
Comment: @TimBrigham We have a sophos web appliance - WS1100
Answer:
Our corporate laptops are restricted to only allow internet access
  through our proxy (connection profile in Internet Explorer pushed
  through a GPO).

Pushing settings  to a connection profile in IE, you don't only allow internet access through your proxy. You just make a notion about internet access through your proxy, and increase accessibility.
If I understand correctly what you want is to have users connect to your VPN
in order to access the internet thus using your proxy. If that's the case you have to be carefull because now all potential malware/attacks get routed through your network.
By default in most Windows after XP when you connect to a VPN you are using the default gateway on the remote network. Thus you have to ensure that this setting stays like this. You can accomplish that through your GP or CMAK or by a script or by even doing it manually as a leveraged user once for every machine.
But on web-based logins your users have to access some random website (and thus the internet) ! This is where the Network Location Awareness kicks in

The Group Policy client will apply policy settings whenever domain
  controller availability returns. Examples of connection events that
  trigger Group Policy processing include establishing VPN sessions,
  recovering from hibernation or standby, and the docking of a laptop.
  This benefit can potentially increase the level of security on the
  workstation by more quickly applying Group Policy changes.

So if your user establishes a connection to a network other than your work network
you will trigger your VPN connection and all is good.
I have to admit not an easy job especially when there is client diversification.
The other way of going around it is locking everything down disabling the lot of it and making another user account for usage outside your VPN and forcing other kinds of limitations (e.g. no videos,audio,specific domains,etc.)
Yet another way is to block certain ports from a specific connection or limit the access to your VPN e.g. no access to internal servers
Comment: Thanks, this is the kind of thing I was looking for. I think it still comes down to, at some point, allowing usre access to an untrusted site which is something we will need to reveiw internally (and I suspect reject). I'm currently reviewing our builds anyway so I'll stil NLA on my list to consider.
Answer: I guess I'm a little confused but why must all of your clients, when outside of your brick and mortar, be forced to connect to the internet only to get routed back through your own network?
I get having a VPN client to be able to call home and access resources on the network but why do you want all of their browsing traffic sent back to you just to be routed back out again?  Is it for content filtering purposes or simply so they may also be able to access corporate resources.
Regardless, I guess I'm just a little confused on why the setup needs to be like this in the first place.  If they aren't on your network why bother with proxying them back to the office if in fact they also have a VPN client?  I guess I'm curious if the whole thing may be a little over complicated, over engineered if you will.
Comment: Our client is a subject to PCI. I'm not an expert but various PCI tests have found flaws with having end users with access to general wifi. I believe one of the earliest failures was that the pen testers setup an AP called "[Client]Wifi", end users connected and were presented with 'Enter user username/password'. There are other concerns with access to webmail systems from corporate laptops as well. In the end forcing all connections from all locations through VPN gives us the right tick marks on the PCI compliance form whilst still allowing remote access.
Answer: Use a real firewall to restrict access - not just the MSIE connection profile.
Comment: Could you provide any further info as to how this would work. All clients have a Trend Firewall that comes as part of the AV but in testing (another admins not mine so I don't know the detaiuls) it was identified as being not worth enabling. My argument would be that the situation is, basically, you allow access to untrusted web pages without the proxy or you don't. I don't see how a client firewall would be intelligent enough to differentiate beetween a valid Virgin Trains signup page vs some dodgy site. The proxy is a managed appliance which ew rely on for that very service.
Comment: I might add that I am aware that the IE connection profile isn't a particularly amazing way of managing this but its what we have and at the moment time is limited so we have to pick our fights. This isn't one we would prioritise over everything else right now.

Corporate Wireless policies


How can I invoke hook function after the block is loaded?

Question: I have created a view with content types in my Drupal 8 and for this view page I have created a customised filter. The view page is located in sites/mysite/modules/view/config/install
And the customised filter is located in sites/mysite/modules/filter/src/Plugin/Block
The issue for me is that I want to change a title of the filter in hook function in view.module . But it is loaded before the FilterBlock. How can I specify the order of the invoked files?
Answer: To change the order of which module's hook will fire first when more than one module implements the same hook you can use hook_module_implements_alter(). It was created for exactly this kind of situation.
Answer: There is two way to do so :

Using this module modules weight
Using hook_module_implements_alter


Submit a form after finished Ajax request

Question: I want to submit a signup form. In the form onload I called one JavaScript function to validate all the fields.
Here I should call one ajax function to validate one field.
var checkExists = true;

checkExists = ajaxQuery(data);

if (checkExists) {

    alert('Already exists');

   return false;

}

ajaxquery is an ajax function which will return true or false based on the result.
My problem is that no matter what the AJAX result is, it will first execute the if condition and return false.
So my form always gets stuck even checkExists variable value is false. Please help
Comment: What does your ajaxQuery function look like? You should use a callback function from the ajax call so you will only execute the if statement when you get a response back.
Answer: because ajax query is asychronous, you need to put your code in the callback method of ajaxQuery: http://api.jquery.com/jQuery.ajax/
$.ajax({
  url: "test.html",
  context: document.body,
  success: function(data){
     // your logic goes here.
     alert('Already exists');
     return false;
  }
});


QML converting string of datetime to a qml parsable date failing on GMT time zone

Question: In a QML (javascript) function, I am trying to parse a date from the backend. All is working except that the date contains the GMT+0100. This causes the conversion to invalidate. For instance:
var dateTimeString = "Thu Sep 12 10:56:06 2019"
console.log("testing date conversion: ", Date.fromLocaleString(locale, dateTimeString, "ddd MMM dd hh:mm:ss yyyy"))

Works totally fine and returns
testing date converstion: Thu Sep 12 10:56:06 2019 GMT+0100

However the date actually comes through as a string like
var dateTimeString = "Thu Sep 12 10:56:06 2019 GMT+0100"

And this causes it to be invalid when it tries to convert. I realise I could strip off the GMT+0100 however this may contain useful information.
What is the correct way to get it to respect the time zone? I tried adding a t at the end, however this doesn't fix it. (I understand t is the timezone).
Thanks
Comment: Maybe this link [Development for Sailfish OS: Features of working with dates and time zones](https://weekly-geekly.github.io/articles/324812/index.html) is useful...
Answer: you could use the javascript "Date" to parse the string before converting it with Qt.
It would then look something like this:
var dateTimeString = "Thu Sep 12 10:56:06 2019 GMT+0100"
var dateTime = new Date(dateTimeString)
console.log("testing date conversion: ", Qt.formatDateTime(new Date(dateTime), "ddd MMM dd hh:mm:ss yyyy"))


Retornando arquivos XML dentro de uma pasta em PHP

Question: estou usando o seguinte código para listar e ler os arquivos XML nesta pasta. Mas como a listagem me retorna . e o .. meu sistema retorna erro que não e possível acessar esses arquivos. Segue os códigos utilizados.
<code>$pasta = $data[0].$data[1].$data[2]."_".$data_end[0].$data_end[1].$data_end[2];
$l_nfe = dir("xml/".$pasta);

while($arquivo = $l_nfe -> read()){
    simplexml_load_file("xml/".$pasta."/".$arquivo);
}
</code>
A string me retorna "xml/01042018_30042018/.." alguém poderia me ajudar como listar esses arquivos xml e carrega-los para exibir o conteúdo.
Answer: Têm de adicionar execção nesses dois diretorios desta maneira.
<code>$pasta = $data[0].$data[1].$data[2]."_".$data_end[0].$data_end[1].$data_end[2];
$l_nfe = dir("xml/".$pasta);

while($arquivo = $l_nfe -> read()){
    if($arquivo !== "." && !$arquivo !== ".."){
       simplexml_load_file("xml/".$pasta."/".$arquivo);
    }
}
</code>
Comment: Obrigado irmão funcionou! Não pensei nessa possibilidade... rsrs


How to get all tables from SQLite database Android Studio

Question: I've been searching on how to get all tables from a database, I'm not familiar with SQLite for Android Studio. I have a DBHelper class that I use to make my sql commands. What I've gathered so far is that I have to make a query to sqlite_master such as "SELECT name FROM sqlite_master WHERE type='table'".
Here is my DBHelper class:
public class DBHelper extends SQLiteOpenHelper
{
public String tableName;
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_DESC = "desc";
private static final String COLUMN_DECKNAME = "deckname";
private static final String COLUMN_IMAGENAME = "imagename";

public DBHelper(Context context, String tablename) {
    super(context, "UserDecks.db", null, 1);
    tableName = tablename;
}

public DBHelper(Context context){
    super(context, "UserDecks.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + tableName + "(" + COLUMN_NAME + " TEXT, " + COLUMN_DESC + " TEXT, " + COLUMN_DECKNAME + " TEXT, " + COLUMN_IMAGENAME + " TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + tableName);
}

@Override
public void onOpen(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + "(" + COLUMN_NAME + " TEXT, " + COLUMN_DESC + " TEXT, " + COLUMN_DECKNAME + " TEXT, " + COLUMN_IMAGENAME + " TEXT)");
}

public Cursor GetDeckList(){
    SQLiteDatabase sdb = this.getReadableDatabase();
    Cursor cursor = sdb.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    return cursor;
}

I only pasted where it reaches up to the GetDeckList method.
This is where I reference DBHelper:
    db = new DBHelper(this);
    Cursor cData = db.GetDeckList();
    int numOfRows = cData.getCount();
    if(numOfRows == 0){
        Toast.makeText(this, "Deck list is empty!", Toast.LENGTH_SHORT).show();
    }else{
        while(cData.moveToNext()){
            DL_deckList = new DeckList(cData.getString(0));
            LIST_currentDecks.add(DL_deckList);
        }
        mAdapter = new RecycleViewAdapter(true, LIST_currentDecks, this);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(mAdapter);
        recyclerView.setHasFixedSize(false);
    }

I think I am missing some piece of code, because I'm doing what I've read on stackoverflow on how to query from sqlite_master, but my app keeps crashing because I keep trying to create a "null" table. It keeps calling "onCreate" or "onOpen" when I tinker with the code, even though I'm not trying to make a table. So it keeps crashing because I'm not giving it a new table. So I'm assuming I'm missing some code, but I don't know what it is.
Answer: try like this
db = new DBHelper(this);
Cursor cData = db.GetDeckList();
if(cData != null) {
    int numOfRows = cData.getCount();
    if(numOfRows == 0){
        Toast.makeText(this, "Deck list is empty!", Toast.LENGTH_SHORT).show();
    }else{

        List<String> tableNames = new ArrayList<String>();
        cData.moveToFirst();
        while (!cData.isAfterLast()) {
            tableNames.add(cData.getString(cData.getColumnIndex("name")));
            cData.moveToNext();
        }
        mAdapter = new RecycleViewAdapter(true, tableNames, this);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(mAdapter);
        recyclerView.setHasFixedSize(false);
    }
}

Answer: You can remove the code from onCreate, onUpgrade, onOpen and that will give you the results you are looking for.
The result from GetDeckList would be only one record: android_metadata, a table by default.
If you need to create tables in the future, then add the code back to onCreate, in that case, you could have some constants in your DBHandler for your new tables.
Finally, I recommend you have a Singleton to have only one instance of DBHandler to avoid memory leaks or memory allocations. Another piece of advice would be If you can use the abstraction library Room from the Android Jetpack, much better, this library will save you from important issues from using SQLite directly. If you want to check Room out, please check Room Setup
Answer: Try with the following query for get all database tables
 //use below query for reading all table list
   Cursor cursor = sdb.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('android_metadata', 'sqlite_sequence', 'room_master_table') ",null);


python: Navigating a 4-D numpy array

Question: I am working with a 4-D array input to a CNN network. The input array has the following shape
print('X_train shape: ', X_train.shape)
X_train shape:  (47204, 1, 100, 4)

Data description:
The input data consists of a 47204 instances (fixed-length segments as far CNN requirement). Each instance (1, 100, 4) i.e. 1 segment contains 100-GPS points, and for each point, 4-corresponding point kinematics (max_speed, avg_speed, max_acc, avg_acc) are stored, thus the (1, 100, 4). Labels are stored in a separate y_train array of shape (47204,) for 5 classes [0..4].
print(y_train)
[3 3 0 ... 2 3 4]

To get a better sense of my X_train array, I show the first 3 elements below:
print(X_train[1:3])
[
 [[[ 3.82280987e+00 2.16802350e-01  7.49917451e-02  3.44416369e-04]
   [ 3.38707371e+00 2.02210055e-01  1.61751110e-03  1.93745950e-03]
   [ 2.49202215e+00 1.60605262e-01  8.43561351e-03  2.40057917e-03]
   ...
   [ 2.00022316e+00 2.70020923e-01  5.40441673e-02  3.57212151e-03]
   [ 3.25199744e-01 9.06990382e-02  1.46808316e-02  1.65841315e-03]
   [2.96587589e-01  0.00000000e+00  6.13293351e-04 4.16518187e-03]]]

 [[[ 1.07209176e+00 7.27038312e-02 6.62777026e-03  2.04611951e-04]
   [ 1.06194285e+00 5.05005456e-02 4.05676569e-03  3.72293433e-04]
   [ 1.02849748e+00 2.12558178e-02 2.95477005e-03  5.56584054e-04]
   ...
   [ 4.51962909e-03 5.63125736e-04 5.98474074e-04  1.63036715e-05]
   [ 2.83026181e-03 2.35855075e-03  1.25789358e-03 2.15331510e-06]
   [8.49078543e-03  2.16840434e-19 9.43423077e-04 1.29198906e-05]]]

 [[[ 7.51127665e+00 3.14033478e-01  6.85170617e-02  7.73415075e-04]
   [ 7.42307262e+00 1.33868251e-01  4.10564823e-02  1.16131460e-03]
   [ 7.35818066e+00  1.23886976e-02  3.02312582e-02  1.28312101e-03]
   ...
   [ 7.40826167e+00 1.19388656e-01 4.00874715e-02  2.04909489e-04]
   [ 7.23779176e+00 1.33269965e-01  1.20430502e-02  1.58195900e-04]
   [ 7.11697001e+00 4.68002105e-02  5.42478400e-02  3.58101318e-05]]]
]

Task:
I am required to create a machine learning model (e.g. random forest) using the 4 kinematics (max_speed, avg_speed, max_acc, avg_acc) as features. This requires navigating each instance and getting these features for the 100-points in the instance.
Clearly, the number of samples will then be 4720400 (i.e. 47204 x 100), so would also match each value to the corresponding label of its instances, i.e. y_train will then be (4720400,).
The expected input would then be like:
      max_speed     avg_speed         max_acc       avg_acc   class
0 3.82280987e+00 2.16802350e-01  7.49917451e-02  3.44416369e-04 3
1 3.38707371e+00 2.02210055e-01  1.61751110e-03  1.93745950e-03 3
2 2.49202215e+00 1.60605262e-01  8.43561351e-03  2.40057917e-03 3
...

I have being thinking about how to do this all through the week, all ideas evaporated. How do I do this, please?
Comment: If I understand correctly, you need 100 ordered copies of every element in `y_train`. How about using NumPy's [repeat](https://numpy.org/doc/1.18/reference/generated/numpy.repeat.html#numpy.repeat) function?

Another possibility could be mapping using the integer division `index // 100`, which effectively repeats itself 100 times for each index.
Answer: You can reshape your X_train array from (47204, 1, 100, 4) to (4720400, 4) simply with:
X_train_reshaped = X_train.reshape(4720400, 4)

It preserves the data order and the total number of elements will be the same.
Similarly, you can expand y_train array using repeat command:
Y_train_reshaped = numpy.repeat(Y_train, 100)

Note the 100 for repeat command. Since you had one label for 100 data points, we will expand these items 100 times. This command will preserve data order too so all instances will have the same original label.
Comment: Ah, thank you so much for this answer. Precise and to the point.

python: Navigating a 4-D numpy array


MySQL 5.5 InnoDB = OFF?

Question: We run a server with MySQL 5.5. 95% of the tables are set to the InnoDB engine.
However whenever I look at the my.ini file (using the MySQL Workbench) under mysqld section innodb is unchecked and OFF is selected in the drop down. I don't see this line added to the my.ini file when viewing with notepad.
Should I check this setting and set it to ON so we can utilize the enabled innodb settings (buffers & log file etc.) or does this not matter?
Answer: Innodb is the default storage engine, and it is loaded by default. I would consider this a flaw in MySQL Workbench. You can read more about the --innodb (and --skip-innodb) option here:
http://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html#option_mysqld_innodb
Notice that if you disable innodb, MySQL won't even start unless you specify a different default storage engine as well.
Comment: I was thinking it was a flaw but I wanted to double check
Answer: Sounds like an issue with MySQL Workbench.
MySQL 5.5 has a default storage engine of InnoDB.
In fact, the option default_storage_engine is predefined as follows:

MySQL 5.5.4 and prior, MyISAM
MySQL 5.5.8 and after, InnoDB

There is another option called storage-engine, which was deprecated as for MySQL 5.5.3. Keep in mind that MySQL 5.5.8 was the very first GA release.
I would strongly suspect MySQL Workbench if it is coded to check storage-engine instead of default-storage-engine. This would allow MySQL Workbench to monitor older release of MySQL.

MySQL 5.5 InnoDB = OFF?


Operator norm of a family of matrices

Question: Let $c$ be a complex number. Consider the family of $n\times n$ matrices $M_n$ which have $c$'s on one off-diagonal, $\bar{c}$'s on the other off-diagonal, and zero everywhere else. So $M_4$ looks like this:$$\left(\begin{array}{cccc}0&c&0&0\\\bar{c}&0&c&0\\0&\bar{c}&0&c\\0&0&\bar{c}&0\end{array}\right)$$How does one find a general formula for the operator norm of $M_n$?
Answer: Write $c=\alpha|c|$, with $|\alpha|=1$. Then
$$
M_4=|c|\,\begin{bmatrix}
1&0&0&0\\
0&\alpha&0&0\\
0&0&\alpha^2&0\\
0&0&0&\alpha^3\end{bmatrix}
\begin{bmatrix}
0&1&0&0\\
1&0&1&0\\
0&1&0&1\\
0&0&1&0
\end{bmatrix}
\begin{bmatrix}
1&0&0&0\\
0&\alpha&0&0\\
0&0&\alpha^2&0\\
0&0&0&\alpha^3\end{bmatrix}^*,
$$
and so $M_4(c)$ is unitarily equivalent to $|c|\,M_4(1)$. Thus we only need to determine the spectrum of $M_4(1)$. The same argument applies for $M_n$ for any $n$.
The eigenvalues of $M_n(1)$ are $\lambda_k=2\cos\frac{k\pi}{n+1}$, where an eigenvector for $\lambda_k$ is $\sum_{s=1}^n\sin\frac{ks\pi}{n+1}e_s$, and $e_1,\ldots,e_n$ is the canonical basis.
As $M_n(1)$ is selfadjoint, its norm is the greatest eigenvalue in absolute value, so
$$
\|M_n(c)\|=|c|\,\|M_n(1)\|=2|c|\,\cos\frac{\pi}{n+1}.
$$

$\newcommand\abajo{\\ \ \\}$
Edit: The Eigenvalues of $M_n(1)$.
Let $e_1,\ldots,e_n$ be the canonical basis of $\mathbb C^n$. Let $\eta_k=\sum_{\ell=1}^n\sin\frac{k\ell\pi}{n+1}\,e_\ell$, $k=1,\ldots,n$. Then
\begin{align*}
M_n(1)\eta_k
&=\sum_{s=1}^{n-1}\sin\frac{sk\pi}{n+1}\,e_{s+1}+\sum_{s=2}^{n}\sin\frac{sk\pi}{n+1}\,e_{s-1} \abajo
&=\sin\frac{2k\pi}{n+1}\,e_1+\sum_{s=2}^{n-1}\left(\sin\frac{(s-1)k\pi}{n+1}+\sin\frac{(s+1)k\pi}{n+1}\right)\,e_{s}
+\sin\frac{(n-1)k\pi}{n+1}\,e_{n} \abajo
&=2\cos\frac{k\pi}{n+1}\sin\frac{k\pi}{n+1}\,e_1+\sum_{s=2}^{n-1}2\cos\frac{k\pi}{n+1}\sin\frac{sk\pi}{n+1}\,e_s+2\cos\frac{k\pi}{n+1}\sin\frac{nk\pi}{n+1}\abajo
&=2\cos\frac{k\pi}{n+1}\,\eta_k.
\end{align*}
All the above requires is the sine of a sum formula.
Comment: Thanks!...but you have left for me the larger mystery of how one arrives at the solution for $M_n(1)$ in terms of trig functions. Any hints there?
Comment: It's fairly basic, just a matter of patience. I've included a few lines.
Comment: That proves it's correct, thanks. But how does one find those eigenvalues and eigenvectors to begin with? I'm trying to improve my skill set. When I try to solve this (not knowing the solution in advance), either by hand or using Mathematica, I get various roots of polynomials, with sin and cos nowhere to be found. Do you know of a general approach that leads to this solution?
Comment: I don't have a general answer for that. In this case, these numbers are fairly well known, but I don't think I would have come up with the eigenvector and the eigenvalue on my own. The numbers $\cos k\pi/(n+1)$ are for instance the roots of the Chebyshev polynomials of the second kind. The numbers $2\cos k\pi/(n+1)$ are the norms of matrices of zeroes and ones, provided that the norm is less than 2.
Comment: Ah: the characteristic polynomial of $M_n(1)$ is the $n$th Chebyshev polynomial of the second kind with $x$ replaced by $-x/2$!
Comment: ...and a way I could perhaps have figured this out on my own would have been to search for the polynomial coefficients in the encyclopedia of integer sequences. That thing you say about norms of matrices of zeroes and ones is wild. Thanks for your help!
Comment: You are welcome. The thing about norms is indeed wild. I'll write a proof here one of these days.

Operator norm of a family of matrices


cannot return maximum element

Question: I am trying to return maximum element from array using recursion
here is my code
    static void Main(string[] args)
    {
        int[] Array=new int[]{10,233,34};

        int _MaxVal = CalculateMax(Array, 0, 0);
        Console.WriteLine(_MaxVal);
        Console.ReadKey();

    }

    private static int CalculateMax(int[] Array, int Startpos, int maxval)
    {
        if (Startpos != Array.Length)
        {
            if (Array[Startpos] > maxval)
            {
                maxval = Array[Startpos];
            }

            CalculateMax(Array, ++Startpos, maxval);
        }

        return maxval;
    }

I am getting MaxVal as 10 .
What is wrong with it ??
Thanks all
Comment: Learning recursion is good, but not everything needs to be (or should be) recursive.
Comment: Do you also want to do `maxval = CalculateMax(Array, ++Startpos, maxval);`?
Comment: You're not taking into account the return value of `CalculateMax()` when  you call it recursively.
Comment: You know you can do `= Array.Max()`, right?
Comment: I was trying to implement it using recursion
Answer: You're losing the value of maxval.
Try this:
maxval = CalculateMax(Array, ++Startpos, maxval);

Unless you're doing this as a personal exercise or for an assignment, you could handle this way more gracefully with LINQ:
var maxValue = Array.Max();

Comment: +1. I'd also add that it would be better to have an initial value for `maxval` of `int.MinValue`, as otherwise if the maximum value is less than zero, the result is wrong. (Just what should be done if the array is empty is another question).
Answer: To use recursion you should have a stop test and be sure to always launch the next step on a smaller problem.
Try this : (Not sure if Array.SubArray(int) is a real function but that is the idea.
static void Main(string[] args)
{
    int[] Array=new int[]{10,233,34};

    int _MaxVal = CalculateMax(Array);
    Console.WriteLine(_MaxVal);
    Console.ReadKey();

}

private static int CalculateMax(int[] Array)
{
    if (Array.Length > 0)
    {
        int maxSubArray = CalculateMax(Array.SubArray(1)); // Use recursive function on the SubArray starting at index 1 (that the smaller problem)
        if (maxSubArray > Array[0])
        {
            return maxSubArray;
        } else {
            return Array[0];
        }

    } else {
        return 0; // Stop test
    }
}

Note : it will not work with negative value.
Answer:     static void Main(string[] args)
    {
        int[] Array = new int[] { 10, 233, 34 };

        int _MaxVal = CalculateMax(Array);
        Console.WriteLine(_MaxVal);
        Console.ReadKey();

    }
    private static int CalculateMax(int[] Array)
    {
        int max = 0;
        for (int i = 0; i < Array.Length; i++)
            if (Array[i] > max)
                max = Array[i];
        return max;
    }

OR
var max1 = Array.Max();
var max2 = Array.Concat(new[] { 0 }).Max();
var max3 = Array.OrderByDescending(p => p).FirstOrDefault();

Answer: You don't use return value from deeper calls of CalculateMax
Change
CalculateMax(Array, ++Startpos, maxval);

to
maxval = CalculateMax(Array, ++Startpos, maxval);

This way you pass maxval not only forward, but also backwards to main().
As (probably) said before, recursion is not best way to do it, because stack overflow may happen.
Answer: You are not using the return value from the recursive call. This:
CalculateMax(Array, ++Startpos, maxval);

should be:
maxval = CalculateMax(Array, ++Startpos, maxval);

Anyway, you are using recursion instead of a loop, which is a very bad way to use recursion. You will be doing recursion as deep as there are items in the array, which means that you have a very slow loop, and you will get a stack overflow if the array is too large.
To use recursion correctly you should divide the work into smaller parts, and use recursion to handle those smaller parts, until the parts are so small that they are trivial.
For example, split the array in half for each level:
int[] Array = new int[]{ 10, 233, 34 };
int _MaxVal = CalculateMax(Array, 0, Array.Length);
Console.WriteLine(_MaxVal);

private static int CalculateMax(int[] array, int start, int length) {
  if (length == 1) {
    return array[start];
  } else {
    int half = length / 2;
    int first = CalculateMax(array, start, half);
    int second = CalculateMax(array, start + half, length - half);
    return first > second ? first : second;
  }
}

Comment: This is not a bad way to use recursion, using recursion at then end of a function can be optimized to a loop and is a common pattern http://en.wikipedia.org/wiki/Tail_call
Comment: Slightly out of date - http://blogs.msdn.com/b/clrcodegeneration/archive/2009/05/11/tail-call-improvements-in-net-framework-4.aspx
Comment: @Hogan: C# doesn't do tail recursion: http://stackoverflow.com/questions/491376/why-doesnt-net-c-optimize-for-tail-call-recursion
Comment: @Hogan: Thanks for the update. Note though that it only does this in x64 mode, not x86 mode. Anyhow, the code in the question doesn't do tail recursion in any case, so it's still a bad use of recusion.

cannot return maximum element


Conditional probability of multivariate gaussian

Question: I'm unsure regarding my (partial) solution/approach to the below problem. Any help/guidance regarding approach would be much appreciated.
Let $\mathbf{X} = (X_1, X_2)' \in N(\mu, \Lambda ) $ , where
$$\begin{align}
    \mu &= \begin{pmatrix}
           1 \\
           1
         \end{pmatrix}
  \end{align}
$$
$$
\begin{align}
    \Lambda &= \begin{pmatrix}
           3 \quad 1\\
           1 \quad 2
         \end{pmatrix}
  \end{align}
$$
We are tasked with computing: $P(X_1 \geq 2 \mid X_2 +3X_1=3)$
I here begin by doing a transformation,
$$ \mathbf{Y} = (Y_1, Y_2)', \qquad Y_1 = X_1, \qquad Y_2 = X_2 + 3X_1$$
We now are interested in the probability,
$$P(Y_1 \geq 2 \mid Y_2 = 3)$$
Since we can write that $\mathbf{Y = BX}$, it follows that,
$$\mathbf{Y} \in \mathcal{N}(\mathbf{B\mu, B\Lambda B')})$$
where
$$\mathbf{B}= \begin{pmatrix}
           1 \quad 0\\
           3 \quad 1
         \end{pmatrix} \rightarrow \quad \mathbf{B \mu} = \begin{pmatrix}
           1 \\
           4
         \end{pmatrix}, \quad \mathbf{B\Lambda B'}= \begin{pmatrix}
           1 \quad 0\\
           3 \quad 1
         \end{pmatrix} \begin{pmatrix}
           3 \quad 1\\
           1 \quad 2
         \end{pmatrix} \begin{pmatrix}
           1 \quad 3\\
           0 \quad 1
         \end{pmatrix} = \begin{pmatrix}
           3 \quad 10\\
           10 \; \; 35
         \end{pmatrix}$$
We thereafter know that we can obtain the conditional density function by,
$$
f_{Y_1\mid Y_2 = 3} (y_1) = \frac{f_{Y_1,Y_2}(y_1, 3)}{f_{Y_2}(3)} \tag 1
$$
The p.d.f. of the bivariate normal distribution,
$$f_{Y_1, Y_2}(y_1, y_2) = \frac{1}{2\pi \sigma_1 \sigma_2 \sqrt{1-\rho^2}} e^{\frac{1}{2(1-\rho^2)}(\frac{(y_1 - \mu_1)^2}{\sigma_1^2} - \frac{2 \rho (y_1 - \mu_1)(y_2 - \mu_2)}{\sigma_1 \sigma_2} + \frac{(y_1 - \mu_1)^2}{\sigma_2^2})} $$
The marginal probability density of $Y_2$,
$$f_{Y_2}(y_2) = \frac{1}{\sqrt{2\pi} \sigma_2} e^{-(y_2 - \mu_2)^2 / (2\sigma_2^2)}$$
Given that,
$$\sigma_1 = \sqrt{3}, \quad \sigma_2 = \sqrt{35}, \quad \rho = \frac{10}{\sigma_1 \sigma_2 } = \frac{10}{\sqrt{105}}  $$
we are ready to determine (1). However, the resulting expression, which I then need to integrate as follows,
$$
Pr(Y_1 \geq 2 \mid Y_2 = 3) = \int_2^\infty f_{Y_1\mid Y_2 = 3} (y_1) \, dy_1
$$
becomes quite ugly, making me unsure whether I've approached the problem in the wrong way?
Thanks in advance!
Answer: https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Conditional_distributions Just apply the result after you obtain the distribution of $\mathbf{Y}$
Answer: The covariance between $X_1 + \lambda (3 X_1 + X_2)$ and $3 X_1 + X_2$ is $10 + 35 \lambda$, therefore if we take $\lambda = -2/7$, we get
$$\operatorname{P}(X_1 \geq 2 \mid 3 X_1 + X_2 = 3) =
\operatorname{P} \left(
 X_1 -\frac 2 7 (3 X_1 + X_2 - 3) \geq 2 \mid 3 X_1 + X_2 = 3 \right) = \\
\operatorname{P} \left( X_1 -\frac 2 7 (3 X_1 + X_2 - 3) \geq 2 \right),$$
and $X_1/7 -2 X_2/7 \sim \mathcal N(-1/7, 1/7)$.
Answer: From where you are, simply use the relation $(a=3)$
$$
Y_1 | Y_2=a
\sim
\mathcal{N}
\left( \mu_1+
\rho\frac{\sigma_1}{\sigma_2} (a-\mu_2),
(1-\rho^2) \sigma_1^2
\right)
$$
and then compute the probability as
$$
1-\Phi_{Y1|Y_2}(2)
$$
using the cdf of $Y_1|Y_2$


Existe um XHTML5 (XHTML + HTML5)?

Question: O XHTML é o HTML com sintaxe estrita (precisa ser um XML válido).
Consigo usá-lo em conjunto com o HTML5?
Comment: Não, pois tinhamos 2 caminhos: XHTML2 e HTML5, e infelizmente prevaleceu o 2o, pois os comitês e empresas envolvidos acharam que era melhor qualquer um conseguir por qualquer coisa no ar, em vez de fazer com que as pessoas aprendam o mínimo necessário para publicar coisas consistentes. Pior é que esse pensamento anda "na moda", dá até alguns discursos bonitos por aí.
Comment: @renan de qualquer forma é bom pra constar, de repente atende à necessidade do OP. Eu particularmente não gosto por não ter as vantagens que o XHTML teria, que é o browser não mostrar conteúdo malformado.
Comment: [maybe](http://html5doctor.com/html-5-xml-xhtml-5/) existam ["documentos poliglotas"](http://tableless.com.br/documentos-poliglotas-com-xhtml5/).
Comment: @renan pior que isso ai só deixa a situação mais feia.
Comment: Talvez isso pode te ajudart http://www.standardista.com/html5-v-xhtml5/
Answer: Não existe um XHTML + HTML5.
O XHTML foi um caminho tomado pelo W3C para tentar restringir o padrão de código da internet toda. A ideia era que todo mundo escrevesse código válido e semântico. O HTML5, por sua vez, é uma atualização da linguagem iniciada por um grupo de desenvolvedores ligados a empresas como Apple, Google e Firefox.
Você consegue escrever sintaxe XHTML (que não tem tanta diferença assim) no HTML5 tranquilamente. O validador do W3C não vai reclamar da sintaxe. Mas é uma ótima prática não misturar os dois.
Comment: Por que não misturar os dois? Eu também evito isso, mas não sei bem explicar o motivo.
Answer: O XHTML tem um padrão e é validado com base no HTML mais antigo, o que não inclui alguns novos inputs do html5 e algumas sintaxes de metatags, infelizmente ainda o XHTML é baseado no HTML2, seguindo suas sintaxes e validações, o que é muito importante para as IDES e Servidores poderem validar seu código, diferente do que se vê hoje em PHP por exemplo(desenvolvi 8 anos nessa linguagem), q é aquele monte de gambiarra e código mal feito. Com validação baseada em um padrão é possível um código mais legível a todos.
 Aguardamos ansiosamente uma definição da JSP com sintaxes de HTML5. Até lá é se virar com o velhro XHTML, CSS e JQuery.
Comment: "XHTML é baseado no HTML2"? Você tem alguma referência para sustentar essa afirmação?
Comment: Desculpe a confusao, o XHTML é baseado no HTML4.
Answer: Acho interessante você entender o que é especificação e implementação.
XHTML 4.x, HTML5 são especificações, são um conjunto de regras que definem como o HTML deve ser interpretado pelos navegadores, é algo análogo à norma culta da lingua portuguesa.
Implementação é como os navegadores de fato interpretam, o que geralmente difere em um ponto ou outro dependendo do navegador, é análogo ao português falado.
Historicamente o XHTML não colou, a maioria dos navegadores não se importava muito com a especificação do XHTML, em boa parte devido à algumas regras meio chatas do XHTMl como ter de definir um doctype com uma url que ninguém lembrava, ter de fechar tags solitárias como por exemplo o
 que tinha de ser escrito como
 segundo a especificação do XHTML. Para os navegadores era mais importante fazer o código que as pessoas escreviam funcionar do que seguir a especificação xarope do XHTML.
Com base nisso foi criado o HTML5, que é uma especificação mais próxima do que os navegadores implementam, que é o que realmente importa.
Em boa parte foi pressão dos navegadores em fazer uma especificação funcional, mas especificamente de um grupo chamado WHATWG .
tl;dr: não existe xhtml5.
Answer: Complementando a resposta do Erik:

o W3C fechou/dissolveu/desmanchou o grupo de trabalho do XHTML2 em 2009. Em 2007 eles já haviam reconhecido o HTML5 como o então próximo padrão de HTML. Portanto, nem se incomode com o XHTML2.
o HTML5 possui tanto o text/html regular como o application/xhtml+xml p/ servir a página.

https://www.w3.org/2009/06/xhtml-faq.html
Note ali na página:

Regarding the XML serialization of HTML, the HTML 5 specification
  includes a section on XML serialization, as well as a section on
  text/html serialization. W3C plans to continue work on both
  serializations in the HTML Working Group. Thus, we expect the next
  generation XML serialization of HTML to be defined in the HTML 5
  specification. Currently, the HTML 5 specification refers to this
  serialization as "XHTML 5"

Sim, existe o tal XHTML5. Pelo menos como uma forma de serializar a página definida numa seção do padrão. Como o próprio W3C diz, o text/html é suficiente p/ a maior parte dos casos (e o que se usa hoje com o DOCTYPE html)
Se vc quiser matar a curiosidade com um material da época:
http://www.standardista.com/html5-v-xhtml5/
https://mathiasbynens.be/notes/xhtml5
http://html5doctor.com/html-5-xml-xhtml-5/
http://xmlplease.com/xhtml/xhtml5polyglot/
https://www.ibm.com/developerworks/xml/library/x-think45/

Existe um XHTML5 (XHTML + HTML5)?


'Easy' question on continuity of integral

Question: Here's a problem that I recently stumbled upon. It seems pretty easy, and quite intuitive yet every time I try to solve it, I run into some difficulties. Here it goes :
Let $\phi \in BC(\mathbb{R}^2,\mathbb{R})$ (bounded and continuous) be a function such that
$$\forall_{x \in \mathbb{R}} \ \phi(x, \cdot) \in L_1(\mathbb{R},\mathbb{R})$$
Then the function defined as
$$\psi(x) = \int_{\mathbb{R}} \ |\phi(x,z)| \ dz $$
is continuous.
I got as far as to trying to estimate the expression
$$\int_{\mathbb{R}\backslash [-T,T]} \ |\phi(x,z) - \phi(x_0,z)| \ dz$$
for large $T$ (we want the expression to be small). However, the main problem is that $T$ may depend on $x$, in other words it need not be uniform for $x$ in some neighbourhood of $x_0$. I feel like it would somehow violate the continuity, but maybe I am totally wrong.. I would be grateful for providing a simple counterexample if the statement is false.
Answer: Here is a counterexample:
$$|\phi(x,z)| = x^2e^{-x}|z|e^{-x|z|}\chi_{[0,\infty)}(x).$$
The function is bounded and continuous, but
$$\psi(0) = 0,$$
and for all $x > 0$,
$$\psi(x) = x^2e^{-x}\int_{-\infty}^{\infty}|z|e^{-x|z|}\,dz= 2x^2e^{-x}\int_{0}^{\infty}ze^{-xz}\,dz=2e^{-x}>0.$$
Comment: @DanielFischer: $\int ze^{-xz}dz = -ze^{-xz}/x - e^{-xz}/x^2$
Comment: Ah, duh. Forgot the $\lvert z\rvert$. Should get me some tea to wake up.
Comment: Actually I need to go to sleep :)
Comment: Good night then.


Fitting a smoothed curve to a noisy data

Question: I have a variable with sales data over time. It is very noisy at a disaggregate level but if you look at it as a whole, you can see a smoothing curve that follows a polynomial pattern. Is there a way to fit such curve and actually generate values of it over time in the dataset?

I tried many different options here including a moving average  (which leaves a lot of noise still); I tried lowess smoother in Stata, which is on the opposite side - too neutral and leaves out important curve patterns. I also tried fitting a nonlinear function nl but to no avail.
The original goal of this task is to determine any infection points that the curve can have. In my mind, I am looking for a curve that would run in the middle of all the noise.
Comment: Do you need the smoothed function to be represented as a polynomial, or would you accept any function that smooths out the noise (not necessarily expressed in polynomial form).
Comment: Have you tried filtering, through the Fourier transform/convolution?
Answer: Sounds like you just need to adjust the smoothing parameters (sometimes called bandwidth) to your liking.  Either of these methods should be able to be tuned appropriately.
Moving average can be adjusted to account for more points (increasing smoothness).
Similarly, lowess smoothers have a smoothing parameter to increase or decrease smoothness.
Answer: Since you mention the "polynomial pattern" in your question, try to fit your data using polynomial least squares fitting.
I tried to reproduce your data (more or less) and plotted a third degree least squares fit on the data. The result is in the graph below.
Actually, I used two goniometric functions to generate the data. The period and amplitude of the base cycle can be estimated by the fitted polynomial: half the period is the distance between the two extremes. The amplitude is half of the difference between the two extremes.
The advantage of this approach is that is it very easy to understand, calculate and apply (maybe at the cost of some mathematical inaccuracy).
There are two disadvantages of using a moving average over any fitting approach:

the moving average is always lagging. This results in shift in the direction of the past data (in the example below: the moving average is above the polynomial fit line; the trend is going down, so the moving average is lagging upwards in this case).
the moving average moves along with any spike in the data. This results in a more "wobbely" line compared to the fitting approach.

These effects can be clearly seen in the picture below (red = polynomial fitting; black = 20 period moving average).
Comment: Because this is a time series, with an obvious seasonal structure and some serial correlation, caution would seem advisable.  In particular a "classic" polynomial least squares fit would have several disadvantages compared to methods that are more suitable to time series or are more robust.
Comment: Possibly--but fitting it via ordinary least squares may be problematic.  It certainly would produce incorrect standard errors of the parameters.
Comment: This is being automatically flagged as low quality, probably because it is so short.
At present it is more of a comment than an answer by our standards. Can you expand
on it? You can also turn it into a comment.
Comment: Moving averages are not always lagging.  If you use points equally spaced on either side of the point (sometimes called 'central moving average') then the moving average is more representative of the current trend.
Comment: The OP mentions polynomial-like patterns. Doing a moving polynomial least squares fit is a logical thing to try, I'd say.
Comment: @gung according to [this meta](http://meta.stackexchange.com/questions/118582/what-is-an-acceptable-answer) answers should be posted as answers (not as comments) - which is what I did. I totally agree that my link-dominant-first-answer had to be expanded, which is what I just did...


Formula for probability-probability plot

Question: I am programmer developing a Software that features the display of a probability plot. As far as I know there are 2 different ways to display a probability plot (please correct me if I say something wrong):

A Percent / Percent Chart
A Quantile / Quantile Chart

My customers want a Percent / Percent Chart. That brings some problems.  There is no charting control I know that features a probability plot chart.

That's why I have to calculate the positions of the data points by hand. Are there any formulas or calculations to place the data points and Y-axis values in a normal coordinate system?
Comment: The y-axis is transformed according to the Normal cumulative density function, $F(y)=\int_{-\infty}^y \exp(-t^2/2) dt / \sqrt{2\pi}$, as multiplied by $100$ to convert to percent. In the illustration it spans the range from (approximately) $y=-3$ to $y=3$, giving $F(y)$ ranging from about $0.3$% to $99.7$%.
Comment: I don't know what programming language you are using, but [here](http://code.google.com/p/bridgescour/source/browse/qqplot.py?r=f08878af3123c5959a7f11220946f4938cbe7130) is some python code to make a QQ plot.
Comment: Hey I am using C#. The display of a QQ chart would be pretty easy since the axis are linear. The Axis in the chart above seems to be kinda (double) logarithmic, thats what giving me headaches.
Comment: What you have there is actually a Q-Q plot; it's just that the y-*axis* is marked with the corresponding percentile-ranks rather than the quantiles. A P-P plot is different.
Answer: What you have displayed in your question is actually a Q-Q plot; it's just that the y-axis is marked with the corresponding percentile-ranks rather than the quantiles.
That is, that y-axis has tickmarks at $\Phi^{-1}(p)$ but labels of $p$. The plotted points are still actually a Q-Q plot.
A P-P plot is different. It would transform the y-axis to be linear in $p$ and apply a similar transformation to the data (after standardizing).


Resize font with jQuery/JS and override font-size

Question: For example, if I have:

This will change font size

This will not change font size

Now I want to resize font with jQuery in all div content. For example, with simple jQuery:
$("#divtochangeFont").css("font-size","16px");

But it changes only in first paragraph. How to override all defined font-size attributes in div?
PS: Scale effect can't be used...
Comment: have you tried $("#divtochangeFont p").css("font-size","16px"); ?
Comment: I'd be worried if your browser interpreted `stlye` as `style`.
Comment: Yep you just needed to add a p : http://jsfiddle.net/srGxF/
Answer: $("#divtochangeFont, #divtochangeFont *").css("font-size", "16px");

Answer: $("#divtochangeFont * ").css({"font-size": "16px","color": "orange"});

you only need to take all children of your div
Comment: What about if there isn't any children - Just text?
Comment: if there isn't children $("#divtochangeFont, #divtochangeFont * ").
Answer: you could do something like:
$("#divtochangeFont").css("font-size","16px");
$("#divtochangeFont").children().each(function () {
  $(this).css("font-size","16px");
});

Answer: Since you're setting the font on the parent div, the child p with a font-size of 10px has precedence for that paragraph. (That's the cascading in CSS.)
What frank blizzard suggests will work. Personally, I'd just change your selector if #divtochangeFont only contains p's.
$("#divtochangeFont p").css("font-size","16px");

Answer: Try something like this, so you won't need to worry about other elements
$("#divtochangeFont").addClass("important").css("font-size","16px");

How to apply !important using .css()?