Amaj chord: Fret buzz on the D string

Question: While playing the A chord on my acoustic, I can't get rid of fret buzz on the D string, no matter how hard I try.
I almost wonder if you guys have found a more parallel angle of the wrist so that the middle finger isn't forced to fret so far back… then I realize we all have to deal with that thing called the neck.
I feel like taller frets is the only way to prevent buzz while the finger is so far behind the fret.(I can only get about 5/8" close to the fret)
Thoughts?
Comment: Exactly what fingering do you use for your A chord? I assumed 123 bottom to top but you mention the middle finger being far back..
Comment: @JohnBelzaguy yeah I do 234 because my index finger would be even further behind the fret and I'm used to playing other chords in A position using the barre
Comment: Just to confirm: If you play only that string but fretted as you would when playing the chord, the buzz still occurs?
Comment: @Aaron yes, if not buzz then a really poor tone
Comment: I generally play an A with the the entire index finger. This prevents the high E so it can be played with in other ways. One of the points of inversions and voicings is to make it easier to play chords and still get the same color. It's always best to learn multiple fingers per chord. You can play A many different ways such as 123, 234, 345, 111, 122, 133, 144, 233, 244, 344, etc and even with some of those you can change the way fingers distribute on each fret(a sort of back to front or front to back. Some can fill twisted up). It's up to you to experiment.
Comment: @Gupta I've seen people play with one finger but wondered if they were somehow skipping the E string. It makes sense to just fret on the 5th, and sounds nice. I'm curious what fingering you prefer for playing other chords in the A shape barre. I find it hard to do a full bar with finger 1, fret strings 234 with finger 3 and reach the octave on high E with finger 4
Comment: You can play A with the high E with one finger but I rarely do unless I have to(it requires "hyperextending" the finger which just means you have to bend it more and it puts some strain on it). You can play the A at the 5th position if you want but of course the voicing is a little different and you have to barre so. Ultimately, again, you should at least try all fingerings out. I do not find it hard to do a full finger 1 barre or even 2 or 3(except a bit near the nut or close up high... depends if it's acoustic or electric and all that).
Comment: Anything you do enough you will get used. I for the half bar open A and getting the high A I find pretty easy(it's a half of a a G barre form. Basically an A chord G form without the 6th string and using open A for the 5th string). It will be hard to do the way you are playing it and there really is no reason to play it that way unless you have to. Note that there are two ways to play the 234. You can play an A major 7 like shape but move the maj7 up to the root(3rd string A note) or sort ofo the "opposite" with the middle finger being "ahead" of the others(it's a 3 note dim like shape but
Comment: squashed up on to the A chord). Generally speaking if you have too much trouble with some shape either you haven't played it enough or you should find an alternative. If by full barre you mean half bar in the open A using one finger, it should be easy but the hardest part, from what i remember, is that sometimes the strings get in the "joints" of the fingers and so might buzz. Generally you sort of "roll" your finger a little so you it's more of the side of the finger. A lot of these things just take care of themselves by playing a lot.
Answer: Assuming your neck and frets are ok and the E note on the second fret of the D string doesn't buzz on its own there are a few options you can try. It sounds like you might have pretty wide fingertips that force your fingers into a diagonal angle when stacked.
You mentioned using your middle finger. The most typical way of playing an A chord is with the 1st finger on the D string, 1,2,3 on D,G,B strings respectively. If you are using 2,3,4 try 1,2,3, the conventional way.
The other option is to finger it low to high 2 1 3 as if you were playing an Amaj7 but with all fingers in the second fret. This places the 2nd finger right up against the D string fret.
Taller frets might allow you to put more down force on the string to make contact with the fret but of course they would all have to be taller, which means a re-fret job or a different guitar. Also you shouldn't have to have to squeeze excessively to get the notes in a chord to speak properly. Lighter gauge strings might be an alternative solution.
I'm pretty sure at least one of these alternate fingerings will work for you.
Comment: I think I found my answer fretting low to high. This seems to get me no buzz. Thanks. And my strings are probably thicker than is good for me.
Answer: Usually, using pinky on 2nd, ring on 3rd and middle on 4th strings leaves enough space behind fret 2 for all finger tips to get close to said fretwire. (Although the combination of pinky, ring and index actually take up a little less space on one fret). Seems like in your case, those tips are wider than normal.
No problem, let's capitalise on that fact! Use two of them instead of three! It's entirely possible to let the tips overlap, playing all three strings using two fingers. Which two, is up to you. You may even find you can do it using just one finger, and that turns up a little to allow the top string to sound under it. (It's what a lot of us use for an 'A' shaped barre chord).
There are at least nine different fingerings for playing that open A chord. Try each until at least one of them sounds clean. I'm not going to list each, as I'm sure folk can work out those different combinations...
Comment: Thanks, Tim- I like the idea of this but I think my fingers aren't quite wide enough for that- or my instrument has wider gaps. I find that I have to flatten my finger to fret an adjacent string, which makes the higher E string get muted. I might as well use one finger and fret the high E string on 5th fret. I can't figure out how people let their finger bend backwards in order to allow the high E to sound under a half barre

Amaj chord: Fret buzz on the D string


Maximo Anywhere 7.5.2 Image Compress issue

Question: Am working on Work Execution app. How to compress the image size before saving the attachment since the attachment size limited to max 10MB.
Answer: We have an iFix available that can be requested that will shrink this filesize of the default attachment on iOS.  Please open a PMR.
Comment: Hi, that's great. Does this also work for Android and Windows devices? It will only be a matter of time before our users run into the same problem there.
Comment: No, the fix is specifically for iOS where the file size is too large by default.   We haven't seen any issue with Android and Windows devices on this.  They tend to respect our original "quality" setting and keep their filesize relatively small. If you see any issues with Android/Windows please open a PMR.


What is the distribution of $X'AX$ when $A$ is not necessarily a symmetric matrix?

Question: Assume that $X$ is a multivariate normal random variable($n$-vector) with known mean $\mu$ and covariance matrix $\sigma^2 I_n$.
What is the distribution of $X'AX$ when $A$ is not necessarily a symmetric matrix?
I want a reference concerning this type of random variables. Thanks!
Comment: Since $x^T A x = x^T \frac{A + A^T}{2} x$ for all $x$, it shouldn't matter whether $A$ is symmetric since $x^T A x$ is equivalent to a symmetric quadratic form.
Comment: Ben has pointed out a key point that I managed to forget. This trick allows you to compute all the moments of the distribution. The exact distribution of the quadratic form will still be pretty intractable however if $A+A^T$ has both positive and negative eigenvalues.
Comment: If A isn't symmetric then the distribution isn't "nice" or useful. I doubt there are any references exploring such distributions, because it wouldn't be a rewarding exercise.
Comment: @GordonSmyth What if $A$ belongs to a certain class of matrices (e.g. tri-diagonal matrices). I do not know the name/term for such kind of researches? Are they known as 'special quasi-linear form of normal random vector' or sth like that? Of course I am not expecting any result for a general $A$. Thanks!
Comment: @GordonSmyth That is what I thought of, but is there any result that assert sth for a special class of matrices(permutation matrices, binary matrices)?
Comment: @Ben I do not think what you wrote down make sense to me...could you kindly explain a bit??
Answer: We have that $$x^T A x = x^T (A^T)^T x = (A^T x)^T x = x^T (A^T x) = x^T A^T x,$$ making $$x^T \frac{A + A^T}{2} x = \frac{1}{2} x^T A x + \frac{1}{2} x^T A^T x = \frac{1}{2} x^T A x + \frac{1}{2} x^T A x = x^T A x.$$ Therefore your problem of $A$ not being symmetric is ameliorated since you need only study the properties of the matrix $\frac{1}{2} \left( A + A^T \right)$, which is indeed symmetric. In the theory of quadratic forms, it isn't restrictive to assume that every defining matrix is symmetric: symmetry is just a freebie!
Put the eigendecomposition $A + A^T = U D U^T$ for orthogonal $U$ and diagonal $D$. Define $y = \frac{1}{\sigma} U^T x \sim\mathcal{N}(\frac{1}{\sigma} U^T \mu, I)$. Then, we see that
\begin{align*}
 x^T A x
 & = x^T \frac{1}{2} (A + A^T) x \\
 & = \frac{\sigma^2}{2} y^T D y \\
 & \sim \frac{\sigma^2}{2} \sum_{j=1}^{\mathrm{rank}(A + A^T)} \lambda_j \chi_1^2 \left( \frac{1}{\sigma^2} \|\mu\|_2^2 \right),
\end{align*}
where $\frac{1}{\sigma^2}\|\mu\|_2^2$ is the noncentrality parameter, $\{\lambda_j\}$ is the spectrum of $A +A^T$, and the $\chi^2$ random variables are independent.
Comment: Make sense and thanks a lot... I miss the point! Appreciated.


How can I add a field to a content type which will accept a price value in the format of a currency?

Question: I need to have price field which will display a price field. This field is a number with the dollar sign (i.e. $200). In my view, this price field will be used for sorting also.
I have installed and enabled the currency module and the currency API.
Via structure > content type > manage fields > I tried to add a new field. But the list of field types do not have the 'currency option'. So I am not sure how I should add the currency field with a dollar sign.
My question: How can I add a field to a content type which will accept a price value in the format of a currency?
Answer: UPDATED ANSWER:
using Views field rewrite:
on the field in the view setup, in the "rewrite results" section of the editing modal select the checkbox "Rewrite the output of this field" then scroll down and open the fieldset "REPLACEMENT PATTERNS" and use the pattern there to rewrite your field in the above textarea. as an example to put a "$" in front of the users uid I used $[uid]

CCK field prefix:
You may just want to use a field that is for currency but doesn't actually include the currency symbol, so it can be saved as a number, which allows for better sorting. Then using views you can set a prefix to a displayed field of the desired currency symbol. This may only work with CCK fields.
Comment: Currently, I added a number field 'price'. Now, this field displays in the view. I can sort. I am not sure how I can prefix in the view for this field? If you can provide some details, it will be great. My site: www.bettylist.com/ac/myview
Comment: I think the prefix option is only available for certain CCK fields. I am updating my answer with another method that should work: rewrite the field.
Comment: I am not understanding by rewrite the field. I am new. Can you please provide some info?
Comment: I added an image to help
Comment: Please mark the answer as correct.


vim alternate color/shade of rows/lines based on grouping criteria

Question: I have a file that is similar to the output of md5sum, i.e., it contains rows/lines of the following form:
9803f392bb3f89f1c20bbc9baec8483a /some/path/file1
9803f392bb3f89f1c20bbc9baec8483a /some/other/path/file1
4ca001c5586eb0744e3174bc75c6fba8 /a/certain/path/file2
4ca001c5586eb0744e3174bc75c6fba8 /another/path/file2
4ca001c5586eb0744e3174bc75c6fba8 /some/different/path/file2withadifferentname
78753e869231cc1417a92eebaa076718 /and/so/on/file3
78753e869231cc1417a92eebaa076718 /and/so/forth/file
78753e869231cc1417a92eebaa076718 /something/like/that

Assume the file is sorted according to md5sums (i.e., the first 32 characters). I would like to view this file in vim with alternate coloring of lines, such that same color is assigned to files with same md5sums.
This could be considered a special case of grouping of lines based on some crieteria (in this case the criteria being same string in the first 32 characters compared to previous line).
How could I achieve this?
Answer: Syntax highlighting with multi-line matches might be expensive and noticeably slow down Vim; additionally, I don't know how to get that alternating effect. But it is pretty easy to define folding of those lines that have the same checksum:
:setlocal foldmethod=expr foldexpr=matchstr(getline(v:lnum),'^\\x\\+')==matchstr(getline(v:lnum+1),'^\\x\\+')?1:'<1'

See :h fold-expr for details.


Question regarding "Dark Necessities" by Red Hot Chili Peppers

Question: The song is written in C-minor.
This, to me, means that most of the music will be playable on a E-flat major scale. I understand that not all chords will necesarily be found in this scale (borrowed chords and all), and I understand that with a key change, the scale also changes.
But why would an entire scale change over a simple chord progression without a key change?
At the 2:57 time mark, there is a musical bridge.  During the bridge, the bass-line is simple descending scales (BEAUTIFUL). There are 4 descending scale runs before they repeat all in the key of C-minor:
The first descending scale is over an E flat major chord, and it is a E flat major scale (in Ionian mode - as would be expected from the Key of C minor)
But here things get weird
The second chord is D flat major (a borrowed chord). The descending scale played is a A flat Major scale in Lydian mode (as if the key is now A flat major?).
The third chord is F minor, and the scale played is, again a A flat Major scale (played in Aeolian mode - also as if the key is A flat major)
The last chord is A flat major, and the descending scale played is a A flat Major scale in Ionian mode - also fitting in with a key of A flat major.
Wait...
Please don't tell me I wrote all that just to figure out they modulated from Cminor to Aflat Major using E flat major as a pivot chord?
Nice first question, Antonie...
Comment: I transcribed a video game theme about a month ago that decided it was using scale portions of all 3 of the C natural minor, C Phrygian, and C Phrygian Dominant scales. (Highlights include harmonizing the same Ab-G-F-G-F-E-F-E-Db-C-Bb melody with all 3 of an A-Ab-G-F#-Db descending line, G -> Db chords, and D (unknown fifth) -> G chords.) Things are only ever going to get weirder.
Answer: They didn't modulate. It's a different kind of music theory that some call "modal improvisation". It's very common in jazz solos.
For each chord in a progression, the soloist re-evaluates the scale they are using as the basis for their solo. The main reason to do this is because chord progressions in jazz, and sometimes in pop and rock, are not necessarily diatonic.
Choosing the scale for each chord can be a bit complicated. It depends on the chord, the preceding and following chords, and the melody (implied or explicit). Even though the scales change frequently it is not considered a modulation. One of my teachers said they think of it as "the key of the moment".
Answer: Like so many, you seem to have fallen into believing that diatonics are the only ones that work in a specific key - other notes don't belong. That's just not the case. It may well be a good initation into music, just like kids are told you can't take 6 from 3, which they later find out just isn't the case, but it keeps things 'safe'.
It's probably true that a lot of music is diatonic, but some isn't, therefore there's no rule saying it should be. The modal mix, borrowing, etc., are jusst ideas humans have come up with to explain what could be happening in certain circumstances - which happen quite a lot !
There's nothing to stop a composer writing whatever he wants. Some of it won't sound good, but it won't necessarily sound bad when it goes off-key diatonically, particularly in minor keys, where there's a bigger choice of notes than major. When there's a 'foreign' chord, the melody will usually follow the notes from that chord (which usually happens in most pieces anyhow), so it's not surprising you find this in 'Dark Necessities', and thousands of other songs.


A particular Poisson Compound process with drift

Question:
$c_1,c_2 \geq 0$
$\lambda_1, \lambda_2 >0$
$\alpha_1, \alpha_2 <0$
$\nu$ is a measure with density on $\mathbb{R}^{*}$ with respect to Lebesgue measure
$\nu(x)= \dfrac{ c_1  }{ |x|^{1+ \alpha_1} } e^{ - \lambda_1 |x|} \mathbb{1}_{x<0}
+  \dfrac{ c_2  }{ x^{1+ \alpha_2} } e^{ - \lambda_2 |x|} \mathbb{1}_{x>0}$
$X$ is the Levy process with characteristic $(0, \nu , \gamma)$
$\gamma$ real ? not defined in the exercise .

Show that $X$ is a Poisson compound process with drift
What is the intensity of the Poisson process and the distribution of the jumps
Under which conditions is the process increasing ?
What is the limit a.e. of the process.

$\gamma t$ is the drift
It is a Compound process, because $\nu$ is bounded.

The jumps take values in ${\mathbb{ R}_{-}}^{*}$ and ${\mathbb{ R}_{+}}^{*}$ with respective distributions $ h_1(x)=\dfrac{ c_1  }{ |x|^{1+ \alpha_1} } e^{ - \lambda_1 |x|}$ and
$h_2(x)=\dfrac{ c_2  }{ x^{1+ \alpha_2} } e^{ - \lambda_2 |x|}$

Let $\pi$ the distribution of the jumps, we have $ \nu =K \pi$.
$\pi$ is a density distribution.
We compute $\int_{ \mathbb{R}\ \setminus{0} }\nu(x)dx$
According to this computation, we obtain
$r=c_1 \lambda_1^{\alpha_1} \Gamma( -\alpha_1) +c_2 \lambda_2^{\alpha_2} \Gamma( -\alpha_2)$
$r$ is the intensity of the compound process.
The jumps have density $\dfrac1r ( h_1 +h_2) $

The process is increasing if $c_1=0$
Answer:
$X(r)=X_1+\cdots+X_{N(r)}$
$r=r_1+r_2=c_1\Gamma(-\alpha_1)\lambda_1^{\alpha_1}+c_2\Gamma(-\alpha_2)\lambda_2^{\alpha_2}$
$\lim_{t\to \infty}\frac{X(rt)}{rt}=\lim_{t\to \infty}\frac{X(rt)}{N(rt)}\times \frac{N(rt)}{rt}=\mathbb{E}(X_1)=r_1\frac{\alpha_1}{r\lambda_1}-r_2\frac{\alpha_2}{t\lambda_2}$

Indeed $N(rt) \sim \mathcal{P}(r t)$ so $\frac{N(rt)}{rt} \to 1$
So if $\mathbb{E}(X_1)>0$ then $X(rt) \to \infty$


Modifying model data before sending response

Question: I am working on a back-end that needs to re-calculate the price based on user-specific currency.
I fetch all required records from the database as following:
 $tasks = Task::with([
            'images' => function($query){},
            'price' => function($query){},
            'user' => function($query){ $query->with('images');},
        ])->whereDoesntHave('tasksState', function($query) use ($user){
            $query->where('user_id', $user->id);
            $query->where('state', '<>', 0);
        })->where('id', '>', $offset)->where('user_id', '<>', $user->id)->take($limit)->get();

Task's price model consists of currency and value attributes.
Then I iterate through $tasks and re-calculate the price based on the user-specific currency:
foreach ($tasks as $k => $task){
            $price = $task->price->value;
            $price = $price * $rate->getValue();
            $tasks[$k]->price = $price;
            //$task->price = $price;
        }

After inspecting the tasks, all price are re-calculated correctly.
However when I subsequently serialize $tasks and send it as a response, it contains the data as they were fetched from the database - no re-calculated prices.
Does anybody where is the problem? Any ideas will be greatly appreciated!
Answer: Since you're serializing the data anyway, you can first convert collection into an array and work it as with an array:
$tasks->toArray();

In this case you'll be able to override original data as you've tried to accomplish with foreach loop.
As alternative, you could create a mutator which will add calculated_price property to the collection.
Comment: Thank you! I had to pick between two correct answers and @Amit Gupta's had it more complete. I gave you at least vote up :-)
Answer: You can use Eloquent Mutator for this.
Create following function in Task Model
public function getNewPriceAttribute($value)
{
  ...// do your processing here
}

And then you can use it as:
$task->new_price;

After creating the accessor, add the attribute name to the appends property on the Task model.
 protected $appends = ['new_price'];

Once the attribute has been added to the appends list, it will be included in both the model's array and JSON representations.


Definir porta automaticamente docker

Question: Estou utilizando docker para desenvolver minhas aplicações web, mas percebi que preciso rodar vários projetos ao mesmo tempo em minha máquina. Como esses projetos necessitam basicamente dos mesmos containers, que são o apache e o mysql, sempre que inicio algum projeto em minha máquina, preciso ficar alterando a porta do host. Existe alguma forma de eu conseguir definir automaticamente uma porta para o container que desejo criar? Por exemplo, se a porta 80 já estiver sendo ocupada pelo apache de outra aplicação, ele automaticamente aloca outra porta para a aplicação a ser iniciada.
Também gostaria de saber se existe como eu configurar a url da aplicação. por exemplo, atualmente eu acesso um projeto meu pelo link: localhost:3000. Existe como eu digitar no meu navegador meuprojeto.com.br e ele direcionar para localhost:3000?
Answer: Se o Dockerfile do seu projeto expor uma porta, basta no docker run usar -P em vez de -p porta:porta para que o docker aloque uma porta válida qualquer dinamicamente na hora de criar o container.
Quando estamos em um docker-compose, no elemento ports, basta definir somente uma porta - "porta" em vez de - "porta:porta" para ter o mesmo resultado.
Comment: Show @Luiz, deu certo essa parte no meu docker-compose, mas para ser possível utilizar a alocação de porta dinâmica, seria necessário configurar uma url para o container, dessa forma o docker-compose iria decobrir qual porta é usada e quando eu digitar no meu navegador, por exemplo, projetoTeste.com, ele acessaria o ip e porta do container.

Definir porta automaticamente docker


Why are odds of a coin landing heads $50\%$ after $'n'$ consecutive heads

Question: I'm trying to understand how the odds of flipping a fair coin $4$ times in a row and landing heads each time is $\frac{1}{2^4}=\frac{1}{16}=6.25\%$;
But at the same time if I've just flipped the coin heads $3$ times my odds of it landing heads a fourth time are $50\%.$ These numbers seem to contradict one another.
I think I figured it out when I was writing this question, but wanted to confirm. Of the 16 possible ways that $4$ coin flips can go, $2$ have $3$ consecutive heads (below). So if I flip heads $3$ times and am about to flip it a fourth, there are two possible outcomes:
$$
% inner array of minimum values
\begin{array}{c|cccc}
\text{series} & 1 & 2 & 3 & 4\\
\hline
1 & T & T & T & T\\
... & ... & ... & ... & ...\\
15 & H & H & H & T\\
16 & H & H & H & H
\end{array}
$$
making the probability of getting a fourth head $= \frac{1 outcome}{2 possibilities} = 50\%$. Is this correct?
Answer: Yep, that's correct!
Here's another phrasing that may make it clearer:
Originally, you have 16 possible options for 4-flip sequences. Both HHHH and HHHT have the probability of 1/16, and so are all the others.
After you've flipped 3 heads, you've narrowed it down to just HHHH and HHHT, and the probabilities are equal.
The probability of HHHH is 1/16. The probability of HHHH given that you've already flipped 3 heads is 1/2. The difference between the scenarios is information - specifically, the information that you've already made some of the flips.
Comment: Thanks! Had I looked up [gamblers falacy](https://en.wikipedia.org/wiki/Gambler%27s_fallacy#An_example:_coin-tossing) on wikipedia it looks like they already did the work for me. Oh well, was probably more fun figuring it out.
Answer: You are correct that the probability of a head on the fourth coin flip (regardless of the three previous outcomes) is $\frac{1}{2}$.
The apparent paradox arises because you are comparing a probability to a conditional probability for events that are not independent. The events in question are the event $A$ of getting 4 heads in a row and the event $B$ of getting heads on the first three flips. Clearly these are not independent events (indeed, if $A$ occurs then $B$ must occur, so $P(B|A)=1 \neq P(B)$). You are comparing $P(A|B)$ to $P(A)$, but we should not expect that these probabilities are equal as $A$ and $B$ are not independent events.
The probability of $A$, i.e., the probability of getting four heads on four independent coin flips is
$$P(A)=P(4 \text{ heads})=\frac{1}{2}\cdot \frac{1}{2} \cdot \frac{1}{2}\cdot \frac{1}{2}=\frac{1}{16}.$$
However, the probability of $A$ given $B$, i.e., the probability of getting four heads on four independent coin flips given that the first three flips resulted in heads is
$$P(A|B)=P(4\text{ heads}|\text{first 3 heads}) = \frac{P(\text{4 heads and first 3 heads})}{P(\text{first 3 heads})}= \frac{\frac{1}{2}\cdot\frac{1}{2}\cdot\frac{1}{2}\cdot\frac{1}{2}}{\frac{1}{2}\cdot\frac{1}{2}\cdot\frac{1}{2}}= \frac{\frac{1}{16}}{\frac{1}{8}}=\frac{1}{2}.$$
Comment: Question: Is this Bayes Theorem?
Comment: Yes, that is how the conditional probability was computed.
Answer: Your explanation is correct, but allow me to elaborate. I'll begin by writing down some formal definitions, and try to explain them. Then, I'll refer to your question.
Lets restrict our discussion to the finite discrete case, i.e. assume that you have a sample space $\Omega$ of finite size. $\Omega$ is the set of all possible outcomes of your experiment, e.g.

If the experiment is tossing one coin, then $\Omega = \{H,T\}$.
If the experiment is tossing four coin, then $\Omega = \{(a,b,c,d) : a,b,c,d\in \{H,T\} \} $.

A probability measure on $\Omega$ is a function $P:\Omega \to [0,1]$ that satisfies $\sum_{\omega \in \Omega} P(\omega) = 1 $, namely a function that gives each possible outcome of the experiment its chance of happening. A nice example is the uniform measure, that gives every possible outcome the same probability.
An event in $\Omega$ is just a set of possible outcomes, i.e. $A\subseteq \Omega$ is an event. When we ask for the probability of an event, we ask "what is the probability that the result of our experiment was in A", i.e. $P(A) \triangleq \sum_{\omega \in A} P(\omega)$. Observe that under the uniform measure, we actually get that $P(A) = \frac{|A|}{|\Omega|}$, and that actually might be easier to grasp.
We say that two events $A,B\subseteq \Omega$ are independent if $P(A\cap B) = P(A)\cdot P(B)$. In order to better understand this, consider the following example: If we toss two different fair coins independently, then the sample space is $\{ (H,H),(H,T),(T,H),(T,T) \}$, and since the coins are fair then every outcome has the same probability of $\frac{1}{4}$. Furthermore, since the coins are fair then:

The probability of the first coin landing on $H$ is $\frac{1}{2}$, i.e. $P(\{(H,H),(H,T)\}) = \frac{1}{2}$.
The probability of the first coin landing on $T$ is $\frac{1}{2}$, i.e. $P(\{(T,H),(T,T)\}) = \frac{1}{2}$.
The probability of the second coin landing on $H$ is $\frac{1}{2}$, i.e. $P(\{(H,H),(T,H)\}) = \frac{1}{2}$.
The probability of the second coin landing on $T$ is $\frac{1}{2}$, i.e. $P(\{(T,T),(T,T)\}) = \frac{1}{2}$.

We get that: $P($first coin $H$ and second coind $T) = $P($first coin $H) \cdot P($second coind $T)$. This captures the intuition that if the coins are tossed independently of one another then their outcomes should not "impact" each other.
The last definition I want to write is the definition of conditional probability. Suppose $A,B\subseteq \Omega$ are two events. The conditional probability of $A$ given $B$ tries to capture the following case: suppose I conducted my experiment and got a result, and you want to guess what result I got. More specifically, you want to guess whether or not I got a result within $A$. If I don't give you any other information, your best guess would be that in probability $P(A)$ the result is in $A$. However, I'm telling you that the result was in $B$. So now you know that my result wasn't just any result in $\Omega$, I've actually "narrowed" down your feasible sample space. Now I'm asking "given that the result was in $B$, what's the probability that it's also in $A$?". The intuition would say: $P(A|B) = \frac{|A\cap B|}{|B|}$ (read: the probability of $A$ given $B$ is ...), and in fact this is exactly the case of the uniform measure! In the general case, $P(A|B) = \frac{P(A\cap B)}{P(B)}$, as long as $P(B)>0$.
Actually, considering the definition of conditional probability, we get another, maybe more intuitive definition of independence of events: Two events $A,B \subseteq \Omega$ are independent if $P(A|B) = P(A)$, i.e. I can either tell you that the result of the experiment was in $B$ or not, and that won't change the probability of the result being in $A$.
That concludes the definition section.
Now, let's tend to your question.
In your experiment, you toss four fair coin independently. That, combined with the explanation above, gives us that $\Omega = \{(a,b,c,d) : a,b,c,d\in \{H,T\} \} $ with the uniform probability measure that gives every possible $(a,b,c,d)\in\Omega$ the same possibility of occurring, $\frac{1}{16}$.
You have presented two different questions. The first one was "What is the probability of getting 4 Hs in a row?". The answer to that is, as I mentioned above, $\frac{1}{16}$. The second question was: "Given that I've got 3 Hs, what's the probability that I also get the fourth H?". Using the notations above:
$P($fourth $H| 3$ consecutive $H) = P(\{(H,H,H,H)\}|\{(H,H,H,T),(H,H,H,H)\})$
Since we are considering the uniform measure, then the we can use the expression I wrote above, and get that:
$P($fourth $H| 3$ consecutive $H) = \frac{|\{(H,H,H,H)\}\cap\{(H,H,H,T),(H,H,H,H)\}|}{|\{(H,H,H,T),(H,H,H,H)\}|} = \frac{1}{2}$.
That is the formal way of explaining what you claimed.
Hope that helps ☺


Interpret contradicting output of lmer model with categorical interaction in R

Question: I am struggling to interpret my output in R. It does not make sense to me.
I first regressed participants' ratings (= value) on manipulations (= variable: H high, AI high, H low, AI low, and control). I then checked whether this effect is moderated by the participants' experience (= Frequency :7 groups, the higher, the less experience). Frequency was added as an interaction factor in my model:
H4_mod <- lmer(value ~ variable * Frequency + (1|subject), data =
  ANALYSIS_long, REML = FALSE)

Then, in order to find out whether the interaction effect is statistically significant, I compared the H4_mod with a reduced model:
red_H4_mod <- lmer(value ~ variable + Frequency + (1|subject), data =
  ANALYSIS_long, REML = FALSE)

An ANOVA and a look at cAICs revealed that the interaction is statistically significant. So far, so good.
Now, I want to find out what the effect looks like. I predicted that the higher the experience, the lower the effect of the prediction (value ~ variable).
I get confused with the output I get from
summary(H4_mod)

Fixed effects:
                               Estimate Std. Error         df t value Pr(>|t|)
    (Intercept)               6.846e+00  2.872e-01  8.334e+02  23.839  < 2e-16 ***
    variable[T.2]             9.542e-01  3.223e-01  1.032e+03   2.960 0.003145 **
    variable[T.3]            -8.000e-01  3.223e-01  1.032e+03  -2.482 0.013226 *
    variable[T.4]             1.104e+00  3.223e-01  1.032e+03   3.426 0.000638 ***
    variable[T.5]            -1.154e+00  3.223e-01  1.032e+03  -3.581 0.000359 ***
    Frequency2                3.310e-01  3.739e-01  8.334e+02   0.885 0.376362
    Frequency3                5.490e-01  3.650e-01  8.334e+02   1.504 0.132893
    Frequency4               -5.164e-01  5.615e-01  8.334e+02  -0.920 0.358013
    Frequency5                2.875e-01  6.421e-01  8.334e+02   0.448 0.654468
    Frequency6                5.417e-02  6.043e-01  8.334e+02   0.090 0.928602
    Frequency7               -1.156e+00  5.295e-01  8.334e+02  -2.183 0.029329 *
    variable[T.2]:Frequency2 -3.397e-01  4.197e-01  1.032e+03  -0.809 0.418551
    variable[T.3]:Frequency2 -4.087e-01  4.197e-01  1.032e+03  -0.974 0.330432
    variable[T.4]:Frequency2 -5.592e-01  4.197e-01  1.032e+03  -1.332 0.183033
    variable[T.5]:Frequency2 -2.545e-01  4.197e-01  1.032e+03  -0.606 0.544378
    variable[T.2]:Frequency3 -5.901e-01  4.097e-01  1.032e+03  -1.440 0.150082
    variable[T.3]:Frequency3  5.128e-03  4.097e-01  1.032e+03   0.013 0.990015
    variable[T.4]:Frequency3 -4.837e-01  4.097e-01  1.032e+03  -1.181 0.238045
    variable[T.5]:Frequency3  2.875e-01  4.097e-01  1.032e+03   0.702 0.482980
    variable[T.2]:Frequency4  3.407e-02  6.303e-01  1.032e+03   0.054 0.956904
    variable[T.3]:Frequency4  2.471e-01  6.303e-01  1.032e+03   0.392 0.695154
    variable[T.4]:Frequency4  2.841e-01  6.303e-01  1.032e+03   0.451 0.652301
    variable[T.5]:Frequency4  1.025e+00  6.303e-01  1.032e+03   1.626 0.104285
    variable[T.2]:Frequency5 -5.708e-01  7.208e-01  1.032e+03  -0.792 0.428548
    variable[T.3]:Frequency5 -2.250e+00  7.208e-01  1.032e+03  -3.122 0.001848 **
    variable[T.4]:Frequency5 -1.288e+00  7.208e-01  1.032e+03  -1.786 0.074342 .
    variable[T.5]:Frequency5 -1.413e+00  7.208e-01  1.032e+03  -1.960 0.050295 .
    variable[T.2]:Frequency6 -1.970e-01  6.783e-01  1.032e+03  -0.290 0.771525
    variable[T.3]:Frequency6 -9.714e-01  6.783e-01  1.032e+03  -1.432 0.152417
    variable[T.4]:Frequency6 -3.327e-01  6.783e-01  1.032e+03  -0.491 0.623863
    variable[T.5]:Frequency6 -1.203e+00  6.783e-01  1.032e+03  -1.773 0.076448 .
    variable[T.2]:Frequency7  3.658e-01  5.944e-01  1.032e+03   0.616 0.538350
    variable[T.3]:Frequency7 -6.000e-02  5.944e-01  1.032e+03  -0.101 0.919610
    variable[T.4]:Frequency7  2.583e-02  5.944e-01  1.032e+03   0.043 0.965340
    variable[T.5]:Frequency7  4.742e-01  5.944e-01  1.032e+03   0.798 0.425178
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Can someone explain it to me? The intercept is my control manipulation ("variable"), but what happened to Frequency 1? I read that only the Frequency 7 group has a significant impact on the relationship (value ~ variable). When I look further down at the (what I think) actual interaction effects, these are only significant for Frequency 5.
Furthermore, I tried to figure out the relationships by looking at an effects plot
e <- allEffects(H4_mod)
plot(e, multiline = TRUE, confint = TRUE, ci.style = "bars")

Unfortunately, this confuses me even more...
Can someone help me interpreting the results? So far, I can only say that Frequency significantly interacts with the value ~ variable relationship. But I would love (and have) to make a statement about the direction.
THANK YOU!
Comment: You have used the [tag:effects] tag which refers to a specific R package (not to effects in general). If the tag does not belong here, I suggest to remove it.
Comment: Hej, thank you! For the effects plot, I used the effects package :)
Comment: OK, then my comment is irrelevant.
Answer: This is really quite simple, the only issue is that you've fallen into the trap of categorizing ordinal values simply because they are ordinal. It's not surprising that the the global test of (5-1) * (7-1) = 24 fixed effects representing the high dimensional interaction is statistically significant, the chance for overfitting and small sample bias is high. Even the plot, which in most cases would be an intelligent summary of such high dimensional output (because it shows Frequency continuously), shows massively overlapping CI bounds.
If you want a simple and easy to interpret output, consider fitting the Frequency and Variable measures as numeric instead. Be sure that the numeric value actually corresponds to the observed level. This gives you a more powerful and more interpretable test.
Comment: Hi AdamO, thank you! I will try that!


Print output until key pressed

Question: This seems like a simple problem, but I can't seem to solve it. I need to print output (from a variable) to the console, until the user presses any key. The printing is done in a while loop as such:
int i;
while((i=input.read())!=-1){
  System.out.print((char)i);
}
input.close();

The problem is that the input stream never reaches it's end, only waits for more characters to come in, thus blocking any more code from executing. It will be quite obvious to the user when to stop the output, so I am fine with giving that responsibility to the user. It doesn't matter how the user tells the application to stop, as long as it is quick, (eg pressing space, enter, or any other specific key is fine).
Thanks in advance,
vikarjramun
Answer: The first solution I came up with was threading the console input. The thread updates a variable accessable by the printing code so you can check it before each print statement.
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

public class RunUntilKeyPressed {
    static AtomicBoolean hasUserPressedKey = new AtomicBoolean(false);

    public static void main(String[] args) {

        Thread t = new Thread(() -> {
            Scanner scan = new Scanner(System.in);
            System.out.println(scan.next());
            hasUserPressedKey.set(true);
            scan.close();
        });
        t.start();

        while(!hasUserPressedKey.get()) {
           System.out.println(hasUserPressedKey);
        }
    }
}

This code will run until the user presses Any Key (except space) and Enter as that is when the scan.next() method gets input.
Comment: This code might not work correctly unless you delcare hasUserPressedKey  as volatile or use AtomicBoolean instead of plain boolean
Comment: @vikarjramun If this solved your problem, please mark it as correct for others :)

Print output until key pressed


Stationary distribution for directed graph

Question: I want to implement the algorithm of graph partitioning of sparse directed graph.
In this algorithm after computing the transition matrix ,we should compute the stationary distribution of the random walk. I don't know how to compute the stationary distribution of random walk in  such sparse directed graph.Is there any suggestion?
Answer: If I understand the problem correctly, you need to construct a transition probability matrix $P=(p_{ij})$ where the probability $p_{ij}$ of transitioning from vertex $i$ to vertex $j$ is $1/\mathrm{deg}^{\mathrm{out}}(i)$, where $\mathrm{deg}^{\mathrm{out}}(i)$ denotes the out degree of vertex $i$.  One you have $P$, the stationary distribution (if it exists) is the eigenvector corresponding to eigenvalue $1$; the eigenvector is normalised so that it sums to $1$.
Here's a simple worked example.  For the graph:

the transition probability matrix is $$P=\left(\begin{array}{ccc} 0 & 1 & 0 \\ \tfrac{1}{2} & 0 & \tfrac{1}{2} \\ 1 & 0 & 0 \\ \end{array}\right).$$  Here the stationary distribution is the eigenvector $$\vec{v}=(\tfrac{2}{5},\tfrac{2}{5},\tfrac{1}{5})$$ since $\vec{v}P=\vec{v}$.
Comment: Thanks a lot for your answer and clear example :). I use the eig(p) instruction of Matlab to compute the eigen vector of your example but the result is not the same as your result,Is there a specific point?Thanks again.
Comment: Does this property(I mean the stationary distribution is proportional to left eigenvector corresponding to eigenvalue 1 ) true for every type of graph such as directed or undirected,strongly connected or sparse, periodic or aperiodic, or just for strongly connected aperiodic graph which has unique stationary distribution?
Comment: If Matlab's results are different (I don't use this package myself), then it's probably either giving you $(1,1,\tfrac{1}{2})$, or something similar, which, when normalised gives $(\tfrac{2}{5},\tfrac{2}{5},\tfrac{1}{5})$, or that it gives $(1, 1, 1)$, which is the eigenvector of $P^T$ rather than $P$.
Comment: Undirected graphs are equivalent to directed graphs with edges pointing in both directions (so it'll work for undirected the same as directed).  It will work in all strongly connected aperiodic cases (e.g. these lecture notes ([.pdf](http://www.dis.uniroma1.it/~leon/didattica/webir/pagerank.pdf)) make this argument).
Comment: Thanks:) for answer and lecture.I also saw this lecture but as mentioned in this lecture "I present a concise proof of the **existence** and **uniqueness** of the limit distribution of an **ergodic Markov chain**."and in lecture [Randomness and Computation](http://people.csail.mit.edu/ronitt/COURSE/S12/handouts/lec8.pdf)  A Markov chain M is **ergodic** if and only if:1.The graph GM is irreducible: For every large enough n, there is a positive probability path of length n between any two states.2.The graph GM aperiodic: The GCD of the lengths of positive probability cycles of GM is 1.
Comment: Do you have any suggestion? The result of Matlab is very different!!!The vector corresponding to eigen value 1 for all of transition matrix is vector with only one constant value.for example for your example the response was(-0.5774,            -0.3780 + 0.3780i,   -0.3780 - 0.3780i  ;  -0.5774,    0.0000 - 0.3780i,     0.0000 + 0.3780i  ;-0.5774,   0.7559 ,   0.7559)
). As you see in the result the value -0.5774 is repeated in the vector corresponding to eigen value 1.I tested it for different transition matrices and the results were the same (I mean constant numbers repeated in vector).
Comment: No idea sorry, not familiar with Matlab.  If you use [GAP](http://www.gap-system.org/) instead, typing `M:=[[0,1,0],[1/2,0,1/2],[1,0,0]];` followed by `Eigenvectors(Rationals,M);` gives `[ [ 1, 1, 1/2 ] ]`.
Comment: Thanks. Did you see my previous comment about lecture? any idea?!Thanks again.


Getting type error in open3d Invoked with 100000,0.999

Question: TypeError: init(): incompatible constructor arguments. The following argument types are supported:
1. open3d.cpu.pybind.pipelines.registration.RANSACConvergenceCriteria(arg0: open3d.cpu.pybind.pipelines.registration.RANSACConvergenceCriteria)
2. open3d.cpu.pybind.pipelines.registration.RANSACConvergenceCriteria(max_iteration: int = 1000, max_validation: int = 1000)
Invoked with: 100000, 0.999
I am getting this error while running the file. I am doing the global registration of open 3d documentation. I am not able to solve this error. I have also updated the version of python and open 3d then also it is not working. can anyone help?
Comment: Hi! Could you please provide the content of file you running as well?
Answer: Depending on the version of open3d, the type of the second parameter of open3d.cpu.pybind.pipelines.registration.RANSACConvergenceCriteria changes:

Until open3d 0.11.1, it expects an int max_validation:

__init__(self: open3d.cpu.pybind.pipelines.registration.RANSACConvergenceCriteria, max_iteration: int = 1000, max_validation: int = 1000) -> None

From open3d 0.12.0, it expects a float confidence:

__init__(self: open3d.cpu.pybind.pipelines.registration.RANSACConvergenceCriteria, max_iteration: int = 100000, confidence: float = 0.999) -> None

Make sure you have indeed updated the version of your open3d.


Como posso ordenar um resultado no Laravel com um attributo personalizado da minha model?

Question: A minha tabela real é muito grande, então irei usar este exemplo que encontrei na internet para ficar mais fácil de explicar meu problema (fonte).
Campos da tabela:

first_name
last_name
email
password
created_at
updated_at

No Laravel podemos personalizar nossos campos na model, como por exemplo (assim conseguimos resgatar o nome completo do usuário):
function getFullNameAttribute()
{
  return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}

Assim ao utilizar a model, eu consigo resgatar o nome completo desta forma:
$user = App\User::find(1);
echo $user->full_name;

Podemos fazer uma pesquisa desta forma:
$users = User::orderBy('name')->get();

Mas se eu tentar fazer uma pesquisa pelo nome completo:
$users = User::orderBy('full_name')->get();

Eu não vou conseguir, já que ele não vai encontrar o campo 'full_name' no meu banco, então para contornamos isso fazemos o seguinte:
$users = User::get()->sortBy('full_name');
return $users;

E ai que entra o meu problema, quando você executa o seguinte comando:
$users = User::orderBy('name')->limit(3)->get();

Ele resgata do banco somente 3 valores, mas se eu executar o seguinte comando:
$users = User::get()->sortBy('full_name')->take(3);

Ele pega todos os usuários do banco e depois ordena e então pega os 3 valores, ocasionando lentidão, já que ele busca todos os valores para depois fazer o filtro.
Como posso ordenar um resultado no Laravel com um attributo personalizado da minha model?
Answer: Resposta curta: Não tem jeito.
O banco só entende o que realmente está no banco.
O único jeito é replicar a funcionalidade do atributo customizado na sua query. No  seu caso, você precisa  usar o CONCAT do SQL. E pra usar essas funções, você precisa usar orderByRaw.
Seria isso:
User::orderByRaw("CONCAT(first_name, ' ', last_name)")->limit(3)->get();

Comment: Bom, espero que alguém consiga encontrar essa solução pra você :)
Comment: Eu coloquei apenas como exemplo este código, para ficar mais simples de explicar, mas o campo ao qual eu quero fazer esta comparação tem diversos teste, e o código ficaria gigantesco se fosse fazer desta forma.
Comment: Pois então,  não tem como você passar uma propriedade computada pelo Eloquent pra sua query.
Comment: O jeito vai ser trazer todos os registros e filtrar depois. Mas talvez há alguma coisa mais óbvia na tabela que te permite reduzir a quantidade de registros que vc vai ter que trazer antes de rodar os filtros.
Comment: Muito obrigado, mas vou esperar mais um pouco, quem sabe alguém saiba a resposta.
Comment: https://stackoverflow.com/questions/45586280/ordering-by-a-custom-attribute-in-laravel-5-model
Comment: Eu vi este link, a solução que ele deu e exatamente como descrevi na pergunta, ele pega da collection.
Comment: Pois é, coloquei o link pra reforçar que é impossível fazer o que você tá tentando fazer.
Comment: De qualquer forma eu vou esperar, porque já tive experiências aqui no stack de perguntas "impossíveis" e chega alguém e da uma resposta genial, como esta: https://pt.stackoverflow.com/questions/240236/como-executar-um-script-sem-me-preocupar-com-caracteres-especiais
Answer: Não pode utilizar um dado computado na SQL do seu banco de dados, mas, se pode utilizar duas vezes o orderBy e solucionar esse problema da seguinte forma:
$users = User::orderBy('first_name')
              ->orderBy('last_name')
              ->limit(3)
              ->get();

uma outra forma é criar uma visão com concat juntando as duas informações e fazer uma busca simples pelo Databasedo Laravel, exemplo:
View
CREATE
    VIEW `database`.`view_usuario`
    AS
    SELECT id, CONCAT(first_name, ' ', last_name) full_name FROM usuario

Laravel
\DB::select('SELECT * FROM view_usuario ORDER BY full_name limit 3');

ou
\DB::table('view_usuario')->orderBy('full_name')->limit(3)->get();

Answer: Tinha um datatable e precisava fazer a sua ordenação, mas existiam alguns campos formatados.
Todos os meus campos formatados eu deixei com o padrão "nome_campo_formatted", ou seja, era sempre o nome original mais o "_formatted" no final.
O que fiz para resolver este problema, criei o seguinte método
private function filterField($column)
{
    return str_replace(
        '_formatted',
        '',
        $column
    );
}

Assim quando fosse ordenar, ao invés de utilizar "nome_campo_formatted" eu utilizava "nome_campo" e se caso entrasse um campo que não fosse formatado a função não substituiria nada e funcionária da mesma forma.


Solving Inequality from the proof of First Order ODE.

Question: Let $x'=f(x)$ $x(0)=x_0$ assuming that $|f(x)-f(x)|\le L|x-y|$. We have $x(t)=x_0+\displaystyle\int_0^tf(k)dk$.
Let's say $$x_{n+1}=x_0+\int_0^tf(x_n(k))dk$$ and $$|x_{n+1}-x_n(t)|\le L\int_0^t|x_{n}(k)-x_{n-1}(k)|dk.$$ From that we know that $\max_{t\in[0,\frac{1}{2L}]}|x_{n+1}-x_n(t)|\le0.5\max_{t\in[0,\frac{1}{2L}]}|x_{n}(t)-x_{n-1}(t)|$.
show that max $\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+1}(t) − x_n(t)|≤ \frac{1}{2^{n−1}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$.
By writing $x_n(t) = [x_n(t) − x_{n−1}(t)] + [x_{n−1}(t) − x_{n−2}(t)] +···+[x_1(t) − x_0(t)] + x_0(t)$
deduce that
$\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_n(t) − x_m(t)|≤ \frac{1}{ 2^{N−2}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$
for all $n,m ≥ N$.
It follows that $x_n(t)$ converges to some function $x_∞(t)$ as $n →∞$,and therefore taking limits in both side of $$x=x_0+\int_0^tf(x(k))dk$$ implies that $$x_{\infty}=x_0+\int_0^tf(x_\infty(k))dk$$. Thus $x_\infty(t)$ is the solution of differential equation.
Here is my problem:
I used induction to and got $\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+1}(t) − x_n(t)|≤ \frac{1}{2^{n}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$
instead of $\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+1}(t) − x_n(t)|≤ \frac{1}{2^{n−1}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$.
I don't know if I am wrong but I did check it very strictly. After deducing this inequality in wrong or right way I came to this one which is something I don't understand how to derive it from
$\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_n(t) − x_m(t)|≤ \frac{1}{ 2^{N−2}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$
And I skipped it but I want this to be solved too so how do I solve it?
Also it says as $n$ approaches $\infty$ you will get to the solution my tought is the inequality's $N$ will become larger and larger so $x_n(t)$ will reach $x_m(t)$ may be it means this by it?
Can anyone explain how to solve this? If I have done any typos on the question pleaselet me know. I derived this from my memory. Thanks for taking time to read and Good luck!
Comment: What are your original question ?
Comment: Yes I mean, is the original question to find a solution or to provide a proof of the exiztence of a solution?
Comment: @EDX what do you mean by original question? Is there anyway the question seems odd? I hope I can fix it. Thank you.
Comment: Ok I include it in my answer
Comment: @EDX apology for not specifying the inequality I mean this one $\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+1}(t) − x_n(t)|≤ \frac{1}{2^{n−1}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$
Comment: Yes i add it to my answer
Answer: First question : what do you want to show
In order to obtain the wanted inequality :
$$|x_{n+1}-x_n|=|\int_0^t f(x_n(t))-f(x_{n+1}(t))dt| $$
$$|x_{n+1}-x_n|\leq\int_0^t |f(x_n(t))-f(x_{n+1}(t))|\leq \int_0^tL|x_n-x_{n+1}| dt $$
Noting $$ s_n \triangleq = \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+1}(t) − x_n(t)| $$
Then particularly restrictive $\forall t \in [0,\dfrac{1}{2L}] $
$$s_n \leq L\int_0^ts_{n-1}dt$$
Taking $t=\dfrac{1}{2L}$
$$s_n \leq L\int_0^{\frac{1}{2L}}s_{n-1}dt=\dfrac{s_{n-1}}{2}$$
By iteration
$$ \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+1}(t) − x_n(t)|=s_n \leq \dfrac{s_0}{2^{n-1}}=\dfrac{1}{2^{n-1}}\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)| $$
When you don't know how to cope with things write them  :
$$\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+1}(t) − x_n(t)|≤ \frac{1}{2^{n−1}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$$.
Then let $N>0$, let $n,m>N$
$$ |x_{n+2}-x_n|\leq|x_{n+1}-x_n|+|x_{n+2}-x_{n+1}|$$
So
$$ |x_{n+2}-x_n|\leq\frac{1}{2^{n−1}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|+\frac{1}{2^n} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|$$
So
$$ |x_{n+m}-x_n|\leq\sum_{i=0}^m\dfrac{1}{2^{n-1+k}}\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|=\dfrac{2^{m+1}-1}{2^{m}2^{n-1}}\displaystyle\max_{t∈[0,\frac{1}{2L}]}
|x_1(t) − x_0(t)| $$
Consequently :
$$ \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+m}(t) − x_n(t)|\leq(\frac{1}{2^{n-2}}-\dfrac{1}{2^{n+m-1}}) \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)|\leq \dfrac{1}{2^{n-2}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_1(t) − x_0(t)| $$
So it can also be written because $n>N$:
$$\displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{n+m}(t) − x_n(t)|\leq\dfrac{1}{2^{N-2}} \displaystyle\max_{t∈[0,\frac{1}{2L}]} |x_{1}(t) − x_0(t)|$$
In others words : your sequences is Cauchy for the norm
$$|| \ ||:\to\displaystyle\max_{t∈[0,\frac{1}{2L}]} |f(t)| $$
and $$ (C^0[0,\dfrac{1}{2L}],|| \ ||) $$ is a Banach Space.
So your sequence is convergent because asbolutely convergent and it results that $$ x_{\infty} \triangleq \lim_{n \to \infty} x_n $$ is a solution to your equation on $[0,\dfrac{1}{2L}]$
Hence your results.
I hope it clarify your work don't hesitate for further questions.
Comment: Your iteration works but why don't you double check it since I got $\frac{s_{-1}}{2^{n-1}}$. Anyway it is not necessary. What is necessary is it is cauchy convergent so once again thank you.
Answer: Your first point is correct, if you insert $n=0$ or $n=1$ you want to recover the basic identity or inequality that was just shown. For the proof it makes no difference, it just makes the upper bound twice as large in a majorant sequence that converges to zero.
Then for the Cauchy property you get the same correction, if $n>m\ge N$, then
$$
|x_n(t)-x_m(t)|\le\sum_{k=m}^{n-1}|x_{k+1}(t)-x_k(t)|
\le \sum_{k=m}^{n-1}\frac1{2^k}\|x_1-x_0\|\le\sum_{k=N}^\infty\frac1{2^k}\|x_1-x_0\|=\frac1{2^{N-1}}\|x_1-x_0\|.
$$
Such discrepancies can occur when in the course of writing the text the preference for the increment indices is shifted from $\|x_n-x_{n-1}\|$ to $\|x_{n+1}-x_n\|$ or back.
Comment: Thanks for pointing out mistake :)


Missing my custom ajax field values by image field in node form alter

Question: I have created new content type and added two taxonomy reference field (select list) both referenced to same vocabulary "car" and one Image field with cardinality = 6,
In car vocabulary listed brands and models like:
Brand 1
- model 1
- model 2
- model 3
...
Brand 2
- model 1
- model 2
....

In my content type, first reference select list depth setting is 1, so displays only brands,
In Second reference select list (Models) content_taxonomy_opt_groups => 1,
I have created simple module, for altering on node form and creating custom ajax on Brands and Models select list,
When select a brand, models field displays only models of selected brand...
My ajax has worked
Problem is: when upload an image (Ajax upload) and click Publish this error is shown:
An illegal choice has been detected. Please contact the site administrator.
/**
 * Implements hook_form_FORM_ID_alter().
 */
function car_info_form_car_info_node_form_alter(&$form, &$form_state, $form_id) {
  $brand_options  = $form['car_brand'][LANGUAGE_NONE]['#options'];
  $selected_brand = isset($form_state['values']['car_brand']) ? $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] : key($brand_options);

  $form['car_brand'][LANGUAGE_NONE]['#default_value'] = $selected_brand;
  $form['car_brand'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'car_info_dependent_model_callback',
    'wrapper' => 'dropdown-model-replace',
    'effect' => 'fade',
  );

  $form['car_model'][LANGUAGE_NONE]['#prefix'] = '
';
  $form['car_model'][LANGUAGE_NONE]['#suffix'] = '
';

  if ($selected_brand > 0) {
    $model_options  = _car_info_get_model_dropdown_options($selected_brand);
    $selected_model = isset($form_state['values']['car_model']) ? $form_state['values']['car_model'][LANGUAGE_NONE][0]['tid'] : key($model_options);
    $form['car_model'][LANGUAGE_NONE]['#options'] = $model_options;
    $form['car_model'][LANGUAGE_NONE]['#default_value'] = $selected_model;
  }
  else {
    // Remove default options (All models of brands) if brand not selected
    $form['car_model'][LANGUAGE_NONE]['#options'] = _car_info_get_model_dropdown_options('');
  }

  // $form['#validate'][] = 'car_info_form_car_info_node_form_validate';
}

function car_info_dependent_model_callback($form, $form_state) {
  return $form['car_model'];
}

function _car_info_get_model_dropdown_options($brand_id) {
  if (isset($brand_id)) {
    $car_models_tree = taxonomy_get_children($brand_id);

    $models[''] = t('Select model');
    foreach ($car_models_tree as $model) {
      $models[$model->tid] = $model->name;
    }
  }
  else {
    $models[''] = t('First select brand');
  }

  return $models;
}

function car_info_form_car_info_node_form_validate($form, &$form_state) {
  $car_brand = $form_state['input']['car_brand'][LANGUAGE_NONE];
  $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] = $car_brand;
}

If I dont add image or add image without click on upload button (upload handled when clicked on publish directly) in both way my form is submitted correctly
But if click upload button in image field (Upload handled by ajax), this issue is happened and $form_state['values']['car_brand'] is empty when using ajax image upload.
Answer: In your form an AJAX call is made when your car_brand element is changed but also when upload image button is clicked. Your problem is the AJAX call that is made when upload button is clicked. In that call car_info_form_car_info_node_form_alter() is called, and probably is modifying the allowed options array for the model select element in a wrong way.
In your form altering function check for the element that fired the AJAX call  modifying the select element options only when your first select (brands). You can check for that element in the $form_state['triggering_element'].


Keeping created data in AngularJS

Question: I've a general question about saving data in AngularJS. Are there any opportunities to save data in json files and kept them when you changed the site? I mean when I change the site from "persons" to "home" and go back to "persons" that the created data remain in the list of persons? How can I resolve this? Or is it only possible to do this with a WebApi who is written in Java/C# for example? Does anyone know anything about this?
My example at the current is to push data in the list of json data:
$scope.addItem = function (item) {
  $scope.list.push(item);
  $scope.item = null;
};

Comment: The best way to persist data it's with an API system.. I don't know your case but for example you can use localStorage to persist data into the Browser for a lot of time
Comment: It is only out of interest. Well I can with localStorage keeping the data if I switch the pages, isn't it?
Comment: oh yes! Try this service https://github.com/grevory/angular-local-storage.. I use in my project
Comment: @gianarb Ok thx. I will try this module. Would this also used in REST API applications or do I needn't the localStorage in REST APIs?
Comment: Example.. I use localStorage for user configuration and for save identity after user's login.. I use API to save all my datas.. For example list of persons into the database by API :)
Answer: It depends on how long you're looking to keep the data around, but there are a few options. If you want to share the data between your app, just while a user is on your website, any of the angular "Services" (Factory, Service, Provider) would work as they are all singletons. For more information on the differences, check out this answer: AngularJS: Service vs provider vs factory
If you are looking to persist data across user visits, you should consider using LocalStorage. There is a great angular local storage module here: https://github.com/grevory/angular-local-storage
Answer: I can think of 3 ways to get this
create a custom service
You can utilize a dedicated angular service to store and share data between controllers (services are single instance objects)
service definition
 app.service('commonService', function ($http) {

        var info;

        return {
            getInfo: getInfo,
            setInfo: setInfo
        };

        // .................

        function getInfo() {
            return info;
        }

        function setInfo(value) {
            info = value;
        }
});

usage in multiple controllers
app.controller("HomeController", function ($scope, commonService) {

    $scope.setInfo = function(value){
        commonService.setInfo(value);
    };

});

app.controller("PersonsController", function ($scope, commonService) {

    $scope.info = commonService.getInfo();

});

use local storage
You can use the built-in browser local storage and store your data from anywhere
writing
$window.localStorage['my-data'] = 'hello world';

reading
var data = $window.localStorage['my-data']
// ...

check out this awesome project:
https://github.com/grevory/angular-local-storage

via server api
If you need to persist data among different users, you should save it somewhere in the server side (db / cache)
function getProfile() {
    return $http.get(commonService.baseApi + '/api/profile/');
}

function updateProfile(data) {
    var json = angular.toJson(data);
    return $http.post(commonService.baseApi + '/api/profile/', json);
}

Answer: Dont know if it's what you're looking fort, but un tour controllers you can use the "$rootscope" which is shared between pages (a bit like the session if you want).
You can store data in it like in the $scope, and your controller must take the $rootscope in parameter
Comment: Isn't shared scope considered evil?
Comment: That's possible :P. But it's a solution :P. (maybe outdated or ugly, but i don't know anything else right now :/)
Answer: There are many possible ways to do this.
Either you make use of the $rootScope or create a service for holding global variables.
$rootScope sample
// Angular
angular.module('app', [])
       .controller('PersonsController', function ($rootScope) {

            $rootScope.personsList = [
                {
                    name: 'Eve',
                    gender: 'Female'
                },
                {
                    name: 'John',
                    gender: 'Male'
                }
            ];

       })
       .controller('HomeController', function ($rootScope, $scope) {

            // You even don't need to store it in $scope
            // You just use $root.personsList directly in your HTML

       });

// HTML

{{ person.name }}

{{ person.gender }}

Service Sample
// Angular
angular.module('app', [])
       .service('SharedData', function() {

            var sharedData = {};
            var vm = this;
                vm.Set = Set;
                vm.Get = Get;

            /**
             * Set a shared data identified by its key.
             *
             * @param {String} key - Unique key identifier
             * @param {Any} value - Value to be set
             */
            function Set(key, value) {
                sharedData[key] = value;
            }

            /**
             * Retrieve a shared data.
             *
             * @param {String} key - The key identifier
             */
            function Get(key) {
                if (sharedData[key])
                    return sharedData[key];
                else
                    return null;
            }

       })
       .controller('PersonsController', function (SharedData) {

            var personsList = [
                {
                    name: 'Eve',
                    gender: 'Female'
                },
                {
                    name: 'John',
                    gender: 'Male'
                }
            ];

            SharedData.Set('personsList', personsList);

       })
       .controller('HomeController', function ($scope, SharedData) {

            $scope.personsList = SharedData.Get('personsList');

       });

// HTML

{{ person.name }}

{{ person.gender }}

I haven't tested the code, but I hope you would get the point between them.
Comment: oh, sorry didn't get what you mean.
well, make it as a service.
Comment: Thx :) short question. I've often seen it in tutorials. Why does the "this" in a variable? What's the advantages about this approach?
Comment: You're welcome :), well, service is being instantiated with `new` keyword  unlike factory (though both of them are singletons), so `this` keyword will refer to its own instantiated object. There's nothing much of an advantage, it just makes your code more organized (in my opinion).
Comment: thx for the info :) only one question. Is it better to create a service for CRUD operations?
Comment: yes, very much!
It's a good practice to separate logic from CRUD operations.
Comment: Is it better to create a service or a controller for CRUD? I mean what is recommendable?
Comment: Can you help me in this thread [here](http://stackoverflow.com/questions/30194123/animate-a-div-box-with-angularjs/) ?

Keeping created data in AngularJS


Make the last visible item blurry in owl-carousel

Question: I am using owl-carousel, and i would like to make the last item that is visible, a little blurry. I maked a photo in photoshop, that what i want.

Utalással is fizethető az egészségügyi szolgáltatási járulék

2024-ben havi 11 300 forintot kell fizetniük azoknak, akik nem biztosítottak és más módon sem jogosultak az egészségügyi ellátásra.

                            Elolvasom

2024. évi nyitvatartási idő Pécel Város Óvodáiban

Tájékoztatjuk a Tisztelt Szülőket, hogy a 2024. évben Pécel Város Óvodáiban (PVO) az 1. a heti nyitvatartási idő 60 óra, munkanapokon 6:00 óra és 18:00 óra között.

                            Elolvasom

Még egy hónapig kérhető az szja-bevallási tervezetek postázása

Március 15-étől mindenki megnézheti szja-bevallási tervezetét, legegyszerűbben a Nemzeti Adó- és Vámhivatal (NAV) Ügyfélportálján vagy eSZJA-oldalán.

                            Elolvasom

Képviselő-testületi ülés - 2024. február 28.

Pécel Város Önkormányzatának Képviselő-testülete 2024. február 28. napján (szerda) 8.00 órai kezdettel rendes képviselő-testületi ülést tart, melyre tisztelettel meghívom.

                            Elolvasom

I was searching for this, but didnt find nothing.
Comment: This post should help https://polypane.app/blog/my-take-on-fading-content-using-transparent-gradients-in-css/
Answer: It would have been better if you provided us with your css code as well. Here is an example on how you can set a sort of blur on your last image. You can  use a wrapping div on your image together with a pseudo element and adding an inset box-shadow. Here I selected the last image wrapping div with class .blurry using the css last-child.

.owl-carousel{
  display: flex;
  gap: 10px;
  flex-direction: row;
}

.blurry{
  position: relative;
  height: fit-content;
  width: fit-content;
}

 .item, .item a{
  max-width: 200px;
}

.item:last-child .blurry::before{
  content: "";
  width:0px;
  height: 160px;
  position: absolute;
  top: 0;
  right: 0px;
  overflow: hidden;
  box-shadow: -0px 15px 40px 50px white;
}

Utalással is fizethető az egészségügyi szolgáltatási járulék

2024-ben havi 11 300 forintot kell fizetniük azoknak, akik nem biztosítottak és más módon sem jogosultak az egészségügyi ellátásra.

Elolvasom

2024. évi nyitvatartási idő Pécel Város Óvodáiban

Tájékoztatjuk a Tisztelt Szülőket, hogy a 2024. évben Pécel Város Óvodáiban (PVO) az 1. a heti nyitvatartási idő 60 óra, munkanapokon 6:00 óra és 18:00 óra között.

Elolvasom

Még egy hónapig kérhető az szja-bevallási tervezetek postázása

Március 15-étől mindenki megnézheti szja-bevallási tervezetét, legegyszerűbben a Nemzeti Adó- és Vámhivatal (NAV) Ügyfélportálján vagy eSZJA-oldalán.

Elolvasom

Képviselő-testületi ülés - 2024. február 28.

Pécel Város Önkormányzatának Képviselő-testülete 2024. február 28. napján (szerda) 8.00 órai kezdettel rendes képviselő-testületi ülést tart, melyre tisztelettel meghívom.

Elolvasom


Cannot run program "pip --version" (in directory "."): error=2, No such file or directory

Question: I execute a simple Linux command through aws emr. This command is launched on the nodes of a cluster:
aws emr add-steps --cluster-id j-XXXXXXXXXX --steps Name="XXX",Jar="command-runner.jar",Args=["pip --version"]

or:
aws emr add-steps --cluster-id j-XXXXXXXXXX --steps Name="XXX",Jar="command-runner.jar",Args=["python --version"]

These basic commands give an error:
Cannot run program "pip --version" (in directory "."): error=2, No such file or directory

Cannot run program "python --version" (in directory "."): error=2, No such file or directory

I am sure that at least python is installed on the nodes, because I can execute spark-submit with *.py files.
The only command that I was able to execute was ls.
P.S. The objective of using this approach is to be able to execute some Linux scripts on different nodes of the cluster, e.g. pip install .... That's why I started with making small experiments and was unable to make them working.
Comment: `pip` is not a built-in Linux command, it is an application that may not be installed or your Linux machine. Are you sure it is installed?
Comment: @UnholySheep: If `pip` is not installed, then I expect that the error message would be like `pip: command not found`. The problem is that the error is `Cannot run program "pip --version" (in directory ".")`. Similar error appears even for `cd /usr/`. Only `ls` runs without problems.
Answer: The problem was due to the lack of comma , between the arguments. There should be pip,--version instead of pip --version:
aws emr add-steps --cluster-id j-XXXXXXXXXX --steps Name="XXX",Jar="command-runner.jar",Args=["pip,--version"]

Comment: Are you sure you got that right? `["pip, --version"]` is still a list with a single item.
Comment: @BryanOakley: The resonse that I get with the COPY-PASTE of my answer (putting the correct cluster ID) is `pip 6.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)`. So, I wonder why you downvoted the answer.
Comment: @BryanOakley: By the way, look carefully at my answer. It does not have a space between the comma and `--version`. Your comment is meaningless.


Prove that $2^{66}-1$ is not a prime number

Question: I just started studying Discrete Mathematics and one of the exercises asks to prove that:
$$2^{66} - 1 \textrm{ is not a prime number}$$
The author suggests to use the well know relation:
$$x^2 - 1 = (x + 1)(x - 1)$$
My proof goes as such (please forgive me — and do correct me — if I use any wrong symbol or term). Let's define the set $X$ as:
$$X=\{n\in\mathbb{N}\;|\;n>2\}$$
$\forall x\in X$ we define two numbers:
$$\begin{align}a & = x+1\\ b & = x-1\end{align}$$
Because $x>2$, then $a>1$ and $b>1$. Therefore we have
$$c=a\cdot b$$
which cannot be a prime number, because:
$$\frac{c}{a}=b \quad \textrm{or} \quad \frac{c}{b}={a}$$
This, in my view, is the proof of the theorem.
Could you please let me know if my proof is correct, or if not, how do I prove the theorem?
Thank you very much!
Valerio
Edit: As cited in the comments/answers below, I didn't show the factorisation, so here we go:
$$2^{66}-1=(2^{33}+1)(2^{33}-1)$$
Now I understand I didn't need to use all the steps above, but I was trying to give a general proof, not just for the specific case.
Anyway, thank you all for your answers and showing interest in my question. I didn't expect it to create so much debate! :-)
Comment: I suggest you call $x=2^{33}$
Comment: In your proof, you haven't declared what $x$ is. So it does not addresses the result you want to prove.
Comment: your number is divisible by $3$
Comment: You have indeed proven that if $x$ is an integer greater than $2$ then $x^2 -1$ is not prime.  But you haven't in any way stated what that has to do with $2^{66} -1$ being prime or not.  BTW, there was no reason to introduce the variables $a,b,$ or $c$.  It'd have been enough (and a *LOT* easier to read) if you just said.  $x^2 -1 = (x+1)(x-1)$ and as $x+1$ and $x-1$ are integers that are not equal to $1$, $x^2 -1$ is  not prime.
Answer: Your proof is correct.
Just a little tip - for a problem like this, you don't need to have such a complex proof. It should just suffice to show that
$$2^{66}-1=(2^{33}+1)(2^{33}-1)$$
and then show that
$$2^{33}+1 \ne 1 \ne 2^{33}-1$$
$$2^{33}+1 \ne 2^{66}-1 \ne 2^{33}-1$$
Which should be fairly simple.
But your proof seems fine to me!
Edit: There's one thing that you missed, as @AndrewD.Hwang pointed out in the comments - you have not actually shown that $2^{66}-1$ can be factored in the way that you decided to use.
But that's okay, it's a quick fix!
Comment: @Wildcard: What I meant was, the OP's original proof was incomplete, and therefore the original draft of this answer might have attracted a downvote by claiming the OP's original proof was correct. ;)
Comment: Aww, why the down vote? Whoever it was, please let me know how I can improve my post. :(
Comment: That's the point: OP hasn't shown that $2^{66}-1$ _can_ be factored as stated. (To see that this has not been shown, replace the exponent $66$ by $3$ and try to point to the incorrect step.)
Comment: Ah, I see what you're saying. Okay, thanks! I'll add that to my answer. :)
Comment: I didn't downvote, but what the OP currently has written is not a complete proof: If $2^{66}$ were replaced by $2^{3}$, say, the "argument" would "prove" that $2^{3} - 1 = 7$ is not prime, contrary to fact,
Comment: @AndrewD.Hwang Umm... no, it would not. $2^3-1$ cannot be expressed in the form $(x+1)(x-1)$ where $x$ is a member of the set $X$ described by the OP.
Comment: @AndrewD.Hwang, I don't see where this answer's proof was incorrect.  Or did you mean just the OP's proof?
Comment: @Wildcard He didn't say it was incorrect, just "lacking in thorough-ness". :P
Answer: Beware: overkill. I hope an interesting overkill. Let $\omega(n)$ be the number of distinct prime factors of $n$ and $\nu_3(n)=\max\{m\in\mathbb{N}: 3^m\mid n\}$.

$$2^{66}-1 = (2^{33}-1)(2^{33}+1),\qquad \gcd(2^{33}+1,2^{33}-1)=\gcd(2^{33}+1,2)=1 $$
hence $\omega(2^{66}-1) = \omega(2^{33}-1)+\omega(2^{33}+1)$. Additionally
$$ 2^{33}-1 = (2^{11}-1)(2^{22}+2^{11}+1),$$
$$ \gcd(2^{22}+2^{11}+1,2^{11}-1)=\gcd(3,2^{11}-1)=1 $$
from which $\omega(2^{33}-1)\geq 2$. In a similar way
$$ 2^{33}+1 = (2^{11}+1)(2^{22}-2^{11}+1),$$
$$ \gcd(2^{22}-2^{11}+1,2^{11}+1)=3$$
and since $\nu_3(2^{33}+1)=2$ we also have $\omega(2^{33}+1)\geq 3$ and
$$\boxed{ 2^{66}-1\text{ has at least }\color{red}{5}\text{ distinct prime factors}.} $$

Actually $2^{66}-1$ has $8$ distinct prime factors, and the smallest of them, $\{3,7,23, 67,89\}$, are not difficult to recognize. $2,6,22,66$ are divisors of $66$, so $\{3,7,23,67\}$ are prime divisors of $2^{66}-1$ by Fermat's little theorem. $89$ is a divisor since $89\mid(2^{11}-1)\mid(2^{66}-1)$.
Comment: Way, way, way overkill.  But, yes, interesting and potentially (down the line) useful overkill.  But as is ...way.... overkill.  +1 for being honest.
Answer: Your proof is correct but I have three critiques.
1) You never actually answer the question whether $2^{66} -1$ is prime or not.
Somewhere you need to state that if $n = 2^{33}$ than $2^{66}-1 = n^2 -1$ which isn't prime.  Yes, it's obvious.  But you never actually indicated how what you were proving applies to the question at hand.
(I know... it was obvious and was abundantly clear to you.... but nonetheless, it should be stated.)
2) Adding the variables $a,b,c$ simply obfuscates.
It's more direct to simply say $n^2 - 1 = (n+1)(n-1)$.   So if $n+1$ and $n-1$ are natural number other than $1$ (i.e. $n > 2$) then $(n+1)(n-1) = n^2 -1$ is composite and not prime.
3) You don't actually have to state or prove that $x^2 - 1$ is not prime for $x > 2$.  It's enough to use it as a hint.
The proof can be done in one sentence:
$2^{66} = (2^{33} + 1)(2^{33} -1)$ so $2^{66} -1$ has factors other than itself and $1$ so it is not prime.  QED.
Comment: Thank you for the critique @fleablood. I see why my proof is convulted, though correct. I'm satisfied that I solved the problem and I'll learn to be more concise.
Answer: I'm surprised that there hasn't been a single mention of the term "Mersenne prime" or at least "Mersenne number" in the answers so far. I admit that aside from that detail, the answer I'm going to give is hardly different from the others.
It is a well-known fact that if $2^n - 1$ is prime (a Mersenne prime), then $n$ must itself be prime. And it is also well known that if $n$ is prime, then $2^n - 1$ is not necessarily prime.
In fact, it's much more likely to be composite. $2^{74207281} - 1$ is believed to be the $49$th Mersenne prime, and $74207281$ is itself the $4350601$st prime overall. Suppose they find a hundred Mersenne prime exponents between $37156667$ and $74207281$. That's unlikely, but it would still mean that less than $1\%$ of primes up to $74207281$ are Mersenne prime exponents.
The fact that composite $n$ means $2^n - 1$ is also composite has been known since before Marin Mersenne's time. To use the hint that was given to you, note that $$2^{2m} = (2^m)^2.$$ Since $66 = 2 \times 33$, it follows that $$2^{66} - 1 = (2^{33} - 1)(2^{33} + 1).$$ Clearly $1 < 2^{33} - 1 < 2^{33} + 1 < 2^{66} - 1$, meaning that $2^{66} - 1$ is divisible by positive integers other than $1$ and itself.
Comment: *also raises hand* @Typhon That's right, there's only one Mersenne prime with an *even* exponent: $2^2 - 1 = 1 \times 3 = 3$.
Answer: Hint:
Start with let $2^{66}-1$, Then factor it as follows:
$$2^{66}-1=(2^{33})^2-1=(2^{33}+1)(2^{33}-1).$$
Now proceed from here.


Why can't we play or convert our daily conversation into piano notes?

Question: Why is it that when you hum a song, you can play it on the piano or keyboard, but when make a sentence in English, it is impossible to play or transcribe it into notes?
For example: I can play "lift up the trumpet and loud let ring" because it is a song I know, but I can't play a discussion, conversation, and even a ordinary sentence on the keyboard.
I need somebody to explain the difference between conversation and vocal musica and why a conversation or English sentence can not be made into notes unless it becomes a song.
Comment: You may be interested in Diana Deutsch's [speech to song illusion](https://www.youtube.com/watch?v=p15yotobgmk). You can find more information [here](http://deutsch.ucsd.edu/psychology/pages.php?i=212) at her own website.
Comment: You might also be interested in 'Silbo Gomero', a transposition from speech to whistling.
Comment: This sounds very similar to the question I asked here: http://music.stackexchange.com/q/45593/9426 which has some good answers.
Answer: Excellent question!
The piano can only play certain fixed notes in a particular scale, whereas the human voice can hit any frequency within a certain range (or ranges). There are quite large gaps between the frequencies of adjacent notes on a piano, whereas human speech typically involves much subtler frequency variations than the piano is capable of. It would be possible to get closer to a frequency graph of human speech with an instrument that is not restricted to discrete pitches, such as a fretless bass or an Erhu.
Even then, hitting the correct pitches isn't the only requirement - you'd need to be able to articulate the volume envelope of human speech too. Between those two requirements, it's quite tricky to do, as the typical intonation of most human languages involves both subtle and large variations in both pitch and volume.
Of course there is also the timbral aspect, and the fact that human speech involves some unpitched elements - but if you want to match those as well, you probably aren't going to trying to do so on any traditional instrument (other than the human voice itself, of course!)
Comment: Steve Vai does quite a good job here: https://youtu.be/Z7Asi870JpI
Answer: Funnily enough, it's just like something I do with students sometimes. We have a (slow) conversation, and put each sentence/phrase into a musical phrase. Question and answer. However, it's not easy to translate everything into musical phrases, because we don't speak in poetry, more like prose, so the end product won't come out in a pure musical way. The rhythm may be there, but the melody won't be, and the metre will often be out.


Detect windows phone call click

Question: I have tried giving dialUp     dial Up
This works fine in android phones but doesnot work in Windows.
Any work around for this. I tried onclick.
Even That doesnt work
Answer: There is no embedded "Call Button" in Windows Phones. If you mean to trigger Phone Call task, which will call a number/person, here's how:
<code>PhoneCallTask phoneCallTask = new PhoneCallTask();

phoneCallTask.PhoneNumber = "123456789";
phoneCallTask.DisplayName = "TestNumber";

phoneCallTask.Show();
</code>

Detect windows phone call click


Porting an Excel Optimization Model to R

Question: Apologies straightaway if this question is not appropriate for this forum...I've already been downvoted out of the house on Stack Overflow...
I have built an optimization model at work in Excel....but Excel solver is not the best, to put it kindly. I get a different answer every time I run it...
I'd like to try implementing it in R, both to teach myself a bit and to see if I can get something that is more useful. I'm not a complete R beginner, but I'm not far off.
Here's the setup:
There are a number of projects that the organization may pursue. Each project has

a dollar cost for the complete project
an "importance" weight - these are normalized so that the entire set
sums to 1
a funding level - these are the decision variables, how much funding
do I give it
a "value curve" that translates funding [0%,100%] to value [0,1]

The value curves can be of three types

linear %funding=value i.e. 50% funding = 0.5, 75% funding = 0.75,
etc
exponential - there is a parameter (rho) that describes the shape of
the curve
S-curve

So for a given project, you set a funding level, consult it's value curve to determine where on the interval[0,1] it falls, and multiply that by the weight. This gives you what I call the "realized value".
The model picks funding levels that maximize the sum of the realized values subject to the constraint that you don't go over the dollars available.
Any hints on how to start pursuing this in R?
Comment: The fact that you keep getting different solutions, highlights a problem with your optimization problem. Know that migration to R will not solve this problem
Comment: This is indeed off topic here. It probably could be on topic on [SO] with a [reproducible example](http://stackoverflow.com/q/5963269/1217536). In addition, question that amount to "any hints on how to start..." are too broad.
Comment: I'll delete the question as it wasn't my intent to run afoul of the community rules...I followed a link from https://r-dir.com/community/forums.html to get here...but with regards to the problem, I disagree.  The issue is that the base excel solver keeps converging to local extremes.  My organization has one license for Frontline's Premium Solver for Excel, and given the same spreadsheet it consistently finds roughly the same solution (+/- 0.005%) every time.  But since we only have one license it's on a shared machine that I can't necessarily always access....hence my desire to move to R.
Answer: Since you already have some functionality working in Excel, use devtools to make a working outline of a brand new R package (devtools::create) and to create a unit testing infrastructure (devtools::use_testthat).
Learn how to write unit tests with the testthat and translate the major working functionality of your Excel program into unit tests. You'll have tests like
test_that("Excel component X computes Y", {
  expect_equal(my_r_fn_that_doesnt_exist_yet(1.2, 3, 5), 6.25)
})

After you've got the tests that describe the major functionality, go write the code for these functions one at a time until you pass your tests.


MVC : Loading an array, depending of the selection client side of a drop down list

Question: I would like to do the following thing :
- Loading an array (meaning using EF to filter the result of a request) on my aspx page, depending of the selection, client-side, of my drop down list (containing the id to pass in parameter in my request result).
I suppose Ill have to pass by jquery or something Like that.
I have began to search a solution, like this. I'm not sure Im on the good way to find a solution.
I am quite begginer on MVC and Client side script, so I'm open to any other kind of solution, or any good tutorial, explaining the result of my question.

<% using (Html.BeginForm("Action", "Post")){%>

<%= Html.DropDownList("FK_MET_ID"); %>
<% } %>

(I used the following tutorial to start coding this part of code : http://www.dotnetcurry.com/ShowArticle.aspx?ID=443)
Answer: You are on the right way, you have to add some script to get it working. You need to pass in the selected value, you should add the controller code to the question. Maybe it's more a post than a get but it's out of the scope of this question. What is the datat you return? I think you should use jquery template to show your data.
$(function() {
           $("#FK_MET_ID").change(function() {
              $.get("/Provider/UpdateListProvider/" + $(this).val(), function(data) {

                if (data) {
                    $("#contractsTemplate").tmpl(data).appendTo('#contracts');
                }

                });
            });
        });

EDIT :
The best way is to work with Json, in youre controller you need a method like this one :
[HttpPost]
public virtual JsonResult GetContracts(string nameOfTheVariable)
        {
            var contracts = _session.All<Contract>();//add restriction with the variable
            return Json(contracts);
        }

In youre view you can work with jquery template :

You need to add a custom route in your global.ascx that will point to your controller with the action you want and the param nameOfTheVariable you need or can you can also do it as query parameter yoururl.com$action?nameOfTheVariable="value"
Let me know if you need more help!
Comment: Thanks for your answer. Nevertheless, I have a couple of questions... : 1) I suppose that I ll have to create a controllercode like : ActionRestut UpdateListProvider. But, which name, am I going to give to the incoming variable, coming from "this.val" ? 2) What does function(data) is used for ??? To answer to your question, the data Ill return is going to be an array inside my form, form I dont want to reload fully. (sorry for my english, hope I had been quite clear...
Comment: I added some code, let me know if you are ok with this. For the name you have to add a custom route in global.ascx. function(data) is the function that will be call after the ajax call is made to your controller and the data will be what you returned from it. You can console.log(data) in Chrome's console (ctrl+shift+j) to see what you have in it.
Comment: Thanks a lot VinnyG. After a little bit of search about the JQueryTemplate, we finally found the solution, not totally like yours, but it works. Thanks a lot again :)


Restricting a ssh key to only allow rsync/file transfer?

Question: I have 2 servers (A & B), and I need to rsync files from A to B as root. Allowing root ssh login is possible (PermitRootLogin without-password), but I'd like to lock it down as much as possible. I'm using ssh keys, and (on B) the root ssh key (in /root/.ssh/authorized_keys) is limited to A's IP address (from="x.x.x.x ...").
But how can I lock (this ssh key) down more? Is it possible to restrict that ssh key to only allow rsync/file transfer (and preferably limited to a certain directory)?
Researching this points me to ancient web pages that mention scponly shell, or rrsync script from rsync, or rssh from OpenSSH. But how can I set them up for just that key, without making my entire root account be rssh ?
Comment: Here is an answer demonstrating how to use rrsync: https://serverfault.com/a/915842/117645 rrsync is designed to be used for a particular key, so exactly what you want.
Comment: @MichałPolitowski that looks interesting. Would you like to add that as an answer?
Comment: I usually do not send such reminders, but since you explicitly asked for the answer: was it useful?
Answer: rrsync is designed to be used as a forced command for a particular key, so it should be exactly what you want.
A forced command is set up using the command option for a key in an authorized keys file and is then always run whenever this key is used for authentication, no matter what command the client requested. But it has access to the requested command so it can for example implement a validated, restricted version of it and that's what rrsync does.
You use it like this:
command="/path/to/rrsync -wo /allowed/directory/",restrict,from="a.b.c.d" ecdsa-sha2-nistp521 AAAAE...

Access for this key is limited to rsync to the /allowed/directory/ only.
The -wo (write only) option means that rsync will be only allowed to send to the remote machine, -ro would only allow reading from the remote system, giving no option would allow transfer in both directions.
On the local side when you give arguments to rsync you must give the remote path relative to the allowed directory, so on A you would do eg.
rsync -options /local/path root@B: and not rsync -options /local/path root@B:/allowed/directory/.
See also this answer to a different but related question.
Comment: @aseques Of course it does not, but it can be used to restrict a particular ssh key to only rsync, which this question is about.
Comment: After reading about rrsync it seems that it doesn't disable ssh login, the restrictions only affect to rsync.
Comment: @MichałPolitowski where has this been all my life! Amazing.
Answer: Not a hard restriction on what type of access but perhaps add a password to your key, then use an agent to add the key to your session. That way you will only have to unlock the key once in a session for password-less ssh/scp/rsync access. In the event that its stolen it has a password protecting it from being used.
Create key with passphrase
ssh-keygen -f mykeyfile
#make sure you add a passphrase when asked

Add key to agent before SSH/SCP/RSYNC usage
ssh-add mykeyfile
#enter password here

Comment: Thanks. I'm aware of adding passwords to SSH keys. In this case, a script needs to run every hour or so, and needs to be non-interactive, so I can't have it password protected.


Prove by induction that $\;A^n = PD^nP^{-1}$

Question: Not sure how to prove the following statement.
$$A^n = PD^nP^{-1}$$
I started letting n = 1, so that is true. Then, I let n = 2 and 3. Again true. How should I finish the proof?
Any help is appreciated!
Here is the proof I got. Please make any corrections if needed.
Comment: Do you understand what proof by induction is? (I hope that doesn't sound sarcastic, it's a genuine question!). You need to prove that if $A^{k-1}=PD^{k-1}P^{-1}$ for some $k$, then $A^k=PD^kP^{-1}$.
Comment: What are these $A$, $D$? Nevertheless, if you can prove it for $n=1$ you should do it and additionally prove that if your statement is true for some $n$ (you don't need to prove this fact itself) then it is indeed true for $n+1$.
Comment: @MattPressland I just said that because there was no answer, in fact, as soon as you answered, I delete the comment.
Comment: I don't know if you get notified of this automatically - in case not, I've edited my answer to comment on your attempted solution.
Answer: Let $P(n)$ be a statement depending on a natural number $n$; in your example $P(n)$ is the statement $A^n=PD^nP^{-1}$. The principle of induction says that you can prove all the statements $P(n)$ (as $n$ varies), by first proving $P(1)$ (the base case), and then proving that if $P(k-1)$ is true for some $k\geq2$, then $P(k)$ is true (the induction step).
(Then, for example, if somebody asks you why $P(3)$ is true, you can say that $P(1)$ is true by the base case, so $P(2)$ must be true by the induction step, hence $P(3)$ is true by the induction step again.)
You claim you have proved $P(1)$, i.e. that $A=PDP^{-1}$, so you just have to prove the induction step, i.e. that  if $A^{k-1}=PD^{k-1}P^{-1}$ then $A^k=PD^kP^{-1}$.
Update: to comment on attempted solution
Unfortunately your attempted solution contains several errors - it is probably easiest to comment line by line.

Line 1: This isn't a proof of the base case, but an assertion that the base case is true. You need to actually say something about why it is true.
Line 2: You haven't proved the induction step yet, so you can't conclude anything "by induction". (There is also nothing about $n=2$ that makes it particularly worth commenting on).
Line 3: Again, you haven't proved the induction step yet. If this line was correct, you could stop here!
Line 4: What you've written isn't exactly clear, but it looks like you're assuming the result again. You want to assume that $A^{k-1}=PD^{k-1}P^{-1}$ for a fixed $k$.
Line 5: You aren't allowed to choose $k$; if you set $k=2$ when proving the induction step, you're not proving that $P(k-1)\implies P(k)$ for all $k$, which is what you want, but only that $P(1)\implies P(2)$. So how do you know that $P(3)$ is true?

I will try to summarise the principle again: to prove that $P(n)$ is true for all $n$, you should:

Prove that $P(1)$ is true; in your case, prove that $A=PDP^{-1}$.
Prove that if $k$ is any natural number with the property that $P(k-1)$ is true, then $P(k)$ is also true (written more concisely as "$P(k-1)\implies P(k)$ for all $k$"). In your case this means proving that if $A^{k-1}=PD^{k-1}P^{-1}$ (for some $k$ that you don't know, and are not allowed to choose) then $A^k=PD^kP^{-1}$.

Then you're done.
The reason this works is that once you have proved these things, then you have:
$$P(1)\implies P(2)\implies P(3)\implies\cdots\implies P(n)\implies\cdots$$
in which all of the implications hold by Point 2, and the left-most statement is true by Point 1, so in fact all of the statements are true.