When to use inversions in harmonizing a bass line

Question: What exactly is the procedure for harmonizing a bass line? In my class, the teacher introduced inversions of chords, which are not hard to understand per se, but I can't wrap my head around how can I use them when harmonizing a bass line.
If I have to use strictly triads in root position, I could give each note its degree just by looking at the note. But I understand there are some degrees that can't pass to others, like a chord from the dominant group (V, vii°) to a chord from the subdominant group (IV, ii).  So I know that I can use inversions to solve this issue.
Other than that, what do I have to look for to understand when I could use an inversion?
For example, I have this exercise done in the class:

I know what I'm asking is probably a hassle to explain completely, but my book is pretty hard to understand - at least for me. If anyone could help me, or at least give me some direction to some resource to study from, you'd have my eternal thanks.
Answer: A single bassline can be harmonized in a number of different ways.  Assuming you are working only with diatonic triads (three note chords that require no accidentals), you'll typically have three options for your harmony for each note.  In the key of G major, those options look like this:

G: I, vi6, IV64
A: ii, vii°6, V64
B: iii, I6, vi64
C: IV, ii6, vii°64
D: V, iii6, I64
E:  vi, IV6, ii64
F#: vii°, V6, iii64

I realize this probably looks a little daunting right now, but it becomes easier as you practice.  To show you how we can apply this, let's look at the last four measures of your exercise.  We have the following bassline: D, E, C, D, G, C, G.  I usually find it easiest to work backwards when harmonizing, so let me walk you through that process:
First of all, we already know the last chord has to be a I chords in root position, so let's look at the second to last chord.  We know we need a cadence here, either plagal or dominant.  The only chord we can use that gives us a valid cadence is a IV, a C in root position.  So, our last two chords are basically decided for us.  From here on, we have to start making some decisions...
This is where we start to get out of the realm of right and wrong answers.  You could, for instance, harmonize all six of these chords in root position and not break any rules (V, vi, IV, V, I, IV, I).  That would probably sound alright, although not particularly creative; besides, we want learn about how to use inversions, so let's be a little more daring here.  For instance, we could instead harmonize this passage as iii6, vi, ii, V, vi6 - IV64, IV, I.
Now I could have just picked those chords randomly from my available options, but I actually didn't; there's a method to the madness!  First of all, you'll notice that iii, vi, ii, V is a sequence of descending fifths in the root of the chords.  Whenever you can harmonize with chords where the root descends by a fifth, it will sound very satisfying (you'll learn more about this when you talk about secondary dominants.)  Second, you'll see that I choose to take the V to a iv6 instead of a I, borrowing from the structure of a deceptive cadence.  My other option was to move directly to the IV64, but, as you pointed out, it is unusual in this style of harmony to move from a dominant chord to a subdominant chord, so I eliminated that option.  Lastly, I choose to switch from a vi6 to a IV64 on the third to last note in order to set up the final cadence.  I didn't have to do this, but it makes things a little more interesting to not always line up the harmony one-for-one with the bass line.
One more thing to consider: second inversion (64) chords can be a little tricky and should be used with care.  Typically, second inversion chords are only used in particular ways.  Let's talk very briefly about three common ways you will probably encounter in basic harmonization: passing, neighbor, and cadential.  A passing second inversion occurs when you have stepwise bass movement, for instance: I, V64, I6.  A neighbor second inversion occurs when the bass line stays on the same note while the harmony shifts, for instance: I, IV64, I.  A cadential second inversion occurs when you use the following very common cadential figure: I64, V, I.  This is by no means an exhaustive list, but it's good to keep an eye out for these opportunities to use second inversion chords when scanning your bass line.
In short, for all the notes between the cadences, you have some freedom as to how you'd like to structure the harmony, and your options only grow as you learn more and more theory.  The good news is that with practice all of these patterns become internalized and you can quickly assess your options and make a decision.  Until then, however, the best method is to write out all three options for each chord and then work backwards from the cadences, eliminating the options that won't work and choosing your harmony from the remaining options based on your own aesthetic judgement.

Some Additional notes as per your comments
Can a cadence be set up anywhere in a phrase? For example, how you set up the deceptive cadence between the two measures?
A cadence is specifically at the end of the phrase.  When I wrote about using a deceptive cadence, I meant that I was simply alluding to that type of cadence in my chord choices.  It's not actually considered a cadence unless it falls at the end of a phrase.
My book tells me to not use triads built on the III and VII grades of the scale in Major and Minor and the II in the Minor mode for now. Do you know why?
Triads build on the seventh scale degree in major and the second scale degree in minor turn out to be diminished triads (vii° and ii°), which I suppose you haven't learned how to resolve yet.  I'm not sure why you're being asked not to use iii in major though.  It's pretty common to procede a vi with a iii, but I suppose they want to teach you how to handle voicing that specific case before you start using that chord.  Chords on the third scale degree can be tricky in harmonic minor, as you end up with an augmented chord (III+), but you probably haven't reached that yet.
Should I incur in errors while harmonizing, like parallel/hidden 5ths and 8ves, would the best solution be changing the whole chord, or are they solvable without doing that?
In most cases, you can avoid parallel and hidden 5ths and 8ves by revoicing the chord, rather than changing the harmony, although there are some cases where you may just need to change your harmony to get out of a jam.
Comment: I can't thank you enough!
You clarified most of my doubts. I have some questions left if you don't mind:
> Can a cadence be set up anywhere in a phrase? For example, how you set up the deceptive cadence between the two measures.
> My book tells me to not use triads built on the `III` and `VII` grades of the scale in Major and Minor and the `II` in the Minor mode for now. Do you know why?
> Should I incur in errors while harmonizing, like parallel/hidden 5ths and 8ves, would the best solution be changing the whole chord, or are they solvable without doing that?
Thanks again!
Comment: Good questions.  I'll edit my answer to include responses to these questions, as my reponse won't fit in a comment.
Comment: Thanks once more for the help. I've skimmed through the following chapters of my book, and found out that the peculiarities of the `III` would be its attraction to the `IV` and the matter with its leading tone that could ascend or descend, talking then about how this matter goes to make up the phrygian cadence. And yes, I didn't quite understand the matter.
Answer: Casey Rule gave a fine answer, I just want to point out a few things about harmonizing in general and you should be aware of while trying to harmonize a bass line.

iii chords are quite rare in a major key, in fact in all my classical theory studies I don't remember analyzing anything that used any type of iii chord in a major key.
While vii° is a viable option, it is quite rare to see it outside of first inversion (vii°6) and if you use it, you will be going to a I chord most of the time because how the diminished 5th likes to resolve.
As Casey points out, second inversion chord are considered dissonant and need to be approached carefully. He listed a few way and there are more, but the best way to look at it is only use a second inversion chord if it is a primary chord (I, IV, or V) and is either at the cadence, approached by step to and from, or part of an arpeggio.
Moving the chords by 3rd or 4th is typically more desired then moving by 2nd so seek to use chords that are not next to each other and if you do move by 2nd try not to string a bunch of them in a row.
Casey already cover this well, but learn and understand cadences. While most of the harmony can vary and be looked at different ways, cadences are very important and there are really only a few ways to approach them.

Besides that, do what sounds right. If given only a bass line, there are many different ways to harmonize the same bass line. I would suggest to keep it simple as you start and listen to how the progression sounds. You can always take a simple progression and re-harmonize it later.
Comment: Thanks for the helpful insight.
As for the fourth point, should I favor intervals of 3ds and 4ths between the chords in their root position (not considering the root in an inversion)? I believe my book says the same by calling the intervals of 4th and 5th principal, while calling skips by 2nd strong and by 3rd weak (Noting also how to avoid creating a harmonic syncopation with the latter one).
So, I should try to use mainly principal and weak intervals? (Hopefully the terms are not much different in English)
Comment: @Dodicin Yes in fact most of the time, the inversions are to smooth out the bass. I'm not use to that terminology, but it sounds like what I'm talking about in the fourth point.
Comment: @Dom - What do you mean iii is rare?  I've gone through iii quite often.  And the seventh chord iii7 is **so** common in anime music.
Comment: @MaikaSakuranomiya I was talking in a classical context. In analysis, it may have come up a handful of times in practical pieces.
Comment: I've also seen iii7 in classical pieces as well.  I've seen the iii triad pretty often especially in Baroque period music, for example, in the I-IV-vii*-iii-vi-ii-V-I progression.  iii7 is not really as common, but I've seen it sometimes.
Answer: When you harmonize a passage for four parts what you have to get your head around is that you are writing a melody within the confines of the given chord progressions.
There is somewhat leeway in regards to root position and first inversion but you want to use these inversions in a way as to make the melody you are writing appealing.
So this means smooth transition between chords. A pleasant line and good form needs to be part of this melody.
When it comes to second inversion chords they are only used in very specific cases. These include.

Passing Six Four
Cadential Six Four.

On the other hand where triads in second inversion only comes in specific cases the quadtat(Dominant 7ths) has a great more freedom in regards to its inversion.
When you use chords with sevenths you can easily use them in second and third inversion as long as it makes sense in the melody you are writing.


How to make xvnc not kill the session on exit

Question: I'm implementing a remotedesktop access to a server thru xvnc/xinetd/gdm.
I'd like many users to connect to that server using vnc (thus providing the gdm login screen) and want that if the xvnc session is closed, it would 'xlock' the session so next time user connects it will resume his session.
Tried several parameter tweaks, but unfortunately each time the vnc viewer is closes, the X session is also destroyed.
Help/clues would be really appreciated.
Answer: I don't think you can do it that way.  When the user disconnects, inetd kills the servers which were spawned for that connection.
Try using NX/FreeNX instead, it can do disconnect-session persistence. It can also allegedly connect users to an already running instance on the desktop, but I've never tried that.
Answer: If you are using Xvnc via xinetd, changing the xinetd "wait" parameter to "Yes", causes the GDM session to remain persistent between vnc sessions.  However, it does not auto-lock the GDM session.
here is the xinetd entry I use:
service vnc1024
{
  disable = no
  socket_type = stream
  protocol = tcp
  wait = yes
  user = nobody
  server = /usr/bin/Xvnc4
  server_args = -inetd :1 -desktop lulu-loginvnc-1024 -query localhost -geometry
 1024x768  -once -depth 16 -fp /usr/share/fonts/X11/misc -SecurityTypes=none -Di
sconnectClients=0 -NeverShared
}
make sure you add an entry in /etc/services as well:
# Local services
vnc1024  5920/tcp

Answer: Thanks for the reply,
I was already following the NX way ... Seems to do exactly what i want, oh by the way if you're interested, google just released a free version of freenx too called 'nextx'(http://code.google.com/p/neatx/) still in early stage but tested svn and works fine (until now).


Determine the slopes of a curve, when we know the tangent vectors of the curve

Question: If I have a set of curves in the $xy$-plane with tangent vectors $(1,y)$, how can I conclude that these curves have slope $y$? The context of this question is the PDE $$u_x +yu_y = 0$$
Edit : If the derivation of this result is particularly long or tedious, then please guide me to the relevant theorems/mathematical architecture to which this problem is related.
Answer: By definition, for some parametrization $\mathbf{r}(t)=(x(t),y(t))$ of it, the tangent vector of a curve  is
$$
\left(\frac{\partial x}{\partial t}, \frac{\partial y}{\partial t}\right)
$$
Now you are asking about the slope of the function $x \rightarrow f(x)$ whose graph $(x,f(x))$ is identical to $(x(t),y(t))$. That means that $f(x(t))=y(t)$, so by chain rule
$$
\frac{\partial y}{\partial t} = \frac{\partial f(x(t))}{\partial t} =
\frac{\partial x(t)}{\partial t} \frac{\partial f}{\partial x}(x(t))
$$
For the particular equality that you mention,
$$
\left(\frac{\partial x}{\partial t}, \frac{\partial y}{\partial t}\right)
 = (1,y(t))
$$
you obtain
$$
y(t) = 1 \times \frac{\partial f}{\partial x}(x(t))
$$
and thus $f'(x)=y$.


Do people who read RTL languages read LTR standard notation?

Question: I have been told that standard notation is virtually universal nowadays. Standard notation is, in my experience, read from left to right, a convention that came naturally to me because the only language I know how to read is read LTR.
Because all of the common markings are in Western languages that are also read LTR, this reading order makes sense.
Those who do not read a Latin-based language often do not read LTR (and sometimes not even RTL, either) or have any way of interpreting the written markings by finding similarities between their language and the language the markings are in.
Do people who speak/read languages like Arabic and Chinese write musical markings in their own language and/or read/write music no-LTR?
(Puzzle canons that are meant to be read both forwards and backwards,  etc are not the focus of this question)
Answer: In Israel, the major spoken language is Hebrew, an RTL language (as is Arabic). Sheet music is laid out in standard manner (LTR); lyrics appear under the notes to be sung, but the words themselves are written RTL. I find it very difficult to read a piece of vocal music as I'm trying to read 'both ways at once'. Native Hebrew speakers may not have this problem.
Answer: In Hebrew, songs are sometimes typeset RTL, especially in older books.
Example Another example.
This makes some sense because lyrics go RTL.
This convention is rarely used nowadays. I have never seen it applied to non-vocal music.
Answer: The western classical tradition in these cultures adopts the left-to-right standard notation in use everywhere else in the world. This makes sense, as anyone playing Mahler 2 is going to be reading score directions in German whether you're playing in France, Italy, Spain or the United States.
Original music written in these cultures, but that follow the western classical tradition will usually use the standard notation, but have score markings written in the native language (top-to-bottom, right-to-left, or whatever). This is simply because western classical music requires a whole infrastructure of music education, conservatories, and musicians to play it, so if your country has an orchestra that plays western classical music, chances are a lot more people can also read it. It also makes sense from a publishing perspective to bring music to the largest possible audience by printing in the lingua franca of "standard" notation.
However, the native cultural tradition of music in these places could make use of any number of traditional notation systems that have nothing to do with the western classical tradition. Furthermore, many of these traditions don't make use of notation at all -- music is simply passed down through the ages from teacher to student.
Comment: This seems like a very complete answer written by someone who knows theirs stuff. The first sentence of the second paragraph should be revised for grammatical correctness and clarity, but I think I understand what you meant. Why would having a national orchestra that reads standard LTR Western notation increase the number of people in the country that can read std LTR Western notation ("chances are a lot more people can also read it")? Or did you mean a lot more people in the nat'l orchestra? Other than those confusing points, I really like this answer because it seems to cover everything.


How to pass multiple values in setArguments() and render view?

Question: I want to pass multiple values in setArguments() and render view. I'm using below code but it's showing only 1 value instead of multiple.
<code> public function _ajax_generate_request_view(array $form, FormStateInterface $form_state) {
  $view = \Drupal\views\Views::getView('play_center_generate_request');
  $view->setArguments(array('23','46'));
  $view->execute();
  $render_view = $view->render();
  $ajax_response->addCommand(new HtmlCommand('#view_wrappers', $render_view));
  return $ajax_response;
}
</code>
Answer: Depends if you need OR or AND clause :
<code>$view->setArguments(array('23,46'));
$view->setArguments(array('23+46'));
</code>
One string for each argument.
Comment: Working....!!!!


I believe this problem has a typo, but I want to make sure before telling my teacher. Does it?

Question: An amphitheater charges $74$ dollars for each seat in Section A, $59$ dollars for each seat in Section B, and $28$ dollars for each lawn seat. There are three times as many seats in Section B as in Section A. The revenue from selling all $13,000$ seats is $\$503,000$. Let $x$ be the number of seats in A, $y$ be the number of seats in B, and $z$ be the number of lawn seats. Which system of equations represents the situation?
There are 2 answers to the question, the problem is multiple choice. The first answer is below:
$$y=3x$$
$$x+y+z=503,000$$
$$74x+59y+28z=13,000$$
The second:
$$y=3x$$
$$x+y+z=13,000$$
$$74x+59y+28z=503,000$$
Wouldn't the correct answer be:
$$x=3y$$
$$x+y+z=13,000$$
$$74x+59y+28z=503,00$$
Comment: What's the difference between the first and the second answer?
Comment: in the first, $x+y+z=503,000$

in the second, $x+y+z=13,000$
Answer: It is correct.
$y=3x$ means that $y$ is three times as large as $x$. For example, if there are $x=2$ section A seats, then there are $y=3x=6$ section B seats, so we have here that there are three times as many seats in section B as in section A.
Comment: Wow... that's embarrassing on my part. How did I not realize that? I've been sitting here blanking for like 20 minutes trying to wrap my head around $$y=3x$$


Let $m$ be Lebesgue measure and $a \in R$. Suppose that $f : R \to R$ is integrable, and $\int_a^xf(y) \, dy = 0$ for all $x$. Then $f = 0$ a.e.

Question: This is a corollary to a proof in Bass, but I don't understand why it follows from the proof he gives. I follow everything up until the last statement. Why is it that proving that the integral is $0$ for all Borel measurable sets guarantees it is true for all Lebesgue measurable sets? Am I missing something vital about the relationship between Lebesgue measurable sets and Borel measurable sets?
Statement: Let $m$ be Lebesgue measure and $a \in\mathbb R$. Suppose that $f : \mathbb R \to\mathbb R$ is integrable, and $\int_a^xf(y) \, dy = 0$ for all $x$. Then $f = 0$ a.e.
Proof: We prove the conclusion first for intervals, then for unions of intervals, then for open sets, then for Borel measurable sets. For any interval $(c,d)$, we have
$$\int_c^df = \int_a^d f - \int^c_a f = 0.$$
By linearity, if $G$ is the finite union of disjoint open intervals, then $\int_G f = 0$. Now, if $G$ is open, then $G$ is the countable union of disjoint, open intervals, $G = \bigcup^n_{i=1}I_i$. We have
$$\int_G f = \int \lim_{n\to\infty} f \cdot \chi_{\bigcup^n_{i=1} I_i}$$
and since $f_n$ is integrable for all $n$, and $|f_n| \le f$ for all $n$, by the dominated convergence theorem,
$$\int_G f = \lim_{n\to\infty} \int_{\bigcup^n_{i=1}I_i} f =0.$$
Now, if $G_n$ is a decreasing sequence of open sets converging to $H$, since $|f \cdot \chi_{G_n}| \le f \cdot \chi_{G_1}$ for all $n$, we again have by the DCT that $\int_H f = 0 = \lim_{n\to\infty} \int_{G_n}f = 0$.
Finally, if $G$ is a Borel measurable set, then we know that there exists a sequence $G_n$ of decreasing, open sets, that converge to some set $H$, where $H \setminus G$ is a null set. Thus,
$$\int_G f = \int_H f = 0.$$
We have found that for every Borel measurable set $G$, $\int_G f =0$. Since $f$ is real valued and measurable, $f = 0$ a.e.
Comment: You need the characterization of measurable sets: they are the union of a Borel set and a set of measure zero.
Comment: Perfect, that's exactly what I was looking for! Thank you. You are welcome to make your comment an answer.
Comment: This question has been asked before on this site. Maybe someone can find the original and mark as duplicate.
Answer: You need the characterization of measurable sets:

Let $G \subset \Bbb{R}^k$ a bounded set. Then the following are equivalent:

$G$ is Lebesgue measurable.

There exist $B, N \subset \Bbb{R}^k$ such that $G = B \cup N$, $B$ is Borel, $N$ has zero Lebesgue measure.

Now, to conclude your exercize call $G= \{ x : f(x) >0\}$ and write $G=\bigcup_n (G \cap [-n,n])$ as a union of bounded measurable sets. Use the characterization to write $G \cap [-n,n] = B_n \cup N_n$. Finally
$$\int_{G \cap [-n,n]} f = \int_{B_n} f = 0$$
So $f=0$ a.e. in $G \cap [-n,n]$. Since $n$ is arbitrary, you have $f=0$ a.e. in $G$.
Do the same thing with $H=\{ x : f(x) <0\}$ and you are done.


How to send a GET request with an array as a parameter?

Question: I was trying to create a function to make a GET with query parameters. I was dealing with the Mangadex API and was to send a parameter called 'manga' as an array. I created the code as follows:
Future<http.Response> getCoverArtResponse(String mangaID) async {
  var queryParameters = {
    'limit': '10',
    'manga': [mangaID] //Here
  };
  var unencodedPath = '/cover';
  var response = await http.get(
      Uri.https(authority, unencodedPath, queryParameters),
      headers: {HttpHeaders.contentTypeHeader: 'application/json'});
  return response;
}

However, the response was the following error:
{"result":"error","errors":[{"id":"9c346772-7b14-5982-b4b6-7b5888522762","status":400,"title":"validation_exception","detail":"Error validating \/manga: String value found, but an array is required","context":null}]}

How am I supposed to send the parameters? So far I have tried -
'manga': [mangaID]
'manga': '[$mangaID]'

None of them seem to work.
Comment: It really depends on how their server expects arrays to be encoded in the query string. [It does not seem like there is a standard](https://stackoverflow.com/questions/6243051), and the Mangadex documentation doesn't seem to explicitly specify the format, but it does imply that they expect the key to be `manga[]`, not `manga`.  Therefore try: `'manga[]': [mangaID]`.
Answer: import 'dart:async';
import 'package:wnetworking/wnetworking.dart';

class MangaDex {
  static const _base = 'https://api.mangadex.org';

  static FutureOr<void> _getter({required String url, required Function(JMap item, int idx) onItem}) async {
    await HttpReqService.getJson<JMap>(url)
      .then((response) {
        var results = response?['results'];
        if (results != null) {
          if (results is List) {
            var i = 0;
            results.forEach((manga) => onItem(manga, ++i));
          } else {
            print(response);
          }
        }
      });
  }

  static FutureOr<void> cover({int limit = 10, int offset=0, String? mangaId, String? coverId}) async {
    final mangas = mangaId != null ? '&manga[]=$mangaId' : '';
    final covers = coverId != null ? '&ids[]=$coverId' : '';
    final url = '$_base/cover?limit=$limit&offset=$offset$mangas$covers';

    await _getter(
      url: url,
      onItem: (item, idx) {
        print('$idx) "${item['data']?['attributes']?['fileName']}"');
        print('   id: ${item['data']?['id']}\n');
      },
    );
  }
}

void main(List<String> args) async {
  await MangaDex.cover(mangaId: '32d76d19-8a05-4db0-9fc2-e0b0648fe9d0', limit: 2);
  print('\nJob done');
}

Result:
1) "f5873770-80a4-470e-a11c-63b709d87eb3.jpg"
   id: b6c7ce9c-e671-4f26-90b0-e592188e9cd6

2) "e9f926db-b469-48c4-8cc4-a8e523ad75ca.jpg"
   id: 00aae6e0-46bb-4f92-a82a-1c740789b704

Job done

Replace wnetworking package with http package, and JMap with Map<String, dynamic>
NOTE: MangaDex Documentation is lacking and misleading about how to correctly use its endpoints.
Comment: Yeah thank you very much that worked fine. However, this code seems interesting and I would like to know more about it, could you please explain how it works? Or could you please link an article to an example? That would be very kind of you, thanks. I understand the cover function but I don't understand what the _getter is doing.
Comment: It is simple, `_getter` method is responsible for calling GET requests, when getting a valid response (a List), it runs an operation (`onItem` function) per every item on that response. This method is useful for endpoints with things in common.


Multi column CSS make the first column wider

Question: Im using a multi column div. Please see CSS below:

    Super duper long text....

#content {
    -webkit-column-width: 300px!IMPORTANT;
    -moz-column-width: 300px!IMPORTANT;
    column-width: 300px!IMPORTANT;
}

It works just fine. All of my columns are 300px. Is there any way to make the first column 500px using css?
Comment: It seems to be not possible: https://stackoverflow.com/questions/2453522/is-there-a-way-to-specify-different-widths-for-columns-in-css3
Answer: You can use flex for it
Below is example :
You can play with below properties
.header,
.footer  { flex: 1 100%; }
.sidebar { flex: 1; } /* You can change property*/
.main    { flex: 2; }

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  height: 200px;

  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;

  -webkit-justify-content: space-around;
  justify-content: space-around;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-align-items: stretch;
  align-items: stretch;
}

.header,
.footer  { flex: 1 100%; }
.sidebar { flex: 1; }
.main    { flex: 2; }

.flex-item {

  background: tomato;
  padding: 10px;
  width: 100px;
  border: 3px solid rgba(0,0,0,.2);

  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}

Header

Sidebar

Main

Sidebar

Footer

Answer: To make first column wide use this code :
=> CSS
    .div_style:first-child
{
    border:1px solid black;
    width: 500px;
}
.div_style
{
    border:1px solid black;
    width: 300px;
}

=> HTML

    Super duper long text....

    Super duper long text....

    Super duper long text....


Simplification of $\int_0^{\frac{\pi}{2}}\sin^{n-1}x \sin x dx$

Question: I don't see how they derived this step, could someone please explain?
$$\int_0^{\frac{\pi}{2}}\sin^{n-1}x \sin x dx = sin^{n-1}x (-\cos x ) |_0^{\frac{\pi}{2}} - \int_0^{\frac{\pi}{2}} (n-1) \sin^{n-2} x \cos x (- \cos x) dx$$
Comment: Integration by parts.
Answer: This follows directly from partial integration.
If you choose $f(x) = \sin^{n-1}(x)$ and $g'(x) = \sin(x)$, then you have $g(x) = -\cos(x)$ and $f'(x) = (n - 1) \sin^{n - 2}(x) \cos(x)$.
Answer: Hint
Let $u=\sin^{n-1}(x)$ and $v'=\sin(x)$
then
$u'=(n-1)\sin^{n-2}(x)(\cos(x))$,
$v=-\cos(x)$
and
$$\int_0^{\frac{\pi}{2}}uv'=[uv]_0^{\frac{\pi}{2}}-\int_0^{\frac{\pi}{2}}u'v$$


How to have logs about users logins/logouts in a NIS server?

Question: I have a NIS server in a Debian machine with several user accounts in passwd and shadow files.
Also, I have 10 Ubuntu desktop boxes rununning as NIS clients. The users can login by binding to the NIS server (in those boxes there is only root account in passwd and shadow files).
Everything works fine.
However, I'd like to see logfiles in the server about users logging in and logging out in the client stations (with timestamp and IP or station name). My problem is: I can't find where are these logs or how to configure ypbind or ypserv to do so. Is it not possible?
Comment: You know....this question might be better on UNIX or SuperUser SE
Answer: The NIS server will tell you nothing useful.
You can configure your NIS server to log all requests, but authentication checks happen on the client.  All the NIS server is asked for is a copy of the passwd entry (username, UID, GID, encrypted password, etc.), which it will happily give to anyone who asks.
The client then performs authentication against that data the same way it would for a local user, determines success or failure, and acts accordingly.
In other words, your NIS server doesn't know who logged in, or if the login succeeded. All it knows is someone asked it for some information.
The NIS servers may not even be consulted for every login (particularly if you're using nscd or something else to cache lookups).
Of course given the above there is also no reason to consult the NIS server for a logout. The NIS server doesn't care when you ended your session.

What you probably want to do is collect auth.log or equivalent from each of your NIS clients and forward those events to a central loghost where you can examine them.
This could be combined with event auditing to accurately track login/logout times.
Comment: Ok, now I undestood the problem and will forward stations auth.log as you suggested. Thank you very much for the nice didactic explanation.
Answer: Each system keeps a log of users logged in / out.... you can read it out using last.


Finding the joint density function of $(X+Y,X)$ with $X$ and $Y$ independent and following an exponential distribution with parameter $\lambda>0$

Question: Given two independent random variables $X$ and $Y$ that both follow an exponential distribution of parameter $\lambda > 0$, I am trying to find the joint density function of $(X+Y,X)$.
I have managed to prove that the density function of $X+Y$ is the density function of a $\Gamma(2,\lambda)$ distribution but I am struggling to find the joint density function of $(X+Y,X)$. I have tried to find its distribution function in order to calculate the derivative, but I have not succeeded.
Thanks in advance for the help !
Comment: Hint: begin after first noting that the support of the joint pdf is the second octant and not the first quadrant.
Answer: Here is one approach. We will assume $a \geq b \geq 0$. First condition over the value of $X$:
$$P(X+Y \leq a, X \leq b) = \int_{-\infty}^{b}P(X+Y \leq a|X=x)f_X(x) dx$$
Then use the density function of $X$ and the fact $X$ and $Y$ are independent
$$=\int_{0}^{b}P(x+Y \leq a)\lambda e^{-\lambda x}dx=\int_{0}^{b}P(Y \leq a-x)\lambda e^{-\lambda x}dx$$
$$=\int_{0}^{b}(1-e^{-\lambda (a-x)})\lambda e^{-\lambda x}dx=\lambda \int_{0}^{b} e^{-\lambda x} - e^{-\lambda (a-x)-\lambda x}dx$$
$$=\lambda((\frac{e^{-\lambda b}}{-\lambda} - \frac{e^{0}}{-\lambda})-e^{-\lambda a}(b-0)) = 1-e^{-\lambda b}-b\lambda e^{-\lambda a}$$
Now to find the joint density we need
$$\frac{\partial^2}{\partial a \partial b} (1-e^{-\lambda b}-b\lambda e^{-\lambda a}) = \lambda^2 e^{-\lambda a}.$$
Now note if $a < b$, $\{X+Y \leq a, X \leq b\} \implies Y<0$, and so
$$P(X+Y \leq a, X \leq b)=0$$
And also if $b<0$,
$$P(X \leq b)=0$$
Combining this all together yields
$$f_{X+Y,X}(a,b) = \begin{cases}
\lambda^2 e^{-\lambda a} & a \geq b \geq 0 \\
0 & \text{otherwise}
\end{cases}$$
Comment: Thank you so much for your answer, it's crystal clear now !
Comment: Unless you include indicator functions, or otherwise describe the _support_ of the joint pdf, your answer is wrong.  -1 pending appropriate edits.
Comment: @DilipSarwate you are correct, I've edited now.
Comment: Thank you. I have removed my downvote.


Generating schedule for pair game

Question: We have 8 players.
On one table plays 4 players (two pairs).

So every player need to be pair with all other 7 players and to have that players as opponent same count.
In case of just creating tables with deleting it from list we have:
Tour 1: (1,2) - (3,4) | (5,6) - (7,8)
Tour 2: (1,3) - (2,5) | (4,7) - (6,8)
.....................................
.....................................
Tour 7: (1,8) - (2,7) | (3,6) - (4,5)

But some payers will have some opponents often than others.
In that direction I need to think?
****UPDATE****
In case of Jens Schauders solution we'll have 7 rounds. And if chack opponents for player 2 we will have 3 times opponent 4 and just one time opponent 7.
If split pair in this schema
       TABLE 1 |  TABLE 2

Pair1: 1    2  |  3    4
      ------------------
Pair2: 5    6  |  7    8

Where is mistake?
Answer: I think there is an easy visualization for the algorithm you are looking for:
Imagine a long table with opponents sitting opposite of each other:
1    2    3    4
----------------
5    6    7    8

Now for each new round everybody moves to the place left of him. Possibly to the other side of the table, with one exception: Player one keeps her seat. So the next round would look like this
1    5    2    3
----------------
6    7    8    4

If you now split the long table in two part you get suitable pairings for your small tables.
Regarding the updated question
To achieve a more evenly distributed opponents one could try to split the large table differently, e.g building a small table from first and fourth column, and the second small table from column 2+3
Comment: There are little problem. Could you please the question update?
Comment: I tried all variants (even in diagonal), but at least one opponent appear 3 times.
Answer: You can have 6 unique games between 4 teams. There are 7 possible pairing hence 42 unique games.
Each player pairs up with every other player only once and play against each one of them 6 times exactly.
List:
Pairs 01: (1,2),(3,4),(5,6),(7,8)
PairRound 1:
GameRound 01: (1,2) - (3,4) | (5,6) - (7,8)
GameRound 02: (1,2) - (7,8) | (3,4) - (5,6)
GameRound 03: (1,2) - (5,6) | (3,4) - (7,8)

Pairs 02: (1,3),(2,4),(5,7),(6,8)
PairRound 2:
GameRound 04: (1,3) - (2,4) | (5,7) - (6,8)
GameRound 05: (1,3) - (6,8) | (2,4) - (5,7)
GameRound 06: (1,3) - (5,7) | (2,4) - (6,8)

Pairs 03: (1,4),(2,3),(5,8),(6,7)
PairRound 3:
GameRound 07: (1,4) - (2,3) | (6,7) - (5,8)
GameRound 08: (1,4) - (5,8) | (2,3) - (6,7)
GameRound 09: (1,4) - (6,7) | (2,3) - (5,8)

Pairs 04: (1,5),(2,6),(3,7),(4,8)
PairRound 4:
GameRound 10: (1,5) - (2,6) | (3,7) - (4,8)
GameRound 11: (1,5) - (4,8) | (2,6) - (3,7)
GameRound 12: (1,5) - (3,7) | (2,6) - (4,8)

Pairs 05: (1,6),(2,5),(3,8),(4,7)
PairRound 5:
GameRound 13: (1,6) - (2,5) | (3,8) - (4,7)
GameRound 14: (1,6) - (4,7) | (2,5) - (3,8)
GameRound 15: (1,6) - (3,8) | (2,5) - (4,7)

Pairs 06: (1,7),(2,8),(3,5),(4,6)
PairRound 6:
GameRound 16: (1,7) - (2,8) | (3,5) - (4,6)
GameRound 17: (1,7) - (4,6) | (2,8) - (3,5)
GameRound 18: (1,7) - (3,5) | (2,8) - (4,6)

Pairs 07: (1,8),(2,7),(3,6),(4,5)
PairRound 8:
GameRound 19: (1,8) - (2,7) | (3,6) - (4,5)
GameRound 20: (1,8) - (4,5) | (2,7) - (3,6)
GameRound 21: (1,8) - (3,6) | (2,7) - (4,5)

Answer: Below are two schedules. The 1st schedule is a 2 round robin fixed partners schedule.  It is a balanced 2 round robin "pairs" schedule. Or, another way of putting it is we are scheduling 'pairs' of 'pairs'.  I think it's what you are looking for?
The 2nd schedule is a "balanced" 2 round robin 'singles' schedule for 8 players (each player is a team).
Note: On both schedules, all players/teams rotate through the all the tables. There is no player/team fixed in a set location which is undesirable for most leagues because it creates unbalanced time slot distribution. The other two answers posted on this thread locks in a single team in a single time slot then rotates the other 7 teams through that time slot.
The PAIRS-4 schedule below is a fixed partner schedule. We also have an 8 player rotating partners schedule. In each round robin all players are partnered with each of the other 7 players once, and play against all the other players exactly twice.
PAIRS-4 SCHEDULE                     Date 8/4/14
-
DATE   DAY  TIME   LOCATION     GM#   HOME  v  AWAY
Week 1
AUG  4 MON  6:00pm Table-1       1  #1 & #2 v #7 & #8
AUG  4 MON  6:00pm Table-2       1  #3 & #4 v #5 & #6
Week 2
AUG 11 MON  6:00pm Table-1       2  #7 & #8 v #3 & #4
AUG 11 MON  6:00pm Table-2       2  #5 & #6 v #1 & #2
Week 3
AUG 18 MON  6:00pm Table-1       3  #1 & #2 v #3 & #4
AUG 18 MON  6:00pm Table-2       3  #5 & #6 v #7 & #8
Week 4
AUG 25 MON  6:00pm Table-1       4  #5 & #6 v #3 & #4
AUG 25 MON  6:00pm Table-2       4  #7 & #8 v #1 & #2
Week 5
SEP  1 MON  6:00pm Table-1       5  #1 & #2 v #5 & #6
SEP  1 MON  6:00pm Table-2       5  #3 & #4 v #7 & #8
Week 6
SEP  8 MON  6:00pm Table-1       6  #7 & #8 v #5 & #6
SEP  8 MON  6:00pm Table-2       6  #3 & #4 v #1 & #2
-
========================================================
-
SINGLES-8 SCHEDULE               Date 8/5/14
-
DATE   DAY  TIME    LOCATION   GM#  HOME v AWAY
Week 1
AUG  5 TUE  6:00pm  Table-1     1   #1 v #8
AUG  5 TUE  6:00pm  Table-2     1   #2 v #7
AUG  5 TUE  6:00pm  Table-3     1   #3 v #6
AUG  5 TUE  6:00pm  Table-4     1   #4 v #5
Week 2
AUG 12 TUE  6:00pm  Table-1     2   #5 v #2
AUG 12 TUE  6:00pm  Table-2     2   #8 v #6
AUG 12 TUE  6:00pm  Table-3     2   #7 v #1
AUG 12 TUE  6:00pm  Table-4     2   #3 v #4
Week 3
AUG 19 TUE  6:00pm  Table-1     3   #2 v #3
AUG 19 TUE  6:00pm  Table-2     3   #5 v #7
AUG 19 TUE  6:00pm  Table-3     3   #4 v #8
AUG 19 TUE  6:00pm  Table-4     3   #6 v #1
Week 4
AUG 26 TUE  6:00pm  Table-1     4   #6 v #4
AUG 26 TUE  6:00pm  Table-2     4   #1 v #5
AUG 26 TUE  6:00pm  Table-3     4   #7 v #3
AUG 26 TUE  6:00pm  Table-4     4   #8 v #2
Week 5
SEP  2 TUE  6:00pm  Table-1     5   #3 v #5
SEP  2 TUE  6:00pm  Table-2     5   #4 v #1
SEP  2 TUE  6:00pm  Table-3     5   #2 v #6
SEP  2 TUE  6:00pm  Table-4     5   #7 v #8
Week 6
SEP  9 TUE  6:00pm  Table-1     6   #6 v #7
SEP  9 TUE  6:00pm  Table-2     6   #4 v #2
SEP  9 TUE  6:00pm  Table-3     6   #5 v #8
SEP  9 TUE  6:00pm  Table-4     6   #1 v #3
Week 7
SEP 16 TUE  6:00pm  Table-1     7   #7 v #4
SEP 16 TUE  6:00pm  Table-2     7   #8 v #3
SEP 16 TUE  6:00pm  Table-3     7   #2 v #1
SEP 16 TUE  6:00pm  Table-4     7   #5 v #6
Week 8
SEP 23 TUE  6:00pm  Table-1     8   #7 v #2
SEP 23 TUE  6:00pm  Table-2     8   #6 v #3
SEP 23 TUE  6:00pm  Table-3     8   #5 v #4
SEP 23 TUE  6:00pm  Table-4     8   #8 v #1
Week 9
SEP 30 TUE  6:00pm  Table-1     9   #6 v #8
SEP 30 TUE  6:00pm  Table-2     9   #1 v #7
SEP 30 TUE  6:00pm  Table-3     9   #4 v #3
SEP 30 TUE  6:00pm  Table-4     9   #2 v #5
Week 10
OCT  7 TUE  6:00pm  Table-1    10   #7 v #5
OCT  7 TUE  6:00pm  Table-2    10   #8 v #4
OCT  7 TUE  6:00pm  Table-3    10   #1 v #6
OCT  7 TUE  6:00pm  Table-4    10   #3 v #2
Week 11
OCT 14 TUE  6:00pm  Table-1    11   #5 v #1
OCT 14 TUE  6:00pm  Table-2    11   #3 v #7
OCT 14 TUE  6:00pm  Table-3    11   #2 v #8
OCT 14 TUE  6:00pm  Table-4    11   #4 v #6
Week 12
OCT 21 TUE  6:00pm  Table-1    12   #1 v #4
OCT 21 TUE  6:00pm  Table-2    12   #6 v #2
OCT 21 TUE  6:00pm  Table-3    12   #8 v #7
OCT 21 TUE  6:00pm  Table-4    12   #5 v #3
Week 13
OCT 28 TUE  6:00pm  Table-1    13   #2 v #4
OCT 28 TUE  6:00pm  Table-2    13   #8 v #5
OCT 28 TUE  6:00pm  Table-3    13   #3 v #1
OCT 28 TUE  6:00pm  Table-4    13   #7 v #6
Week 14
NOV  4 TUE  6:00pm  Table-1    14   #3 v #8
NOV  4 TUE  6:00pm  Table-2    14   #1 v #2
NOV  4 TUE  6:00pm  Table-3    14   #6 v #5
NOV  4 TUE  6:00pm  Table-4    14   #4 v #7
-
-                 # # # # #
-

You can copy & paste the schedules above into your word processor and use
Search & Replace to replace the player numbers with real names.  You can also
edit the schedule, ie, change dates & times, add notes, graphics, contact
info for each player, etc.
Comment: There's no need to include your signature in the post as it's automatically attached to the bottom of the post.

Generating schedule for pair game


Intuition about the coupon collector problem approaching a Gumbel distribution

Question: The coupon collector's problem
Let there be $n$ different types of coupons and we try to collect all of the types.
We do this by independent random draws of coupons in which each type of coupon has an equal probability, $1/n$, to be drawn.
How many draws $k$ do we need to collect all coupons?
What is the probability distribution of the variable $K$?
Solution

The distribution of $K$ follows the distribution
$$P(K \leq k) = \frac{k!{{n}\brace{k}}}{k^n}$$ where ${{n}\brace{k}}$ are Stirling numbers of the second kind.

The distribution can also be seen as the distribution of the sum of independent geometric distributed variables. $$K = \sum_{i=1}^{n} X_i \qquad \text{with $X_i \sim Geom(p = i/n)$}  $$

Problem of this question
We can approximate the above results with a Gumbel distribution.

I have found in a section of the Wikipedia page that several people found the limiting distribution $e^{-e^{-c}}$, but no resources are given.
In 'asymptotics of the Stirling number of the second kind revisited' by Guy Louchard it is stated on page 196 that Erdõs and Szekeres came with a an approximation for the Stirling number of the second type in the form of $e^{-e^{-c}}$. But the resource points to page 164 in Sachkov's book 'probabilistic methods in combinatorial analysis' and I can not track down the original source (and there is a lot to search through).
The article from Lars Holst, 'Extreme value distributions for random coupon collector and birthdays problems', is getting close to what I am searching for. But it still becomes quite technical.

So, what I am trying with this question is prove that the coupon collector's problem approaches the Gumbel distribution. Potentially, make it also intuitive why it is a type of extreme value distribution that is the limiting distribution. Is there a relation with extreme values? Or do extreme values and these types of combinatorial problems for some reason have similar behavior in the limit?
I have tried to manipulate the characteristic function of the sum of geometric variables but got stuck there. Maybe I have to dig harder or try some other route.
Comment: Doesn't this come down to a direct application of the [Fisher-Tippett-Gnedenko theorem?](https://en.wikipedia.org/wiki/Fisher%E2%80%93Tippett%E2%80%93Gnedenko_theorem)
Comment: Fair enough.  I just looked at the abstract of Holst's paper--it sketches the connection.
Answer: Below is a bastardized short version of the connection made in the paper by Holst:
The connection with the Gumbel distribution is made with the following steps...

Viewing the waiting time to collect all the coupons by the individual waiting times to collect each individual coupon.
The waiting time to collect all coupons is the maximum of these individual waiting times.
The individual waiting times are approximately independent and exponential distributed (this independence is still fuzzy to me).
Then the waiting time to collect all coupons approaches an extreme value distribution. Since the distributions involved are approximately exponential distributions, the limiting distribution will be a Gumbel distribution.

An illustration relating to Holst's approach in this post on mathematics.
Comment: @Alexis I made an illustration relating to Holst's approach in [this post on mathematics](https://math.stackexchange.com/a/4283180). It may help to explain the difference. In this approach, the variables are considered as a Poisson process and in that case, the connection between the 'watining time' and the 'extreme value' is very clear and without any troubles....
Comment: ... the trouble with the Birthday problem is that it is not like that Poisson noise. The waiting time is in the number of coupons, with the Poisson process the waiting time is the unit of time. After waiting for one coupon, it is *certainly* gonna give you a coupon (so that's the dependence; if one box is without coupons this increases the probability of another contacting is). With the Poisson process, after waiting one unit of time, you may have a different number of coupons....
Comment: --- But, this is just fuzzy. Intuitively I see these problems disappear for a larger number of coupons. The exponential distribution for the Poisson process and the geometric distribution for the coupons are gonna be very close to each other. In addition the 'Poissonation' and approximation of the coupons as independent Poisson processes exponential variables becomes better when the number of coupons is very large.
Comment: +1 Sextus Empiricus, Can you say a little about your fuzziness regarding the independence of the argument about individual waiting times (of each coupon) being approximately **independent** (and exponentially distributed)? The notion that the coupon problem can be conceived of as sampling with replacement makes me hunch at independence, so I would love to learn why that might not be the case.


SSIS 2012 Send Mail Task with an attachment

Question: My SSIS package writes a log file during the execution. In the end it calls another package that sends that log file via email.
I'm not able to send it (the email without the attachment works fine) and I always get this error:
[Send Mail Task] Error: Either the file "F:\ etc..." does not exist or you do not have permissions to access the file.
I've already tried to:
- set DelayValidation property to True for the Send Mail Task;
- close the filestream of the log file before sending the email.
but nothing changes...
Comment: The error is about permissions, so what have you done in terms of looking at the permissions? Do both packages run in the same security context? What permissions does that context have on the file and the folder containing the file?
Answer: I added the file extension to the file path and now it works! I also left DelayValidation property set to True for the Send Mail Task.
I didn't think of it because I saw that Windows opened the file, even if without extension.


Proving a function is continuous on all irrational numbers

Question:
Let $\langle r_n\rangle$ be an enumeration of the set $\mathbb Q$ of rational numbers such that $r_n \neq r_m\,$ if $\,n\neq m.$ $$\text{Define}\; f: \mathbb R \to \mathbb R\;\text{by}\;\displaystyle f(x) = \sum_{r_n \leq x} 1/2^n,\;x\in \mathbb R.$$
  Prove that $f$ is continuous at each point of $\mathbb Q^c$ and discontinuous at each point of $\mathbb Q$.

I find this question very challenging and have no idea even how to start off with the proof. Please suggest a proof or any hint.
Comment: A simple hint: can you show that if $x_0\in\mathbb{Q}$, then $\lim_{x\to x_0^-}f(x)$ exists and is $\neq f(x_0)$?
Comment: You may find this paper interesting: http://arxiv.org/pdf/0901.2360v1.pdf (see Example 1)
Answer: This is a part of my answer here, but it should completely answer your questions too.
I use the notation $$\lim_{y\to x^{+}}f(y)=f(x^+)$$  $$\lim_{y\to x^{-}}f(y)=f(x^-)$$

There is a very nice way of constructing, given a sequence $\{x_n\}$ of real numbers, a function which is continuous everywhere except the elements of $\{x_n\}$ [That is, discontinuous on a countable set $A\in\Bbb R$]. Let $\{c_n\}$ by any nonnegative summable sequence [that is $\sum\limits_{n\geq 0} c_n$ exists finitely], and let $$s(x)=\sum_{x_n<x} c_n$$
What we do is sum through the indices that satisfy the said inequality. Because of absolute convergence, order is irrelevant. The function is monotone increasing because the terms are nonnegative, and $s$ is discontinuous at each $x_n$ because $$s(x_n^+)-s(x_n^-)=c_n$$
However, it is continuous at any other $x$: see xzyzyz's proof with the particular case $c_n=n^{-2}$. In fact, this function is lower continous, in the sense $\lim\limits_{y\to x^{-}}f(y)=f(x^-)=f(x)$ for any value of $x$. If we had used $x_n\leq x$, it would be upper continuous, but still discontinuous at the $x_n$.
To see the function has the said jumps, note that for $h>0$, we have $$\begin{align} s(x_n^+)-s(x_n^-)&=\\ \lim_{h\to 0^+} s(x_k+h)-s(x_k-h)&=\lim_{h\to 0^+}\sum_{x_n<x_k+h} c_n-\sum_{x_n<x_k-h}c_n\\&=\lim_{h\to 0^+}\sum_{x_k-h\leq x_n<x_k+h} c_n\end{align}$$
and we can take $\delta$ so small that whenever $0<h<\delta$, for any given $x_m\neq x_k$, $x_m\notin [x_k-\delta,x_k+\delta)$, so the only term that will remain will be $c_k$, as desired.
Comment: Dear Pedro, would such a function be $0$ at a point $x$ where $x< x_{k}$ for all the elements of the sequence? Also, would you know how one would go about showing whether are not such function is differentiable at the points outside the sequence?
Answer: Here's an easy reason why this is true: look at the interval from 0 to 1. there are only finitely many fractions with a given base between 0 and 1. There is only one with base 2, (I.e, 1/2), two with base 3, etc. so as you approach any irrational number by a sequence , that sequence is going to run out of all the fractions with small bases.
The same thing is true as you approach any rational number; so in either case, the limit as you approach a number is 0. Since that agrees with the function for irrationals, it's continuous there. Since it disagrees at a rational, it's discontinuous.


Regression with random X

Question: Suppose we have a standard regression model
$$Y= X\beta + \epsilon$$
with
$$\epsilon \sim \sigma^2$$
$$X \sim N(\mu,\gamma^2)$$
Are the estimated coefficients the same as if $X$ was fixed?
Is the estimated variance of $\hat{\beta}$ the same?
Thanks!
Answer: If we assume that
$$
{\rm E}[\varepsilon | X] = 0,
$$
then the regression coefficients are still calculated as
$$
\hat{\beta} = (X^TX)^{-1}X^TY.
$$
The variance of $\hat{\beta}$, however, is no longer the same as the one in the deterministic case since expression
$$
\sigma^2(X^TX)^{-1} =: {\rm Var}[\hat{\beta} | X]
$$
is now a random variable. To calculate the overall, unconditional variance of $\hat{\beta}$, we use the rule
$$
{\rm Var}[\hat{\beta}] = {\rm E}[{\rm Var}[\hat{\beta} | X]] + {\rm Var}[{\rm E}[\hat{\beta} | X]].
$$
The landmark book by
... Greene, W. H. (2011). Econometric Analysis (7th ed). Upper Saddle River, NJ: Prentice Hall.
covers the case of stochastic predictors in detail in the earlier chapters.
Answer: Regression is the analysis of the conditional distribution of a response variable $Y$ given an explanatory variable $X$.  The parameters in the regression model are measuring terms in the expectation of the response variable conditional on the explanatory variable, so the model, and the corresponding estimation method, so it will always treat the explanatory variable as a constant.
To the extent that you are interested in the marginal distribution of $Y$ when $X$ is a random variable, that is no longer a question about regression analysis --- it is multivariate analysis.  In that case you formulate a broader model that will its own parameters to describe the marginal distribution of $Y$.

Regression with random X


To have a REST service as a plugin

Question: Lets say I have some REST service A running. As part of a client request, it does steps 1, 2 and 3. I want to enable a few third party REST servers to be able to do step 2 for me. Lets say REST services B, C or D could plug in into / register with A and do the step 2 on its behalf.
So the flow would look something like:

Service B registers with A (or A discovers B somehow) with its config - URL, security supported, version, etc.
A gets a request from a client, performs 1, makes a call into B, gets the response back from B and then performs 3 before responding the result to the client.

What design pattern should be followed here to ensure extensibility and scalability? One of the challenges I see here is the need to ensure contract between A and B or C is correct.
Answer: You got the design mostly correct. This is classic case of service oriented architecture where each service is delegated to do one specified task. Things I would make sure is -
-Each service becomes a stand alone service following a protocol (say rest). It can run on its own, maybe has its own load balancer, maybe authentication (oauth) if required etc.
-There is a strong contract/protocol/schema for each of these services so that one can be called from other.
-Its very similar to a OOP class design just applied to services if that makes you visualize better.
Hth

To have a REST service as a plugin


How to interpret main effect and interaction between factors that have more than two levels (logistic regression)

Question: I'm new to stats and I'm not sure how to interpret the output of my glm model.
I have two fixed factors, task which has two levels (task A and task B), and condition which has four levels (conditions a, b, c, and d). Both factors are sum-coded (because I don't have a clear baseline/reference level).
> contrasts(data$condition_c) <- contr.sum(4)
> contrasts(data$condition_c)
  [,1] [,2] [,3]
a    1    0    0
b    0    1    0
c    0    0    1
d   -1   -1   -1
> contrasts(data$task_c) <- contr.sum(2)
> contrasts(data$task_c)
         [,1]
taskA     1
taskB    -1

My dependent variable is binary so I'm using logistic regression. The model output looks like this:
Call:
glm(formula = DV ~ task_c * condition_c, family = "binomial",
    data = data)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.3678  -1.0629   0.3536   0.9301   1.8400

Coefficients:
                     Estimate Std. Error z value             Pr(>|z|)
(Intercept)           0.26432    0.07572   3.491             0.000482 ***
task_c1               0.20972    0.07572   2.770             0.005611 **
condition_c1         -0.22247    0.11058  -2.012             0.044237 *
condition_c2         -0.09502    0.11226  -0.846             0.397350
condition_c3          1.98070    0.16615  11.921 < 0.0000000000000002 ***
task_c1:condition_c1 -0.22080    0.11058  -1.997             0.045856 *
task_c1:condition_c2  0.23499    0.11226   2.093             0.036332 *
task_c1:condition_c3  0.28610    0.16615   1.722             0.085087 .

Can anyone help me understand the main effect of condition and the interaction between task and condition? Thanks!
Am I correct to say that for the main effect of condition, the model summary says that while conditions a and c are significantly different from the grand mean, condition b isn't? What about condition d? And I'm completely lost for the interaction.
Comment: Welcome to Cross Validated! With interactions you shouldn't rely solely on the reports of "significance" of individual model coefficients; you need to use post-modeling tools (like those in the R `car` or `emmeans` packages) to evaluate your hypotheses reliably. I find treatment contrasts easier to explain than sum contrasts; the model is fundamentally the same regardless of how the predictors are coded. It doesn't really matter whether or not you have clear baseline/reference levels for your categorical predictors; you can still just choose 1 as reference arbitrarily (or let R do it for you).
Answer: Start with the intercept. As you have chosen sum/deviation coding, that is a type of average outcome over all levels of the predictors: "the mean of means of the dependent variable at each level of the categorical variable," as this UCLA web page puts it. You have two such categorical variables, so the intercept is the estimate at the average over all levels of both of them. With logistic regression, this is in a log-odds scale.
The main effect of condition
With an interaction between task and condition, the association of one with outcome depends on the value of the other. With sum/deviation contrasts, the "main effect" coefficient for any level of one of those 2 predictors is the associated difference (here, a log-odds difference) from the intercept ("grand-mean" outcome), evaluated at the "grand mean" over the levels of the other. Is that really of interest by itself, without considering the significant interaction between task and condition?
What might be of more interest is the overall association between condition and outcome, taking all of its levels and interactions into account, sometimes called a "chunk test." A UCLA web page on logistic regression illustrates that with the wald.test() function of the R aod package. If you work within the rms package (highly recommended if you are going to do a lot of regression analysis), its anova() function (unlike that of base R statistics) provides that type of test.
What about condition d?
With 4 levels of condition you only get 3 coefficients. The intercept ("grand mean") includes the effect associated with the 4th level. If you know the "grand mean" over all 4 levels and the differences of the other 3 levels from the grand mean (their individual coefficients under sum/deviation coding), it's simple algebra to get the point estimate of the 4th level, condition d. For confidence intervals around that estimate, however, you need to know the variance-covariance matrix of the coefficient estimates. That's not included in this model summary, although it's included in the model and accessible via the vcov() function.
Post-modeling tools like those provided by the emmeans package can perform such calculations for you. These tools take the choice of predictor coding into account, so that you can typically just use the default R dummy/treatment coding for categorical predictors.*
The interaction between task and condition
Two-way interaction coefficients represent additional differences beyond what you would otherwise predict, based on the intercept and the individual coefficients for those specific levels of the predictors. I find it easier to think through those interactions with dummy/treatment coding. You can get outcome predictions for any combinations of predictor values, taking all coefficients into account, with post-modeling tools like those in the emmeans and rms packages.

*The only situation I can think of where categorical-variable coding matters is when you perform so-called "Type III ANOVA" tests on a model; dummy/treatment contrasts don't work then. But you probably shouldn't be doing those tests anyway; see the help page for the Anova() function in the R car package.


$2 \cdot 4^{2n + 1} + 3^{3n + 1}$ is divisible by $\lambda$, for all $n \in N$. Find $\lambda$.

Question: I'll state the question here:

If "$P(n): 2 \cdot 4^{2n + 1} + 3^{3n + 1}$ is divisible by $\lambda$, for all $n \in N$" is true, then what is the value of $\lambda$?

This is what I can think of:
$P(1): 2 \cdot 4^{2(1) + 1} + 3^{3(1) + 1}$ is divisible by $\lambda$.
i.e., $209$ is divisible by $\lambda$.
And,
$P(2): 2 \cdot 4^{2(2) + 1} + 3^{3(2) + 1}$ is divisible by $\lambda$.
i.e., $4235$ is divisible by $\lambda$.
Now the common factors of the $209$ and $4235$ are $1$ and $11$. So, $\lambda$ is one of $1$ and $11$. My textbook says that the answer is 11. And this how it was solved in the book.
Now I can't understand why can't the answer be $1$? Is doing what I did above enough to state the answer as $11$? What if for some $k \in N$, $2 \cdot 4^{2n + 1} + 3^{3n + 1}$ is not divisible by $11$? So to avoid missing such a term, I believe I should substitute $\lambda$ with $11$ in the statement and prove the statement using induction (that is what the chapter in my book is about). If I am able to prove it (and I will be since it's true), the answer is $11$. Otherwise, the answer is $1$.
My doubt is regarding the approach to the question. Does the method by which I solved it above suffice to give the answer as $11$? Or, as I mentioned in the previous paragraph, do I have to prove the statement again by replacing $\lambda$ with $11$?
Comment: I hope I didn't do anything wrong by editing ..
Comment: Looking at the posted solutions, the answer from @BillDubuque seems to dodge modular arithmetic effectively.
Comment: As the question is written, there is nothing to exclude $\lambda=1$.  Clearly they intended you to find the maximum value of $\lambda$ and the answers show how.  If I got this question I would be tempted to answer $\lambda=1$ will work because $1$ divides all naturals and quit at that point.  Of course, if my teacher did not have a sense of humor I might get rather few points.
Comment: Most powers of $2.4$ are not integers ...
Comment: I assume you mean to write $A_n=2\times 4^{2n+1}+3^{3n+1}$, and you seek to show that $11\,|\,A_n\,\forall n$, yes? If so, then you just need to check $A_n$ for $n\in \{0,\cdots,9\}$ .  It helps to note that both $3,4$ have order $5\pmod {11}$.
Comment: @HagenvonEitzen I meant $2 \cdot 4$. Sorry for the formatting error. I wasn't aware.
Comment: @lulu I didn't get your point. Probably cause I'm not aware of modular arithmetic. Please check out the question again. I edited it and made it clear what I really want to ask.
Comment: Well, perhaps I do not understand.  I thought that you (sensibly) checked a few cases out and determined empirically that the answer had to be $\lambda= 11$.  Great!  Now you have to prove it.  Are you saying that you don't know how to work $\pmod {11}$?  If so...well, there's probably a trick that avoids that.  Let me think a bit.
Answer: You've proved $\lambda$ divides $11$. To see that $11$ divides $\lambda$, we need to show that $11$ divides $f(n)$ for all $n$. To see this let's use induction on $n$, and note that $f(n) = g(n) + h(n)$ where:
$$g(0) = 8\\
h(0) = 3\\
g(n+1) = 16g(n) = 11g(n)+ 5g(n)\\
h(n+1) = 27h(n) = 11\cdot 2h(n) + 5h(n)
$$
So $11$ certainly divides $f(0) = 11$ and we have
$$
f(n+1) = 11(g(n) + 2h(n)) + 5(g(n) + h(n)) = 11(g(n)+2h(n)) + 5f(n).
$$
Hence, if $11$ divides $f(n)$, it will also divide $f(n+1)$. So $11$ divides $f(n)$ for all $n$ by induction.
Comment: Just showing that $11$ divides the first two values of $f(n)$ doesn't obviously guaranteee that if divides $f(n)$ for every $n$, so the proof you quote from your book is incomplete. I've tried to free my answer of modulo arithmetic..
Comment: Thanks! I couldn't understand the last sentence. Probably cause I'm not aware of modular arithmetic. Please check out the question again. I edited it and made it clear what I really want to ask.
Answer: Hint $\ {\rm mod}\ 11\!:\,\ 8\cdot  16^n + 3\cdot \overbrace{ \color{#c00}{27}^n}^{\textstyle\color{#c00}{16}^n}\equiv 11\cdot  16^n\equiv 0\ $ by $\ \color{#c00}{27\equiv 16}\,$ & Congruence Power Rule.
Remark $ $ If modular arithmetic is unfamiliar then we can instead rewrite is as follows
$$ 3(27^n\!-16^n) + 11\cdot 16^n$$
which is divisible by $11$ by $\,11 = 27\!-\!16\mid 27^n\!-16^n$ (provable by induction or by invoking the Factor Theorem $\, a-b\mid a^n-b^n)$
Induction is also (implicitly) used in the modular proof because it uses $\,27\equiv 16\,\Rightarrow\, 27^n\equiv 16^n\,$ and the proof of this Congruence Power Rule is by induction on $\,n$.
Update $ $ OP seeks a direct inductive proof without modular arithmetic etc. Below is one.
$$\begin{align}  f(n)\ &=\qquad 8\cdot  16^n +\, 3\cdot  27^n\\
\Rightarrow\ f(n\!+\!1)\ &=\, 8\cdot \color{#0a0}{16}\cdot 16^n +\, 3(\color{#0a0}{16}\!+\!11)\, 27^n\\
&=\, \color{#0a0}{16}\ \color{#c00}{f(n)}\ \ \ +\ \ \ 3\cdot \color{}{11}\cdot 27^n\\
&=\, \color{#c00}{11} (\color{#0a0}{16}\, \color{#c00}m\ \ +\,\ \ 3\cdot 27^n)\ \ {\rm by}\,\ \color{#c00}{f(n) = 11m}\,\ {\rm(inductive\ hypothesis)}
\end{align}$$
therefore $\ f(n) = 11m\,\Rightarrow\, f(n\!+\!1) = \color{#c00}{11}k,\ $ i.e. $\,11\mid f(n)\,\Rightarrow\, 11\mid f(n\!+\!1)$.
Comment: @Sam It seems the root of your question is that, as written, the question doesn't ask for the *greatest* common divisor (gcd) so both $1$ and $11$ are common divisors. Usually such questions ask for the gcd (the other common divisors are precisely the divisors of the gcd).
Comment: Thanks! Please check out the question again. I edited it and made it clear what I really want to ask.
Comment: @Sam By above we know $d=11$ divides all the $a(i)$. By your argument we know that $d$ is the *greatest* common divisor of the $a(i)$ since $d\mid a(1),a(2)\,\Rightarrow\,d\mid\gcd(a(1),a(2)) = 11.\ $
Comment: Yes. But I can't be sure if $\lambda = 11$ for all natural numbers just because it is the case for $n = 1 , 2$. So, I have to use induction or something like you did. Well, thanks again!
Answer: Note that any numbers of the form $u_n=Aa^n+Bb^n$ satisfy the recurrence $u_{n+1}=(a+b)u_n-abu_{n-1}$ (easy to check directly). You can use this to show that any number which is a factor of $u_1$ and $u_2$ is a factor of $u_n$ for $n\ge 1$.
Here you use $a=16, b=27$

This works as follows. $a,b$ are the roots of the equation $(x-a)(x-b)=0$ so that $x^2=(a+b)x-ab$. Multiply through by $x^{n-1}$ and this gives $x^{n+1}=(a+b)x^n-(ab)x^{n-1}$. This still has roots $a$ and $b$ so setting $x=a$ and multiplying through by $A$ gives $$Aa^{n+1}=A(a+b)a^n-A(ab)a^{n-1}$$ Similarly with $b, B$$$Bb^{n+1}=B(a+b)b^n-B(ab)b^{n-1}$$
Adding these together gives $$Aa^{n+1}+Bb^{n+1}=(a+b)(Aa^n+Bb^n)-(ab)(Aa^{n-1}+Bb^{n-1})$$ which is just $$u_{n+1}=(a+b)u_n-abu_{n-1}$$
Comment: @SamInuyashaANMF The proof is easy by induction - once you have two consecutive terms divisible by the same number, divisibility inevitably persists You can remember the form easily from $(x-a)(x-b)=x^2-(a+b)x+ab$. But you probably don't want that overload if it is new to you and you are in exam prep mode.
Comment: @SamInuyashaANMF I've done a little note at the end of the answer to show how these things are related.
Comment: Thanks! But it's a bit inconvenient for me to remember this for examinations since I've never used it before. And I don't know how to prove it with this either, though I got your point. Please check out the question again. I edited it and made it clear what I really want to ask.
Comment: I don't get how are the two related. That's $x^2$, $x$ and $ab$ and that's $u_{n+1}$, $u_n$ and $u_{n-1}$.
Answer: Take it modulo 11:
$2\cdot4^{2n + 1} + 3^{3n + 1} = 8 \cdot 5^n + 3 \cdot 5^n = 11 \cdot 5^n = 0$
Comment: Thanks! But sorry, I'm not aware of modular arithmetic. Please check out the question again. I edited it and made it clear what I really want to ask.


NetworkStream.DataAvailable property does not return the right result when using SslStream

Question: I've got an application with a persistent socket (it's open when the application starts and closed along with the application).
This socket is used by a server to push some data.
Since this connection could be either HTTP or HTTPS, I wrote this code to initialize my objects:
s_tcpClient = new TcpClient(s_server.CometIp, s_server.CometPort);
s_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, false);
s_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, CST_STREAM_BUFFER_SIZE);
s_tcpClient.ReceiveTimeout = 0;

s_networkStream = s_tcpClient.GetStream();

s_cometStreamReader = null;

if (s_server.Protocol == "HTTPS")
{
    SslStream sslStream = new SslStream(
        s_tcpClient.GetStream(),
        false,
        new RemoteCertificateValidationCallback(ValidateServerCertificate)
    );

    sslStream.AuthenticateAsClient(s_server.CometIp);
    s_cometStreamReader = new StreamReader(sslStream, Encoding.UTF8, true, CST_STREAM_BUFFER_SIZE);
    s_cometStream = sslStream as Stream;
}
else
{
    s_cometStreamReader = new StreamReader(s_networkStream, Encoding.UTF8, true, CST_STREAM_BUFFER_SIZE);
    s_cometStream = s_networkStream as Stream;
}

This way, I can handle both HTTP and HTTPS protocols.
Then, I've got this loop (in a thread) which waits for data to be available in the socket:
while (s_networkStream.DataAvailable)
{
    numberOfBytesRead = s_cometStream.Read(buffer, 0, buffer.Length);
    message.Append(Encoding.UTF8.GetString(buffer, 0, numberOfBytesRead));
    ExtractMessages(ref message);
}

Here are my 2 questions:

The documentation says that the Read method returns 0 if no data is available. But in my case, Read either returns a number > 0 (when some data have been read) or throws an exception because it timed out... What am I missing, here? Under which circumstances does Read return 0?
When my connection uses HTTP protocol, this code works fine. I receive everything and if a message is bigger than my buffer size (CST_STREAM_BUFFER_SIZE), DataAvailable remains true, and the loop reads all remaining data.
But when I try this with HTTPS, it works only for messages smaller than my buffer. If a message if bigger, the method Read first reads CST_STREAM_BUFFER_SIZE bytes and then DataAvailable becomes false, although some bytes are obviously ready to be read.
And in this case, receiving another message "unstucks" the remaining data because DataAvailable becomes true again.
What am I doing wrong? Why does not DataAvailable act the same in both cases?

Any help would be appreciated.
Comment: Nobody knows what I'm doing wrong, here?
Comment: Is my question that hard to answer or is it just dumb?
I'd really like to understand what's going on here...
Answer: It would only return 0 if the stream is closed, and hence no more data will ever come. Otherwise a positive number if data could be read, which may involve blocking if no data is yet available. If CanTimeout is true, the operation will throw after ReadTimeout has passed with no data available.
It sounds like maybe the socket has been left open and/or you are trying to read too much of you have an protocol that sends multiple chunks of data in a conversation.
http://msdn.microsoft.com/en-us/library/system.io.stream.readtimeout.aspx
Comment: OK, thanks. This answers my first question. And it's a really strange coincidence that you're the one answering me because I tried your protobuf-net yesterday. ;o)
Comment: @Rodolphe - any problems, let me know.


How often is it recommended to change bass strings?

Question: With the risk of being a duplicate question of How often should I replace the strings on my guitar? I'd like to ask the same thing for bass guitar.
Bass strings are pricier than guitar strings, so I don't want to replace them more often then I should. I try to keep them as clean as possible (FastFret + occasional cleaning with 90% alcohol). However 4 months in (and about 40-50H of playing), and I'm starting to feel they don't sound that great. There are also fret marks on the high G
How often (playing hours or chronological months) should good quality bass strings be replaced?
I have a 4 string electric bass, and I use round-wound strings.
Comment: Are you asking if they should be replaced more often that you're currently replacing them? Because if they sound bad you certainly wouldn't want to keep them longer.
Comment: I'm asking what's the "normal" rate in which one would replace Bass strings. They currently don't sound bad, just not as good as they used to.
Comment: Chris Squire (Yes) changed his strings before every gig. James Jamerson (Motown) never changed his strings, except when his was bass stolen, with the strings. There's a lot of latitude here...
Answer: I change my strings when they start to sound stale, about every 4-6 months.  As a gauge, I play about 5 hours a week in my church, plus an additional hour or two of practice on top of that.  When I used DR coated strings, they would last a bit longer than that, but even with the extra life I had a hard time justifying the extra cost.
Comment: They are a brand of coated strings. Strings degrade in part because your fingers bring chemistry which corrodes them and funk which embeds between windings. Coating protects them, but changes the tone in ways some musicians don't like. More here: http://music.stackexchange.com/questions/1629/coated-stringsgimmick-or-worth-the-money
Comment: What is DR coated?
Answer: As guitarist who plays bass occasionally, I can tell you that bass strings just seem to be pricier. But they also last much, much longer.
Of course after some time, they loose some brilliance but after that they usually keep the sound for a long time. The sweat-production of your hands also reduces the life of your strings. In general I'd say that bass-strings lives about 5-10 times longer than guitar strings, which makes them as cheap(/expensive) as guitar-strings.
If you want to keep the brilliance of your sound, you have no choice to either use coated strings or to change your strings more frequently. (And of course keep a good maintenance) If you can live with a 'dull' sound, you can generally keep uncoated strings on for over an year or longer. (unless they break^^)
As you can see, there is no basic yes or no to your question, you need to decide for yourself what you expect from your sound. [ I know, I hate such answers, too. ;) ]
I hope that helps, but keep in mind that the life of guitar/bass-strings can vary drammatically. It's all about how often you play, your hand-sweat, your maintenance and the material of your strings (+coat). So bass strings last from roughly 1 month to 5 years. ;)
Answer: As some people have said already it depends on how you want to sound. Depending on how often you play your strings will sound a lot more dull after some time. I personally think that if you're slapping, newer strings sound much better. They just have that bright punch to them. If you're using a pick I also think newer strings sound better.
For most things though, I like a duller, rounder sort of sound that I think older strings give after they lose their shine. It could be a combination of my amp settings and play style, it could also be the fact that I haven't broken a G string in quite some time so I just haven't bothered to change them and forgotten what it sounds like.
I would not be worried about the fret marks on your strings. I estimate I used to practice ~4-6 a day when I first put the strings on, this was pre-college. I switched majors about half way through and I didn't play as much. The strings have been on there for going on 7 years I'd say. The last 4 of which I play at most 10 hours a month maybe with no serious practicing just recording little things here and there.
I'd say part of this is luck. I use DR but I don't remember the exact kind and they were whatever the lightest guage they had at my local shop.
One thing to note is that if you are playing old strings it's good to wipe them down after you play, it's good to do this anyway actually. I can't imagine how disgusting they are and rather not think about it but besides that old strings will kill whatever sort of sustain you have and if that's something you're worried about I'd definitely change them as soon as they start to get a dull sound or start to get build up on the strings. There is no exact time period for this and it depends on how much you play and the humidity of the area where you keep your instruments.
Answer: If our old open-mic club  is any indication.... Never.  The "house" bass wore the same set for at least 10 years.
Comment: This sounds like a joke... lasted ten years... nobody would use it because of the short... that might be why it lasted so long :)
Comment: Yeah, but I'm assuming here that I want my bass to sound reasonably good ... :)
Comment: Not something that could be said of the bass in question...It also had a short and would shock people...
Comment: I used a set of strings for 10+ years also. Changed them when they broke.
Answer: It is usually stated that James Jamerson, legendary Motown bassist, never changed his strings.  This was generally considered to be a part of his sound.  He also used flatwound strings which last longer than roundwound (although I don't think they're intended to last a whole career!)
Comment: I would be very surprised if James Jamerson had never had to replace a broken string, considering I must have been playing many hours every day.
Answer: I have known rock bassists who play nightly, practice during the day, and change their strings before every single concert. These are players who insist on a very bright sound with prominent overtones, and play with a pick much of the time. This seems wasteful to me, but people do it.
Answer: Always change strings before recording at least. We borrowed a same brand, same model bass, but with different tuning when we were recording. The strings were bass-"fresh", a month or so. It sounded very muddy compared to the other which had really fresh strings. Changing strings got the sound back. (It should be common wisdom to change strings before recording, but it's also common knowledge that bass strings last "forever"...)
Answer: To be honest, it all depends on your ear.  I myself love the Marcus Miller Fat Beams, but after only a couple months (2-3) of playing, the initial "out of the pack fresh" brightness is already gone.  Even though it can be more expensive, I tend to replace them at this point because I love the way that they sound when I play.  If you are using strings that you think still sound good 1 year later, then there is no reason to replace them.
Comment: Thanks! I usually break the G string after 4-6 months, so never tested the strings for a whole year. Anyway, I'm glad to see I have justification to change them after 3... :)
Answer: If you can't afford new strings and there not so old that they have stretched. Try boiling stainless steel strings in water to steam clean, remove oils, it should sound brighter.
Comment: Back in more penurious times I would add a couple of teaspoons of baking powder (sodium bicarbonate)  to a saucepan of water and boil the boohoozola (technical term) out of the strings. An alarming scum would float to the surface of the water. The strings sounded brighter. Now that I am rolling in dough I buy lots of sets of cheap strings because my thrifty ways have never left me and a new cheap string sounds brighter than an old deluxe one.
Comment: @AreelXocha - Changed the strings on my go-to Bass Collection 5 string this week , after 10 yrs, and thousands of hours playing. Old strings didn't sound too bad, but the edge had gone, comparable to new. Boiled the old ones for 15 mins, with added washing up liquid. Amazing amount of dirt in the water. Might have to wait another 10 yrs to find out if they sound any better though...
Answer: I play TI jazz flats and I love the sound. I have had them on my bass for about a year and they still sound good. My preference, my opinion.
Comment: Is there any trace of the "fret marks on the high G" that OP was concerned about? About how many hours of playing (rough hrs/day is sufficient) does this represent? Would you expect the same results from Thomastik's roundwounds (OP uses rounds)?
Comment: Welcome to the Site! Don't get me wrong! I love Thomastik Jazz Flats to death (I get about 5-6 years out of a set of George Benson's). But, as a "late answer", we're looking for a little more substance. ... I'm certain that facts will bear out your claim. :)
Answer: I play my Gibson about 24 -30 gig hours a month plus practice 8hrs a week.   Let's call that 60 hrs a month and change my strings monthly. I prefer a brighter tone, but my bass is natually deep, so the balance is perfect.
My Jazz bass has flat wounds and rarely change the strings. Maybe ever few years. But I don't play it as often either. Maybe 3-4 hrs a month.
Answer: How do you know if you need new guitar strings?
For Acoustic and Electric guitars
 Couple of questions to answer:

Have you had the same strings on for over 2 months?
Are your strings rusty?
Are your strings rough?
Do your strings sound dull?
Had a string break recently?

If you answered yes to any of the above, its probably time to replace your strings.
Because of moisture on your fingers and in the atmosphere, strings corrode and rust over time and their ablility to vibrate diminishes. This not only causes the sound to dull but even worse, the feel of the strings becomes rough and will hurt or even damage your fingers.
Strings can also become brittle from too much vibration, just think of how a paper clip snaps if you twist it too much, the same happens to strings - especially if you use a lot of different tunings.
If you play a lot, say for 2 hours a day every day, then you should look at changing your guitar strings every month.
 If you play less, but still strum most days, the max you should leave them on the guitar would be 2 months.
Strings are quite cheap, about £5 for a set of 6.
There is an alternative to changing your strings this often. You can buy coated strings. These last longer due to a coating on the strings that prevent dirt build up and corrosion. Coated guitar strings tend to last 3 to 5 times longer than normal strings, so you can leave them on for longer. These still need to be changed though. At least every 6 months these should be changed as they are also prone to breaking because of the vibrations of the string as explained earlier using the paper clip analogy.
 Coated strings do cost more, about £12 for a set of 6, but last longer, so can work out more cost effective.
Ernie Ball Coated Strings have titanium reinforcement to make them stronger and less prone to break.
For Bass Guitars, the strings are much more substantial and tend to last longer and hold their tone. Change bass strings at least once a year.
For Classical Guitars with nylon based strings, again because of the way they are made, they don't rust, so last longer. They do age though, so do need replacing. When they age they tend to stretch and become hard to keep in tune. If you don't want to wait till this starts happening, you should look at changing them every 3 to 4 months.
So to summarize:

Change your Electric / Acoustic uncoated strings at least every 2 months.
Change your coated Electric / Acoustic strings at least every 6 months.
Change your Bass guitar strings at least once a year.
Change your Classical guitar strings at least every 4 months.

Details of guitar strings can be found at the Guitarbitz Guitar Strings page.
Comment: Per the [FAQ](http://music.stackexchange.com/faq#promotion), "you *must* disclose your affiliation in your answers." Also, "the community frowns on overt self-promotion and tends to vote it down and flag it as spam." This is just a reminder (your username gave it away). Good answer on the whole, though.
Comment: Guitars and basses are entirely different beasts. But some things do apply.
Answer: Basically it depends on how often you play. The more that you play the more often that they need to be changed. I play daily and tend to go through a set of strings a month, but I like to have a very bright tone. One thing that can be done is boiling your strings every so often. I have done that on occasion when money is tight. This can make your strings sound new again.
Answer: MarloweDK has a good tutorial on How to get NEW bass strings in 2 minutes!. He drops the tuning about an octave and pulls the strings away from the guitar and lets them whack off the fretboard. The idea is that any dirt gets shaken out.
The 'before' and 'after' comparison is right at the start if you don't want to watch the whole thing.
Answer: I play once every weekend for 4 hours and practice about 4 hours a week.  I've had the same strings for 5 years. If there is a difference in the sound compared to when they were new, I can't hear it and neither does anyone else.  In fact, in the past twenty years of playing routinely,  I only change the strings on my electric bass about every 5 years. I've never broke a string yet.
Answer: Depends on the sound you're going for.  There is no rule that suits everyone regardless of what some people might say or imply.  If you like that bright, twangy guitar-like sound then you'll want new strings relatively often.  If you're like me and prefer a deep, flat sound then you'll want to avoid changing them ever if at all possible.  If I put on new strings I'll have to wait for them to get back that nice sound I'm after.  I play with a pick or my fingers, sometimes both, depending on what I'm going for in a particular song.
Answer: To me the answer is:  When you're less happy with the sound.
I recently switched from guitar to bass guitar and wondered when I should change the strings.  After 2 months of daily playing I noticed the bass didn't seem to sound as good as it did when new.  It had less personality and was darker and more mellow.  The strings also were a little discolored and had some fret marks on them.
I took a chance and replaced the strings.  It sounds good as new again.
New strings cost me about $30.  The bass was $2,500.  Seems like a good investment to keep it sounding it's best.
Opinions vary of course.  I always notice when I hear old, dead strings on guitar or bass.  Some don't notice, while others prefer the sound of old strings.
On guitar old strings loose their intonation with age.  I don't know about bass though.  You might want to check that with a tuner.
Answer: I usually play my bass strings until I notice a change in sound. Usually one string at some point on the fret board on the bass sounds weird or flat. That means that string has gone. I've changed strings every 6 months or it might last a year or more depending how often I'm playing. Right now I am changing strings that are 7 months months old just because its not the  sound I want but they are still good. I play about 5 to 10 hours per week depending if its 1 or 2 gigs per week. I find new strings are a cleaner sound whether bass bombers or something sharper. GHS bass bombers are my fav! I'm trying DR strings now and they seem great. And also different basses I have different brand strings to get the sound I want. Trial and error to get what you want and it costs money!!!
Answer: Go by the sound, there is no specific time frame. The more you play the faster they wear out. Guitar strings last about 2-3 days honestly before the sound starts to decline if you play a lot or professionally. If you're playing gigs, I would change before every show. To those that will say your guitar won't stay in tune, make sure you stretch them when you install and also tighten up your winding game around the tuning peg and get a setup. Especially if you play slap bass, fresh strings will always sound 1000 times better. Some people say they like the sound of older bass strings because they are less bright, but for me, you can tone down the brightness with your tone knobs or with your amp eq. You can get a better "more round and smooth" bass tone with fresh strings and the tone know rolled back. The difference is in the punch. As strings get old, they lose their elasticity which kills the attack, again, even if you don't want a bright sound, there's not much thump on old strings. I change my strings every 4 weeks only because of the cost and effort to change. If I had enough time and funds, I'd change them after maybe 2-3 weeks. They don't sound bad after that, just not as good. Lastly for recording, always change them. Don't waste thousands of dollars in the studio only to get a crappy sound over $35 pack of strings. Get a setup too if you don't know how to do it yourself. Any time you change gauges you will need an adjustment otherwise the feel and the action will get screwed up. I know a lot of people may disagree or be satisfied with the sound for longer, but as an audio engineer and professional player, I always want the best sound, not just ok or 85% good, the best.


Is it possible to prove $a \in\mathbb R$ in the quadratic?

Question: $a^2−2a+17>0$
I didn't really know how to go about proving this.
At first I tried finding the range of '$a$' but the equation has imaginary roots so that doesn't really help.
Trying to look at it graphically, it's a parabola that doesn't touch the $x$-axis but I just can't prove that '$a$' will never be imaginary for this inequality.
Answer: You have $a^2-2a+17=a^2-2a+1+16=(a-1)^2+16>0$. So, the inequality holds for every $a\in\Bbb R$.
Comment: Thank you, but can't any imaginary values of a also satisfy the equation? I want to prove that 'a' can ONLY be real.
Comment: Sure there are real complex numbers that are roots of the equation: $1\pm4i$. But I assumed, from the title of your question, the you wanted to prove that, if $a\in\Bbb R$, then $a^2-2a+17>0$. Am I wrong?
Comment: No, my bad, you were right, thank you.
Answer: Yes, there is!
Complete the square: $$(a−1)^2-1+17>0$$ so $$(a−1)^2+16>0$$
This is true for all values of $a$ as any number squared will be greater than or equal to zero. Adding $16$ will obviously ensure the expression is always greater than $0$, so the inequality is true for all real values of $a$.
Hope that helped!
Answer: On the opposite "the equation has imaginary roots" is quite helpful !
That means that as there are no real roots, the polynomial keeps the same sign for all $a$. Then taking $a=0$, $17>0$ confirms that the sign is positive throughout.


Representation of a sphere as $\left\{\theta \in [0,2\pi], \phi \in [0,\pi], R\in [0, r]\right\}$

Question: In spherical coordinates, a sphere can be described as $S = \left\{\theta \in [0,2\pi], \phi \in [0,\pi], r\in [0, R]\right\}$
by letting  $x = r\sin \pi \cos \theta, ~ y= r \sin \phi \sin \theta,$ and $z= r\cos \phi$ in the equation $x^2+y^2+z^2 = R$.
This apparently comes from the parametrisation after considering the top surface and bottom surface by drawing a picture. I've tried, but I'm honestly incapable of thinking geometrically.
Question 1: Could someone explain how one can come to this representation algebraically?
Question 2: If we consider the region between the sphere $x^2+y^2+z^2 = R$ and the cone $z = \sqrt{x^2+y^2}$, the upper bound for $\phi$ changes and everything else stays the same:  we have
$$S'=\left\{\theta \in [0,2\pi], \phi \in [0,\pi/4], r\in [0, R]\right\}$$
Why is that? I'm thinking because we're only considering a quarter of the sphere, but I'm not sure.
Comment: The volume you're describing in Question 2 is the result of the intersection of the sphere with the cone $z \ge \sqrt{x^2+y^2}$
Answer: Let's first describe the outer surface of the sphere: pick a point $P$ on the surface and consider the radius connecting the origin to $P$. Now let $\phi$ be the angle between the radius and the positive $z$ semi-axis: it is evident that the height of $P$ can be written as $r\cos\phi$, where $r$ is the radius of the sphere.
Now consider the circumference obtained by cutting the sphere orthogonally to the $z$ axis and containing $P$. The radius connecting $P$ to the center of the circumference (that is, the distance between $P$ and the $z$ axis) has length $R_C=r\sin\phi$: you can then describe the circumference on coordinates $x$ and $y$ in the usual way: $y=R_C\sin\theta=r\sin\phi\sin\theta$ and $x=R_C\cos\theta=r\sin\phi\cos\theta$, with $\theta \in [0, 2\pi]$. Since we need to sweep these circumferences only from top to bottom and not all the way around, we take $\phi \in [0, \pi]$.
In this way we have described the outer surface of the sphere, but by varying $r$ we can again sweep all possible spherical surfaces with radius between $0$ and $R$, touching all the internal points of the sphere. Hence, $r\in[0, R]$.
I think that now, reasoning on the function of $\phi$, you can better understand the problem in Question 2.
P.S. Sometimes a Google image search is your friend.
Comment: Imagine P traveling along the meridian and the associated circumference sweeping the surface: you will see that the sphere is covered twice. As for number two, as far as my university is concerned, a sound geometrical reasoning justifies the boundaries, but I'm sure you can pull some trigonometry equivalence and justify it algebraically.
Comment: Many thanks for the reply. I've seen this image before. My question #1 was how this is achieved algebraically (i.e. without geometry). Do tell me if this request is misguided. For example, in an exam where I've to do question #2, do I've to draw that picture and go through this reasoning all over? Also, I don't understand the sentence "Since we need to sweep these circumferences only from top to bottom and not all the way around, we take..." Why is this sufficient? Why not all the way around?