How many different ways are there you can make your choices?

Question: Say you have a playlist with 8 hiphop albums, 6 rock albums and 5 pop albums. You then want to create a new playlist with 3 albums from your other palylist.
How many ways are there that you can make your choice if
a) there is supposed to be one album from every genre?
My attempt: multiplication principle gives the answer: $8 * 6 * 5 = 240$ different ways.
b) all 3 albums are to be from the same genre?
My attempt: addition principle gives the answer: $8 + 6 + 5 = 19$ different ways.
Have I used the principles correctly?
Answer: For (a), your solution is correct. There are $8 \choose 1$, $6 \choose 1$, and $5\choose 1$ ways to pick the albums in each genre. You were right to use the rule of product to multiply and to get $240$.
For (b), your solution is wrong. If you want all three albums from hiphop, there are $8 \choose 3$ ways to to do this. If you want all three from rock, you have $8 \choose 3$. Similar for pop.
So you get ${8 \choose 3} + {6 \choose 3} + {5 \choose 3} = 56 + 20 + 10 = 86$ ways. You were right about using the rule of sum, however.
Comment: You meant "If you want all three from rock, you have $\binom{8}{\color\red{3}}$".
Comment: @N.F.Taussig Cheers, edited. Next time, feel free to just edit my post.


Por que esse código JavaScript não funciona?

Question: Por que esse JavaScript não funciona?
Código JavaScript:
$('#basic_validate').submit(function(e) {
    document.getElementById('successmsg').style.display = 'none';
    document.getElementById('errormsg').style.display = 'none';
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "../suppliers/resources/controllers/register.php",
        async: true,
        data: $(this).serialize(),
        success: function(data) {
        },
        complete: function(result){
            if(result == true){
                //clear inputs
                document.getElementById('successmsg').style.display = 'block';
            }else{
                document.getElementById('errormsg').style.display = 'block';
            }
        }
    });
});

Código HTML:
<form class="form-horizontal" method="post" name="frmLogin" id="frmLogin">
//text_inputs

Answer: Se estás a fazer o submit por ajax tens de parar o submit por HTML.
Para isso tens de usar o .preventDefault().
Usa assim:
$('#frmLogin').submit(function(e) {
    e.preventDefault(); // <------------
    $.ajax({
        type: "POST",
        url: "../controllers/insert.php",
        async: true,
        data: $(this).serialize(),
        success: function(data) {
        },
        complete: function(result){
            if(result == 10)
                //clear inputs
                //show msg success
            else
                //show msg error
        }
    });
});

Comment: Tive um erro nessa linha data: $form.serialize(). No seu código tem um }); que eu removi entao o erro nao foi por isso
Comment: @Lucas pois, isso era uma das minhas perguntas no comentário anterior. Imagino que o que queiras seja `$(this).serialize()`. Corrigi na resposta.
Comment: Atualizei o post principal, funcionou mas nao consigo pegar o retorno. No caso do .php eu coloquei return true quando dá sucesso e return false quando dá erro @sergio
Comment: @Lucas faz `console.log(data);` dentro da função success, e `console.log(result);` dentro da função complete. Assim ficas a saber o que recebes. O que aparece na consola?
Comment: @Lucas faz `console.log(data);` dentro da função success, e `console.log(result);` dentro da função complete. Assim ficas a saber o que recebes. O que aparece na consola?


ASP.NET MVC4: IE hangs with file upload and download in same request

Question: I have an elusive client-side problem with Internet Explorer. I am unable to create a webpage that uploads a file and downloads a file in the same request. My application lets the the user download a modified copy of a file they upload.
It's a simple form post event, with no AJAX involved, so the view has this:
<code>@using (Html.BeginForm("Export", "Report", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   <input id="physicalFile" name="physicalFile" type="file" />
   ...
</code>
The server response in the controller is pretty simple too:
<code>[HttpPost]
public ActionResult Export(ReportDetailsModel model, HttpPostedFileBase physicalFile)
{
    ...

    var fileStream = MakeReportFileStream(physicalFile.InputStream);
    return File(fileStream, System.Net.Mime.MediaTypeNames.Application.Octet, "Results.xlsx");
}
</code>
However, Internet Explorer hangs after submitting the form. So bad that you cannot close Internet Explorer and must forcibly "End Task".
Curious factors, including things I've tried, from most curious to least curious:

Does not happen if I remove the file upload control from the form, the download works fine!
Does not happen if I remove the download from the response; the upload on its own works fine!
Still happens with all IE addons disabled
Does not happen in other browsers (Chrome and Firefox)
Does not happen on some machines (like mine) with the same version of Internet Explorer

Any ideas?
EDIT:

Being administrator on the machine has no effect
Still happens when forcing the site into "Trusted Sites" and with minimal available restrictions.
Installing IE11 resolved the issue
In the cloud of confusion, I suspect some configuration forced onto these machines by the IT department.
Answer: Solution: install IE11.
I saw the issue both on IE8 and IE9. I have no data on IE10.


Application of Banach Fixed Point Theorem to sequences

Question: I have the following question
Show that there is unique real bounded sequence $(a_n: n \in \mathbb{N})$ such that
$$a_n = \frac{n+1}{n}+\sum^\infty_{m=1}\frac{\sqrt{3a^2_{m+n}+1}}{4m^2}$$ for all $n \in \mathbb{N}$.
I know I need to use the Contraction/Fixed Point Theorem, so I first defined $\Phi : l_{\infty}(\mathbb{N}) \to l_{\infty}(\mathbb{N})$ by
$$\Phi(a)_n=\frac{n+1}{n}+\sum^\infty_{m=1}\frac{\sqrt{3a^2_{m+n}+1}}{4m^2}$$ where $a\in l_{\infty}(\mathbb{N})$ and $n \in \mathbb{N}$.
But I got stuck in my attempt to show $\Phi$ is a contraction. My last line of work is
$$|\Phi(a)_n - \Phi(b)_n| \leq \cdots \leq \left|3 \sum^{\infty}_{m=1} \frac{a^2_{n+m}-b^2_{n+m}}{4m^2\left(\sqrt{3a^2 _{n+m}+1}+\sqrt{3b^2_{n+m}+1}\right)}\right|$$
Thanks in advance
Comment: Hint: You have $a_{n+m}^2 - b_{n+m}^2 = (a_{m+n} + b_{n+m}) (a_{n+m} - b_{n+m})$. The term $a_{n+m} - b_{n+m}$ is the one you want to keep, while $a_{n+m} + b_{n+m}$ is a really bad term as it can be as big as possible. Try to get rid of it using the term at the bottom. Also see [this](http://www.wolframalpha.com/input/?i=sum+1%2Fn%5E2+%5Ctimes+%5Csqrt+3+%2F4)
Comment: @JohnMa Thanks, I had thought about using the difference of two squares, but hadn't thought enough about trying to cancel with the term at the bottom.
Answer: Just to finalize John Ma's idea.
Note the sequence of inequalities
$$
\begin{align}
|\Phi(a)_n - \Phi(b)_n|
&\leq \left|3 \sum^{\infty}_{m=1} \frac{a^2_{n+m}-b^2_{n+m}}{4m^2\left(\sqrt{3a^2 _{n+m}+1}+\sqrt{3b^2_{n+m}+1}\right)}\right|\\
&\leq \left|3 \sum^{\infty}_{m=1} \frac{a^2_{n+m}-b^2_{n+m}}{4m^2\left(\sqrt{3a^2 _{n+m}}+\sqrt{3b^2_{n+m}}\right)}\right|\\
&\leq \left|3 \sum^{\infty}_{m=1} \frac{(a^2_{n+m}-b^2_{n+m})}{4m^2\sqrt{3}(|a_{n+m}|+|b_{n+m}|)}\right|\\
&\leq \left| \sum^{\infty}_{m=1} \frac{\sqrt{3}}{4m^2}(|a_{n+m}|-|b_{n+m}|)\right|\\
&\leq \sup_m|a_{n+m}-b_{n+m}|\sum^{\infty}_{m=1} \frac{\sqrt{3}}{4m^2}\\
&\leq \frac{\pi^2\sqrt{3}}{24}\sup_m|a_{n+m}-b_{n+m}| \\
\end{align}
$$
Then
$$
\Vert \Phi(a) - \Phi(b)\Vert
\leq\frac{\pi^2\sqrt{3}}{24}\sup_n\sup_m|a_{n+m}-b_{n+m}|
\leq\frac{\pi^2\sqrt{3}}{24}\Vert a-b\Vert
$$
Since $\alpha=\frac{\pi^2\sqrt{3}}{24}<1$ we may apply Banach fixed point theorem.


Tenor sax trouble with low D and E (other notes are fine)

Question: I recently bought a 1950's Conn Naked Lady sax and it works fine except the low D and E are, for lack of a better word, "bubbly", or unstable.  It's not a leak because C and below sound fine.  I've had it checked out and he found nothing wrong, so I assumed it was operator error.  I mentioned it to a friend who asked what kind of mouthpiece I was using (it happens with both my metal and my hard rubber ones.) He said the problem was the shape of the instrument and suggested putting the plastic cap (or some other sort of foreign object) down the bell to create back pressure.  That helped slightly, but not a lot.  I've never had this problem on other saxes (Selmer Mk VI and Yamaha YTS-23), so I'm not sure what to do.  What can I try?
EDIT:  Here's what it sounds like: http://loami-windmill.com/Music/StackExchange-Bubbly%20Tenor%20Sax.mp3
Comment: Can you record that "bubbly sound"? It's very common for old saxophones to have trouble on the low end (even more so than for new ones). I've never played a Naked Lady, but I must admit that I've had _a_ _lot_ of trouble with Conn instruments (even those produced before the years the company went into decline). I played a 1937 no-name model, for example, and it had an issue that I assume is the same as the one you describe. Has the instrument ever been bent/refurbished? Are the pads new? Is there any saliva dried on the pads? Are the tone holes bent in any way?
Comment: To be honest with you, the only saxophones I've played that had a good low end are King Zephyr (not sure about the alto, I play tenor), Keilwerth SX90R and Trevor James Signature. 2 out of those have a large bell. On the other ones, it was always thin, out of tune or distorted in some way. Maybe @MattPutnam will know more about a possible solution to your problem.
Comment: See update to my answer
Comment: I had a similar issue with low C with my 1949 Buescher True Tone 400 (top hat and cane). About 10 years ago I was in London's Soho district when I came across a sax shop (that's right, a sax shop in Soho). I went inside and asked the repair technician about this problem. He said "put a cork in it." More accurately, he said I should drop a cork down the bell. And if that didn't work, put another cork in it. I tried that, and it worked, though it transferred the problem to low B.
Answer: I think you've just run into a "Cranky old Lady" model.  Just as beginners have difficulty producing the lowest notes until they learn breath control,  some saxes are less forgiving than others.
It is possible that the C-pad is too close to its hole, thus partially blocking airflow for notes above C.  If so, then closing the C-pad to produce C would be fine.
Otherwise, I don't see any downside to putting things into the bell to modify the structure slightly.  Try some soft cushions such as a Sax Mute (yes, they exist) to see how those work.
UPDATE
I talked with my brother, who's been a performing sax player for 40 years & a repairman for 30.  He says this is a fantastic horn, and there should be no problem with those notes.  In his words, "find a better repairman," as there is almost certainly a pad leak.
Comment: I had a friend (who is a much better player than I am) play it, and he said the same, "It's a great horn, if you ever think about selling it, call me first."  So my conclusion is my problem is operator error.
Comment: Ugh, he's the best guy I know in a town with not many options.  Guess I'll have to look around.


Why use lag 12 autocorrelation to test January effect?

Question:
I don't understand this example. Why use lag 12 autocorrelation to test January effect.
Comment: The interpretation at the end is blatantly incorrect: the data merely *suggest* there is a nonzero lag-12 correlation.  They could just as well be consistent with an annual drop in stock prices in July.
Comment: A lag 12 autocorrelation on monthly data would measure if a given months returns are linearly related to the same months returns in a prior year.  I certainly doesn't single out an specific month.  I think you're right to be confused.
Comment: As a side comment, it's bad practice to scan a page and post an image of it.  It is more work to type it out, but it greatly helps the usability of the site.  Some of our users interact with the site with other senses than vision, and they cannot interpret your question, which is a shame, because it seems like a good question.
Comment: This isn't how I would test the January effect, but if returns are higher in January, you indeed would see a positive autocorrelation at the 12 month lag and a slightly negative autocorrelation at lower lags.
Comment: @whuber This is exactly what I thought.
Answer: Let $j_{t}$ be an indicator that month $t$ is January. Imagine the return process is:
$$r_t = \mu + b j_t + \epsilon_t$$
Where $\epsilon_t$ is a white noise process. Mean returns are higher in January. Technically, this isn't a stationary process but let's hand wave around that for a second.
\begin{align*}
\operatorname{Cov}\left(r_t, r_{t-12} \right) &= \operatorname{Cov}\left(\mu + bj_t + \epsilon_t, \mu + bj_{t-12}+ \epsilon_{t-12} \right)\\
&= b^2 \operatorname{Cov}(j_t, j_{t-12})
\end{align*}
Remember that $j_t$ is an indicator for whether month $t$ is January, so $\operatorname{Cov}(j_t, j_{t-12}) > 0$.
If this were the data generating process and you ran a regression of returns $r_t$ on $r_{t-12}$, you'd get a positive coefficient (with sufficient data).
Note that this test isn't specific to January. If an effect were specific to February or any other month, it would also create positive autocorrelation at lag 12.
Comment: Interesting.  I'm picturing a blob of points that are the other months and their lags, and then a smaller blob to the upper right that are the Januaries and their lags.


How can I write a 'clamp' / 'clip' / 'bound' macro for returning a value in a given range?

Question: I often find myself writing something like
int computedValue = ...;
return MAX(0, MIN(5, computedValue));

I would like to be able to write this as a single one-line macro. It must be free of side effects, in the same way that the existing system macros MIN and MAX are, and should work for the same data types as MIN and MAX.
Can anyone show me how to turn this into a single macro?
Comment: Just for curiosity, is there any reason not to use std::min and std::max from the C++ standard library ?
Comment: It is usually called `clamp`.
Comment: @ybungalobill Or bound, or clipped, or ... I think the most usual denomination depends on the application domain.
Comment: Well, then, maybe remove the C++ tag, as C++ programmers tend to avoid macros, especially if the standard library provides a much better solution.
Comment: Can't you simply do that, define a min-max macro, _using_ the min and max macros? Or am I misunderstanding your question?
Comment: @kebs I'm mostly in objective-c. It does not fall naturally to use c++ functions :)
Answer: This is without side effects and works for any primitive number:
#define MIN(A,B)    ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; })
#define MAX(A,B)    ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; })

#define CLAMP(x, low, high) ({\
  __typeof__(x) __x = (x); \
  __typeof__(low) __low = (low);\
  __typeof__(high) __high = (high);\
  __x > __high ? __high : (__x < __low ? __low : __x);\
  })

Can be used like so
int clampedInt = CLAMP(computedValue, 3, 7);
double clampedDouble = CLAMP(computedValue, 0.5, 1.0);

Other suggested names instead of CLAMP can be VALUE_CONSTRAINED_LOW_HIGH, BOUNDS, CLIPPED.
Answer: Taken from this site http://developer.gnome.org/glib/2.34/glib-Standard-Macros.html#CLAMP:CAPS
#define CLAMP(x, low, high)  (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))

Comment: Oh, side effects. `CLAMP(getchar(), low++, high--)`
Comment: That's right. Good point!!! So that's why we should do like this http://stackoverflow.com/questions/3437404/min-and-max-in-c/3437484#3437484 and not use the default MIN and MAX like @VosobeKapsimanis suggests.
Answer: Maybe you want to try it like that:
template <class T>
const T& clamp(const T& value, const T& low, const T& high) {
    return value < low ? low:
           value > high? high:
                         value;
}

Comment: Or `return std::max( low, std::min( high, value ) );`
Answer:  #define MAX(a, b) (((a) > (b)) ? (a) : (b))
 #define MIN(a, b) (((a) > (b)) ? (b) : (a))

making it in one #define directive isn't going to be very readable.
Answer: Using just one compare operation:
static inline int clamp(int value, int min, int max) {
    return min + MIN((unsigned int)(value - min), max - min)
}

Comment: Well. Say the type of the value can change - I would prefer a macro? Do you agree?
Comment: Yeah, would require some way to make "unsigned typeof" to turn it into macro.
Comment: On the other hand assuming we're working with integral types only, `#define CLAMP(x, low, high) ({ typeof(low) _low = (low); LARGE_ENOUGH_UNSIGNED_TYPE _x = (x) - _low, _high = (high) - _low; (typeof(x)) MIN(_x, _high); })`


Como colocar uma imagem de "loading" após validação e submit?

Question: Tenho a seguinte situação, um formulário com validação Jquery funcionando.
Porém, como estou enviando alguns anexos no formulário via e-mail, eu queria apresentar uma imagem para o usuário aguardar.
Ai começaram os problemas.
Se todos os campos do formulário forem preenchidos corretamente, sem erros na validação, funciona perfeitamente com a imagem de "loading".
Agora se der um erro de validação, o loading aparece e trava o formulário.
Então minha ideia era fazer com que somente aparecesse o loading se não houvesse erro para evitar o travamento.
Vou postar meu código de js de validação:
$(function () {
$("#divErro").dialog({
    title: 'Erros de Preenchimento',
    bgiframe: true,
    modal: true,
    autoOpen: false,
    buttons: {
        Ok: function () {
            $(this).dialog('close');
        }
    }
});
$.validator.addMethod("verificaTipo", function (value, element) {
    if (value === null) {
        return false;
    }
    return true;
}, "Selecione um tipo válido.");

$("#formEmail").validate({
    invalidHandler: function (e, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
            var message = 'Existe(m) ' + errors + '    campo(s) de preenchimento obrigatório com erro. \n Para corrigir, observe a mensagem de erro no campo em destaque.';
            erro(message);
        }
        return;
    },
    rules: {
        'email.destinatario': {
            required: true,
            email: true
        },
        'email.cc': {
            email: true
        },
        'email.cco': {
            email: true
        },
        'email.assunto': {
            required: true,
            maxlength: 100
        },
        'email.corpo': {
            required: true,
            maxlength: 300
        }
    }
});

E aqui minha função que abre um dialog com o botão submit e cancelar:
function enviaProposta(cod) {
            var buttons = {};
            buttons["Enviar"] = function () {
                $("#formEmail").attr("action", "<c:url value="/proposta/enviarPropostaPorEmail"/>");
                $("#formEmail").submit();
                $("#loadingImg").show();// aqui coloquei a imagem de loading

            };
            buttons["Cancelar"] = function () {
                $(this).dialog('close');
                $('#dialogEmail').limpaForm();

            };
            $('#dialogFormEmail').dialog('option', 'title', 'Enviar Proposta por E-Mail');
            $('#dialogFormEmail').dialog({buttons: buttons});
            $('#dialogFormEmail').dialog('open');
            buscaPropostaEmail(cod);
        }

Poderiam me ajudar nisso?
Answer: Eu costumo usar a função beforeSend do Ajax.
No lugar de:
$("#formEmail").attr("action", "<c:url value="/proposta/enviarPropostaPorEmail"/>");
            $("#formEmail").submit();
            $("#loadingImg").show();// aqui coloquei a imagem de loading

Coloque

$.ajax({
  type: 'POST',
  url: '/proposta/enviarPropostaPorEmail',
  data: $("#formEmail").serialize(),
  beforeSend : function(){
    $("#loadingImg").show();
  }
  success : function(result){
    alert("Enviado");
    $("#loadingImg").hide();
  }
});
Comment: Obrigada @Diego Souza , funcionou perfeitamente! Tks
Answer: Acredito que o NProgress possa resolver seu problema.
Comment: Vou ver isso, obrigada pela dica.


Detect if physical optical drive is present

Question: I need a method to detect if an optical DVD/CD drive is physically present on a computer. Not if a disc is inserted or not (unless that will help my goal).
Using DirectoryExists to me wouldn't always work because not everyone's optical disc drive is D:\ and wouldn't it return false even if there was a drive, but no disc was current inserted?
Answer: If you are prepared to restrict consideration to mapped volumes only you can follow this procedure:

Call GetLogicalDrives to find which drive letters are mapped to a drive.
For each mapped drive letter, call GetDriveType to determine whether or not the drive is an optical drive. An optical drive (CD, DVD, etc.) is identified as DRIVE_CDROM.


Estimating the most abundant isotopomer of an isotopic distribution

Question: i'm trying to pre-estimate the most abundant isotopomers of isotopic distributions.
as a simplified example, picture a molecule with an increasing number of carbons
the natural abundance of carbon's 2 natural isotopes:
C12: 0.9893,
C13: 0.0107

i can figure out a basic way of estimating the most abundant isotopomer of a distribution of 280 carbons by just multiplying each probability by 280:
C12: 277.00399999999996
C13: 2.996

and the distribution is like this:
C12(277)C13(3): 0.22525042944721088 <-- most abundant isotopomer matches the simple estimate
C12(278)C13(2): 0.22474307454998224
C12(276)C13(4): 0.16871013540851823
C12(279)C13(1): 0.14895543071202053
C12(275)C13(5): 0.10072470876143455

which seems to make sense, but this basic estimation of the most abundant isotopomer fails for specific amounts of carbon. the first 200 times this fails:
46,  47,  48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,
59,  60,  61,  62,  63,  64,  65,  66,  67,  68,  69,  70,  71,
72,  73,  74,  75,  76,  77,  78,  79,  80,  81,  82,  83,  84,
85,  86,  87,  88,  89,  90,  91, 140, 141, 142, 143, 144, 145,
146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158,
159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184,
233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245,
246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258,
259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271,
272, 273, 274, 275, 276, 277, 278, 327, 328, 329, 330, 331, 332,
333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345,
346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358,
359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371,
420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432,
433, 434, 435, 436, 437

using 264 as an example:
simple estimate:
C12: 261.17519999999996
C13: 2.8247999999999998

actual distribution:
C12(262)C13(2): 0.23726605718494173
C12(261)C13(3): 0.22411525479708402
C12(263)C13(1): 0.16682229513738878
C12(260)C13(4): 0.15816402306474694
C12(259)C13(5): 0.08895427315599433

and the simple estimate fails, the estimate would be nice for me because i could calculate the rest of the distribution much quicker.
some kind of pattern is clearly there, but has just a sprinkle of seemingly chaotic behavior when you try and find a deeper pattern, annoyingly difficult to predict. How might I approach this problem? Is there a way to accurately predict the most abundant isotopomer?
is there a non-algorithmic way of knowing how many of each isotope will be present in the most abundant isotopomer population? can it be applied to an element, S for example, that has multiple isotopes?
Answer: First, all those $.99999999$ things must be artifacts of your calculations. Especially when you are starting with four significant figures, you can't expect to wind up with more than four significant figures.
Now, let's look at $264$. The probability of $m$ atoms of C12 and $n=264-m$ atoms of $C13$ is $p_m={264\choose m}(.9893)^m(.0107)^{264-m}$. You want the value of $m$ that maximizes $p_m$.
Let's look at
$$
p_{m+1}/p_m={264!\over(m+1)!(263-m)!}{m!(264-m)!\over264!}{.9893\over.0107}
$$
which simplifies to ${264-m\over m+1}{.9893\over.0107}$ We need to know when this changes from being bigger than one to being smaller than one, so set it equal to one, and solve for $m$. You get $261<m<262$, so you just have to check $m=261$ and $m=262$ to see which gives a bigger result.


Pegar foto de galeria android diretamente

Question: Já pesquisei aqui e em outros lugares da internet mas não consegui localizar nada do tipo.
É possível restringir que as fotos selecionadas por um usuário venha apenas da galeria? Ex: Quando eu clico em uma foto de perfil e escolho a opção galeria eu ser direcionado diretamente para as fotos que estão na galeria e seleciono uma qualquer.
Answer: Tente o seguinte:
Abrir opção:
<code> public static final int PICK_IMAGE = 1234;
 Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(Intent.createChooser(i, "Selecione uma imagem"), PICK_IMAGE);
</code>
Recepção da imagem na Activity:
<code> @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != Activity.RESULT_CANCELED){
            if(requestCode == PICK_IMAGE){
                Uri selectedImage = data.getData();
                Toast.makeText(getApplicationContext(), selectedImage.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    }
</code>
Comment: Resposta do Thiago está correta, desse modo a galeria é aberta diretamente. Questão resolvida.


Multiple expressions in mysql IF condition

Question: I need to compare some values from table, i.e. if less, greater and equal...
My query looks like:
  SELECT `t1`.`K1`
  IF (Sum(`t1`.`K1`) > Sum(`t2`.`K1`), 'Greater', 'Less') AS State
  FROM `t1`
  INNER JOIN `t2` ON `t1`.`Code` = `t2`.`Code`
  GROUP BY `t1`.`K1`

How to implement condition if values are equal?
Comment: Just btw, you are missing `,` after `SELECT t1.K1`...
Answer: SELECT `t1`.`K1`,
       case when Sum(`t1`.`K1`) = Sum(`t2`.`K1`) then 'Equal'
            when Sum(`t1`.`K1`) > Sum(`t2`.`K1`) then 'Greater'
            else 'Less'
       end AS State
FROM `t1`
INNER JOIN `t2` ON `t1`.`Code` = `t2`.`Code`
GROUP BY `t1`.`K1`

Answer: SELECT `t1`.`K1`,
IF (Sum(`t1`.`K1`) = Sum(`t2`.`K1`), 'Equal', IF (Sum(`t1`.`K1`) > Sum(`t2`.`K1`), 'Greater', 'Less')) AS State
FROM `t1`
INNER JOIN `t2` ON `t1`.`Code` = `t2`.`Code`
GROUP BY `t1`.`K1`


Computation of log-loss optimal function

Question: I am new to machine learning. Though I know the basic concept of loss functions, Bayes optimal function, Bayes Risk etc. as well as the fundamental concepts of probability, calculus and so on, I can't seem to figure out the following exercise:

Let $Y_I = \{-1,1\}$ and $f: X \to \mathbb{R}$. Compute explicitly the minimizer $f_L(x)$ of the logistic loss $$ L(y, f(x)) = \text{log}(1 + \text{exp}(-y\,f(x)))$$
  in dependency of $\mathbb{P}(Y = 1| X = x)$.

What do I have to do here? Obviously I have to minimize some function but minimizing the loss function itself does not work. I revisited the lecture notes and apparently it is $$ \arg\max\limits_{y} \mathbb{E}[L(y, f(x)), \mathbb{P}(Y = 1|X = x)].$$ This is equivalent to $$\arg\max\limits_y \int_{\mathbb{R}} L(y,f(x))\mathbb{P}(Y=1|X=x),$$ right? But what is $\mathbb{P}(Y=1|X=x)$ exactly? And how to proceed?
Answer: To my surprise, I completely forgot about this question. In the meantime I came across a solution that I will sketch below.
The objective is to minimize $$\mathbb{E}[L(Yf(x))\, \vert\, X = x]$$.
Now rewrite $P = P(Y = 1\, \vert\, X = x)$ and $f = f(x)$. Then we calculate that
$$ \begin{align}
\frac{\partial}{\partial f} \mathbb{E}_Y[L(Yf)\, \vert\, X = x] &= \frac{\partial}{\partial f} \Big(PL(f) + (1-P)L(-f)\Big) \\
                              &= PL'(f) - (1-P)L'(f) \\
                              &= P\frac{-e^{-f}}{1 + e^{-f}} + (1-P)\frac{e^{f}}{1 + e^{f}} \\
                              &= P\frac{-e^{-f}}{1 + e^{-f}} + (1-P)\frac{1}{1 + e^{-f}} \\
                              &\overset{!}{=} 0 \end{align}
                              $$
and thus after solving for $f$ we see that $$f = \log\frac{P}{1 - P}$$ As a matter of fact we are done now since $L(f)$ is convex and hence also some composition. As such the critical point is definitely a minimum. I hope that helps!
Comment: Sorry I mixed up some notation. At first we used $\alpha$ to derive the solution, I changed it to $f$ for the sake of clarity.
Comment: What is the interpretation of this result - and what is $\alpha$?


Example: Principal transformation groupoid with groupoid topology strictly finer than product topology

Question:
Out of curiosity, what would be an example for the following situation:

Let $G\curvearrowright X$ be a free action of a locally compact Hausdorff group $G$ on a Hausdorff space $X$.
By the freeness condition, the tranformation groupoid is algebraically principal,
$$X\times G\subseteq X\times X\text{ where }(x,g)\mapsto(x,gx).$$
Moreover one has $X\times G=X\times X$ precisely if the action is transitive.
But the groupoid topology is generally finer than the product topology induced by $X\times X$.
More precisely, convergence in the groupoid topology is given by
$$(x_n,g_n)\to (x,g)\iff x_n\to x\text{ and }g_n\to g,$$
while convergence induced by the product topology is given by
$$(x_n,g_nx_n)\to (x,gx)\iff x_n\to x\text{ and }g_nx_n\to gx,$$
whence the former is generally finer the latter.
What would be an example where the topology is strictly finer?
What I tried so far were examples along the lines $\mathbb{C}\setminus0\curvearrowright\mathbb{C}\setminus 0$,
but from here it looks one requires maybe some sort of "hyperbolic" behavior?

Parallely out of curiosity, I learned from Ian Putnam the following interesting example:
Inside the unit square, consider the diagonal plus the other two corner points,
$$\Delta\cup\{(0,1),(1,0)\}\subseteq [0,1]\times[0,1].$$
I think this example cannot arise as transformation groupoid, but I'm not sure.
So my question, is there maybe a simple argument which forbids such a representation resp. does it admit one?
Answer: Consider the action of $G=\mathbb Z$ on $X=S^1$ given by
$$
  \alpha_n(z)=e^{2\pi i n\theta }x, \quad \forall n\in\mathbb Z, \quad \forall x\in S^1,
  $$
where $\theta$ is an irrational number.  Can you show that the two topologies on the transformation groupoid are very different?
Comment: Right, thank you! :)


How to use GridSearchCV to compare imputer methods?

Question: I'm working on preprocessing the Titanic data set in order to run it through some regressions.
It is the case that the "Age" column in the train and test sets is only populated for around 80% of the rows in each set.
Rather than just eliminate the rows that don't have an "Age" I'd like to use the SimpleImputer (from sklearn.impute import SimpleImputer) to fill in the missing values in those columns.
SimpleImputer has three options for the 'method' parameter that work with numeric data. These are mean, median, and most frequent (mode). (There's also the option to use a custom value, but because I'm trying to avoid "binning" the values I don't want to use this option.)
At its most basic, my approach would involve manually setting up the required datasets. I'd have to run one of each kind of imputer (imputer = SimpleImputer(strategy="xxxxxx") where xxxxxx = 'mean', 'median', or 'most frequent') on each of the train and test datasets and then end up with six different datasets that I'd then have to feed through my RandomForestRegressor one at a time.
I know that GridSearchCV can be used to exhaustively compare various combinations of parameter values in a regressor, so I'm wondering if anyone knows a way to use it or something similar to run through the various 'method' options of the imputer?
I'm thinking something along the lines of the following pseduocode -
param_grid = [
    {'method': ['mean','median', 'most frequent']},
]

forest_reg = RandomForestRegressor()
grid_search = GridSearchCV(forest_reg, param_grid, cv = 5, scoring = 'neg_mean_squared_error')

grid_search.fit(titanic_features[method], titanic_values[method])

Is there a clean way to compare options like this?
Is there a better way to compare the three options than to build all six data sets, run them through the RF regressor and see what comes out?
Answer: Sklearn Pipeline are exactly meant for this. You have to create a pipeline with imputer component preceding the regressor. You can the then use grid search parameter grid with __ to pass the component specific parameters.
Sample code (documented inline)
# Sample/synthetic data shape 1000 X 2
X = np.random.randn(1000,2)
y = 1.5*X[:,0]+3.2*X[:, 1]+2.4

# Randomly make 200 data points in each axis as nan's
X[np.random.randint(0,1000, 200), 0] = np.nan
X[np.random.randint(0,1000, 200), 1] = np.nan

# Simple pipeline which has an imputer followed by regressor
pipe = Pipeline(steps=[('impute', SimpleImputer(missing_values=np.nan)),
                       ('regressor', RandomForestRegressor())])

# 3 different imputers and 2 different regressors
# a total of 6 different parameter combination will be searched
param_grid = {
        'impute__strategy': ["mean", "median", "most_frequent"],
        'regressor__max_depth': [2,3]
        }

# Run girdsearch
search = GridSearchCV(pipe, param_grid)
search.fit(X, y)

print("Best parameter (CV score=%0.3f):" % search.best_score_)
print(search.best_params_)

Sample output:
Best parameter (CV score=0.730):
{'impute__strategy': 'median', 'regressor__max_depth': 3}

So with GridSearchCV we are able to find that the best impute strategy for our sample data is median with combination if max_dept of 3.
You can keep extending the pipeline with other components.


Probability that first and last are same gender?

Question: There are twelve members on a team, $8$ women and $4$ men. Out of these $12$, a $4$-person relay team is being chosen. What is the probability that the first and last leg of the race are the same gender?
I started working on this, I though it might be a combination but I cant seem to figure it out.
Comment: You can think of the process as filling in order, so the middle two people don't matter. Now you need to ask what's the probability to choose 2 out of 12 things and get the same category, when one category has 8 things and another has 4?
Answer: Approach via multiplication rule of probability and breaking into cases.
"First and last leg of race are the same gender" is equivalent to "First and last are both men or first and last are both women."
Let $M_f, M_l, W_f, W_l$ represent the events man first, man last, woman first, woman last respectively.
The probability you are looking for them is:  $Pr((M_f\cap M_l)\cup(W_f\cap W_l)) = Pr(M_f\cap M_l)+Pr(W_f\cap W_l)~~~~~(\star)$

Multiplication principle of probability:
  $$Pr(A\cap B) = Pr(A)\cdot Pr(B|A)$$

Continuing from $(\star)$ we have $= Pr(M_f)Pr(M_l|M_f)+Pr(W_f)Pr(W_l|W_f)$
Fill in the missing information above and complete the arithmetic to find the final answer.

 $Pr(M_f)=\frac{4}{12}$ since when picking the first position, four of the twelve people available for it are men.  $Pr(M_l|M_f) = \frac{3}{11}$ since we can choose the last person next after having picked the first.  If the first person was a male, then there are three men left who can be in the last spot out of the eleven available remaining people.

Alternatively, approach directly via counting.  Let our sample space be all ways to organize the four people on the team where order is important.  Here we will have $|S|=\frac{12!}{8!}=P(12,4)$.
Count how many ways the first and the last are the same gender.  Break into cases.  Either the first and last are both men, or the first and last are both women.
In either case, pick who the first person is ($8$ ways if woman, $4$ ways if man), followed by picking who the last person is next ($7$ remaining if woman, $3$ remaining if man).  Then pick the second and third persons for the team ($10\cdot 9$ ways regardless).  Apply multiplication rule of counting and addition principle of counting, take the total count and divide by the sample space size, and complete the simplifications to arrive at the answer.


$ I = \int_0^1 ((y')^2-y^2)dx $ and $I_1= \int_0^1 (y' + y \tan x)^2dx$

Question:
Let
  $$ I = \int_0^1 ((y')^2-y^2)dx $$ and $$ I_1= \int_0^1 (y' + y \tan x)^2dx$$
  where y is a given function of $x$ satisfying $y=0$ at $x=1$.
  Show that $I - I_1 = 0$ and deduce that $I \geq 0$.
  Show further that $I = 0$ only if $y=0$ for all $x$ $(0\leq x\leq 1)$

I can show the first part:
$$I_1 = I + [y^2\tan x]_0^1$$ leading to $$I-I_1 = 0$$
How do I do the rest?

deduce that $I \geq 0$.
  Show further that $I = 0$ only if $y=0$ for all $x$ $(0\leq x\leq 1)$

I don't know where to start from here
Many thanks in advance.
Comment: $I_1 \geq 0$, as it is the integral if a non negative function.
Comment: Hint: $I_1>0 \rightarrow I>0$
Answer: You did the most complicate :-)
$$(y'+y\tan x)^2\geq 0\implies \int_0^1(y'+y\tan x)^2dx\geq 0$$
and
$$(y'+y\tan x)^2= 0\implies \int_0^1(y'+y\tan x)^2dx= 0.$$
Answer: Note $I_1=\int_0^1(y'+y\tan x)^2dx\ge 0$ since the integrand is non-negative.  Inasmuch as $I=I_1$, then $I\ge 0$.
The only way that $I=0$ is if $y'+y\tan x=0$ for all $x\epsilon [0,1]$.
This implies that for $y \ne 0$, $\log y=\log (\cos x) +C=0$ for all $x\epsilon [0,1]$.  But this latter solution is not possible.  This in turn implies  $y\equiv 0$.
Comment: @zcahfg2 The ODE $y'+\tan x y=0$ has as solutions either the trivial solution $y=0$ or the solution $\log y=\log \cos x+C$ for some $C$, which implies $y=A\cos x$ for some constant $A$.  Of course, only the trivial solution is viable since $y(1)=0\implies A=0\implies y=0$
Comment: @Dr. MV. Third line, May I ask why you made assumption that $\log y = \log(C\cos x) $ equals to $0$?


size lvm snapshot

Question: I'm configuring an openvz node and would like to use lvm snapshot for backup (I do remote backup too).
The snapshot size is the same that data in the backuped partition ?
If I have a logical volume with 100G data, the snapshot is 100G size ?
I ask that because I don't know how space  use for virtual machines and snapshots in my volume group.
My vg is 450G.
roberto
Comment: sidenote: a snapshot is not a backup.  it's usefull for making a backup, since it shows an exact copy at given instant in time.  The best use is: flush all databases, make a snapshot, allow the VM to continue while you copy from the snapshot to the real backup media, finally destroy the snapshot.
Answer: The size of an LVM snapshot gives the maximum number of blocks you can write in the snapshot or the underlying volume before the snapshot overflows and is broken. So, in your example, having a logical volume of 100G you can create a 1GB snapshot volume it will take 1G in your LVM. Now you can write 1G of data to the snapshot, 1GB of data to the original volume or 500MB to each before the snapshot overflows. A snapshot of 100G would never overflow.
Using snapshots as disks for virtual machines is very nice, as you can provision them quickly, but if you expect the users to write a lot you will have to monitor the size of the snapshots and potentially increase it. The relevant stat is Allocated to snapshot in lvdisplay.
Answer: There's a relevant bit in the man page for lvcreate that seems clear to me:
-s, --snapshot
  ... the  snapshot does  not  need  the same amount of
  storage the origin has. In a typical scenario, 15-20%
  might be enough. In case  the snapshot runs  out
  of  storage,  use lvextend(8) to grow it. Shrinking
  a snapshot is supported by lvreduce(8) as well.
  Run  lvdisplay(8) on  the snapshot in order to check
  how much data is allocated to it....

So, for a 100 GB LV, I'd start with 20 GB for the snapshot volume.
Answer: A snapshot volume ONLY contains the files that have been changed since it was created.  i.e. If you only changed 2kb of files since the snapshot... the snapshot consumes 2kb of disk space.  It is a good idea to plan on allowing the snapshot sufficient space to do what you need before the snapshot is removed...   i.e. if you are going to make 100gb of changes after the snaphot is taken... you need to allocate 100gb to the snapshot.. so it can consume 100gb if needed.

size lvm snapshot


I need. to find $E\exp(luX_{t})$, where $ u \in \mathbb R$

Question: $$
X_{t} = \int _{0}^{t}h(t)dW_{t}
$$
where $h(t)$ is a determined function (not random) and $W_{t}$ is Wiener process.
My thoughts so far:
1)use Ito's formula and find X's probability density.
2)Try to do it by definition of Ito's integral maybe.
3)I know for sure that $X_{t}$ is a gauss process, so maybe there's something there, but still, I'd need to find density first.
Nothing came out so far. So any help is appreciated.
Answer: $X_t$ is normal with mean $0$ and variance $\int_0^{t}h(s)^{2}ds$. Hence $Ee^{luX_t}=e^{l^{2}u^{2}\int_0^{t}h(s)^{2}ds}$.


Intersection of a line through two points on a unit circle with real axis

Question: Suppose we are given two points on unit circle which are represented as complex numbers $u$, $v$. We want to show that the intersection of the line through $u$ and $v$ and the real axis is
$$z=\frac{u+v}{1+uv}.$$
(Again, the complex number $z$ represents the point in plane.)
I will show below my derivation of this formula. I would like to ask:

Are there simpler/other ways to get to the same result?

If I draw the picture, then I see, that I want to find a point which lies on the line going through $a=\frac{u+v}2$ (=center of the line segment joining $u$ and $v$) which is perpendicular to the vector from the origin the point $a$.
If $a$ is the point with coordinates $(R\cos\alpha,R\sin\alpha)$, then I get that $z=\frac{R}{\cos\alpha}$ (simply from the right-angle triangle fromed by $0$, $a$ and $z$). Since $R=|a|$ and $R\cos\alpha=\frac{a+\overline{a}}2$, I get that
$$z=\frac{|a|^2}{\frac{a+\overline{a}}2} = \frac{2a\overline{a}}{a+\overline a}.$$
By plugging $a=\frac{u+v}2$ and using $\overline u = \frac1u$ and $\overline v=\frac 1v$ (since they are on unit circle), I get
$$z = \frac{2a\overline{a}}{a+\overline a} = \frac{\frac{(u+v)(\overline{u}+\overline{v})}2}{\frac{u+\overline{u}+v+\overline{v}}2} =
\frac{(u+v)(\overline{u}+\overline{v})}{u+\overline{u}+v+\overline{v}} = \frac{(u+v)(\frac1u+\frac1v)}{u+\frac1u+v+\frac1v} =
\frac{\frac{(u+v)^2}{uv}}{u+\frac1u+v+\frac1v} = \frac{(u+v)^2}{u^2v+v+uv^2+u} = \frac{(u+v)^2}{(u+v)(uv+1)} = \frac{u+v}{uv+1}.$$

This is the same question as in another post here. The post was put on-hold. Since it seems interesting to me, I would like to repost a better version of that question. Hopefully, I have added enough so that this is not closed for lack of context/effort.
Answer: I don't see how complex numbers play a role here. I am just using the first point as $u(\cos\theta_1,\sin\theta_1)$ and the second as $v(\cos\theta_2,\sin\theta_2)$, write down the equation of the line (this assumes that we don't have $\theta_1=\theta_2$ or $\theta_1=-\theta_2$ --- in the first case there is no line and in the second the answer is $\cos(\theta_1)=\cos(\theta_2)$ - draw a picture).
If $\theta_2+\theta_1\neq\pi$ I find the intersection at
$$\frac{\sin(\theta_1-\theta_2)}{\sin(\theta_1)-\sin(\theta_2)}.$$
Comment: To answer the first sentence of your post: *I don't see how complex numbers play a role here.* Well, the original problem (see the link in my post) was formulated as the task to find the intersection when the points are given as complex numbers. I was somehow surprised that it is such a simple formula, so I wondered whether there is an easy way to the same result. (To be honest, formula in your post is also simpler that I would expect the result of this.)
Comment: Thanks for the answer. Just a quick check whether this leads to the same formula: $\frac{\sin(\theta_1-\theta_2)}{\sin\theta_1-\sin\theta_2}=
\frac{\frac uv - \frac vu}{u-\frac1u -v+\frac1v} = \frac{u^2-v^2}{u^2v-v-uv^2+u} = \frac{(u-v)(u+v)}{(u-v)(uv+1)} = \frac{u+v}{uv+1}$
Comment: @MartinSleziak I appreciate what you are saying but a line in the complex plane is geometrically the same object as a line in the $x$-$y$ plane. I mean you could embed your problem in quaternionic space but you would never actually use any properties of the quaternions. The same principle applies here. By the way, can you see how I got my answer?
Comment: Re: *Can you see how I got my answer?* Probably there are many ways to get to this formula. For example by putting
$\dfrac{x-\cos\theta_2}{-\sin\theta_2}
=\dfrac{\cos\theta_1-\cos\theta_2}{\sin\theta_1 - \sin\theta_2}$ we get
$x=\cos\theta_2-\sin\theta_2\cdot \dfrac{\cos\theta_1-\cos\theta_2}{\sin\theta_1 - \sin\theta_2} =$
$\dfrac{\cos\theta_2(\sin\theta_1 - \sin\theta_2)-\sin\theta_2(\cos\theta_1 - \cos\theta_2)}{\sin\theta_1-\sin\theta_2}=$
$\dfrac{\cos\theta_2\sin\theta_1 - \sin\theta_2\cos\theta_1}{\sin\theta_1-\sin\theta_2}=
\dfrac{\sin(\theta_1-\theta_2)}{\sin\theta_1-\sin\theta_2}$
Comment: Yeah... I just find find the line $y=mx+c$ and solve for $x$ when $y=0$... what you have here.


how to dynamically create multiple select statement and store it in a datatable

Question: the case here is the number of columns i would like to store to the datatable depends on the number of available data. i would need a multiple select statements to collect all the data.
select test_result.stud_id,test_info.max_score,
test_result.test_score
from test_result left join test_info
  on test_result.test_info_id = test_info.test_info_id
where test_info.test_type_id = 1 and test_info.test_num = 1;

i would have to repeat this code over and over again until the test_num reaches the current maximum count. i was thinking of looping this code while storing it to the datatable.this is what i would like the datagridview would display.
|Quiz Number  | Quiz#1 | Quiz #2 | Quiz #3 |  Quiz #4 |  Quiz #5 |
|Max score    |    20  |    25   |    30   |    15    |    15    |
|student 1    |    18  |    22   |    25   |    12    |    14    |
|student 2    |    19  |    20   |    25   |    11    |    13    |
|student 3    |    20  |    24   |    20   |    12    |    11    |

the display of data would be in rows. so each row would require a different select statement in order to display the required data.
Comment: Which RDBMS are you using? Looks like you may need PIVOT
Comment: im using mysql for my database and im using c# as my front end
Answer: Something like below will woek for you
select
test_result.stud_id,
max(case when test_result.test_info_id =1 then test_result.test_score end) as quiz_1,
max(case when test_result.test_info_id =2 then test_result.test_score end) as quiz_2,
max(case when test_result.test_info_id =3 then test_result.test_score end) as quiz_3,
.
.
.
from test_result left join test_info
  on test_result.test_info_id = test_info.test_info_id
where test_info.test_type_id = 1 and test_info.test_num = 1
group by test_result.stud_id;

Comment: thanks man it worked. but i was wondering if how can i make the cases dynamic or is it even possible? coz the test_info_id are all dependent on my selected combo box items


make object move to the mouse clicked position 2d

Question: This is the code for 3D in unity. I changed this to the 2D form, but the object does not move in the 2D world. The writer said it will be okay if I change the word from 3D to 2D, but I seem to be missing something.
private bool flag = false;
private Vector2 endPoint;
public float duration = 50.0f;
private float yAxis;

void Start()
{
    yAxis = gameObject.transform.position.y;
}

void Update()
{

    if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
    {
        RaycastHit hit;
        Ray ray;
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit))
        {
            flag = true;
            endPoint = hit.point;
            endPoint.y = yAxis;
            Debug.Log(endPoint);
        }

    }

    if (flag && !Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
    {
        gameObject.transform.position = Vector2.Lerp(gameObject.transform.position, endPoint, 1 / (duration * (Vector2.Distance(gameObject.transform.position, endPoint))));
    }

    else if (flag && Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
    {
        flag = false;
        Debug.Log("I am here");
    }
}

Comment: Is `flag` ever set to true?
Comment: @Dawnkeeper Yes, look inside `if (Physics.Raycast(ray, out hit))`
Comment: I meant if the code actually reaches this instruction while debugging. =)     He might not get a Raycast hit.
Comment: Ahh ok. I though you meant he's not setting it to true anywhere in the code
Answer: There are two things that could be wrong here:
1) You might not get a Raycast hit
Raycast needs 3D Colliders in the scene. If you don't have them you can't get a hit and thus the movement part of the code is never activated.
2) You might be mixing 2D and 3D
If you are on a purely 2D setup you will have to use Physics2D instead of Physics. So it will be Physics2D.Raycast.
This will also require you to use 2D Colliders.    One example is the PolygonCollider2D
Basically: If the class doesn't end with 2D it will not work with Physics2D.
Answer: Assuming that this code is working properly and all you want to do is make it work in 2D
RaycastHit should be RaycastHit2D
Ray should be Ray2D.
Physics.Raycast should be Physics.Raycast2D
All you do is add 2D to the end of those API then changing all your colliders to colliders 2D in the Editor. For example, Box Collider should be replaced with Box Collider 2D.
Replace:
RaycastHit hit;
Ray ray;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit))
{
    flag = true;
    endPoint = hit.point;
    endPoint.y = yAxis;
    Debug.Log(endPoint);
}

with
Vector2 ray = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray, Vector2.zero);
if (hit)
{
    flag = true;
    endPoint = hit.point;
    endPoint.y = yAxis;
    Debug.Log(endPoint);
}


chamar um método da main activity a partir de um botão do Fragment

Question: Estou usando uma activity padrao do android, a "Navigation Drawer Activity", e Existe um botão  na navigation bar
<code>public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    if (item.getItemId() == R.id.action_example) {
        Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT)
                .show();
        //getActivity().drawGraph();
        return true;
    }
</code>
E eu gostaria de chamar o método drawGraphic() da minha main activity somente ao apertar o botao
Vale ressaltar que essa navigation bar é um fragment
Answer: Tente:
<code>((Nome da Sua Activity)getActivity()).drawGraph();
</code>
Comment: @Andrey Realmente não tenho certeza se o código acima resolve o problema, mas fazer um *cast* de um tipo genérico para um específico é uma saída para chamar algum método do tipo específico. Porém, concordo que o ideal seria o Mateus explicar o código, de forma que a resposta tenha uma utilidade mais abrangente.
Comment: Funcionou. Muito obrigado. Depois vou pesquisar o porquê de ter funcionado.


NBA draft picks as a team rebuilding strategy

Question: I am reading about strategies that general managers use to rebuild an NBA basketball team. By rebuilding I mean the process of letting go existing players and signing new young players with the aim of making a competitive team in the future.
I was reading about the rebuilding process by the Boston Celtics, which seems to be centered around getting draft picks:

In the meantime, Ainge has been doing a great job accumulating future
  draft picks, and that can only help accelerate the restocking of his
  roster. When Ainge traded Jordan Crawford and former Net MarShon
  Brooks to Golden State this past week in a three-way deal with the
  Heat, the Celtics picked up two more draft picks. Between Ainge's
  deals with the Nets and Clippers and other moves, the Celtics now have
  17 potential draft picks over the next five seasons. Some will be used
  for their drafts, but others are likely to be included as sweeteners
  in deals for established players.

http://www.nydailynews.com/sports/basketball/lawrence-rondo-rajon-move-article-1.1583942
My question is: how important is it to accumulate draft picks in a rebuilding effort compared to any other available strategies? And are there examples of teams that have built competitive teams without giving up important players? For example, I would think the San Antonio Spurs as an example of a team that has had competitive teams without going through a rebuilding phase in many years.
Answer: There's no one-size-fits all answer here. Some teams have been fabulously successful rebuilding through the draft. Often it helps to get lucky and have the first pick fall to your team in a year when there is a clear great player to be drafted like Tim Duncan or LeBron James. Other teams have tried to rebuild through the draft and failed because the players they chose did not turn into stars. In the past ten years, teams like the Celtics (who traded for Kevin Garnett and Ray Allen) and the Heat (who signed or traded for LeBron James and Chris Bosh) have been built through a mixture of savvy trades and clever free agent signings. The NBA has a salary cap and a byzantine set of rules about how much you can pay who, so a big factor to success is avoiding bad contracts as much as signing good ones. The Celtics have been stockpiling draft picks but it remains to be seen if they try to rebuild by using them or by trading them for more established players.
Answer: It can be a risky strategy because not all draft picks deliver on the potential/promise of their college performance. There is a similar situation in the NFL where the transition from college to professional playing schedule/style makes it very difficult for young players to handle. A good manager would try to balance the risk of draft picks with the safety of tried and tested players. It is also about getting the right balance in a team of mixing experienced with rookie players so that the energy and respect within the team is good and a solid culture can be established.
Sometimes this has to be considered as part of a bigger strategy for both long term and short term objectives that the team needs to achieve. There's no point getting a lot of rookies to plan for the future if the coach is going to get sacked for under performing or not making the play-offs for example. So the other aspect is managing the expectation of the franchise owners and the fans, which is why it is never an easy job, but someone's got to do it...
Answer: I envisioned three possible values of draft picks: better player talent, cheaper pay, and increasing options for the future.
The main negatives of uncertainty in player development and the time needed to develop.
But had really no great idea on how to weigh them.
However, I came across some great articles, particularly http://fivethirtyeight.com/features/how-much-is-winning-the-nba-draft-lottery-really-worth/ and http://www.82games.com/barzilai1.htm, that helped clear the picture more.  They really narrowed it down to simply how much cheaper a drafted player's results are compared to the same results from free agency.
Averaging from 538's table of net profit per pick... it appears that as of 2014, a random first round draft pick was a gain of about $13 million dollars salary over 5 seasons on average, or about $2.6 million per season.  Which is about 4% of a team's cap (now ~ $3.1 million, next year probably near $4 million).  Second round picks are worth probably at most $1.5 mill/yr based upon the graphs, probably less.
So... if the interest is trying to be good, it looks like $3 mill this year would bump you around 20-40 players by salary this year... or allow you to improve one player by just under 1/4 of the league's talent.
To upgrade from about the cheapest end starting salary (#150 = 4.3 mill) to a max contract (this year 1st year = $18.5-26 mill based on experience, higher for certain players) you'd need the benefit of about 5-7 average draft picks.
So then looking into the Celtics... based on http://espn.go.com/blog/boston/celtics/post/_/id/4716912/bostons-pile-of-draft-picks, you'll gain 5 more extra first round draft picks by the 2017 Draft... so in theory seems decent.
In a totally random world, you'd expect picks of about 3, 7, 10, 13, 17, 20, 23, 27.  So if the team had designed their contracts to absolutely start over from scratch about now... you'd get those 8 picks locked up for a 2nd year cost of only $14 mill total!  Then you could afford to add on maybe like a... Kevin Durant max (should be ~23 mill second year^)... plus a DeMar DeRozan max (~22 mill second year^)... and still have 11 mill left (perhaps sneak in a free agent of the likes of Aaron Afflalo [8 mill], Danny Green [10 mill], or Rondo [9.5 mill], or get a team like Washington to trade someone like Gortat [11 mill] for later picks\contracts if they want to rebuild).
^ - These numbers will all change a bunch this year due to the salary increases.  But the thing is, assuming the distribution by talent stays the same (it generally should given min\max\rookie and such are all tied to salary cap), then the approximate player classes you can get and what a draft pick is worth shouldn't change.  So you'll see bigger numbers than those I gave for the players, but have a higher salary cap to match.
So that's an average expectation of how things could be worked.  You'd also quickly be going well into the luxury after a couple years, and so your owner would probably have to be willing to pay a lot extra.  The economics from an ownership standpoint is a whole nother ball game.  Getting these picks meant rebuilding, and that can be some really poor years.  But then, being a middling team won't make money like being a star team.  So a whole lot of other calculations to it from the ownership standpoint.  Basically, is it financially worth it to be good?  Considering league minimum is 90% of the salary cap, you'd think generally yes, unless you have a really consistent fan base.
Anyways, if it did all build together as I've suggested, the team would then be mostly limited after that to building through the draft, min deals, and mid-level exceptions.  Not a ton of flexibility once that team starts growing (and that's why most teams don't consistently contend anymore?)
But feasibly, it could be done.  Though your additional extra pick last year ended up being low, looks like this year you'll get a good lottery pick from the Nets, plus a fair pick from Dallas, and your own.  I guess your Minnesota pick is turning into two more second round picks (gosh!).  But then you've still got what are probably fair picks from Memphis and the Nets to come in upcoming years (plus your picks and that pile of second rounders).
But then, in all this, I didn't even look into what the Celts have already built.  #4 in the east, mighty impressive.  With $20 million cap room next year (based on current cap).  Actually, $32 mill if you elect to part with Amir.  Thomas, Bradley, and Crowder locked up for two more seasons.
So you could maybe resign one or two of Turner, Zeller, Sullinger... and still get a max player contract... and sign most of your rookies (doubt you'd want 8, if you still have that many picks this season!).
And again, the numbers of course go way up for the cap this year and next (and thus the max and rookie contracts), but it's still the same general situation because it all balances, salary increases vs cap increases.
Players honestly probably won't want to sign long deals because of the big 2017 increases, but in a sense that only helps you.  If you can woo a star for a year based on what you have... then you can have the inside track to sign them next year... or be free to part ways and pursue other max contract guys while enjoying the same great cap situation.  Usually players are FORCING long-term deals as it benefits them with security.  So that you don't have to do that is just generally a plus.  Especially if you're good next year (so people want to come your way).
Plus the picks allow you maneuverability to trade for players or perhaps for picks further on down the road.
Yeah, picks certainly aren't the end all. I don't think the most explosive resurgence stories (Heat 2010, Celtics 2007) were heavy on picks.  But then there are situations like the Cavs last season or the Magic in 2000 (McGrady+Hill... perhaps close on Duncan) that still show potential is there.
A lot of luck involved when it comes to draft picks.  Having them be high.  Having the players picked work out.  Getting stars to invest in you over clubs.  Picking up the right cheap free agents.  But overall, it seems economically workable.  Though it depends what you give up to get them, of course.
But so far... you're looking mighty good!
Addition to better answer one of your questions:
The problem with rebuilding without giving up talent is usually your options are very limited.  If your decent, you're not getting great draft picks.  And you don't have much cap room to sign players, all the while dealing with restrictions based upon your current roster (and player desires).  That the Spurs turned the 28th and 57th picks into two of their cornerstones was a shot in the dark.  And now Leonard at at 15th.  Not everyone can do that, it just isn't possible: there aren't enough good players available to be found that low!  So finding the stud GM\staff\talent scouts cannot be undervalued.
And the bonus that elite teams also get players (their stars and FAs) to sign for less helps extend their reign, as San Antonio has done a fair bit of too, I believe.
Most teams will "rebuild" just by sliding towards mediocrity as their stars age and retire\move on.  Does selling the entire farm for picks give more potential for a return to elite success?  Don't know if we can tell given there are so few real fullblown cases.  The numbers given show there is some potential.  But the real answer probably is: go where the value is.  If there's a lot of teams moving towards rebuilding, then the buyers market will land you talent for cheaper.  But if there's a lot of teams seeking talent, you might have an opportunity to stockpile picks.  It's not so much what you do as what the other teams do, and then what you make of that situation.
But I certainly can't think of many San Antonio's at all in this day-and-age in the NBA.  Much like the Patriots.  You absolutely have to mine low picks in the draft and free agency insanely better than the league.  And so then it just can't be a common thing!
Answer: It depends. I could say that some successful cases would be what Red Auerbach and Danny Ainge have done with the Celtics in their history as well as the Golden State Warriors here recently with Steph, Klay and Draymond and of course the Spurs within the last decade.
Some examples where that did have some success but failed or just been failing because of a lack of experience or just tanking would be the Magic in the 1990s. They had a successful team with the draft picks that they had and build that team up to a championship contender and when their best players either left or got injured, it lost the potential of what that team could have done. I don't know if the 76ers would be revelant with this, but I know that they have had good players on that team that they could have build around and could have made a good team around that and they have been getting high draft picks, but they haven't really build around it yet and I don't think they are trying to either.
The Timberwolves right now should an example of them building a playoff-contending team that can eventually become a championship-contending team. If they keep up with the way that they do in the draft, that will happen and their potential will be high and they should be able to find success for years as long as everything works out.
Comment: Much of this reads purely as opinion or speculation, and the grammar/syntax doesn't help it to make sense either. References to support factual statement should be used and clearly differentiated from your own hypotheses.


Do you have to use a tie over the middle of a bar in 4/2 time?

Question: In my workbook I need to fill in the time signatures and in this example I have used 4/2 as the time signature

as you can see there is a whole note across the bar, is this allowed in 4/2 time? shouldnt you need to use a tie across the middle?
Answer: It's a bit visually strange, but permissible. In general, the convention is to clearly delineate the half-measure in 4/2 (or 2n>0/X) time. But when the rhythm is straightforward, as it is here, using a whole-note can be easier to read.
Comment: I suppose though, if this were a class, and you wanted to be snarky about it just to tweak the teacher, you could give the time signature as (3+1)/2 or (1+2+1)/2. (Because of the note spacing, I would not use (1+3)/2.)
Answer: More and more, we see dots written out as such - with no easily seen demarcation of the middle of a bar in even numbered timing. As in 4/4, crotchet, minim, crotchet, instead of crotchet, crotchet tied to crotchet, crotchet.
I guess when there is a complex rhythm, there's a need for that 'rule' to be in place, but in simplistic cases, as yours, there's little to be gained. After all, the whole point of writing out dots is to make it easy for anyone trying to read said dots. Maybe at the stage someone is at when tackling questions at this level, adhering to the 'rules' would be better. Again, questioning the question!
Answer: I think I might spot one potential confusion. Ian Stewart talks about "lies-to-children," over-simplifications that are necessary to scaffold an understanding, but that are not the full truth. One of those that we were probably all told was "This is a quarter note. It is one beat," and "This is a whole note. It's called that because it takes up a whole measure." The truth is, of course, that any duration can be a beat, and that a whole note is simply 4 x a quarter note. In your example, your whole note is not going "across" a bar line; it simply occupies the second and third of your half-note beats.
Comment: The question isn't about crossing bar lines; it's about the "rule" that notation should express the half measure. OP understands that a whole note is equivalent to two half notes.


Database Design - SQL or NoSQL - CSV data

Question: My scenario:
There's a flask WebApp where a user can login and upload a CSV file.
I need to store and be able to recall the data from the CSV.
Each user can have a different number of columns and rows in their CSV.
I was thinking I could create a unique table per user, recreate it each time a user uploads a new dataset.
However, maybe it makes more sense to just dump it into a NoSQL based database??
Looking for advice of what's the best approach my scenario?
Answer: Since you are only storing and recalling CSV data, I presume you do not change anything within the CSV file. At this point you do not really need a database, in my opinion the simplest solution is to store the CSV file in a folder (let's say each user has its own folder on the server).
Even if you have multiple CSV files for each user, you can store them in the same folder (with different names - you can come up with your own naming convention).
When you recall the file, you can scan the folder of that user and give him the list of files (if there are more than 1), so he can pick whatever CSV he/she wants to get back from the server.
Let's talk about databases: a SQL-like database needs fixed structure (with some exceptions). So you would need to have a consistent dataset in order to add it to a sql DB. In your case it would be easier to use a noSQL database, since with noSQL you don't care about the structure, is just "random" data that you store.
But again ... if you don't do anything with the data, only storing, just store the data as it is: CSV files.
If you have more info, we can brainstorm further.
Regards,
Mike
Comment: Thanks for the great response, Mike. I'm going to look into using cloud storage like S3 to persistently store the files. I can generate a unique identifier for each user in the app database and use that ID to store and retrieve files. Something like:  "[CLOUD_STORAGE]/UPLOADED_USER_FILES/user_UNIQUE_ID/data.csv"
Comment: Yeah that should work. S3 is a good option for storage.  I also use GCP Storage for similar stuff.


Can't get ajax - loaded image's height and width via jquery

Question: I'm loading an image exteranlly via ajax like so...
function load_image(image_href) {

    var img = new Image();
    $(img).load(function () {
        $(this).hide(); $('#a_box').append(this);
        $(this).fadeIn();
        }, gallery_image_load_complete()
    ).error(function () {
    }).attr('src', image_href);

}

function gallery_image_load_complete() {
    conslole.log('complete')

     $('#a_box img').height(); //wrong numbers, as though the image is partially loaded
     $('#a_box img').width(); //wrong numbers
}

The problem is I'm trying to get the loaded image's height and width inside the function gallery_image_load_complete().
For some reason, this image height and width are off, it's astohugh the image hasn't fully loaded.
Can someone help me out please?
Comment: The first parameter of the load method should be the URL, which seems to be missing. Could explain the problem.
Answer: gallery_image_load_complete() needs to be called within the load event handler:
function load_image(image_href) {

    var img = new Image();
    $(img).load(function () {
        $(this).hide(); $('#a_box').append(this);
        $(this).fadeIn();
        gallery_image_load_complete(); // now inside the load event handler
    }).error(function () {
    }).attr('src', image_href);

}

Answer: You do know that the height and width attributes tell you the size of the image object in the DOM, not the underlying image files themselves, right?
Comment: but I have nothing resizing the image, no css, script or restrictions on it whatsoever. It's height in the dom should be it's actual height.
Answer: I don't have the code handy right now, but when I needed the size of an arbitrary image in order to decide how to present it, I preload in a hidden element and get the size of the element @ loaded. then do what you will and place the image where it is needed.
works well.


can't use document.execCommand('copy') with input type file

Question: can't copy the content of textarea to clipboard
using the code below.

    <button id='butt' onClick='copyText()'>copy text</button>
    <input id='in' type='file' style='display:none;'/>

while if i add an alert() after the setTimeout(call,100) in the if block before return statement.Text is being copied.
tried it on chrome,opera and firefox every browser responded the same way.I am using the above structure to copy the base64 encoded text of the file that user opened.
Answer: Most browsers will only copy text to the clipboard in this way from Javascript that was directly initiated from a real user event (like a click or a key) and not from a setTimeout().  So, if your code takes the setTimeout() path, then it is likely that the copying of the text to the clipboard will not work.  You can't just manufacture the keypress event - the whole point of this restriction is to require a real user event, not one manufactured by code.
In case you're interested, here's a tested function to copy text to the clipboard in this answer.  It has the same restrictions as any other code - it must be initiated from Javascript that is called by a real user event and it works in modern versions of Chrome, Firefox and IE, but not in Safari.


ASP.NET built in validation attribute to specify a min or max value?

Question: How can I specify that a value has a certin minimum OR maximum?
I can do range such as:
<code>[Range(0 , 3)]
public int start { get; set; }
</code>
But that specifies its upper and lower bounds. How can I just check if my value is positive ie greater than 0?
Here is my current domain model:
<code>public class Block
{
    [Required(ErrorMessage = "Please enter a value for block id.")]
    public int blockID { get; set; }

    //Start Account code
    [Range(0 , 3)]
    public int start { get; set; }

    //End Account code
    public int end { get; set; }

    //Size of the block space
    public int blockSize { get; set; }

    [Required]
    public Customer customer { get; set; }

}
</code>
Comment: What about `[Range(1 , 1000)]`?
Comment: Yes but I want to know for the case  (x > 0)  that is for the case (0< x <1000 )
Comment: unclear, with your comment
Comment: Maybe you mean that you want one error message if x less than 1 and another if x greater than 1000?
Answer: You can specify the min and max value as
<code>[Range(1 , 999)]
</code>
Comment: Ling the Op wants the range to be greater than 0 and less than 1000. Your answer should be [Range(1, 999)]. Cheers


The time complexity of solving an ODE

Question: I'm a teacher assistant in an ODE course, and I was thinking about the different methods to solve a linear ODE of order $n$ with constant coefficients, and how long they can get. For example you need to invert a matrix (a very costly operation) and do a bunch of integrals if you want to use variation of parameters, or if you want to use undetermined coefficients, finding the coefficients can be a long process (I don't know the actual computational cost though).
I'd like to tell the students that you can't solve the equations faster than this, or that you can actually do it faster, at least theorically, so my question is: is there an upper/lower bound for the time complexity of analytically solving a linear ODE?
Comment: What do you mean by the complexity of *analytically* solving the equation ? Do you mean using a CAS ? I doubt there are well defined results about the complexity of analytical antiderivation. And what would be your definition of the problem size ?
Comment: Also note that for $n\ge5$, there is in general no analytical solution at all,  as you need the roots of the characteristic equation.
Answer: I doubt that this question has a known answer.
If we just consider the simplest case of $y'(x)=f(x)$, as far as I know

we have no theory of the minimal computational cost of analytical integration;
we have no theory of the minimal computational cost of numerical integration.

(And similarly for the problem of root finding for the characteristic polynomial.)
Generally speaking, non-trivial lower bounds are hard to obtain, even for seemingly simple problems. (We still don't know the cost of matrix multiplication.) These questions are highly technical and require some care to define the problem size and the computational model.
As regards upper bounds, these are settled by exhibiting concrete algorithms, but the complete analysis remains difficult and probably only feasible in the numerical case.
Answer: This answer is not about upper/lower bound for the time complexity of analytically solving a linear ODE. It focused on helping students or readers  how to solve $n$ order ODE with starting from first order ODE and then to show how to get general solution and show some simple methods can reduce time to get the final result.
Firstly, students should understand how the general solution looks like and how they can reduce time to solve ODEs with some simple methods. I do not claim that it is upper/lower bound time for an ODE question. I recommend that they use these methods to solve any type of constant coefficient linear ODEs.
Firstly ,Let's solve first order constant coefficient linear ODE.
$$y^{'}(x)-r_1 y(x)=f(x)$$
General solution for it:
$$y(x)=e^{r_1x}\int f(x)e^{-r_1x}dx=e^{r_1x}(\int f(x)e^{-r_1x}dx+c)=ce^{r_1x}+e^{r_1x}\int f(x)e^{-r_1x}dx$$
$$y(x)=ce^{r_1x}+e^{r_1x}\int f(x)e^{-r_1x}dx$$  where $c$ is a constant
Note that we will use this solution for second order ODEs
$$y^{''}(x)+a_{1}y^{'}(x)+a_0 y(x)=f(x)$$
Need to find out roots of 2 order characteristic polynomial.
$r^{2}+a_{1}r+a_0=0$
Roots are $r_1,r_2$
$$(r-r_1)(r-r_2)=0$$
$$r^2-(r_1+r_2)r+r_1r_2=0$$
We can rewrite second order ODE as 2 separate first order ODEs:
$$y^{'}(x)-r_1 y(x)=z_1(x)$$
$$z_1^{'}(x)-r_2 z_1(x)=f(x)$$
If we put $z_1(x)$ in second ODE, we can get
$$(y^{'}(x)-r_1 y(x))'-r_2 (y^{'}(x)-r_1 y(x))=f(x)$$
$$y^{''}(x)-(r_1+r_2) y'(x)+r_1r_2 y(x)=f(x)$$
This is the same ODE with $$y^{''}(x)+a_{1}y^{'}(x)+a_0 y(x)=f(x)$$
We separately will solve 2 first order ODEs
Firstly,
$$y^{'}(x)-r_1 y(x)=z_1(x)$$
$$y(x)=c_1e^{r_1x}+e^{r_1x}\int z_1(x)e^{-r_1x}dx$$
Secondly,
$$z_1^{'}(x)-r_2 z_1(x)=f(x)$$
$$z_1(x)=c_2e^{r_2x}+e^{r_2x}\int f(x)e^{-r_2x}dx$$
$$y(x)=c_1e^{r_1x}+e^{r_1x}\int e^{-r_1x}(c_2e^{r_2x}+e^{r_2x}\int f(x)e^{-r_2x}dx)dx$$
$$y(x)=c_1e^{r_1x}+c_2e^{r_1x}\int e^{(r_2-r_1)x}dx+e^{r_1x}\int e^{(r_2-r_1)x}\int f(x)e^{-r_2x}dxdx$$
Now we will attempt to solve 3 order ODE:
$$y^{'''}(x)+a_{2}y^{''}(x)+a_{1}y^{'}(x)+a_0 y(x)=f(x)$$
$$y^{''}(x)-(r_1+r_2) y'(x)+r_1r_2 y(x)=z_1(x)$$
$$z_1^{'}(x)-r_3 z_1(x)=f(x)$$
$$y(x)=c_1e^{r_1x}+c_2e^{r_1x}\int e^{(r_2-r_1)x}dx+e^{r_1x}\int e^{(r_2-r_1)x}\int z_1(x)e^{-r_2x}dxdx$$
$$z_1(x)=c_3e^{r_3x}+e^{r_3x}\int f(x)e^{-r_3x}dx$$
$$y(x)=c_1e^{r_1x}+c_2e^{r_1x}\int e^{(r_2-r_1)x}dx+e^{r_1x}\int e^{(r_2-r_1)x}\int e^{-r_2x}(c_3e^{r_3x}+e^{r_3x}\int f(x)e^{-r_3x}dx)dxdx$$
$$y(x)=c_1e^{r_1x}+c_2e^{r_1x}\int e^{(r_2-r_1)x}dx+c_3e^{r_1x}\int e^{(r_2-r_1)x}\int e^{(r_3-r_2)x}dxdx+e^{r_1x}\int e^{(r_2-r_1)x}\int e^{(r_3-r_2)x}\int f(x)e^{-r_3x}dxdxdx$$
If we generalize the solution:
$$y^{(n)}+a_{n-1}y^{(n-1)}+a_{n-2}y^{(n-2)}+.....+a_{2}y^{''}+a_{1}y^{'}+a_0 y=f(x)$$

Finding out roots of n degree characteristic polynomial.

$r^n+a_{n-1}r^{n-1}+a_{n-2}r^{n-2}+.....+a_{2}r^{2}+a_{1}r+a_0=0$
We will get n roots for this characterictic equation ;
If characteristic equation  ($n>=5$), the roots of this equation cannot be expressed by radicals but Jerrard demonstrated that quintics ($n=5$) can be solved by using ultra radicals (also known as Bring radicals) . 1858 Charles Hermite showed that the Bring radical could be characterized in terms of the Jacobi theta functions and their associated elliptic modular functions. Higher degree polynomial equation roots can be solved  by some special functions but I have not seen a general  method to solve for all orders yet. Please see my wiki reference link in beyond radicals section . link.
Homogeneous solution :
$$y_h(x)=c_1e^{r_1x}+c_2e^{r_1x}\int e^{(r_2-r_1)x}dx+c_3e^{r_1x}\int e^{(r_2-r_1)x}\int e^{(r_3-r_2)x}dxdx+c_4e^{r_1x}\int e^{(r_2-r_1)x}\int e^{(r_3-r_2)x}\int e^{(r_4-r_3)x}dxdxdx+c_5e^{r_1x}\int e^{(r_2-r_1)x}\int e^{(r_3-r_2)x}\int e^{(r_4-r_3)x}\int e^{(r_5-r_4)x}dxdxdxdx+.........+c_ne^{r_1x}\int e^{(r_2-r_1)x}\int e^{(r_3-r_2)x}\int e^{(r_4-r_3)x}\int.....\int e^{(r_{n}-r_{n-1})x}dxdx......dx  \tag 1$$
Non-Homogeneous solution (particular solution) :
$$y_p(x)=e^{r_1x}\int e^{(r_2-r_1)x}\int e^{(r_3-r_2)x}\int e^{(r_4-r_3)x}\int.....\int e^{(r_{n}-r_{n-1})x}\int f(x)e^{-r_nx}dxdxdx......dx$$
General solution is for n order linear ODE:
$$y(x)=y_h(x)+y_p(x)$$
First method to reduce time:Focus on repeated roots
We can reduce time while placing repeated roots in general solutions above if some roots are repeated
More generally, we can express the root of polynomial as:
$$r^n+a_{n-1}r^{n-1}+a_{n-2}r^{n-2}+.....+a_{2}r^{2}+a_{1}r+a_0=0$$
$$(r-r_1)^{m_1}(r-r_2)^{m_2}...(r-r_k)^{m_k}=0$$ where $m_1+m_2+...+m_k=n$
$$y_h(x)=(c_{(1,1)}+c_{(1,2)} x+...+c_{(1,m_1)}x^{m_1-1})e^{r_1x}+(c_{(2,1)}+c_{(2,2)} x+...+c_{(2,m_2)}x^{m_2-1})e^{r_2x}+.....+(c_{(k,1)}+c_{(k,2)} x+...+c_{(k,m_k)}x^{m_k-1})e^{r_kx}$$
where $c_{(i,j)}$ are unknown constants. (Totally $n$ unknown constant must be.)
Non-homogenous solution:$y_p(x)$
We can reorder roots in any combination in solution of $y_p(x)$ and result will be the same because of symmetrical property of roots.
$$y_p(x)=e^{r_1x}\underbrace{\int.\int}_{m_1\text{ times}} e^{(r_2-r_1)x}\underbrace{\int.\int}_{m_2\text{ times}} e^{(r_3-r_2)x}\underbrace{\int.\int}_{m_3\text{ times}} e^{(r_4-r_3)x}.....\underbrace{\int.\int}_{m_{k-1}\text{ times}} e^{(r_{k}-r_{k-1})x}\underbrace{\int.\int}_{m_k\text{ times}} f(x)e^{-r_kx} \underbrace{dx..dx}_{n\text{ times}}$$
General solution is: $$y(x)=y_h(x)+y_p(x)$$
Second method to reduce time:Focus on complex conjugate roots
If the coefficients of characteristic polynomial are  real constants and if any root has imaginary part, the characteristic polynomial must have a conjecture complex root too.
$$r^n+a_{n-1}r^{n-1}+a_{n-2}r^{n-2}+.....+a_{2}r^{2}+a_{1}r+a_0=0$$
$$(r-r_1)^{m_1}(r-r_2)^{m_2}...(r-r_i)^{m_i}...(r-r_j)^{m_j}...(r-r_k)^{m_k}=0$$ where $m_1+m_2+...+m_i+...+m_j+...+m_k=n$
if ($r_i=\bar{r_j}$) then  $m_i=m_j$
$$r_i=a+ib$$
$$r_j=a-ib$$
$m_1+m_2+...+2m_i+...+m_k=n$
$r_i=a+ib$
$$y_h(x)=(c_{(1,1)}+c_{(1,2)} x+...+c_{(1,m_1)}x^{m_1-1})e^{r_1x}+(c_{(2,1)}+c_{(2,2)} x+...+c_{(2,m_2)}x^{m_2-1})e^{r_2x}+.....+(c_{(i,1)}+c_{(i,2)} x+...+c_{(i,m_i)}x^{m_i-1})e^{ax}\cos(bx)+(c_{(j,1)}+c_{(j,2)} x+...+c_{(j,m_i)}x^{m_i-1})e^{ax}\sin(bx)...+(c_{(k,1)}+c_{(k,2)} x+...+c_{(k,m_k)}x^{m_k-1})e^{r_kx}$$
Comment: Should be tagged as a comment, as it does not address the question of time complexity. And the OP is not asking for a specific method but for a theoretical bound.
Comment: @YvesDaoust :  As you pointed , The main question is very theoretical and unknown path. In other case, I wanted to share some methods that  can help students or readers reduce time while solving ODEs. . I wanted to collect them in one answer. I hope  I pointed out my aim in my answer clearly.Thanks a lot feedback. Best Regards

The time complexity of solving an ODE


PHP Session Script Semi-Functional

Question: I posted a question here yesterday and got a quick response. Great community!
I hope someone can help enlighten me (a newbie to PHP) about my script below and why its execution is inconsistent.
I'm using the following session.php file to check for login and session timeout:
`

function logged_in() {
    return isset($_SESSION['user_id']);
    session_write_close();
}

function session_expired() {
    $now = time();
    $limit = $now - 7200; // 2 hour
    return isset($_SESSION['last_activity']) && ($_SESSION['last_activity'] < $limit);
    session_write_close();
}

function confirm_logged_in() {
    $now = time();
    if (session_expired()) {
        $_SESSION = array();
        if(isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time()-42000, '/');
        }
        session_destroy();
        redirect_to("http://domain.com/login.php?logout=2");
        exit;
    }
    elseif (!logged_in()) {
        redirect_to("http://domain.com/login.php");
        exit;
    }
    else {
        $_SESSION['last_activity'] = $now;
        session_write_close();
    }
}

?>`
At the top of each page I then have:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/functions.php"); ?> defines some other functions I use
<?php confirm_logged_in(); ?>
What's happening is that the session_expired() doesn't always get triggered and instead of  redirect_to("http://domain.com/login.php?logout=2"); it goes to redirect_to("http://domain.com/login.php");
Can anyone see what may be wrong?
Comment: You have `session_write_close()` after your `return` statement. That line won't be executed.
Comment: I see. I have it twice in the two functions logged_in() and session_expired(). I added this based on some research when trying to figure out why my pages were sometimes not loading on the first attempt.
Answer: In a couple of different places, you have session_write_close() after a return. A return statement is always the last thing executed in the function.
Also, just to make sure, you are calling session_start() to actually start a session, right?
Comment: I had to double check (that's how new I am to this, haha!) but yes. I forgot to add it to the top. it starts with session_start(); before function logged_in(). I will delete the session_write_close() from those two lines and try that out. You guys are super helpful!
Answer: So, I took the advice of the nice people who recommended I remove the session_write_close() from sections of the code. Great advice!
However, that didn't solve my problem. My pages were still not loading when moving around the site and this was happening only sporadically.
Turns out I needed to set $_SESSION['last_activity'] = time(); in my login page. That solved the problem. Now my pages load consistently and quickly. Thank you all for the help!
Comment: Hey Mike, remember they only adviced you to remove that line of code just because it was being called after return so it was never being executed, php by defaults executes session_write_close() after a php script finish loading but if you are redirecting you should always use session_write_close() before redirect.
Comment: Thanks, Joe. I have actually started having problems with my password protected forum being spammed by spambots. I wonder if my sessions are being highjacked or something because I was missing the session_write_close() command? I have no idea how to stop them. I will post another question including my login script to see if anyone can point out security holes.
Comment: Try to add a captcha to effectively avoid robots spamming your site.

PHP Session Script Semi-Functional


How to reverse parse using rapidjson?

Question: for example, I have a class to parse from string to object:
Student.h
class Student{
public:
    inline std::string getName(){
        return this->name;
    }

    inline void setName(std::string name){
        this->name=name;
    }

    inline int getAge(){
        return this->age;
    }

    inline void setAge(int age){
        this->age=age;
    }

    void parse(rapidjson::Value& value);

    //std::string reverseParse();
protected:
    std::string name
    int age;
};

Student.cpp
void Student::parse(rapidjson::Value& value){
    if(value["name"].IsString()){
        this->name=value["name"].GetString();
    }
    if(value["age"].IsInt()){
        this->age=value["age"].GetInt();
    }
}

//std::string Student::reverseParse(){
//}

main.cpp
int main(){
    rapidjson::Document doc;
    doc.Parse<0>("{\"name\":\"abc\",\"age\":20}").HasParseError();

    Student student;
    student.parse(doc);
    printf("%s %d\n",student.getName().c_str(),stundent.getAge());

    student.setName("def");
    student.setAge(30);
    //printf("%s\n",student.reverseParse().c_str());
    return 0;
}

which call parse(doc) to fill the value from json string, and the output should be:
abc 20

,now I want to reverse the parse process, convert the object to json string, by changing the name to def and changing the age to 30,calling reverseParse() should return:
{"name":"def","age":30}

how to write reverseParse()?
Answer: There is a rapidjson tutorial here.
Your reverseParse() could look like this:
std::string reverseParse()
{
    rapidjson::Document doc;
    doc.SetObject();
    rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();

    doc.AddMember("name", this->name.c_str(), doc.GetAllocator());
    doc.AddMember("age", this->age, doc.GetAllocator());

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    doc.Accept(writer);

    return buffer.GetString();
}

How to reverse parse using rapidjson?


Unable to Search or Sort through Webform Submitted Data

Question: I created an exposed filter for my View that aggregates user-submitted webform data.  I was hoping this would allow them to search the View for specific webform entries.  Unfortunately, the View remains unsortable by column (although I checked the option to make every column sortable), and whenever I search via my exposed filter, it comes back with 0 results.
I've attached images of my Filter and View settings...  am I doing something wrong?
Thanks!
View Settings:

Filter Settings:

Table Settings:
Answer: Check your FORMAT -> Format: Table | Settings for a checkbox that says Override normal sorting if click sorting is used and turn it on if it is not already.
Comment: Hi Darvanen,  Thanks so much for your advice.  I checked, and that checkbox is checked.  I'll edit my post to show my Table Settings, too.  Any further advice would be greatly appreciated.  Thanks!
Comment: I wonder if the combined filter is interfering, maybe try removing that?
Comment: I thought that the exposed combined filter is what allowed the users to search?
Comment: Okay, interesting - I removed the filter, and yes, now the columns are sortable.  Now, how would I get search functionality, too...


React js component, map works, foreach doesn't

Question: I have a component that renders tags. It loops through a Map and displays the data. I tryed using forEach but it doesn't work. However it works if I convert the map to an array (foreach doesn't work on the array either). What am I missing here?
This works:
render(){
    return(

            {Array.from(this.props.tags.values()).map((tag,i) => (
                <Tag
                    handleKeyDown={this.handleKeyDown.bind(this)}
                    handleBlur={this.handleBlur.bind(this)}
                    handleTouchTap={this.handleTouchTap.bind(this)}
                    handleRequestDelete={this.handleRequestDelete.bind(this)}
                    tag={tag}
                    key={i}
                />
            ))}

    )
}

This doesn't:
render(){
    return(

            {this.props.tags.forEach((tag,i) => (
                <Tag
                    handleKeyDown={this.handleKeyDown.bind(this)}
                    handleBlur={this.handleBlur.bind(this)}
                    handleTouchTap={this.handleTouchTap.bind(this)}
                    handleRequestDelete={this.handleRequestDelete.bind(this)}
                    tag={tag}
                    key={i}
                />
            ))}

    )
}

Answer: Map#forEach doesn't return a new array. They both work exactly as you'd expect, which is for Array#map to build a new array mapped from the old one. React.createElement needs to take its children as an argument list, or as an array. Generally you want to think of your Map more like a plain Object than as an array, i.e. you convert it to an array if you want to manage its values separately.
Your Array.from use is a fine approach. This is how I'll typically use Maps. If you wanted to get really modern with it, and avoid one of the iterations (though I can only imagine that mattering at all for the most extreme of cases), you could always apply an iterator function to your Map's values, then spread on that iterator.
render() {
  const asTags = function* () {
    for (const [key, tag] of this.props.tags) {
      yield <Tag tag={tag} key={key} />;
    }
  };

  return (

      {[...asTags()]}

  );
}

The generator function is a simple iterator, which yields each of the entries it loops through in your Map. I only use the array in there because I'm not totally sure how to spread arguments inside a JSX (one reason I don't use JSX). If you had React.createElement imported as ce, you could simply say ce('div', { class: 'container' }, ...asTags()) in the render instead.
Comment: Thanks! Is there a better way of doing this other than converting the map to an array and useing map on that?
Comment: Sure @Gopid, I've updated the answer with an example using generators, which saves you having to iterate once to convert to an array, and lets you directly iterate and map the entries to your new format.


Use a variable defined from a custom form in a custom template

Question: I created a custom form, a custom template, and I "linked" both with a theme hook.
In the buildForm() method, I used the following code.
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#foo'] = array("key_a"=>"value_a", "key_b"=>"value_b", "key_c"=>"value_c");
  // …
  return $form;
}

From the template, when I show all the available variables with {{ dump() }} or {{ kint() }} I see #foo is present, but I cannot print its value.
I tried the following code, but either I get an error or NULL is printed.
{{ element.#foo }}
{{ element.'#foo' }}
{{ 'element.#foo' }}
{{ foo }}

How can I print that value?
Answer: Like javascript you need to use bracket notation to get hash key variables:
{{ element['#foo'].key_a }}


Instrument or line level for recording amplifier through headphone jack?

Question: I just got a digital combo amplifier and the only outputs it has are USB and a headphone jack. I am trying to record it by using a 3.5 mm to dual 1/4 inch adapter and plugging it into my interface. The USB out does not work well because I already have an audio interface.
My question is do I need to engage the Instrument level button on my interface?
I am not familiar with how line/inst level and things of that nature work. I read somewhere that impedance can affect sound quality. I want the best quality I can get although this isn't the optimal setup.
Hope this is not too confusing,
Thanks.
Comment: Be aware that recording the headphone output of a _digital combo amp_, especially one that has _only_ a headphone output, will likely not give you anywhere as good sound as what can nowadays be achieved with even free amp-sim plugins on the computer. So, I'd recommend just recording the dry guitar signal instead through the interface, and only wiring the amp as a _monitor_.
Answer: As you said, that's a story of impedance: in short instrument level is generally used when the signal is coming from a high impedance source (guitar pickups) and the line level for low impedance or preamplified sources (DI, electronic keyboard and so on). The main reason for these two levels is that a high impedance will have an hard time driving a low impedance input (you can have a look at impedance adaptation for instance) hence resulting in very low levels of sound, resulting in more noise with respect to the signal.
The headphone output is designed to drive headphones (hence the name) and headphones have usually fairly low impedance (ranging from a few ohms to a few hundreds). Furthermore, this is coming from an amplifier which surely can provide the current to drive a line input so..
TL:Dr
You can safely put it in the line input and this is how, in theory, you'll achieve the best sound.