Is it possible to find the correct chords from melody notes alone?

Question: I'm caught up in this thought. My friend gave me just the melody notes of a song. Here it is,

So, here is the problem: "without having the chords supplied, there is no way of knowing what the chords should be."
For example: The E note that begins the melody might correspond to Em or Cm or A chords.
Is this correct?
Answer: You're right that the same melody can be played over a variety of different chord sequences, and that the choice of chords will have a marked effect on how the piece sounds.
One of the modern jazz performers' favourite tricks is to take a well known melody and accompany it with unexpected (yet still musically pleasing) chords.
Note that the key signature for your example is D major (or B minor), having C and F sharpened. So you'd be unlikely to play a Cm chord, since the chord contains a C♮ and the key does not.
The four notes you've provided form too short a melody to make any solid decisions about the right chord. It's very common to use the chord corresponding to the key of the piece, and the snippet ends on a D, so D major will probably work.
Not every note in a melody will correspond to a note that appears in the accompanying chord. For example, if you play a D major chord with the four notes in your example, the F♯ and the D will fit in the chord, and the E and C♯ will not. These can be thought of as "connecting notes".
Comment: It just occurred to me you might have meant C♯m. When referring to chords, you have to use the sharps/flats -- people won't apply the adjustments in the key signature to the names of chords.
Comment: At least in jazz, the chord charts indicate more what *scale* may be played, than exact chord tones. If you see a triad chord, you may just as well play the 9th, 6th, maj 7th (and not just passing by, I mean playing them). D, Dmaj7, Dmaj9, D6, D69 are practicaly saying the same thing to the improviser, and chord instrumentalists do switch them around. So I would say that E is a note implied by the D chord. On the other hand, in the sequence E - Eb - D played on a D chord, the Eb (foreign to the scale of D) is definitely a connecting note.
Comment: I thought the other way round. since D major scale has C #'ed it can very well contain Cm.
Comment: Sorry, I used a sharp sign when I meant a natural. Fixed. Cm is C♮, E♭, G♮ -- two of those notes are not in the key of Dm.
Answer: The answer to your question (as expressed in the title) is "No".
Any melody can be harmonized with a wide variety of chord progressions. You can use this to achieve a variety of sophisticated musical effects. One simple example would be using either a minor chord progression or a major chord progression to harmonize the same melody.
That's what makes music so interesting.
It's a well-established songwriting and compositional technique to take the same melody and harmonize it differently each time the melody is repeated. That is one form of what we refer to in classical music as a "theme and variations".
In jazz, it's call "re-harmonizing" or "using chord substitutions".
Now I don't mean to imply that you can take a given melody and choose chords at random and call it a chord progression that accompanies the melody. There are rules for this, and to learn them, you need to study music theory, or at least to listen to some good music composed by people who know their music theory.
Part Two
Nobody here has yet raised the subjects of harmonic rhythm or counterpoint.
Do you want to compose a different chord for each melody note, so that the chord progression incorporates a distinct bass line? That is called a chorale harmonization in homophonic texture. For example, that is the way that Protestant Christian hymns are often arranged in traditional hymnals.
Or do you want to simply create one chord per measure, or a different chord only on strong beats? In that case certain notes in the melody are treated as notes that are not in the chord, and go by various terms such as non-chord tones or passing tones.
Then there is counterpoint, in which there are multiple melody lines going on at the same time. The song tune is the dominant melody, but there are other lines going on underneath it or around it. In properly composed counterpoint there is still a chord progression that can be perceived and derived by looking at how the notes in the various melody lines line up vertically. Counterpoint is a complex and advanced compositional technique.
Answer: In a bar of 4/4 the strongest beats are 1 and 3
If for the bar shown you want one chord for the bar then in the snippet shown you have F# for beat 1 and C# for beat 3.
Usually if the tonic note is on a weak beat it is not part of a cadence therefore the tonic chord of D major should not be used.
The best candidate is F# minor (F#, A, C#)
Having said this the example provided is out of context in that it is very short. But be mindful what notes occupy the strongest beats in a bar, and also which bars are strongest in a phrase of music. Usually bars are strong-weak alternatively. This should help with choice of chords.
Comment: I agree the best candidate is F# minor based on what is given, but be careful as 1 and 3 are not always the strongest beats in a 4/4 bar.  (Depends on phrasing, style, etc)
Answer: Taken out of the context of a musical phrase, there is no unambiguously most correct analysis. Everything harmonic is relative to what's being tonicized in a given context, and that can be subjective at times. If you were given both a complete musical phrase to be considered in isolation, and a known harmonic rhythm (which chunks of notes are considered at once in deciding what's a chord), then it's sometimes possible to make a very strong argument for a certain interpretation, and there may even be a "most correct analysis", but tautologies of that kind are pretty uncommon. Usually it's just a collection of either more or less plausible analysis.
Assuming functional harmony to begin with, if harmonic rhythm isn't super explicit - as it would be with very homophonic voicing, e.g. you have only a melody - there's still what's called "implied harmony". One of the absolute most canonical examples of implied harmony recognized by everyone are the Bach two part inventions. Everybody knows and studies these, even non-pianists. Frequently no more than two notes are sounded at once, yet it is still possible to perform harmonic analysis with a high degree of certainty because harmony is implied by what's given very strongly by outlining chords and scales, and through phrasing.
Since music is temporal (your ears gather information over time), it's possible to introduce ambiguity and later resolve that ambiguity by giving your ears more complete information about which functions are currently being expressed. Lots of musical interest comes from your ears trying to solve that puzzle as they gather more information about context. The snippit you've given is too short to draw any conclusions. If we knew something about the key, whether this is at the beginning or end of a phrase, and something about the relationship to other voices, it could be narrowed down substantially, but the possibilities would still be enormous.
Finally, what Wheat Williams said in another answer about there being infinite harmonizations is true in theory, but assumes being able to subdivide indefinitely. He's also spot on in that in practice that's never the case, so there are technically finitely many possible harmonizations, and also in practice, there are further stylistic constraints with regards to structure and voice leading regardless of the genre, because every local small-scale musical descision is contingent upon it's surroundings.
Answer: Chord for first note:  D-F#-A    (Tonic)
Chord for second note: A-C#-E    (Dominant)
Chord for third note:  A-C#-E-G  (Dominant 7th)
Chord for fourth note: D-F#-A-D  (Tonic)
Comment: And why did you choose these chords? Couldn't there be some other chord?
Comment: You would most likely not change chords every beat as the harmonic rhythm of a piece is seldom that fast.


Does the sequence $\{a_n\}_n$ converge in a special metric of $(\mathbb R_+,d)$

Question: I am trying to prove or disprove convergence of the Cauchy sequence $\{a_n\}$ with $a_n = n$ for all $n\in \mathbb N$ in the metric:
$$
d(x,y) = \left|\frac 1x - \frac 1y\right|.
$$
I can see that as $n$ increases, the distance of $a_n$ to $0$ is decreasing, but under this metric, I can't have $0$ because $1/0$ is undefined. Does this mean it does not converge? And thus, the space $(\mathbb R_+,d)$ is not complete?
Comment: Assume for the sake of contradiction that there is an $a\in\mathbb R_+$ with $d(n,a)<\frac a2$ for all sufficiently large $n\in \mathbb N$. What can go wrong?
Comment: $a_n\to a$ in $(\Bbb{R}^+, d) $ implies $\frac{1}{a_n}\to \frac{1}{a}$ in $(\Bbb{R}^+, d_{\text{usual}}) $  $\space\space$ $(\frac{1}{n})$ is a well known sequence (you have seen it earlier, isn't it?) Where it converge? Is the limit in $\Bbb{R}^+$ ?
Comment: @SouravGhosh yes I see what you're saying. it feels weird because the sequence clearly does not diverge, it just never reaches 0 because 0 is not in the set
Answer: If $a_n \to a$ then, given $\epsilon >0$ there exists $n_0$ such that  $|\frac  1n -\frac 1 a|<\epsilon$ for all $n \geq n_0$. This gives $\frac 1 a <2\epsilon$ if $n \geq n_0$ and $n \geq \frac 1 {\epsilon}$. Since $\epsilon$ is arbitrary this gives $\frac 1  a=0$ which is a contradiction. Hence, the sequence is not convergent.
Answer: $\Bbb R_+$ is ambiguous. Let me assume it means $(0,+\infty)$ (but the answer would essentially be the same with  $[0,+\infty)$).
The map $x\mapsto\frac1x$ is an isometric bijection between your $\left((0,+\infty),d\right)$ and the subspace $(0,+\infty)\subset\Bbb R$ with the usual metric, which we shall denote by $\delta.$ It maps your $a_n=n$ to $b_n:=\frac1n.$
Since (for $\delta$) $b_n\to0\notin(0,+\infty),$ $(b_n)$ is Cauchy but has no limit in $\left((0,+\infty),\delta\right).$ Therefore, $(a_n)$ is Cauchy but has no limit in $\left((0,+\infty),d\right).$


Application of Differentiation

Question: Prove that if the curve $y = x^3 + px + q$ is tangent to the x-axis, then
$$4p^3 + 27q^2 = 0$$
I differentiated $y$ and obtained the value $3x^2 + p$. If the curve is tangent to the x-axis, it implies that $x=0$ (or is it $y = 0$?). How do I continue to prove the above statement? Thanks.
If I substitute in $x=0$, I will obtain $y= q$? Are my above steps correct? Please guide me. Thank you so much!
Comment: To answer your question, it is $y=0$.
Comment: What do you mean by *the curve is tangent to the x axis*? Do you mean that the curve has one point in which the tangent is parallel to the x axis?
Comment: Wow, that is the cubic resolvent. Very nice problem.
Answer: Notice, we have $$y=x^3+px+q$$ $$\frac{dy}{dx}=3x^2+p$$ Since, the x-axis is tangent to the curve at some point where $y=0$ & slope $\frac{dy}{dx}=0$ hence, we have $$\left(\frac{dy}{dx}\right)_{y=0}=0$$ $$3x^2+p=0\iff x^2=\frac{-p}{3}\tag 1$$
Now, at the point of tangency with the x-axis we have $$y=0\iff x^3+px+q=0$$ $$x^3+px+q=0$$ $$(x^3+px)=-q$$$$ (x^3+px)^2=(-q)^2$$ $$x^6+2px^4+p^2x^2=q^2$$
$$(x^2)^3+2p(x^2)^4+p^2x^2=q^2$$ Setting the value of $x^2$ from (1), we get $$\left(\frac{-p}{3}\right)^3+2p\left(\frac{-p}{3}\right)^2+p^2\left(\frac{-p}{3}\right)=q^2$$ $$-\frac{p^3}{27}+\frac{2p^3}{9}-\frac{p^3}{3}=q^2$$ $$-\frac{4p^3}{27}=q^2\iff -4p^3=27q^2$$ $$\color{red}{4p^3+27q^2=0}$$
Answer: The curve $y=f(x)$ is tangent to the $x$ axis if there exists some $x_0$ such that $$f(x_0) = 0$$ and $$f'(x_0) = 0$$
From the equation $f'(x_0) = 0$, you can see that only two possible values of $x_0$ are possible. Using them in the equation $f(x_0) = 0$ yields your result.
Comment: so y is 0? and then i differentiate it and compare?
Comment: @user271716 That's not what I said.
Answer: Hint:
Let $f(x)=x^3+px+q$.
Since the x-axis has equation $y=0$, the graph of $f$ is tangent to the x-axis
if there is a number $a$ such that $f(a)=a^3+pa+q=0$ and $f^{\prime}(a)=3a^2+p=0$.
Then $q=-(a^3+pa)\implies q^2=(a^3+pa)^2=a^6+2pa^4+p^2a^2\;\;$ where $a^2=-\frac{p}{3}$.

Application of Differentiation


Right click event (onclick) in Chrome, Opera and IE

Question: In Firefox I used the document.onclick event and then checked if it was a right click, and if I right clicked everything went as expected, but in Chrome, Opera and IE8, if I right click the document.onclick doesn't fire.
I want to have a custom context menu for img elements. How do I go about this?
Answer: The right-click invokes the context menu within most standard browsers; therefore, you can use the "oncontextmenu" listener to handle right-click events.  The listener should return false if you do not want it to display the standard browser context menu after invoking your JS code.
Here's some sample html that handles left and right clicks on an image.

For more information, check out http://www.w3schools.com/html5/html5_ref_eventattributes.asp


The $\Gamma$-function as a holomorphic function

Question: Let $U:=\{s \in \mathbb{C} | \operatorname{Re}(s)>0\} .$ I know that
$$
\Gamma(s):=\int_{0}^{\infty} e^{-x} x^{s-1} d x \quad\left(x^{s}=e^{s \log x}\right)
$$
defines a holomorphic function $\Gamma: U \rightarrow \mathbb{C}$ that satisfies the functional equation $s \Gamma(s)=\Gamma(s+1) .$ I've already constructed a holomorphic extension of $\Gamma$ to $\tilde{U}:=\mathbb{C} \backslash\{0,-1,-2, \ldots\}$:
$\Gamma(s)=\frac{1}{s(s+1)(s+2)...(s+n-1)} \Gamma(s+n)$
Now I have to argue that this is the ONLY extension of $\Gamma$ from $U$ to $\tilde{U}$
How do I have to argue?
Comment: By the principle of analytic continuation
Answer: By the Identity theorem (also known as principle of analytic continuation), if two holomorphic functions are equal on a open connected set they are equal on all their common domain. Thus, since $U$ is an open and connected set, every holomorphic function defined on $\tilde{U}$ which extends $\Gamma$ will be equal to the analytic continuation you obtained.


Why won't my float code work?

Question: I'm going crazy trying to figure out why this code isn't working to put these 2 divs side-by-side. Am I crazy? Is this an obvious fix? Please help! Thank you

Creativene is a place for artists and art enthusiasts to come together to buy and sell art.

  Sign-up today!

Comment: Have you tried adding a width to the `mastleft` div?
Answer: Floated elements should be defined BEFORE the elements they're floating relative to, e.g.

...
  <--- defined first

 ...

Answer: Div elements have an implicit new line attached to them.  If you want to elements to be on the same line, use ... instead.
Answer:

Creativene is a place for artists and art enthusiasts to come together to buy and sell art.

    Sign-up today!

Why won't my float code work?


Porta do roteador não abre!

Question: Então, eu estou com um problema aki. Queria fazer um website apache2 (apenas para teste) e liberá-lo para a rede, mas a porta do meu roteador não abre de jeito nenhum. Modelo do router: TL-WR740N e Modem: ZTE.
Obs: quando coloco o meu ip na porta 80 aparece uma janela dizendo "DSL Router", mas não consigo acessar a minha página (que configurei em outra porta).
Comment: Depende de quantas "camadas de rede**s**" você tem e também pode ser que o roteador bloquei a porta, pode ser também que o firewall esteja bloqueando, pode ser  o provedor de internet que tenha algum bloqueio, esta um pouco amplo para poder responder, veja se isto lhe ajuda: [acesso externo com wamp](https://pt.stackoverflow.com/a/50934/3635)
Comment: o que seriam essas camadas? no roteador eu já abri, so se for o firewall ou o provedor (oi). Mas existe algum tipo de firewall no linux?como que acessa?
Comment: Jackson, coloquei entre aspas, digo camadas no caso um aparelho em Wan que esta entre o computador e o roteador ou modem (se o modem se conecta diretamente), então no caso teria que liberar a porta "camada" por "camada". Isto é apenas uma **teoria**, não tem como saber, por isso lhe informei todos possíveis problemas que presumo: 1. vc tem mais de um aparelho em Wan ("camadas") 2. Firewall que bloqueia algo 3. provedor que bloqueia algo. Claro que podem existir outros problemas, mas não tem como lhe dar uma resposta exata para isto, é muito relativo...
Comment: ... tente seguir as dicas do link https://pt.stackoverflow.com/a/50934/3635 fazendo o passo a passo para ver se consegue, se ainda falhar tentarei lhe auxiliar via "chat" ;)
Comment: ok vou tentar, valeu pelas dicas : )
Answer: 1) Isso provavelmente é por causa do seu provedor de internet, você pode comunica-los para saber o que é preciso fazer para abrir as portas ou utilizar outra porta corrente do computador.
2) Voce pode utilizar uma VPN Open Port - Quando conectado a uma VPN Open Port você tem todas as portas necessárias abertas... Mas lembrando que VPN'S Open Port as gratuitas nem sempre são ilimitadas entao recomendo que você use o No-IP que dessa forma não haverá problema caso você use outra VPN
Espero ter Ajudado qualquer duvida só perguntar
Comment: Então tentei aqui e nada. Já desativei o firewall, coloquei meu IP na DMZ, será que o modem está de alguma forma "bloqueando" a conexão? testei aqui com a porta 7777 (para não haver conflito).
Answer: 1) Só usa um único modem?
Tenta usar DMZ ao invés de abrir uma porta no NAT. (é só pra testes mesmo não é?)
Desative o firewall pra garantir.
Se não funcionar, pode ser que seu provedor de internet não permita o uso da porta 80, tente com outra porta.
Comment: Sim, uso apenas um modem, mas será que interfere em algo o fato de eu usar um notebook (que está conectado por WiFi) e o modem (que está conectado a um computador)? Queria liberar as portas para o notebook
Comment: Pensei que tinha resolvido tudo, mas fui testar e na verdade o host só está na rede interna. Já coloquei no DMZ e nada, mas percebi que quando coloco o meu ip na porta 80 aparece uma janela dizendo "DSL Router", mas não consigo acessar a minha página (que configurei em outra porta).

Porta do roteador não abre!


Error 1935.An error occurred during the installation of assembly 'Microsoft.VC90.CRT,version="9.0.30729.4148"

Question: I have troubles installing VC runtime libraries to be able to install SQL Server Compact Edition.
The same problem causes also other apps to fail when installing, but I chose this one as a good representative example of my problem (and also it's provided by Microsoft, so "installation should work").
I took a look at what is usually provided as logs/more information and I put on Dropbox on this location: https://www.dropbox.com/s/7zh7ajn50cxz7km/logs.zip 2 logs:

installation log with more info
procmon log of non-success and non-"result not found" while doing the installation step

Any idea what could be the cause and how to fix it?
Edit: CBS Log added: https://www.dropbox.com/s/vcru82wo12y5tj5/CBS.log
Comment: As you can see in the MSI logs, the underlying call to a function named `CreateAssemblyCacheItem` returns `HR=0x80070003` which is "Path not found". It's probably not msiexec.exe that encounters this fault, but some system component, rendering the ProcMon log kinda useless :-(
Comment: I need the folder **C:\Windows\logs\CBS** to see why this fails.
Comment: @magicandre1981: I've added the CBS log as well
Comment: I need the complete CBS folder with all files (copy it to the desktop and zip the folder)
Comment: @magicandre1981, here you go: https://www.dropbox.com/s/4ygwvvw8kzk2q7e/CBS.ZIP
Comment: I can't see any error in the log :(
Comment: try the FixIt from this KB article: http://support.microsoft.com/kb/970652/en-us
Comment: @magicandre1981 that is one the things I tried. Automatic fix app doesn't work on Windows 8 BTW, but I have manually applied the fixes in the registry, restarted ... nope, same log output of the install
Comment: do the old Inplace upgrade (which also works for 8.1) to repair Windows: http://www.sevenforums.com/tutorials/3413-repair-install.html After this install the VC++ Runtime.
Comment: thanks @magicandre1981; I am not sure I am able to do it since I don't have retail Windows 8.1 installation (only the one given by laptop manufacturer, on a partition). I planned on resetting the entire laptop anyway since this problem doesn't plan on going away. Thanks anyway
Comment: you can find 8.1 retail ISOs in the Internet
Comment: where you able to find an ISO and repair Windows? Compare the SHA hashes from the MSDN subscriber page to make sure the ISO is untouched/unmodified.
Answer: This problem was resolved by executing the Windows Refresh, which is destructive on many settings, but all other options were not working...
Answer: All your msi can't be broken at same time, so it's windows installer fault.
big bang mode:
from a cmd elevated:
<code>msiexec /unregserver
msiexec /regserver
</code>
Then install again
Comment: Unfortunately that didn't help either (it was one of the things I tried)
Answer: On a windows 2016 server, I solved the problem by relaxing a bit the DCOM security:
launch dcomcnfg
Then setting it to default:


implement function object bind without using c++11

Question: I'm trying to implement my own function object class and bind function (only need to wrap member functions of 2 parameters). I'm restricted to use GCC 4.4.6 and c++0x is not an option.
My Code is as follows. It wouldn't compile.
#pragma once

namespace utils
{

template<class>
class CFunction;

template<class TRet, class Arg1, class Arg2>
class CFunction<TRet(Arg1, Arg2)>
{
public:
    typedef TRet (*FuncPtr) (void*, Arg1, Arg2);
    void* m_pObj;
    FuncPtr m_FuncPtr;

    TRet operator()(Arg1 arg1, Arg2 arg2)
    {
        return m_FuncPtr(arg1, arg2);
    }

    template <class TObj, TRet (TObj::*TMemFunc)(Arg1, Arg2)>
    static CFunction Create(TObj* pObj)
    {
        CFunction Ret;
        Ret.m_pObj = (void*)pObj;
        Ret.m_FuncPtr = &Caller<TObj, TMemFunc>;
        return Ret;
    }
private:
    template<class TObj, TRet (TObj::*TMemFunc)(Arg1, Arg2)>
    static TRet Caller(void* obj, Arg1 arg1, Arg2 arg2)
    {
        TObj* pObj = static_cast<TObj*>(obj);
        return (pObj->*TMemFunc)(arg1, arg2);
    }
};

template<class TRet, class TClass, class Arg1, class Arg2>
CFunction<TRet(Arg1, Arg2)> Bind(TRet (TClass::*func)(Arg1, Arg2), TClass *pObj)
{
    return CFunction<TRet(Arg1, Arg2)>::Create<TClass, func>();
}

} // end of namespace utils

The compile reports
Functional.h: In function 'utils::CFunction<TRet(Arg1, Arg2)> utils::Bind(TRet (TClass::*)(Arg1, Arg2), TClass*)':
Functional.h:48: error: expected primary-expression before ',' token
Functional.h:48: error: expected primary-expression before ')' token

Would anyone tell me what's wrong with the code and how to make it work

After fixing the problem @Vittorio and @MSAlters metioned. I got new Compile errors.
Fixed Code
#include <iostream>

namespace utils
{

template<class>
class CFunction;

template<class TRet, class Arg1, class Arg2>
class CFunction<TRet(Arg1, Arg2)>
{
public:
    typedef TRet (*FuncPtr) (void*, Arg1, Arg2);
    void* m_pObj;
    FuncPtr m_FuncPtr;

    TRet operator()(Arg1 arg1, Arg2 arg2)
    {
        return m_FuncPtr(m_pObj, arg1, arg2);
    }

    template <class TObj, TRet (TObj::*TMemFunc)(Arg1, Arg2)>
    static CFunction Create(TObj* pObj)
    {
        CFunction Ret;
        Ret.m_pObj = (void*)pObj;
        Ret.m_FuncPtr = &Caller<TObj, TMemFunc>;
        return Ret;
    }
private:
    template<class TObj, TRet (TObj::*TMemFunc)(Arg1, Arg2)>
    static TRet Caller(void* obj, Arg1 arg1, Arg2 arg2)
    {
        TObj* pObj = static_cast<TObj*>(obj);
        return (pObj->*TMemFunc)(arg1, arg2);
    }
};

template<class TRet, class TClass, class Arg1, class Arg2>
CFunction<TRet(Arg1, Arg2)> Bind(TRet (TClass::*func)(Arg1, Arg2), TClass *pObj)
{
    return CFunction<TRet(Arg1, Arg2)>::template Create<TClass, func>(pObj);
}

} // end of namespace utils

class TestLogic
{
public:
  bool Test(std::string& str, double d) {
     std::cout << str << ",  " << d << std::endl;
     return true;
  }
};

int main(int argc, const char **argv) {
    TestLogic testObj;
    utils::CFunction<bool(std::string&, double)> f = utils::Bind(&TestLogic::Test, &testObj);
    std::string str("hello");
    f(str, -1.0);
}

New Error:
prog.cc: In function 'utils::CFunction<TRet(Arg1, Arg2)> utils::Bind(TRet (TClass::*)(Arg1, Arg2), TClass*) [with TRet = bool, TClass = TestLogic, Arg1 = std::string&, Arg2 = double]':
prog.cc:59:   instantiated from here
prog.cc:43: error: 'func' is not a valid template argument for type 'bool (TestLogic::*)(std::string&, double)'
prog.cc:43: error: it must be a pointer-to-member of the form `&X::Y'
prog.cc:43: error: no matching function for call to 'utils::CFunction<bool(std::string&, double)>::Create(TestLogic*&)'

Can anyone help me with this pls?
You can run this code enter link description here
Answer: You need to use the template keyword as a disambiguator in Bind:
return CFunction<TRet(Arg1, Arg2)>::template Create<TClass, func>();
//                                  ^~~~~~~~

This is because Create is a dependent name, and the compiler doesn't know if you're trying to call a template function or compare it with TClass. More reading on the subject: Where and why do I have to put the "template" and "typename" keywords?
Comment: Also, `Create` takes a single `TObj*`, but it's called with an empty argument list. Because the name lookup fails, this error isn't yet spotted.
Comment: @MSalters Yes. I encountered this after fixing the name lookup problem memtioned by Vittorio. But my code still not compile. I modified the question. Would you pls hlep me solve this? Thanks a lot
Comment: Luckily that one is trivial. You're using a runtime variable `func` as a compile-time argument `Create`. That's not how C++ works. I suggest you look at an older Boost version (pre C++11, so 1.46 or similar). The C++11 `bind` came from Boost.
Comment: @MSalters Allright. I actually tried to read Boost bind version last night. But stopped right after begnning.  Template is realy a monster to me. Guess I have to pick it up again. v_v. Again, thank you very much !
Comment: @FeiyuChen: It is a monster. Which is why you want it; otherwise you need to invent that yourself. C++11 was not a random fluke; it was designed to make Boost and similar libraries easier to write.


Inductive proof that $n(n-1)(n+1)$ is divisible by $6$

Question: I am trying to prove that $n(n-1)(n+1)$ is divisible by $6$ for all $n$ in $\mathbb{N}$.
My attempt:
The result certainly holds for $n=0$. Suppose now that $n > 0$. Assume that $P(k)$ is true for all $k<n$. In particular $P(n-1)$ is true. Thus $(n-1)(n-2)n$ is divisible by 6. But
$n(n-1)(n+1) = (n-1)(n-2)n + 3n(n-1)$
Now I don't know how to proceed from here. It is not immediately apparent to me that the right hand side of the expression is divisible by 6.
Comment: The first term on the left is a multiple of 6 by hypothesis. The second term is obviously a multiple of 3, and one of $n$ and $n-1$ must be even, because they're consecutive, so the second term is a multiple of 6, too.
Comment: In fact, no need to use induction here. You have the product of three consecutive integers; one of them must be even and one of them must be a multiple of 3, so the product must be a multiple of 6.
Comment: If you want to get some more practice with induction, you could show that $3n (n-1)$ is divisible by $6$ for all $n$ using induction. (Which would then complete your current proof) There are easier ways to do it than induction, of course, but there are easier ways of solving the original problem too.
Answer: Does it have to be by induction?  The solutions suggested by the other answers are more straightforward.
Anyway...
Basis: $(1)(0)(2) = 0$ is divisible by $6$ (when $n = 1$).
Induction: Suppose $k = n(n-1)(n+1)$ is divisible by $6$.  Then
\begin{align}
(n+1)n(n+2) & = (n+1)n[(n-1)+3] \\
            & = k+3n(n+1)
\end{align}
and provided $n(n+1)$ is always even, this quantity is always also divisible by $6$.  We show this secondary claim, also by induction (!).
Basis: $(1)(2) = 2$ is even (when $n = 1$).
Induction: Suppose that $j = n(n+1)$ is even.  Then
$$
(n+1)(n+2) = j+2(n+1)
$$
is also even.
Answer: Hint : either $n$ or $n-1$ is even.
Answer: Hint:

if you multiply 2 consecutive integers together , one of them is going to be even (contains a factor of two)
if you multiply 3 consecutive integers together, one of them is going to contain a factor of 2, and one of them is going to contain a factor of 3
Answer: $n(n+2)(n+2)=$ 6$n \choose 3$, $n \choose 3$ is always a natural number.
Answer: Since the OP already has an answer, here is one more approach for "fun" (in the spirit of killing a fly with a sledgehammer).
The product of the first two terms is $n^2 - n$ which is divisible by $2$, and the product of all three terms is $n^3 - n$ which is divisible by $3$, as follows in each case from Fermat's Little Theorem.
Since $\gcd(2,3) = 1$, divisibility by each implies the expression is divisible by $2 \cdot 3 = 6$. QED.


Localization-induced homomorphism

Question: Currently, I am trying to follow the proof of Proposition 2.5 in this paper. The proposition and proof are shown below, where $S$ is a multiplicatively closed subset of the commutative ring $R$.

I just have one question about this proof. It is the third sentence of the proof. Why does there exist such a $t$? Is $t$ just another name for $1/s$? If this is the case, how we know that $s$ is invertible? From my knowledge, it's not necessary that every element of the multiplicatively closed subset $S$ is invertible.
Thank you!
Answer: The fraction $f_2(a_2)/s=0/1$ in the localization $S^{-1}A_3$.
Now recall when two fractions are same in a localization. This mean that there exists $t\in S$ such that $t(f_2(a_2)\cdot 1-0\cdot s)=0$ in $A_3$. There you go!

Localization-induced homomorphism


Gradual clustering in deterministic manner

Question: We have 128-dimensional vectors representing people's identities where the euclidean metric defines the similarity between them.
Ours solution requires them to be clustered and then annotated (assign real identities to the clusters). This procedure has the purpose of reducing the amount of work necessary to annotate every object - the amount of work needed to annotate objects drops to one fifth since we have the groupings obtained from clustering.
One pass solution with DBSCAN works well, but we would like to do clustering on the fly (gradually). Upload a batch of data, cluster it, annotate it, upload additional batch of data, cluster the additional batch (add them to existing clustering), annotate … If we cluster whole data after new batch then we lost the annotated identities. Is it possible to implement such a solution? Furthermore is it possible to be solved in deterministic manner (no matter on an order of the batches to everytime get the same solution)?
Comment: Clustering in high dimension is is *hard* (Klawonn et al, 2015, "What are Clusters in High Dimensions and are they Difficult to Find?"). You seem to be looking for *online clustering*; I'll add the tag, and [previous questions with both tags](https://stats.stackexchange.com/questions/tagged/online%2bclustering) may be helpful. However, I wouldn't expect there to be an online version that gives results which are invariant with respect to the order of observations.
Comment: Sounds like a tough question, but neither off-topic nor unclear.
Answer: Adding data to DBSCAN suffers from as parameterization problem: the new data can cause clusters to merge, but not to split. Add enough data, and eventually everything will be connected. To prevent this, you would likely need to decrease epsilon and increase minPts over time.
But why don't you just label clusters based on the data they contain? If 80% are labeled the same, assume that the remaining 20% should also be labeled? Or ask the user to verify the current labels, etc. There are many possibilities to reuse the labels from a previous run.


confusion over using constructor in repository pattern

Question: Im new in C#,i have read about constructor,and i have learned the reason we use them is we can assign whatever we want at the time of construct,but something which is difficult for me to understand is,i have a IRepository student like:
    public  interface IStudentRepository
    {

        object getAll();
    }

i implemented it in StudentRepository:
     public class StudentRepository:IStudentRepository
    {
       public testDBEntities DB = new testDBEntities();
        public object getAll()
        {
            var reslt = (from s in DB.Students
                     select new StudentViewModel
                     {
                         Name = s.Name,
                         Id=s.Id
                     });

            return reslt;
        }
    }

in my homeController i can do like the following:
    IStudentRepository _repository=new StudentRepository();
    public JsonResult Index()
    {
       var m= _repository.getAll();
       return Json(m,JsonRequestBehavior.AllowGet);
    }

why should i have a constructor then?like:
       IStudentRepository _repository=new StudentRepository();
    public HomeController(StudentRepository _repository)
    {
        this._repository = _repository;
    }
    public JsonResult Index()
    {
       var m= _repository.getAll();
       return Json(m,JsonRequestBehavior.AllowGet);
    }

im sorry if my question is basic but i could not find a right answer,thanks in advance
Comment: By injecting the repository into the constructor you are doing something called Dependency Injection. This removes the tight coupling between the controller class and the specific implementation of `IStudentRepository`. Constructor injection is one method (probably the most common) of dependency injection.
Answer: Single Responsibility Principle
The first advantage is that your HomeController doesn't have to worry about creating the StudentRepository object. Someone else already instanciated it, generated it from a database, a file or user input or whatsoever. And this is great, because your controller can then focus on its real job, not on how to instanciate another object. This is getting closer on the Single Responsibility Principle.
Dependency Injection
Then, to take advantage of the second one, your constructor should receive the interface instead of the class. That is called Dependency Injection.
If later on, for a reason or another, you decide to change your StudentRepository class in any way, as long as you still implement the interface, you don't have to make a change into your controller.
So your final code could look like :
class HomeController
{
    private IStudentRepository _repository;
    public HomeController(IStudentRepository _repository)
    {
        //We don't know who instanciated the repo, but we don't care
        this._repository = _repository;
    }

    public JsonResult Index()
    {
        //We only know about the repo that it implements IStudentRepository
        //So we know we can call this method without a risk.
        var m= _repository.getAll();
        return Json(m,JsonRequestBehavior.AllowGet);
    }
}

When it changes
To illustrate a change, let's say you first want to test your repo, but don't have a proper database connection. So you decide to use a file, there your class would look like :
public class TestStudentRepository : IStudentRepository
{
    private string MyDatabaseFilePath;

    public object getAll()
    {
        //Load everything from my text file
    }
}

Okay this will work. Let's now say that you have a connection to your database, but that connection requires some steps before being able to use the getAll() method. With your solution, you would have to perform the init steps in your HomeController.
Now with this pattern, you can do :
public class StudentRepository : IStudentRepository
{
    private string _connectionString;

    public DatabaseStudentRepository(string ConnectionString)
    {
        _connectionString = ConnectionString;
    }

    public object getAll()
    {
        //Load everything from my text file
    }
}

Then, it is the role of the object that is using the controller to make sure it instanciated your object correctly. No changes in your controller.
The factory pattern
Final step is to create a Factory for your StudentRepository. It is the role of the Factory to instanciate a proper repo:
public static class StudentRepositoryFactory
{
    public static IStudentRepository InstanciateRepo(bool FromDatabase)
    {
        if (FromDatabase)
        {
            return new DatabaseStudentFactory("ConnectionString To my server");
        }
        else
        {
            return new TestStudentRepository();
        }
    }
}

And now, whatever the way you need to init your repo, it is the role of the Factory to do so; while it is the role of the Controller to use one method of your repository, getAll().
Comment: what change for example?even if i add more interface in the Studentrepository i still can have access to them by instantiating,am i right?
Comment: thanks for your nice example and if i have multiple repositories should i have multiple constructor in homecontroller as well?
Comment: @mortezasol No, and that is the point of such constructs. You constructor in HomeController juste receive an IStudentRepository, whatever class implements it.
Comment: sorry Martin for asking stupid questions,if i want to use other repositories in homecontroller,whats the best practice?add them also in this constructor?
Answer: I think your constructor isn't correct. It must like
IStudentRepository _repository
public HomeController(IStudentRepository _repository)
{
     this._repository = _repository;
}

In fact, it's better to pass the IStudentRepository in the constructor for respecting the pattern dependency injection.
Imaging that you want to test your controller by the unit test. So you want to create fake data. If you create new StudentRepository inside the controller, how to test it?.
But if you pass by the constructor, like :
public class FakeStudentRepository : IStudentRepository
{
     //return fake data
}

By some config, the 3rd library ``dependency injection` will pass your fake repo to the controller and you can test it


Variance after resampling uniformly from a sample from a normal population

Question: I have recently been looking into the Bootstrap, and I was wondering, if I were to have a sample $X=\{x_1,x_2,\dots,x_N\}$ that has $N$ samples, all i.i.d coming from a normal distribution, $N(\mu,\sigma)$.
In the Bootstrap, $B$ resamples, $X_b=\{x_{b1},x_{b2},\dots,x_{bN}\}$, are obtained by resampling uniformly from $X$ (I know that there are variations with bias-corrections and accelerations, but let's keep that aside for now).
So, my question is, how can I relate the variance of $x_1$ to $x_{b1}$? I have a feeling that they are two different random variables now that the uniform resampling with $\tfrac{1}{N}$ selection probability.
Here is how I think of it. $x_i$ comes from a continuous distribution, that is normal. $x_{bi}$, however, comes from a discrete distribution, that is a uniform selection of $x_1, x_2, \dots, x_N$. I think that the probability space of $x_i$ maps somehow into that of $x_{bi}$, but I do not know what sort of a relationship is between them. I am pretty sure it is some form of a bijective mapping $x_i \to x_{bi}$, where $x_{bi}=f(x_i)$, but I cannot think of a way to map "normally distributed numbers to make them uniformly distributed".
My purpose is to simply understand how the resampling process works, how it affects the variance, and whether the variance of $x_{bi}$ can be related to the variance of $x_i$? I am just interested in how it works.
Comment: When you say resample uniformly, do you mean that the rank/database position of the sample was chosen with equal probability for each? Or is the sampling based on the magnitude of X in order to achieve a uniform distribution of values in X? If the former,  are the sample positions randomised or structured prior to resampling?
Answer: The question can be rephrased as: what is the distribution of $x_{b_1}$? In other words consider $b_1$ being uniformly distributed in $\{1,2,...,N\}$ and $x_1,x_2...x_N$ being independent and distributed according to $N(\mu,\sigma^2)$, what is the distribution of $x_{b_1}$?
$$P(x_{b_1}\in A)=\sum_{k=1}^N P({b_1}=k)P(x_k\in A|{b_1}=k)$$
Since ${b_1}$ and $X$ are independent (which is natural since ${b_1}$ is generated with a random generator):
$$P(x_{b_1}\in A)=\sum_k P({b_1}=k)P(x_k\in A)=\frac{1}{n}\sum_kP(x_k\in A)=P(x_1\in A)$$
because all $x_k$ have the same distribution. Thus $x_{b_1}\sim N(\mu,\sigma^2)$ and thus has variance $\sigma^2$. In other words, $x_{b_1}$ is the mixture of several times the same distribution thus has this distribution.
Next question: what is the distribution of $X_b$? It's more difficult I think.


Is it true that $\lim_{x\to 0}\lim_{y \to 0}f(x,y) = \lim_{x\to 0}f(x,x)$?

Question: Is it true that $$\lim_{x\to 0}\lim_{y \to 0}f(x,y) = \lim_{x\to 0}f(x,x)?$$
I have no idea how to disprove or prove it, but it seems intuitively like it must be true.
Comment: I don't think so. You are talkin about two different variables.
Comment: But do you mean the limit $(x,y)\to (0,0)$?
Answer: No. Consider this counter example:
$$\lim_{x\to 0}\lim_{y\to 0} \frac{y^2}{xy}=\lim_{x\to 0}0=0$$
while $$\lim_{x\to 0}\frac{x^2}{x^2}=1.$$
Comment: Ah so it is not true intuitively because in the first case tbeelimit is first taken w.r.t. 1 variable, and then w.r.t the second when the value of  the first limit is already inserted into the formula, whereas in the second case the limits are basiclly taken "at the same time"
Comment: Right, in general limits don't commute.
Answer: In general it is not true because you talking about two different variables because if you consider the function
$$f(x,y) = \frac{xy-xy^2}{x-y}$$
then you see that $$\lim{x\to 0}\lim{y\to 0}f(x,y)$$ gives defined value if you want to replace x with y then function is not defined
So it may be true in few cases but not in general


Diferença entre Error - Exception - Throwable dentro do catch()

Question: Sempre quando eu tratava o catch eu usava (Exception e) porém a alguns dias atras me deparei com uma exceção que não se encaixava no catch (Exception e) então descobri que ela na verdade não é uma exceção mas sim um erro. Logo então passei a suar catch (Error | Exception e) porém hoje me deparei com um código que usa apenas catch (Throwable e).
Então gostaria de saber a diferença entre esses termos, ou, não sei como posso chamá-los.
Comment: Entre no tópico do Uso específico do try-catch e não encontrei nada falando sobre Error, no final das contas acabei achando outros tópicos a respeito que mais ou menos resolveram minha questão, mas sinceramente não acho que minha pergunta seja duplicata desta que você marcou as duvidas são bem diferentes.
Comment: De qual linguagem de programação você está falando? Há um mais do que uma linguagem que tem `Exception` e `Throwable`, mas as regras variam de uma para outra.
Comment: Eu trabalho com java, mas achei que as regras da explicação fossem as mesmas para a maioria das outras linguagens.
Comment: Pelo que eu entendi tanto o `Error` quanto a `Exception` implementam a interface `Throwable` então se eu fiz um `catch (Throwable e)` eu irei capturar todos os objetos lançáveis que no caso são as exceções e erros, entretendo se eu um `catch (Exception e)` eu irei capturar todas os objetos lançáveis do tipo `Exception` e se eu fizer `catch (Error e)` eu irei capturar todos os objetos lançáveis do tipo `Error`. Esta certa a lógica?
Comment: Em Java, `Throwable` é uma classe, e não uma interface. Você recebeu uma resposta sobre PHP porque você não disse sobre qual linguagem estava falando e um amigo aí achou que podia ser PHP. Isso também significou que a sua pergunta estava confusa e mal-elaborada, e portanto foi fechada (afinal de contas, não estava claro sobre qual linguagem você estava falando). Agora, sabendo que a sua pergunta era sobre Java, ela talvez seja uma duplicata [desta outra pergunta](https://pt.stackoverflow.com/q/27529/132).
Answer: Throwable é a interface base para qualquer objeto lançável.

Fonte: PHP - Throwable

Exception é a classe base para todas Exceptions no PHP 5, e a classe base de todas as exceções de usuário no PHP 7.

Fonte: PHP - Exception

Em resumo, a capturar a interface é equivalente a capturar todas as classes que a implementam...

- não sei como posso chamá-los

Imagine o seguinte cenário: você estende a classe \Exception no seu projeto e, quando quiser parar a execução de algo e simplesmente exibir a mensagem, lança essa classe. Mas caso ocorra algum erro fatal, exceção literal, e etc, você exibe a mensagem do erro e encerra a execução total do script. Exemplo:
<?php

try {
    bar();
    if (!baz())
        throw new MinhaExcecao('A função baz() retornou falso.');
} catch (MinhaExcecao $e) {
    echo $e -> getMessage();
    // O script vai continuar a ser executado...
} catch (PDOException $e) {
    die('PDO lançou uma exceção. Há algo errado na conexão/consulta do banco de dados.');
    // O script não vai continuar a ser executado...
} catch (Throwable $e) {
    die('Capturado alguma classe que implementa a interface Throwable');
    // O script não vai continuar a ser executado...
}

echo 'foo';

Se a função baz() retornar falso, vai cair no bloco catch (MinhaExcecao $e) com o echo e logo o script vai continuar no echo 'foo';... Nos outros casos, a execução será totalmente interrompida pela chamada da função die().
Vale lembrar que os catch funcionam como uma cascata. Ao lançar algum objeto, ele vai ser capturado no primeiro bloco catch compatível com a classe/interface lançada. Dessa forma, sua classe personalizada deve ser capturada primeiro ou antes de sua classe/interface pai, ou então não vai chegar no catch pretendido.
Ainda existe o bloco finally que, teoricamente, SEMPRE é executado.
Estender a classe \Exception é muito útil quando você quer passar alguma mensagem de erro para o usuário a qual ele fez algo de errado. As demais mensagens costumam ser erros do programador ou algum recurso que não está trabalhando da forma adequada. Daí é melhor você gerar um log acessível apenas a você (admin/dev). O usuário não precisa saber o motivo ou onde ocorrem tais erros. Logicamente que seria bem útil dizer algo do tipo: "Este recurso apresentou um erro", mas sem detalhar...
Outro exemplo típico é a conexão com o banco de dados com PHP via PDO que exibe os dados explicitamente quando não estão em um bloco try / catch adequado:

Utilizei o PHP como referência, mas a teoria é equivalente nas principais linguagens de programação. Talvez há algumas pequenas diferenças...
Comment: Pelo que eu entendi tanto o Error quanto o Exception estendem o Throwable é isso? Então se eu colocar catch (Throwable e) eu iriei capturar qualquer exceção ou erro gerado? Sobre a questão das exceções 'próprias' eu já tinha estudado um pouco a respeito, mas mesmo assim obrigado ajudo a clarear ainda mais.
Comment: Sim, mas o certo seria dizer que elas **implementam** a interface Throwable. E, logicamente, você deve capturar cada tipo de exceção em seu devido lugar...
Comment: Sim, eu confundi a palavra estender com implementar, na maioria dos casos eu trabalho cada exceção separadamente porém, em alguns casos, é bem melhor capturar tudo de uma vez. Obrigado pela explicação.


How to boost search relevance based on certain values using Search API

Question: I'm using the Search API with a database back-end.
I would like search results that are tagged Editorial to be favoured over results not tagged Editorial. So, for example, if two articles match a search query, and one is tagged Editorial, I'd like to see the Editorial one listed first.
Can this be done?
Thanks.
Answer: It would be insanely complex to do this properly, since you need to alter some very core Search API mechanics, much of which is handled by the database backend and not search api itself.
What you could do as a hack, it to

Create two fields: A and B.
Select a non existing word like ethsrtsghtpofksd
Add the word in field A when it's an editorial and in field B when it's not an editoral.
Set the searcg weight for field A to be higher than field B
Add the word to all searches before search API sends it to the DB.

Since the word is used in all searches and it always is matches (either in field A or B) it won't effect the results, but the weight they get will be different since field A will get a boost. I haven't tried this before, but it should work. But like I said it's a hack so it's not a pretty solution, but it's a clever way of avoiding to mess with the internal workings of Search API module.
Comment: genius, although I use ethsrtsghtpofksd all the time, so I'd have to pick another word. Hmmm. Also considering loading - say 30 - results and sorting those post-search. No-one ever wants more than 30 results anyway!
Comment: @artfulrobot The problem loading a set of results, is both handling the sorting without messing up how Search API does things especially with facets etc. Also doing that you might end up with close to 0 editorials since they might only start to appear after the loaded set.
Comment: yeah. get that. Still, I'm already mangling user input (e.g. to map "youth" to "young people") so I can be pretty sure that if something is relevant it will appear high up. But it's a good point, thanks for your help.


How can I print user field values in page.html.twig?

Question: I've created a couple of fields for the user in Drupal 8, example: first name. And i'm trying to print it in the home page (page.html.twig) but to no avail.
I tried the following:
{{ user.field_first_name.0['#context']['value'] }}
{{ user.field_first_name.0.value }}
{{ user.field_first_name }}

I even tried adding preprocess functions on mytheme.theme, and still it didn't work.
noting that the below works
{{ user.displayname }}

Appreciate any help given,
thanks
Comment: Don't print user values on page.html.twig. You simply can create a Views block for that, printing the current user in a certain view mode.
Comment: There is a reason why can't get user fields in a page template, this is because the page is not cached per user, only per user permissions. When you use a block, like @leymannx suggested, then only this block needs to be cached per user and not the entire page.
Comment: Alright, will try that, is there a readon not to print user values on page.html.twig?
Comment: Rule of thumb is to avoid templating when possible. Only do this when you need markup changes like in a structural way. Page template is for printing regions. Other reason is you can invalidate the admin UI too easily with templating. That will result in maintenance overhead later.
Comment: It's also worth mentioning that the user object isn't fully loaded by default, you would need to fully load it in a preprocess hook. Where, you could, if you wished, alter the caching. But a block would be a better approach, no need for code.
Answer: To print user fields on the page template create a Views block and place it in an existing region.
At best you first added a new view mode for User under https://example.com/admin/structure/display-modes/view and then on https://example.com/admin/config/people/accounts/display select the newly created view mode and place the fields you like to display.
Then create the view, have it display Users and in the very right under ADVANCED add a contextual filter for User ID. Select Provide default value and choose User ID from logged in user, save. Then in the very left under FORMAT > Show > User select the view mode you created earlier.

Don't print user values on the page template.

page.html.twig is for printing regions.
page.html.twig is cached per user role. Next user with the same role will get displayed initially cached values of another user.
The user object with all field values isn't fully loaded by default, you would need to preprocess the user first.
Templating should be done when you need to structurally change markup.
Answer: Provided that you have Twig Tweak extension installed you could use this method to load any field. It is heavy so use sparingly:
{% set user_entity = drupal_entity('user', user.id, 'default') %}
{% set user_field = user_entity['#user'].getFields().field_name %}
{{ user_field.0.value }}


Delphi Problemas ao Listar Sub-Nó do XML

Question: Tenho o código abaixo, porém no nó do [ICMS]. ele põe na mesma
linha não estou conseguindo ler os filhos. Acontecendo o mesmo com o
[PIS] e [COFINS].*
Ele não obedece o nível 2. Como pegar ou checar se tem mais Niveis ou nó?
Agradeço a quem puder ajudar...
procedure TForm1.Button1Click(Sender: TObject);
var Doc: IXMLDOMDocument;
    node_pai,
    node_filho: IXMLDOMNode;
    node_lista: IXMLDOMNodeList;
    i, j: Integer;
begin
    Memo1.Lines.Clear;
    Doc := CoDOMDocument.Create;
    Doc.load(

'<imposto>                        '+
'    <vItem12741>8.25</vItem12741>'+
'    <ICMS>                       '+
'       **<ICMS00>**              '+
'           <Orig>0</Orig>        '+
'           <CST>00</CST>         '+
'           <pICMS>18.00</pICMS>  '+
'           <vICMS>4.53</vICMS>   '+
'       </ICMS00>                 '+
'   </ICMS>                       '+
'   <PIS>                         '+
'       <PISAliq>                 '+
'           <CST>01</CST>         '+
'           <vBC>25.15</vBC>      '+
'           <pPIS>0.0000</pPIS>   '+
'           <vPIS>0.00</vPIS>     '+
'       </PISAliq>                '+
'   </PIS>                        '+
'   <COFINS>                      '+
'       <COFINSAliq>              '+
'           <CST>01</CST>         '+
'           <vBC>25.15</vBC>      '+
'           <pCOFINS>0.0000</pCOFINS>'+
'           <vCOFINS>0.00</vCOFINS>  '+
'       </COFINSAliq>                '+
'   </COFINS>                        '+
'</imposto>                          '
);
    Doc.async  := False;
    node_lista := Doc.selectNodes('//'+Edit1.Text);

    repeat
        node_pai := node_lista.nextNode;
        if (node_pai = nil) then
            Break;

        Memo1.Lines.Add(node_pai.baseName);
        // Nó do Pai ou Nível 1
        for i := 0 to node_pai.childNodes.length -1 do
        begin
            node_filho := node_pai.childNodes[i];
            if (node_filho <> nil) and
               (node_pai.childNodes[i].childNodes.length > 1) then
            begin
                // Nó do filho ou Nível 2
                for j := 0 to node_pai.childNodes[i].childNodes.length -1 do
                   Memo1.Lines.Add('<' +
                   node_pai.childNodes[i].childNodes.item[j].nodeName + '> '
                   + node_pai.childNodes[i].childNodes.item[j].text);
            end
            else
               // Nó do Pai ou Nível 1
               Memo1.Lines.Add('<' + node_pai.childNodes.item[i].nodeName +
               '> ' + node_pai.childNodes.item[i].text);
        end;
    until (node_pai = nil);
end;

Trecho do XML
<imposto>
    <vItem12741>8.25</vItem12741>
    <ICMS>
        <ICMS00>
            <Orig>0</Orig>
            <CST>00</CST>
            <pICMS>18.00</pICMS>
            <vICMS>4.53</vICMS>
        </ICMS00>
    </ICMS>
    <PIS>
        <PISAliq>
            <CST>01</CST>
            <vBC>25.15</vBC>
            <pPIS>0.0000</pPIS>
            <vPIS>0.00</vPIS>
        </PISAliq>
    </PIS>
    <COFINS>
        <COFINSAliq>
            <CST>01</CST>
            <vBC>25.15</vBC>
            <pCOFINS>0.0000</pCOFINS>
            <vCOFINS>0.00</vCOFINS>
        </COFINSAliq>
    </COFINS>
</imposto>

Answer: Pelo o que entendi você acesso o nó pai que seria "", porém só fez uma tratativa para os possíveis filhos dele.
Quando acessar o pai, precisará realizar um loop nele e criar uma condição para cada um dos filhos que você quer acessar e assim por diante.
É um trabalho um tanto quanto desgastante, no meu caso comecei a trabalhar diretamente com String, lendo o arquivo XML e trabalhando e manipulando a string no XML para conseguir os resultados desejados, o que poupou muito tempo de desenvolvimento.


Help with these isomorphisms

Question: Let $X$ be an affine algebraic set and $f\in K[X]$ where $K[X]$ is the coordinate ring of $X$. Suppose $I(X)=\langle G_1,\ldots,G_r\rangle$ and $W=Z(G_1,\ldots,G_r,FT_{n+1}-1)$, where $G_1,\ldots,G_r\in k[T_1,\ldots,T_n]$.
The image of $F\in k[T_1,\ldots,T_n]$ in the quotient $K[X]$ is $f$, i.e, $f=F+I(X)$.
I'm trying to prove these isomorphisms:
$$k[W]\cong \frac{k[T_1,\ldots,T_n,T_{n+1}]}{\langle G_1,\ldots,G_r,FT_{n+1}-1\rangle}\cong \frac{k[X][T_{n+1}]}{\langle fT_{n+1}-1\rangle}\cong k[X][1/f].$$
I couldn't prove it (I tried a lot), if someone could help me with some of these isomorphisms it would be very helpful to me and I would be very grateful.
I really need help.
Thanks a lot
Comment: Where do you still have problem?
Comment: Dear @EhsanM.Kermani I still don't completely understand why $(k[T_1,\cdots,T_n]/(G_1,\cdots,G_r)) [T_{n+1}] \cong k[T_1,\cdots,T_n][T_{n+1}]/(G_1,\cdots,G_r)$ and why the isomorphism is preserved if you take the quotient from both sides by the ideal $(fT_{n+1}-1)$. Thank you.
Comment: Dear @user75086, I added the detailed explanation. Usually, you should be able to fill all the gaps when you see the guidelines. If you see you can't, this indicates you've missed some preliminary materials. As an advice, going through them helps a lot. Cheers!
Answer: Well, break it down into some small pieces as follows: $k[X]=k[T_1,\cdots,T_n]/(G_1,\cdots,G_r),$ so
$$k[X][T_{n+1}]=(k[T_1,\cdots,T_n]/(G_1,\cdots,G_r)) [T_{n+1}] \cong k[T_1,\cdots,T_n][T_{n+1}]/(G_1,\cdots,G_r)$$
which is in fact
$$k[X][T_{n+1}]\cong k[T_1,\cdots,T_n,T_{n+1}]/(G_1,\cdots,G_r).$$
Then show that the isomorphism is preserved if you take the quotient from both sides by the ideal $(fT_{n+1}-1).$
For the final isomorphism, let $R=k[X],$ define the ring morphism $R[T_{n+1}] \to R[1/f]$ by sending $T_{n+1} \mapsto 1/f,$ then show that it is surjective and its kernel is the ideal $(fT_{n+1}-1).$
Added:

Building the first isomorphism.

To prove $R[X]/I[X] \cong (R/I)[X]$ for $R=k[T_1.\cdots,T_n]$ and $I=(G_1,\cdots,G_r)$ define $g: R[X] \to (R/I)[X]$ by sending a polynomial with coefficient in $R$ to the polynomial with coefficient in $R/I.$ That is, first consider the projection morphism $\pi: R \to R/I$ sending $r \mapsto r+I$ and then
$$g(r_nX^n+\cdots+r_1X+r_0)=(r_n+I)X^n\cdots+(r_1+I)X+(r_0+I)$$
It is easy to show that $g$ is a surjective ring homomorphism. Basically $g$ is constructed from $\pi$ which is a surjective ring homomorphism. Now, in order to use the first isomorphism theorem for rings we should show that the kernel of $g$ is $I[X],$ which is clear since the kernel of $\pi$ is $I$ and $g$ was constructed from $\pi$ by adding a variable $X,$ so the kernel of $g$ is $I[X],$ or if $g(r_nX^n+\cdots+r_1X+r_0)=0$ means that $(r_n+I)X^n\cdots+(r_1+I)X+(r_0+I)=0$ and $0$ in the ring $(R/I)[X]$ is $I[X]$ because a polynomial is equivalent to zero (always zero) if and only if all of its coefficients are zero, that is, $r_i+I$ is zero in $R/I$ for $1 \leq i \leq n,$ and the zero element in $R/I$ is just $I,$ so $r_i+I=I$ implying $r_i \in I$ for all $i.$
Remark: As I explained in my last comment, since $I=(G,\cdots,G_r)$ is an ideal of $k[T_1,\cdots,T_n]$ then $I[T_{n+1}]$ will be an ideal in $k[T_1,\cdots,T_n,T_{n+1}],$ but we still can write $(G,\cdots,G_r)$ instead of $(G,\cdots,G_r)[T_{n+1}]$ when we say consider $(G,\cdots,G_r)$ now as an ideal in $k[T_1,\cdots,T_n,T_{n+1}]$ with no harm.

Why taking quotient of $(fT_{n+1}-1)$ is preserving the isomorphism?

Back to our notation, we showed that
$$k[T_1,\cdots,T_n,T_{n+1}]/(G_1,\cdots,G_r) \cong (k[T_1,\cdots,T_n]/(G_1,\cdots,G_r))[T_{n+1}]$$
and since $k[X]=k[T_1,\cdots,T_n]/(G_1,\cdots,G_r)$ we then have
$$\varphi: k[T_1,\cdots,T_n,T_{n+1}]/(G_1,\cdots,G_r) \cong k[X][T_{n+1}]$$
say the isomorphism map is called $\varphi.$
To prove
$$k[T_1,\cdots,T_n,T_{n+1}]/(G_1,\cdots,G_r,FT_{n+1}-1) \cong k[X][T_{n+1}]/(fT_{n+1}-1)$$
again define a map
$$p: k[T_1,\cdots,T_n,T_{n+1}]/(G_1,\cdots,G_r) \to k[X][T_{n+1}]/(fT_{n+1}-1)$$
by sending an element in $s \in k[T_1,\cdots,T_n,T_{n+1}]/(G_1,\cdots,G_r)$ to $\varphi (s) \in k[X][T_{n+1}]$ and the sending it to $\pi (\varphi (s)) \in k[X][T_{n+1}]/(fT_{n+1}-1)$ where
$$\pi: k[X][T_{n+1}] \to k[X][T_{n+1}]/(fT_{n+1}-1)$$
is the natural projection.
Since $p=\pi \circ \varphi$ then is a ring homomorphism and since $\pi$ is surjective and $\varphi$ is an isomorphism then their composition $\pi \circ \varphi$ is surjective, so $p$ is a surjective ring homomorphism. Again to use the first isomorphism theorem for rings, we should show that the kernel is $(FT_{n+1}-1)$ which is clear since $p(s)=0$ for some $s \in k[T_1,\cdots,T_n,T_{n+1}]/(G_1,\cdots,G_r)$ is meaning that $\pi (\varphi(s))=0$ which means $\varphi(s) \in \ker(\pi)=(fT_{n+1}-1).$ So $\varphi(s)=(fT_{n+1}-1)t$ for some $t \in k[X][T_{n+1}]$ by definition of an ideal. Since $\varphi$ is an isomorphism so its inverse is also an isomorphism then $s=\varphi^{-1}((fT_{n+1}-1)t)=\varphi^{-1}(fT_{n+1}-1) \varphi^{-1}(t).$ The way $\varphi$ was constructed shows that $\varphi^{-1}((fT_{n+1}-1))=FT_{n+1}-1$ because $F \mapsto f$ via the projection $k[T_1,\cdots,T_n] \to k[X].$ Therefore, $s \in (FT_{n+1}-1)$ and $\ker p \subset  (FT_{n+1}-1).$ Obviously $(FT_{n+1}-1) \subset \ker p,$ hence the equality, so we're done.
For the last isomorphism in the question follow the same approach and the last paragraph before "Added."
Comment: @user75086, Basically, you want to prove that $(R/I)[x] \cong R[x]/I.$ Note that you can write any polynomial with coefficient in $R/I,$ as follow: $(a_n+I)x^n+\cdots+(a_1+I)x+(a_0+I)=(a_nx^n+\cdots+a_1x+a_0)+I.$
Comment: @user75086, No, I wouldn't say that. They're basically two different sets. Also note that, when we write $R/I$ it means $I$ is an ideal of $R$ and so $R[x]/J$ means $J$ is an ideal of $R[x],$ so if you don't want to use abuse of notation, since you might get confused, it's better to write the above isomorphism as $(R/I)[x] \cong R[x]/I[x]$ which would be the same as $R[x]/I$ but now this $I$ is different from the previous $I$ in $R/I.$
Comment: Yes, I'm glad you understood it :) Btw the second approach (my last comment) is somewhat easier but less illuminating.
Comment: Dear Ehsan, thank you very much for your answer. I couldn't prove that $(k[T_1,\cdots,T_n]/(G_1,\cdots,G_r)) [T_{n+1}] \cong k[T_1,\cdots,T_n][T_{n+1}]/(G_1,\cdots,G_r)$, can you give me some hints how to proceed?
Comment: Then they are equal, not only isomorphic?
Comment: Dear Ehsan, thank you very much for the details, I didn't understand just the four last lines: "The way $\varphi$ was constructed shows that $\varphi^{-1}((fT_{n+1}-1))=FT_{n+1}-1$ because $F \mapsto f$ via the projection $k[T_1,\cdots,T_n] \to k[X].$ Therefore, $s \in (FT_{n+1}-1)$ and $\ker p \subset  (FT_{n+1}-1).$ Obviously $(FT_{n+1}-1) \subset \ker p,$ hence the equality, so we're done." because you didn't show the isomorphism $\varphi$ explicitly.
Comment: Dear @user75086, initial we defined $g$ and by using the first isomorphism theorem for rings, we constructed $\varphi.$ This is the explicit construction. Perhaps, you should review the theorem once more to shed more lights on this. The fact that $\varphi^{-1}(fT_{n+1}-1)=FT_{n+1}-1$ is directly coming from the construction. Also, since $s$ is a multiple of $FT_{n+1}-1$ i.e. $s=(FT_{n+1}-1) \times \varphi^{-1}(t),$ therefore, $s$ is in the ideal generated by $FT_{n+1}-1$ i.e. $s \in (FT_{n+1}-1).$ And because, $p(s)=0$ implied $s \in (FT_{n+1}-1)$ shows that $\ker p \subset (FT_{n+1}-1)$
Comment: ... and now if you take an element in the ideal $(FT_{n+1}-1)$ say $(FT_{n+1}-1) \times w,$ *because of the construction* $\varphi((FT_{n+1}-1) \times w)=\varphi(FT_{n+1}-1)\varphi(w)=0 \times \varphi(w),$ so the ideal $(FT_{n+1}-1) \subset \ker p.$
Comment: Dear Ehsan how can be possible $\ker p=(FT_{n+1}-1)$? since $(FT_{n+1}-1)$ is not a subset of the the domain of $p$.
Comment: @user75086, this seems very confusing for you. Ok, lets reverse the construction. With the same technique show that the map $k[T_1,\cdots,T_{n+1}]/(FT_{n+1}-1) \to k[X][T_{n+1}]/(fT_{n+1}-1)$ is a surjective ring homomorphism with kernel the ideal $(G_1,\cdots,G_r).$ Can you prove this now?
Comment: No, it's not necessary, I think I understood what you did. However the Kernel in my calculations was $\ker p=\frac{(G_1,\ldots,G_r,FT_{n+1}-1)}{(G_1,\ldots,G_r)}$ and I used the third isomorphism theorem to have the desired result.
Comment: Thank you very much for your help, without you I couldn't understand these isomorphisms! Btw could you improve the last paragraph for others? I think the $\ker p$ doesn't seem quite right. thanks again.
Comment: Ok, I don't have time these days, but I'll explain more in a few days.

Help with these isomorphisms


Music construction kit from some great mind

Question: Quite some years ago in school, a teacher told us about a music construction kit.

The kit is a set of cards.
If you put some cards together, something musically / esthetically sound is the result.
Quite likely, there are some rules, which cards may and which cards may not be put aside.

I'm quite sure, that some great mind was the inventor of the music construction kit. Goethe, Mozart? I'can't remember this fact.
I searched the web, but didn't find anything.

Do you know, who invented the kit?
Where may I find details, which cards the set contained?
And which rules need to be applied.

I'd probably write a software that mimics the kit. But for that, I need details about the kit.
Comment: Also there's this product, created by Philip Sheppard, which sounds closer to what you're describing: http://www.daddoes.com/12134/review-compose-yourself/
Comment: You might find some helpful ideas here: https://music.stackexchange.com/questions/71804/recognizing-intervals-without-interval-songs/110911#110911. It describes an ear-training exercise using a standard deck of playing cards. It may or may not be what your teacher introduced you to, but it could trivially be adapted as a music construction kit. Who invented the game I don't know. I learned it from a choir director.
Answer: You may be looking for the concept of the Musikalisches Würfelspiel ("musical dice game"). The idea has been realized by several musicians throughout history, but it's often created by having a set of pre-composed musical excerpts that are then strung together randomly as decided by the rolls of the dice.
It also looks like there are some apps and browser plug-ins currently available, so your software may already exist.
Answer: Maybe you're thinking of Mozart's 'dice music'?
"One of the most often cited examples of algorithmic music in the Classical Period (1750-1827) is Musikalisches Würfelspiel by Wolfgang Amadeus Mozart (1756-1791). In this composition, Mozart composed discrete musical excerpts that could be combined to form a waltz. The order of musical excerpts was determined by rolling two six-sided dice. The person assembling the waltz would refer to a table created by Mozart that showed which music should be used for the values of 2-12 on the dice."
https://quod.lib.umich.edu/s/spobooks/bbv9810.0001.001/1:5/--algorithmic-composition-a-gentle-introduction-to-music?rgn=div1;view=fulltext
Answer: You might find some inspiration in the Generative Music wikipedia page - the term now means different things to different people, but there's pointers to bunch of different algorithmic music generation approaches, especially relevant if you're looking from an electronic perspective.
Answer: I'm sure Brian Eno had something like this. A set of cards with options like "throw away everything you did and start again". It's a bit risky picking a card because you have to do what it says…
Comment: That's the Oblique Strategies method for breaking creative blocks (https://en.wikipedia.org/wiki/Oblique_Strategies) - Brian Eno is also the coiner of the term Generative Music in my answer, and probably counts as 'some great mind'.
Comment: Method does not relate to music composition. Despite that, thank you.


Custom Control returning task from another function Picker Control

Question: I am developing a Custom Control part of dialog kit fork however I am having a bit of trouble here.
I have included item source as a property of the constructor which works but my question is how do I pass back the value of the picker control to the constructor.
public PickerView(string title, string message, IEnumerable ItemSource, string text = null, Keyboard keyboard = null)
{
        InitializeComponent();

        txtInput.Text = text;
        BindTexts(title, message);
        txtInput.Keyboard = keyboard;
        pickItems.ItemsSource = ItemSource.Cast<object>().ToList();
        pickItems.SelectedIndexChanged += PickItems_SelectedIndexChanged;
 }

The way the control is instantiated is through the interface of
Task<T> GetPickerChoice<T>(string title, string message, IEnumerable ItemSource, string currentText = null,
Keyboard keyboard = null);

I want to be able to get the result that the user has selected out of the xamrian picker control which gets set in this event
private void PickItems_SelectedIndexChanged(object sender, EventArgs e)
{
        throw new NotImplementedException();
}

I need some way of passing the result back to the way it is initiated this I pass in a list as follows.
   List<PickerModel> _testList = new List<PickerModel>();
   PickerModel model = new PickerModel();
   model.Value = 1008;
   model.Description = "FW";
  _testList.Add(model);
  var returnValueFromPicker= await Plugin.DialogKit.CrossDiaglogKit.Current.GetPickerChoice<PickerModel>("Fuel", $"This item is in one or more bins please select a bin location", _testList, null, Keyboard.Numeric);

I want the value of the picker to be in the value of returnValueFromPicker.
Answer: You could have also added a bindable command to your PickerView. With that approach, you can bind ViewModel's command to it (if you use MVVM pattern).
To do that, you may want to add
public static BindableProperty ConfirmedCommandProperty = BindableProperty.Create(
    propertyName: nameof(ConfirmedCommand),
    returnType: typeof(ICommand),
    declaringType: typeof(YourPickerClass),
    defaultValue: null);

public ICommand ConfirmedCommand
{
    get { return (ICommand)GetValue(ConfirmedCommandProperty); }
    set { SetValue(ConfirmedCommandProperty, value); }
}

to your picker. Then you can bind on a view layer.
Answer: What I ended up doing was adding an event handler
public event EventHandler<string> Picked;

To which when the person clicked the ok button of the popup I basically invoked it and returned the selected item for the control in case anyone else finds this usefull.
private void Confirm_Clicked(object sender, EventArgs e)
{
        Picked?.Invoke(this, pickItems.SelectedItem.ToString());
}

Comment: Thank you for sharing, you could marked it. This will make answer searching easier and beneficial to community members.


Declare UIViewController without Knowing Subclass?

Question: Lets say I have a UIViewController subclass called ViewControllerOne and another ViewControllerTwo.
I know the at one point that the class I need in another method is either one of these. Is it possible to pass the class in a method, then inside that method which its received at, declare a UIViewController with whichever subclass was passed?
I want to know if its possible without just doing something like, if this = this, declare view one, else declare view two.
Thanks.
Answer: Your method could be:
- (void)myMethod:(Class)class {
    UIViewController *controller = [[class alloc] init];
}

Or something to that effect.
Or you could create the controller where you know what the class is and pass it into the method:
UIViewController *controller = [[MYViewController alloc] init];
[self myMethod:controller];

And then if need be inside the method:
- (void)myMethod:(UIViewController *)controller {
    if ([controller isKindOfClass:[MYViewController class]]) {
        // Do something
    } else {
        // Do something else
    }
}

Hope that helps! :)
Answer: Josh, besides George's answer, if I understand you right, you should be aware about the following method that every NSObjecthas:
- (BOOL)isKindOfClass:(Class)aClass

So, you can check this way
if ([myObject isKindOfClass:[ViewControllerOne class]])
{
     //declare here ViewControllerOne
     ViewControllerOne *myViewControllerOne = myObject;
}
else if ([myObject isKindOfClass:[ViewControllerTwo class]])
{
     //declare here ViewControllerOne
     ViewControllerTwo *myViewControllerOne = myObject;
}


UITextField not setting NSString

Question: I have a pickerView in a popOver.
When the user selects a row from the pickerView, it should be stored into a UITextField (subject)
The method i'm having troubles is:
- (void) viewWithPickerController:(ViewWithPickerController*) viewWithPickerController didSelectValue:(NSString*) value
{   NSLog(@"selected value is: %@",value);
    subject.text = [NSString stringWithFormat:@"%@",value];
    NSLog(@"subject is: %@",subject.text);

}

Where value is the row of the pickerView: it logs the right value but it doesn't set it to the textField subject, which seems to be null.
Where am i wrong?
Answer: You need to make sure your "subject" IBOutlet is set.
If you're doing this picker view method before your XIB / view controller is instantiated, that would explain why subject is a nil object.
How else would you be instantiating "subject"?
Comment: Yeah, i just noticed that i forgot to set the connection! Damn me! Thank you.
Comment: Don't feel bad. Most iOS devs might not admit it, but everyone makes simple mistakes like this pretty often.
Comment: Yes, definitely! When you think you're sure you've connected everything.. here it comes the error! :)

UITextField not setting NSString


drupal_render() is deprecated. What replaces it?

Question: I have a render array and I want to convert it to HTML and place it in a WYSIWYG field. What is the generally accepted way to do that since drupal_render() is deprecated?
Answer: It was replaced with the renderer service.
$render_service = \Drupal::service('renderer');

As mpdonadio and 4k4 have pointed out in the comments, to prevent metadata from bubbling up to the main request, you should execute this in a new render context. You can do so by using the renderPlain method, rather than the usual render method (unless you're returning this from a controller, in which case use renderRoot instead).
$rendered = $render_service->renderPlain($build);

Comment: Shouldn't that be done in a new render context to prevent any metadata from bubbling to the main one for the page?
Comment: Yes, in this case you should use a new render context, with `\Drupal::service('renderer')->renderPlain($renderArray)` or `->renderRoot()` if this delivers the result from a controller.
Comment: @mpdonadio I'm sure you're right, but I haven't found it necessary the one or two times I've used this. Probably a result of where/when I'm calling it
Comment: @4k4 Thanks for the info, that's very useful to know. I incorporated it into the answer
Comment: @rjacobsen0 You're very welcome, but please see the edit as it has some potentially important information :)
Comment: Got your edit. Thanks! Here's my edited example for anyone who needs it.
`$newBodyValueHtml = drupal_render($newBodyValueRenderArray);` becomes `$render_service = \Drupal::service('renderer');
  $newBodyValueHtml = $render_service->renderPlain($newBodyValueRenderArray);`
Answer: This documentation is the best place to have the most accurate/up-to-date documentation about the rendering pipeline and its methods - such as drupal_render() - in Drupal 8+.


Generalisations of the Gronwall's lemma

Question: Suppose we have the following differential inequality
$F''(w)\le \frac{p-1}{p}\frac{(F'(w))^2}{F(w)}$ on $w\in(w_0,w_0+\varepsilon)$, $w_0>0$, $\varepsilon>0$, $p>1$. In addition, $F(w)>0$, $F'(w)>0$ for $w\in[w_0,w_0+\varepsilon)$.
Let's consider the solution of the Cauchy problem
$\begin{cases}G''(w)= \frac{p-1}{p}\frac{(G'(w))^2}{G(w)},& w\in(w_0,w_0+\varepsilon),\\G'(w_0)=F'(w_0),&\\G(w_0)=F(w_0),&\end{cases},$ which can be written explicitly:
$G(w) = F(w_0)\left(1+\frac{F'(w_0)}{F(w_0)}\frac{w-w_0}{p}\right)^p$.
Is it possible to compare the functions $F$ and $G$ in any meaningful way? This case fits neither the canonical version of the Gronwall's lemma nor its generalisation by Bihari, because it involves second derivatives.
I'd be glad to hear all suggestions!
Answer: For the sake of having an answer, I repost here a solution based on the idea proposed by Hicham at mathoverflow.
In fact, the first differential inequality leads to $\frac{d^2}{dw^2}((F(w))^{1/p})\le 0$, or $(F(w))^{1/p}$ being concave. In the same time, $(G(w))^{1/p}$ is a tangent line to $(F(w))^{1/p}$ in $w_0$, therefore $(F(w))^{1/p}\le (G(w))^{1/p}$ and $ F(w) \le  G(w) $.

Generalisations of the Gronwall's lemma


Unable to obtain desired scrolling with ListView.builder - flutter

Question: I'm trying to achieve a scrolling page that contains a chart and a list of four items such that the whole page must scroll and not partial scrolling of a widget. I created a scrolling list using ListView.builder and wrapped it inside Expanded as a child of Column.
Following is the code:
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Column(
        children: <Widget>[
          new Container(
            width: 490.0,
            height: 340.0,
            child: new LineChart(),
          ),
          new Expanded(
             //height: 500.0,
            child: new ListView.builder(
              itemBuilder: (_, int index) {
                return new Row(
                  children: <Widget>[
                    //displays list details
                    Contents(this.details[index]),
                  ],
                );
              },
              itemCount: this.details.length,
            ),
          ),
        ],
      ),
    );
  }

The output for the above snippet
Thus, in order to achieve complete scrolling I included my class(created to display list details) in the ListView.builder itself. After running the program, I obtained the full page scrolling but a separate chart was created for each of the items in the ListView. I realised that the 'itemCount'  was applied to both the widgets.
Following is the code:
@override
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
  return new ListView.builder(
    itemCount: this.details.length,
    itemBuilder: (BuildContext context, int index) {
      return new Column(
        children: <Widget>[
          new Container(
            width: 490.0,
            height: 340.0,
            child: LineChart(),
          ),
          //displays list details
          Contents(this.details[index]),
          new Divider(height: 2.0,),
        ],
      );
    },
  );
}

The output for the above snippet
P.S.: AsyncSnapshot snapshot has nothing to do with the current page displayed.
Can someone please tell me about the mistake that I made in the above snippets? If the error is big or complicated, then please could you provide the necessary code?
Answer: To stop scrolling of your inner lists you can use physics: NeverScrollableScrollPhysics() in your inner list view. This way their individual scrollability will be removed and they will act like they are a part of your outer list view
Comment: I will try what you've suggested, although I obtained results using Slivers


MySQL won't start or won't installed

Question: I'm trying to get a local LAMP setup on my Ubuntu desktop. I'm successfully got PHP install but I'm having trouble with MySQL
If PHP tries to connet to MySQL I get this error:
Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /var/www/testing.php on line 3
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
If I try via command line I get much the same error:
owen@desktop:~$ mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)
Weirdly "/var/run/mysqld" does not exist.
Running a whereis command I get the following:
owen@desktop:~$ whereis mysqld.sock
mysqld: /usr/sbin/mysqld /usr/share/man/man8/mysqld.8.gz
So is MySQL even installed? Well acording to dpkg
owen@desktop:~$ dpkg -l | grep mysql
ii  libapache2-mod-auth-mysql                                4.3.9-13ubuntu1                                   Apache 2 module for MySQL authentication
ii  libdbd-mysql-perl                                        4.016-1                                           Perl5 database interface to the MySQL database
ii  libmysqlclient15off                                      5.1.30really5.0.83-0ubuntu3                       MySQL database client library
ii  libmysqlclient16                                         5.1.49-1ubuntu8.1                                 MySQL database client library
ii  mysql-admin                                              5.0r14+openSUSE-2.1                               GUI tool for intuitive MySQL administration
ii  mysql-client-5.1                                         5.1.49-1ubuntu8.1                                 MySQL database client binaries
ii  mysql-client-core-5.1                                    5.1.49-1ubuntu8.1                                 MySQL database core client binaries
ii  mysql-common                                             5.1.49-1ubuntu8.1                                 MySQL database common files, e.g. /etc/mysql/my.cnf
ii  mysql-gui-tools-common                                   5.0r14+openSUSE-2.1                               Architecture independent files for MySQL GUI Tools
ii  mysql-query-browser                                      5.0r14+openSUSE-2.1                               Official GUI tool to query MySQL database
ii  mysql-server                                             5.1.49-1ubuntu8.1                                 MySQL database server (metapackage depending on the latest version)
ii  mysql-server-5.1                                         5.1.49-1ubuntu8.1                                 MySQL database server binaries and system database setup
ii  mysql-server-core-5.0                                    5.1.30really5.0.83-0ubuntu3                       MySQL database core server files
ii  mysql-server-core-5.1                                    5.1.49-1ubuntu8.1                                 MySQL database server binaries
ii  php5-mysql
Can someone please help I'm really confused as what to do next. I'm not a Linux expert at all most of these commands I've ran I found of diffrent blogs and help forums.
Comment: Apparently your mysql server is not running. Use `/etc/init.d/mysql-server start` and check your log `tail -f /var/log/syslog` for any errors on the startup process.
Comment: netstat -tupln | grep 3306
Comment: Run the above comment and it will identify if mysql is listening on it's standard port.
Comment: owen@desktop:~$ /etc/init.d/mysql-server start
bash: /etc/init.d/mysql-server: No such file or directory
Comment: owen@desktop:~$ netstat -tupln | grep 3306
(Not all processes can be identified, no information of ownership of the process not show, to be root to see them all.)
Answer:
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Sounds like you're doing something like.....
mysql_connect('localhost'....

The mysql client lib, when it sees 'localhost' doesn't bother making a network conection - it uses the local file (unix) socket. In order to find this socket, it should check the php.ini setting, or use the value in my.cnf, or failing these, compiled in default(s).
Check the mysql is running
ps auxwww | grep mysqld

Check its listening on a network socket:
netstats -nap

The above should also show what file socket it is listening on.
Assuming this is a default installation (i.e. listening on the network port and with no root password) You should be able to connect to the network socket using
mysql -u root -h 127.0.0.1

Then
    show variables like '%sock%'
will also show you where the filesystem socket is.
Update your php.ini setting, e.g.
mysql.default_socket = /var/lib/mysql/mysql.sock

and restart your webserver.
Comment: It seems to be running:
owen@desktop:~$ ps auxwww | grep mysqld
owen      2434  0.0  0.0  11348   868 pts/0    S+   15:03   0:00 grep --color=auto mysqld
Comment: I now think that somehow my installation of MySQL has been corrupted or failed, how can I uninstall & reinstall it?
Answer: I have the same problem on my box.
Try running mysql -h 127.0.0.1 to connect via tcp/ip instead of socket.
Comment: owen@desktop:~$ mysql -h 127.0.0.1
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)
Comment: When PHP tries to connect using 127.0.0.1 I get this diffrent error message:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in /var/www/testing.php on line 3
Lost connection to MySQL server at 'reading initial communication packet', system error: 111
Answer: Success! I finally got MySQL working by running the commands I found on a similar forum post: http://ubuntuforums.org/showthread.php?t=1373144
sudo mysql_install_db
sudo /etc/init.d/mysql start
sudo dpkg-reconfigure mysql-server-5.1
Thanks for all your help guys.

MySQL won't start or won't installed


length of time series to estimate $\phi_2$ for an AR(2)

Question: So I have this question that I am kinda stumped on...
I have an AR(2) model with $\phi_1=0.4$ $\phi_2=0.5$, I need to find how long of a time series I would need to estimate $\phi_2$ with 95% confidence that the estimate is no more than $\pm0.15$
normally when I am working with linear regression I would just calculate SSE and divide by n-2 to get the standard error of the model. My problem is that I have no data and am at loss as to what equation I would use to estimate n.
I know how to estimate $\phi_k$ for k=1,2,3... on rstudio but not what the actual equation that is used to generate the results.

So perusing my book I found that CI for estimated values of $\phi_k$ is $\pm\frac{2}{\sqrt n }$ so just set $0.15=\frac{2}{\sqrt n}$ and solve for n...yielding $n=178$ ?
$$0.15\gt\frac{2}{\sqrt n }$$ so $n\gt177$
Comment: Compare your first inequality (last line in the current post) with what the corresponding part of the question says in words. Paste them one above the other. What quantity should be "no more than" 0.15?
Comment: It looks okay now (apart from some minor details, such as $<$ where it should be $\leq$). The thing was to realize that the interval half-width (which is $2/\sqrt{n}$) is stated to be $\leq 0.15$.
Comment: Please add the `self-study` tag, read its [tag-wiki](http://stats.stackexchange.com/tags/self-study/info) and modify your question to follow the guidelines on asking such questions. In particular, you'll need to clearly identify what you've done to solve the problem yourself, and indicate the specific help you need at the point you struck difficulty.
Comment: Can you work out the standard error of the estimate?
Comment: put my latest attempt down...probably wrong but feel free to comment
Answer: Converting comments and expanding to an answer:
Since the standard error doesn't depend on the variance of the data, if you have the parameter values and a way to work out the standard error from  $n$,  you should be able to at least approximately (/asymptotically) work out the width of a confidence interval as a function of those things.
Since you know a bound on that width you should be able to turn that into a bound on $n$.
Note that your bound is an inequality. This gives you an inequality involving $n$. If you correctly manipulate the inequality, you end up with a lower bound on $n$. There's no need to handwave an equality; the whole thing can be done formally with no additional effort (other than being careful about what happens to the direction of the inequality as you manipulate both sides, but you can  avoid having to remember how to deal with that as long as you never do anything that flips that direction).

Outside of that it looks like you're headed in the right direction.
Comment: put up my new attempt...appreciate your time looking at it
Comment: @statsGuy It's completely wrong. Go back to the earlier attempt with the equality you had relating to the interval half-width. Write *that* as an inequality (read the question wording carefully)
Comment: edited again to reflect ur comment....still seems like im doing something wrong
Comment: 1. What happened to your original quote about what $\frac{2}{\sqrt{n}}$ represents? You've forgotten what you typed about it. $\:$ 2. Back up a couple of edits (click on "edited n minutes ago" under your post, scroll down to the edit where you put in the bit about $\frac{2}{\sqrt{n}}$ - edit 4 - and click "rollback" to go back to what you had at that point). Don't change that until you understand what you're doing from there. $\:$ 3. Specifically read what $\frac{2}{\sqrt{n}}$ *is* and then read what the question says about the 0.15 (it specifically states an *in*equality, not an equality)