Seeking alternative practical learning methods for piano if I only want to play for fun

Question: I see advertisements where I live for a course titled "Instant Piano for Hopelessly Busy People".  While I am sure the title is exaggerated to attract attention - it seems to imply that the student would be exposed to a learning method that could have them "playing" piano with far less time invested than the traditional weekly lessons for many years approach that is commonly used.
While I have no delusions that one could "instantly" learn much of anything, much less how to play piano, I am guessing that there is more than one approach to learning to play piano and that some may get a student up to speed faster than others.
Let us assume a person did not find it absolutely necessary to sight read music notation (unless it would help them learn faster or easier), but wanted to be able to play popular songs with both hands for their own enjoyment and to entertain their friends and family. Let's also assume some reasonable ability to maintain basic rhythm and general aptitude to learn music (not tone deaf and can hear the difference between a minor and major chord etc.).
What are some plausible alternative learning methods that could potentially have someone playing some basic popular songs on piano (or keyboard) within a matter of a few months while devoting somewhere between 10 - 20 hours per week?  What resources are available (in print or on line) for the methods you suggests?
Comment: Up to 20 hrs a week is about 3 hrs per day. That's a lot of practice time! I'd have thought with that amount, anyone would get pretty good, pretty soon. If there was a rapid way, the majority of teachers would be using it, I think. Apart from - we all learn in different ways (which is why schools don't work that well!!) - so one method won't work best for all. A shame, really...  The best way I found to get better on a new instrument was, apart from practice, playing on it with others, in public being the most productive.
Comment: That should be *teaching* four chords in my last comment. My point being I'm convinced that there are no shortcuts but the upside is if the only thing you have to do to improve every day is play every day. If you're doing it for fun, then that's like saying you just have to remember to have a little fun every day and you'll become great. Why would anyone want a shortcut that prevents them from having a little fun every day?
Comment: Practice five hours a day seems the easiest solution.
Comment: Those ads might be very much exaggerating. There's a Ted talk where a guy says you can learn anything more quickly. He "proves" this buy showing how he "learned to play ukelele" in like two months or something. Then he proceeds to play the exact same four chords over and over again for five minutes as if that demonstrates he has competence on the ukelele. Now imagine someone texting you just four chords in a single key on the piano and then saying "see? You're a great pianist already!"
Comment: @RockinCowboy I just want to be clear, I did not down vote because I don't have an answer or even because I don't think there is a good answer (it's true that I don't think there's a good answer, but that's not why i downvoted). I downvoted because I think the question is unhelpful, and I think it's unhelpful because it promotes the idea that there are ways to shortcut the learning process. I'm sure I don't have to remind you that I have a lot of respect for you, and my down vote isn't about you, it's just about the concept that the question is based on.
Comment: This question is for all those who wanted to answer the closed question about learning to play piano in a month (which I don't believe can be done).  I would also be interested in learning ways I might improve my own piano playing without taking too much time away from improving my guitar skills.
Comment: @ToddWilcox  I think I linked to that same Ted talk from an answer here on SE.  There may not be any shortcuts, but there is more than one way to skin a cat.  I know this for a fact (as it relates to learning to play an instrument).  And some ways will produce results faster than others.  I am hoping some of the folks who expressed an interest in answering this question (when it was posed in unclear way by Twonny) will weigh in with their ideas.  If they don't - I'll weigh in with some of mine.  I guarantee we will see some enlightening and interesting answers by the end of the day tomorrow.
Comment: Oh dear!  The old "I want to learn piano, but I'll tell you WHICH parts of it I want to learn" question!  Yes, I could probably coach you into learning some tricks.  The "Yamaha Music Schools" method, which is a sort of watered-down Suzuki method, specialises in this.  Perhaps there's one in your neighbourhood.
Comment: A person who wants to be able to play piano to entertain themselves and friends and family would probably get there faster by learning to read music than by learning to play by ear, in my experience. Whatever aspects of musicianship a person wants to learn, I have not found any substitute for practice in my 36 years of learning music, and there's no shortcut in practice. It's like farming. You have to sow in spring and tend all summer if you want to reap in the fall. Sorry Cowboy, -1.
Comment: @ToddWilcox Hey just cause you don't have an answer does not  mean you have to downvote the question!  Give me a break.     I am only asking it because there are folks in our community who want to answer it and I promise you there will be some answers.  I will edit the question to allow for an answer that suggests that learning to read music might accelerate the process.  I suppose it might be faster for some to learn that way.  I find it much easier to play by ear personally - but I know every one is different and not everyone can play by ear.
Comment: @ToddWilcox - but I do appreciate the explanation with the down vote.  Explanations sometimes illustrate the flaw in the question that can be edited to make it more easily understood or provide for more possible answers.
Comment: @ToddWilcox - I did not take your downvote personally. I think u are entitled to your opinion that alternate methods of learning  may not be the best way to learn in the long run.  But everyone's goals are different!  And there are obviously folks out there who's goal is to learn to "play" piano at some level of proficiency, without the traditional several year investment in the process. And to state that anything less than your preferred method shortcuts "THE" process implies that there is only ONE process.  I submit that there are other valid processes that address differing goals.
Comment: Hmmm ... I interpreted the question title to mean "how can I play at a faster tempo than by using the techniques from traditional (i.e. using technique stuck  in a time warp at the end of the 18th century) teaching methods". Oh well, never mind .... next question please...
Comment: @alephzero - hey thanks for the input on the potential confusion caused by question heading.  I edited to make it more clear.
Answer: Really, the answer to this is entirely dependent on the individual.  However, I'm getting that you have the ability already to play guitar fairly well by ear.  You can probably hear a melody and put a few chords together for it, and you know most of your basic guitar chords.  That's a good place to start.
If I were your teacher, I would strongly suggest that you learn to read music halfway decently if you can't already (because yes, it will help you learn faster and easier).  Once you get a working knowledge of notes, you can begin leveraging your guitar skills by working on your own arrangements, picking up fake books, and the like.  Reading notes is a skill that will expose you to a whole lot of new musical ideas, just as literacy exposes you to a whole lot of general ideas.  Sure, it's easier to play by ear than to read music, but it's easier to learn to understand speech than to learn how to read as well.  Musical literacy has analogous benefits to "book learning."
If you'd like to look into this further, I like Alfred's Adult All-In-One Course.  (Here's a link to a pdf someone uploaded, although I would suggest that you buy the book and do all the theory exercises.)  You can blow through the first 30 pages quickly, probably in a couple or three days.  Make your goal to be to play all those silly songs perfectly (don't obsess over the stuff about how to sit and how to hold your hands; those are good basic ideas but there are all sorts of other opinions on this stuff).  As you improve your play, you'll find more interesting material to work on.  (If you blow through the entire book, you'll probably find that your $10 or so investment gets you to at least the place that that $75 investment for "Instant Piano etc." would get you.  And there are several more books, if you like the approach enough.)
You'll notice that all the songs are spelled out.  You need to be able to play as written, but you will find it interesting to work out your own arrangements of the music.  By the time you get to book 2 (or perhaps before), the chords are written over the music, and you should see a song or two that you can play that is sufficiently interesting to get you thinking about how you can change the voicings of the chords and experimenting with altering the harmony.  Once you get to that point, I think you'll be where you want to be.
What's nice about all that is that you'll find that your guitar playing improves along with it.  The piano is like a map; every note looks the same for each octave.  For example, on the guitar, if you want to play the lowest B it's the first fret on the A string.  An octave higher, and it's the fourth fret on the G string.  On the piano, every B is the note immediately to the right of three black keys (and conversely, every note to the right of three black keys is a B).  So, it's much easier to figure out how to play a chord on the piano, without having to resort to learning it by rote as you generally do on the guitar.  As you do that, you'll get a clearer picture of why you play the notes you do on a guitar chord, and this will allow you to invent alterations in your chord voicings on the guitar as well.
Comment: @ToddWilcox Well, that's true, and I didn't mean to suggest otherwise, so perhaps I overstated.  However, there is a good deal of variation in what will not injure and what is foundational for basic technique.  A lot of very fine pianists don't curve their fingers more than sometimes: https://www.youtube.com/watch?v=ZK6DxupkUPQ .  Some lean forward towards the piano, some sit straighter.  Compare Rubinstein with Horowitz for an obvious example.  But, in defense of your point of view, neither of them slouch.  Perhaps I should have said to take those pictures with a big grain of salt.
Comment: As a person who has suffered from a repetitive motion injury because of poor technique, I have to mention my disagreement about downplaying "the stuff about how to sit and how to hold your hands". Not only are posture and body geometry important for preventing injury, they also are foundational for being able to execute even basic techniques.
Comment: I like your comments on how learning to play keys better may foster a deeper understanding of guitar music.
Comment: @RockinCowboy When I was a music major in college, all the majors had to get a certain proficiency on the piano as part of their degree requirement.
Comment: @BobRodes  I can see how that would be a great idea for music majors.  My question is more about folks who are interested in recreational music for enjoyment and may not be as dedicated as a music major.
Comment: @RockinCowboy Sure, but the reason it's a great idea for music majors is the same reason that it's useful for any musician.
Comment: @BobRodes  Agreed that learning piano will help with overall musicianship.  That's why your answer got my upvote on March 7th.
Comment: Good luck!  Post back when you have questions.
Answer: I would check out the music courses on udemy.com, especially by Rosa Suen.
There are basically two types of music lessons -- one is for classic music which is what many piano teacher teach, but the other is to play by ear.  Rosa teaches you how to take a "fun melody" and how to harmonize it on the left hand.
Most popular music sheet music shows the melody and gives the chords for the left hand.  She has a bunch of lessons on how to harmonize the melody with both basic and fancy chords, etc.
The electric pianos give you some great rhythms  to go with the melodies, and some will even play the chords as well.
Answer: Playing piano quickly depends on what you want to play and why you require it to be quick, I think. :-)
If you want the feeling of your hands moving up and down the piano, lots of scales might get you there quickly.
If you want to learn specific classical piano pieces, there are many altered scores for beginner pianists that are simpler than the originals and therefore faster to learn.
If you want to learn jazz or blues quickly, your route to playing could be completely different, as different as playing chords on guitar for rock music vs finger picking and reading individual notes. I think you could learn chord recognition quite well without reading music and that would shorten your time.
If you want to learn pop music quickly, the rhythms can be surprisingly difficult to replicate and you'd need simplified versions which probably wouldn't feel like they did the songs justice.
All in all it just depends what direction you want to take and then we could help you with a more detailed approach. :)
Answer: You can probably go with the piano teacher through the key sequence of the particular song and learn which keys to press. Then the teacher could play the melody to you and you would get an impression on the note duration.
This allows to skip all music theory.
From experience, it is not difficult to learn to play a few pieces this way (as long as they are not very long and the fingering is not difficult). The problem is, if you do not play daily, you may easily forget one or another key you need to press - and your capability to play that whole piece is gone.
Answer: Right hand plays random notes in Blues escale in c:
https://www.google.fr/search?num=100&safe=off&espv=2&q=blues+piano+scale+in+c&oq=blues+piano+scale+in+c&gs_l=serp.3..0i22i30l4.146.1183.0.1322.214.171.124.0.0.0.162.523.0j4.4.0....0...1c.1.64.serp..2.4.521...0i67.WglvX6UOkDM
Left hand plays C mayor chord, F mayor chord and G mayor chord.
Enjoy!


How can I use a Gamma Random Variable to Aproach the Expected value of a exponential random variable function?

Question: I´m working on trying to approach the value of $E\left[ \dfrac{e^x}{x+1} \right]$. Where $x$ is an exponential random variable. All that data I have to work with is a gamma random variable with parameters $3/2$ and $1$. I also know that $x$ has mean $1$.
I think that I could get some relations by knowing that if I sum k exponential random variables I would get a gamma random variable. But I´m a bit confused on how I could apply this to the computation of the Expected Value. Can anyone suggest any valid process to compute the above value using the fact that I know the Gamma Random Variable??
EDIT:
POSSIBLE ANSWER:
I have received several comments about the divergence of the integral, however I think I can use this estimator to approach the value:

Where $T$ is the expected value of the gamma random variable and $Si$ the i-th value generated by the gamma distribution
Thank you
Answer: I'm not sure whether you mean  $E\left[ \dfrac{e^x}{x+1} \right]$ or $E\left[ \dfrac{e^x}{x} + 1\right]$.  But neither of these exists (the improper integrals diverge).  Your gamma random variable is irrelevant to this question.
Comment: No!!!  You can **not** use simulation or any other method to "approximate" something that does not exist.
Comment: The density for an exponential random variable of mean $1$ is $\exp(-t)$.  So
$$ E\left[\dfrac{e^x}{x+1}\right] = \int_0^\infty \dfrac{e^t}{t+1} e^{-t}\; dt = \int_0^\infty \dfrac{dt}{t+1} = \infty$$
Comment: Now, the divergence is rather slow, so in a simulation it may not be very easy to see that it diverges, but nevertheless it really does diverge.
Comment: You've **repeatedly** been told that the expectation is infinite, and despite this, you somehow continue to insist on "simulating" something.  You refused to believe you are wrong and had to have it **proven** to you.  I don't think any further assistance on your questions is justified because you have demonstrated incredibly obstinate behavior.
Comment: I´ve edited the question to correct the expression. Thanks for your answer, I don´t think the expected value does not exist for both since you can approximate it with simulation or other methods. My question is about how  can  I use this Gamma 'black box' to approximate the expression, even though they diverge. Thanks for your help
Comment: I think it does exist, since x is an exponential random variable with mean 1. But maybe I´m not being able to see something that you do.
Comment: Thanks for your answer. So then it is possible to simulate it using the gamma variable? If that´s true what´s the best way to proceed?
Comment: Hello I´m not being obstinate. I do understand what Robert said, but there must be another way around then. I´m reading a simulation book and got interested by this particular exercise I don´t think a simulation book has exercises with no solutions.
Comment: This would not be the first time a textbook exercise had a mistake.  Maybe try writing to the author?
Comment: Ok thank you very much. I´m sorry if I was obstinate, I was just trying to get an appropriate answer. Thanks for your time and knowledge


The maximum domain of the function $f(x)=\log_2(\log_3(\log_2(\log_3(\log_2x))))$ is?

Question: I do know how to find domain for most of the functions I find but this one's a bit off. A step-by-step response would be appreciated.
$$f(x)=\log_2(\log_3(\log_2(\log_3(\log_2x))))$$
Thanks in advance!
Comment: MathJax hint:  if you put a backslash before common functions you get the proper font and spacing, so \log_2 x gives $\log_2 x$ as contrasted with log_2 x giving $log_2 x$  It is better to make sure the body of the question has the whole question in it, rather than relying on the title.
Answer: Using the fact $\log_bx>a\iff x>b^a$ (when $b>1$) we can reason as follows:
$$\begin{array}{ll} &  \log_2\log_3\log_2\log_3\log_2 x \quad \textrm{exists} \\ \iff & \phantom{\log_2}\log_3\log_2\log_3\log_2x>0 \\ \iff & \phantom{\log_2\log_3}\log_2\log_3\log_2x>3^0=1 \\ \iff & \phantom{\log_2\log_3\log_2}\log_3\log_2 x>2^1=2 \\ \iff & \phantom{\log_2\log_3\log_2\log_3}\log_2 x>3^2=9 \\ \iff &  \phantom{\log_2\log_3\log_2\log_3\log_2}x>2^9=512. \end{array} $$
Comment: Well done. Would be better if the fact is supported by $b>1$.
Answer: Clearly you have no trouble if $x$ is very large, so you are just trying to find the minimum value of $x$ that makes sense.  The problem comes if the argument of the outer $\log_2$ is negative or zero.  What is the minimum argument of the first $\log 3$ to avoid that?  Keep going in layer by layer to find the minimum value of $x$.
Comment: Minor nitpick: the problem is if the argument is *nonpositive*, not just negative.
Comment: @Ian:  Good point.  I have updated the answer.  Thanks.
Answer: You can make changes:
$$x=2^a \Rightarrow \log_2 x = a$$
$$a=3^b \Rightarrow \log_3 a = b$$
$$b=2^c \Rightarrow \log_2 b = c$$
$$c=3^d \Rightarrow \log_3 c = d$$
$$d>0 \Rightarrow c>1 \Rightarrow b>2 \Rightarrow a>3^2=9 \Rightarrow x>2^9.$$


XGBoost4J - Scala dataframe to sparse dmatrix

Question: What is the most efficient and scalable way to convert a scala dataframe to a sparse dmatrix for XGBoost4J?
Say I have a dataframe train with columns row_index, column_index, and value, it would be something like
new DMatrix(train.select("row_index"), train.select("column_index"), train.select("Value"), DMatrix.SparseType.CSR, n_col)

However the above code results in a type mismatch because DMatrix expects Array[Long].
train.select(F.collect_list("row_index")).first().getList[Long](0) seems like a possible option but it doesn't seem to be memory friendly and scalable.
I am doing this on Databricks so solutions in the other supported languages (python, SQL, scala) are welcome.
Comment: have you looked into docs: https://docs.databricks.com/applications/machine-learning/train-model/xgboost.html ?
Comment: @AlexOtt Yes I have. All of the examples use data in wide format. My data is in long format, and since it's highly sparse, I'm trying to avoid pivoting to wide format
Answer: The answer was to use sparse vectors by row rather than trying to create sparse matrix or dmatrix.
train.rdd.map(r => (r.getInt(0), (r.getInt(1), r.getInt(2).toDouble))).groupByKey().map(r => (r._1, Vectors.sparse(n_col, r._2.toSeq))).toDF
I tested scoring a sample of the data in R using Matrix::sparseMatrix and xgboost::dmatrix and the results matched up.


Can one explicitly solve the shifted harmonic oscillator

Question: The quantum harmonic oscillator is described by a Hamiltonian
$$H=-\Delta + \left\lvert x \right\rvert^2.$$
By decomposing the eigenvalue problem $H\psi= E\psi$ into its angular and radial part one obtains essentially the ODE
$$-\varphi''(r) + \frac{2}{r} \varphi'(r) + \frac{l(l+1)}{r^2} \varphi(r)+r^2\varphi(r)=E\varphi(r).$$
Please let me know if you have any questions.
This ODE can be solved explicitly, i.e. one obtains the usual eigenfunctions and eigenvalues
I wonder whether one can also solve the shifted version
$$-\varphi''(r) + \frac{2}{r} \varphi'(r) + \frac{l(l+1)}{r^2} \varphi(r)+(r-r_0)^2\varphi(r)=E\varphi(r)$$
for some $r_0>0.$
It does not seem possible to map this one immediately back to the original one that's why I am asking.
Please let me know if you have questions or remarks.
Comment: I bet this has some kind of hypergeometric solution though, perhaps in terms of https://en.wikipedia.org/wiki/Heun_function
Comment: You might also want to ask this at Physics.SE, as I'm sure this problem has been considered mostly in Quantum Mechanics
Answer: Hint:
$-\varphi''(r)+\dfrac{2}{r}\varphi'(r)+\dfrac{l(l+1)}{r^2}\varphi(r)+(r-r_0)^2\varphi(r)=E\varphi(r)$
$\dfrac{d^2\varphi}{dr^2}-\dfrac{2}{r}\dfrac{d\varphi}{dr}-\left(r^2-2r_0r+r_0^2-E+\dfrac{l(l+1)}{r^2}\right)\varphi=0$
Let $\varphi=e^{\pm\frac{r^2}{2}}u$ ,
Then $\dfrac{d\varphi}{dr}=e^{\pm\frac{r^2}{2}}\dfrac{du}{dr}\pm re^{\pm\frac{r^2}{2}}u$
$\dfrac{d^2\varphi}{dr^2}=e^{\pm\frac{r^2}{2}}\dfrac{d^2u}{dr^2}\pm re^{\pm\frac{r^2}{2}}\dfrac{du}{dr}\pm re^{\pm\frac{r^2}{2}}\dfrac{du}{dr}+(r^2\pm1)e^{\pm\frac{r^2}{2}}u=e^{\pm\frac{r^2}{2}}\dfrac{d^2u}{dr^2}\pm2re^{\pm\frac{r^2}{2}}\dfrac{du}{dr}+(r^2\pm1)e^{\pm\frac{r^2}{2}}u$
$\therefore e^{\pm\frac{r^2}{2}}\dfrac{d^2u}{dr^2}\pm2re^{\pm\frac{r^2}{2}}\dfrac{du}{dr}+(r^2\pm1)e^{\pm\frac{r^2}{2}}u-\dfrac{2}{r}\left(e^{\pm\frac{r^2}{2}}\dfrac{du}{dr}\pm re^{\pm\frac{r^2}{2}}u\right)-\left(r^2-2r_0r+r_0^2-E+\dfrac{l(l+1)}{r^2}\right)e^{\pm\frac{r^2}{2}}u=0$
$\dfrac{d^2u}{dr^2}+2\left(\pm r-\dfrac{1}{r}\right)\dfrac{du}{dr}+\left(2r_0r-r_0^2+E\mp1-\dfrac{l(l+1)}{r^2}\right)u=0$
Let $u=e^{\mp r_0r}v$ ,
Then $\dfrac{du}{dr}=e^{\mp r_0r}\dfrac{dv}{dr}\mp r_0e^{\mp r_0r}v$
$\dfrac{d^2u}{dr^2}=e^{\mp r_0r}\dfrac{d^2v}{dr^2}\mp r_0e^{\mp r_0r}\dfrac{dv}{dr}\mp r_0e^{\mp r_0r}\dfrac{dv}{dr}+r_0^2e^{\mp r_0r}v=e^{\mp r_0r}\dfrac{d^2v}{dr^2}\mp 2r_0e^{\mp r_0r}\dfrac{dv}{dr}+r_0^2e^{\mp r_0r}v$
$\therefore e^{\mp r_0r}\dfrac{d^2v}{dr^2}\mp 2r_0e^{\mp r_0r}\dfrac{dv}{dr}+r_0^2e^{\mp r_0r}v+2\left(\pm r-\dfrac{1}{r}\right)\left(e^{\mp r_0r}\dfrac{dv}{dr}\mp r_0e^{\mp r_0r}v\right)+\left(2r_0r-r_0^2+E\mp1-\dfrac{l(l+1)}{r^2}\right)e^{\mp r_0r}v=0$
$\dfrac{d^2v}{dr^2}\pm2\left(r-r_0\mp\dfrac{1}{r}\right)\dfrac{dv}{dr}+\left(E\mp1\pm\dfrac{2r_0}{r}-\dfrac{l(l+1)}{r^2}\right)v=0$
Let $v=r^kw$ ,
Then $\dfrac{dv}{dr}=r^k\dfrac{dw}{dr}+kr^{k-1}w$
$\dfrac{d^2v}{dr^2}=r^k\dfrac{d^2w}{dr^2}+kr^{k-1}\dfrac{dw}{dr}+kr^{k-1}\dfrac{dw}{dr}+k(k-1)r^{k-2}w=r^k\dfrac{d^2w}{dr^2}+2kr^{k-1}\dfrac{dw}{dr}+k(k-1)r^{k-2}w$
$\therefore r^k\dfrac{d^2w}{dr^2}+2kr^{k-1}\dfrac{dw}{dr}+k(k-1)r^{k-2}w\pm2\left(r-r_0\mp\dfrac{1}{r}\right)\left(r^k\dfrac{dw}{dr}+kr^{k-1}w\right)+\left(E\mp1\pm\dfrac{2r_0}{r}-\dfrac{l(l+1)}{r^2}\right)r^kw=0$
$\dfrac{d^2w}{dr^2}\pm2\left(r-r_0\mp\dfrac{k-1}{r}\right)\dfrac{dw}{dr}+\left(E\pm2k\mp1\mp\dfrac{2r_0(k-1)}{r}+\dfrac{k(k-3)-l(l+1)}{r^2}\right)w=0$
Which can converts to Heun's Biconfluent Equation similar to Hunt for exact solutions of second order ordinary differential equations with varying coefficients.


Como criar um sistema para listar as imagens mais populares do meu aplicativo

Question: Estou querendo montar um sistema para exibir as imagens mais populares do meu aplicativo.
Hoje eu listo essas imagens de forma simples mas eficiente: as pastas se tornam categorias e listo as imagens de dentro da pasta. Então, o aplicativo lê o link da imagem como url do servidor + categoria + nome da imagem.
Para montar um sistema de popularidade eu pensei em contar quantas vezes alguém clicou no botão de compartilhar e enviar essas informações para um banco MySQL junto da categoria e do nome da imagem. Assim quando eu fazer a listagem em PHP eu posso ordená-las por numero de compartilhamentos.
Alguém pode me ajudar a como fazer isso? Sabem de um projeto open source que tem algo parecido para tentar aprender?
Comment: Você precisa criar um `webservice`, ao clicar em compartilhar, o aplicativo deve enviar o nome(unico) ou `hash` da foto(ou algum identificador unico) para o `webservice` salvar no bd  `mysql` do servidor. No bd precisa ter uma tabela que contém a identificação da foto, categoria e a qtd de compartilhamento.
Answer: Pensei no seguinte:
Você cria uma tabela compartilhamento, relacionando imagem e usuario. A tabela compartilhamento seria única nas colunas imagem_id e usuario_id, fazendo com que nenhum usuário possa compartilhar a imagem mais de uma vez.
A query para buscar as imagens mais compartilhadas seria algo assim:
SELECT nome, count(id) compartilhamentos
FROM imagem
GROUP BY nome
ORDER BY compartilhamentos DESC;

Em seguida você pode criar um serviço para buscar as imagens mais compartilhadas. A URL desse serviço pode ser algo bem auto-explicativo, algo como:
GET /imagens/compartilhadas

E a resposta pode ser um XML ou um JSON contendo o resultado da consulta em SQL:
[
    {
        "nome": "imagem1.jpg",
        "compartilhamentos": 472
    },
    {
        "nome": "imagem4.jpg",
        "compartilhamentos": 298
    },
    {
        "nome": "imagem5.jpg",
        "compartilhamentos": 112
    },
    {
        "nome": "imagem3.jpg",
        "compartilhamentos": 55
    },
    {
        "nome": "imagem6.jpg",
        "compartilhamentos": 37
    },
    {
        "nome": "imagem2.jpg",
        "compartilhamentos": 14
    }
]

PS: dependendo do caso a implementação provavelmente será mais complexa, mas ideia básica é mais ou menos o que foi dito acima.
Comment: Só faltou um `ORDER BY` e um `LIMIT` para pegar as mais compartilhadas :)
Comment: @Lucas bem notado! Coloquei o `ORDER BY` mas o `LIMIT` varia bastante de acordo com a implementação :)


Change node configuration dashboard UI settings

Question: While creating a node content Drupal 8 provides the following settings.

I want the URL path setting tab to be open by default.
I want to achieve it through the Drupal 8 backend customization settings (more preferable) or even Javascript/jQuery.
Comment: Notice that you are simply stating facts, without asking any explicit question.
Comment: @kiamlaluno I have mentioned I want the URL path setting tab to be open by default.
Comment: You didn't said what exactly is your problem, what you don't understand, and what you tried. "I want" is a request, not a question.
Answer: You can't do this in the UI, you need code.
You could attach some JS to open it, but it's much easier to create a module with a form_alter and then you can make the element expanded by default.
https://api.drupal.org/api/drupal/core%21modules%21path%21path.module/function/path_form_node_form_alter/8.2.x defines the element, you can see that it defaults to open when there is an alias already.


Solving a linear system of the form C .* (BX) = AX

Question: I have formed the above problem, which involves a mix between element-wise (Hadamard) multiplication (indicated by ".*") and ordinary matrix multiplication. In this problem I know all of A, B and C but I still have no idea how to solve for X.
Dimensions, if this helps:

A = N x N (sparse)
B = N x N (sparse)
C = N x 1 (not sparse)
X = N x 1 (not sparse)

The sparse matrices above are populated only with either 0 (of course), +1, or -1.
Alternatively, the problem can also be stated in the form:
log(C) + log(BX) = log(AX)
In a simpler form of the problem, A and B were so sparse that they had only one entry (+1) per row. I found (clumsily) that I was able to go like this:
log(C) + B * log(X) = A * log(X)
... which is easy enough to solve, and gave the correct solution (I am just doing some modelling, so can check against whatever X I use). However, in the "real" problem, my clumsy attempt to pull A and B outside the log operator does not work out.
Does anyone have any ideas on how I can go about solving this problem? It seems I need either

Some fancy method to combine Hadamard and ordinary matrix multiplication
Some fancy method to express the logarithm of ordinary matrix multiplication
Something else I have no idea about (likely)

Many thanks in advance!
Answer: The Hadamard product of two vectors is the same as the matrix product of one vector with the diagonal matrix of the other vector. Namely
$$
C.*(BX) = D_CBX
$$
where
$$
D_C = \begin{bmatrix}
c_1&0&\dots&0\\
0&c_2&&\vdots\\
\vdots&&\ddots&0\\
0&\dots&0&c_N
\end{bmatrix}
$$
Then the equation reduces to
$$(D_CB-A)X = 0$$
Comment: Thanks for this, exactly what I needed. Now, I just have to figure out how to pull a useful solution out of the null space...


Comparing strings inside of two objects

Question: I've been trying to compare the string inside of the Card() object with the other Card() objects to check for duplicates when the playing cards are dealt.
Except when printing out the compare statement i'm getting something like Card@97sd829. I made my own Equals() method for comparison of the object Card() inside of the Class but still to no avail.
I've tried using the override of the equals() object but I'm getting an error saying it needs to be inside of a superclass?
public static boolean Equals(Card a, Card b) {
    String str1 = a.toString();
    String str2 = b.toString();
    if (str1.equals(str2))
        return true;
    else
        return false;
}
public static boolean checkDuplicate (Card a, Card b, Card c, Card d, Card e){
    int num = 5;
    boolean bool = true;
    if (Card.Equals(a, b)||Card.Equals(a, c)||Card.Equals(a, d)||Card.Equals(a, e)||
    Card.Equals(b, c)||Card.Equals(b, d)||Card.Equals(b, e)||Card.Equals(c, d)||
    Card.Equals(c, e)||Card.Equals(d, e)); num--;
    if (num == 5)
        bool = false;
    else
        bool = true;
    return bool;
}

Answer: You are using the toString() method of the Object.class to get a String representation of your cards.
The default implementation of toString() contains the hash of the object. Since you have two different Card-objects the toString() method of these objects produces different output.
A better way would be to implement equals() in the Card class. Then you could check for equality with a.equals(b).
If you want advice how to implement Card.equals() you should post the source code of the Card class.

Comparing strings inside of two objects


Is this version of the Hanoi towers problem NP-complete?

Question: This was really inspired by Solitaire, but a few people reacted with ``oh, it's like the towers of Hanoi, isn't it?'' so I'll try to pose the problem in terms of discs here.
Let's start. There are n disks on the real line, one of size 1 at position $x_1$, one of size 2 at position $x_2$, ..., and one of size n at position $x_n$. Your goal is to make a tower with all n discs, consuming as little energy as possible in the process. You are allowed to move a tower whose base is a disk of size k only on top of the disk with size k+1 (which may be the top of another mini-tower). The energy you consume to perform such a move is the distance traveled by the moved mini-tower. For example, the energy consumed by the first move is $|x_k-x_{k+1}|$.
Now, you'd like to write a program that tells you whether the energy you have is enough to perform the task. It just needs to say Y or N. (If the answer is Y, then clearly the list of moves is proof enough that the answer is correct, so the problem is NP. If the answer is N, there's no point in even attempting the task---you are too tired.)
What's the fastest such program you can find? Is the problem NP-complete? If it helps, consider a simplifications that restrict $x_k$'s to be rational, integers, integers in a certain range, etc.
Here's an upper bound: $O(n2^n)$. Represent the initial state by the list $x_1$, $x_2$ ,... ,$x_n$. A move affects the state by deleting a number in this list and the energy consumed by the move is the absolute difference between the deleted number and the number coming after. Clearly there are $2^n$ states with at most $n$ moves each. (See my blog post for an example run of this algorithm if it's not clear. The description there is in terms of cards.)
Note: Some of the comments below refer to older versions of the questions. See the history of edits if they seem confusing.
Comment: The way you have the question stated now, the solution is always to place 1 on top of 2, 2 on top of 3, 3 on top of 4, etc., which I doubt is what you intended.  Are the discs meant to be placed in a random order, or are the "distances" arbitrary (meaning they're not really in a line?), or is moving a tower with more rings supposed to take more energy?
Comment: The distances are integers. Equivalently, the discs always have integer coordinates along this line. Equivalently, there is an infinite line of empty boxes all of the same size.
Comment: Start with 1,3,2. Your solution uses 3 units of energy, while it's clearly possible to use only 2: move 2 on top of 3, then move 1 on top of 2.
Comment: Oh, now I see what was troubling you. I edited the question.
Comment: "n=3, the one with size 1 might be at position 1000" ???? If n = 3, doesn't that limit positions to 1, 2, and 3? Are there two constants here? (# disks, # of positions) If so, give them separate names.
Comment: By "line" I mean http://upload.wikimedia.org/wikipedia/commons/7/76/Lineline.jpg extended infinitely to left and right. The disks stay on that at some positions/coordinates. I restricted the *differences* to be integers just for simplicity. Drop the restriction if it's less confusing: Then you could put a disk at e and one at $\pi$. Is it more clear now?
Comment: I think the point is, the positions must matter somehow, if only in the most trivial way: if all positions are in the range [-M, M], then the running time of any algorithm (and the input size) depends on log(M).
Comment: @SheervatsaR: Such a solution would be interesting, but it wouldn't qualify as a polynomial time solution for the problem I posed.
Answer: Here's a polynomial time solution given to me by Javi Gomez. Let (i,j) with $i\le j$ represent the situation where disks i, i+1, ..., j are on top of each other in position $x_j$, and let E(i,j) represent the energy needed to obtain that configuration. Clearly E(i,i) is zero for all i. Also, $E(i,j)=\min_k E(i,k)+E(k+1,j)+|x_k-x_j|$. What we want is E(1,n).
(I made this a community wiki since the answer wasn't really found by me. Feel free to edit.)
Answer: You said that "If the answer is Y, then clearly the list of moves is proof enough that the answer is correct, so the problem is NP".
My question is, can you enumerate the list of moves in polynomial time on a nondeterministic TM ? I would say no. Actually, to enumerate all the moves, you require exponential space, regardless of the type of approach you use: deterministic or nondeterministic.
Therefore, your problem is not in NP.
Comment: You can never move a disk more than once, so the length of the certificate is $O(n)$. Taking into account the other answer, the problem is actually in P, not only in NP.


Rules condition: check for a product with particular value for a field in the cart

Question: I have to aplly a custom fee if in the cart there's a product with a certain value for a field (producs with particular kind of battery). I use Commerce fees for applying the fee.
Every time the cart is updated I have to check: if there is at least one of those products the fee is applyed; if there's not (or there's not anymore) I have to not apply or remove the fee.
Removing a fee is a problem, as the module doesn't allow this.
But the bigger problem is whith rules: in conditions I can look for a particular SKU (only one) or a particular content type; instead I have to check something like this: "if there's in cart at least one product whith the value 1 for the field_battery,..."
Field_battery is a boolean field thath allow to the store's owner to flag products whith particulr battery, that require the extra fee.
I'm trying with the event "After updating an existing ordine commerce" btu I need help for conditions...
Thanks.
Answer: Not sure if this is the best way, but its the only way I can think of to do it.
You can do this by adding 3 different rules as well as adding a new field to "order" at admin/commerce/config/order/fields. We will call the field "Apply Fee" (apply_fee) and it is of the field type "integer"
Rule # 1,
Event: when product added to cart
Condition: Entity has field: Entity=order Field=Apply_Fee
Action: Set Data Value: (use the data selecter to slect the "apply_fee" field) add offset "1"
Rule # 2,
Event: when product removed from cart
Condition: Entity has field: Entity=order Field=Apply_Fee
Action: Set Data Value: (use the data selecter to slect the "apply_fee" field) add offset "-1"
Rule # 3,
Event: Apply fee to order
Condition: Entity has field: Entity=order Field=Apply Fee
Condition: Data Comparison: order's field Apply Fee is Greater than 0
Action: Apply a Fee to order
Answer: You can have a Rule that looks for a SKU, a partial SKU or a Product Type using the module Commerce Rules Extra.


What is the functional description of the I-III-VI(7) progression?

Question: How do you functionally describe the I-III-VI(7) progression, when used as a substitute for I-V-vi?
The bridge goes ii-V / I-V-vi / in the first two lines, then ii-V / I-III-VI(7),
resolving to ii-V-I.
I almost feels like a temporary excursion into ii minor or a modal variation, but I'm sure there's a clearer way to explain it.
Comment: Meaning, all major, including VI as a Major 7th chord?
Answer: I think this is the chart...

| ii V | I  V  vi  |
| ii V | I III VI7 |
| ii V | I

...I'm not exactly sure of your barlines.
The part I V vi can be called a deceptive progression.
The part I-III-VI(7) I think you mean in F major the chord would be F A D7
Functionally I think you could just say I V/vi V7/ii. After the tonic chord it's like the beginning of a circle of fifths of dominants. Roots descending by 5th to ii. So then the chart could be analyzed like this...

| ii V | I   V    vi  |
| ii V | I V/vi V7/ii |
| ii V | I

In F major the named chords are...

| Gm C | F C Dm |
| Gm C | F A D7 |
| Gm C | F

The last five chords are a long segment of the circle of fifths.
We can list out just the roots with Roman numerals and letters...

F    Bb   E    A    D    G    C    F
I    IV   viio iii  vi   ii   V    I

The diatonic chord qualities are...

F    Bb   Edim Am   Dm   Gm   C    F
I    IV   viio iii  vi   ii   V    I

Excepting IV and viio it totally fine to modify the other chord to become either major triads or dominant seventh chords as long as the function as secondary dominants. I put the sevenths in parenthesis to show it is optional without changing the functional harmony. I also used both kinds of Roman numerals...

F      Bb     Edim   A(7)   D(7)   G(7)   C(7)   F
I      IV     viio   V/vi   V/ii   V/V    V      I
I      IV     viio   III(7) VI(7)  II(7)  V(7)   I

...you can use other combinations of minor chords versus major/dominant sevenths in that part of the circle of fifths from iii to I. The important thing is the roots descending by perfect fifths.
So, the final part of your piece plays the full circle of fifths using  a few secondary domiants but omitting the IV and viio chords.
Comment: Ha, I should have provided a key. I'm playing it in F, and transposing your comment!
Comment: The song is in F. The bridge starts on Gm:

Gm  C
F      C Dm
Gm  C
F A D7
Gm  C
F
Comment: sorry, the line breaks didn't hold in that comment
Comment: Gm C /  F         C Dm /
Gm  C /
F A D7  /
Gm  C  /
F
Comment: @PaulF, I made an edit re. key of F and with the bridge parts. If my bar lines are problematic can you edit your answer to give the exact bars?
Comment: I understand the deceptive progression, yes. And you got the bar lines right, and the chords in F. What confuses me is my misunderstanding of the descending circle of fifths.  A is the dominant of D, which is Dm, vi, in F. D7 is the dominant of G, which is Gm, ii, in F. They both look ascending to me. Can you tell me what we are descending from?
Comment: This part... `A D7 / Gm C / F` ...you are descending chord roots from `A` to `F` by desc. 5ths. I made another edit stepping through the diatonic and chromatic possibilities on those roots.


I conjecture that there are infinitely many linear relations $p_n + p_{n + 3} = 2 p_{n + 2}$ in the sequence of primes!

Question: Let $p_1 < p_2 < p_3 < \ldots < p_n < \ldots$ be the sequence of primes (with $p_1 := 2$ as usual).
Conjecture: There are infinitely many positive integers $n$ for which
\begin{eqnarray}
p_n + p_{n + 3} = 2 p_{n + 2}.
\end{eqnarray}
Or equivalently,
There are infinitely many quadruplets of consecutive primes of the form
 $$(p, q, p + h,  p + 2h)$$
Comment: Sounds like an unsolved problem to me.
Comment: No.${}{}{}{}{}$
Comment: Mathematicians generally don't make conjectures unless they have a strong reason for believing a statement to be true. Why do you think there are infinitely many such triples?
Comment: @GerryMyerson: Well, my intuition tells me so :). OK, jokes aside. We know there are arbitrarily long polynomial progressions of primes (Tao-Ziegler http://arxiv.org/pdf/math/0610050v2.pdf). I think this should be true too with the added restriction that the primes be consecutive (But I'm unable to prove it).  This would prove the conjecture I stated. Is this "reason" strong enough ? :)
Comment: OK, well a problem is a problem; you can dispose of it or solve it. I don't see the contribution of this discussion to the problem at hand...
Comment: Now posted to MO, with no notice to either site. http://mathoverflow.net/questions/218450/i-conjecture-that-there-are-infinitely-many-linear-relations-p-n-p-n-3
Answer: On standard conjectures in Number Theory, there are infinitely many $p$ such that $p\equiv6\bmod7$, and $p$, $p+2$, $p+6$, and $p+12$ are all prime. The congruence guarantees that the four primes are consecutive primes. Then $p_n=p$ gives a solution to the equation in the question.
The standard conjectures are probably not going to be proved any time soon.
[Note: the idea of using $p$, $p+2$, $p+6$, and $p+12$ came from a poster on MO.]
Comment: Nice. You have my upvote. BTW, the referenced MO post is here http://mathoverflow.net/questions/218450/i-conjecture-that-there-are-infinitely-many-linear-relations-p-n-p-n-3
Answer: Your equation is equivalent to
$$p_{n+3}-p_{n+2}=p_{n+2}-p_n$$
Consider the prime-constellation $0,2,6,12$ , which is a so-called admissible
prime constellation (See https://en.wikipedia.org/wiki/Prime_k-tuple for more details).
It is conjectured that there infinite many prime constellations for every
admissible vector. So, probably your claim is correct, but I think there
is no proof.
The first few constellations solving your equation :
<code>? x=1;while(x<1000,x=x+1;while(1-(isprime(x)==1)*(isprime(x+2)==1)*(isprime(x+6)
==1)*(isprime(x+8)==0)*(isprime(x+12)==1),x=x+1);forprime(j=x,x+12,print1(j,"  "
));print)
17  19  23  29
41  43  47  53
227  229  233  239
347  349  353  359
641  643  647  653
1091  1093  1097  1103
</code>
The first constellation, for which $p_n>10^7$ ,seems to be the $1485-th$
<code>1485   10017011  10017013  10017017  10017023
</code>
Comment: @dohmatob I just noticed that you had this idea. A proof of such conjectures seems to be out of reach.
Comment: You can add the assumption that $x\equiv6\pmod7$, still get (conjecturally) infinitely many primes, and then they'll be consecutive, since $7\mid x+8$.
Comment: Note that not every constellation leads to a solution, you must find an $x$, such that $x,x+2,x+6,x+12$ are prime, but not $x+8$, for instance. I am not sure, it is also conjectured that such constellations appear infinite many times, but probably this is the case.
Comment: I also had the idea of considering constellations of the form $(0,2g,6g,12g)$ and then abandoned it, since I'm actually interested in consecutive primes, whilst the conclusions of the $k$-tuples conjecture, etc. are quite modest, in this regards.
Comment: @GerryMyerson: Thanks for the great insight. Finally, something constructive :) I've commented your mathoverflow comment.
Comment: @Peter: You have my upvote. Nice.


Enviar arquivos clonados em javascript usando php

Question: Estou criando um formulário de pedido. Nesse formulário tem um campo com o produto e a quantidade. Eu estou utilizando uma função javascript para clonar o campo quando o cliente quer mais um produto, com isso cada vez que o cliente clica em novo produto cria uma nova caixa de seleção para ele selecionar o produto desejado e depois preenche a quantidade.
O que eu preciso é enviar esses dados que são gerados atraves dessa função por php. Tentei varias coisas mas em nenhuma obtive sucesso.
Segue abaixo os codigos.
JavaScript
 <fieldset id="listproducts">  <legend> PRODUCTS </legend>

            <select name="product" id="product">
            <optgroup label="GALLON BAG">
                <option>GALLON BAG BANANA SPLIT</option>
                <option>GALLON BAG BIRTHDAY CAKE</option>
                <option>GALLON BAG COTTON CANDY</option>
              </optgroup>
               <optgroup label="PRE-CUP">
                <option>PRE-CUP BANANA SPLIT</option>
                <option>PRE-CUP CHOCOLATE</option>
                <option>PRE-CUP COTTON CANDY</option>
               </optgroup>
                </select>

            <select name="quantity" id="quantity">
                <optgroup label="Qty">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                  </optgroup>
                  </select>

PHP
<?php

if(isset($_POST['email'])) {

$email_to = "email@example.com";

$email_subject = "[ Online Order ]";

function died($error) {

    echo "We are very sorry, but there were error(s) found with the form you submitted. ";

    echo "These errors appear below.

";

    echo $error."

";

    echo "Please go back and fix these errors.

";

    die();

}

if(!isset($_POST['name']) ||

    !isset($_POST['business']) ||

    !isset($_POST['email']) ||

    !isset($_POST['phone']) ||

    !isset($_POST['quantity']) ||

    !isset($_POST['product'])) {

    died('We are sorry, but there appears to be a problem with the form you submitted.');

}

$name = $_POST['name']; // required

$business = $_POST['business']; // required

$email_from = $_POST['email']; // required

$phone = $_POST['phone']; // not required

$quantity = $_POST['quantity']; // required

$product = $_POST['product']; // not required

$error_message = "";

$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

if(!preg_match($email_exp,$email_from)) {

    $error_message .= 'The Email Address you entered does not appear to be valid.
';

}

if(strlen($error_message) > 0) {

    died($error_message);

}

$email_message = "You received an online order.
Follow below the informations.

\n\n";

function clean_string($string) {

    $bad = array("content-type","bcc:","to:","cc:","href");

    return str_replace($bad,"",$string);

}

$email_message .= "
Name: ".clean_string($name)."\n";

$email_message .= "
Business: ".clean_string($business)."\n";

$email_message .= "
Email: ".clean_string($email_from)."\n";

$email_message .= "
Phone: ".clean_string($phone)."\n";

$email_message .= "

ORDER: \n";

$email_message .= "

Qty: ".clean_string($quantity)."\n";

$email_message .= "  Product: ".clean_string($product)."\n";

$headers = "Content-Type: text/html; charset= UTF-8 \r\n";
$headers .= 'From: '.$email_from."\r\n".

    'Reply-To: '.$email_from."\r\n" .

    'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);

?>

Thank you for order. We will contact you as soon as possible.

You can close this page now.

    <?php

}

?>

HTML
<fieldset id="listproducts">  <legend> PRODUCTS </legend>

            <select name="product" id="product">
            <optgroup label="GALLON BAG">
                <option>GALLON BAG BANANA SPLIT</option>
                <option>GALLON BAG BIRTHDAY CAKE</option>
                <option>GALLON BAG COTTON CANDY</option>
              </optgroup>
               <optgroup label="PRE-CUP">
                <option>PRE-CUP BANANA SPLIT</option>
                <option>PRE-CUP CHOCOLATE</option>
                <option>PRE-CUP COTTON CANDY</option>
               </optgroup>
                </select>

            <select name="quantity" id="quantity">
                <optgroup label="Qty">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                  </optgroup>
                  </select>

Answer: Pelo que entendi, você precisa salvar uma lista de produtos, isto? Se for, você precisa alterar o nome dos elementos na tela, para passar um array por POST.
Onde você têm:
<select name="product" id="product">
    ...
    <option>GALLON BAG BANANA SPLIT</option>

Você precisa trocar por:
<select name="product[]">
    ...
    <option value="GALLON BAG BANANA SPLIT">GALLON BAG BANANA SPLIT</option>

Com isto, no PHP você vai receber um array então é só usar um for():
<?php
$produto = $_POST["product"];
$qtd = $_POST["quantity"];

for ($i = 0; $i < count($produto); $i++) {
    // para inserir cada produto você usa $produto[$i] e $qtd[$i]
}

Answer: @Éderson Fernandes Não funcionou, não chegou no email as informações. Da uma olhada se eu fiz certo...
HTML
<select name="product[]" id="product">

<select name="quantity[]" id="quantity">

PHP
$name = $_POST['name']; // required

$business = $_POST['business']; // required

$email_from = $_POST['email']; // required

$phone = $_POST['phone']; // not required

$quantity = $_POST['quantity']; // required

$product = $_POST['product']; // not required

for ($i = 0; $i < count($produto); $i++) {
    // para inserir cada produto você usa $produto[$i] e $qtd[$i]
}

$email_message .= "
Name: ".clean_string($name)."\n";

$email_message .= "
Business: ".clean_string($business)."\n";

$email_message .= "
Email: ".clean_string($email_from)."\n";

$email_message .= "
Phone: ".clean_string($phone)."\n";

$email_message .= "

ORDER: \n";

$email_message .= "

Qty: ".clean_string($quantity[$i])."\n";

$email_message .= "  Product: ".clean_string($produto[$i])."\n";


Cauchy's mean value theorem easy proof

Question: So the theorem is
$\frac{f'(c)}{g'(c)}=\frac{f(b)-f(a)}{g(b)-g(a)}$
The usual proof on Wikipedia or here seems to come from defining a $h(x)$ and doing some magic with it.
But with the mean value theorem $f'(c) = \frac{f(b) - f(a)}{b-a}$, can't this simply be proved by bringing this on a form like $b-a=\frac{f(b)-f(a)}{f'(c)}=\frac{g(b)-g(a)}{g'(c)}$ and rearranging this to the form at the top? I'm probably missing something crucial reason.
Answer: $c$ is not the same here. You have $f'(c_1)=\frac{f(b)-f(a)}{b-a}$ for some $c_1\in\mathbb R$ and you have $g'(c_2)=\frac{g(b)-g(a)}{b-a}$ for some $c_2\in\mathbb R$

Cauchy's mean value theorem easy proof


How to capture selected element from dropdown in razorview and send it using POST?

Question: Below is my razor view. I am populating my dropdown from my controller's passed list.
I need to send item that was selected from the dropdown list to send it to my api.

            @model List<Data>

            <select>
                @foreach(var item in Model)
                {
                    <option value="@item.value" >@item.value</option>
                }
            </select>

            <form id="sendstuff">

               @*TODO need to send what was selected in the dropdown here*@

                <input class="btn" type="submit" id="createAccount" value="Send Stuff" />

            </form>

Jscript here sends json post request to web api and grabs apiresponse back from the api and replaces the view's #apiresponse. What I want to do is to
send the option that has been selected in the dropdown and send that option to this json ajax post request.
Here is the controller code. It is a json file and passing the list of "Data" from the file to the view.
namespace Something.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            using (StreamReader r = new StreamReader(System.IO.File.OpenRead(WebConfigurationManager.AppSettings["JsonFileLocation"])))
            {
                string jsonData = r.ReadToEnd();
                List<Data> testsNamesList = JsonConvert.DeserializeObject<List<Data>>(jsonData);
                return View(Data);
            }
        }
    }
}

Comment: When do you want to send it? And how? You don't have it in the form... do you have a button for this?
Comment: I have updated the question. Hopefully this clears things up.
Answer: try this
@using (Html.BeginForm())
{
    <select name="dropdownValue">
    @foreach (var item in Model)
    {
        <option value="@item.value">@item.value</option>
    }
    </select>
   <input type="submit" value="submit" />
}

and get the value by add string parameter called dropdownValue to your action method
Comment: I do want to include my options in the form. See my above updated question. This might help you better answer my question now.
Answer: I have come up with one solution using javascript. Basically when the dropdown is selected, it populates the textbox with the dropdown selection and when I submit, the populated field in the textbox will be sent to api.
$('#dropdown').change(function () {
    $('#textbox').val($(this).find(":selected").text());
});

This is not the ideal solution, but if anyone else has better solution please feel free to answer.


CloudFormation mentions Document type is required for schema version 2.2

Question: The following error is displayed on the stack in the cloudformation service of the browser AWS console.

Document type is required for schema version 2.2 (Service: AmazonSSM; Status Code: 400; Error Code: InvalidDocumentSchemaVersion; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

It occurred for the following Resource in the CloudFormation Document:
InstanceConfigDocument:
  Type: AWS::SSM::Document
  Properties:
    Content:
      schemaVersion: "2.2"
      description: Join Active Directory
      mainSteps:
        - action: aws:domainJoin
          name: joiningDomain
          inputs:
            directoryId: !Ref ActiveDirectory
            directoryName: myDirectoryName
            dnsIpAddresses:
              - !Select ['0', !GetAtt 'ActiveDirectory.DnsIpAddresses']
              - !Select ['1', !GetAtt 'ActiveDirectory.DnsIpAddresses']

How can I solve this error?
Answer: Adding the DocumentType property worked for me.
  InstanceConfigDocument:
    Type: AWS::SSM::Document
    Properties:
      DocumentType: "Command"
      Content:
        schemaVersion: "2.2"
        description: Join Active Directory
        mainSteps:
          - action: aws:domainJoin
            name: joiningDomain
            inputs:
              directoryId: !Ref ActiveDirectory
              directoryName: myDirectoryName
              dnsIpAddresses:
                - !Select ['0', !GetAtt 'ActiveDirectory.DnsIpAddresses']
                - !Select ['1', !GetAtt 'ActiveDirectory.DnsIpAddresses']

The CloudFormation Documentation refers to DocumentType as not required. It seems it is required for SSM Documents using schema version 2.2.
Comment: Thank you for replying but right after I posted this question, I managed to figure out how to include the property in the schema for the stack.

Since the output json schema doesn't feature the document type in the cloudformation stack content and it doesn't mention in the aws docs that the property is required, I had this question.

It is resolved now, thanks again because quite possibly, reading this thread helped clear my mind!:)
Comment: There is no "Properties" property in version 2.2 "Unknown property error" in CDK but yes, it is required and there is no documentation on the schema for the "DocumentType" property when deploying programmatically with cdk.

Any pointers?
Comment: sorry I don't have a lot of experience with the CDK. I assume that you do not have to specify the "Properties" property. In this example only DocumentType and Content are properties. I would assume that the CDK is smart enough that you do not have to add Properties as well...


Dois números não somam, eles concatenam

Question: Vocês já devem estar carecas de ver problemas iguais a este. O meu problema, acredito eu, é um pouco diferente.
Eu tenho um método (chamado de transformaParaContas) que transforma qualquer tipo de valor monetário para ser possível calcular. Porem, mesmo transformando, eu não estou conseguindo utilizar estes números para somar. Fiz um método para verificar se o retorno do transformaParaContas realmente é numérico, e sim, sempre da true.
Metodos:
function transformaParaContas(value){
    if(value.indexOf(".") >= 0){
        value   =   value.replace(/\./g, "");
    }

    value   =   value.replace(",", ".");
    value   =   Number(value);
    value   =   value.toFixed(2);
    return value;
}

// metodo para verificar se é realmente um número
function isNumber(numero){
    return !isNaN(numero);
}

// disparo
$("input[name='txt_valNaoProcedente']").on("keypress", function(){
    var valProc, valNaoProc, total;
    valProc     =   $("input[name='txt_valProcedente']").val();
    valNaoProc  =   $("input[name='txt_valNaoProcedente']").val();
    if(valProc != "" && valNaoProc != ""){
        valProc     =   transformaParaContas(valProc);
        valNaoProc  =   transformaParaContas(valNaoProc);

        console.log(isNumber(valProc));
        console.log(isNumber(valNaoProc));

        total       =   valProc + valNaoProc;

        $("#div_valorDebito").text(valProc + valNaoProc);
    }else{
        $("#div_valorDebito").text("");
    }
});

Se eu fizer o seguinte, funciona:
$("input[name='txt_valNaoProcedente']").on("keypress", function(){
    var valProc, valNaoProc, total;
    valProc     =   $("input[name='txt_valProcedente']").val();
    valNaoProc  =   $("input[name='txt_valNaoProcedente']").val();
    if(valProc != "" && valNaoProc != ""){
        valProc     =   transformaParaContas(valProc);
        valNaoProc  =   transformaParaContas(valNaoProc);
        valProc     =   Number(valProc);
        valNaoProc  =   Number(valNaoProc);

        console.log(isNumber(valProc));
        console.log(isNumber(valNaoProc));

        total       =   valProc + valNaoProc;

        $("#div_valorDebito").text(valProc + valNaoProc);
    }else{
        $("#div_valorDebito").text("");
    }
});

Alguém saberia me explicar o porque isso acontece?
Comment: Já tentou Parsefloat? https://www.w3schools.com/JSREF/jsref_parsefloat.asp
Comment: Desculpe, não ficou claro. Utilizar o Parsefloat aonde?
Comment: Na função transformaParaContas, ao invés de fazer Number(value), tente parseFloat(value). Teste sem o Tofixed se nao funcionar.
Answer: Caro amigo, a função toFixed(n) sempre irá retornar um o tipo string por isso que há a concatenação e não a soma dos seus valores. E é por isso que quando você usa Number funciona.
Para uma mudança menos dramática por assim se dizer, considere retorna a valor sua função transformaParaContas(value) já como número, que seria um return Number(value);
Outra coisa, que é apenas uma curiosidade, mas que vale sempre a pena está de olho, você criou uma variável total que nunca está sendo usada. Considere remover, ou melhorar o seu código como por exemplo:
$("input[name='txt_valNaoProcedente']").on("keypress", function(){
    var valProc, valNaoProc, total = ""; // Valor já iniciado
    valProc     =   $("input[name='txt_valProcedente']").val();
    valNaoProc  =   $("input[name='txt_valNaoProcedente']").val();
    if(valProc != "" && valNaoProc != ""){
        valProc     =   transformaParaContas(valProc);
        valNaoProc  =   transformaParaContas(valNaoProc);
        valProc     =   Number(valProc);
        valNaoProc  =   Number(valNaoProc);

        console.log(isNumber(valProc));
        console.log(isNumber(valNaoProc));

        total       =   valProc + valNaoProc;
    }
    $("#div_valorDebito").text(total);
});

Comment: Excelente! Era esse mesmo o problema, obrigado.

Dois números não somam, eles concatenam


Views: What setting is available in Views to hide or skip the first entry in a multi-value field? (example skip first image)

Question: On my site, I have created an "Images" field with "unlimited" values. I have used "image delta=0" to show only the first image as the main gallery image. I then created a grid with a contextual filter of "content: nid" to display up to 10 of the images in that field. I would like to now hide the first image from the output, so that it isn't repeated with the first/main image on the page.
I have the contextual reference working well, but I haven't been able to figure out how to skip the first image. I tried a playing around with the Image Delta settings "=1", assuming that this means to increment by 1, but when I save, my view is empty.
I'm sure this is straight forward, but I have come up empty in my attempts (literally) and searches.
Thanks,
keb
Answer: I vaguely remembered doing this in a Views tutorial and remembered it was a control located within the center region of the Views interface.
Turns out it's under "Pager": Use pager: Display a specified number of items >> "You may also adjust the settings for the currently selected pager"
Click setttings and you'll be able to add an offset.


Can a logistic regression have both continuous and discrete variables as covariates or as regressors?

Question: My dependent variable should be binary, but can I include discrete and continuous variables simultaneously in my equation? For example let's say X1 is discrete and X2 is continuous?
Comment: Yes, no problem.
Comment: Could you please elaborate as in how that would be possible?
Comment: Do you mean how it should be done when using statistics software? Or do you mean how to specify the equation? Or are you interested in the maths? In all cases it would help to know more about the variables, the software used and where you are not sure when including the regressors.
Answer: There is absolutely no problem, just code your categorical predictor(s) as dummy variables, or some other form of categorical-encoding. This can be used with all form of regression models. It is usually the type of the response ($Y$) variable which "dictates" the type of regression model that can be used, not the predictors.
So, for a binary response, logistic regression, for a multinomial response, multinomial logistic regression,  continuous response, muliple linear regression, and so on (there are of course alternatives).  But in these decisions the type of predictor variable generally plays little role. See for instance Model for continuous response and a mix of continuous and categorical predictors  and  Predicting with both continuous and categorical features
Comment: What if there are more than 1000 rows and I have a column which has continuous variable (e.g. 67.22,77.89) this will create an awful lot of dummy variables extending my column size from the original 21 to 212..
Which approach should I take
Comment: @Harishreddy That warrants its own question. Briefly, you would treat it as a continuous variable, not as 1000 levels of a categorical variable.


Using Ito's lemma to compute a SDE

Question:
This is the version of Ito's lemma that we are given in our notes.

Now I'm just not able to understand how to begin this problem and arrive at  the given solution. The g(x) integral function that they have given is just confusing me and using Ito's lemma I don't understand what we have to differentiate.
Any help would be much appreciated.
Answer: We need to apply Ito's lemma to the function $g(X_t)$, where $g(x) = \int_0^x\frac{1}{\sigma(u)}\ du$, and where $dX_t = \sigma(X_t)dW_t$. Notice that there is no $t$-dependence in the function $g$, so the first term $f_t(X_t,t)dt$ of Ito's lemma vanishes, and the lemma reduces to
$$dg(X_t)  = g_x(X_t)dX_t + \frac{1}{2}g_{xx}(X_t)\sigma(X_t)^2dt.$$
Consider the first term $g_x(X_t)dX_t$. Here $g_x$ is just the derivative of $g$, and by the fundamental theorem of calculus, we have
$$g_x(x) = \frac{d}{dx}g(x) = \frac{d}{dx}\int_0^x\frac{1}{\sigma(u)}\ du = \frac{1}{\sigma(x)},$$
and thus
$$g_x(X_t)dX_t = \frac{1}{\sigma(X_t)}dX_t = \frac{1}{\sigma(X_t)}\sigma(X_t)dW_t = dW_t.$$
Consider then the second term $\frac{1}{2}g_{xx}(X_t)\sigma(X_t)^2dt$. The expression $g_{xx}$ is nothing more but the second derivative of $g$, and we have by the chain rule
$$g_{xx}(x) = \frac{d}{dx}\frac{1}{\sigma(x)} = -\frac{1}{\sigma(x)^2}\sigma'(x).$$
We then obtain
$$\frac{1}{2}g_{xx}(X_t)\sigma(X_t)^2dt = \frac{1}{2}\left(-\frac{1}{\sigma(X_t)^2}\sigma'(X_t)\right)\sigma(X_t)^2dt = -\frac{1}{2}\sigma'(X_t)dt.$$
In total, we have
$$dg(X_t) = dW_t - \frac{1}{2}\sigma'(X_t)dt.$$

Using Ito's lemma to compute a SDE


Leitura do AsyncStorage gera um loop infinito

Question: Estou com um problema nas minhas aplicações. Eu uso bastante o useState(), porém venho observando que isso está gerando loops infinitos na minha aplicação.
Segue um exemplo:
if(show){
   AsyncStorage.getItem('PEDIDO').then(value => {
      console.warn(value)
   });
}

Esse código está em um componente funcional, onde exerce a função de um modal. Por exemplo, o usuário clica em um botão e esse componente entra na tela, a propriedade show representa quando o componente está na tela. O resultado é um loop infinito mostrando o parâmetro value, se eu usar o seguinte código:
if(show){
   AsyncStorage.getItem('PEDIDO').then(value => {
      setPedido(JSON.parse(value));
   });
}

Como posso resolver esse problema do loop infinito?
Comment: Este acesso precisa estar em um [`useEffect()`](https://pt-br.reactjs.org/docs/hooks-effect.html), se ficar no corpo da função (componente), vai executar em cada render (e causará um novo render por causa do `setPedido`)
Comment: O uso do useEffect foi uma solução muito boa, muito obrigado!!
Answer: Olá, tudo bem?
Uma sugestão é, pelo trecho do código não consigo identificar ao certo o que pode está causando o "erro", recomendo que retire o .then e coloque o um async e await na chamada do AsyncStorage
Ficaria desta forma:
  const nomeDoMetodo = async () => {
    if(show){
          let pedido = await AsyncStorage.getItem('PEDIDO');
          setPedido(JSON.parse(pedido));
    }
}

Comment: Essa método continua gerando o loop... mas obrigado por responder!
Answer: Você não deve ficar acessando o AsyncStorage o tempo todo.
const [fetchStorage, setFetchStorage] = useState(true);

if(show){
   if (fetchStorage) {
       AsyncStorage.getItem('PEDIDO').then(value => {
          setPedido(JSON.parse(value));
       });
       setFetchStorage(false)
   }
   //restante do código referente ao modal
}

Desta forma, você só acessará o storage uma vez, buscando o item e salvando no state.
Espero que ajude!
Answer: Seu acesso ao AsyncStorage está num loop infinito porque você está realizando essa acesso no corpo do seu componente funcional, ou seja, a cada renderização você está obtendo o dado do AsyncStorage, atualizando o state e realizando um novo acesso (loop).
Realizei um exemplo abaixo da chamada de uma função assíncrona (com setTimeOut) sendo executada no corpo da função se show === true:

function Componente() {
  const [date, setDate] = React.useState('');
  const [show, setShow] = React.useState(false);

  React.useEffect(() => {
    setShow(true);
  }, []);

  function getDateAsync() {
    setTimeout(function() {
      console.log('Leitura assíncrona realizada');
      const now = (new Date()).toString();
      setDate(now);
    }, 1000);
  }

  if (show) {
    getDateAsync();
  }

  console.log("[RENDER] show:", show);
  return date ?
Data obtida: {date}
 :
Carregando...
;
}

ReactDOM.render( <Componente /> , document.querySelector("#app"));

Pare resolver isso, a solução ideal é fazer uso do Hook useEffect:

O que o useEffect faz? Usando esse Hook, você diz ao React que o componente precisa fazer algo apenas depois da renderização.

Então faremos um useEffect que será chamado sempre que mudar o estado de show, mas queremos executar o getDateAsync() apenas se show for true, então criamos uma condição também:

function Componente() {
  const [date, setDate] = React.useState('');
  const [show, setShow] = React.useState(false);

  React.useEffect(() => {
    setShow(true);
  }, []);

  React.useEffect(() => {
    // Criando uma função desta maneira, você pode inclusive fazer uso de
    // async/await para obter o resultado do AsyncStorage.
    function getDateAsync() {
      setTimeout(function() {
        console.log('Leitura assíncrona realizada');
        const now = (new Date()).toString();
        setDate(now);
      }, 1000);
    }

    if (show) {
      getDateAsync();
    }
  }, [show]);

  console.log("[RENDER] show:", show);
  return date ?
Data obtida: {date}
 :
Carregando...
;
}

ReactDOM.render( <Componente /> , document.querySelector("#app"));

Repare que quase não houve mudanças no código, mas dessa maneira fazemos um bom uso dos Hooks e o código executa o comportamento esperado pelo usuário.


How to see detailled error message "Apple Mach -O Linker Error" in Xcode?

Question: I have only one error but I don't know what's exactly. I would like to see the exact Linker error message output in the std err in Xcode. How to do that in Xcode?
Comment: double check you library search path and libs in liker settings and remove duplicated and non exists libs
Answer: Right-click the error message you described in Xcode, and choose the option "Reveal in Log". That displays the full error message.


How many three digit numbers are not divisible by 3, 5 or 11?

Question: How many three digit numbers are not divisible by 3, 5, or 11?
How can I solve this?
Should I look to the divisibility rule or should I use, for instance,
$$
  \frac{999-102}{3}+1
$$
Comment: You clearly mean '3, 5 or 11', since otherwise you would just have these numbers: 165, 330, 495, 660, 825, 990 and you could say (999 - 99) - 6 = 894
Comment: `>>> len([x for x in range(100,1000) if x%3 and x%5 and x%11])`
`437`
Answer: Assuming that you mean by either $3$ or $5$ or $11$, use inclusion/exclusion principle:

Amount of numbers with at most $3$ digits that are not divisible by $3$ or $5$ or $11$:
$999-\lfloor\frac{999}{3}\rfloor-\lfloor\frac{999}{5}\rfloor-\lfloor\frac{999}{11}\rfloor+\lfloor\frac{999}{3\times5}\rfloor+\lfloor\frac{999}{3\times11}\rfloor+\lfloor\frac{999}{5\times11}\rfloor-\lfloor\frac{999}{3\times5\times11}\rfloor=485$
Amount of numbers with at most $2$ digits that are not divisible by $3$ or $5$ or $11$:
$99-\lfloor\frac{99}{3}\rfloor-\lfloor\frac{99}{5}\rfloor-\lfloor\frac{99}{11}\rfloor+\lfloor\frac{99}{3\times5}\rfloor+\lfloor\frac{99}{3\times11}\rfloor+\lfloor\frac{99}{5\times11}\rfloor-\lfloor\frac{99}{3\times5\times11}\rfloor=48$
Amount of numbers with exactly $3$ digits that are not divisible by $3$ or $5$ or $11$:
$485-48=437$
Comment: Your answer is incorrect, as you count one and two digit numbers as well.
Comment: @dmg: Thank you for pointing that out. I will update the answer.
Answer: A simple approach I like is the Inclusion-exclusion principle.
Let $C_{[i1, i2,...]}$ mean number of three digit numbers divisible by i1, i2, ... and $C$ the number of three digit numbers. So we have:
$C - C_{[3]} - C_{[5]} - C_{[11]} + C_{[3, 5]} + C_{[3, 11]} + C_{[5, 11]} - C_{[3, 5, 11]}$
For each $C_{[i_1, i_2, ...]}$ we have:
$C_{[i_1, i_2, ...]} = \lfloor\frac{999}{i_1 * i_2 *...}\rfloor - \lfloor\frac{99}{i_1 * i_2 *...}\rfloor$
This results in $900 - (300 + 180 + 81) + (60 + 27 + 17) - 6 = 437$
Note:
I assume you mean "How many three digit numbers are not divisible by 3,5 or 11?"
Otherwise your answer is $\lfloor\frac{999}{3*5*11}\rfloor - \lfloor\frac{99}{3*5*11}\rfloor = 6$
Answer: One can compute the required exclusions/inclusions quickly and avoid having to deal with floor function by going about it as below:
Numbers from 1 to 990 not divisible by $3, 5$ or $11$ = $990(1-\frac{1}{3})(1-\frac{1}{5})(1-\frac{1}{11})$ = 480
One can count that from 991 to 999 there are 5 such numbers.
Total numbers between 1 - 999 => $485$
Total numbers from 1 to 99 not divisible by $3,5$ or $11$ = $99(1-\frac{1}{3})(1-\frac{1}{5})(1-\frac{1}{11})$ = 48
Total 3 digit numbers not divisible by $3, 5$ or $11$ = $485 - 48$ = $437$
Answer: This question can also be solved by applying set theory.
Using the formula
$n(A⋃B⋃C) = n(A) + n(B) + n(C) - n(A⋂B) - n(B⋂C) - n(A⋂C) + n(A⋂B⋂C)$
calculate the number of three digit numbers divisible by 3, 5, 11, 15, 55, 33, 165 (15, 33, 55 and 165 are LCMs of 3-5, 3-11, 5-11 and 3-5-11 respectively) using the formula that you mentioned. This will give the number of 3 digit numbers which are divisible by either 3 or 5 or 11. Subtract this number from 900 (total number of 3 digit numbers) to get the desired result.
Comment: Isn't this exactly what the other two answers did?
Comment: They all **indeed** do the same thing. The approach is different though.


What does taskset in linux exactly do?

Question: I have a program running on a 32 core system using Intel TBB.
The problem I have is when I set the program to use 32 threads, the performance doesn't gain enough compared to 16 threads (only 50% boost). However, when I use:
taskset 0xFFFFFFFF ./foo

which would lock the process to 32 cores, the performance is much better.
I have the two following questions:

Why? By Default, the OS would use all 32 cores for the 32 thread program anyway.
I'm assuming that even with taskset, the OS is allowed (would) to exchange the virtual threads and the physical threads, i.e. threads are not pinned. am I right?

Thanks.
Comment: `The OS would use all 32 cores for the 32 thread program anyway` -- Are you sure that assumption is valid?
Answer: The operating system may choose to use less cores for cache purposes. Imagine if the application uses the same set of memory then each write causes a cache invalidate. Forcing the lock is essentially you telling the OS the cache overhead for concurrency is not worth it, go ahead and use all the cores.
You must also remember there are other processes to run (like kthreads from the kernel, and background processes.) and migrating threads between cores is costly and may cause imbalances if your threads are not doing an even amount of work.
Also remember that the OS tries to evenly distribute work on the cores across ALL processes not just yours. This means that the load balancer may choose to not place your process on all 32 cores as there are other processes currently running and migration costs could be high or spreading your process evenly could cause load imbalance among the cpu cores. The OS strives for best system performance not necessarily best per application performance.
Comment: Can you explain again, why the OS might use less cores?
Comment: @user1316459 cache coherency is expensive. It's better to place processes on a smaller number of cores sometimes so that there is less cache invalidations and coherency issues (since they may share L1/L2 cache). If they are all on separate cores they may just be stepping over each other. The other reason is CPU utilization and other processes running on the system.
Comment: So you're saying that for a multithreaded program, the OS, by default, uses less cores than needed to increase  performance?
Comment: @user1316459 That's one possible situations. Others are that there are other processes running on some cores which the OS may not want to move around or placing threads on those cores would cause an imbalance.

What does taskset in linux exactly do?


Finding partial derivative $f_x$ of $\ln(x^2y)$ using definition.

Question: How do find partial derivative $f_x$ of $f(x,y)=\ln(x^2y)$  using definition? I know that the answer is $\frac2x$, but I can't see how to get there by using limit $$\lim_\limits{\Delta x\to 0}\frac{\ln((x+\Delta x)^2y)-\ln(x^2y)}{\Delta x}.$$
Comment: You can start by using the properties of the $\ln$ function. First, $\ln((x+\Delta x)^2y)=\ln(x+\Delta x)^2+\ln y$. Do the same with $\ln (x^2y)$...
Answer: Write
\begin{align}
L&=\frac{\ln((x+\Delta x)^2y))-\ln(x^2y)}{\Delta x} \\
&=\frac{2\ln(x+\Delta x)+\ln(y)-2\ln(x)-\ln(y)}{\Delta x}\\
&=2\left(\frac{\ln(x+\Delta x)-\ln(x)}{\Delta x}\right)
\end{align}
which is recognized as the derivative of $2\ln(x)$ for $\Delta x\rightarrow 0$.


Sampling from a distribution the 10% of values around the peak value in R

Question: I have a vector of 100 values.
bingo<-sample(0:5000, 100)

plot(density(bingo))

which.max(density(bingo)$y) # [1] 194

density(bingo)$x[194] # [1] 1507.085

I wanto to sample the 10% of the values around 1507.085, the peak of my distribution. Ho can I achieve it?
Many thanks for any advice!
Comment: What is your desired output? Also, next time when you are using random data in the question, use `set.seed()` before `sample()` to make sure we get the same random numbers.
Comment: If I understood your need correctly, this could be `bingo[bingo > quantile(bingo,0.9)]`
Answer: It depends on what you mean by "around". Here are a couple of options:
set.seed(94)
bingo <- sample(0:5000, 100)
bingo <- sort(bingo)
bingo_mode <- density(bingo)$x[which.max(density(bingo)$y)]
idxMode <- match(TRUE, bingo > bingo_mode)

# to sample from 5 before and 5 after the peak (or the top/bottom decile if the
# peak is in the 95th/5th percentile)
if (idxMode < 5) {
  idxFrom <- 1
  idxTo <- 10
} else if (idxMode + 4 > 100) {
  idxFrom <- 91
  idxTo <- 100
} else {
  idxFrom <- idxMode - 5
  idxTo <- idxMode + 4
}

sample(bingo[idxFrom:idxTo], 1)
#> [1] 2557

# to sample from the 10 nearest the peak
if (idxMode < 10) {
  idxFrom <- 1
  idxTo <- 20
} else if (idxMode + 9 > 100) {
  idxFrom <- 81
  idxTo <- 100
} else {
  idxFrom <- idxMode - 10
  idxTo <- idxMode + 9
}

sample(bingo[idxFrom:idxTo][order(abs(bingo_mode - bingo[idxFrom:idxTo]))[1:10]], 1)
#> [1] 2678


Natural language de-identification

Question: I am looking for a natural language tool that can automatically de-identify English text. For example, every email address should be renamed or obscured. But proper names should be de-identified, as should addresses and what not.
There is a MITRE Identification Scrubber Toolkit. I don't know how well it works.
My questions:

Are there any other tools out there?
Does anyone have experience with the MITRE tool? How well does it work?

Thanks.
Comment: @eowl Agreed - named entity recognition + token substitution is principally about named entity recognition.  However, you might also add anaphora resolution.  Being able to identify anaphora ("he", "the official", "the spokesman", etc.) is important in being able to further anonymize text.  Such tools are definitely in the NLP domain, and less about coding (i.e. not so much related to SO as the above SE site).
Comment: (Continued) If this is related to legal or ethical requirements, then you'd do very well to look at what the NLP community can offer, which will be more substantive than simply coding something anew (which could incur new legal liabilities for not using the state of the art resources).  Anyway, this is more tool related than coding, which is a reason to migrate.  Good luck, it is an interesting question.
Comment: @Iterator NLP is still only a proposal, so we can't migrate anything there until it actually becomes a site.
Comment: @eowl Please don't use URL shorteners. A proper link would be a lot clearer and potentially more inviting.
Comment: @anna Ah, I was unaware of that limitation. Darn :( This is perfect.
Answer: De-identification (perhaps more often referred to as anonymization) is a very active research area as its success is obviously a requirement for the use of authentic text corpora in such fields as NLP for healthcare, medicine and the like. I recommend that you look at the tools listed in the answer to this question on CrossValidated. If you follow the links further, you will find research papers describing how these tools work with further references and results evaluations.

Natural language de-identification


Como organizar o código para que seja reaproveitado

Question: Considere o seguinte cenário:

Como podem ver, o prefab (vermelho) é constituído por 3 elementos:

O sprite (que é o chão, os quadradinhos castanho e o tubo verde)
O enemy (rosa) que é um outro prefab
O empty GameObject (azul)

Apenas para entender o contexto, o jogo funciona assim: a cada "x" segundos adiciono um novo prefab no do cenário, produzindo assim um cenário infinito (tenho vários prefab's e a imagem acima contém apenas 1 para exemplo). O player vai para cima e para baixo e não pode encostar no inimigo.
A parte de movimentar o prefab, de colidir com o inimigo e morrer, etc... está feito e a funcionar e não é esse o problema, por isso não inseri aqui códigos.
O que pretendo é quando o player (laranja) colidir com o GameObject (azul) o Enemy (rosa) vá para cima e para baixo em looping.
Para entender o porquê de cada elemento dentro do prefab: como tenho vários prefabs (vermelho) de larguras diferentes e inimigos (rosa) diferentes em posições diferentes, o empty GameObject (azul) serve apenas para indicar ao inimigo que deve iniciar a sua animação quando o player colidir com ele, assim tenho mais flexibilidade para criar novos prefabs.
Exitem 2 tipos de animações para cada inimigo: a que fiz através da aba Animation e é especifica para cada tipo de inimigo e a animação compartilhada, por exemplo, ir um pouco para cima e um pouco para baixo em looping, ou ir para a esquerda e para a direita em looping, etc...
A segunda animação pode ser utilizada em vários inimigos e pretendo fazer por código para que o boxcollider também se movimente, o que não é possível utilizando o Animation (até onde eu sei).
A minha dúvida é como implementar o que descrevi acima? Como organizar o código para que seja reaproveitado?
Sei implementar a relação entre 2 objectos, quando um colide com o outro, porém estamos a falar de uma colisão que terá efeito em um terceiro objecto.
Answer: Eu presumo que você esteja usando o GameObject vazio apenas como "ativador" pra animação do inimigo por motivos de desempenho (isto é, pra evitar que ele já venha animado desde a instanciação do prefab, mesmo com o avatar do jogador ainda bem longe do inimigo). Isso é uma boa coisa a se fazer, mas ainda assim seria interessante colocar esse controle no escopo do próprio inimigo.
É mais ou menos próximo do que prega a orientação a agentes: cada entidade "inteligente" no seu jogo tem seus próprios objetivos, e por isso toda a programação desses objetivos faz mais sentido no escopo do agente. Pense assim: o seu inimigo começa ou para de se animar porque ele tem como objetivo atacar o avatar do jogador. Então, na fantasia do jogo, ele não está se movendo ou parando por questões de desempenho (ainda que no mundo real isso seja extremamente útil!), mas apenas porque ele é capaz de detectar por si só a presença do jogador.
Sendo assim, eu faria da seguinte forma:

Não usaria um GameObject vazio como no seu exemplo pra detectar o jogador, mas sim usaria um trigger (o colisor é mais voltado à física) em toda a área do prefab (vermelho). Esse trigger capturaria os dois eventos de entrada (onTriggerEnter e onTriggerExit) para indicar à todos os inimigos existentes no prefab que o jogador entrou e saiu dessa área de ameaça (threat area).
O script/classe dos inimigos seria herdado de um script/classe-base, de forma que você pudesse invocar um método abstrato a partir dos eventos de colisão do trigger. Assim, cada inimigo poderia implementar o seu próprio comportamento (isto é, cada um poderia fazer como mais bem entender com a informação de que o inimigo entrou e/ou saiu da área de ameaça).

Código de Exemplo
Classe básica do Inimigo:
using UnityEngine;
using System.Collections;

public class EnemyBase : MonoBehaviour {

    private bool playerNear;

    public bool isPlayerNear {
        get { return playerNear; }
        protected set { playerNear = value; }
    }

    public void playerEnteredThreat ()
    {
        isPlayerNear = true;
    }

    public void playerExitedThreat ()
    {
        isPlayerNear = false;
    }
}

Classe específica de um inimigo qualquer, herdada da classe básica:
using UnityEngine;
using System.Collections;

public class EnemySpecific : EnemyBase {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if (isPlayerNear) {
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            Debug.Log ("Player esta proximo! Distancia: " + Vector3.Distance(transform.position, player.transform.position));
        }

    }
}

Exemplo de uso (detecção das colisões e passagem de mensagem para a classe abstrata do inimigo - este é o código que vai no trigger; eu só referenciei um inimigo nele, mas dá na mesma no seu caso):
using UnityEngine;
using System.Collections;

public class Teste : MonoBehaviour {

    public GameObject enemy;

    void OnTriggerEnter(Collider oOther) {
        if (oOther.tag == "Player")
            enemy.GetComponent<EnemyBase> ().playerEnteredThreat ();
    }

    void OnTriggerExit(Collider oOther) {
        if (oOther.tag == "Player")
            enemy.GetComponent<EnemyBase> ().playerExitedThreat ();
    }
}

Explicação do Código de Exemplo

A classe do inimigo herda de uma classe base, que contém todo o código para receber as indicações de entrada/saída do colisor/trigger (use o que preferir, mas se não tem intenção de ter resultados físicos, trigger é mais indicado). Esses valores são reutilizados pela classe filha (via uma propriedade que eu criei chamada isPlayerNear, mas você poderia sobrescrever os métodos de notificação se assim desejasse.
O script que está de fato adicionado ao objeto do inimigo é o EnemySpecific, mas note como no código do trigger ele faz o seguinte:

enemy.GetComponent<EnemyBase> ().playerEnteredThreat ();
Ou seja, ele referencia o que quer que esteja no inimigo por meio da classe abstrata. Como todos os inimigos vão herdar dessa classe (e, consequentemente, ter em sua interface o método playerEnteredThreat, seja ele o original da classe base ou um reescrito na classe filha), isso garantidamente funciona. E permite que o trigger avise de forma genérica, e cada implementação de inimigo faz com isso o que bem desejar.
Concluindo
Essa abordagem tem a vantagem de que facilita a criação de inimigos com comportamentos distintos, de forma independente da detecção da movimentação do jogador. Hoje, por exemplo, você praticamente só detecta a aproximação do jogador. Mas imagina que o jogo tá quase pronto e então o projetista do jogo (o game designer) chegasse pra você e solicitasse uma "pequena alteração": ele quer que se o jogador consiga se desvencilhar do inimigo e se afaste, o inimigo ative uma arma de tiro único de longo alcance (sei lá, cuspa uma semente explosiva, por exemplo). Nesse caso, você vai precisar também detectar o afastamento do jogador, e com a arquitetura atual isso será bem mais difícil (talvez você terá que incluir um novo GameObject vazio no final, e mais código duplicado pra fazer o mesmo que já faz).
Outra vantagem de saber que o avatar do jogador está na área de ameaça é que a "inteligência" do inimigo pode mudar sua atitude do ponto de vista da observação. É muito fácil cada inimigo no jogo ter uma referência ao objeto do jogador e calcular a distância euclidiana de si até ele. O problema é que isso tem custo computacional bem grande. Imagina cada inimigo em um conjunto de 100 fazendo esses cálculos (que envolvem raiz quadrada, uma operação bem custosa) a cada quadro. Usando a indicação da presença ou ausência do jogador na área de ameaça, esse tipo de cálculo pode ser realizado com um bom desempenho apenas pelos inimigos que estão na mesma área de ameaça do jogador. Pode parecer bobagem, mas isso facilita a implementação futura de comportamentos mais complexos com um desempenho melhor. Por exemplo, um inimigo poderia intencionalmente esperar que o jogador esteja muito próximo (distância bem curta) para ativar sua animação de surpresa.
Comment: Muito obrigado pela sua ajuda Luiz!
Comment: O objetivo do objeto azul é mesmo isso que você falou, animar somente quando o inimigo realmente entrar em cena e também para pegar o player de surpresa, por exemplo, no prefab que mostrei acima, a "flor" sai de trás do cano quando o player atingi o objecto azul, porém há um terceiro que não mencionei (me esqueci), que é executar a movimentação somente se o player passar por uma área específica e assim só tenho que reposicionar/redimensionar o gameobject azul para onde quero dentro do prefab.
Comment: Bom, então o "objeto azul" é a sua área de threat. Ainda assim, talvez seja vantajoso pra você capturar ambos os eventos (de entrada e saída), fazendo-o ser mais largo - só pra facilitar eventuais necessidades futuras. De todas as formas, faz muito sentido você comunicar esses eventos de colisão dele diretamente pro inimigo, e ele se virar com o que tem que fazer a respeito. Como eu disse na sua outra pergunta, usar uma classe genérica pra centralizar esses comportamentos só vai dificultar a sua vida.
Comment: Sim, eu acabei por entender que utilizar uma classe para tudo não seria uma boa solução... vou aplicar o que aqui foi dito, incluindo os 2 triggers mencionados! Entretanto como faço para comunicar ao inimigo que o player entrou na threat area? Aplicando também a solução que está na resposta do Lollipop?
Comment: Sobre o "como faço pra comunicar ao inimigo [...]", eu editei a resposta para adicionar alguns exemplos. Espero que ajude. Boa sorte. :)
Answer: O conceito:
Trigger em um child object para dar OnTriggerEnter em um parent object.
O caminho:
Adicione um script para Objeto Azul que dar uma referência de script para o Objeto Rosa.
A prática:
Escreva 3 métodos no Objeto Rosa(OnCollisionEnter2DChild, OnCollisionStay2DChild, OnCollisionExit2DChild) e chame os respectivos métodos (OnCollisionEnter2D, OnCollisionStay2D, OnCollisionExit2D) no objeto Objeto Azul, passando o objeto de colisão.


What is an ECMAScript "native object"?

Question: According to the ECMA-262 a native object

object in an ECMAScript implementation whose semantics are fully
  defined by this specification rather than by the host environment

A built-in object is defined as

object supplied by an ECMAScript implementation, independent of the
  host environment, that is present at the start of the execution of an
  ECMAScript program.

with a note

Standard built-in objects are defined in this specification, and an
  ECMAScript implementation may specify and define others.  Every
  built-in object is a native object.

If a native object is fully defined by the ECMA-262 specification rather than the host environment and an ECMAScript implementation may specify and define new built-in objects, how is it that these new built-in object's can be native objects when they are not fully defined by the ECMA-262 specification?
What am I missing?
Answer: They're "native" because they come with the ECMAScript implementation.  A host environment in generally an application consisting of an ECMAScript implementation and several other interfaces that work together.  For instance,

Web Browser — a host environment consisting of ECMAScript implementation, DOM interface, Rendering engine, UI, etc.
Windows Script Host — a host environment consisting of ECMAScript implementation, VBScript implementation, etc.
Node.js — a host environment consisting of ECMAScript implementation (V8), HTTP interfaces, etc.

"Built-in" objects are required to inherit from Object or Function, whereas host objects — objects provided by the host environment, but not necessarily present at the start of execution — are not required to but may (and sometimes do).
Examples of native objects defined by ECMA-262

Object(), Array(), Date()
Math, JSON, the Global object.

Examples of native, built-in objects not defined by ECMA-262

Mozilla's numerous JavaScript extensions — such as WeakMap() or __proto__
JScript's ActiveXObject() constructor and (undocumented) CollectGarbage() function

Examples of host objects

DOM objects, document and window
console
Comment: @Raynos @AndyE `Object.getPrototypeOf(Object.prototype) === null`. The `Object` prototype object is the only built-in which doesn't have the `Object` prototype object in its prototype chain.
Comment: @Raynos It's not proprietary because it's sufficently specified to be implemented by anyone. It's not standard, true, but it's not proprietary.
Comment: Are you sure there are no built-in objects whom `Object.getPrototypeOf(obj)` doesn't contain `Object.prototype` ?
Comment: Note that WeakMap isn't a proprietary extension, it's an implementation of a Harmony proposal. Also `ActiveXObject()` is a host object and not a native object.
Comment: @gsnedders: `ActiveXObject()` *is* a native object, but it returns a host object.  Even in older versions of IE and JScript, `ActiveXObject.prototype` is present whereas it is not on *all other* host objects.  Also, `WeakMap()` is an extension until Harmony becomes ES 6 :-p
Comment: @Raynos: I can't say for sure, but I believe that it would be a violation of the spec.  Built-in objects are required to be native and therefore following the semantics laid out by ECMA-262.
Comment: @gsnedders can one argue it is proprietary because it may differ from the finalized ES6 specification semantics of `WeakMap` ?
Comment: @AndyE Whether or not the object has a `prototype` property doesn't change whether it is a host object or a native object. Try using a custom impl of [[Construct]] matching that of native objects, for example --- that won't work, so its semantics aren't entirely described by ES.
Comment: @gsnedders: word *'proprietary'* retracted.  My argument wasn't that `ActiveXObject` was a built-in object because it has a `prototype`, but rather that having a `prototype` in environments whose host objects don't have one is evidence that it's provided by the JavaScript implementation (JScript) and not the host environment.
Comment: @AndyE I think that line between JScript and host environment is implementation specific. My understanding is that (ignoring the JIT) everything is translated from js source code into C++ objects. Some implement more javascript object like interfaces then others. having a split between JScript objects or host objects is strange.
Comment: @AndyE  I think, `window` is a native object, not a host object. I have created [this question](http://stackoverflow.com/q/10553188/425275).
Answer: The semantics of a native object are fully defined by ECMA-262. The object itself may not be.
So we have three levels of objects:

Standard built-in objects: defined ECMA-262, and follow ECMA-262 semantics. Example: Object.
Other built-in objects: not defined in ECMA-262, but follow ECMA-262 semantics. Example: setTimeout.
Host objects: don't follow ECMA-262 semantics; they can have weird behavior of any sort, and interact with EMCA-262 built-in objects in weird and unexpected ways (for example lying about various internal properties). Example: NodeList.
Comment: `setTimeout` isn't a built-in object, it's a host object (it's part of the DOM).
Comment: I'm not entierly clear myself, but I am pretty sure it follows ECMA-262 semantics, which would make it a built-in by these definitions, right?
Comment: host objects can follow ECMA-262 semantics if they want to.  Sadly, in older versions of IE and other browsers, this isn't the case.  Even `setTimeout instanceof Function` returns `false` and `typeof setTimeout` returns `"object"` in IE 7 and lower.
Answer: The definition of native object is the relative term of host object
Like window.console object is a host object which Ecma262 haven't been documented to tell the browser how to implement it.
And Ecma262 is just a project to specify the language the feature. ECMAScript implementation actually is browser's business. That means the implementation compliant to the specification on the object type, we can say it built-in object though they does not work exactly the same.

What is an ECMAScript "native object"?