How can I avoid distortion and stuttering in DirectSound?

Question: I have a DirectSound application I'm writing in C, running on Windows 7. The application just captures some sound frames, and plays them back. For sanity-checking the capture results, I'm writing out the PCM data to a file, which I can play in Linux using aplay.
Unfortunately, the sound is choppy, sometimes contains stuttering (and plays at the wrong speed in Linux). Oddly, the amount of distortion observed when playing the capture file is less if the PCM data is not played in the playback buffer at the time of capture.
Here's the initialization of my WAVEFORMATEX:
memset(&wfx, 0, sizeof(WAVEFORMATEX));
wfx.cbSize = 0;
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nChannels = 1;
wfx.nSamplesPerSec = sampleRate;
wfx.wBitsPerSample = sampleBitWidth;
wfx.nBlockAlign = (wfx.nChannels * wfx.wBitsPerSample) / 8;
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign code here

The sampleRate is 8000, and sampleBitWidth is 16.
I create a capture and play buffer using this same structure, and the capture buffer has 3 notification positions. I start capturing with:
lpDsCaptureBuffer->Start(DSCBSTART_LOOPING);

I then spark off a playback thread that calls WaitForMultipleObjects on the events associated with the notification points. Upon notification, I reset all the events, and copy the 1 or 2 pieces of the capture buffer to a local buffer, and pass those on to a play routine:
void playFromBuff(LPVOID captureBuff,DWORD captureLen) {
  LPVOID playBuff;
  DWORD playLen;
  HRESULT hr;

  hr = lpDsPlaybackBuffer->Lock(0L,captureLen,&playBuff,&playLen,NULL,0L,0L);

  memcpy(playBuff,captureBuff,playLen);
  hr = lpDsPlaybackBuffer->Unlock(playBuff,playLen,NULL,0L);
  hr = lpDsPlaybackBuffer->SetCurrentPosition(0L);
  hr = lpDsPlaybackBuffer->Play(0L,0L,0L);
}

(some error-checking omitted).
Note that the playback buffer has no notification positions. Each time I get a chunk from the capture buffer, I lock the playback buffer starting at position 0.
The capture code, guarded by the WaitForMultipleObjects, looks like:
    lpDsCaptureBuffer->GetCurrentPosition(NULL,&readPos);

    hr = lpDsCaptureBuffer->Lock(...,...,&captureBuff1,&captureLen1,&captureBuff2,&captureLen2,0L);

where the ellipses contain calculations involving the current and previously-seen read positions. I'm omitting those likely-wrong calculations -- I suspect that's where the problem lies.
My notification positions are multiples of 1024. Yet the read positions reported are 1500, 2500, and 3500. So if I see a read position of 1500, does that mean I can read from bytes 0 to 1500. And when next I see 2500, does that mean I should read from 1501 to 2500? Why do those read positions not correspond exactly to my notification positions? What's the right algorithm here?
I've tried the simpler alternative of stopping the capture when the capture buffer is full, without other notification positions. But that means, I think, allowing some sound to escape capture.
Answer:
My notification positions are multiples of 1024. Yet the read positions reported are 1500, 2500, and 3500. So if I see a read position of 1500, does that mean I can read from bytes 0 to 1500. And when next I see 2500, does that mean I should read from 1501 to 2500? Why do those read positions not correspond exactly to my notification positions? What's the right algorithm here?

DirectSound API is nowadays a compatibility layer on top of other "real" audio capture API. This means that inside audio capture fills some buffers (esp. those multiples of 500) and then passes the filled buffers to DirectSound capture, which in turn reports them to you. This explains why you see read positions as multiples of 500, because DirectSound itself has data available this way.
Since you are interested in getting captured data, your assumption is correct that you are interested mostly in read position. You get the notification and you know what offset is safe to read up to. Since the capture API is layered, there is some latency involved because layers need to pass chunks of data between one another, before making them available to you.
Comment: I redid my capture buffer calculations, so that now, when I save the capture data to a file, the sound is perfect when playing with Linux aplay -- IF I don't also play the data with the playback buffer in Windows. Somehow, the act of playing data in a separate buffer affects what's captured.
Comment: Some hints: you should be able to find something with debugger and tracing the order of the calls and actions. Perhaps your thread synchronization makes you somehow lose certain loops. For debugging purposes you would want to start with super long capture buffer to make sure you don't have overflows, underflows and stuff. Once things are tuned in this simple scenario, you can change it close to what you eventually want.
Comment: I loaded a WAV file into a buffer, and tried playing it in 2 ways. First, I tried the old-fashioned call sndPlaySound, and that sounded fine. Next, I tried using my DirectSound playback buffer. It sounded choppy and distorted, although it was at the right pitch and speed. Could that be because the emulation layer doesn't work so well?
Comment: I see it this way: if you have a standard/external method that plays captured data smoothly, then the capture itself is fine. If capture is affected by concurrent playback, then I would look into threading issues and deadlocks causing capture to act late. If it is only playback which is giving troubles, then there should be a bug there. Note that with playback you again deal with layered APIs and you have to get the data ready and take your hands off buffered data well in advance (20-30-50 ms) or the data arrives late to real playback and you hear choppiness.
Comment: See related Q [What is the smallest audio buffer needed to produce Tone sound without distotions with WaveOUT API](http://stackoverflow.com/questions/14293749/what-is-the-smallest-audio-buffer-needed-to-produce-tone-sound-without-distotion) for another legacy API and the same applies to DirectSound playback - there is a minimal data pre-loading time and doing less than this is leading to playing segments of silence due to late data arrival.
Comment: It doesn't seem to matter whether the call to Play is in the same thread or another, or whether the Play loops or is finite. It doesn't seem to matter whether the playback buffer has any data written to it, or is left untouched. In all cases, the data in the capture buffer seems to be compromised if Play is called. I verified that the sequences of read positions and capture cursor offsets in the capture buffer are roughly the same for the Play and no-Play situation.


dd() on laravel doesn't echo out

Question: My routes.php
    <?php

Route::group(['middleware' => ['web']] , function() {
    route::get('/' , [
        'as' => 'home',
        'uses' => 'HomeController@index',
        ]);
    Route::post('/' , [
        'uses' => 'HomeController@create',
        ]);
});

and HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class HomeController extends Controller
{
    public function index() {
        return '<form action="'. route('home') .'" method="post"><input type="text" name="email"><input type="submit"></form>';
    }
    public function create(Request $request) {
        dd($request->email);
    }
}

its a form with an input name 'email'  , and when i enter my email it should show me the email i have just entered , its gives me a blank page instead.
Answer: try
dd($request->all()) or dd($request->input('email')

Comment: dd($request->all()); ,   dd($request->input('email')); giving me a blank page too :/
Comment: check you route file, the first get route must be `Route` and not `route`, try again replacing it
Answer: You are using the wrong action in the form
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class HomeController extends Controller
{
    public function index() {
        return '<form action="{{action('HomeController@create')}}" method="post"><input type="text" name="email"><input type="submit"></form>';
    }
    public function create(Request $request) {
        dd($request->email);
    }
}

Also, make sure to place the CSRF token in your forms, if you have the middleware enabled.

dd() on laravel doesn't echo out


Mixing Absolute Positioning, Relative Positioning of DIVS

Question: Okay, I want to achieve the following effect
I have two divs that should be on top of each other. I have a third div that should be directly under the two divs. The first two divs can toggle visibility so that when one is visible, the other is not (note: I removed the toggle on part in the javascript to simplify the troubleshooting). But regardless, the third div should be below the other two. Sounded simple a couple hours ago, but I am missing something and would appreciate your help.
I created a paired down HTML file with only the important parts for you to review and hopefully show me what I am misunderstanding.
Also note that I really don't want to use a top property on div3 as it is possible that I might want to dynamically change the size of the first two divs.
<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

Comment: Need a better description of what is supposed to happen. When I click on it, I get two changes of state.
Comment: Yup, you are seeing each of the first two divs disappear. Once both disappear, I want the third div to move up to fill in the space. this isn't exactly what I am looking to do, but if I understand this more simplified case, I can get to what I really want to do.
Comment: But I do see the third div in the end.
Comment: "I want the third div to move up to fill in the space." If this is unclear, I will try to explain another way: The first two divs take up 100px. I want the third div to move up 100px if the first two are collapsed.
Comment: I'm saying that is what I see. It's 100px tall but not as wide as the other two and takes up the same space as the other two divs.
Comment: That is very odd. I will check this out on another browser and see what I see. I am stuck on a box with only IE 11 and the third div stays stationary no matter what I do.
Comment: Never, EVER use IE as a reference for how things should work. I was using Chrome. It works the same in Firefox.
Comment: I am trying it in Chrome, same behavior. The Blue box does not move up once the other two divs disappear.
Comment: By "move up" do you mean slide up from a lower position into this one?
Comment: Is visibility collapse not a table property? .. It does not work on a div.
Answer: Try this :
<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

DIV 1

DIV 2

DIV3

Comment: Thanks, that is exactly what I am looking for. I changed your code a bit to allow for both div 1 and 2 to disappear and div 3 move appropriately. I voted this as the correct answer and would vote it up but don't have enough reputation yet... So it appears that it is the display:  'block' is what I was missing?
Comment: You used absolute positionning but you want static positionnning. this was the main problem. Check the differences in the CSS code.


Modifying the HTML generated for Menus

Question: I've read the questions already asked but they didn't answer my question. But they were sucessful in confusing me more. There are hooks, render functions of two types, theme functions, pre-processing functions, processing functions. In every question I read over internet the answer is different every time. My head's gonna explode.
Coming to question, I need just the text & href from menu-item or link. I'll handle the rest.
How I want it?
//I need control over the HTML wrapper elements for menu
foreach $menu_items as $menu_item:
    if(has_submenu($menu_item)):
        print "custom html here";
        foreach $menu_item as $sub_menu_item:
            print "custom html here".$sub_menu_item['name'].$sub_menu_item['href']."custome html here";
    endif
    print "custom html here".$menu_item['name'].$menu_item['href']."custome html here";

Comment: No! No! No! enough with marking duplicates. Newbies like me get lost moving from one question to another. The situation changes, question changes & because its asked by someone else, what one knows also changes. Most of the time gets spent on reading others questions only to find out that its not I want or to find its too complicated to understand. Its just too inefficient. I asked a direct question. I need a direct answer please
Comment: We can certainly point you to the right functions/disciplines within Drupal, but I just want to make sure you know that we can't write your full code for you. What I mean is that if an answer to a different question provides the theoretical answer to your question, it will be closed as a duplicate - we don't provide one-one support, so if it's a matter of 'that one works but I want it blue', then it's fair game to be closed as a dupe. I'm not saying this _is_ a dupe (though I suspect it is, this has been asked quite a few times if I recall), just don't be shocked if it does get closed as such
Comment: A bit more info from you would actually be useful in working that out - how is this menu being rendered? Through theme_links in a template file or some other method?
Answer: Try to use: menu_tree_all_data(). It will get a menu tree of your given menu machine name.

Modifying the HTML generated for Menus


Conditional probability with "at least"

Question: We split 8 colored (and distinguishable from each other[each ball is unique]) balls to 4 kids, 2 balls for each kid.
There are 2 blue balls, 2 red balls, 2 yellow balls, 2 green balls [still each ball is unique]

A) It is known that Amy got at least 1 red ball, what is the
  probability that also John got at least 1 red ball?
B) It is known that Amy got balls of different colors, what is the
  probability that also John got balls of different colors?

What I have done is as follows:
A) let A be "Amy got at least 1 red ball"(B the same for John) hence $P(A)=1-{6\over8}*{5\over7}={13\over28}$ (all the cases subtract the case in which the first ball isn't red and also the 2nd isn't red)
So $P(A|B)={{{(2*{2\over8}*{6\over7})}^2}\over{13\over28}}=0.395$
This is because there is $2\over8$ chance to get red ball first and then $6\over7$ chance of getting non red ball, this chance is multiplied by 2 since we could do it the other way around(1st non red 2nd yes red) and then I square it all since the same chance applies to B(John).
I feel like I may have done it too complicated? is it even the right answer? not sure.
B)first ball can be any color $8\over8$ the 2nd ball has to be different than the first so $6\over7$ chance of that.
But now when I tried to find the new(A is now different color balls so is B) $P(A|B)$ I got something weird like that: ${({6\over7}*{6\over7})\over{6\over7}}={6\over7}$ which I really dont feel good about
Answer: We solve the first problem. Let $A$ be the event Amy got at least one red, and $B$ the event John got at least one red. We are asked to find $\Pr(B\mid A)$, which by definition is equal to $\Pr(A\cap B)/\Pr(A)$.
We compute the two required probabilities. You found $\Pr(A)$ correctly. Now we need $\Pr(A\cap B)$. This is the probability Amy and John each got one red.
Imagine that Amy drew a ball, then another, then John drew a ball, then another. The probability Amy got exactly one red is $\frac{2}{8}\cdot \frac{6}{7}+\frac{6}{8}\cdot\frac{2}{7}$, that is, $\frac{24}{56}$.
Given that Amy got exactly one red, the probability John got a red is $\frac{1}{6}\cdot \frac{5}{5}+\frac{5}{6}\cdot \frac{1}{5}$, that is, $\frac{10}{30}$.
Thus $\Pr(A\cap B)=\frac{24}{56}\cdot \frac{10}{30}$. Now we can find $\Pr(B\mid A)$.
It might be a little smoother to use binomial coefficients. For example, the probability that Amy gets exactly one red is $\frac{\binom{2}{1}\binom{6}{1}}{\binom{8}{2}}$.
The second problem is in a sense somewhat easier than the first. Change the meanings of $A$ and $B$ in the obvious way. You can find $\Pr(B\mid A)$ directly, without finding $\Pr(A)$ and $\Pr(A\cap B)$.
Comment: Thanks I was sure that because we are using the conditional formula I shall ignore the fact that something is given when I calculate $P(A \ and \ B)$ because in a sense if I do consider what is given then $P(A \ and \ B)$ is itself what I was looking for without the long formula isnt it? kind of weird when I think about it [we have used the given information inside the intersection already so why shall we divide by $P(A)$ now]
Comment: You are welcome. If the question were: Given Amy got exactly one red, what is the probability John got exactly one red, we could find this (different) conditional probability directly. One red and one non-red are gone, say a blue, and now we can compute for John. (This is an additional hint for the second problem!) What complicates things in the first problem is the possibility that Amy got two red. This kind of forces us to go through the conditional probability $\Pr(A\cap B)/\Pr(A)$ machinery.
Comment: Oh now I see, our intersection says something different indeed. about the 2nd question I thought to say that if Amy got 2 different color balls we now only have 2 sets of same color balls so the only way for John to fail is to get 1 ball from the duplicated set (there are 2 of those) and to take the pair of that ball so its $1-{2\over6}*{1\over5}*2={13\over15}$ is that the shortcut?
Comment: Thanks I at the start did both 4/6 and multiplication by 2 then I thought that its weird so I changed to 2/6 and multiplication by 2 but now I understand how I could use my first 4/6 way (which clicks better in my head)
Comment: I will delete my previous comment, since while I was typing you changed the $4$ to a $2$, and you understand the issues. In the longer run, you will need to use the "binomial coefficient" approach that I mentioned, since tracing all patterns would be too painful.

Conditional probability with "at least"


Number Theory: Product of Power of Two

Question: I'm having trouble solving the following number theory problem in my textbook:

Let a $\in Z$ with $a > 0$. Prove that there exists $k, n \in Z$ with n odd such that $a = 2^k n$

So far I've tried writing $n$ as an odd integer (i.e. n = 2q + 1) and then reducing somehow but that doesn't seem to be the correct way to solve it because I can only prove that $a$ can be even and not odd.
Any help would be appreciated?
Comment: k can be 0. (padding for 30 char minimum ......)
Answer: Prime factorization:
$$a=\prod_{p\in P} p^{e_i}=2^{e_1}\prod_{p\not=2}p^{e_i}=2^k\cdot n$$
where $k=e_1$ and $n$ is a product of odd primes.
Answer: You could use (strong) induction. The result is certainly true for $a=1$. Suppose that the result is true for all positive integers $i \lt a$. We show the result must hold for $a$.
There are two possibilities: (i) $a$ is odd and (ii) $a$ is even.
(i) If $a$ is odd, the result is trivially true for $a$, since $a=2^0a$.
(ii) If $a$ is even, let $a=2c$. Since $c\lt a$, by the induction assumption, the result is true for $c$. That is, there exist $j$, $w$, with $w$ odd, such that $c=2^j w$. But then $a=2^{j+1}w$, so the result is true for $a$.
Comment: is "b" suppose to be "a" in my problem description? Some of the letters are a little confusing.
Comment: You can call it $a$. I somewhat prefer a new letter, but maybe $a$ makes the logic clearer to you.
Answer: I will assume $0\in\mathbb{N}$.
Define $ord_2 : \mathbb{N}\rightarrow \mathbb{N}$ as $ord_2(a)$ is the highest power of $2$ that divides $a$. Since $a$ is a number $ord_2(a)$ will be finite and well-defined. Let $ord_2(a)=k$. You have that $2^k|a$, but by definition $2^{k+1}\nmid a$. Therefore, you can write $a=2^k\cdot n$ from the first conclusion. The second conclusion establishes that $n$ is odd. Your integers therefore are $k=ord_p(a)$ and $n=\frac{a}{ord_p(a)}$.

Number Theory: Product of Power of Two


Find Picard exceptional values

Question: I have a problem with the following task. I need to find (if there are) picard's exceptional values of the function $z^8+\sin ^2(3z)+e^{z^2}$ point $\infty$ of entire function is not exceptional value.
Answer: Let $f(z) = z^8 + \sin(3z)^2 + e^{z^2}$ be the function at hand.
Since $f(\mathbb{R}) \subset \mathbb{R}$, it satisfies
$\overline{f(z)} = f(\bar{z})$. A consequence of this is if $f(z)$ avoids any $\alpha \in \mathbb{C}$, it need to avoid $\bar{\alpha}$ too. Since $f(z)$ can avoid at most one number, this forces $\alpha = \bar{\alpha}$ and $\alpha$ need to be real.
It is not hard to see $f(\mathbb{R}) = [1,\infty)$ and $f(i\mathbb{R}) = (-\infty,1]$. This means $f(z)$ doesn't avoid any real number. As a result,$f(z)$ doesn't avoid any complex number.
Comment: What about point zero? I think that there is no point on $i \mathbb{R}$ for which $f$ is equal to zero
Comment: So for $f(\mathbb{R}) \subset \mathbb{R}$ it is easy to show. I have a problem with the second one
Comment: Notice $f(iy) = y^8 - \sinh(3y)^2 + e^{-y^2}$. We have $\lim_{x\to\infty} f(x) \to \infty$ and $\lim_{y\to\infty} f(iy) = -\infty$. Since $f(0) = 1$ and $f(x), f(iy)$ are continuous, IVT tell us $f(\mathbb{R}) \supset [1,\infty)$ and $f(i\mathbb{R}) \supset (-\infty,1])$. They are actually equal but this is strong enough to deduce $f(\mathbb{R}) \cup f(i\mathbb{R}) = \mathbb{R}$.
Comment: So why intermediate value theorem formally holds for complex case? In my course there wasn't such proposition , so I wondering why is this true. Of course we can represent our function as sum of two real-valued functions for which theorem holds
Comment: Along the real and/or imaginary axis, $f(z)$ is real and you can apply IVT there.
Comment: Oh, I forgot about the generalization of IVT

Find Picard exceptional values


I want to play guitar but I can't bend the tip of my index finger

Question: I have never played guitar but I want to start. I love how you can make sounds that you can almost feel. I'm just worried that not being able to bend my left index finger on my fretting hand will be a hindrance.
My interest isn't playing chords; I know I'll learn them at first, but I'm really interested in a shredding style of playing and playing rock songs (Sweet Child O Mine to be exact). I know it will take months, maybe even years, to get good enough to play it but that's my goal.
Will my finger be a real problem in this? I don't want to play left handed but at the same time I feel it will be easier to use my right hand to hit all the fast notes in solos. I hope I'm asking this in the right place if not I'm sorry I just really want to learn to play my favorite songs and be able to play with and for my friends and family.
I should add I can still put pressure on strings fine; I just can't bend the second knuckle because I cut my finger with a knife when I was a kid and I must have cut through the tendon or something along those lines.
Comment: You may just have to alter how you play to accommodate your condition.  Look at Tony Iommi and Django Reinhardt.
Comment: why don't you want to play lefty?
Comment: I was once attacked by pickpocketters with a knife, my index fingertip wouldn't bend anymore, but I'm still able to play the guitar... I'm kinda unable to make some open chords though, but it makes me practice my riffs and solos a lot more, so go for it
Comment: I can only partly bend my left 4th finger, because the knuckle is missing, and it's never been an issue for me. Not sure how that compares to not being able to bend it at all, though.
Comment: Just because its easier to find right handed guitars and I know people that play them is all it's not that I don't want too I would just much rather play right handed
Comment: Have you considered playing a regular right-handed guitar "upside down", fretting with your right hand? At least give it half an hour if you can borrow a guitar some time, to see how it feels! It's unusual, sure, but at least some great players have done it. To mention two: https://en.wikipedia.org/wiki/Albert_King https://en.wikipedia.org/wiki/Eric_Gales
Answer: My first words will be to encourage you!
DO PLAY THE GUITAR!
First of all, it has been scientifically proven that playing any kind of melodic instrument is healthy: it develops dexterity, arms / hands synchronisation mind to limb synchronisation...
A bit of music theory also develops the intelect, keeps the mind sharp for long.
Who knows what good it might do to your "not bending" index? Maybe none? Maybe it will improve?
Talk to a doctor about it
If you have a serious hand injury, maybe you should talk to a doctor about it (or to a physiotherapist or... you get the idea).
Remember two things:

Playing the guitar should not be painful or harmful
Playing 5 minutes everyday will take you further than you can imagine!

If you do experience pain, simply put the guitar away and come back to it later.
If you experience pain in your wrist, elbow or shoulder, chances are, this pain has nothing to do with you not bending index, but rather with lack of technical experience. Therefore, you should consider...
Take some classes
With a nice, understanding teacher. One that will take his time with you!
AND MOST IMPORTANT OF ALL
Do keep in mind that some of the most extraordinary, amaising, creative, influencial guitar players have build a awe striking style around a deficiency on their fretting hand:

Django Reinhardt had 2 fingers burt and was considered a giant of gipsy jazz guitar
Tony Iommy (Black Sabbath) had the tips of 2 fingers cut in a press and he is considered one of the father of heavy metal

These are the only examples I have in mind. If you think of somebody else, please write them in the comment section.
Bottom line is: unless you have a serious medical advice against playing the guitar, you should be unstoppable!
Work your own style and you'll do great!
Comment: i believe Richie Haven was born with a hand problem. he played (at least when he was young) with his fretting hand coming over the top of the neck, played in open tuning, and played mostly barre chords. as he got older he was able to expand on this a bit and has written some great songs and was a great performer.
Comment: Thanks avi I'm going to give it a go I have cystic fibrosis so I spend 2 weeks in the hospital every 6 weeks I spend ALOT of time on YouTube. Iv learned the rubix cube and all sorts of stuff with all the time I have in here so time to learn and practice is no problem at all. I am going to start playing and who knows maybe a year down the road I'll be shredding lol!
Comment: I deliberately omitted to mention blind musicians like Steve Wonder or Ray Charles, or other guitar giants like Jason Becker who was stroke by ALS because their cases are a bit distant to yours. Anyway, the message from all these incredible people is: nothing should (can) stop you from making music.
Comment: And he set the world on fire at Woodstock!
Comment: @jaymebelonge, so happy to hear this! Please keep me updated!
Comment: The Django Reinhardt example is most significant to me, those burnt fingers were almost completely paralyzed and could only be used in chord work and yet he is still one of the most amazing guitarists to ever live.
Comment: There was a band I used to like in the 70s. Their guitarist broke his left ring finger in 1973 but was still able to tour and play. It was a long time ago but you should still be able to find some info on Jimmy Page and Led Zeppelin.
Answer: You shouldn't expect to be able to shred without the basics (chords, scales, simple warm-up exercises, etc.), even if you could bend your finger.
That being said, while it will be a hindrance and you might never be as dexterous as someone like Paul Gilbert or Steve Vai, it is absolutely plausible that you will be able to develop techniques to get around this. There are professional guitarists with entire fingers missing (or finger tips, à la Tommi Iommi).
Comment: Thank you James, I said in my post I dont expect to shred as soon as I start but that is my end goal!
Answer: Although I'm new here, I've only had 4 years of lessons/playing 4 years - this much I know. I started playing after age 55 - I have advanced arthritis, and less than ideal hands (short fingers / most don't want to bend). I found a teacher that has taught me the basics, 50 chords, scales, rhythms, power chords, etc and every week is still exciting. He advises on substituting something here or there, but overall I'm able to play just fine
 (mostly as a rhythm player still) - looking to improve
 and be the lead :-) player, so really - you can do it!! Don't worry about what you think you don't have, and if you are able, consider maybe getting some lessons so you can figure out together good basics and habits that work for you. Also, it has really helped my hands to move better!! Best to you as you start playing!!
Answer: It will definitely be a hindrance, but shouldn't stop you if you are persistent. Something that will probably help a lot is taking some note of proper left hand form for classical guitarists. Googling should get you hours of content, but a major difference between classical and modern guitar positioning is the thumb (which in turn, controls the positioning of the wrist).
Most regular guitar plays will have their thumb near the low e string (the one closer to their eyes). This causes their hand to wrap around the neck and requires a lot of bending of the fingers. Classical guitar necks are much wider, so if you try to play on one with your hand in that positioning, you won't be able to reach all the strings to play a chord. Those players will instead have their thumb near the high e string instead. This gives their fingers a more vertical positioning, which gives them a much more dynamic range of motion (I can stretch my fingers across the first 4 frets in the prior position, and 5-6 in the latter). But what this will give you is the opportunity to keep your index finger a lot straighter in most situations. Also, it'll help you keep your wrist loose, which is in my opinion the biggest problem that beginners don't know they are facing.
Also, definitely make sure to work your middle and pinky fingers a lot. Most amateur players spend a lot of effort training the index and ring fingers because those feel most natural, and many never use their pinkies at all outside chords when necessary. You would definitely want to offload some of the work from your index finger to the others.
Finally, certain styles of guitar will require more or less effort, and certain techniques (e.g. tremolo, arpeggiation, tapping, stops, etc) can help speed up your playing without adding finger dexterity issues. The right hand is just as important as the left!
P.S. I know that arpeggiation is not a real word, just go with it.
P.S. Arpeggiation is totally a real word and I can English goodly.
Comment: https://www.merriam-webster.com/dictionary/arpeggiation .  So there :D
Answer: I'm a banjo player, and my limitation is different than yours, but I think my experience may help.  I learned to play banjo with a physical limitation that caused me great trouble at first.  Due to very small hands, I was unable to play certain chords, even after years of stretching and practice.  Some things that are commonly done, I still cannot do.  But I have learned to play.
What let me continue to learn to play despite this limitation is to combine these attitudes.  I think these apply to anyone with a limitation.  And to some extent, maybe to anyone at all:

As long as I'm getting better in some way, it's OK.
I don't have to be able to do everything the book says.
I don't have to be able to do what everyone else can do.
But that doesn't mean I shouldn't try hard to do it the usual way.  My limitation is not an excuse to not even try.
But that doesn't mean I should get bull-headedly stuck on something I can't do yet.  Sometimes it's best to move on and come back to a technique later.
I should be creative and learn other ways to play it when my limitation prevents me from playing the usual way.  For me, that could mean using partial chords instead of full chords, or playing an inversion up the neck, or playing melody instead of chords, or almost anything.  For you, the creative workarounds will be something else.
There's no limit to how creative you can be when working around limitations, and there are no musical police who will arrest you for doing it "wrong."
If I do invent my own way to do it, I should try the usual way again after some time.  Sometimes the limitation is less evident after lots of playing and practice.  Not always, but try it from time to time and find out.
Play lots.  Play at least a little every day.
Growth happens most in the hard parts, so don't get mad when it gets hard.
But have fun.  Learning to play has moment of great joy.  Savor the journey.

Barry Abernathy is the banjo player who inspired me to stop whining about my hand size and get on with it.  With a hand deformity that would seem impossible to overcome, he plays professionally and very capably.  He "cheats" every which way he can to get the music out.  That's the creativity I'm talking about.
Watch Barry play here (youtube)
Answer: Don't let a minor impairment stop you! Django Reinhardt, who is regarded as one of the greatest musicians of the twentieth century, had two paralysed fingers on his left hand.
Answer: Why don't you just try it for a few weeks/months. If you can't play music because of your finger then you can drop it later, but at least try. No one on here really understands your finger bending issue better than you do. And hey - if you really wanna learn it then maybe your finger will start to bend, or maybe you'll figure something else out as you play. I would just say start with the basics and take it from there. by the way I started learning to play guitar a few weeks/months ago and I'm learning each day, and every couple of days I see improvement. just hang in there and keep going hard towards your goals!


Characteristic polynomial of a nilpotent matrix

Question: Let $A$ be $n\times n$ nilpotent matrix.
How to calculate  its characteristic polynomial?
I know it should be $X^n$, but I don't know why?
Comment: Do you know about minimal polynomials and the Cayley-Hamilton theorem? Or (if working over the complex numbers) you could argue which possible eigenvalues a nilpotent matrix can have.
Answer: If the overlying field is the complex numbers (see Listing's and Mark's comment):
If $A^k=0$ and $\lambda$ is an eigenvalue of $A$ with eigenvector $\bf x$:
$$\eqalign{
A {\bf x}=\lambda {\bf x} &\Rightarrow A^2  {\bf x}= \lambda^2  {\bf x} \cr
&\Rightarrow  A^3 {\bf x}=\lambda^3  {\bf x}\cr
&\ {\vdots} \cr &\Rightarrow 0=\lambda^{k } {\bf x} \cr &  \Rightarrow \lambda=0}
\ \ \ \raise6pt{\left. {\vphantom{\matrix{1\cr1\cr1\cr1\cr1\cr}}}\right\}}
\raise6pt{\scriptstyle{(k-1)-\text{times}}}
$$
So 0 is the only eigenvalue of $A$. The characteristic polynomial of $A$ is then $x^n$.
Comment: This answer assumes that you are working over an algebraic closed field.
Comment: @Listing Thanks, I edited the post to reflect this.
Answer: The minimal polynomial is of the form $x^k$ for some $k$, because the matrix is nilpotent. Since the minimal polynomial is divisible by all the irreducible polynomials which divide the characteristic polynomial, we see that in fact the only irreducible polynomial which divides the latter is $x$. Thus $\chi_A(x)=x^n$.
Comment: @PythonSage, nope, not at all. The classification is given by the the Jordan canonical form.
Comment: So does that mean for $n \times n$ size matrices, there is only one similarity class of  nilpotent matrices?


Java NullPointerException When I call a method on a custom class

Question: I get a null pointer exception when a call a method on a custom class. I do not see why my object p of class Player is null.  (Player is a class of Players of my game) play is the method. This class should create n number of p objects of the Player class and run the play method on them.
import java.util.*;
public class PsychicGameMore
{
    private ArrayList <Player> players;
    private int orginalNumber;
    private Player p;

    public PsychicGameMore()
    {

        int n;
        Scanner s;
        s = new Scanner(System.in);
       System.out.println("How many players will there be?, Please enter a number");
       n = s.nextInt();
       players = new ArrayList<Player>(n);

        //for loop to create n number of Players
        for(int i = 0; i < n; i++)
        {
           Player p;
            p = new Player();

            players.add(p);
        }

       orginalNumber =0;

    }

     public void play()
      {
        Random myRandom;
        myRandom = new Random();

    do
    {
    orginalNumber = myRandom.nextInt(6)+1;
    System.out.println("The computer has choosen the number " + orginalNumber);
    p.play();

        if(orginalNumber == p.getGuessedNumber())
        {
        System.out.println(p.getName() + " has won!!!!!!!!!!!!!!!!");
        }

      } while((orginalNumber != p.getGuessedNumber()));

     }
}

Thanks for any help.
Comment: Where is the nullpointer? You have a global Player p and defined local again in for loop. I won't even comment on the code style...
Comment: I know the code style could be improved working on that
Answer: You assign quite a few Players to your arraylist players, but you never assign any to p.  Note that in the loop:
   for(int i = 0; i < n; i++)
    {
       Player p;
        p = new Player();

        players.add(p);
    }

The local p hides the one in the object.  It is not clear what value you want the object-level p to have, so I have no idea how to correct your code.
You should also really work on keeping your block indentation consistent.  It is hard to follow your code as is.  If you're using eclipse, fix it up by highlighting the whole mess and hitting ctrl-i.
Answer: Your code needs a LOT of work, but this gets you past the NPE.  The problem is that your private data member Player is never initialized.
package psychic;

import java.util.*;

public class PsychicGameMore
{
    private ArrayList<Player> players;
    private int orginalNumber;

    public static void main(String[] args)
    {
        PsychicGameMore game = new PsychicGameMore();
        game.play();
    }

    public PsychicGameMore()
    {
        int n;
        Scanner s;
        s = new Scanner(System.in);
        System.out.println("How many players will there be?, Please enter a number");
        n = s.nextInt();
        players = new ArrayList<Player>(n);

        //for loop to create n number of Players
        for (int i = 0; i < n; i++)
        {
            Player p;
            p = new Player();

            players.add(p);
        }

        orginalNumber = 0;
    }

    public void play()
    {
        Random myRandom;
        myRandom = new Random();

        boolean hasWon = false;
        do
        {
            orginalNumber = myRandom.nextInt(6) + 1;
            System.out.println("The computer has choosen the number " + orginalNumber);
            for (Player player : players)
            {
                player.play();

                if (orginalNumber == player.getGuessedNumber())
                {
                    System.out.println(player.getName() + " has won!!!!!!!!!!!!!!!!");
                    hasWon = true;
                }

            }
        } while (!hasWon);
    }
}

Comment: Thank you, I have beautified my code. I know it was hard to read. I will work on posting better indented code. What I was not getting was the for(Player player : players) loop.
Thanks
Answer: p at
p.play();

is null.  You never create it.  The only instances of Player being initialized are the ones your adding to your ArrayList collection.
Comment: I want to call the play method on the ones in the ArrayList collection
Answer: Your class attribute private Player p is not instantiated, so that when you call p.play() in the play() method, you get an NPE.  Instantiate private Player p before you call p.play().


#states with effects (fade, slide)

Question: I'm using the form API #states feature to show and hide fields based on the value of other inputs. This is working great; however, I would like to have the option to fade or slide the inputs as they are shown and hidden.
I realise the conditional fields module offers this functionality, but I found it too buggy to use.
I am using this code.
<code>$form['more_info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Additional Information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,

  // Expand the expand_more_info fieldset if the box is checked.
  '#states' => array(
    'expanded' => array(
      ':input[name="expand_more_info"]' => array('checked' => TRUE),
    ),
  ),
);
</code>
This made me think using 'expanded' instead of 'visible' would make the element slide and not just appear however this is not working for me.
I am editing a node form using hook_form_alter so my working code (but with no effect) looks like this.
<code>$form['field_full_name'][LANGUAGE_NONE][0]['value']['#states'] = array(
    'visible' => array(
        ':input[name="field_person_type[und]"]'=> array(
            array('value' => 'Contractor'),
            array('value' => 'ICM'),
            array('value' => 'Member of public'),
        ),
    ),
);
</code>
Replacing visible with expanded or collapsed has no effect so I guess these properties only apply to fieldsets, not elements. A full list of possible states can be found here.
So, is is possible to fade or slide form elements using #states?
Comment: that `expanded` is for fieldset expand/collapse feature.
Comment: Possible duplicate of http://drupal.stackexchange.com/questions/11905/how-can-i-slidedown-with-states
Answer: Please try this. may be it will help you.
<code>**Your Code:**
$form['more_info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Additional Information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,

  // Expand the expand_more_info fieldset if the box is checked.
  '#states' => array(
    'expanded' => array(
      ':input[name="expand_more_info"]' => array('checked' => TRUE),
    ),
  ),
);
</code>
Instead of that you can try it in another way which is mentioned below in hook_form_alter() function.
Example:
<code>$form['more_info'] = array(
                          '#type' => 'fieldset',
                          '#title' => t('Additional Information'),
                          '#collapsible' => TRUE,
                          '#collapsed' => TRUE,
                     );

**$form['more_info']['und']['#states']**= array(
                                'expanded' => array(
                                 ':input[**name="expand_more_info[und]**"]' => array('checked' => TRUE),
                                ),
                             );
</code>
Note: you can use 'visible' instead of 'expanded'.
you can try this in your custom module or template.php
Answer: You miss understand this concept, I think, In your code
<code>$form['field_full_name'][LANGUAGE_NONE][0]['value']['#states'] = array(
    'visible' => array(
        ':input[name="field_person_type[und]"]'=> array(
            array('value' => 'Contractor'),
            array('value' => 'ICM'),
            array('value' => 'Member of public'),
        ),
    ),
);
</code>
you have written for,
It means when the field "field_persion_type[und]" value is "Contractor or ICM or Member of public" then only the $form['field_full_name'][LANGUAGE_NONE][0]['value'] field will be visible
<code>$form['field_persion_type']['und'] = array(
  '#states' = array(
    'expanded' => array(
      // we could set with field id
      // '#id-of-field' => array('checked' => TRUE),
      ':input[name="field_full_name"]' => array('checked' => TRUE),
     ),
   ),
);
</code>
So now if the field_full_name selected the field_persion_type field will be expand..
Comment: Yes, I understand. `field_person_type` is a series of radio buttons. If the value is `Contractor` or `ICM` or `Member of public` then the `field_full_name` will be visible. My question concerns how to animate the field appearing / disappearing.

#states with effects (fade, slide)


Given that $P_1(x)=x^2-2$ and $P_j(x)=P_1(P_{j-1}(x))$ then prove that the roots of $P_n(x)=x$ are real and distinct

Question: I went on using induction
$P_1(x)=x$ and $P_2(x)=x$ have real and distinct roots
Assume that $P_{k-1}(x)-x=(x-\alpha_1)(x-\alpha_2)...(x-\alpha_t)$ has real and distinct roots
Then  $P_k(x)-x=P_1(P_{k-1}(x))-x =(x-\alpha_1)^2 (x-\alpha_2)^2 ...(x-\alpha_t)^2-2-x =0$
What to do next ? I tried factoring but no use.Any help??
Comment: Note that if $x=2\cos t$, then $P_1(x)=2\cos 2t$.
Answer: Let
$$P_1(x):=x^2-2$$
and
$$Q(x):=\frac14 x+\frac12  \ \text{and} \  L(x):=4x(1-x) \ \text{for} \ x \in [0,1]\tag{0}$$
where $L$ is known as (a version of) the logistic map.
It is easy to show that :
$$P_1=Q \circ L \circ Q^{-1} \tag{1}$$
(one says that $P_1$ and $Q$ are conjugated).
where $\circ$ is the symbol for function composition. Let :
$$P_1^{[n]}:=\underbrace{P_1 \circ P_1 \circ \cdots P_1}_{n \ \text{times} \ P_1}$$
Using (1), one has :
$$P_1^{[n]}=Q \circ L^{[n]} \circ Q^{-1} \tag{2}$$
Therefore, your equation $P_1^{[n]}(x)=x$ is equivalent to $L^{[n]}(u)=u$ and this equation has $2^n$ real solutions. See for that :

the explanation of @Andrew D. Huang here
or an almost explicit solution using the (bijective) change of variables

$$x=\sin^2 t \ \text{for} \ t \in [0,\pi/2]$$ that I give now :
Using (0) and a classical trigonometry formula : $$L(x)=L(\sin^2 t)=4 \sin^2 t (1 - \sin^2 t)=(2 \sin t \cos t)^2$$
i.e.,
$$L(\sin^2 t)=\sin(2t)^2\tag{3}$$
Therefore, setting
$$R(t):=\sin^2 (t) \ \ \ \text{and} \ \ \ D(t):=2t,$$
relationship (3) can be written :
$$L \circ R = R \circ D \ \ \iff \ \ L= R \circ D \circ R^{-1}$$
i.e., once again a conjugation relationship giving :
$$L^{[n]}=R \circ D^{[n]} \circ R^{-1}\tag{4}$$
Remark : $D^{[n]}(u)=2^n u.$
Thus, combining (4) and (2), one obtains :
$$P_1^{[n]}=(Q \circ R) \circ D^{[n]} \circ (Q \circ R)^{-1} \tag{5}$$
One finds back in this way the "almost explicit" solutions given in this interesting answer I just discovered now !
See as well the answer of EditPiAf here.


Intuitive Interpretation of Interaction Term?

Question: This is my first time posting on this site so please excuse me if I am not following certain rules or guidelines specific to this forum.
I have a data set on a training program and I want to see whether equally skilled people are paid the same or their demographic influences their future earnings.
Variables:
 assignmt:     treatment group or not.

 training:     received the training or not.

 afdc:         receiving AFDC (Aid to Families with Dependent Children) at the same time

 sex:          male = 1, female = 0

 bdate:        date of birth

 age:          age at the time of assignment

 earn:         total 30 month earnings after the assignment takes place

 married:      married and living with spouse or not

 hsorged:      high school  diploma or GED (General Educational Development)

 black:        black, non-Hispanic

 hispanic:     Hispanic

 wkless13:     worked less than 13 weeks in the past year

Here is the full regression model:
 . reg earn assignmt training afdc sex bdate age married hsorged black hispanic wkless13

      Source |       SS           df       MS      Number of obs   =    11,204

 -------------+----------------------------------   F(11, 11192)    =    118.81
       Model |  3.2932e+11        11  2.9938e+10   Prob > F        =    0.0000

    Residual |  2.8202e+12    11,192   251985269   R-squared       =    0.1046

 -------------+----------------------------------   Adj R-squared   =    0.1037

       Total |  3.1495e+12    11,203   281133832   Root MSE        =     15874

 ------------------------------------------------------------------------------

        earn |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]

-------------+----------------------------------------------------------------

    assignmt |  -872.3136   397.0343    -2.20   0.028    -1650.571   -94.05645
    training |   3139.047   378.3347     8.30   0.000     2397.445     3880.65
        afdc |  -2372.576   427.2609    -5.55   0.000    -3210.083    -1535.07
         sex |   4598.853   322.3371    14.27   0.000     3967.016    5230.691
       bdate |  -1.733176   .7830663    -2.21   0.027    -3.268123    -.198228
         age |  -723.1733   286.1614    -2.53   0.012      -1284.1   -162.2466
     married |   2491.303   327.5803     7.61   0.000     1849.188    3133.418
     hsorged |   3590.436   344.8135    10.41   0.000     2914.541    4266.331
       black |  -1744.983   360.6557    -4.84   0.000    -2451.932   -1038.035
    hispanic |  -901.8467   496.6624    -1.82   0.069    -1875.392     71.6991
    wkless13 |  -6421.666    331.158   -19.39   0.000    -7070.794   -5772.538
       _cons |   34420.77   8092.328     4.25   0.000     18558.39    50283.16

------------------------------------------------------------------------------

A general analysis of the regression table indicates that there is some level of discrimination present: however I am trying to build a more specific model to show that equally skilled individuals are not paid the same even with the same training/skill level.
I was considering adding some interaction terms, such as black * hsorged (blck_educ) but the results, assuming I am interpreting this correctly, indicate that black individuals with a GED or diploma earn less than black individuals without an education, which I find very counter-intuitive.
. reg earn assignmt training afdc sex age married hsorged black hispanic

wkless13 blck_educ

      Source |       SS           df       MS      Number of obs   =    11,204

-------------+----------------------------------   F(11, 11192)    =    118.53

       Model |  3.2863e+11        11  2.9876e+10   Prob > F        =    0.0000

    Residual |  2.8209e+12    11,192   252046952   R-squared       =    0.1043

Adj R-squared   =    0.1035

       Total |  3.1495e+12    11,203   281133832   Root MSE        =     15876

------------------------------------------------------------------------------

        earn |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]

-------------+----------------------------------------------------------------

    assignmt |   -881.271   397.0472    -2.22   0.026    -1659.553   -102.9887

    training |   3177.937   378.1713     8.40   0.000     2436.654    3919.219

        afdc |  -2376.105   427.3079    -5.56   0.000    -3213.704   -1538.507

         sex |   4605.594   322.3958    14.29   0.000     3973.641    5237.546

         age |  -91.48007   16.00721    -5.71   0.000     -122.857   -60.10312

     married |   2527.633   327.4857     7.72   0.000     1885.703    3169.562

     hsorged |   3835.689   394.8049     9.72   0.000     3061.802    4609.576

       black |   -876.932   685.7989    -1.28   0.201    -2221.219    467.3546

    hispanic |  -856.3717   496.8757    -1.72   0.085    -1830.335     117.592

    wkless13 |  -6438.197   331.1042   -19.44   0.000     -7087.22   -5789.175

   blck_educ |  -1174.194   799.2005    -1.47   0.142    -2740.768    392.3792

       _cons |   16387.24   726.8202    22.55   0.000     14962.54    17811.93

Is this a reasonable or significant interaction term to incorporate into my analysis? If not, what other interactions would provide a more intuitive and clear answer to me question?
Answer: You are not interpreting the outputs correctly. In particular:

The p-value for blck_educ is relatively large (e.g., greater than 0.05), so you should be thinking of its coefficient as not being known to be different to 0 rather than being negative.
The p-value for black has changed a lot, suggesting something odd. Perhaps multicollinearity. I am not sure. You need to figure this out. The way to test whether the interaction makes a difference to the model as a whole is via an F-test to compare the two models. I am sure Stata will have some nifty way of doing this, but I don't use Stata.
You're not comparing like with like, as bdate is in model 1, but not model 2. If you want to test the effect of a single new parameter (such as your interaction), you need to be keeping everything else constant.
Ignoring my first three points (e.g., let's pretend everything is significant), the interpretation of your second model is not quite right. The key bits are that having the high school diploma adds 3835.689  to the income of a non-black person, but only (3835.689 + -1174.194) to a black person. That is, it is worth less to a black person. While this effect could be interpreted as a race effect (but, as the effects are not significant, this would be dodgy).
This is not my field, but my guess is that with an earnings model you should have a natural log of the dependent variable. Such topics are studied extensively in economics, so I would suggest copying what is the norm there.
Answer: In addition to the answer above, I would like to recommend this and this as additional reading. In STATA, it is possible to do an interaction term right off the regression command without generating an additional variable. Instead of having gen blck_educ = black * hsorged, you can run the command like:
reg earn assignmt training afdc sex age married i.hsorged##i.black hispanic

where i indicate dummy/factor variable (assuming both have only 0 or 1 in their values, other wise use c to indicate continuous variable). This way the code will be easier to read. The Interaction and its constitutive terms will be listed together and ease some interpretation when you generate tables etc.
To greatly simplify your model, the first one, you have
$$
earn = \alpha_1 hsorged + \alpha_2 black
$$
In the one with interaction term, it becomes:
$$
earn = \beta_1 hsorged + \beta_2 black + \beta_3 (hsorged \times black)
$$
When the interaction is included, one should look at the statistical significance and coefficients with great attention to their substantive meanings because they are no longer the same. For instance, it is not surprising that the coefficient of black ($\beta_2$) has changed from -1744.983 to -876.932 in your analysis because the number now means a different thing:

Without interaction, it means the average effect of black on earn
With interaction, it means the average effect of black on earn when hsorged is set to 0.

This is because when we do a derivative on earn with respect to black on the model with interaction, we will find that
$$
\frac{d}{d(black)} earn = \beta_2 + \beta_3 hsorged
$$
which shows that the effect of black on earn depend not just on $\beta_2$, but also the level of hsorged and its coefficient ($\beta_3$). So $\beta_2$ is now only the effect of black when hsorged = 0. The same logic also shows that $\beta_1$ is no longer the effect of hsorged but its effect when black = 0
Under this situation, it might be better to look at the effect of black when you set the value of hsorged to a range of possible values (in this case perhaps just 0 and 1?) This is doable in STATA with the command (if you specify the interaction term the way I did it above):
margins dydx(hsorged black) at(hsorged=(0 1) black=(0 1))

after which marginsplot can also visualize the interactive relationship. Hope this helps in any way!


merge two similar data and sum the value using python?

Question: how do I merge and sum`` genre1 and genre2 total movie?
genre1= movie_overavg.groupby('genre_1',as_index=False)['movie_title'].count()
genre1.columns=['genre','total movie']
genre1=genre1.set_index('genre')
print(genre1)

genre3= movie_overavg.groupby('genre_3',as_index=False)['movie_title'].count()
genre3.columns=['genre','total movie']
genre3=genre3.set_index('genre')

Comment: Check [this](https://stackoverflow.com/a/41181829/8353711). Concat data vertically and apply `groupby` as you did.
Answer: Use DataFrame.add:
df = genre1.add(genre3, fill_value=0)

Or concat wth aggregate size:
s = pd.concat([movie_overavg['genre_1'], movie_overavg['genre_3']])

df = s.value_counts().sort_index().to_frame('total movie')

df = s.groupby(s).size().to_frame('total movie')

Answer: pd.merge(genre1, genre2, on=['genre']).set_index(['genre']).sum(axis=1)

Answer: Lets say
df = table 1
    genre   total
0   action      450
1   adventure   200
2   animation   300
3   crime       10

df2 = table 2
genre   total
0   action      450
1   adventure   200
2   animation   300

these can be done by
f = [df, df2]

result = pd.concat(f)
new_df = result.groupby('genre')['total'].sum().reset_index()

output
genre        total
0   action       900
1   adventure    400
2   animation    600
3   crime        10


Pinescript Syntax error at input 'strategy'

Question: I know the usual solutions provided on the net, already searched, but I have the tab in front of the conditional block, yet it still has a problem

Funny thing is it is based on a YT video tutorial and it works in the video :D
https://www.youtube.com/watch?v=h-erJbnBj6A&t=46s
import TradingView/ta/5

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Arek1313

//@version=5
strategy("Simple Pullback Strategy",
     overlay=true,
     initial_capital = 50000,
     default_qty_type = strategy.percent_of_equity,
     default_qty_value = 100, //100% of balance invested on each trade
     commission_type = strategy.commission.cash_per_contract,
     commission_value = 0.005) //Interactive Brokers Rate

//Get User Inpu
i_ma1          = input.int(title = "MA 1 Length", defval = 200, step = 10, group = "Strategy Parameters", tooltip = "Long-term MA")
i_ma2          = input.int(title = "MA 2 Length", defval = 10, step = 10, group = "Strategy Parameters", tooltip = "Short-term MA")
i_StopPercent  = input.float(title = "Stop Loss Percent", defval = 0.10, step = 0.1, group = "Strategy Parameters", tooltip = "Failsafe Stop Loss Percent Decline")
i_StartTime    = input.time(title = "Start Filter", defval = timestamp("01 Jan 1995 13:30 +0000"), group = "Time Filter", tooltip = "Start date & time to begin strategy")
i_EndTime      = input.time(title = "End Filter", defval = timestamp("1 Jan 2099 19:30 +0000"), group = "Time Filter", tooltip = "End date & time to stop searching")

//Get Indicator values
ma1 = ta.sma(close, i_ma1)
ma2 = ta.sma(close, i_ma2)

// Check Filter(s)
f_datefilter = time >= i_StartTime and time <= i_EndTime

//Check buy / sell conditions
var float buyPrice = 0

buyCondition   = close > ma1 and close < ma2 and strategy.position_size == 0 and f_datefilter
sellCondition  = close > ma2 and strategy.position_size > 0
stopDistance   = strategy.position_size > 0 ? ((buyPrice - close)/ close) : na
stopPrice      = strategy.position_size > 0 ? buyPrice - (buyPrice * i_StopPercent) : na
stopCondition  = strategy.position_size > 0 and stopDistance > i_StopPercent

// Enter positions
if buyCondition
     strategy.entry(id="Long", direction=strategy.long)

if buyCondition[1]
     buyPrice := open

// Exit positions
if sellCondition or stopCondition
     strategy.close(id="Long", comment="Exit" + (stopCondition ? "SL=True" : ""))
     buyPrice :=na

// Draw pretty colours
plot(buyPrice, color=color.lime, style=plot.style_linebr)
plot(stopPrice, color=color.red, style=plot.style_linebr, offset=-1)

plot(ma1, color = color.blue)
plot(ma2, color = color.orange)

Answer: Your code is fine, the only problem is the indentation after the if statement.
Here is the corrected version:
import TradingView/ta/5

//@version=5
strategy("Simple Pullback Strategy",
    overlay=true,
    initial_capital = 50000,
    default_qty_type = strategy.percent_of_equity,
    default_qty_value = 100, //100% of balance invested on each trade
    commission_type = strategy.commission.cash_per_contract,
    commission_value = 0.005) //Interactive Brokers Rate

//Get User Inpu
i_ma1          = input.int(title = "MA 1 Length", defval = 200, step = 10, group = "Strategy Parameters", tooltip = "Long-term MA")
i_ma2          = input.int(title = "MA 2 Length", defval = 10, step = 10, group = "Strategy Parameters", tooltip = "Short-term MA")
i_StopPercent  = input.float(title = "Stop Loss Percent", defval = 0.10, step = 0.1, group = "Strategy Parameters", tooltip = "Failsafe Stop Loss Percent Decline")
i_StartTime    = input.time(title = "Start Filter", defval = timestamp("01 Jan 1995 13:30 +0000"), group = "Time Filter", tooltip = "Start date & time to begin strategy")
i_EndTime      = input.time(title = "End Filter", defval = timestamp("1 Jan 2099 19:30 +0000"), group = "Time Filter", tooltip = "End date & time to stop searching")

//Get Indicator values
ma1 = ta.sma(close, i_ma1)
ma2 = ta.sma(close, i_ma2)

// Check Filter(s)
f_datefilter = time >= i_StartTime and time <= i_EndTime

//Check buy / sell conditions
var float buyPrice = 0

buyCondition   = close > ma1 and close < ma2 and strategy.position_size == 0 and f_datefilter
sellCondition  = close > ma2 and strategy.position_size > 0
stopDistance   = strategy.position_size > 0 ? ((buyPrice - close)/ close) : na
stopPrice      = strategy.position_size > 0 ? buyPrice - (buyPrice * i_StopPercent) : na
stopCondition  = strategy.position_size > 0 and stopDistance > i_StopPercent

// Enter positions
if buyCondition
    strategy.entry(id="Long", direction=strategy.long)

if buyCondition[1]
    buyPrice := open

// Exit positions
if sellCondition or stopCondition
    strategy.close(id="Long", comment="Exit" + (stopCondition ? "SL=True" : ""))
    buyPrice :=na

// Draw pretty colours
plot(buyPrice, color=color.lime, style=plot.style_linebr)
plot(stopPrice, color=color.red, style=plot.style_linebr, offset=-1)

plot(ma1, color = color.blue)
plot(ma2, color = color.orange)

Answer: Yes it is the tabulation issue!!!!
Everyone says "Just press tab on windows" which I did, but Tab on windows creates 5 spaces for some reason and Pine Script expects 4. So in effect you have to manually put 4 spaces in instead of pressing tab.
voila!


PHP: array_splice() not giving me correct output

Question: I'm trying to experiment with array_splice and I get an output like this (from $match)
Array
(
    [Keep me Updated] => Array
        (
            [winner] => winnerl.jpg
            [0] => value0.jpg
        )

    [0] => valuel.jpg //this should really be inside [Leep me Updated] array
    [1] => value2.jpg //this should really be inside [Leep me Updated] array
    [2] => value3.jpg //this should really be inside [Leep me Updated] array
}

from (this foreach creates puts in the values into $match)
foreach($data as $d)
{
    if (isset($match[$d['data']['name']])) {
        $match_loser = array($d['loser']['lrg_img']);

        array_splice($match,1,0,$match_loser);
    }else{
        $match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
                                            $d['loser']['lrg_img']);
    }
}

What I'm trying to get is bring [0],[1],[2] into the [Keep me Updated] $match array:
Array
(
    [Keep me Updated] => Array
        (
            [winner] => winnerl.jpg
            [0] => value0.jpg
            [1] => value1.jpg   // old one: [0] => valuel.jpg
            [2] => value2.jpg   // old one: [1] => value2.jpg
            [3] => value3.jpg   // old one: [2] => value3.jpg
        )
}

This is what $data looks like
    $data[] = array(
    "data"=>array
    (
        "name"=>$name,
    ),
    "winner"=>array
    (
        "lrg_img"=>$img_url_winner
    ),
    "loser"=>array
    (
        "lrg_img"=>$img_url_loser
    )

$data has array values, and $match is where I'm trying to sort the data. So if my values match, it'll consolidate.
Thanks!
Comment: What is your actual output?
Comment: @Asad sorry didn't make myself clear. The actual output is the first code, the values are going outside of the array I want to put into
Comment: Alright, but what is the purpose of having a single array inside an array?
Comment: @Asad there's more to it, but this is just the premise of the code I'm trying to figure out how to fix.
Comment: Try turning `$match[$d['data']['name']]` into `$match['Keep me Updated'][$d['data']['name']]`. Also, please post the values for `$name` etcetera
Answer: Use the inner array as the argument to array_splice
foreach($data as $d)
{
    if (isset($match[$d['data']['name']])) {
        $match_loser = array($d['loser']['lrg_img']);

        array_splice($match[$d['data']['name']],1,0,$match_loser);
    }else{
        $match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
                                            $d['loser']['lrg_img']);
    }
}


Must a moderator correlate significantly with the dependent variable (Y) in a moderation analysis?

Question: Must the moderator variable correlate significantly with the dependent variable, if I am to do a moderation analysis (multiple regression)?
I have a predictor (X) and an outcome (Y). They correlate significantly. My hypothesis is that a moderator (W) moderates the relationship. Multiple regression analasys shows that this is true. M is a significant buffer, weakening the correlation between X and Y.
BUT W does not correlate with X or Y ... I see that W correlates with Y in most moderation analyses - but I cannot find anyone who explains, if this is required, to do the analysis in the first place!?
Answer: No.  Moderation means that the relationship between one independent variable (IV) and the dependent variable (DV) is different at different levels of the other IV.  It can also be important to analyze a moderating relationship in order to show that it is weak (especially if the literature reports moderation).
Comment: Thank you so much for your answer!
Just to clarify: no, as in no the moderator does not have to correlate with the DV?

Yes my results show exactly that the correlation between IV and DV differs at different levels of M
Comment: Yes.  I mean, yes, that is what I meant.


Poisson counts over differing times or spaces

Question: When modeling count data I often have varying waiting times or varying surfaces (differing protocols of count between two studies that need to be merged). How can I use a Poisson count model while accounting for the different "search effort"?
I can apply that to R
Example (random) data:
flowers <- data.frame(n=rpois(10,2),
                 env=sample(c("grassland","forest"),size=10,replace=TRUE),
                 surface=sample(c(50,100),size=10,replace=TRUE))

Answer: An usual way to account for that is to set an offset: an additional parameter that is not fitted but considered equal to 1 that multiplies the search effort.
As the link function is usually the log in the Poisson regression we then use the log of the search effort to keep the proportionality between the search effort (here the surface, could be the time) and the outcome):
model <- glm(n~env+offset(log(surface)),family=poisson())


Check if a value exists in a column in mysql table

Question: I have a table called accountinfo with a row called username.
When i run the register.php i want to check if the username already exists in the mysql table or not.
Anyone have any ideas?
Comment: what you tried so far ?
Answer: SELECT count(*) AS num_user
FROM   accountinfo
WHERE  username = "your_user_name"

which will give you a non-zero value if your_user_name already exists in the database. If it doesn't exist, then you will get zero.
P.S.
If you don't want duplicate username in the database, then you better add uniqueness constraints in your table.
To add uniqueness constraints, use this query -
ALTER TABLE accountinfo ADD CONSTRAINTS unique_username UNIQUE (username);

Adding this uniqueness constraint will save you from a lot of troubles.
Answer: Just query for the username:
SELECT `username` FROM `accountinfo` WHERE `username` = :existing_username
-- or
SELECT `username` FROM `accountinfo` WHERE `username` LIKE :existing_username

Answer: I suggest you quickly learn SQL queries :)
SELECT * from accountinfo where username = 'something'


openssh sftp chroot

Question: I chrooted a user to the directory /var/www/upload using ChrootDirectory /var/www/upload in my etc/ssh/sshd_config.
The permissions of all the files in var/www/upload is 755 and owner is root:upload_user.
However, I still cannot modify the files. (Getting a permission denied error.)
Is it possible if I create a subdirectory with ownership upload_user:upload_user.
Is it, by any means, possible to allow my chrooted user to write to his / directory?
Answer: Is it possible if I create a subdirectory?
Yes, it will be possible to modify the files if you create a subdirectory.
Is it, by any means, possible to allow my chrooted user to write to his home directory?
Using home directory for chrooting users is highly discouraged (but you asked "by any mean"):
Modify openssh source code and introduce security breach :

Is there another way to restrict SFTP to a user's home directory?
  No, and I don't think one is necessary. If having to create a
  subdirectory (which users can automatically be cd'd to on sftp login) is
  so onerous then feel free to reintroduce CVE-2009-2904 by removing the
  checks in session.c:safely_chroot().
Answer: Change the directory mode to 770 or 775. With 755 only root has write acces to it. upload_user group only have read and execute/changedir.
Comment: 770 and 775 are likely to lead to "fatal: bad ownership or modes for chroot directory component" error messages.
Comment: If I do this I get a `fatal: bad ownership or modes for chroot directory "/var/www/upload"` error.

openssh sftp chroot


WebStorm/Intellij Gherkin tests configuration run

Question: How to set up running configuration with WebStorm feature file?
When I click on green run button seems that WebStorm can't find the steps realisation.
How could I change that WebStorm understands from where should it take steps?
When I run tests with command line it works, I have config file where I declared steps folder.
Answer: You can specify <code>--require path/to/step/definitions</code> as Cucumber.js arguments: field:
Comment: it is creating good config, but when I click on green button 'run' next to feature it runs with new fresh config and the one I created is not used.
Can you please suggest on that?
Comment: you can add these parameters to **Cucumber.js** configuration [template](https://www.jetbrains.com/help/webstorm/2021.1/run-debug-configuration.html#templates)


How to use RestSharp.NetCore in asp.net core

Question: I have gone through the http://restsharp.org/ code which work greats. Below is the code of RestSharp with out asp.net core .
public GenericResponseObject<T> GetGeneric<T>(string operation, params KeyValuePair<string, string>[] nameValues) where T : class
{
    RestClient client = new RestClient(_baseUrl)
    {
        Authenticator = new HttpBasicAuthenticator(_username, _password)
    };

    RestRequest request = new RestRequest(operation, Method.GET);

    foreach (KeyValuePair<string, string> nameValue in nameValues)
    {
        request.AddQueryParameter(nameValue.Key, nameValue.Value);
    }

    IRestResponse<GenericResponseObject<T>> response = client.Execute<GenericResponseObject<T>>(request);
        GenericResponseObject<T> responseObject = response.Data;
        return responseObject;
    }
}

This code works great to me. Now I want to implement same code in asp.net core.
Can I get a sample example how to use RestSharp in asp.net core. I have added the dependency RestSharp.NetCore": 105.2.3.
Answer: RestSharp v106 supports .NET Standard so your code should work without changes.
RestSharp.NetCore package is not from RestSharp team and is not supported by us. It is also not being updated and the owner does not respond to messages, neither the source code of the package is published.
Comment: I was actually wondering why the RestSharp.NetCore SDK sucked... Makes sense now.
Comment: where is sample. i have dotnetcore web api that want to use restsharp to call my other web service but cant find any sample. or tutorial? hope you add link or sample. please
Comment: I couldn't get the RestSharp.Netcore nuget package to install.  Just went back to RestSharp.  Hopefully this will save someone some trouble.
Answer: Update: I still see upvotes on this. Please follow Alexey Zimarev's answer instead. This answer was for the non-opensource RestSharp.NetCore nuget package, when the offical RestSharp package did not target .NET Standard.

Adding to Antwone Antics's answer, create an extension class:
public static class RestClientExtensions
{
    public static async Task<RestResponse> ExecuteAsync(this RestClient client, RestRequest request)
    {
        TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();
        _ = client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
        return (RestResponse)(await taskCompletion.Task);
    }
}

You can now use it as follows:
var client = new RestClient(BASE_URL);
var request = new RestRequest();
// do whatever else you want/need to, to the request
// ...

// ... and use it like we used to
var response = await client.ExecuteAsync(request);

You can also create extension methods that parses the response to return a strong type and so on.
Comment: client.ExecuteAsync doesn't accept only one argument
Comment: @PieroAlberto yes, which is why you need the extension method above :)
Comment: Small note: `RestRequestAsyncHandle handle` is not used, so could be left out
Answer: There's an existing StackOverflow question and example that calls ExecuteAsync on RestSharp.NetCore.
ExecuteAsyncPost Example in RestSharp.NetCore
I successfully used that example when referencing RestSharp.NetCore 105.2.3 with Newtonsoft.Json 9.0.2-beta2.
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;

public async Task<SomeObject> TestPost(ObjectFoo foo)
{
    JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings {
    ContractResolver = new CamelCasePropertyNamesContractResolver()
    };

    RestClient restClient = new RestClient(API_URL);

    RestRequest request = new RestRequest("SOME_METHOD", Method.POST);
    request.AddHeader("Accept", "application/json");

    string jsonObject = JsonConvert.SerializeObject(foo, Formatting.Indented, jsonSerializerSettings);
    request.AddParameter("application/json", jsonObject, ParameterType.RequestBody);

    TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();

    RestRequestAsyncHandle handle = restClient.ExecuteAsync(
        request, r => taskCompletion.SetResult(r));

    RestResponse response = (RestResponse)(await taskCompletion.Task);

    return JsonConvert.DeserializeObject<SomeObject>(response.Content);
}

Comment: please post an answer, steps to be followed. then reference
Comment: I took it one step farther and created an extension method for it. (See below).
Answer: I created an extension method from it (see above comment for context).
public static class RestSharpExtensions
{
    public static RestResponse Execute(this IRestClient client, IRestRequest request)
    {
        var taskCompletion = new TaskCompletionSource<IRestResponse>();
        client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
        return (RestResponse)(taskCompletion.Task.Result);
    }
}

now I can use use it as var response = restClient.Execute(request);
Comment: Can you elaborate more on "damaged"? If what I said was wrong, then I'd like to fix it so that it can help someone else.
Comment: That's nonsense. Damaged copy of **gldraphael**'s answer. I say "copy" because it really is that, and "damaged", because it drops Task/async pattern and waits implicitly by `.Result`.
Comment: In my case I wanted a synchronous version, therefore I actually block until I get a result. If I wanted the async version then I would have simply used the ExecuteAsync() method that is built into the framework. I think you misunderstood my use case.
Comment: Sure. For me, implicit wait for a task is a bug. IMHO, it should explicitly `.Wait` so further maintainers will easily notice that during refactoring/etc. But more importantly, from newest `.nuget\packages\restsharp\106.2.1\lib\netstandard2.0\RestSharp.dll` in `interface IRestClient` you've got: (A) `ExecuteAsync(request,callback)` with the callback you hack via `TaskCompletionSource` into your sync way, (B) `ExecuteTaskAsync(IRestRequest request);` which you can hack into sync by just `.Result` or `.Wait`, and finally you have (C) **synchronous** `Execute(request)` - go figure.


Jazz improvisation theory

Question: As mentioned before, I am classically trained and started looking into jazz (and blues) about a week ago, starting with the 2-5-1 progression and looking at other similar techniques.
I am also looking/learning and started improvising with this book "1001 jazz licks".
I obviously pick what I like and transpose it up or down half steps, circle of fifth and in any way I know for variations.
However, even if this is very useful, it seems very mechanical and not very satisfying for the ear.  I feel I am missing something!
Should I put what I have transposed in the chord progression of 2-5-1 or 1-2-5-1 as it happens?
In jazz, is it more satisfying, when using a lick, to use the keys that are closely related, like CM, Am, GM... and so on? Or is there no rules really?
Or maybe my ear is not used to the sound?
Comment: Have you spent much time listening to jazz?
Comment: Transcribed Solos: **_https://jazzleadsheets.com/transcribed-solos.html_** • Transcribed Jazz Solos for Alto Sax, Tenor Sax, Trumpet, Trombone, Piano, Bass, Drums, Voice.
Answer: Judging from the title of your book and what reviewers have said about it, you should probably look for a different book. Contemporary jazz is built on an entire system of theory that differs significantly from the traditional system.
Jazz theory today is its own discipline - there is far more to playing good jazz than just applying "jazz licks" to a standard chord progression.
You should consider books such as:

Jazzology: The Encyclopedia of Jazz Theory for All
Musicians
The Jazz Theory Book
Jazz Theory: From Basic to Advanced Study
The Berklee Book of Jazz Harmony

Having said that, IMO, as an experienced musician your ears are your best guide, not theory or books - the theory is secondary. You need to listen to plenty of jazz, jazz played by the masters: Musicians like Louis Armstrong, Duke Ellington, Charlie Parker, Dizzy Gillespie, Miles Davis, Thelonious Monk, Horace Silver, Dave Brubeck, Charles Mingus, John Coltrane, Eric Dolphy...  More than any theory, jazz is about feel and sound and timing - things that can't be learned from books.
Transcribing solos from such recordings is of great help in learning how it's done. You can also find transcriptions of great solo performances which you can analyze and try to play yourself - perhaps with a recording or drum machine, etc.
Also try to spend some time seeking out live jazz - preferably in clubs, where spontaneous new jazz is created on the spot, not formal jazz "concerts", a term which might even be an oxymoron.
With the sound of jazz in your ears, try improvising on familiar tunes - the traditional standards and even common every day tunes like Happy Birthday or Mary Had a Little Lamb provide great frameworks for jazz improvisation. You can find endless of good material for improvisation in a fake book, for example: The Real Book: Sixth Edition
Just play the tune and let your imagination kick in. I don't have classical training, but my understanding is that is often the most difficult aspect for those moving from classical to jazz: Learning to let your own imagination and musical instincts take charge, instead of just reading off the page and doing a bit of interpretation or following the conductor.
Although you are already a trained musician, if you're serious about playing jazz, also consider finding a good jazz teacher: Someone who will appreciate your already existing level of musicianship and help move you in the right direction for playing jazz. It doesn't have to be a lot of lessons - maybe only one or two sessions would be enough, just to "give you a push in the right direction".
You are very fortunate to be a trained musician that already has the basic tools at your disposal: Musical literacy and command over your instrument. Books certainly help, but ultimately using your ears and your innate musical talent will teach you how to use those tools to create better jazz.
Answer: It's worth bearing in mind that jazz standards treasure melody. The original melody is a gold mine for improvisation. For one thing, it already fits the chord changes. For a second thing it contains phrases/motives that you can use for sequences, or modify. If you spend some time seeing how many ways you can modify the existing melody, or indeed an existing solo, your own improvisation will have more context than a random ii V I.  There is also a world of fun to be had seeing how far you can go with quoting snatches of memorable melodies and using them as sequences, or playing them starting on different scale (or non scale) tones.
These snatches of familiar  melodies, with their memorable rhythms, are little parcels of logic and cleverness that you can use to your advantage. When You Wish Upon a Star, Salt Peanuts, Over Hill Over Dale, All Day all Night Mary Ann, The Andy Grifiths Theme, The Untouchables TV theme, advertising jingles, themes from My Fair Lady, The Sound of Music, Bach inventions... the list is endless. Often they can be used to add humour, but, because they have a 'power' in themselves, these quotes can be used in a poignant way too.
Answer:
Even if this is very useful, it seems very mechanical and not very
  satisfying for the ear.
I feel I am missing something!

Beginners run into (at least) two common problems where they feel what they are playing "doesn't sound like jazz"

They start from scales but all their lines then sound like they are running a scale rather than creating a melody.
They start from transcribed or preexisting lines but they don't fit them into the correct context.

It sounds like you're doing the later. Keep in mind that it's not just the melodic sequence that makes it sound like jazz but maybe even more importantly the underlying harmonic context. If you take a line that was originally played over a Dm7, it may not work when played over a different chord because they entire point of the line was that it was using or dancing around the chord tones of a Dm7.

Should I put what I have transposed in the chord progression of 2-5-1
  or 1-2-5-1 as it happens?
In jazz, is it more satisfying, when using a lick, to use the keys
  that are closely related, like CM, Am, GM... and so on? Or is there no
  rules really?

This highlights what I was just saying. It sounds like you're playing a ii-V-I lick out of place. Try playing the lick over the same chords as it was written and see if it sounds better to you. Then start changing a few notes here and there.
As for what key you should play in, that's part of the art. If the changes of a particular part of the song fall into say C Major, then playing in C Major will give you the most "inside" or diatonic sound. But part of jazz is playing "outside" or specifically creating dissonance that can later be resolved (or not).
I think it really helps to think in chord tones. So over Dm7 playing D, F, A, C would give you a very inside sound. But when you start adding the extensions of a Dm7, say an E which is the 9th, then it gets a bit more flavor. A neat trick that I like is thinking about the diatonic arpeggio that is a diatonic 3rd, 5th, or 7th above the given chord because this is essentially like you're still playing a Dm7 but focusing on the extensions (an F Major 7th is like playing a Dm9 without the root).
Another way is to consider different scales or modes for different chords. So maybe under a ii-V-I you'd use Dorian over the ii but then switch to something more exotic like Lydian Dominant or the Altered scale over the V and back to Lydian or Ionian for the I chord to resolve it. That's just one example and there are all kinds of ways navigate the changes.
But don't get lost in that stuff and forget that

You're supposed to be playing melodies and not scales
You want to play through the chords and not over them. When focusing on each chord change as its own island it's easy to forget that how you connect between chord changes is really important. Also don't forget about sequences/themes. When you switch chords try repeating or varying a previous line within the new harmonic context (changing notes so it fits within the chord/scale you're targeting) to add some cohesion between changes.

Or maybe my ear is not used to the sound?

Knowing the idiom, or learning the vocabulary as some say, is a huge part. Some people start with classic Bebop like Charlie Parker because most jazz that came after it had its roots there. But just listen to a lot of Jazz and try to transcribe the parts that you like.
Comment: Do both, but don't forget that a lick isn't just a lick that can moved anywhere and played over anything. The main point is how those notes relate to the changes. Also, I didn't mean to imply that scales are bad. In fact they can be really useful when mixing them up. Try playing scales and arpeggios in different variations (in 3rd, 6ths, 3rd-to-9th, etc) and you'll start to hear familiar bits that you've probably heard in real lines. Also practice things like enclosures. Try playing through a scale/arp using a scale step above the target note, half step below, then resolve to the target note.
Comment: I have learnt the appropriate scales needed for jazz and only practise them to warm up( I am fairly experienced) I am looking at this book of licks to see "the language" used by jazz pianist(I've done a lot of classical piano). But what you're basically saying is that I should experiment with what I know? Right?

Jazz improvisation theory


Como definir ícones diferentes no mapa no início e no fim do trajeto?

Question: Estou desenvolvendo sistema de rastreamento e preciso que ao consultar o trajeto onde o veículo passou. Quero que ponto inicial e final sejam identificados com outro ícone conforme imagem. Segue também código PHP:
    while($RS= mysql_fetch_array($RSS)){
    $x = $x + 1;
    $kx .= "new google.maps.LatLng(".str_replace(",", ".", $RS["vl_latitude"]).", ".str_replace(",", ".", $RS["vl_longitude"])."),";

    if($RS["ig"] == "1"){$ig="LIGADA";}else{$ig="DESLIGADA";}
    if($x == 1){$pt = $pt . chr(91)."'INICIO: ".date("d/m/Y H:i:s", strtotime($RS["dt_hora"]))." - ".$RS["ds_posicao"]." | Ig: ".$ig."', ".str_replace(",", ".", $RS["vl_latitude"]).", ".str_replace(",", ".", $RS["vl_longitude"]).", ".$x."],";}else{$pt = $pt . chr(91)."' ".date("d/m/Y H:i:s", strtotime($RS["dt_hora"]))." - ".$RS["ds_posicao"]." | Ig: ".$ig."', ".str_replace(",", ".", $RS["vl_latitude"]).", ".str_replace(",", ".", $RS["vl_longitude"]).", ".$x."],";}
    $adata  = $RS["dt_hora"];
    if($RS["ig"] == "1"){$aig="LIGADA";}else{$aig="DESLIGADA";}
    //$aig  = $RS["ig"];
    $apos   = $RS["ds_posicao"];
    $alat   = $RS["vl_latitude"];
    $alng   = $RS["vl_longitude"];
}
$pt = $pt . chr(91)."'FIM: ".date("d/m/Y H:i:s", strtotime($adata))." - ".$apos." | Ig: ".$aig."', ".str_replace(",", ".", $alat).", ".str_replace(",", ".", $alng).", ".$x."],";

Função para criação do Marker:
function setMarkers(map, locations) {
    var image = new google.maps.MarkerImage('../../imagens/car_mini.png',
        new google.maps.Size(20, 32),
        new google.maps.Point(0, 0),
        new google.maps.Point(0, 10));
    var shape = {
        coord: [1, 1, 1, 20, 18, 20, 18, 1],
        type: 'poly'
    };

    for (var i = 0; i < locations.length; i++) {
        var beach = locations[i];
        var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: image,
            shape: shape,
            title: beach[0],
            zIndex: beach[3]
        });
    }
}

Comment: Por favor, remova a imagem do código em Javascript e insira o próprio código. Isso facilita pra quem vai te ajudar.
Answer: Basta criar dentro do laço de repetição um Marker diferente criando uma condição para identificar qual primeira e última coordenada registrada. Veja abaixo como deveria ficar seu código:
var image = new google.maps.MarkerImage('../../imagens/car_mini.png',
  new google.maps.Size(20, 32),
  new google.maps.Point(0,0),
  new google.maps.Point(0, 10));

var outraImagem = new google.maps.MarkerImage('../../imagens/car.png',
  new google.maps.Size(20, 32),
  new google.maps.Point(0,0),
  new google.maps.Point(0, 10));

var shape = {
  coord: [1, 1, 1, 20, 18, 20, 18 , 1],
  type: 'poly'
};

for (var i = 0; locations.lenght; i++) {

    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });

    // aqui é a primeira posição
    if (i == 0) {
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: outraImagem,
            shape: shape,
            title: beach[0],
            zIndex: beach[3]
        });
    }

    // aqui é a ultima posição
    if (i == (locations.length - 1)) {
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: outraImagem,
            shape: shape,
            title: beach[0],
            zIndex: beach[3]
        });
    }
}

Comment: @LucasSpielmann viu que eu comentei na sua pergunta. Edite a pergunta e coloque o código em vez da imagem. Isso facilita pra quem está te ajudando. Tem como você fazer isso?!
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/64578/discussion-between-white-and-lucas-spielmann).
Comment: Entendi, e como faço para declarar a segunda imagem?
//imagem1
var image = new google.maps.MarkerImage('../../imagens/car_mini.png',
      new google.maps.Size(20, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 10));

//imagem2
 var imagem = new google.maps.MarkerImage('../../imagens/car.png',
      new google.maps.Size(20, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 10));

seria algo assim?
Comment: @LucasSpielmann faz logo abaixo da primeira porém com um nome diferente. Como no exemplo que dei: outraImagem
Comment: consegue me chamar no whats fazendo favor? nossa vai me ajudar muito mesmo.
49 999290123
Comment: @LucasSpielmann é isso ai mesmo que você fez.
Comment: @LucasSpielmann se tiver mais alguma dúvida, pode perguntar por aqui mesmo! =D
Comment: estranho que não está exibindo os icones desta forma
Comment: @LucasSpielmann está mostrando algum erro?!
Comment: Não, simplesmente quando insiro duas vezes:
  var image = new google.maps.MarkerImage('../../imagens/car_mini.png',
      new google.maps.Size(20, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 10));
  var imagem = new google.maps.MarkerImage('../../imagens/car.png',
      new google.maps.Size(20, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 10));

ele nao exibe os icones
Comment: não fica identado o codigo javascript, mas vou postar mesmo assim..
Comment: @LucasSpielmann não estou vendo seu código depois da alteração, então fica difícil eu te falar o que está errado.
Comment: posso enviar para seu email o arquivo? talvez fica mais facil
Comment: @LucasSpielmann não cara. Temos que resolver aqui ou no chat. Mas não sei se você tem reputação para entrar no chat.


How do you set up the initial directory for a FileDialog to be in sharepoint and allow you to select multiple items in VBA?

Question: What I am trying to do is open file dialog in a network path. I have figured out how to open it in the correct location, but it sets itself up as a website.
Here is the code:
Set files = Application.FileDialog(3) '3 is the File Picker type
    files.InitialFileName = "https://website.com/pathing/Document/"
    'files.InitialFileName = "\\website.com@SSL\pathing\Document\"
    files.AllowMultiSelect = True
    files.Show

Both lines that set the initial file name act exactly the same.
When I run the code I am unable to select more than one file. Unwanted Behavior

However, when I manually type in the pathing \\website.com@SSL\pathing\Document\ the File Dialog behaves as I want it to, allowing me to select multiple files. Desired Behavior

Is there a way for me to get directly to the intended behavior without having to manually enter it into the explorer bar?
Thank you.
Answer: If you want to access this directly, you need to tell the explorer that its dealing with webDav, which in fact SharePoint does if you open a library in an explorer view.
So the path to your library is https://website.com/pathing/Document/
So the UNC path looks like this:
\\website.com\davWWWroot\pathing\document\
You can however get the correct path all by yourself if you follow these steps:

Open the path in a browser
Switch to explorer view
Copy the address in the explorer
Map a network drive with the copied address.
The network drive has the desired UNC path for you.
Comment: The problem isn't being able to get to the right location. (I am in fact getting to the desired location). But when I open up the location through vba, it defaults to the view seen in the first link I posted and it does not allow me to select more than one file at a time.

However, if I click directly on the address line in the file explorer and type in the path "\\website.com\pathing\document\", it behaves as desired and lets me select multiple files.
Comment: Have you used davWWWroot in your path?
Comment: Yes, and it still behaves the same way.
Comment: @Andrew Meagher Did you ever solve the problem? I have the same issue with every application that uses the FileDialog.


Why is it $e^z$ specifically that maps the imaginary line to the unit circle without distortion?

Question: I'm not looking for a technical proof. I'm quite familiar with things like Euler's formula $e^{i\theta} = \cos\theta + i\sin\theta$ and how one could derive that by defining $e^z = \sum_{n=0}^{\infty}\frac{z^n}{n!}$ for $z\in\mathbb{C}$.
Rather, I'm looking for a rich intuitive understanding.
I get that the main interesting thing about exponentials is how they swap the roles of addition & multiplication. Which is to say, for $f:\mathbb{R}\rightarrow\mathbb{R}$, we could actually define the property of it being exponential by $f(a+b) = f(a)f(b)$ for all $a,b\in\mathbb{R}$ and then derive everything else we're familiar with about exponentials from that one property.
One could just replace $\mathbb{R}$ with $\mathbb{C}$ here and generalize nicely to exponential functions in the complex plane. And if $f(1)\in\mathbb{R}$, then $f|_\mathbb{R}$ will be just like a normal real exponential function by $f(\lambda) = (f(1))^\lambda$. Which is to say, $f$ extends a real exponential into the complex plane.
This has some nice geometry to it on the real number line. $\mathbb{R}$ stretches and shifts rightward such that $\mathbb{R}^-$ maps to $(0,1)$ and $1$ maps to the exponential base $f(1)$.
There are three points I'm not at all clear on:

Why would $f(i\mathbb{R})=S^1=\{z\in\mathbb{C} : |z|=1\}$? I see why it's plausible, since that gives $f(a+bi)=f(a)f(bi)$ for $a,b\in\mathbb{R}$ and that does in fact extend a real exponential into the complex plane if $|f(bi)|=1$. But why does it have to be that $|f(bi)|=1$? Geometrically speaking, why does a complex exponential have to wrap the imaginary line repeatedly around the unit circle?

I think that given some real exponential, there's exactly one extension to the complex plane. Which is to say, for a complex exponential $f$, the value of $f(1)\in\mathbb{R}$ is sufficient to completely define $f$. Is that true? If so, why?

Given the uncountably infinite number of exponential functions $f:\mathbb{C}\rightarrow\mathbb{C}^*$ with $f(1)\in\mathbb{R}$, why does the one that doesn't distort lengths in its mapping $f|_{i\mathbb{R}}: i\mathbb{R}\rightarrow S^1$ also happen to send $f(1)$ specifically to $e$? Why not some other real number?
Comment: I don't think this answers your question exactly, but you might find it useful. https://deaneyang.github.io//blog/blog/math/exponential-function/euler-formula/2022/06/05/ExponentialFunction.html
Comment: If you accept the geometric interpretation of complex multiplication and the identity $e^z=\lim_{n\to\infty}(1+\frac zn)^n$, then considering the limit when $z=iy$ is sort of informative.
Comment: For your question 2, you probably need to add that $f$ is continuous. Otherwise some continuous-nowhere (on $\mathbb{C}$) solution might appear, defined using a Hamel basis.
Comment: I haven't checked, but I *think* that having $f(a+b)=f(a)f(b) \; \forall a,b \in\mathbb{C}$ already grants continuity to $f$. I'm not sure what a Hamel basis is though.
Answer: This is an intuitive way of answering your third question.
Think of uniform circular motion around the unit circle in the complex plane, moving at unit speed.
Let the position be described as a function of time by the function $f(t) = a^{it}$. We want to show that $a=e$
The velocity of the particle is described by $f'(t)$
The condition that velocity is perpendicular to position gives $f'(t) = ikf(t)$ with $k \in \mathbb R$
Since there is no distortion, we must also have $|f'(t)|=1$ so that $k = \pm 1$
So the position function is the solution to
$$f'(t) = \pm i f(t)$$
Choosing the positive sign we get $a = e$, the negative sign gives $a = \frac 1e$


invertible block matrix equivalence

Question: Let $$A=\begin{pmatrix} R&v \\u^T & 0 \end{pmatrix}$$ where $R$ is an invertible upper triangular matrix and $u,v \in \mathbb R^n$

Prove that $A$ is invertible if and only if $u^TR^{-1}v\neq0$

Would appreciate any help
Comment: Shouldn't it be $\begin{pmatrix} R& v \\u^T & 0\end{pmatrix}$?
Comment: @A.G sorry. should be correct now
Answer: If $u^TR^{-1}v=0$ then $$\left(\begin{array}{cc} R & v \\ u^T & 0 \end{array}\right)\left(\begin{array}{c} R^{-1}v \\ -1\end{array}\right) = 0$$ which means that there is a vector $x\neq 0$ that satisfies $Ax=0$, $A$ is not invertible.
If $c= u^TR^{-1}v\neq 0$, we find
$$\left(\begin{array}{cc} R & v \\ u^T & 0 \end{array}\right)\left(\begin{array}{cc} cR^{-1}-R^{-1}vu^TR^{-1} & R^{-1}v \\ u^TR^{-1} & -1 \end{array}\right) = cI$$
Answer: According to the determinant formula for block matrices
$$
\det A=\det\begin{bmatrix}R & v\\u^T & 0\end{bmatrix}=\det R\cdot\det(0-u^TR^{-1}v)=-\det R\cdot u^TR^{-1}v.
$$
Since $\det R\ne 0$ we have $\det A\ne 0$ iff $u^TR^{-1}v\ne 0$.
Answer: Let x = $0 \in \mathbb{R}^n$
Let  $$B=\begin{pmatrix} R^{-1}&x \\x^T & 1 \end{pmatrix}$$
$B$ is invertible => $A$ is invertible iff $C = AB$ is invertible
$$C=\begin{pmatrix} E&v \\u^TR^{-1} & 0 \end{pmatrix}$$
So, you can prove it only for $R = E$

invertible block matrix equivalence