Right hand accuracy

Question: I've realized, that I have a big problem with right hand accuracy, when using a pick, especially, when I play arpeggios and have to skip a string or a couple of stings. Sometimes, I hit the wrong string, hit two strings instead of one or even miss a string at all.
On the other hand, when I use finger picking, the accuracy does not seem so bad, because each finger rests on separate string.
Looking at picking hand solves the problem in some way, but then I start to miss with my left hand - fretboard also requires some attention.
I saw many players rest their pinky finger on a guitars body, but since I was not introduced to this habit at the very beginning, I find this very uncomfortable.
Is there a way to improve a situation? Some best practices or exercises, ti improve right hand accuracy?
Comment: @Mr.Boy A good pick can change a lot; if you feel that the plastic is making you more "distant" from the strings, try using something small, like Jazz III or M3; they require very precise hand movements and keep your fingers very close to the strings.
Comment: To restate what others have said earlier, you have to get used to using the pick. I learned to play guitar with my fingers, so the transition was a bit hard but after a while I eventually got used to it. It may seem hard now, but push through and you'll get there :D
Comment: I have the exact same issue. Although for me it's the pick itself which causes clumsiness... if I play with my thumb and index finger as if I have a pick, I am way more accurate. I find the thick plastic makes me lose all sensitivity
Answer: I would say a couple of things may help you out here:

Start by picking slow and intentional and then get increasingly faster.
Do string skipping drills. Lots of string skipping drills.
Make sure to practice consistency on your picking. Try to always pick down/up/down/up for subsequent notes on scales and solos. Concentrate on it, and ignore what your left hand is doing. You could start by playing simple scales for this, and then eventually incorporate string skipping drills.

I have the same problem and I'm working through it in my practice sessions. I have found that these three things are improving my right hand accuracy slowly but surely.
Answer: Its hard to offer advice without seeing the picking in question but, if your having trouble with picking strings during phrases where you have to skip a string or to; try outside picking those parts, that is pick the lower string with a down-stroke and the higher string with and up-stroke.
<code>$6.5  $6.8h   $4.5   $4.7h  $6.5  $6.8h   $4.5   $4.7h
</code>
The above is an example: pick the E string on a down-stroke, and pick the D string on an up-stroke, rinse and repeat as needed.  Most of the answers to this question you asked can be picked in this way What is a string skipping exercise?
As for other situations AbstractDissonance is right practice will do the job, be careful though, practising something in a wrong way is worse that not practising at all, that's how bad habits can form, and the longer you practice something a specific way, the more ingrained it becomes and the more difficult it is to break out of further down the line.
With that in mind, for any picking the most important thing I tend to watch for is economy of movement.   The less distance your fingers/hand have to travel, the more accurate you will be; this applies to vertical movement as well as up/down-strokes  (vertical movement is the distance from/to your guitar that your hand/pick moves during picking).
Palm muting will help you greatly when learning picking patterns; having an anchor on the guitar may help, though is is more a personal thing, some people do, some don't.   I often have some part of my hand anchored on the guitar (palm/finger/side of hand).
Also check out the type of pick your using, and how your holding it; thicker picks tend to be better for any kind of fast/alternate/sweep picking.  The thicker material has less give when you pick a string, this allows you to pick the string more sturdily with less movement.   Try hold the pick near the tip (with about 5mm protruding) and on and angle; pushing it into the side of your index finger with your thumb, this will give you a more sturdy grip which in turn allows you to have more control over the pick.
So practice your lines slowly; looking at your picking hand, alternate your picking and use outside picking(or any other type) where needed.  If you have trouble fretting the notes while picking; then just don't, practice your picking patterns using a relevant chord(s) instead, or on open strings.  If you start slowly and patiently enough; you should have it in no time, build speed slowly, until your up to tempo.
Each song/tune you learn in this way will make the next one easier.
Comment: it depends. There are people that have "done it wrong" yet have done it really well and for them it is right. We judge based on what people have done. For all we know the great's "could be doing it wrong"(maybe there is a better way).
Comment: In any case my main thing is that 99% of the people who pick up an instrument to learn will fail to learn much. Of that probably 99% of those will fail to be very good. Hence we need people to be innovated just in case they turn out to be the good ones so we can push the envelope. We don't need a bunch of copy cats. Luckily it seems most of the true great's are special and have done a great deal to develop our understanding of music.
Comment: " There are people that have "done it wrong" yet have done it really well and for them it is right." - Absolutely couldn't agree more, I don't think it hurts to give people good guidelines though, especially if they are struggling.  Eventually, everyone who plays for long enough will develop their own style anyway; having good technique to begin with can only enhance this.
Answer: The single best way to do it is to use finger exercises - as have alrady been posted in answers - with the rhythm set by a metronome. Start off with a slow and easy speed which lets you have perfect accuracy, then speed up.
Very simple - but it is hard work. Although I am the lead guitarist in my band, my rhythm guitarist always had better picking accuracy at speed: his trick - half an hour a day of metronome practice.
I've been doing that now for the last couple of months and it is really working for me!
Answer: The secret to superfast, blazing alternate picking is knowing the fundamentals and ergonomics of your right hand. First, the picking motion should come from rotating the wrist just like opening a doorknob. Some call it sarod picking. Watch pebberbrown on youtube youll get the idea. Second, holding the pick with the SIDE of your index finger and PAD of the thumb. If you hold this way, you dont need to hold the pick too tightly and the pick will still be in place regardless of how fast you  play. Third, the angle of the pick. The pick should not be pointing towards the ceiling or the floor as it will put one motion in advantage and another at a disadvantage. ( ceiling: makes downstrokes easier but upstrokes harder to play and vice versa). Fourth and the most important of all.. Practice superslow practice.. As in one note per second. This will help you analyze your picking problems more clearly as you play very very slowly. Hope this helps.. Im picking 16notes at 250bpm now. What a great feeling it is.:)
Answer: Just practice! If playing guitar was so easy everyone would do it. You tend to fix problems with practice or develop bad habits which people end up trying to copy once you have practiced enough to become great.
There is no way to learn guitar but through practice. Now, learning how to practice efficiently is something that can be taught.
If you have a problem area such as this you must makes sure to practice it every day(you should be practicing a minimum of 1 hour a day anyways).  Learning songs that exhibit your problem is a good way to both learn songs and fix those problems. Noodling is another way.
If you haven't spend at least 10 hours(not continuous but say over a week or two) specifically practicing this then that is the reason you have that problem.
The best advice I can give you is for you to learn to develop yourself(I know it sounds harsh but it is the best way). Once you get to a certain level there are no books, teachers, pills, or anything that an help you overcome your issues. If you develop a good understanding of how to solve your own problems it will pay off down the line rather than you plateauing and no body can help.
As then old saying goes, "Those who can, do. Those who can't, teach". i.e., your "teachers" are people that really can't help you.
The best thing about teachers is they can keep you focus and inspire you. There are some very good teachers but usually 95% suck. They simply regurgitate what they were taught. I can give you specific advice about how to solve your problem as others here will but it will do you very little good because there are to many variables involved to say if it will work for you.
What I do know, and you should know too, is practice will overcome all problems. Quick fixes won't. This is why there are so many good players with such a wide variety of ways to do it. They learned it through practice because their mind/body chose that way because it was best for them.
Just as a teacher can help in some cases with specific problems they can also hurt because they think that is the way it is suppose to be done when it actually won't work for you.
You might not like this advice but you know I'm right! ;) (j/k)
BTW, you might not know what I mean by practice. Basically practice is intentionally working(as if it were a job) to accomplish goals(Both long and short). Just a like a job, it's up to you to figure it out(That's why you get paid). A lot of practice is simply spending countless hours playing the same thing over and over because you have issues with it. If you have string skipping problems then spend hours playing stuff that involves it. When you hit something you just can't do. Spend an hour on it forcing yourself to do it(slow, fast, how ever works for you which you'll have to figure out). Do it the next day maybe vary it up a little. Day after that take a break and work on something else. You'll see over time that after a few days of this you'll generally have no issues with it.
Teachers are great for beginners though as all the stuff to learn can be overwhelming for some. For others teachers just get in the way. Ultimately though if you need someone to tell you how to do something you'll never get very good(who teachers the masters? They teach themselves!).
Comment: "Those who can, do. Those who can't, teach" - I suppose this is true in with regards to some people; but you also hear this kind of nonsense from people who don't know enough to teach (non-field specific).   Its the same kind of phrase as "Learning music theory makes you unable to produce music with feeling" when actually the opposite is true.
Comment: Music theory allows you to understand what you are composing; without understanding how music woks, you will, as a musician remain in a very confined box.  That is to say, your compositional capacity is very restricted, making it difficult to express yourself fully as a musician/'composer'/artist.   Any 'composition' would be formed from basically stumbling around in the dark, trying to decide what note sounds better with another, even just for a single instrument, composing for an ensemble of any kind would be much more difficult.
Comment: Of course anyone can knock together a progression and play some blues stuff over it; with feeling, and without any knowledge of how it works.   Which is good and takes practice; but if they want to take that further and be real artists they need to have access to all the tools.
Comment: Yes, but you know what you are doing if you have developed your innate musical abilities. 90% of music theory is simply about naming things. That's very good to have when you need to quickly communicate your music thoughts or understand someone elses. But the fact of the matter is that many of the best musicians don't know squat about theory which proves that it isn't needed.
Comment: My intention wasn't to anger you; and yes as I mentioned, you can create music without any knowledge.  Whether you or I are able to form music in our heads is immaterial, knowledge gives us the tools needed to express and expand it.  Knowledge of these things does not hinder or 'hurt' the creative process in anyway.
Comment: Actually it's not. I know a ton of music theory because I have a degree in mathematics and music "theory" is a cinch compared to that. Music theory has only hurt me because I rely on it when I shouldn't. Music theory is a statistical analysis of the common practice period and a language for communicating musical concepts. It has little to do with actually composing for feeling. Music theory will not help you compose with "feeling". It may help you compose better pieces or may make it worse.
Comment: I somewhat agree with AbstractDissonance because as a self-taught guitarist I didn't really have anyone to teach me everything that I used during my musical career. However, after the fact I have come to rely on teachers (i.e. the kind folks here) that know much more about music theory to help me define exactly what the hell I was doing all those years. Being a scientist myself, I see the usefulness in create a taxonomy for describing the musical problem space. However having a strict categorization doesn't discourage anyone from fully exploring outside the box on their own.
Comment: So, I agree that you should explore, but I also find it very important to know what the hell you are doing. How else can you innovate without truely knowing what everyone else is doing? You can't write a paper on your awesome novel research without understanding (and citing for fear of death and dismemberment from peers) original research.
Comment: @DRL: you simply don't have a clue what you are talking about. Some of the best musicians I know compose without knowing any music theory. I know this one guy that does all kinds of counterpoint and advanced harmonies and he barely knows what a chord is. There are some people that truly hear music in their heads(hell, I do) and they are able to get it out somehow. They don't stumble either. They just have more sense of musicality than you can imagine(obviously you've never experienced it or you wouldn't be making such comments).
Comment: Ok, but now you have switched the topic from "theory" to knowledge. If we were discussing mathematics I would totally agree with you but music is an aesthetic and music theory is not a theory any more than astrology is a science. Music theory is very important for the working musician but for people learning the guitar it only gets in the way. This is not completely true but for most people it is either too abstract or too much. Some people are natural musician and do not need theory to make music. Some do. In any case the OP was about technique and not theory
Answer: All I can suggest is practice, practice etc. Here are just Some things that work for me when I'm struggling to add some tools to my repertoire. First I watch closely with my eyes taking turns between my pick hand and fret hand. You get to know your current mechanics and whether or not they can use a tweak. Then I slow down and methodically practice the motion, or shape, movement whatever. I also over emphasize, for example if I were struggling to skip a string while picking I'd take my pick hand and make a wide swerve, probably a quarter to half inch away and around the string I dont want to touch. Its takes away the pressure of trying to be so fine and the more I practice this wide swerve the more my hand, wrist, arm and pick get comfortable passing a string. Eventually I'll feel comfortable and the pass will get tighter and fluid. Last bit of practice advice is I close my eyes and let my mind takeover.

Right hand accuracy


Regarding countable sets

Question: Please help to to prove that if a collection of sets $A$ is countable, then the set of all finite intersections of members of $A$ is also countable.
I couldn't find the bijection between them.
Answer: A countable union of countable collections is countable. So you just need to show that the collection of all possible intersections of $k$ sets is countable, for each $k$. For this, you can use the fact that ${\mathbb N} \times {\mathbb N} \times \cdots \times {\mathbb N}$ is countable if the product has finitely many copies of ${\mathbb N}$. If you need to show this as well, then just define the injection $f(x) = \prod_i p_i^{n_i}$ for given $x = (n_1,\ldots,n_k)$, where $p_i$ is the $i$th prime.
Answer: Let $\mathcal{A} = \{A_1, A_2, \ldots\}$ be a countable collection. For each $k \in \mathbb{N}$, note that $\mathbb{N}^k$ is countable. For each $\alpha =(j_1, j_2, \ldots, j_k) \in \mathbb{N}^k$, define
$$
B_{k, \alpha} = A_{j_1}\cap A_{j_2}\cap \ldots\cap A_{j_k}
$$
and let
$$
\mathcal{B}_k := \{B_{k,\alpha} : \alpha \in \mathbb{N}^k\}
$$
Then $\mathcal{B}_k$ is countable, and the collection you are interested in is
$$
\bigcup_{k=1}^{\infty} \mathcal{B}_k
$$

Regarding countable sets


How do I pass disjoint slices from a vector to different threads?

Question: I am new to Rust, and struggling to deal with all those wrapper types in Rust. I am trying to write code that is semantically equal to the following C code. The code tries to create a big table for book keeping, but will divide the big table so that every thread will only access their local small slices of that table. The big table will not be accessed unless other threads quit and no longer access their own slice.
#include <stdio.h>
#include <pthread.h>

void* write_slice(void* arg) {
    int* slice = (int*) arg;
    int i;
    for (i = 0; i < 10; i++)
        slice[i] = i;

    return NULL;
}

int main()
{
    int* table = (int*) malloc(100 * sizeof(int));
    int* slice[10];
    int i;
    for (i = 0; i < 10; i++) {
      slice[i] = table + i * 10;
    }

    // create pthread for each slice
    pthread_t p[10];
    for (i = 0; i < 10; i++)
        pthread_create(&p[i], NULL, write_slice, slice[i]);

    for (i = 0; i < 10; i++)
        pthread_join(p[i], NULL);

    for (i = 0; i < 100; i++)
        printf("%d,", table[i]);
}

How do I use Rust's types and ownership to achieve this?
Comment: Where is the Rust code that doesn't work, links to documentation you don't understand, or any research whatsoever that shows that you tried to solve this problem on your own? Stack Overflow isn't intended as a "write my code for me" service.
Comment: Possible duplicate of http://stackoverflow.com/questions/32750829/passing-a-reference-to-a-stack-variable-to-a-scoped-thread.
Answer: Let's start with the code:
// cargo-deps: crossbeam="0.7.3"
extern crate crossbeam;

const CHUNKS: usize = 10;
const CHUNK_SIZE: usize = 10;

fn main() {
    let mut table = [0; CHUNKS * CHUNK_SIZE];

    // Scoped threads allow the compiler to prove that no threads will outlive
    // table (which would be bad).
    let _ = crossbeam::scope(|scope| {
        // Chop `table` into disjoint sub-slices.
        for slice in table.chunks_mut(CHUNK_SIZE) {
            // Spawn a thread operating on that subslice.
            scope.spawn(move |_| write_slice(slice));
        }
        // `crossbeam::scope` ensures that *all* spawned threads join before
        // returning control back from this closure.
    });

    // At this point, all threads have joined, and we have exclusive access to
    // `table` again.  Huzzah for 100% safe multi-threaded stack mutation!
    println!("{:?}", &table[..]);
}

fn write_slice(slice: &mut [i32]) {
    for (i, e) in slice.iter_mut().enumerate() {
        *e = i as i32;
    }
}

One thing to note is that this needs the crossbeam crate.  Rust used to have a similar "scoped" construct, but a soundness hole was found right before 1.0, so it was deprecated with no time to replace it.  crossbeam is basically the replacement.
What Rust lets you do here is express the idea that, whatever the code does, none of the threads created within the call to crossbeam::scoped will survive that scope.  As such, anything borrowed from outside that scope will live longer than the threads.  Thus, the threads can freely access those borrows without having to worry about things like, say, a thread outliving the stack frame that table is defined by and scribbling over the stack.
So this should do more or less the same thing as the C code, though without that nagging worry that you might have missed something.  :)
Finally, here's the same thing using scoped_threadpool instead.  The only real practical difference is that this allows us to control how many threads are used.
// cargo-deps: scoped_threadpool="0.1.6"
extern crate scoped_threadpool;

const CHUNKS: usize = 10;
const CHUNK_SIZE: usize = 10;

fn main() {
    let mut table = [0; CHUNKS * CHUNK_SIZE];

    let mut pool = scoped_threadpool::Pool::new(CHUNKS as u32);

    pool.scoped(|scope| {
        for slice in table.chunks_mut(CHUNK_SIZE) {
            scope.execute(move || write_slice(slice));
        }
    });

    println!("{:?}", &table[..]);
}

fn write_slice(slice: &mut [i32]) {
    for (i, e) in slice.iter_mut().enumerate() {
        *e = i as i32;
    }
}

Comment: @Lucretiel: The main thread observing the "I'm done" signal from the child thread implies it can also see the other writes it did *prior* to that signal.  It shouldn't matter if there's an explicit lock or not; what matters is that the two agree on what point in time they can both see.  If you're not convinced, you should open a new question: I'm not an expert, and comments aren't an appropriate place for this.
Comment: @Lucretiel: I've never seen an explicit guarantee written down, but threads would be horrifically broken if they didn't.  I'm reasonably sure that synchronising the parent and child threads as the child threads terminate should be enough: they both need to agree that the child thread has finished, and those writes take place before said synchronisation.
Comment: This brings up an interesting question: This solution didn't involve any atomic operators or guards. Does rust's threading model provide that all of the side effects of a thread are visible to other threads after that thread has joined? Is there a case where the worker threads could finish, but the main thread still sees the unchanged memory?
Comment: Not necessarily; a lot of modern thread doctrine calls for the use of atomic data structures, like lockless queues, to communicate between threads. I believe that `std::thread` uses such a mechanism to pass return values from threads back to the `thread.join()`


Lilypond: How to remove extra vertical space for piano "play with right hand" notation

Question: I am trying to add a half bracket with "r.h." next to it in my score, indicating that notes inside the bracket are to be played with the right hand. Here is an example measure from the Fugue No. 1 in C Major from the Well-Tempered Clavier Book I:
\language "english"

#(define-markup-command (piano-hand-bar-down layout props text) (markup?)
  #:properties ((bar-length 6))
  "Draw a piano hand half-bracket."
  (interpret-markup layout props
    #{
      \markup { \tiny \italic { #text } \path #0.1 #`(
        (moveto -1 ,bar-length)
        (lineto -2 ,bar-length)
        (lineto -2 0)
      )}
    #}))

#(define-markup-command (piano-hand-bar-up layout props text) (markup?)
  #:properties ((bar-length 6))
  "Draw a piano hand half-bracket."
  (interpret-markup layout props
    #{
      \markup { \tiny \italic { #text } \path #0.1 #`(
        (moveto -1 ,(- 1 bar-length))
        (lineto -2 ,(- 1 bar-length))
        (lineto -2 1)
      )}
    #}))

\parallelMusic fugueOneVoiceOne,fugueOneVoiceTwo,fugueOneDynamics,fugueOneVoiceThree,fugueOneVoiceFour {
  r2 r8 g'-3 a-4 b-3 | % 15
  d'8-2 g-5~ g16 a-5 g-4 f-3 e8-2 e-1 fs-2 g-2~ |
  s2 s8 \crescTextCresc s16\< s16\! s4 |
  b8-1
      -\tweak extra-offset #'(1 . -3.9)
      -\markup \override #'(bar-length . 7)
      { \piano-hand-bar-up "r.h." }
      e-3 a,-1 d4-1 g,8-1 d'4-1 |
  r8 g,-5 a-3 b-1 c8.-3 d32-2 c-3 b8-4 e-1 |
}

\header {
  title = "Test Piece"
}

\new PianoStaff <<
  \set PianoStaff.connectArpeggios = ##t
  \new Staff = "up" {
    <<
        \new Voice = "first" \relative {
            \voiceOne
            \fugueOneVoiceOne
        }
        \new Voice = "second" \relative {
            \voiceTwo
            \fugueOneVoiceTwo
        }
    >>
  }
  \new Dynamics {
    \fugueOneDynamics
  }
  \new Staff = "down" {
    \clef "bass"
    <<
        \new Voice = "third" \relative {
            \voiceThree
            \fugueOneVoiceThree
        }
        \new Voice = "fourth" \relative {
            \voiceFour
            \fugueOneVoiceFour
        }
    >>
  }
>>

This seems to do the job, and is fairly easy to place wherever needed. However, the staves are moved apart a significant amount, which is to accommodate the mark before it is moved by the extra-offset tweak. Here is the output without the mark:

...and with the mark:

Does anyone know of a good way to place the symbol without affecting the rest of the layout? Or a better way to add this symbol to begin with?
Comment: Related : [What's this L symbol in piano notation called?](https://music.stackexchange.com/questions/76126/whats-this-l-symbol-in-piano-notation-called/123794#123794)
Comment: Yeah, I left that link there more for other users looking for various ways to get the incomplete L-shaped half brackets to work in LilyPond. (It also links that post back to this one.)
Comment: Thanks for that link! It has some good suggestions, although it wouldn't be as useful in a situation where you need to play with hands crossed. With the code I have above, you can include the "l.h." or "r.h." as needed to indicate which hand should be used for the bracketed notes.
Answer: To get that nice markup to ignore the "collision" with the upper staff, use an override of the outside-staff-prioirty as below:
...
\once \override TextScript.outside-staff-priority = ##f
b8-1
    -\tweak extra-offset #'(1 . 0.6)
    -\markup \override #'(bar-length . 7)
        { \piano-hand-bar-up "r.h." }
...

Another thing you might want to do, is to hide the half bar rest for the top voice (change r2 to s2), as it's not necessary.  Then use \oneVoice and \voiceTwo to set the stem direction etc. like this:
...
s2 r8 g'-3 a-4 b-3 | % 15
\oneVoice d'8-2 g-5~ g16 a-5 g-4 f-3
    \voiceTwo e8-2 e-1 fs-2 g-2~ |
...

If you use both of these suggestions you'll get the following, which is nice and compact:
Comment: Thanks, that looks great! I thought there might be some property that I could set to make that work. I think the removal of that rest is also a major improvement over the old score from IMSLP that I copied this from. Thanks for all your suggestions!
Comment: @Dubl - Actually if the piece is a strict four part counterpoint (which it is in this case - because Bach), it makes sense to keep that rest visible.
Comment: So now that I've played around with it some more, your suggestions work perfectly for the case above. If I were to add another one to the same measure, using the `\piano-hand-bar-down` function instead, it ends up not working anymore to eliminate that extra space. Would you have any ideas about fixing that case?
Comment: I can update the question with an updated example if that would be helpful.
Comment: @Dubl - I've had another look at this, and I've noticed something odd. The code above is actually applying the markup to the wrong note; it should be applying the half bracket to the E (not the B-flat). So you might want to fix that first.  There are some other weird things going on with the scheme code for the markup definition. I'm not much good with scheme, but someone else might be able to help.
Comment: Thanks for taking a look. I guess I copied that over wrong, you are right that it should be on a different note. As far as the scheme code, I was following [this](https://lilypond.org/doc/v2.22/Documentation/extending/new-markup-command-definition#a-complete-example) example from the documentation. Either way, I may open another question to see if anyone else might know how to fix this. Thanks again for all your help!


Sum of independent continuous and discrete random variables

Question: I am trying to understand how to create a PDF from the sum of an independent continuous and discrete rv, Z = X + Y. I was wondering if anyone would be willing to provide an example of this. I have seen the equation FZ(z) = ∑ FY(z−x) . PX(x), but I can't seem to make sense of how the z's and x's are taken as input into FY. Specifically I am working with a Bernoulli and Gaussian, but an example with any continuous and discrete random variables would be appreciated. Thanks.
Answer: If $Y$ has density $\frac{1}{\sqrt{2\pi} \sigma} e^{-(y-\mu)^2/(2\sigma^2)}$ and independently $X$ has $\mathbb P(X=1)=p$ and $\mathbb P(X=0)=1-p$, then $Z=X+Y$ has density  $$(1-p) \frac{1}{\sqrt{2\pi} \sigma} e^{-(z-0-\mu)^2/(2\sigma^2)} + p \frac{1}{\sqrt{2\pi} \sigma} e^{-(z-1-\mu)^2/(2\sigma^2)}$$  and you can see that this is $f_Z(z)=\sum\limits_x \mathbb P(X=x) f_Y(z-x)$
Comment: I see, thanks for the explanation, I was getting confused at some of the notation, but this makes it much clearer - thank you.


Textbox1.Focus(); does not work; as does not Page.SetFocus(Textbox1); why?

Question: as stated both of these do not work (from Page_Load):
Textbox1.Focus();

or
Page.SetFocus(Textbox1);

any idea why?
this is the control itself:
<asp:TextBox ID="Textbox1" ClientIDMode="Static" CssClass="Textbox1"
                runat="server" MaxLength="80"></asp:TextBox>

it is located on a page, two master pages deep. the form tag is on the second master page, so that is why the focus is not being set there.
not working in: ie, firefox, chrome and safari (all latest versions).
help!
thnx
edit: need any more info? i'll do / post anything just tell me what to do to help you help me, i tried EVERYTHING. even google is out of results and is showing my this question.
Comment: What is the context here, UpdatePanel, standard full load?  Also, are you sure you have no javascript errors happening?
Comment: just a page load, no fancy stuff. it is just a web form (ajax not included).
Comment: calling Textbox1.Focus(); and Page.SetFocus(Textbox1); from Page_Load.
Comment: SetFocus and Focus are going to require some JavaScript (not AJAX). Can you confirm there are no JS errors.
Comment: well there probably IS some problem. not sure if it is JavaScript. i see no error...
Comment: i am not using any javascript on my own, there is just the javascript that gets inserted automatically (by the likes of Textbox1.Focus();
and Page.SetFocus(Textbox1);).
Answer: ok, here is what the ACTUAL problem seems to be.
<asp:Content ID="PlaceHolder1" ContentPlaceHolderID="PlaceHolder1"
    runat="server">

i have no idea how those ID's (ID="PlaceHolder1") got there, but they seem to be the problem.
i figured it out by remaking the project from scratch and seeing if the focus method works in there, then (among other things, so I could post here) i found out this difference.
this works:
<asp:Content ContentPlaceHolderID="PlaceHolder1" runat="server">

hope this helps someone, sometime...
Answer: Have you tried this?
<form id="Form1" defaultfocus="Textbox1" runat="server">

Or since you mentioned a page in within a MasterPage so it will be in a ContentPlaceholder:
    ContentPlaceHolder cp = (ContentPlaceHolder) Master.FindControl("ContentPlaceHolder1");
    cp.FindControl("Textbox1").Focus();

Make sure you reference your Master in your aspx:
<%@ MasterType VirtualPath="~/MyMaster.master" %>

Comment: i tried it. not working. error: System.NullReferenceException: Object reference not set to an instance of an object. here's what i did: i put <%@ MasterType VirtualPath="~/MyMaster.master" %> on the page (not master page) and ContentPlaceHolder cp = (ContentPlaceHolder) Master.FindControl("ContentPlaceHolder1"); cp.FindControl("Textbox1").Focus(); on the master page (tried it also on the page (not master page)). not working. not even sure WHY i'd need to do something like this?!?
Comment: thnx for trying, i figured out what the problem was (see my own answer).
Comment: That will not work for an asp:form control as defaultFocus is not a property of ASP
Answer: you can write the js code control the textbox  in the client event window.onload=.....
Answer: if your page use the master page , you should find the the textbox firstly ,so then set the textbox focus. and you also should attention the events sequence of the page and master
Comment: i have no idea what you mean, sorry.


Laravel usage "@layout" in Ajax Requests

Question: Hi there stackoverflow!
In my laravel views I am using a default layout by calling
@layout('layouts.default')

to the same controller I am sending Ajax Requests yet I can't put 'if' to @layout if its a ajax call. Because if ajax request has made to controller it also produce header, footer and content(header and footer are in default layout). So to avoid this I made one copy without @layout of my view.
However its so boring to edit two files for making changes. Can't I add a code to my view something like that?:
@if(!$ajaxrequest)
 @layout('layouts.master')
@endif

I want this because my codes in controllers are too messy
Comment: Use `Request::ajax()` to determine where a request is an ajax request. Because layout needs to be the very first thing in a view, I'd recommend wrapping your whole layouts.master file in an if statement like `@if ( ! Request::ajax() ) ... layout ... @endif`
Comment: In your controller you should be using `Request::ajax()` then have a `view` which uses a particular layout. That `view` can then nest another `view`. That nested `view` can be a single template to edit then be used via AJAX calls or non AJAX calls.
Comment: Is this Laravel 3 or Laravel 4?
Answer: A slight variation is to put the logic for the layouts in your main layout template. e.g.
layouts/app.blade.php:
@if (Request::ajax())

    @include('layouts.ajax-app')

@else

    @include('layouts.default-app')

@endif

Your views just extend the main layout as usual e.g.
@extends('layouts.app')

@section('content')
    Content goes here...
@endsection

And then create a default layout file (default-app.blade.php) and an ajax layout file (ajax-app.blade.php). The advantage of doing it this way is that any of your blade templates can be loaded via Ajax, without having to clutter up controller methods with lots of duplicated logic.
Answer: You can't have the @layout call after the if statement like that (see the notice in red under "Blade Templating" in the docs. You'll have to set the public $layout and call $this->layout->nest instead of View::make (see "The Basics" on the page linked to above).
Answer: You can use something like this in your view template:
@extends( 'layouts.' . (isset($layout) ? $layout : 'default'))

Also apply check in your controller(or Supercontroller) for AJAX request, if it is set $layout variable to needed layout. Otherwise "default" layout will be taken.


application redirect to IIS root folder during upload excel file in asp.net

Question: I am facing issue in my web application which is made in asp.net. I have host the application on IIS server.and I am going to upload excel file to port data in database from application.when i uploading from locally from server itself its working fine but i when i try to uploading using public ip or outside then my application redirect to IIS root folder can any one tell me whats is the issue.
Answer: this could be an permission issue on your web.config, file and folder permission or maybe a missing reference to correct folder.
Web.config
What is the authentication ? Do you allow Anonymous access. I understand that you can upload fine if you open the side from localhost from the server itself. Did you try to open the side with public ip from the server itself ?
Application Pool in IIS
Look for the "Identify" configuration and set this to "ApplicationPoolIdentify"
File Permission
Look for the folder and ensure that the "IIS_IUSERS" got write permissions
Code Try to sepecify the correct path using the server.MapPath()
<code>Dim myPath As String = Server.MapPath("foldername") & "\" & "filename.csv"
</code>
Comment: please share the code snipped that you use for upload.


Use field from current node in filter in view

Question: I have a content type called 'article_landing' and a content type called 'article'.
They both have an entity reference field called 'field_focus_area'.
I'm attempting to create a view that appears as a block on an article landing node and only displays articles that have the same field_focus_area as the current node. I'm having trouble figuring out how to do this though. I thought this would need to be accomplished with contextual filters but I'm not getting any results.
Below is the method I was using.

I also tried using regular filters and using tokens like [node:field_focus_area] but that didn't work either.
Is there a way I can use fields of the node that a view block appears on inside filters in the view?
Answer: Niall Murphy's concept is correct but there are some differences between how it's performed in D8 and D7. Here is the code I ended up using which was successful.
function my_module_views_pre_view(&$view, &$display_id,&$args){
    if($view->id() == 'news'){
        if($view->current_display == 'block_2'){
            $current_node = \Drupal::routeMatch()->getParameter('node');
            if(!empty($current_node)){
                $focus_area = $current_node->field_focus_area->entity->id();
                $args[0] = $focus_area;
                $view->setArguments($args);
            }
        }
    }
}

Comment: Thanks for this example.  With some adjustments for my use-case, still works perfectly on Drupal 9.5 in 2023.
Answer: EDIT: For correct implementation, OP has added the proper way to do this in D8.
That contextual filter will show nodes that reference the current node, so it's not what you're looking for.
As far as I know, this requires a custom module and this is what I do with D7 but I assume it's the same in D8 since the function didn't change much.
For this example, keep that Contextual filter from the screenshot, but click Hide View instead of Provide default value.
MYMODULE.info
name = Contextual Filter: field_focus_area
description = "Provide Contextual Filter for block."
core = 8.x

MYMODULE.module
<?php

function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Check for view
  if($view->name == 'MYVIEWNAME') {
    // Explode url to get /node/xxx
    $current_args = explode('/', current_path());
    // Check that the path has xxx
    if (isset($current_args[1])) {
      // Load node
      $current_node = node_load($current_args[1]);
      // Send the node's field_focus_area to the view
      if (isset($current_node->field_focus_area['und'][0]['target_id'])) {
        $args[0] = $current_node->field_focus_area['und'][0]['target_id'];
      }
    }
  }
}

That will probably work. I haven't worked with D8 much and the function is slightly different. In D7, it's hook_views_pre_view(&$view, &$display_id, &$args){
I assume the ->field_focus_area['und'][0]['target_id'] part is the same but if not, you can find it using the Devel module.


Send email to users after node update

Question: I have a content type "Room" with this config:

Title
Body
field_comments (Comments)
field_members (Users Entity reference)

When I create a room I send with hook_entity_insert() an email to users add to the room
But my problem is when I edit this room and I add New members, I want to send an email only for new.
I try it with this code in custom module with hook_entity_update:
notify.module
/**
* Implements hook_entity_update().
*/
function notify_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
 if ($entity->getEntityTypeId() !== 'node' || ($entity->getEntityTypeId() === 'node' && $entity->bundle() !== 'room')) {
   return;
 }
 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = 'notify';
 $key = 'new_notif';

 //send to all members in room
 $members = $entity->get('field_members')->getValue();
    $tos = [];
    foreach ( $members as $member ) {
        if ($member['target_id'] !== '1') {
            $tid = intval($member['target_id']);
            $user = \Drupal\user\Entity\User::load( $tid );
            $tos[] = $user->getEmail();
        }
    }

 $membersTo = implode (', ', $tos);

 $to = $membersTo;

 $params['message'] = 'You access to the room';

 $params['node_title'] = $entity->label();
 $langcode = \Drupal::currentUser()->getPreferredLangcode();
 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
 if ($result['result'] !== true) {
   drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
 }
 else {
   drupal_set_message(t('Your message has been sent.'));
 }
}

I Don't know how to exclude old members after edit, add new members and save a room.
Answer:
But my problem is when I edit this room and I add New members, I want
  to send an email only for new.

As hook_entity_update mentions

Get the original entity object from $entity->original.

$entity->original gives you access to the values before the update.
So all you gotta do is compare the original members to the updated members to find out who are the new members.
$og_members = array();
$og_members = $entity->original->get('field_members')->getValue();

$up_members = array();
$up_members = $entity->get('field_members')->getValue();

$new_members = array();
// use array_diff() to find the difference.
$new_members = array_diff($up_members, $og_members);

Answer: Ok you have options here...
Option1, (Harder) If the node revisionable ... you can do a difference check between the last revision and the newly added values ...
Option 2 (easy)
make a new field called  field_members_to_add (Users Entity reference)
when you edit the node you would put the new people on the new field ...
then in your "hook_entity_update" you can get the values of this field..
send the emails, update the normal "field_members" with the new values .. then  set "field_members_to_add" it to null so it will be empty next time you add new people.
so then it would be...
  $new_members = $entity->get('field_members_to_add')->getValue();
  // send email ...then later...
  $entity->set('field_members_to_add', NULL);
  $old_members = $entity->get('field_members')->getValue();
  // merge values.
  $all_members = array_merge($old_members,$new_members);
  $entity->set('field_members', $all_members);
  // Party.

Comment: Thx Taggart for your answer, I try the option 2 but when I save my node after edit, old and new members don't merge.
Comment: It's work with this methode but not for entity_presave, Thx Taggart

Send email to users after node update


Qual o linux mais completo para programadores?

Question: Eu estudo programação por hobby há uns 4 anos, comecei com php, c#, aprendi um pouco de tudo, mas agora estou pensando em ir mais a fundo. Sempre usei o Windows que aliás sempre gostei muito, mas sinto que o Linux pode me oferecer uma liberdade maior em certas tarefas, sem contar na sua estabilidade e performance.
Gostaria de saber de quem use e trabalhe com programação, qual poderia me indicar. Não ligo muito pra design então não precisa ser tão amigável assim a interface, eu estive olhando o fedora e me agradou muito mas como não sei se é uma boa escolha gostaria da opinião de vocês!
Grato desde já!
Comment: Eu testei Ubuntu, fedora e Mint realmente achei o Mint perfeito ao que eu procurava. Obrigado pela excelente resposta Cigano Morrison Mendez sanou todas as minhas dúvidas! Grato a todos também que responderam a minha pergunta!
Comment: Gostaria de ressaltar que pesquisei também a respeito de cada um dos sistemas aqui comentados e decidi escolher por base do que pesquisei e não por opiniões aqui dadas a mim.
Obrigado mais uma vez.
Answer: Esta pergunta é bastante ampla, portanto irei pincelar as distribuições mais usadas e suas características.
Linux Mint
É a distribuição que mais ganhou adeptos nos últimos dois anos. É um híbrido que funciona misturando repositórios Ubuntu e Debian (ver mais abaixo). Está em primeiro lugar nas distribuições, segundo o DistroWatch.
Possui uma filosofia que mistura código livre e proprietário, sendo o código proprietário formado basicamente por codecs de vídeo e drivers de mídia.
Sendo bastante eclético e suportando largamente o apt-get, é a distribuição que eu recomendaria para começar.
Ubuntu
É o Linux com o maior apelo comercial e de Marketing, estando em 2o lugar pelo ranking da DistroWatch. É desenvolvido pela Canonical e foi uma das distribuições que mais se desenvolveram nos últimos tempos. Começou como um fork do Debian, mas desenvolveu características peculiares rapidamente.
Diferentemente do Debian e assim como o Linux Mint, possui uma filosofia mais tolerante em relação a drivers e código proprietário (o Debian é 100% livre, o que faz com que determinados drivers também o sejam, sendo inferiores aos proprietários). O sistema de empacotamento primário é o apt-get e é um dos únicos que possui uma App Store, que mistura software livre e pago.
Possui aqui na rede Stack Exchange um site inteiramente dedicada a ela: Ask Ubuntu.
Fedora
É a alternativa livre patrocinada pela Red Hat. Está em 5o lugar no ranking de distribuições, segundo o DistroWatch. A ideia é copiar algumas das funcionalidades do Red Hat, mas sem focar no usuário empresarial, e sim no usuário doméstico.
O sistema de empacotamento primário é o yum.
Debian
é uma das distribuições Linux mais antigas, possuindo uma das maiores comunidades. Está em 3o lugar pelo ranking da Distrowatch. Possui 100% do código livre.
O sistema de empacotamento primário é o apt-get

Instalando uma distribuição
Antes de sair formatando disco, recomendo que você instale uma distribuição Linux dentro de uma máquina virtual para não comprometer o estado atual do seu computador. Há vários softwares de máquina virtual gratuitos, mas o que eu recomendo é o VirtualBox da Oracle.
Comment: Vale ressaltar que a parceria [se] / Ubuntu é tal que ambos sites compartem o menu superior, e não sei de nenhum outro site SE que tenha isso. Eu escolhi Ubuntu basicamente por isso: tem um site aqui e quase todas as dúvidas iniciais tem uma Q&A com a solução imediata.
Answer: Você provavelmente vai querer usar a distribuição que tem a maior base de usuários. Maior comunidade = maior chance de vc achar soluções pros seus problemas no google.
Vai de ubuntu
Answer: Vai de Linux Mint, rápido, leve e fácil de achar soluções.
Answer: Particularmente prefiro o Ubuntu. Uso desde que iniciei no curso de Análise e Desenvolvimento de Sistemas.


My internal JavaScript for my Kelvin/Fahrenheit Converter is not working

Question: I put my JavaScript inside  tags instead of externally(because external files weren't working) and for some reason my code is not running.
Just to be sure that it wasn't a problem with the code itself, I put a simple alert before all the code and nothing popped up.
<!DOCTYPE html>

Fahrenheit/Kelvin Converter

Kelvin to Fahrenheit

        <input type = "text" placeholder = "Enter Kelvin here" id = "kinput">
        <button id  = "ksubmit">Submit Kelvin</button>

        <textarea id = "fpopup" rows = "5" cols = "50"></textarea>

Fahrenheit to Kelvin

        <input type = "text" placeholder = "Enter Fahrenheit here" id = "finput">
        <button id  = "fsubmit">Submit Fahrenheit</button>

        <textarea id = "kpopup" rows = "5" cols = "50"></textarea>

Comment: You're using some weird Unicode character for multiplication: `×`. Instead, you should use an asterisk: `*`. If you open your browser's console you can see the error.
Comment: Oh ok I'll edit that :)
Answer: You can use DOMContentLoaded function to make sure the HTML is ready and parsed properly. Also you have some syntax errors which i have fixed as well.
Also, You were using some weird minus and multiplication characters.

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed

Your code is now working as expected.
Live Demo:

<!DOCTYPE html>

Fahrenheit/Kelvin Converter

Kelvin to Fahrenheit

    <input type="text" placeholder="Enter Kelvin here" id="kinput">
    <button id="ksubmit">Submit Kelvin</button>

    <textarea id="fpopup" rows="5" cols="50"></textarea>

Fahrenheit to Kelvin

    <input type="text" placeholder="Enter Fahrenheit here" id="finput">
    <button id="fsubmit">Submit Fahrenheit</button>

    <textarea id="kpopup" rows="5" cols="50"></textarea>


Criar divs dinamicamente

Question: Senhores,
Estou trabalhando com tabs em Jquery. Eu tenho uma página chamado incluir_servidor.php aonde faço o insert no banco de quantos servidores eu quiser. Eu preciso que após clicar no botão próximo a quantidade de abas da página seja a mesma da quantidade de registros que foram inseridos na página anterior. Isso eu até consegui fazer com o código abaixo:

        <?php
            do {
        ?>

<a href="#tabs-<?php echo $row_menu_servidor['host_servidor']?>"><?php echo $row_menu_servidor['host_servidor']?>

        <?php
            } while ($row_menu_servidor = mysql_fetch_assoc($menu_servidor));
            $rows = mysql_num_rows($menu_servidor);
                if($rows > 0) {
                    mysql_data_seek($menu_servidor, 0);
                    $row_menu_servidor = mysql_fetch_assoc($menu_servidor);
                            }
        ?>

Meu problema agora é que preciso que o conteúdo dessa DIV ou dessa TAB/ABA também seja dinâmico. Pelo o que estou imaginando, eu preciso declarar que para cada

<a href="#tabs-<?php echo $row_menu_servidor['host_servidor']?>"><?php echo $row_menu_servidor['host_servidor']?>
` a página inclua uma DIV com o conteúdo `

ID Solicitação

                <form name="form1" method="post" action="">
                    <input name="id_solic" id="id_solic" type="text" value="<?php echo $_POST['id_solic'];?>" size="5" readonly="readonly">

                </form>

Acredito que eu tenha que fazer o ID dessa DIV conteudo ser dinâmico, de acordo com a quantidade de registros da query passada acima.
Espero ter conseguido explicar com clareza.
Answer: A resposta para a sua pergunta (se eu entendi) é SIM, o id precisa ser dinâmico.
Para cada aba que você quiser ter você deverá, criar uma div com um id e apontar esse mesmo id no href do link dentro da li conforme exemplo abaixo:

Primeira Aba

Segunda Aba

Terceira Aba

    bla bla bla 1

    bla bla bla 2

    bla bla bla 3

mais exemplos no site da jquery ui
Comment: deFreitas, eu entendi isso mas eu estou pegando o href de acordo com a query que executei. Ela pode ter 10 registros como pode ter 2.
 Eu preciso que o ID da tabs seja igual ao colocado no href por variavel.

Criar divs dinamicamente


Numpy : resize array

Question: I have two Numpy array whose size is 994 and 1000. As such I when I am doing the below operation:
X * Y

I get error that "ValueError: operands could not be broadcast together with shapes (994) (1000)"
Hence as per fix I am trying to pad extras / trailing zeros to the array which great size by below method:
padzero = 0
if(bw.size > w.size):
    padzero = bw.size - w.size
    w = np.pad(w,padzero, 'constant', constant_values=0)
if(bw.size < w.size):
    padzero = w.size - bw.size
    bw = np.pad(bw,padzero, 'constant', constant_values=0)

But now the issue comes that if the size difference is 6 then 12 0's are getting padded in the array - which exactly should be six in my case.
I tried many ways to achieve this but its not resulting to resolve the issue. If I try he below way:
bw = np.pad(bw,padzero/2, 'constant', constant_values=0)

ValueError: Unable to create correctly shaped tuple from 3.0

How can I fix the issue?
Answer: a = np.array([1, 2, 3])
To insert zeros front:
np.pad(a,(2,0),'constant', constant_values=0)
array([0, 0, 1, 2, 3])

To insert zeros back:
np.pad(a,(0,2),'constant', constant_values=0)
array([1, 2, 3, 0, 0])

Front and back:
 np.pad(a,(1,1),'constant', constant_values=0)
 array([0, 1, 2, 3, 0])

Numpy : resize array


How do I show $f$ is bounded.

Question: Let $B$ be a closed unit ball in $\mathbb{R}^2$ with respect to the usual metric; $\rho$ be the metric defined by
$$\rho(x,y)=\begin{cases} |x-y|, & \text{ if } x \text{ and } y \text{ pass through the origin,} \\
|x|+|y|,& \text{otherwise}.\end{cases}
$$
Suppose the $f: B \rightarrow \mathbb{R}$ is uniformly continuous on $B$ with respect to metric $\rho$ on $B$, and usual metric on $\mathbb{R}$.
Prove that $f$ is bounded.
I tried to prove by contradiction, and I am able to handle this question in usual metric space. Can anyone suggest me, how do I solve with respect to the metric $\rho$?
Comment: I'm a bit confused. If $x$ and $y$ are points in $\Bbb{R}^2$, does the statement "*if $x$ and $y$ pass through the origin*" mean that the line passing through $x$ and $y$ contains the origin?
Answer: Take $\delta$ s.t. for all $x, y$, if $\rho(x, y) < \delta$ then $|f(x) - f(y)| < 1$.
Then by induction on $n$, we can show that for all $n$, for all $x$ s.t. $\rho(x, 0) < n\delta$, $|f(x) - f(0)| \leq n$.
Base case: $n = 1$. This is immediate.
Inductive step: suppose $\rho(x, 0) < (n + 1) \delta$ and $|f(x) - f(0)| > n + 1$. Then clearly $|f(x) - f(0)| > n$; then $\rho(x, 0) \geq n \delta$. That is, $|x| \geq n \delta$. Then consider $x' = x(1 - \frac{\delta}{|x|})$. We have $\rho(x', 0) = |x'| = |x|(1 - \frac{\delta}{|x|}) = |x| - \delta < n \delta$. Then $|f(x') - f(0)| < n \delta$. And since $\rho(x, x') = \delta$, we have $|f(x) - f(x')| < \delta$. Then $|f(x) - f(0)| \leq |f(x) - f(x')| + |f(x') - f(0)| < n \delta + \delta = (n + 1) \delta$. Contradiction.
Then in particular, take $n$ s.t. $n\delta > 1$. Then for all $x$, we have $\rho(x, 0) = |x| \leq 1 < n \delta$. Then for all $x$, $|f(x) - f(0)| < n \delta$. Then $|f(x)| \leq |f(x) - f(0)| + |f(0)| \leq n \delta + |f(0)|$.
So $n\delta + |f(0)|$ is an upper bound on $f$.

How do I show $f$ is bounded.


Como o navegador lida com laço infinito em Javascript?

Question: Estava fazendo um exercício sobre laço de repetição for em Javascript no codecademy, porem, no exercício me deparei com o seguinte aviso:

codecadeny
Tenha muito cuidado com sua sintaxe — se você escrever um laço que não
  possa finalizar corretamente, ele é chamado de laço infinito e irá
  travar seu navegador!

E lá fui eu testar:

for (var i = 2; i > 0; i++) {
 console.log(i);
}

A responsabilidade de executar o código acima é sua, ele serve apenas como exemplo.
E advinha o que aconteceu?

Isso mesmo travou tudo :D
Entretanto, esta situação me deixou com algumas duvidas que são:

Como o navegador lida com o laço infinito?
Porque o travamento ocorre?
No ambiente de desenvolvimento WEB existe alguma forma ou ferramenta
que minimize os efeitos causados pelo laço infinito?
Comment: Acho que ele lida quebrando a aba infratora :D Como ele detecta eu não sei, se é que faz. Em geral os navegadores possuem uma ferramenta que permite dar *pause*/colocar um *breakpoint* na execução, afinal o JS roda em um VM, com bastante controle se estiver em modo de desenvolvedor.
Comment: Aqui eu não deixei muito tempo, mas apesar de a página ficar travadona, foi só fechar no X da aba que tudo bem. O legal é que o Opera 12 lida melhor com isso (testei agorinha pra ter certeza) do que a versão atual, que usa o mesmo engine do Chrome. A atual trava. No 12 fica um pouco lento o browser, mas tudo funciona. Inclusive dou scroll na página com loop rodando, abro console, etc, o que indica basicamente isso como resposta: só depende da implementação de cada browser.
Comment: Se tiver alguma sugestão de melhoria pode deixar um comentário.
Comment: Estou aprendendo programação WEB e este efeito é mais devastador  do que em Desktop kkkk, eu acho que ele nem detecta, talvez alguma IDE alerte sobre isso, mais eu não sei.
Comment: talvez seja de interesse : [Como liberar thread congelado/travado?](http://pt.stackoverflow.com/q/100654/14213)
Answer: Existem vários cenários diferentes que podem travar seu navegador - sem contar os bugs. :P
Execução demorada
A execução demorada de um script pode fazer ele ficar bloqueado, mas não necessariamente causar um travamento.
Exemplo:
for (var i = 2; i > 0; i++) {}

O código acima não faz a página travar e nem ocupa muito o processador, mas dado que a execução de JavaScript no navegador é realizada de forma síncrona, isto significa que o navegador fica impedido de realizar outras ações naquela página.
Se o navegador tiver alguma proteção contra isso, ele vai identificar que o script está demorando muito para retornar (timeout) e oferecer uma opção ao usuário para "matar" o processo daquela página ou aba. Caso contrário você terá que finalizar o navegador como um tudo.
Consumo de memória
Entretanto, o código de exemplo da pergunta não apenas fica bloqueado num laço infinito, mas também gera uma quantidade infinita de output para o console.
A não ser que você tenha desativado o console, os dados vão sendo armazenados em algum local da memória até que não haja mais espaço disponível e aí você vai ter uma falha no processo. Se o console estiver sendo exibido na Ferramenta do Desenvolvedor, isso é pior ainda pois o navegador tem que atualizar a interface com o usuário, executando diversos cálculos de posicionamento dos textos, entre outras coisas.
Navegadores podem usar diferentes técnicas para prevenir um travamento total, como é o caso do Chrome, que usa um processo por página ou aba, o que significa que se uma aba travar, basta "matar" ela e a memória consumida será recuperada sem prejuízo ao sistema e às demais páginas ou abas.
Note que esta é apenas uma das muitas formas de consumir muita memória. Por exemplo:

Vazamentos de memória podem ser introduzidos adicionando indefinidamente valores à objetos ou listas, ou mantendo referências a elementos que nem estão na página.
Trabalhar com strings muito grandes, fazer concatenações em laços e coisas parecidas também podem acabar com a memória.
Usar recursividade sem um limite adequado também vai travar o script.

Evitando tais problemas
A verdade é que não existe uma forma prática e segura de evitar esse tipo de problema pois há muitas construções diferentes na linguagem que podem levar a tais situações.
Entretanto, as melhores abordagens que conheço são:

Escrever código modular (AMD, ES6) onde as funções e variáveis são isoladas tanto quanto possível.
Testar o seu código de forma automatizada e unitária (QUnit, Jasmine).
Usar ferramentas de linting (ESLint), isto é, que analisam seu código estaticamente, de acordo com regras pré-estabelecidas, procurando por práticas ruins e possíveis equívocos.
Use o paradigma funcional, quando possível

Especificamente sobre o item #3, ESLint possui uma lista de regras definidas dentre as quais existem algumas que podem detectar laços sem condições de parada, como esta. Se há algum erro frequente que não está ali, você pode escrever sua própria regra.
Por que código modular
Algo importante é que, quanto mais confuso seu código, menos efetivo são os testes e a análise estática. Por isso o item #1 da minha lista acima está nessa posição.
Por exemplo, muita gente usa variáveis de escopo global em laços. O comportamento desse tipo de código é absurdamente complexo de prever.
function f1() {
    for (i = 0; i < 10; i++) f2();
}
function f2() {
    for (i = 0; i < 5; i++) whatever();
}

No exemplo acima, f1 chama f2 para cada execução do laço. Porém i não é uma variável local, então f2 vai sempre terminar com i = 5 e o laço em f1 nunca vai acabar.
Por que paradigma funcional
O BrunoRB mencionou algo muito importante acima, que é o uso de rotinas como forEach ao invés de fazer o laço manualmente.
O paradigma de programação funcional é conhecido por evitar vários problemas inerentes do paradigma imperativo, como este caso.
A ideia é usar rotinas especiais que encapsulam a lógica de percorrer determinada estrutura de dados, afinal elas são implementadas uma vez, testadas e tem pouquíssima chance de sofrer regressões. A partir diss você pode executar ações em cada elemento da estrutura de dados usando uma função callback.
Somente é importante considerar que, embora isso ajude a não errar com o contador de um laço, isso ainda não protege totalmente contra o mau uso de variáveis globais ou que são compartilhadas com outras funções, como no exemplo acima.
Answer: Como 1 e 2 já foram bem respondidas nos comentários da questão e na resposta do Sergio vou apenas dar um adicional sobre a 3: é interessante você entender como detectar um loop infinito é um problema intratável chamado de Halting Problem, tanto para o browser quanto para alguma ferramenta de análise estática de código é impossível detectar laços infinitos (exceto em casos como while(true);, o que não é lá muito útil), o melhor que o browser consegue é verificar que seu código está executando a tempo demais sem pausa o que indica que tem algo errado, e aí ele pode tomar uma decisão sobre o que fazer, porém isso vai variar conforme o que quem implementou acha que é o melhor.
Sobres formas de evitar laços infinitos existem certas práticas de código que impossibilitam a ocorrência destes, um exemplo é que se ao invés de utilizar um for(;;) tradicional você sempre iterar sobre arrays com forEach ou for...in, ou em objetos com for...in (forEach só funciona em arrays), fica impossível iterar infinitamente. Para os casos em que você não quer iterar sobre um objeto ou array, mas sim rodar certo trecho "N" vezes uma opção é criar um array com o tamanho igual ao número de iterações que você quer fazer e utilizar ele em conjunto com um foreach, exemplo:
// obs, fill só existe em chrome >=45 e firefox >=31
new Array(10).fill().forEach(function() {
   console.log('olá');
});

É meio exótico, principalmente porque javascript não possui uma maneira limpa de criar um array de tamanho X, a performance também vai sofrer (embora você precise criar uma quantidade realmente grande de laços de tamanho razoável para isso ser relevante), mas é uma técnica bacana para se conhecer (até porque que ela é a maneira padrão de se iterar em python e ruby e é tão limpa quanto um for padrão em php).
Answer:
Como o navegador lida com o laço infinito?

Ele crasha. Acredita que o desenvolvedor sabe o que está a fazer e corre o código cegamente, bloqueando.

Porque o travamento ocorre?

Porque usa a capacidade máxima de execução. O exemplo que tens na pergunta não dá espaço ao browser para respirar, ele vai tentar correr isso tão rápido quanto possivel, infinitas vezes. E como o processamento em JavaScript é single threaded ele só corre esse processo e o resto do código fica à espera que o loop acabe. Isso nunca acontece.

No ambiente de desenvolvimento WEB existe alguma forma ou ferramenta que minimize os efeitos causados pelo laço infinito?

A única maneira é ter verificadores dentro do código que "procurem" por coisas irregulares. Algo assim:
for (var i = 2; i > 0; i++) {
    console.log(i);
    if (i > 100000) break;
}

Essa linha if (i > 100000) break; vai interromper o loop caso ele chegue à iteração cem mil.
Comment: um adendo, em computadores lentos ou OS que necessitam de uma formatação, esse tipo de ocorrência pode ocasionar o congelamento do navegador e manter o sistema ocupado por longos períodos de tempo


Como criar um filtro de arquivo ao arrastar em C#

Question: Estou implementando a função de Arrastar arquivos para preencher uma Listbox com o caminho dos arquivos.
Ela funciona muito bem, mas eu gostaria de colocar um "filtro" tornando possível apenas txt serem importados.
caso não seja txt deveria surgir um MessageBox de erro ao usuário.
Segue o Código
private void listBoxArquivosSelecionados_DragOver(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
            e.Effect = DragDropEffects.Link;
        else
            e.Effect = DragDropEffects.None;
    }

    private void listBoxArquivosSelecionados_DragDrop(object sender, DragEventArgs e)
    {
        string[] arquivos = e.Data.GetData(DataFormats.FileDrop) as string[];
        if (arquivos != null)
            listBoxArquivosSelecionados.Items.AddRange(arquivos);
        CarregarStatus();
    }

Answer: Deixa pra la, descobri como faz, só varrer o vetor e se a string conter o padrão ".txt" vai ser adicionada na lista, se não, apresentar mensagem de erro, segue código.
private void listBoxArquivosSelecionados_DragDrop(object sender, DragEventArgs e)
    {
        string[] arquivos = e.Data.GetData(DataFormats.FileDrop) as string[];
        if (arquivos != null && arquivos.Any())
        {
            foreach(string arquivo in arquivos)
            {
                if (arquivo.Contains(".txt"))
                    listBoxArquivosSelecionados.Items.Add(arquivo);
                else
                    MessageBox.Show("Carregue apenas arquivos de Texto (.txt)", "Atenção");
            }
        }
    }


segmentio/parquet fails to read files written with Julia and/or Python

Question: The code below, which was taken almost verbatim from the segmentio/arrow, fails to read .parquet files written with Python and/or Julia libs.  When the code returns from the call to parquet.ReadFile("file") the rows contain 0 values for int64 or "" for strings. The reading fails with codec = {ZSTD, GZIP, or SNAPPY}
type FiRowType struct{ x1, x2, x3 int64 }
func RdFiFile() {
    rows, err := parquet.ReadFile[FiRowType]("fileName_ZSTD.parquet")
    if err != nil {
        log.Fatal(err)
    }
    for _, c := range rows {
        fmt.Printf("%+v\n", c)
    }
}

type FsRowType struct{ x1, x2, x3 string }
func RdFsFile() {
    rows, err := parquet.ReadFile[FsRowType]("fileName_ZSTD.parquet")
    if err != nil {
        log.Fatal(err)
    }
    for _, c := range rows {
        fmt.Printf("%+v\n", c)
    }
}

The Golang code does not return an error, i.e., err == nil.
The code returns the right number of rows and columns, some info in the metadata seems to be correct (like the originator of the file, date of creation etc).  I created the files using Julia:
using Parquet
function WrForGo( )
  min = 1
  max = 10
  # arrays of size (10,3). ai is int and as is
String
  ai = Array{Int64, 2}(undef, 10,3)
  as = Array{String, 2}(undef, 10,3)
  for i =1:max
      for j=1:3
        as[i,j] = string(i, pad=2) * "_" * string(j,pad=2)
        ai[i,j] = (j-1)*10 + i
      end
    end

    dfi = DataFrame(ai, :auto) ; dfs = DataFrame(as, :auto)
    print( dfi ) ;  print( dfs )
    Parquet.write_parquet( prqDir * "fi_ZSTD.parquet", compression_codec = "ZSTD", dfi)
    Parquet.write_parquet( prqDir * "fs_ZSTD.parquet", compression_codec = "ZSTD", dfs)

    Parquet.write_parquet( prqDir * "fi_GZIP.parquet", compression_codec = "GZIP", dfi)
    Parquet.write_parquet( prqDir * "fs_GZIP.parquet", compression_codec = "GZIP", dfs)

    Parquet.write_parquet( prqDir * "fi_SNAPPY.parquet", compression_codec = "SNAPPY", dfi)
    Parquet.write_parquet( prqDir * "fs_SNAPPY.parquet", compression_codec = "SNAPPY", dfs)

end

Comment: It an error is being returned then it's unsurprising that `rows` contains default values. Can you please provide a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (i.e. Python code to generate a file and the full Go code you are using to attempt to read it).
Comment: The code returns no error msg, i.e, err == nil. The code fins the right number of rows and columns, and the  right data types for each column. However when you enter the for loop to print the rows, the rows have zero values.
Answer: In Go variables that start with a lower case character not exported so cannot be updated from other packages (e.g. segmentio/parquet-go). Try the below:
package main

import (
    "fmt"
    "log"

    "github.com/segmentio/parquet-go"
)

type FiRowType struct {
    X1 int64 `parquet:"x1,optional"`
    X2 int64 `parquet:"x2,optional"`
    X3 int64 `parquet:"x3,optional"`
}

func RdFiFile() {
    rows, err := parquet.ReadFile[FiRowType]("fi_ZSTD.parquet")
    if err != nil {
        log.Fatal(err)
    }
    for i, c := range rows {
        fmt.Printf("%d %+v\n", i, c)
    }
}

func main() {
    RdFiFile()
}

Comment: Yes, that was it. I completely forgot that Go only exports variables that start with upper case letters. I guess this happened to me because I am going back and forth between several languages. Thank you much ! ! !