params overload apparent ambiguity - still compiles and works?

Question: We just found these in our code:
public static class ObjectContextExtensions
{

    public static T Find<T>(this ObjectSet<T> set, int id, params Expression<Func<T, object>>[] includes) where T : class
    {
        ...
    }

    public static T Find<T>(this ObjectSet<T> set, int id, params string[] includes) where T : class
    {
       ...
    }
}

As you can see, these have the same signature except for the params.
And they're being used in several ways, one of them:
DBContext.Users.Find(userid.Value); //userid being an int? (Nullable<int>)

which, strangely enough to me, resolves to the first overload.
Q1: Why doesn't this produce a compile error?
Q2: Why does the C# compiler resolve the above call to the first method?
Edit: Just to clarify, this is C# 4.0, .Net 4.0, Visual Studio 2010.
Comment: This post from Eric Lippert recently discussed how overloads are resolved: http://ericlippert.com/2013/12/23/closer-is-better/
Comment: @Chris fair enough, it might not apply directly. But given that `params` can be omitted entirely from the calling parameters (see here: http://msdn.microsoft.com/en-us/library/w5zay9db.aspx) then I was taking closer to mean 'the first one defined'.
Comment: @CharlieKilian There is nothing about the order of declarations in this blog post.
Comment: Fun fact: Even though this works, Resharper 7.1 treats it as an error.
Comment: It seems that it considers the generic object to be "closer" in the params. If both are generic or both are non-generic then it complains about ambiguity. I can't tell you why this is though but I suspect some line in the spec somewhere says that this is the way of it.
Comment: Related question: http://stackoverflow.com/q/17390255/15541
Comment: @CharlieKilian: From memory I don't think that discussed this situation did it? I don't recall params being mentioned at all and I'm not sure how you can call one closer than the other if both are basically empty arrays... Hopefully Eric will see this and enlighten us. Certainly a good question...
Comment: Does flipping the order the functions are defined change which one is called?  If so then the closer one is the nearest one or first one.
Comment: @DStanley He has shown specifically how he's calling it, and it is ambiguous.
Comment: For fun, what does the compiler say when you remove the `params` and give both default values of `null`?
Comment: @CharlieKilian: Well if you'd tried it you'll see order of declaration is irrelevant and I would be shocked if the compiler every just said "Oh well, you declared this one first so I'll ignore the ambiguity". As you saw from the article on resolution you'll see that it gets a candidate set and eliminates the possibilities til one remains and if there is more than one we expect an ambiguous call exception to occur. There is thus clearly a rule somewhere that defines one as closer than the other, just that nobody here (currently) can say what it is.
Comment: @Chris You're right, the article doesn't specify the exact reason this method is considered 'closer' -- if indeed that is what is going on here. I'd be interested to hear the exact rule.
Comment: Look at IDEONE link in my answer - this seems like a bug to me :)
Answer: This is clearly a bug in overload resolution.
It reproduces in C# 5 and C# 3 but not in Roslyn; I do not recall if we decided to deliberately take the breaking change or if this is an accident. (I don't have C# 4 on my machine right now but if it repros in 3 and 5 then it will in 4 also almost certainly.)
I have brought it to the attention of my former colleagues on the Roslyn team. If they get back to me with anything interesting I'll update this answer.
As I no longer have access to the C# 3 / 4 / 5 source code I am unable to say what the cause of the bug is. Consider reporting it on connect.microsoft.com.
Here's a much-simplified repro:
class P
{
    static void M(params System.Collections.Generic.List<string>[] p) {}
    static void M(params int[] p)  {}
    static void Main()
    {
        M();
    }
}

It appears to have something to do with the genericity of the element type. Bizarrely, as Chris points out in his answer, the compiler chooses the more generic one! I would have expected the bug to be the other way, and choose the less generic one.
The bug is, incidentally, likely my fault, as I did a fair amount of the work on the overload resolution algorithm in C# 3. Apologies for the error.
UPDATE
My spies in the Roslyn team tell me that this is a known bug of long standing in overload resolution.  There was a tiebreaker rule implemented that was never documented or justified that said that the type with the bigger generic arity was the better type. This is a bizarre rule with no justification, but it's never been removed from the product. The Roslyn team decided some time ago to take the breaking change and fix overload resolution so that it produces an error in this case. (I don't recall that decision, but we made a lot of decisions about this sort of thing!)
Comment: Thanks for your answer. This didn't cause any trouble to us, I was asking out of curiosity. I'm glad that I'm contributing to improve the language / compiler =)
Comment: @HighCore: You're welcome; thank Chris for bringing it to my attention. Will it cause you trouble when Roslyn suddenly starts reporting this as an error when you upgrade in the future?
Comment: no, I (and the rest of my team agrees on this too) prefer that the compiler catches and removes as much ambiguity as possible. We can easily fix that by adding an overload `T Find(this ObjectSet set, int id){...}`
Comment: @EricLippert: Thanks for the feedback. I'll try not to make a habit of asking you for help .:)
Answer: On IDEONE the compiler successfully produces an error. And it should be an error, if you analyse the resolution algorithm step by step:

1) The set of candidate methods for the method invocation is constructed. Starting with the set of methods associated with M, which were found by a previous member lookup [...] The set reduction consists of applying the following rules to each method T.N in the set, where T is the type in which the method N is declared:

For simplicity, we can deduce here that that the set of methods here contains both of your methods.
Then the reduction proceeds:

2) If N is not applicable with respect to A (Section 126.96.36.199), then N is removed from the set.

Both methods are applicable with respect to Applicable function member rules in their expanded form:

The expanded form is constructed by replacing the parameter array in the function member declaration with zero or more value parameters of the element type of the parameter array such that the number of arguments in the argument list A matches the total number of parameters. If A has fewer arguments than the number of fixed parameters in the function member declaration, the expanded form of the function member cannot be constructed and is thus not applicable.

This rule leaves both methods in the reduction set.
Experiments (changing the id parameter type to float in one or both methods) confirm that both functions remain in the candidate set, and are further discriminated by the implicit conversion comparison rules .
This suggests that the above algorithm works fine in terms of creating the candidate set, and is not dependent on some internal method ordering. Since the only thing that discriminates methods further are Overload resolution rules this seems to be a bug, because:

the best function member is the one function member that is better than all other function members with respect to the given argument list, provided that each function member is compared to all other function members using the rules in Section 126.96.36.199.

and clearly none of these methods is better than other, because no implicit conversions exist here.
Comment: The confusing thing is that their expanded forms should be absolutely identical (it adds 0 parameters thus their expanded forms are the same as you've already noted) so I don't understand how it could differentiate after that...
Comment: @Chris Look at the IDEONE link I've provided. This seems to work fine on MONO, so it seems this is a bug.
Comment: That definitely looks like a bug. The only question is in which one. I personally don't trust myself to read the spec and all its complicated language perfectly. ;-) Or it might be something has changed and we are comparing different spec versions... And a belated +1 since I've jsut realised I haven't done so yet.
Answer: This isn't a full answer since it explains the differences but not why. It really needs s specification reference for completeness. However I didn't want the research I've done to get lost in comments so am posting as an answer.
The difference between the two overloads lies in the fact that the params for one is generic and the other is not. The compiler seems to decide that the generic type is closer than the non-generic.
That is if the Expression<...> type was changed to an int the compiler would complain about ambiguity. Similar if the types are both generic then it complains about ambiguity.
The following snippet will exhibit this behaviour more simply:
void Main()
{
    TestMethod();
}

public void TestMethod(params string[] args)
{
    Console.WriteLine("NonGeneric");
}

public void TestMethod(params List<string>[] args)
{
    Console.WriteLine("Generic");
}

This will print "Generic".
Comment: @Yandros: That is referring to the genericity of the *method*, not the *formal parameter type*.  That is, if we have a conflict between two methods `M(int)` and `M(T)` where `T` is `int`, then the non-generic one wins.
Comment: That would be contrary to the [C# specification](http://www.microsoft.com/downloads/details.aspx?familyid=DFBF523C-F98C-4804-AFBD-459E846B268E&displaylang=en): `If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.`
Comment: I don't have office on my computer so I'm having trouble viewing a copy of the spec but that snippet is tested and not guesswork output. However your quote refers to generic methods and not generic parameters on methods. Also the fact it has to be a params type parameter is going to be relevant in there somewhere...
Comment: Changing the type of parameter of the other overload to `Action` doesn't change anything unfortunately.
Comment: Unfortunately this doesn't actually answer the question.
Comment: @ken2k: As I said in the first paragraph I am aware that it is only a half answer but it at least answers in as far as it says "It chooses the one with generic type parameters" even if it doesn't explain why the compiler would choose to do that.


How to embed webview inside another widget in Flutter?

Question: I've tried to embed webview inside another widget in Flutter and I found some libraries.

First Library
Second Library

But all of libraries I found can only launch webview as a new activity.
Comment: As others said it's not possible yet. Just show it on 1 whole screen by setting AppBar properties and put title to it.
Answer: Having a WebView, MapView, video, camera, etc. inline in a Flutter widget tree is not currently supported. To my understanding, they're working on this currently.
See these GitHub pull requests:

Add texture support (eg video, camera) #4159
Add backend texture support (eg video, camera) #12525

Edit #1: The PRs have landed, and there's a WIP plugin of embedding a native video control inside a Flutter widget tree. To my understanding, WebView / MapView etc. require dispatching the touch/gesture events to the native counterparts, and they're not ready yet.
Comment: Correct. That's not possible yet.


linear mixed effect model, can I have fixed effect and random effect from a same source?

Question: Say I sampled 50 schools and take 20 students from each school. I randomly give 10 in each school concentration enhancement treatment.
For each school, I also have the school's teacher-student ratio.
Now I want to model the students' performance,
For school $i$ and student $ij$, $S_{ij}$ is the student's score, $E_{ij}$ is indicator of the treatment, and $T_i$ is the teacher-student ratio. I want to set up the model like this
$$S_{ij} = \mu+\alpha T_i + \beta E_{ij} + U_i + \epsilon_{ij}$$
to mean that schools have a random effect and that effect is partially explained by teacher-student ratio. $\alpha$ and $\beta$ are parameters of interest.
Is this a valid model? I haven't seen a mixed effect model with explanatory variable and random effect explaining variance from a same source.
The problem I am worried is that, if $U_i$ were to be included as a fixed categorical variable, then the model is not determined, $\alpha$ can be anything and $U_i$ alone will fit for all between school variance.
Answer: Yeah that would be valid. All that would happen is that the random effect for school would represent all the variance between schools that can't be accounted for by knowing the teacher-student ratio of the schools.
If you compare the model with and without the teacher-student ratio variable then I'd expect you'd find that the model with that fixed effect is a better fit to the data.
Models like this are not uncommon in psychology, where, say, you want know whether people find one task more difficult than another, and you expect that the difficulty a person experiences in both tasks is partially influenced by some individual difference (e.g., IQ).
Answer: Yes, that is true.
you mean  students' performance, after treatment not only depends on treatment but also it may have better effects with some teachers.


Javascript: Calling different variables depending on variable

Question: I'm trying to access different variables depending on user input. To simplify, let's say I have three variables, x1 = "variable 1", x2 = "variable2" and x3 = "variable3". I want to be able to call a different variable, depending on another variable, y. Let's say y=2, that means I want to get x2.
I tried something like console.log(x[y]), but that doesn't seem to work. I didn't find anything on this topic anywhere, so I don't know if it's possible or not, or if that's even how you would solve this problem.
For those who are interested, I'm trying to access different Discord.RichEmbed()s depending on the variable, and I don't think I can store those in an array. If that is somehow possible, please let me know.
If I forgot to explain something let me know and I'll add it or answer any questions you might have
Thanks in advance ^^
EDIT: It would also work if y="x2" and if I could then somehow get the contents of x2 that way.
Comment: Does this answer your question? "[Use dynamic variable names in JavaScript](//stackoverflow.com/q/5117127/90527)", "["Variable" variables in JavaScript](//stackoverflow.com/q/5187530/90527)"
Comment: Why do my comments keep getting deleted :|
Answer: You are exhibiting a fundamental misunderstanding of JavaScript principles and my feeling is that you are essentially "hacking together" something for Discord.
I don't know if this will help you because there should probably be more context posted.
There are many ways to accomplish this.
You could create a method that has the source of variables and returns a reference to one of them based on a y variable passed as an argument.
const retrieveX = (y) => {
  const source = {
    x1: 'variable1',
    x2: 'variable2',
    x3: 'variable3',
  }
  return source[y]
}
retrieveX('x1')

Comment: Actually no, I'm just trying to make a fun Discord bot in my spare time ^^
Here's more context:
I'm trying to do "page switching" in an embed, which means I have pre-defined all possible "pages" of the embed as individual embeds. When the user reacts to the message, it's supposed to advance a page, so edit the message with another embed. I have a variable i storing the current page number and each embed is simple called "embed" with the number behind it. If I do it like sugessted, it gets the NAME of the embed, not the embed. So logging shows "embed2", not the contents of the embed.
Comment: Firgued out with the help of the code you provided, thanks a ton! ^^


Function of a complex variable; must the real and imaginary parts be functions of two variables?

Question: Quoting Saff & Snider's "Fundamentals of Complex Analysis" (3rd. edition):

If w denotes the value of the function $f$ at the point $z$, we then write $w=f(z)$.
Just as $z$ decomposes into real and imaginary parts as $z=a+ib$, the real and imaginary parts of $w$ are each (real-valued) functions of $z$ or, equivalently, of $x$ and $y$, and so we customarily write

$w=u(x,y)+iv(x,y)$

with $u$ and $v$ denoting the real and imaginary parts, respectively, of $w$. Thus a complex valued function of  a complex variable is, in essence, a pair of real functions of two real variables.

My question is, does $u$ and $v$ have do be functions from $\mathbb{R}^2$? If $z=x+iy$ and $w=a+ib$, can you have just $h(x)=a$ and $g(y)=b$ so that $w=h(x)+ig(y)$?
What about stuff like $w=u(x,y,0)+iv(x,y,0)$?
Basically, why is it obvious that $f(z)$ should decompose into functions of two variables? Is there a nice way to think about this?
Comment: It's not that it should, it's that it can.
Comment: You can identify $\mathbb{C}$ with $\mathbb{R}^2$, so you can interpret every function of one complex variable as a function of two real variables and vice versa.
Comment: In your example you would have $u(x,y)=h(x)$, $v(x,y)=g(y)$, perfectly legal functions of $x$ and $y$.
Answer: It is common  to misunderstand "$u$ is a function of $x$ and $y$" as "$u$ depends on $x$ and $y$". Which leads to errors such as thinking that $u(x,y)=x^2$ is not a function of $x $ and $y$.
Saying that "$u$ is a function of $x$ and $y$" means that the domain of $u$ is the set of ordered pairs $(x,y)$. Informally, $u$ takes two real numbers as inputs, and produces a number as output. To qualify as a function, $u$ must be consistent: if given the same pair $(x,y)$ today and tomorrow, it must give the same output. Other than that, it's free to use the inputs in any way it wants; and that includes not using them at all. For example, $f(x,y)=\sqrt{2}$ is a function which always returns $\sqrt{2}$ as output. It's still a function of $x$ and $y$ -- meaning it takes $x$ and $y$ as inputs -- it just does not use those inputs.
Comment: There is no reason to bring up time! A function is $f:A\to B$ is a subset $f\subset A\times B$ such that for every $a\in A$ there *exists* one, and *only one* $b\in B$ such that $(a,b)\in f$; from where we write $f(a)=b$. Slightly informally it is a correspondence that assigns to *every* $a\in A$ *one*, and *only one* $f(a)=b\in B$.
Comment: I just think the time analogy is a strange one.


What is the conditional expected value?

Question: Consider two random variables, X and Y, with joint density function,
\begin{align} f_{X,Y}(x,y)=8xy, \qquad(0<x<1,0<y<x) \end{align}
Calculate $\mathbb{E}(X\mid Y=y)$.
I've tried this,
$$f_{X\mid Y=y}=\frac{f_{X,Y}(x,y)}{f_Y(y)}=\frac{8xy}{\int_0^18xy\;dx}=\frac{8xy}{8y\left[\frac{x^2}{2}\right]_0^1}=\frac{8xy}{4y}=2x$$
$$\mathbb{E}(X\mid Y=y) = \int_0^1 xf_{X\mid Y=y} \; dx = \int_0^1 2x^2 \; dx = 2\left[\frac{x^3}{3}\right]_0^1 =2\cdot\frac{1}{3}=\frac{2}{3}$$
but my book says it is:
$$\frac{2(1-y^3)}{3(1-y^2)},\;(0<y<1)$$
What I'm doing wrong? Help please!
Comment: $f_{X,Y}$ only has support on $x>y$ and you aren't taking this into account.
Comment: So what I'm doing wrong, I don't understand.
Comment: You should integrate $f_{X,Y}$ over $x\in(y,1)$ to find $f_Y$.
Comment: For instance you need $f_Y(y)= \int_y^1 8xy dx.$ the lower limit of $y$ is needed since $f_{X,Y}$ is zero for $x<y$
Answer: $$
f_Y(y) = \underbrace{\int\limits_{\{\, x \,:\, 0\,<\,y\,<\,x\,<\,1 \,\}}}_\text{see below} f_{X,Y} (x,y) \, dx = \int_y^1 8xy \, dx = \cdots
$$
The thing over the $\underbrace{\text{underbrace}}$ was given at the outset and tells you  over what range of values you need to integrate.

What is the conditional expected value?


Evaluating $\int^\infty_0 \frac{\tanh(x)}{x\cosh(2x)}dx$

Question: I am trying to evaluate $\int^\infty_0 \frac{\tanh(x)}{x\cosh(2x)}dx$ by Feynman's technique.
Let $I(b)=\int^\infty_0\frac{\tanh(bx)}{x\cosh(2x)}dx$, then $I'(b)=\int^\infty_0 sech^2(bx)sech(2x)dx$. However, I am unable to find out the integral in terms of b. Or should I use another approach? Thanks for help.
Comment: If complex integration as a method is acceptable, a solution for a more general case can be obtained. Should I proceed?
Comment: This has a surprisingly nice value of ln(2) lol
Comment: Yes, it has a nice value of ln2. However, I don't know how to prove it.
Comment: Hm, since the function is even, perhaps a complex analysis approach with a semicircle contour that avoids the pole in the center might work.
Comment: I think we can try with a substitution first, $y=e^{-kx}$.
Comment: Sure, I also want to know a solution for a more general case.
Comment: This one came up in MIT Integration Bee 2023.
Answer: We can consider a bit more general case. Let's denote
$$J(a)=\frac{1}{2}\int_{-\infty}^\infty\frac{x}{a^2+x^2}\,\frac{\tanh\pi x}{\cosh 2\pi x}dx$$
then
$$J(a)=\frac{1}{2}\Im\frac{\partial }{\partial a}\int_{-\infty}^\infty\ln(a-ix)\,\frac{\tanh\pi x}{\cosh 2\pi x}dx=\frac{1}{2}\Im\frac{\partial }{\partial a}I(a);\,a\geqslant0\tag{1}$$
and the desired integral $$J_0=\frac{1}{2}\int_{-\infty}^\infty\frac{\tanh\pi x}{x\cosh 2\pi x}dx=J(0)\tag{2}$$
Using $\,\ln(a-ix)=\ln\Gamma(a-i(x+i))-\ln\Gamma(a-ix)$ and the property $\,\displaystyle\frac{\tanh\pi (x+i)}{\cosh 2\pi (x+i)}=\frac{\tanh\pi x}{\cosh 2\pi x}\,$, we can present  the integral $\,I(a)\,$ as the integral along a rectangular contour in the complex plane $\,(-R\to R\to R+i\to-R+i\to -R )$
$$I(a)=\int_{-\infty}^\infty\ln(a-ix)\,\frac{\tanh\pi x}{\cosh 2\pi x}dx=-\oint\ln\Gamma(a-iz)\frac{\tanh\pi z}{\cosh 2\pi z}dz$$
Therefore, as we have three simple poles inside the contour,
$$I(a)=-2\pi i \underset{z=\frac{i}{4}, \frac{3i}{4}, \frac{i}{2}}{\operatorname{Res}}\ln\Gamma(a-iz)\frac{\tanh\pi z}{\cosh 2\pi z}$$
The residue evaluation is straightforward and gives
$$I(a)=-i\bigg(\ln\Gamma\Big(a+\frac{1}{4}\Big)+\ln\Gamma\Big(a+\frac{3}{4}\Big)-2\ln\Gamma\Big(a+\frac{1}{2}\Big)\bigg)$$
Using (1),
$$\boxed{\,\,J(a)=\frac{1}{2}\int_{-\infty}^\infty\frac{x}{a^2+x^2}\,\frac{\tanh\pi x}{\cosh 2\pi x}dx=\psi\Big(a+\frac{1}{2}\Big)-\frac{1}{2}\psi\Big(a+\frac{1}{4}\Big)-\frac{1}{2}\psi\Big(a+\frac{3}{4}\Big)\,\,}$$
and the initial integral
$$J_0=J(0)=\psi\Big(\frac{1}{2}\Big)-\frac{1}{2}\psi\Big(\frac{1}{4}\Big)-\frac{1}{2}\psi\Big(\frac{3}{4}\Big)=\ln 2$$
Comment: You could also integrate $\frac{\psi(a-iz)\tanh(\pi z)}{\cosh(2 \pi z)}$ around the same contour and exploit the functional equation of the digamma function.
Comment: Since
\begin{equation*}
 \dfrac{\tanh(\pi x)}{\cosh(2\pi x)} = 2\left(\dfrac{1}{e^{2\pi x}-1}-\dfrac{3}{e^{4\pi x}-1}+\dfrac{2}{e^{8\pi x}-1}\right)
\end{equation*}
we can alternatively get the value of $J(a)$ via the formulas
\begin{equation*}
 \Psi(a) = \ln(a)-\dfrac{1}{2a}-2\int_{0}^{\infty}\dfrac{x}{(x^2+a^2)(e^{2\pi x}-1)}\, \mathrm{d}x
\end{equation*}
and
\begin{equation*}
 \Psi(2a)= \frac{1}{2}\Psi(a)+\frac{1}{2}\Psi(a+\frac{1}{2})+\ln 2.
\end{equation*}
Comment: Thanks for the alternative solution. Actually, this question comes from Integration Bee 2023, which allowed candidates to complete this question within 3 minutes, so I think there may be a shorter solution for it.
Comment: The technique of Blagouchine! +1
Comment: You can actually write this in a pretty form via the Gauss multiplication: $$J(a)=\ln2+\psi(a+1/2)-\psi(2a+1/2)$$In particular if $n$ is a positive integer we get: $$J(n)=\ln2-2\sum_{m=n}^{2n-1}\frac{1}{2m+1}$$If I'm not mistaken. Thank you for reminding me of this technique. ^^ if $n$ is a half integer there will be a similarly nice form, I think
Comment: Yes. $$\forall n\in\Bbb N,\,\int_0^\infty\frac{x}{x^2+n^2}\cdot\frac{\tanh\pi x}{\cosh2\pi x}\,\mathrm{d}x=\ln2-2\sum_{m=n}^{2n-1}\frac{1}{2m+1}$$Is very pretty!
Answer: If we observe that the given integral is a Frullani integral we get an alternative to Feynman's technique. See
https://en.wikipedia.org/wiki/Frullani_integral
Put
\begin{equation*}
 f(x)=\dfrac{2}{e^{x}+1}.
\end{equation*}
Then
\begin{gather*}
\int_{0}^{\infty}\dfrac{\tanh(x)}{x\cosh(2x)}\,\mathrm{d}x = \int_{0}^{\infty}\dfrac{2(e^{2x}-1)e^{2x}}{x(e^{2x}+1)(e^{4x}+1)} \,\mathrm{d}x = \\[2ex]
\int_{0}^{\infty}\dfrac{1}{x}\left(\dfrac{2}{e^{2x}+1}-\dfrac{2}{e^{4x}+1}\right)\,\mathrm{d}x = \int_{0}^{\infty}\dfrac{f(2x)-f(4x)}{x}\,\mathrm{d}x = \\[2ex]
\left(f(\infty)-f(0)\right)\ln\frac{2}{4} = \ln(2).
\end{gather*}
Comment: It is a really nice solution and thanks for introducing this useful technique.
Comment: That's a great observation!
Answer: This integral can be done via Feynman's technique and Digamma function. First, I rewrote the integral as a more convient form.
$$
I=\int_0^{\infty}{\frac{\tanh \left( x \right)}{x\cosh \left( 2x \right)}\mathrm{d}x}=2\int_0^{\infty}{\frac{e^{2x}\left( e^{2x}-1 \right) ^2}{x\left( e^{8x}-1 \right)}\mathrm{d}x}
$$
Then I define $I\left( t \right) $ as follows
$$
I\left( t \right) \stackrel{\mathrm{def}}{=}\int_0^{\infty}{\frac{e^{tx}\left( e^{2x}-1 \right) ^2}{x\left( e^{8x}-1 \right)}\mathrm{d}x}
$$
Where $t\in\left(-\infty, 2\right)$. Then
\begin{align*}
I'\left( t \right) &=\int_0^{\infty}{\frac{\left( e^{2x}-1 \right) ^2e^{-8x}}{1-e^{-8x}}e^{tx}\mathrm{d}x}
\\&
=\int_0^{\infty}{\left( e^{\left( t-4 \right) x}-2e^{\left( t-6 \right) x}+e^{\left( t-8 \right) x} \right) \sum_{n=0}^{\infty}{e^{-8nx}}\mathrm{d}x}
\\&
=\sum_{n=0}^{\infty}{\int_0^{\infty}{e^{-\left( 8n+4-t \right) x}-2e^{-\left( 8n+6-t \right) x}+e^{-\left( 8n+8-t \right) x}\mathrm{d}x}}
\\&
=\sum_{n=0}^{\infty}{\frac{1}{8n+4-t}-\frac{2}{8n+6-t}+\frac{1}{8n+8-t}}
\\&
=\frac{1}{8}\sum_{n=0}^{\infty}{\frac{1}{n+\frac{4-t}{8}}-\frac{2}{n+\frac{6-t}{8}}+\frac{1}{n+\frac{8-t}{8}}}
\\&
=\frac{1}{8}\left[ 2\mathrm{\psi}_0\left( \frac{6-t}{8} \right) -\mathrm{\psi}_0\left( \frac{8-t}{8} \right) -\mathrm{\psi}_0\left( \frac{4-t}{8} \right) \right]
\end{align*}
Due to the way how Digamma function was defined, we can actually integrate this quite easily. The expression reduces substantially, and we got the answer $\ln(2)$
\begin{align*}
I&=2\int_{-\infty}^2{I'\left( t \right) \mathrm{d}x}
\\&
=\frac{1}{4}\int_{-\infty}^2{\left[ 2\mathrm{\psi}_0\left( \frac{6-t}{8} \right) -\mathrm{\psi}_0\left( \frac{8-t}{8} \right) -\mathrm{\psi}_0\left( \frac{4-t}{8} \right) \right] \mathrm{d}x}
\\&
=\left. 2\ln \left( \frac{\Gamma \left( \frac{8-t}{8} \right) \Gamma \left( \frac{4-t}{8} \right)}{\Gamma \left( \frac{6-t}{8} \right) \Gamma \left( \frac{6-t}{8} \right)} \right) \right|_{-\infty}^{2}=2\ln \left( \csc \left( \frac{\pi}{4} \right) \right) =\ln \left( 2 \right)
\end{align*}
Comment: Thanks for your solution.
Answer: Using
$$ \int_0^1\frac{x^p-x^q}{\ln x}\mathrm{d}x=\ln\bigg(\frac{p+1}{q+1}\bigg) $$
one has
\begin{eqnarray}
I&=&\int_0^{\infty}{\frac{\tanh \left( x \right)}{x\cosh \left( 2x \right)}\mathrm{d}x}=-\int_0^{1}{\frac{2x(1-x^2)}{(1+x^2)(1+x^4)\ln x}\mathrm{d}x}\\
&=&-\int_0^{1}{\frac{2x(1-x^2)^2}{(1-x^8)\ln x}\mathrm{d}x}=-\int_0^{1}{\frac{\sum_{k=0}^\infty2x(1-x^2)^2x^{8k}}{\ln x}\mathrm{d}x}\\
&=&-2\sum_{k=0}^\infty\int_0^{1}{\frac{x^{8k+1}-2x^{8k+3}+x^{8k+5}}{\ln x}\mathrm{d}x}\\
&=&-2\sum_{k=0}^\infty\ln\bigg(\frac{(4k+1)(4k+3)}{(4k+2)^2}\bigg).
\end{eqnarray}
Let
$$ S_n = \prod_{k=0}^n\frac{(4k+1)(4k+3)}{(4k+2)^2}=\frac{\sqrt\pi\Gamma(2n+\frac52)}{4^{n+1}\Gamma^2(n+\frac32)}. $$
Using the Sterling formula
$$ \Gamma(z)\approx \sqrt{\frac{2\pi}{z}}(\frac{z}{e})^z$$
one has
$$ \lim_{n\to\infty} S_n=\lim_{n\to\infty}\frac{\sqrt{\frac{2\pi}{2n+\frac52}}(\frac{2n+\frac52}{e})^{2n+\frac52}}{4^{n+1}\bigg(\sqrt{\frac{2\pi}{n+\frac32}}(\frac{n+\frac32}{e})^{n+\frac32}\bigg)^2}=\frac1{\sqrt2}$$
which imples
$$ I = -2\ln \frac1{\sqrt2}=\ln2. $$


Minor problem while loading page with jquery

Question: I'm using the slidedeck jquery plugin which basically puts slides on my page. Everything works fine, but the problem is with the css loading part. Below these slides i have an import statement for another page. This page which i'm importing fetches quite a bit of data from the database before being completely displayed.
So whenever i open my page for a second or two the display for my page goes hay wire. The probable cause of this may be that i'm putting most of my jquery including the one for these slides in the document.onready function. So since the document is not loaded completely for that period of time slides are also not displayed. (as in they are displayed but in a weird manner......they are all over the page!!!!)
Is there some way i can make sure that my css and jquery get loaded first and then a call is made to this page which i'm importing or something like that. i just want that my display comes fine right in the beginning.
this is the slidedeck jquery plugin i'm using
slidedeck : http://www.slidedeck.com/
Comment: pranky, are you loading data using ajax and calling a external file or are you loading it directly using php that is embedded in the page to load the data from the database into the page?
Comment: no its not actually an ajax request. I'm using spring, so the page which i'm importing has a multiaction controller associated to it which is called when a request for that page comes.
Comment: oh and can it be because of the data being to much that the browser is taking time to load the page?..cause the jsp page is already converted to html when it comes to the client . is there some way i can make the js in the document.onready function to run first??
Comment: pranky, I see spring is a java based platform. I don't know java, so I'm afraid I've reached a dead end here. I'm sorry that I wasn't able to help you. I hope someone else could.
Comment: yeah i guess i should have mentioned the java n the jsps the beginning itself :P...thnks anyway
Answer: ahh i actually found a solution for my problem. Now what i'm doing is that i'm keeping the div (say id="slideDeckContainer") containing this slidedeck initially as hidden (using css style=display:none). Only after the page is done loading inside the $(document).ready(function(){....}); i call $('#slideDeckContainer).show(); on the div. (since the $(document).ready(function(){...}) is callled only after the page is loaded)
Definitely not the best solution but for now it works :).
Answer: instead of $(document).ready(function() { //code here }); you can use $(document).load(function() { //code here}); The load function fires after everything in the selector has loaded. In this case, we are selecting the document, so this function will run only after the CSS, javascript, and DOM have finished loading. Another suggestion is to give the DOM elements that you are loading content into a defined width and a height. This way, before the loading finishes, there will be space reserved for the loading content and it won't mess up your page layout.
Comment: do u mean `$(window).load(function(){...});` instead of `$(document).load(function(){});` ??....
Comment: I imagine either one would probably work? [jquery reference](http://api.jquery.com/load-event/)
Comment: no actually it didn't work, i'm having the same problem with the '$(window).load(function(){...}). i guess its because my page takes a bit long to load and by the way window.load is called only after the document.ready, what i wanted was something that could have been run even before the document.ready. thanks any way


MongoDB - aggregate match field from the previously matched document

Question: I have a collection with following schema -
const ContentSchema = new Schema({
    label: {
        type: String
    },
    itemId: {
        type: Schema.ObjectId,
        refPath: 'onModel'
    },
    formId: {
        type: Schema.ObjectId,
        refPath: 'onModel'
    },
    value: {
        type: Schema.Types.Mixed,
        index: "text"
    },
}, { timestamps: true, versionKey: false });

Here are some example documents the collection may have -
{
  _id: ObjectId('647b1538c29a553ad6e8f316'),
  label: "Name",
  itemId: ObjectId('647b1538c29a553ad6e8f313'),
  formId: ObjectId('647b1538c29a553ad6e8f913'),
  value: "ABC"
},
{
  _id: ObjectId('647b1538c29a553ad6e8f416'),
  label: "Email",
  itemId: ObjectId('647b1538c29a553ad6e8f313'),
  formId: ObjectId('647b1538c29a553ad6e8f913'),
  value: "email@example.com"
},
{
  _id: ObjectId('647b1538c29a553ad6e8f516'),
  label: "Name",
  itemId: ObjectId('647b1538c29a553ad6e8f320'),
  formId: ObjectId('647b1538c29a553ad6e8f913'),
  value: "MNO"
},
{
  _id: ObjectId('647b1538c29a553ad6e8f616'),
  label: "Email",
  itemId: ObjectId('647b1538c29a553ad6e8f320'),
  formId: ObjectId('647b1538c29a553ad6e8f913'),
  value: "firstname.lastname@example.com"
}

Now, I need to perform a query to search "ABC" from the collection with formId - ObjectId('647b1538c29a553ad6e8f913').
Here is the code to do that -
return await ContentModel.aggregate([
{
    $match: {
        $text: { $search: text },
        formId: new mongoose.Types.ObjectId(formId)
    }
}]

The above code is absolutely working fine and returns the document -
{
    _id: ObjectId('647b1538c29a553ad6e8f316'),
    label: "Name",
    itemId: ObjectId('647b1538c29a553ad6e8f313'),
    formId: ObjectId('647b1538c29a553ad6e8f913'),
    value: "ABC"
}

But I need more records within the same aggregation. Now I need to find out other documents from the document with itemId - ObjectId('647b1538c29a553ad6e8f313').
So that the aggregation should now return 2 documents -
    {
      _id: ObjectId('647b1538c29a553ad6e8f316'),
      label: "Name",
      itemId: ObjectId('647b1538c29a553ad6e8f313'),
      formId: ObjectId('647b1538c29a553ad6e8f913'),
      value: "ABC"
    },
    {
      _id: ObjectId('647b1538c29a553ad6e8f416'),
      label: "Email",
      itemId: ObjectId('647b1538c29a553ad6e8f313'),
      formId: ObjectId('647b1538c29a553ad6e8f913'),
      value: "email@example.com"
    }

I am trying with following query which does not work -
return await ContentModel.aggregate([
{
    $match: {
        $text: { $search: text },
        formId: new mongoose.Types.ObjectId(formId)
    }
},
{
    $match: { itemId: "$itemId" }
}]

Comment: Are you looking for `$lookup` or `$graphLookup` perhaps?
Answer: If I've understood correctly you can use $lookup with your own collection in this way:
In this query you can $match as you have done and then, with matching results you can $lookup (like a SQL JOIN) against your data using collection and matching itemId.
So is like to say "join the matching itemId with all others itemId". And I think is what you want.
db.collection.aggregate([
  {
    "$match": { /* your match*/ }
  },
  {
    "$lookup": {
      "from": "collection",
      "localField": "itemId",
      "foreignField": "itemId",
      "as": "results"
    }
  },
  {
    "$unwind": "$results"
  },
  {
    "$replaceRoot": {
      "newRoot": "$results"
    }
  }
])

Also the two others steps are to output the result as root.
Example here


Use more than 3 GB of memory on SQL Server 2005 on Windows Server 2003 R2 Enterprise x64

Question: I am running SQL Server 2005 Standard x64 on Windows server 2003 R2 x64. I have 32GB of total server RAM. I am unable to make SQL Server use more than 3 GB of memory, even I set min and max server options as follows:
<code>sp_configure 'show advanced options', 1
RECONFIGURE
GO

sp_configure 'min server memory', 1024
RECONFIGURE
go

sp_configure 'max server memory', 24576
RECONFIGURE
GO
</code>
What could be a problem?
Update
There was SQL Server 2005 32bit installed. See my answer.
Comment: How big is your dataset? SQL will only use what it needs to so if your dataset is less than 3GB then it's wont user more than that
Answer: Actually I did recognize that there was 32 bit version of SQL server installed. After re-installation the problem was solved.
Thank you very much for your efforts.
Cheers
Darius
Answer: You need to add a directive to the Boot.ini on your root drive.
under the
[operating systems] header
you should add /3gb  switch at the end of the OS entry.
Comment: Doesn't apply to 64-bit operating systems
Comment: You don't need this on 64bit systems, it's a workaround for limitations on 32bit systems


xp client problem

Question: I used to have as a file server for my clients recently and switched to windows server 2008 and I faced strange problem
My win7 clients have no problem but xp client get disconnected about 2-3 time a day. I had not any problem when I had server2003, this problem starts when I changed my server from 2003 to 2008, be sure that the is no any network problem, ping in both side are under 1ms
Comment: I updated my answer.
Comment: We need more info than this, any errors? Event log messages?
Comment: When you say 'disconnected' - what is the client seeing?  Mapped network drive becomes disconnected, or something else?
Comment: Are they domain users? http://serverfault.com/questions/85328/windows-server-2008-share-not-accessible suggests it could be SEP/SAV, what AV are you running?
Comment: hello
no,not any event is logged.,they only use sharefolder not mapped network.
No I don't install AD for serve they have office group only
but ping in two side are  good , when they type the server address in RUN like \\servername\sharename  the name and pass form doesn't appear or if they was connected when they click on the share folder  their computer  be hanged and the net work will be slow
Answer: Please check  through Windows Server 2008 does not use CIFS to connect to network shares (and sublinks there)  for possible causes and solutions.

---Update1:
See also:

Computer disappeared from Workgroup

which basically tells that you must have WINS server (or dynamic DNS) server.
From my experience, I cannot see my own PC in "My Network Places" in WindowsExplorer without WINS

cannot access my own computer through My Network Places
Comment: tank you I shall check and try.

xp client problem


Can I have two mail server for different emails

Question: I have a registered domain name where the emails are handled by windows live admin center having a single mx record for my domain. I also have access to modify the dns records any time.
We have around 20 email registered in windows live for my domain. for e.g. firstname.lastname@example.com, firstname.lastname@example.com etc.
Some users want to go in for google app accounts as they say there are lots of features in it, and therefore I think I need more than one mail server in my organization.
Is it possible that i can have some emails redirected to windows live and some to google apps, provided that I have access to change the dns and mx records?
Answer: So you want different users for the same domain to go to different mail servers?
You can't do this by manipulating the DNS records - the mail will be delivered to the server(s) defined by your MX record for the domain without any reference to the user name.
However, there's nothing stopping that mail server being an application that forwards mail onto several other servers based on the user name of the recipient...
Answer: This can't be done within the DNS - mail routing is done on the domain part only.
You'll need to arrange for all of the mail to arrive at one central place, and for it to be then forwarded-on depending on who it's for.
Do note that that isn't completely trivial, although any decent mail server should be able to do it.  This is because in some cases (cc:, etc) that forwarding will need to result in two copies being forwarded, i.e. if there are multiple recipients and they're not all on the same service.


Is there a service to legally stream football games?

Question: I have a Roku TV and no cable. I understand this is on Fox, but I can't find any useful information on their website about what I need to buy or subscribe to in order to watch this live. I see how to watch old games with NFL Game Pass, and I see how I could watch last year's game on CBS, but nothing about this year.
Is there some kind of online subscription or other service I can purchase (anything other than a traditional cable service) in order to legally watch the live game on my Roku TV? (I can also use Google Cast with the TV, if that helps).
Comment: I'm voting to close this question as off-topic because  it requests either information that should be obtained directly from the provider, or information on how to break laws.
Comment: I'm not asking how to do it _illegally_, that's easy to do.

I'm asking how to do it legally and as I mentioned in the question, I've already checked the provider's site, but all the NFL and Fox sites talk about is how to stream Sunday games and Thursday night games. Thanksgiving day games aren't mentioned.
Comment: Nij, I appreciate the attention you've given my question which has obviously caused you so much frustration. I was under the impression that the purpose of this site was to ask questions about sports. I'm sure every answer to this site could be achieved by contacting experts over the phone or via email, but then why would we have any of the sites in the SE network?
Comment: [This](http://sports.stackexchange.com/q/1525) is a similar question (which was revised to avoid sounding like a [source request](https://sports.stackexchange.com/help/on-topic)). If things are the same as they were in 2012, then "there is no 'legal' way to watch live streaming NFL games online without going through a cable provider" (which [your answer](http://sports.stackexchange.com/a/15006) seems to support). However, considering there has been Super Bowl streaming since, that may have changed.
Comment: Last year for Thanksgiving, streaming was possible via Fox Sports Go (but not without providing your cable provider). http://www.cbsnews.com/news/how-to-watch-nfl-football-on-thanksgiving/
Comment: Oversimplification of how Stack Exchange works doesn't support your point. Plenty of questions about sports are closed every week.
Comment: Thanks for the feedback Nlj. In your view, which types of sports questions are appropriate for this site?
Comment: Thanks @MASTERMIND_ED, I've edited my question to make it clear that I'm looking for legal options and that I'm happy to pay for a service like Sling, I just don't want to go through a a traditional cable provider.
Comment: If nothing else, this question may be a duplicate of [a question about how the NFL distributes content online](https://sports.stackexchange.com/questions/1525/how-does-the-nfl-distribute-their-content-online), given the information is as valid today as it was almost seven years ago.
Answer: After talking with a few friends, I found two options.

Buy an HD Antennae and use that to watch the game on a local affiliate.
Another possibility is to pick up a either an orange or blue subscription from SlingTV. The orange subscription says it will let you watch Sunday games, and the blue apparently adds Thursday night, but I couldn't find confirmation anywhere about Thanksgiving day games.

So as far as I can tell, the best option is the $20 antennae on Amazon.
Comment: Unfortunately, it appears that the Thanksgiving day game isn't included in the Twitter deal :(

https://nflcommunications.com/Pages/2016-'Thursday-Night-Football'-Broadcast-Schedule-Announced.aspx


SyntaxError: keyword argument repeated: fget

Question: class Rectangle:

    def __init__(self,height,width) :
        self.Height = height
        self.Width = width

    def _get_Height(self):
        return self.Height

    def _set_Height(self,value):
        self.Height = value

    def _get_Width(self):
        return self.Width

    def _set_Width(self,value2):
        self.Width = value2

    Dimensions = property(fget = _get_Height, fset = _set_Height, fget = _get_Width, fset = _set_Width)

I was getting an error inside the property parenthesis:
SyntaxError: keyword argument repeated: fget

Highlighted underneath [ fget = _get_Width ]
Comment: You can only create one property at a time. In general you can't pass the same keyword twice anywhere - if you called `foo(bar=123, bar=456)` how would that work, what would the value of the `bar` parameter be inside the function? But why not use the decorator (or, given that your properties are pointless, just use regular attributes)?
Answer: The problem is that you set the fget= and fset= parameters twice each in the property function, which is not allowed to happen (in any function, ever). What you probably want to do is create functions which: return a tuple (getter), and accept a tuple (setter), either using lambdas or normal functions.
Also, the _get_width, _get_height, _set_width, and _set_height functions are pointless, as you can use them as normal attributes. Instead just use one function for getting (_get_dims) and one for setting (_set_dims).
In this way, you can also use the property decorator to create a property, instead of just using it as a normal function, which makes the code clearer.
The full code would be:
class Rectangle:

    def __init__(self, width, height) :
        self.width = width
        self.height = height

    @property
    def dimensions(self):
        return (self.width, self.height)

    @dimensions.setter
    def dimensions(self, new_dims):
        self.width = new_dims[0]
        self.height = new_dims[1]

Also note that variable names of things other than classes should always be lower case in Python, so I have changed the variable names accordingly.
Also, it is more normal to take width first and then height, so I have changed the order in the constructor to width, height, not height, width, but you can change this back if necessary.
Comment: Thank you. Still trying to understand property.


How do you find weights for weighted least squares regression?

Question: I am a bit lost in the process of WLS regression. I have been given dataset and my task is to test whether there is heteroscedascity, and if so I should run WLS regression.
I have carried out the test and found evidence for heteroscedascity, so I need to run the WLS. I have been told that WLS is basically OLS regression of a transformed model, but I am a bit confused about finding the transformation function. I have read some articles which suggested that the transformation can be function of squared residuals from OLS regression, but I would appreciate If someone can help me to get on the right track.
Comment: If you assume the covariance matriz of the errors is diagonal you can estimate the covariance matrix and then WLS regression with the estimated weights. To do this you can check feasible generalized least squares on http://en.wikipedia.org/wiki/Generalized_least_squares
Answer: Weighted least squares (WLS) regression is not a transformed model.  Instead, you are simply treating each observation as more or less informative about the underlying relationship between $X$ and $Y$.  Those points that are more informative are given more 'weight', and those that are less informative are given less weight.  You are right that weighted least squares (WLS) regression is technically only valid if the weights are known a-priori.
However, (OLS) linear regression is fairly robust against heteroscedasticity and thus so is WLS if your estimates are in the ballpark.  A rule of thumb for OLS regression is that it isn't too impacted by heteroscedasticity as long as the maximum variance is not greater than 4 times the minimum variance.  For example, if the variance of the residuals / errors increases with $X$, then you would be OK if the variance of the residuals at the high end were less than four times the variance of the residuals at the low end.  The implication of this is that if your weights get you within that range, you are reasonably safe.  It's kind of a horseshoes and hand grenades situation.  As a result, you can try to estimate the function relating the variance of the residuals to the levels of your predictor variables.
There are several issues pertaining to how such estimation should be done:

Remember that the weights should be the reciprocal of the variance (or whatever you use).
If your data occur only at discrete levels of $X$, like in an experiment or an ANOVA, then you can estimate the variance directly at each level of $X$ and use that.  If the estimates are discrete levels of a continuous variable (e.g., 0 mg., 10 mg., 20 mg., etc.), you may want to smooth those, but it probably won't make much difference.
Estimates of variances, due to the squaring, are very susceptible to outliers and/or high leverage points, though.  If your data are not evenly distributed across $X$, or you have relatively few data, estimating the variance directly is not recommended.  It is better to estimate something that is expected to correlate with variance, but which is more robust.  A common choice would be to use the square root of the absolute values of the deviations from the conditional mean.  (For example, in R, plot(model, which=2) will display a scatterplot of these against $X$, called a "spread level plot", to help you diagnose potential heteroscedasticity; see my answer here.)  Even more robust might be to use the conditional interquartile range, or the conditional median absolute deviation from the median.
If $X$ is a continuous variable, the typical strategy is to use a simple OLS regression to get the residuals, and then regress one of the functions in [3] (most likely the root absolute deviation) onto $X$.  The predicted value of this function is used for the weight associated with that point.
Getting your weights from the residuals of an OLS regression is reasonable because OLS is unbiased, even in the presence of heteroscedasticity.  Nonetheless, those weights are contingent on the original model, and may change the fit of the subsequent WLS model.  Thus, you should check your results by comparing the estimated betas from the two regressions.  If they are very similar, you are OK.  If the WLS coefficients diverge from the OLS ones, you should use the WLS estimates to compute residuals manually (the reported residuals from the WLS fit will take the weights into account).  Having calculated a new set of residuals, determine the weights again and use the new weights in a second WLS regression.  This process should be repeated until two sets of estimated betas are sufficiently similar (even doing this once is uncommon, though).

If this process makes you somewhat uncomfortable, because the weights are estimated, and because they are contingent on the earlier, incorrect model, another option is to use the Huber-White 'sandwich' estimator.  This is consistent even in the presence of heteroscedasticity no matter how severe, and it isn't contingent on the model.  It is also potentially less hassle.
I demonstrate a simple version of weighted least squares and the use of the sandwich SEs in my answer here: Alternatives to one-way ANOVA for heteroscedastic data.
Comment: Point 5 sounds oddly familiar to [IRLS](https://en.wikipedia.org/wiki/Iteratively_reweighted_least_squares), is that coincidence?
Comment: Good question, @FransRodenburg. It isn't really IRLS, but there's a clear analogy there. I suppose I would call it [convergent evolution](https://en.wikipedia.org/wiki/Convergent_evolution) if I had to say something.
Answer: When performing WLS, you need to know the weights. There are some ways to find them as said on page 191 of Introduction to Linear Regression Analysis by Douglas C. Montgomery, Elizabeth A. Peck, G. Geoffrey Vining. For example:

Experience or prior information using some theoretical model.
Using residuals of the model, for example if ${\rm var}(\varepsilon_i)=\sigma^2x_i$ then we may decide to use $w_i=1/x_i$.
If the responses are the average of $n_i$ observation at each $x_i$ or something like ${\rm var}(y_i)={\rm var}(\varepsilon_i)=\sigma^2/n_i$, then we may decide to use $w_i=n_i$.
Sometime we know that different observations have been measured by different instruments that have some (known or estimated) accuracy. In this case we may decide to use weights as inversely proportional to the variance of measurement errors.


Recurso do Bootstrap 3 existe?

Question: Existe esse recurso no Bootstrap 3? Não encontrei e acho tão frequente o uso em sites.
Answer: Existem sim jovem e se chama tabs, aqui está a documentação oficial do BS3 https://getbootstrap.com/docs/3.3/javascript/#tabs

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

Home

Profile

Messages

Settings

1

2

3

4

Comment: Muito obrigado Hugo!
Comment: @EliseuB. Sem problemas

Recurso do Bootstrap 3 existe?


Master's theorem applicability.

Question: I have to find out if the following recurrence can be solved with the master theorem:
$$T(n) = 3T\left(\frac{n}{2}\right) + n^{\log\log n}$$
I have figured that, here, I have the third case because $f(n) > n^{\log_2 3}$ but it understand that, in order for master to be applicable, $f(n)$ must be polynomially larger than $n^{\log_23}$ and I have no idea how to verify it.
Any help would be much appreciated!
Answer: The third case asks for (here, $a=3,b=2$)

$f(n) = \Omega(n^{\log_2 3+\epsilon})$ for some $\epsilon > 0$
$3f(\frac{n}{2})\leq \kappa f(n)$ for some $\kappa < 1$ (and any $n$ large enough)

Observe than $f(n) = n^{\log \log n} = 2^{\log n\cdot \log \log n}$; $f$ is not polynomial, it's asymptotically greater than any polynomial (in particular, for $\epsilon=1$, $n^{\log_2 3+1} = 2^{\log n\cdot(\log_2 3+1)} = o(2^{\log n\cdot \log \log n})$. The first condition holds.
The second too, as
\begin{align*}
\frac{3f\left(\frac{n}{2}\right)}{f(n)} &= 3\cdot 2^{\log(\frac{n}{2})\cdot \log \log( \frac{n}{2}) - \log n\cdot\log\log n} = 3\cdot 2^{\log(n)\cdot \log \log( \frac{n}{2}) - \log \log( \frac{n}{2}) - \log n\cdot\log\log n} \\
&=3\cdot 2^{\log(n)\cdot \left(\log \log( \frac{n}{2}) - \log\log n \right)- \log \log( \frac{n}{2})} = 3\cdot 2^{\log(n)\cdot \left(\log \left( 1-\frac{1}{\log n} \right) \right)- \log \log( \frac{n}{2})} \\
&= 3\cdot 2^{\log(n)\cdot \left(-\frac{1}{\log n}+o(\frac{1}{\log n}) \right)- \log \log( \frac{n}{2})} = 3\cdot 2^{-1- \log \log( \frac{n}{2}) + o(1)}\\
&= \frac{3}{2}\cdot \frac{1}{\log\frac{n}{2}}\cdot 2^{o(1)} \xrightarrow[n\to\infty]{}0
\end{align*}
(you can also get a sanity check to see this limit is indeed $0$ with Mathematica, although it is not a proof)
Comment: I still didnt understand how did you demonstrate that the first condition holds, could you elaborate?
Comment: Look at the exponent: one of them is $C\log n$ (for the constant $C=\log_2 3 +1$, the other one is $\log n \cdot \log\log n$ (where $\log\log n \to \infty$, so clearly greater than $C$ for $n$ sufficiently large).
Comment: I see now, it was actually very obvious.

Master's theorem applicability.


Advantage of 7-note based theory over 12-note alternative

Question: I'm a beginner at music, so I apologize if this is a dumb question. I've been trying to figure out why (in a 21/12 equal temperament tuning) music theory is based on 7 distinct notes (A,B,C,D,E,F,G) instead of the 12 semitones.
Here are a few things that bug me and make music theory very confusing for me:

It seems very redundant to have both sharps and flats (not to mention double flats and double sharps)
All pitch classes seem as fundamentally important, why are 5 of them second class citizens and not assigned a proper letter?
Why not name intervals by their actual distance (let's say 4 semitones, for example), instead of having to see what the base note is to figure out if you should call it a doubly augmented second, a major third, a diminished fourth, etc?
Is there an advantage to memorizing unpleasant things like the circle of 5ths instead of just doing mod 12 arithmetic?
Comment: An entirely different approach to music where these questions don't come up, but you intuitively learn answers to them: start playing music on the white keys of the piano. Gradually start incorporating the black keys into your playing. You learn to create music, and you don't need to ask these questions at any point. But good luck trying to make sensible music with your modulo 12 arithmetic. ;) With that "better" system you'd probably spend a lot of time and eventually "invent" the white keys of the piano.
Comment: Spoiler alert : the "unpleasant circle of 5ths" is really just mod 12 arithmetic, and you don't need to memorize anything in order to use it. ;) That being said, your question is insightful and it really resonates with me.
Comment: @ElizaWilson the idea is not novel or unconventional at all, it's more like, if you know how music works and you try to model it as maths and logic for, say, a computer program, you'll inevitably bump into the modulo 12 stuff. But for learning or making actual music it's all backwards, the horse and cart the wrong way around.
Comment: @piiperiReinstateMonica Isn't [set theory](https://en.wikipedia.org/wiki/Set_theory_(music)) essentially a description of music in terms of modulo 12 arithmetic? I don't think Alexbib's idea is as novel as they think it is, nor as unconventional as you think it is.
Comment: @EricDuminil Not really. If you think about modulo 12 arithmetic as a series of notes on the keyboard, then you're memorizing new "words" for each number. The pattern for the "words" seems a bit arbitrary as to where the sharps and flats lie (i.e. why F to Bb rather than E to Ab?) (though I know it's not arbitrary, the circle of fifths doesn't necessarily tell you why?). Also, if you treat sharps and flats differently, then it's not really mod 12, though it could be seen as a simpler rule where F to Bb always adds a flat and B to F# always adds a sharp.
Comment: @awelotta: Say you like this scale : `[0, 2, 4, 5, 7, 9, 11]`. You can try to transpose it in every chromatic key, by shifting every notes by the same amount, modulo 12. You get : `[[0, 2, 4, 5, 7, 9, 11], [1, 3, 5, 6, 8, 10, 0], [2, 4, 6, 7, 9, 11, 1], [3, 5, 7, 8, 10, 0, 2], [4, 6, 8, 9, 11, 1, 3], [5, 7, 9, 10, 0, 2, 4], [6, 8, 10, 11, 1, 3, 5], [7, 9, 11, 0, 2, 4, 6], [8, 10, 0, 1, 3, 5, 7], [9, 11, 1, 2, 4, 6, 8], [10, 0, 2, 3, 5, 7, 9], [11, 1, 3, 4, 6, 8, 10]]` You can notice that when you shift by -7 or +7, only one note has been changed : `11` to `10` or `5` to `6`.
Comment: Congrats, Alexbib! You asked the same question a lot of theorists did in 40s and 50s. This now is known as set theory.
Answer: Not all music theory is based around 7-note scales, but the 7-note diatonic scale basically 'caught on' and became popular due to a number of subjectively useful properties it has. Most of its modes facilitate many opportunities for consonant harmony, chord building around triads, have notes that are close enough for easy melodic construction, and so on, while also giving some opportunity for interesting tensions and discords, and - also importantly - being fairly simple (7 notes is quite easy to get your head around!)
So yep, a lot of 'standard'/'western' music theory is based around that scale.

It seems very redundant to have both sharps and flats

It enables you to give each note in any diatonic scale a distinct letter name, and a distinct line on the staff.

All pitch classes seem as fundamentally important, why are 5 of them second class citizens and not assigned a proper letter?

Well, if you begin by assuming use of the diatonic scale, you can see why 7 of the 12 notes are more important - because they're in that scale.
At this point you might be thinking "but there's more to life than the diatonic scale!", and sure, there is. But here's a thing: Much of the reason that we have the chromatic (12 note) scale - and in particular 12-TET - is that it is a clever pattern in which 12 different diatonic scales fit together. More often than not, people use the chromatic scale to make music that can be viewed as still being based around broadly diatonic ideas, but with the added flexibility that 12-TET gives in terms of allowing modulations, chords from 'outside the key' still sounding good, and so on.
Of course there is value in being to look at things from different viewpoints, and for some use cases, people do use terminology that gets away from the diatonic scale: we have pitch class sets, the chromatic staff, and so on. You could certainly imagine a parallel universe in which these ideas had gained a bit more currency. It may even happen in the future if music theoreticians (or product engineers!) build a 12-tone viewpoint of music that seems to offer particularly useful and important insights that a diatonic perspective doesn't.
Of course notation and analysis suited to the 12-TET chromatic scale would still be scale-specific - it wouldn't qualify as some kind of 'pure' model for music. After all, one could reasonably ask: "there are infinite possible pitches - what's so special about these 12?"
Comment: @Alexbib You're not alone - from http://musicnotation.org/, *"The need for a new notation, or a radical improvement of the old, is greater than it seems, and the number of ingenious minds that have tackled the problem is greater than one might think." — Arnold Schoenberg*. Personally, as I moved away from being a 'reading' violinist to an 'earing' guitarist, I found myself thinking of intervals more in terms of numbers of semitones than the traditional interval names.
Comment: To answer the question this answer asks, there is a definite reason for 12 notes. It boils down to there being a limited number of options where you can create simple ratio based values and have nearly equidistant spacing between notes. The next stop is 53, followed by 306. No one wants that many notes per octave. https://www.youtube.com/watch?v=IT9CPoe5LnM is a great explanation of this.
Comment: @Azendale 12, 53, 306, etc. are how you get "near equal temperament" with stacking the perfect fifth (aka, the ratio 2:3). But this is only a subset of the possible equal temperaments that  approximate simple ratios closely. You could also manually test each equal division of the octave, or stack different intervals, such as 4:5 or 3:5, which gives you instead (near) 31-EDO and 19-EDO respectively, which also contain many other useable intervals; (quarter-comma)-meantone tuning has practically the same fifths as 31-EDO.
Comment: Yeah, I get that in the diatonic scale 7 notes are more important, but it's not as if we were always playing in the same key... Whereas with 12-TET you can play a very large proportion of the music that exists without extra-convoluted notation. Anyway, thanks for pointing me to the chromatic staff, its notation makes a lot more sense to my brain!
Comment: @Dom I guess part of the point of this question is to wonder whether thinking in terms of 12 tones rather than 7 *could* be useful even when dealing with diatonic or mostly diatonic works. It's easy to think of some advantages (or arguable advantages) of thinking in a 12-tone way,  but also fully understandable that the world at large doesn't see them as outweighing the disadvantages!
Comment: @Azendale in that video he starts by considering what options you have to 'fill out' the octave without equal temperament, then he goes on to pick 12, and explain what it means to temper it. But if you begin the process with the possibility of equal tempering, can't you pick any root of 2 as your step size? To look at it another way, if you want the notes from 12-TET and some more, don't 24-TET and 36-TET achieve this?
Comment: So Schoenberg was a very experimental and his music sought to make all 12 tones equal in importance which most if not all musicians will not want to do. If you are writing in that style, you are using concepts like tone rows and set theory which have been around a while over typical tonal harmony. I think it's very important to remember that option is available, but is only really useful when dealing with post tonal ideas which while most people don't deal in strict tonality, people do write more tonal than not in western music. There's a reason the 4 chord song covers so many songs.
Comment: @awelotta You just taught me more! My thinking would be since simpler ratios have less dissonance, that would be the default you start with. I didn't know about 19 and 31 EDO. Seems like those would be alternative versions of the general "equal spacing balanced with good harmony" idea. Tools for expression that would coexist. Whereas "7 notes with special notation to access some of the 12 equal tones underneath" seems like a kludge built over time, not a well reasoned system.
Answer: Until 12-TET was invented a 7 note system (A-G) made more sense. The tuning, with ratios 1, 9/8, 5/4, 4/3, 3/2, 5/3, 15/8 and 2 from the first note of the scale, gave flexibilty, scope for melodic invention, scope for harmonies that sounded good, and it worked well with instruments like the trumpet where some of these ratios are part of the physics of how they work. The system could be extended into sharps and into flats.
There were known issues with the system, because the sharps and flats did not work together. In particular A-flat and G-sharp were so different they could not be used to replace each other, so a keyboard could not play an A major scale and an E-flat major scale without being re-tuned.
The 12-TET tuning system approximates the traditional system well enough most of the time, and it gives far more flexibility for composers. A number of composers have tried to break out of the traditional scale system, but their attempts have not gained general popularity.
Perhaps it is a self-sustaining system where children hear scale-based music and learn to like it, so that is what their children hear, too.
Comment: @RosieF that same coincidence is why 12-TET works at all.
Comment: "made more sense". Indeed still makes more sense. "A-flat and G-sharp were so different they could not be used to replace each other" True, but they mean different things, and it is only a mathematical coincidence that they are so close that anyone might think that either pitch might serve as a replacement for the other pitch.
Comment: @Azendale But this is exactly what we do have. Guido's system provided notation for hexachords on G, C and F; this (with B and B flat) gracefully upgraded to handle some 7-note scales; further flats and sharps upgraded it to handle further 7-note scales and chromatic alterations.
Comment: @RosieF "only a mathematical coincidence" - maybe, but it's a mathematical coincidence that (to many people's ears) does actually work, which means they genuinely can be thought of as the same note, and the same pitch. (And I do mean *can* be, rather than have to be).
Comment: @RosieF I would say there is no reason that 12-TET shouldn't be where we start. Then add a notation for micro pitch shifting/hinting for when we want to be as accurate as differentiating A flat and G sharp. Systems that simply express the basics and can still gracefully upgrade to handle the complicated are a beautiful thing. Pitch shifting/hinting could then be also used for microtonal music, giving a system that can do more, while still being simple for the beginner.
Answer: There are some good answers here, but I would like to answer two of your points in a way that nobody here has used.

It seems very redundant to have both sharps and flats (not to mention double flats and double sharps)

At the first glance it is so. However by discarding the other accidentals you rob yourself of a lot of features that make reading scores considerably easier.
Here's a C major scale:

Notice how the dots are nicely lined up. Each dot is one line or space above the previous one, and each line and space is occupied by exactly one dot (within the scale). That makes the scales very easy to spot. I also feel that it's very natural to represent scales like this.
Now consider F major. Traditionally, you write it as shown on the left. Since each degree of the scale has its own line/space, you can introduce key signatures that can target each note separately. So you can write the scale in the way shown on the right too:

If you forbid the usage of flats, suddenly it's very hard to do this. You could write an A# instead of the Bb, but that will put two dots on the same space and the next line will be empty, so the nice properties are lost. The only way to keep the nice properties and write the scale without using flats is this:

I certainly prefer the traditional way.
In fact, there are lots of similar features in the traditional notation. There are quite some patterns that make reading simpler: for instance, if you're in A minor, the dominant chord is E major, written as E-G#-B. Now you use the same pattern in the other keys too, so in B flat minor the dominant chord is F-A♮-C (you had too many flats, so instead of a sharp you use a natural), and in G# minor you would use D# major, written as D#-F-A#. Each time you used a different accidental for the middle note, but it is always "one semitone sharper than the rest of the key". (By the way, the reason for using the double accidentals is just upholding these patterns even in keys with lots of sharps or flats.) If you forbid using some accidentals, this breaks for some keys. (Also the chords would need to change their "shape" on the staff in some of the keys which would make them harder to read.)
Here's an image to make it more clear, hopefully:

In the first bar, there is a very simple chord progression in A minor. In the second bar, I have written the same progression, but transposed to D♯ minor. You see that if I use a double sharp, it looks just like the original. However if I forbid using double sharps, I need to write what is in the third bar. You can certainly see that the chord highlighted in red now looks different (it's no longer a nice stack of three notes), even though it's the same chord, so in this way we have only made it more confusing. To get rid of this confusion, we use double sharps. (Similarly for double flats in other situations.)

Is there an advantage to memorizing unpleasant things like the circle of 5ths instead of just doing mod 12 arithmetic?

Yes. There is a decisive advantage. Suppose you have two different major keys. Now let's define the distance d(A,B) of those two keys as the number of notes in which they differ (not taking the enharmonic equivalents into the account, so for the purpose of this definition, A# = B♭ etc.)
For instance, C major has the notes C, D, E, F, G, A and B, and D major has notes D, E, F#, G, A, B, C#. They share 5 notes and differ in two, so d(C major, D major) = 2. However, the C# major scale has the notes C#, D#, E#, F#, G#, A#, B#, so it share two notes with C major (E#/F and B#/C) and d(C major, C# major) = 5.
I think that this notion of distance is quite natural. (This is very useful. For instance if you are in a certain key, you want to harmonize melodies mostly using the "nearby" chords in this sense.)
And now the important thing: on the circle of fifths, the adjacent keys have always d = 1. So d(A, B) = the number of steps you need to take on the circle of fifths to get from A to B (taking the shorter way). I think that this makes the circle immediately useful and well worth remembering. (And by the way, the circle measures the distance for the minor keys in just the same way.)
Comment: @EricDuminil that is true, but it it seems to be a "fuzzy" recognition that can gloss over the major vs minor. Where there is more space in a 12 note system which makes it slightly harder to recognize chords, but a major or minor chords have distinct shapes and are always consistently shaped, since notes are not being "modified" by a key signature.
Comment: @Azendale: that's of course true. I find the advantage of the traditional system in the fact that tracking diatonic notes is not too hard and the system makes it painfully obvious when some note is out of key (accidentals appear — at least when a correct key signature is used). A 12-note system would also use >50% more vertical space, which is not negligible (considering that most instruments can play both well below and well above their staff).
Comment: The lines in a staff also make it easier to recognize common chords (e.g. CEG or ACE).
Comment: @DavidLE: No. I try to explain the reasons in the answer, but for your convenience, I'm going to add an image to it that will hopefully make it more clear.
Comment: From a genuinely 12-tone perspective, perhaps the idea of a 'key' being based around a 7-note scale would not exist, and therefore nor would the concept of 'distance' in the sense you've explained it..?
Comment: @topoReinstateMonica: That's true
Comment: @Azendale true. With the current system, you need to know the diatonic chords. Which isn't too hard, at least for the common keys.
Comment: I understand that flats and sharps serve as a convenience to sheet music, but what about double flats and sharps? Shouldn't it almost always be better to just play the next note of the scale?
Answer: I would like to give a really elementary perspective.
If you know what music is, but don't have a lot of experience making it except maybe by singing along, then it seems like the simplest thing to do is make an instrument with all the notes uniformly spaced, and the simplest notation would be some kind of graph where each note had its own row.
But not all combinations of notes make equal sense together. This is at least partially cultural, but some of it has to do with the physics of how the sound waves interact. For instance, if one note is a vibration that's twice as fast as another, then people in lots of cultures think of them as, in some sense, "the same note". We say they are an octave apart and give them the same letter. If one note vibrates 1.5 times as fast as another, people often think they sound good together, and we call that a "perfect fifth".
Because of this, if you write a melody that sounds good to Western ears, there will usually be one note that is sort of the "main note", and most of the other notes will come from a 7-note scale starting with that main note (which is called the "tonic"). In other words, the major scale is a set of notes that sound a certain way together, and that set is so important that it's built into the notation rather than treating all the notes in an evenhanded way.
So the instruments and notation all evolved in such a way that the notes that are "most natural" for the piece you are playing don't require any special notation, but you can use other notes by putting a sharp or flat right in front of the note on the page (that is, an accidental). This ends up being a convenience for a musician, once you develop some experience.
There is one complication. If you take an octave and divide it into twelve equally-spaced steps, none of the notes is (for instance) exactly 1.5 times the frequency of the tonic. The closest one is about 1.498 (according to Wikipedia), which is pretty good. This kind of tuning is called 12-tone equal temperament, or 12-TET, which others have mentioned. Centuries ago, instruments would be tuned so that a 5th was a true perfect 5th, but then you would have to re-tune instruments to play in a different key.
Comment: The reference to Bach is a common misconception.  Bach wrote *The Well-Tempered Clavier" for a well-tempered instrument, not an equal-tempered one.  https://en.wikipedia.org/wiki/Well_temperament The point of the work is not that all the keys sound the same, the point is that all the keys sound different, and each prelude and fugue is especially suited for the intonation of that key.
Comment: Thanks, @brendan, I think I probably never understood that correctly. I'll remove that part.
Answer: It's a big question, hopefully with not-so-big answers.
For starters, the grand stave developed as the simplest way to portray where the notes can be put so people can translate them into playable music. Seven letters work well, diatonically, as by the time we get to eight, the cycle repeats. And each letter has its own place, on a line or space. Non confusing, in reality.
Sharps/flats? As we move away from the C D E F G A B found in key C, certain letter names are o.k., except that they don't represent a white key on piano any more. For instance, in key E, the note G doesn't work as well as G♯, which while it's in a different place on piano, it has the same place on the stave. If we ten called it G♯ as the tonic in G♯ major, it affects all the notes and complicates things unnecessarily. Callin it A♭ makes things far simpler. That paragraph may take a bit of unravelling.
Intervals? Again, because any note could have at least two names, the naming of intervals has to be a little involved, and it's not possible to name an interval heard accurately. It has an academic factor which involes knowing what the notes actually are. Yes, with your idea of maybe only sharps or flats, that could be simplified, but further down the line it makes things more complex! Life is full of compromises!
Cirsle of fifths? Unpleasant? Don't get that. It's contrived, maybe, but it's a useful tool in music, and even if you're not aware of it, you use it anyway. Actually knwing it can make theory and playing easier. Look at any letter name. Call that chord I. its neighbours are IV and V - the mainstay of most Western diatonic music, for starters.
Answer: I think the OP is right, 7-note based music theory is unnecessarily complicated and convoluted compared to the 12-note alternative. It is like this due to historical legacy. This is similar with how natural languages have grammar that is often irregular and full of exceptions to rules for historical reasons. Yet, once you have learned the language, it will start to feel natural despite its irregular structure. Most native speakers of a language would be opposed to reforming their language just to make it easier for foreigners to learn. In the same way, most people who have learned 7-note based music theory and have been using it for a long time are strongly opposed to switching to a different system because the 7-note based system has started to feel natural to them despite its flaws. There are artificial languages like Esperanto that have more logical grammar than natural languages but they have not really caught on. The same goes for alternatives to 7-note based music theory: they may be theoretically better but have not caught on much. So the main advantage of the 7-note based system is simply that it is already widely used.
Comment: Life experience has shown that many of the standards and systems we "suffer" under were not picked because they are the most logical or best, but because they were first, and switching from them is too hard until everyone else does. So the US keeps not using the metric system, almost nobody speaks Esperanto, most people use Qwerty instead of Dvorak or Colemak, and the internet still mainly uses IPv4 instead of IPv6. Personally, I have found using sheet music printed in 12 tone notation helps connect sight reading with hearing music, which is a massive positive for me.
Comment: @personal_cloud I'm not sure, but I think everything can be represented properly in 12-based theory, including triads and the circle-of-fifths, they just become a bit more explicitly about mathematical relations, so maybe less intuitive for some people.
Answer: The point of the 7-tone scale is that it reflects compositional practice over the past 1000 years or so. Early theory (and for that matter, early music like Gregorian Chant) used only 7 notes (actually 8 as B could change to B♭ under some circumstances.) In Western theory, the 12-note chromatic scale came later than the 12 note diatonic stuff. That's the historical answer.
There is a (hand-waving) mathematical argument explaining the interest in a 7-note scale. If one takes 7 perfect fifths (ratio 3/2) then they line up nicely as F to E (one can take 12 perfect fifths and line up F to F if desired too.) One gets a scale with 6 perfect fifths and 1 diminished fifth. By positioning the diminished fifth in different places, one gets 7 different patterns; the chromatic scale (12 note) gives only 1 pattern.
The cycle of fifths exists in any 7 or 12 tone system (in common use.) However, the 7-tone patterns are different from one another as well as occurring on different pitches.
A couple of references I found (while looking for something else.)
https://www.academia.edu/35382108/Chapter_1_DIATONIC_THEORY
https://www.academia.edu/35400186/Chapter_2_WELL-FORMED_SCALES
https://www.academia.edu/10482229/Scratching_the_scale_labyrinth
Comment: The commonly made Pythagorean 7-perfect-fifths argument doesn't really make that much sense because **a)** this doesn't really explain why you'd stop at 7 **b)** tonal music since the Renaissance has been 5-limit, not 3-limit.
Comment: "mathematical argument explaining the interest in a 7-note scale" True, but the importance of the 7-note scale still exists even if nobody argues the mathematics. Intervals between pitches whose frequencies are in the ratios of small integers sound nice when played together or one after the other.
Comment: As far as I can tell, there's no mathematical explanation why the major scale should have 7 notes. It's only because of historical and cultural reasons.
Answer: This question is very interesting. It touches the fundaments not only of all music symbolic representations, but also the theoretical system, the tone resources,  note repertoire, intervals, triads and chords and the of notation, reading and playing.
I can imagine a 12 tet notation system that is more comfortable than the traditional grand staff - I' ve even developed such a system by myself 40 years ago. It was something like a horizontal piano roll that we know today from Youtube: there were 5 lines (2 and 3 with a standard space between the lines and double  space between the 2 groups) representing the black keys , the notes for the white keys are notated in the space between the lines. So the sharps resp. flats were notated on the lines, d between the 2 lines, g and a between the 3 lines, the semitone steps (ef and bc) in the double space between  the 2 and 3. This system fitted well for notating (and reading!) 12 tone music.
About 30 years ago I had my 1st atari ST 1024 computer and was working with the notator program. There was a grid editor where the note lengths and the pitch was represented in a grid system, maybe this was something you have in your mind.
A mathematician invented a program called Presto, you could draw with the mouse lines and circles which the program computed in tones. (It's the software of which Karajan said, he could have played the whole night with it - me too!)
Yes, you are not alone. But don't forget the notation system and the entire music theory of western music is the result of a development of thousands of years, and it has not only been influenced by the greek tetrachords and scales, natural tones and over tone series but also by the instruments and the way we play them. We still could know the tablature for organs and lutes,  we still use guitar tab, and ... imagine the setting of the buttons of an accordeon! (I don't know how this works.) maybe this would be an approach to another system?
Anyway, the theoretical system of western music and it's notation, the function of the tones and chords, the harmonic analysis all this alone is an artwork by itself, apart the great compositions written based in this system, that could never be interpreted and understood without this bases of relations of keys, chords, functions, circle of fifths.
Maybe everything had been said in this language when Schoenberg started writing his  TET music.
But Bartok, Hindemith, Gershwin, Shostakovich, Bernstein, Rutter (many others) and  Jazz make me assume something different.
Comment: I did something similar, but I used twelve lines per octave placed to represent the edges of keys, so there were five pairs of closely spaced lines, separated by a wide gap, and two lines that had medium gaps on either side.  IMHO, it might have been nice for actual piano rolls to be marked in such a fashion since it work work nicely with the uniform hole spacing they used, but still make it visually clear what notes were represented.
Answer: Some excellent questions here.

It seems very redundant to have both sharps and flats (not to mention double flats and double sharps)

Sharps and flats are a holdover from pythagorean tuning. In this method, the "circle of fifths" is actually more of a spiral of fifths - stacking fifths yields a sequence of sharps, while traversing the spiral in the other direction (stacking fourths) yields a sequence of flats. Pythagorean theory is interesting because it actually can yield an infinite set of notes (or at least a very large finite set). It's true that in equal temperament, this spiral is "flattened" so that we go from an infinite set to a set with just twelve members.

Is there an advantage to memorizing unpleasant things like the circle of 5ths instead of just doing mod 12 arithmetic?

All pitch classes seem as fundamentally important, why are 5 of them second class citizens and not assigned a proper letter?

(I'm going to use the words "scale" and "set" here interchangeably.)
The natural major scale and its associated modes is very important in Western theory. There's an easy programmatic way to build a natural major set from the twelve-tone set, assuming that the twelve-tone set is cyclically ordered in a specific way (the circle of fifths). Take any note, and stack fifths until you have seven notes. That is a natural major set (ordered in the Lydian mode). (Note that even though we use equal temperament, this method is still rooted in Pythagorean philosophy.)
The natural major scale represents an adjacent ordering of seven pitch classes on the circle of fifths. The pentatonic scale represents an adjacent ordering of five pitch classes on the circle of fifths (in the natural major case, it's the set of five "unused" notes). The same method of stacking fifths, as such, also works to construct a pentatonic scale.
I can't really speak to the lettering, as they do seem somewhat arbitrary. (Essentially, why are the white keys white and the black keys black? Even with only seven note names, I'm not sure why the "sharps and flats" seemed to get the shaft.) My guess is that someone started with what we know as F and built a natural major set out of that, and it because the "default".

Why not name intervals by their actual distance (let's say 4 semitones, for example), instead of having to see what the base note is to figure out if you should call it a doubly augmented second, a major third, a diminished fourth, etc?

I believe this again goes back to Pythagorean tuning, which depends on a base note to determine where the other notes lie. Unfortunately, equal temperament leaves this making a lot less sense as it's largely unnecessary outside of strict classic musical theory analysis standpoints. (Due to enharmonic equivalency influencing music theory, I think we're now seeing branches of music theory that break away from classical theory, which is interesting.)
That said, I believe there are systems that do what you are talking about - they eschew ciassic naming conventions, notation, and interval categorization in favor of a system that more accurately reflects the state of equal temperament tuning. However, I don't believe that these systems have been well accepted in musical parlance - by composers, theorists, and performers alike - and that's why we don't see them. Essentially, despite some of its drawbacks, the western music systems we have are perpetuated in the name of tradition, and they will continue to be.
Answer: Just for context, I'm a maths nerd and I have to agree it does all seem completely arbitrary: to me music seems like set theory. I have spent considerable amounts of time talking to musicians and not understanding why they construct their notation/music in the way they do: particularly as they often disagree with each other.
So my final understanding is that it's ultimately about making 'good sounds.' I reckon 'good' has two aspects: one is arbitrary and cultural i.e. 'this is how we have always made good sounds, they have these meanings and they work around these scales (i.e. tone sets, often with between 5 and 8 elements) on these chord movements (these sub-sets of the main set played simultaneously, in this order.) '
The other aspect of 'good' is probably related to physics. A perfect 5th is so near to the root note, (to my ear) that it sometimes sounds like an overtone of the string I'm playing on the guitar (especially with distortion); so practically speaking it isn't even part of a chord, merely a fatter tone, with no musical colour. What I mean is that some intervals are simpler, and occur more commonly in nature (in terms of frequency ratios) and so they are favoured more often. But the order in which these intervals are considered 'good' isn't purely due to the simplicity of the frequency ratio and is also partially determined my cultural meaning. For example, the Gypsy-Spanish music I love seems to prefer a semitone and a minor third – rather than the 'harmonically simpler' major third and tone.
How you stack these intervals into an octave, and the tone/semitone runs you use to fill out those 'harmonies' into a scale seem completely arbitrary (but you are constrained it you want to have a rich set theory – 'classical music' is one of those, I think.) You could also split the octave into more intervals than 12 (24 springs easily to mind) and you would also have a perfect 5th, 4ths major thirds etc. or maybe, divide two octaves into one complex scale if you wished (or 7 – but at some point the constraints of human memory play a role.)
So to me these are cultural set-theory games, but they do often seem to play either with the tension between what is considered 'consonant' and 'dissonant', with the latter often resolving to the former, or they enjoy repetition, perhaps in some dance/meditative sense (okay, I'm ignoring dynamics for now.) I think that whatever musical culture precedes you will make more sense to you and those tone-sets/scales will also have a particular meaning (e.g. the western 'minor is sad'.) Again, Gypsy-Spanish music, twists many classical music theory constraints, but sounds fantastic to my ear.
As for notation – well just take a look at writing for arbitrary notation – anything that works well, would be my guess, just so long as we could read it easily. Actually, now that I think about it, that is a massive constraint; what we can process in real-time. Most humans couldn't hear, remember, read or play even a fraction of the possibilities of music. So maybe that cuts the tone-set down to five (pentatonic) plus a few extra notes (perhaps one or two quarter tones for extra colour.) This means that attempting to create a notation for 12 (never-mind 24) tone music might not work. So maybe seven feels about right..
Answer: Your question had two parts. One about 7-note scales, the other about sharps and flats. Clearly the 7-note scale is driven by actual use of that scale, as other answers have noted. But the reason for sharps and flats is structural, having to do only with abstract mathematical properties of translations on subgrids.
You need subgrid structure. Sure, mod 12 arithmetic is fine. But 12 is a lot of points to think about or see. Think of trying to read a ruler that only marks full inches and 1/12 inches, with all the tick marks between the inches looking the same. Hard to read, right?
So you want some kind of subgrid. Regular subgrids (that include the octave) are based on 2, 3, 4, or 6 pitch classes. Maybe the best is 6. Let's call them 0 1 2 3 4 5 (= C D E F# G# A#). Suppose we try to get rid of the "flat" concept, which you complained was redundant. Pentatonic scales would be:

0 1 2 3# 4#
0# 1# 2# 4 5
1 2 3 4# 5#

etc.
Now you see an issue here: do the base numbers go 0,1,2,3,4, or 0,1,2,4,5? So we need a flat concept, so then we'd have:

0 1 2 3# 4#
1b 2b 3b 4 5
1 2 3 4# 5#

etc.
The sharps/flats issue comes up with any scale that goes off a regular grid, not just pentatonic scales. Any kind of harmonious music will go off any regular grid (since the overtone series itself quickly goes off all regular grids). And so, if you want to play in any key, then whatever regular subgrid you choose will need sharps and flats.
(For irregular subgrids like the 7-note scale, sharps and flats are also required in order to keep the base numbering consistent in all keys. To see this, take a scale with both on-grid and off-grid notes. Shift it up by semitones, and note that the on-grid and off-grid notes change base symbol at different points unless you have redundant modifiers).


Why is this the generating function for the set of partition numbers?

Question: Within my lecture notes, it is stated that the generating function of $\{ p(n) \}$ is given by
$$
P(x) := (1 + x + x^2 + x^3 + \dots )(1 + x^2 + x^4 + x^6 + \dots )(1 + x^3 + x^6 + x^9 + \dots ) \dots
$$
That is, the coefficient of $x^n$ in the expansion of $P(x)$ is equal to $p(n)$ (the number of ways of writing $n \in \mathbb{N}$ as the sum of positive integers).
However, I am struggling to see why this is true. Clearly the coefficient of $n$ in this expansion is equal to the number of solutions to the sum
$$
a_1 + a_2 + a_3 + \dots = n
$$
where $a_1 \in \{ 0,1,2,3,\dots \}, a_2 \in \{ 0,2,4,6 \dots \}, a_3 \in \{ 0, 3,6,9, \dots \}$ and so on. However, this does not account for some partitions of $n$, such as $1+1+1+ \dots + 1$.
It also counts some partitions twice. For example, if we are considering $n=5$ then it would count $2+3$ and $3+2$ as separate partitions.
So what is the reason that there is a correspondence here?
The reason that this is important to understand is because I come across questions which ask me to find the generating function of the number of partitions of $n \in \mathbb{N}$ subject to some condition (i.e. all parts being distinct, etc). The way that these sorts of questions are answered is by starting with the expression for $P(x)$ given above, and then cancelling out certain terms. Without understanding how $P(x)$ is reached, it is difficult to know which terms should be removed.
Answer: Think, instead, that $a_1$ is the number of $1's$ in the partition, $a_2/2$ is the numbers of $2$ and so on. Hence you would have something like $$\underbrace{1+\cdots +1}_{a_1}+\underbrace{2+\cdots +2}_{a_2/2}+\cdots +\underbrace{k+\cdots +k}_{a_k/k}+\cdots =n.$$
Comment: @MSmith yes sir.
Comment: Thank you. As an addendum, could you help me to understand the effect of eliminating certain terms from the expression for $P(x)$?  For example, in terms of partitions of 5, what would be represented by the generating function given by
$$
P(x) = (1 + x + x^2)(1 + x^2 + x^4)(1 + x^3)(1 + x^4)(1 + x^5)
$$
Comment: So, if you see, you are allowed to put $0$ or $1$ 5. Same with $4$ and $3.$ You are allowed to put $0,1,2$ $2's$ and you are allowed to put at most $2$ 1's hence it is the number of partitions of $5$ in which at most there are $2$ ones.
Comment: So am I correct in thinking that the terms in the first bracket determine how many 1's there may be in our partition, and the terms in the k$^\text{th}$ bracket determine how many k's there may be in our partition?
Answer: The coefficient of $x^n$ in the expansion is the number of solutions to
$$
1a_1+2a_2+3a_3+\dotsb=n
$$
where $a_i\geq 0$. Hence the coefficient of $x^n$ is the number of partitions of $n$. The partition $1+1+\dotsb+ 1$ of $n$ is accounted for by choosing $x^n$ from the first bracket and $1$ from the remaining brackets. Also the partition $3+2$ is accounted for by choosing $x^2$ from the second bracket and $x^3$ from the third bracket and $1$ from the remaining brackets.


event emitter works one time but not a second time Angular 8

Question: I have this variable which controls if a dialog shows up or not, it works on the first time, but not on a second time, emit excutes but the receiveing function is no longer called.
parent class:
  isLogin :boolean ;

  constructor(...){
    this.isLogin = false;
}
  receiveNotification(notification: boolean): void {
    this.isLogin = notification;
  }

parent html:
<login-dialog   *ngIf="!isLogin"  name="{{name}}" (notify)="receiveNotification($event)"></login-dialog>

in the child class:
I have a function that when triggered calls emit and emit is indeed called just doesn't trigger the function on the parent on a second time
@Output() notify = new EventEmitter<any>();

  exampleFunction(){
 this.notify.emit(true);
}

I think maybe this is connected to the ngIf but not sure,  what is wrong here?
Answer: It could be because you are emitting a true value but on the parent template you are checking for !true which is false.
As per your current logic, you should either emit a false value or change the condition to *ngIf="isLogin" in the parent template.
Answer: Try to use hidden instead of ngIf, because ngIf remove the component from the DOM but hidden just hide it.
<login-dialog   [hidden]="isLogin"  name="{{name}}"...></login-dialog>