Elliptic curves: Why over the complex numbers?

Question: I am a math undergrad, so much of the literature on elliptic curves escapes me. I'm trying to understand why one considers elliptic curves over the complex numbers. Specifically, this part of the Wikipedia article is very technical and hard to understand for me. Silverman and Tate say the following:

In general, two cubic curves meet in nine points. To make that statement correct, one should first of all use the projective plane, which has extra points at infinity. Secondly, one should introduce multiplicities of intersections, counting points of tangency for example as intersections of multiplicity greater than one. And finally, one must allow complex numbers for coordinates. [emphasis mine]

I understand the two first musts, but why must we allow complex numbers for coordinates? An explanation in language understandable by an undergrad would be appreciated. Thanks.
Comment: Here's an analogy: A polynomial of degree 3 has 3 roots, counting multiplicities. But only if we count roots in $\mathbb C$ as well as $\mathbb R$.
Comment: Silverman--Tate's statement about 9 intersection points requires coordinates in some algebraically closed field (e.g. the complex numbers). But as the Wikipedia article goes on to discuss (in the section after the one you linked to) there are many interesting questions about elliptic curves over other fields, like the rational numbers.
Answer: In general, Bezout's theorem asserts that two curves in the projective plane over an algebraically closed field intersect in a number of points wich equals the product of their degrees, counting the points with multiplicity and assuming that the two curves have no components in common. You cannot relax hypothesis of this theorem in any way. If you consider the affine plane instead of the projective one, you could not be able to "see" points that lie at infinity, e.g. take two parallel lines in the affine plane over any field.
If the field is not algebraically closed the curves could have intersection points which "do not appear" because of the fact that over fields which are not algebraically closed there exist polynomials in one variable of degree $>1$ which are irreducible. In fact, finding points of intersection of two algebraic curves roughly means finding zeroes of polynomials. For example, consider the conic given by $x^2+y^2-z^2=0$ and the line $z=0$. If you consider them as curves over $\mathbb R$, you won't find any intersection point, because the equation $x^2+y^2=0$ has as the only solution over $\mathbb R$ the pair $(0,0)$ which does not give you a point in the projective plane since $(0\colon 0\colon 0)$ is not allowed. But over $\mathbb C$, you can find the two intersection points: they are $(1\colon i\colon 0)$ and $(1\colon -i\colon 0)$.


What alternatives are there to the generalized continuum hypothesis?

Question: Since the generalized continuum hypothesis is independent of ZFC, we can adopt its negation as an axiom. However, this would not be a very "nice" axiom, since all it does is assert that there is at least one instance in which GCH fails.
My question is what axioms have been studied that prove the negation of the GCH, but has many more consequences than the negation of GCH. In particular, I am looking for ones that mathematicians would consider appealing axioms for mathematical foundations, not merely any statement that implies the negation of the GCH.
As an example, I would consider the Axiom of determinacy a "nice" alternative to the Axiom of choice.
Answer: There are many reasonable axioms that have been studied in diverse situations and all are known to contradict instances of GCH.
By far the strongest case can be made for strong forcing axioms such us Martin's maximum MM, or some of their significant consequences or close relatives (strong reflection principles). These forcing axioms imply that the continuum is $\aleph_2$ (so CH fails) and have many appealing combinatorial consequences. They also imply the singular cardinals hypothesis, which in turn implies many instances of GCH, so their effect in cardinal arithmetic is not "wild".
But axioms rather different than these have been considered as well. For example, the existence of (atomlessly) real-valued measurable cardinals implies that the continuum is very large. The axiom is perhaps most appealing in its alternative formulation stating that there is a measure extending Lebesgue measure and defined on all sets of reals. (On the other hand, the effect of this axiom on cardinal characteristics of the continuum is rather different from the nice behavior provided by Martin's axiom.)
There are also ad hoc axioms that have been considered precisely because of their wild behavior. I think these are different from the examples above, which are reasonable assumptions for a working mathematician. Perhaps the best known here is the maximality principle, still not known to be consistent, which implies that GCH fails everywhere. In a sense, MM seems to come from an attempt to obtain a reasonable version of this principle, see the comments to this answer in Mathoverflow.
Comment: Do you have a name or reference for the axiom in the third paragraph?
Comment: The maximality principle? The answer I linked to mentions the standard reference. The principle is due to Foreman. The reference is [MR0830070 (87i:03102)](https://mathscinet.ams.org/mathscinet-getitem?mr=830070).
Foreman, Matthew; Magidor, Menachem; Shelah, Saharon. *[$0^\sharp$ and some forcing principles](https://doi.org/10.2307/2273940)*. J. Symbolic Logic **51** (1986), no. 1, 39–46.
Comment: no, the one about the lebesgue measure
Comment: For the existence of atomlessly real-valued measurable cardinals, Kanamori's book on large cardinals has some of the history and a modern treatment, and yu probably want to start there. The axiom was shown consistent by Solovay, in [MR0290961 (45 #55)](https://mathscinet.ams.org/mathscinet-getitem?mr=290961). Solovay, Robert M. *Real-valued measurable cardinals*. In **[Axiomatic set theory (Proc. Sympos. Pure Math., Vol. XIII, Part I, Univ. California, Los Angeles, Calif., 1967)](https://bookstore.ams.org/pspum-13-1)**, pp. 397–428. Amer. Math. Soc., Providence, R.I., 1971.
Comment: An encyclopedic survey can be found in [MR1234282 (95f:03084)](https://mathscinet.ams.org/mathscinet-getitem?mr=1234282). Fremlin, D. H. *Real-valued-measurable cardinals*. In **Set theory of the reals (Ramat Gan, 1991)**, 151–304, Israel Math. Conf. Proc., 6, Bar-Ilan Univ., Ramat Gan, 1993. You can find a pdf of it in Fremlin's page.
Comment: I also wrote a paper with a short survey, which includes a characterization in terms of generic embeddings. See [MR2267147 (2007g:03064)](https://mathscinet.ams.org/mathscinet-getitem?mr=1234282). Caicedo, Andrés Eduardo. *Real-valued measurable cardinals and well-orderings of the reals*. In **Set theory**, 83–120, Trends Math., Birkhäuser, Basel, 2006. You can find a copy in my papers [page](https://andrescaicedo.wordpress.com/papers/).
Comment: Does the atomlessly real valued measurable cardinal contradict the axiom of choice? If AC proves the existence of non measurable sets, but ARVMC proves its negation then it should be so unless I'm missing something.
Comment: @Lave These cardinals are compatible with the axiom of choice. The measure you get extends Lebesgue measure, but it is not Lebesgue measure.
Comment: @AndrésE.Caicedo would it retain the same properties?
Answer: I'm personally a fan of the inner model hypothesis - or rather, hypotheses might be more appropriate. IMHs should be understood as codifications of the general idea that "Anything which can happen, does" in a precise sense via inner and outer model theory.
Specifically, the idea is that the set-theoretic universe $V$ should be maximally rich with respect to inner models. For example, both $\mathsf{CH}$ and $\neg\mathsf{CH}$ are "easy to achieve" via forcing, so $V$ should have inner models where $\mathsf{CH}$ holds and inner models where $\mathsf{CH}$ fails. A bit more specifically:

Anything which can happen in an inner model of an outer model of $V$, already happens in some inner model of $V$.

I personally find this idea quite attractive. The technicality of inner/outer models is definitely something which can give someone new to the field pause, but I think is actually very natural - especially in light of the role that forcing and inner model constructions already play in set theory.
Of course this is all wildly imprecise, and this is where the pluralization above comes in: there are multiple different ways one might try to formulate this principle. See here (and the papers cited therein) for more details on this point. The point is that even a mild IMH makes the continuum quite large. It also, interestingly, contradicts even the existence of a single inaccessible cardinal!
Answer: One thing to keep in mind are models where the GCH holds up to a point and then "fails." Gitik says something about the argument in "No bound for the first fixed point" requiring the GCH below the FFP but then there is no special bound on the FFP's powerset. Otherwise, I don't know if there's a generalization from $2^{\aleph_0} = 2^{\aleph_1} = \aleph_2$ but...
Now here it says that:

... Woodin showed (again assuming large cardinals) that it is possible that for all κ, 2κ = κ++.

But the context is singular cardinals so I'm not sure "all $\kappa$" means all cardinals whatsoever, or singular ones. Still, whatever the proof actually is, it constitutes some kind of at least partial alternative to the GCH.
Comment: It means all infinite cardinals $\kappa$. It is also consistent to have GCH fail solely at all singulars, or to fail solely at all limit cardinals.


Cannot add property to an outer object from function scope?

Question: I have a function that gives me a socket object inside the io.on() function. However when i try to give a new property to its object inside a socket.on function, i am unable to use the property outside the socket.on function.
The console shows me this -
roomName
#undefined

I want to know how can i use the property outside the object also.

io.on("connection", function(socket) {
 socket.on("join_group", function(user, roomnum) {
  socket.userName = user;
  socket.selfRoom = roomnum;
  socket.join(roomnum);
  console.log(socket.selfRoom);
 });
    socket.on("msg", function() {
 console.log("#" + socket.selfRoom);
    });
});
Answer:
I want to know how can i use the property outside the object also.

You are setting the property to outside object socket in the callback function to on event.
But by the time on event-handler is invoked, outside console.log("#" + socket.selfRoom); statement has already been executed.
Please note that

Defining the event handler socket.on("join_group", function(user, roomnum) { is not same as this event handler (callback method) being invoked.
JavaScript is single threaded and work on event-loop model, so when the event is fired this event-handler has gone to a event-loop queue which will be executed after the current task + task already in queue.
Comment: I am sorry, I have edited my question. Please have a look. I actually wanted to know how can i add properties to an outer object from inside another function, such that those properties are not confined to the scope of the function.
Comment: @DhruvChadha it is not confined to scope of the function, it is set to the same object only.
Comment: Then why am i getting #undefined (please take a look at the edited code) ?
Comment: @DhruvChadha the output will depend on which event is getting fired first. Can you try doing the opposite way to test your theory?


Flex Google Chrome cache issue

Question: I have one issue with my web project we use to release a new swf, the older version gets cached in Chrome and you have to clear your cache to see it. The same does not happen in Firefox and IE.
Environment Used: - Web Application (Flex), Browser tested on IE, Firefox and Google Chrome.
Is there any programmatic solution which can help to solve this problem by using JavaScript, HTML or through Flex?
Solution tried (Does not work): -
I have the following headers:
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
meta http-equiv="cache-control" content="no-store, no-cache, must-revalidate" />
meta http-equiv="Pragma" content="no-store, no-cache" />
meta http-equiv="Expires" content="0, -1" />
Answer: Use a naming convention for your swf that includes the version and build number.  The file name difference will address caching as well as being a best practice for numerous reasons.
It's hard to argue that it's better to just guess which version of the code base "myApp.swf" is versus "myApp.2.1.0015.swf" and knowing immediately.
Here is a good version nomenclature.
http://apr.apache.org/versioning.html
I'm always confused why people are so adverse to a rename operation after compiling.  Make it part of your deployment routine.  Updating a little HTML to point the the appropriate build is not that time consuming.
I promise users won't care if you're builds are actually appropriately named, in fact, I doubt they'll notice other than not having any more caching issues.
If you're re-distributing you're app and patches so much and so often that it is too much hassle for 2 minutes of html to point to the new build, you're doing it wrong.
Comment: Not to mention that if you're using ANT to compile, you can script the name change, versioning, etc., and make it 100% automatic.

Flex Google Chrome cache issue


can I compare failure rates of two appliances in case I do not have an equal number of each?

Question: I am a student working on an original article about oral appliances that are place after the extraction of primary teeth in children. there are two variants of these appliances, fixed and removable.
I collected the data retrospectively (from 2019-2021), so I have no control of how many was placed and ended up with 345 fixed and 118 removables. I am to assess and compare the failure and survival rates of both groups. I cannot tell if it is a problem that I do not have an equal number of both appliances, if I can carry out a Kaplan-Meier survival rate analysis? and what would you recommend to do in this case?
If anyone could guide me or give me useful material to read, I would be very grateful.
Answer: There is no need to have equal numbers in both groups. Real-world survival data almost never ends up that way. Even in randomized trials that are designed to have equal numbers in each of two treatment groups, problems can lead to different numbers being analyzed between the groups.
If you just want to compare the two types of appliances without accounting for other variables, then Kaplan-Meier analysis is a good choice. If you want to account for other variables that might be associated with failure rates, then an extension to a survival regression model like Cox proportional hazards analysis would be called for.
The vignette provided by the R survival package is a pretty good place to start, illustrating concepts with the freely available software of the package. This page has some suggestions for other references on survival analysis, and there are nearly 3000 pages on this site with the survival tag.
Comment: Hey, thank you so much for answering, I really appreciate it, I will take a look at them!


Is there a general formula for the ratio limit of a(n) = a(n-1) + a(n-m).?

Question: I am exploring the properties of a generalization of Fibonacci numbers and have been encountered an issue.
Specifically I am trying to find the limit of the ratio of the the sequence:
A(n) = A(n-1) + A(n-m)
A(n) = n+1 for 0 <= k < m

when m = 2 this is the Fibonacci sequence.
It's clear that the solution is the real root of the polynomial:
x^m - x^(m-1) - 1 = 0
For n=1 the ratio is 2, n=2 is the golden ratio and n=3 is the supergolden ratio. But beyond that I haven't made much progress. I have written a script to generate the sequences and approximate the ratio which has given the following for the for 1 <= m <= 10:
1: 2.0: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288]
2: 1.618033988749895: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946]
3: 1.465571231876768: [1, 2, 3, 4, 6, 9, 13, 19, 28, 41, 60, 88, 129, 189, 277, 406, 595, 872, 1278, 1873]
4: 1.3802775690976141: [1, 2, 3, 4, 5, 7, 10, 14, 19, 26, 36, 50, 69, 95, 131, 181, 250, 345, 476, 657]
5: 1.324717957244746: [1, 2, 3, 4, 5, 6, 8, 11, 15, 20, 26, 34, 45, 60, 80, 106, 140, 185, 245, 325]
6: 1.2851990332453493: [1, 2, 3, 4, 5, 6, 7, 9, 12, 16, 21, 27, 34, 43, 55, 71, 92, 119, 153, 196]
7: 1.2554228710768465: [1, 2, 3, 4, 5, 6, 7, 8, 10, 13, 17, 22, 28, 35, 43, 53, 66, 83, 105, 133]
8: 1.2320546314285723: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 14, 18, 23, 29, 36, 44, 53, 64, 78, 96]
9: 1.21314972305964: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 19, 24, 30, 37, 45, 54, 64, 76]

Is there a known solution for this? Or a proof there isn't one?
Thank you
Comment: What do you regard as a *solution*? You have a recurrence and a generating function is not difficult. The ratio limit is precisely the real root of $x^n-x^{m-1}-1=0$ precisely as you have stated
Comment: You're right. I should've been more precise. The generating function is `f(x) = 1/(1-x-x^m)`. Would it be possible to represent the roots using continued fractions?
Answer: The sequence that you are looking at is similar to the Fibonacci-Narayana sequence, which is given by $f_n=f_{n-1}+f_{n-1-m}, m\ge 1$. The generating function is given by
$$
\frac{1}{1-x-x^{n+1}}
$$
and the limiting ratio is given by
$$\lim_{n\to\infty}\frac{f_{n+1}}{f_{n}}=\chi\\
\chi-1=\chi^{-n}
$$
This sequence can be found in OEIS A000930 and related. $n=1, 2, 4$ are the golden ratio, supergolden ratio, and the plastic number, respectively.
Additional properties of this sequence are
$$
\sum_{n=0}^{\infty}\frac{1}{\chi^n}=\chi^{n+1}\\
S_n=\sum_{j=1}^{n}f_j \quad \text{(cumulative sum)}\\
\lim_{n\to\infty}\frac{S_{n}}{S_{n+1}}=\chi
$$
You might also be interested in the Fibonacci-Padovan series, $f_n=f_{n-m+1}+f_{n-m}$ with a limiting value given by $X+1=X^m$.
Answer: I am not sure what you want. You have essentially specified the answer to be a root of a certain polynomial equation.
If you want to express the solution in terms of radicals (i.e. $n$th roots) like $\phi = \frac{1+\sqrt5}2$ then I am afraid this is impossible, and the reason has to do with Galois theory, so you can ignore the following if you are unfamiliar with Galois theory.
But if you are, then e.g. the case where $m=7$ we have the polynomial $x^7 - x^6 - 1$ whose Galois group is $S_7$ (computed with PARI/GP) which is not solvable, so its roots cannot be expressed using radicals.
Comment: I am familiar with Galois theory and due to the fact this polynomial has a degree larger than 5, a general solution is not possible. I am looking for other solutions.


How to prove that these sequences converge / diverge

Question: 1)$$\lim_{n\to \infty}10 - \sqrt{n} = -\infty $$
I know that I have to find the function $N(M)$ such that $$10 - \sqrt{n} > M$$ but I'm unsure of what function to compare $$10 - \sqrt{n}  $$ to.
2)$$\lim_{n\to \infty} n - 2\sqrt{n}= \infty $$
I know this is somewhat similar to problem 1) except with $-M$.
3)$$\lim_{n\to \infty} \frac{5n^2 +2n}{n^2 - 3} = 5$$
I know that you have to set
$$\lvert \frac{5n^2 +2n}{n^2 - 3} - 5 \rvert < M $$
and find a function for $N(M)$.
For my function $N(M)$ i got $$\max \{2, 3m + 15, 3+\frac{17} m \}$$ but I'm unsure.
Please help!
Comment: do you know the $\epsilon$-N definition of a limit for a sequence?
Comment: In the first line, in the limit definition, I presume you mean $n$ instead of $x$ ?
Answer: We have for any $M>0$
$$\left|10-\sqrt{n}\right|>M$$
whenever $n>N(M)=\max\left(100,(M+10)^2\right)$.
Comment: @RyanT.Donnelly For any $M>0$, if we take initially $N\ge 100$, then for $n>N$, $|10-\sqrt{n}|=\sqrt{n}-10>M\implies n>(M+10)^2$.  Therefore, whenever, $n>\max(100,(M+10)^2)$, we have $|10-\sqrt{n})|>M\implies 10-\sqrt{n}<-M$.
Comment: why wouldn't N(M) be $$(10-m)^2$$


Notification for Disk-Space Shortage Issue in Server

Question: I have a ubuntu server, and facing frequent space issue, i.e. logs are eating up lot of disk space. So, I want a check to be applied, so that whenever there is less than 5 GB free disk space, I should get an e-mail notification, so that I can delete the logs. How can I configure this. Do I need any other application?
Answer: You can use Nagios for monitoring and sending email. But, before setting up monitoring, I would start by setting up logrotate to periodically rotate log files.
The appropriate system depends on where you host your server. For example, if it is hosted on AWS, you can configure Amazon's built-in CloudWatch to monitor its health rather than deploy a new monitoring solution.
Comment: +1 for not only answering the nominal question, but also employing logrotate to avoid the need to manually intervene in the first place.
Comment: What Monty Harder said.
Answer: On my Ubuntu server, I have the following script in /etc/cron.daily that alerts me by email whenever /dev/sdc (my /srv partition) has less than 200MB of free space.
ALERT=200
UNIT=M
PARTITION=/dev/sdc

df -B$UNIT | grep "^$PARTITION" |
while read partition size used free perc mnt ;
do
        free_space=$(echo $free | tr -d $UNIT )
        if [ $free_space -le $ALERT ]; then
                echo "Partition $partition ($mnt) running out of space ($free) on $(hostname) as on $(date)" |
                mail -s "Alert: $mnt almost out of disk space on $(hostname) - $free" root
        fi
done

It was initially taken and adapted from this blog post on nixCraft. Save this into a file in /etc/cron.hourly as root, modify the first 3 lines to suit your server and needs, and make the file executable. If you want to have it executed more often, save it as a script and create a regular cron job.
Note that you will need something providing the mail command, typically from the packages qmail-run or courier-mta.
Answer: You can adopt two different strategies:

use a custom script which will run every minute/hour/day to detect and notify you about the space shortage
install and deploy a true monitoring solution as Zabbix or the likes.

For a single server, solution n.1 is surely the faster path. However, for multiple servers and/or to check multiple data point (eg: ram usage, cpu load, etc) the second one is preferable, by far.
Answer: Can some one help me out with my below concern?
Issue : need to setup one automatic job to perform disc space clear on Linux machine but the job which we create should be outside the Linux machine , so once we trigger that job the space in that Linux machine needs to be get cleared
Any suggestions?
Comment: If you have a new question, please ask it by clicking the [Ask Question](https://serverfault.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/504921)
Comment: This is another question, not an answer.


Can I put a list in a struct?

Question: I am trying to use a list as part of a struct due to the fact our products come in several colors.  Is this some thing I can do or should i just use an array?  Either way i have not found any examples on the web.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<sstream>
#include<cctype>
#include<list>

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////
//  Constances
////////////////////////////////////////////////////////////////////////////////////////

#define N_PRODUCT 3

struct Brand_t {
int Model_Num;
string Product_Name;
list<string> Colors;
} brands [N_COLOR];

////////////////////////////////////////////////////////////////////////////////////////
//  Functions
////////////////////////////////////////////////////////////////////////////////////////

int main()
{
string mystr;
int n;

for (n=0; n < N_PRODUCT; n++)
{
    cout << "Enter Model Number: ";
    std::getline (cin,mystr);
    stringstream(mystr) >> brands[n].model_Num,4;
    cout << "Enter Product Name: ";
    getline(cin,classrooms[n].Product_Name);
    list<string>::iterator it;
    Students.push_back ("Red");
    Students.push_back ("Yellow");
    Students.push_back ("Blue");
}

return 0;
}

Comment: list vs. array is a very weird tradeoff. vector vs. array, sure, but lists have entirely different performance characteristics; if you really need a list, and can't use std::list for some reason (which is very rare), you'd probably substitute a C-style linked list, not a C-style array.
Comment: In c++ a struct is a class, with an implied public: at the top. But for code readability only use if for data, with all members public. I some times add a constructor and maybe a destructor, but no other methods. But if you are explicit about access, then the language does not care.
Comment: I think I figured out what may be wrong where it says Students its suppose to be Colors.  and when i put this together I took from diffrent examples, but I think the refrence should be brands[n].Colors.push_back ("Red");
Answer: Yes, this can be done. Thanks to the RAII, the list object will be automatically initialized and freed based on the lifetime of your struct. Take note that even thought this is not the case in other programming languages such as Object Pascal, the struct and class are effectively the same thing in C++, the only difference being default visibility of member methods and variables, as other answers have noted.
You can not put non-PODS objects into unions though.
I suggest you use a std::vector or a std::array instead of a C-style array. A std::vector would probably be most useful if your array is supposed to be of dynamic size. If you use plain new or even malloc(), then your objects will NOT be automatically freed (not even initialized with malloc())
Comment: Note: You *can* (in C++11) put non-PODs into unions, even if I would not recommend doing it (you have to manually control the lifetime of the object, call the constructor and destructor as needed to change the active member in the union... painful.
Comment: Well, an array would be cleaned up automatically as well unless you allocated it dynamically.
Answer: Yes, there is no reason not to.  The only differences between a struct and a class in C++ are
A) struct members are public by default, and
B) struct inheritance is public by default (i.e., struct A : B is equivalent to class A : public B where B is a class.)
Comment: +1 for pointing out the second difference, I wasn't aware of that one.
Answer: Using a list, or any object, inside of a struct is perfectly acceptable as long as the object has or supports a default constructor.
The default constructor is required because when a struct variable is first declared, it is also initialized. Any object inside of it will also be initialized by calling the default constructor.
Comment: Also known as RAII. Good answer though, and welcome to StackOverflow.
Comment: If the struct is given a constructor with an initializer list, it can contain objects that are not default cosntructable.
Comment: This is incorrect on two accounts: `struct` is equivalent to `class` but has a default access specifier of `public`, so anything that can be done in a `class` can be done in a `struct`. Even considering only aggregates (i.e. no constructors), you can store objects that don't have a default constructor. This will force all uses of your type to use *aggregate-initialization*, but it can be done.
Comment: @Drise: I am not sure what you mean by that comment, where is the RAII concept mentioned in this answer? RAII is quite unrelated to the answer.
Comment: @DavidRodríguez-dribeas Unless I'm horribly mistaken, "...struct variable is first declared, it is also initialized." Do correct me if I'm wrong.
Comment: @Drise: That is not what RAII is about, RAII is about resource management, where the acquisition of the resource is to be considered initialization of the object (Resource Acquisition Is Initialization) and more importantly, resources are released in the destructor.
Answer: There's nothing wrong with having an instance of a class as a member of a struct in C++, UNLESS you're relying on C++ treating instance of the struct as POD (plain old data) objects. (Like with bit-wise copying, etc.
Comment: and you should _never assume_ an object is a POD.  Always check at compile-time.

Can I put a list in a struct?


Degree Major Choice

Question: I have about 10 years of experience in IT and a handful of certifications and am planning on going to university and getting a bachelor's degree. My experience has been progressive up to this point but a lot of jobs I'd like to be moving into (be they technical or management) require a degree and I'd also really like to move into management at some point.
I am trying to determine what the best major for me to take is - a computer science degree (be it computer science, computer information systems, or whatever) or a business degree (like a business administration degree with a management information systems concentration or something like that). I'm not sure that either would be especially relevant to my job performance on the technical side of IT so I'm kind of interested in the MIS business major but would hate to have it reflect unfavorably on a job application because it's a 'lighter' degree than CS.
I'd love to hear anyone's viewpoints on this subject and their experiences.
Thanks!
Comment: @Chris: That's horrible advice.
Answer: If you're sticking with programming or infrastructure administration, you pretty much can't go wrong with CS. Depending on the CIS program, it can be just as applicable, but it's learning toward accomplishing management goals.
MIS degrees haven't had the development and honing that CS programs have; so I advise them to people who want to go into Management much more than a technical professional.
Bachelors in Business Admin are a dime a dozen these days; MBA are still highly regarded however, so if you're going the BSBA route, I'd plan on continuing to MBA.
Just my 2 cents of course. Find a good school and their counseling program will know all this too.

Degree Major Choice


Why can't our Exchange mail server find DNS records for a single (external) domain?

Question: We have a lot of outgoing mail every day. This all works fairly flawlessly.
unfortunately, there is 1 domain we can't send to. The error given in Queue viewer <code>"451 4.4.0 DNS query failed. The error was: DNS query failed with error InfoNoRecords"</code>.
When I NSlookup the domain, our Mail server finds nothing. When I NSlookup from a domain computer or from a website like CentralOps, their domain and records seem to be working like normal.
Does anyone know why no DNS records for said domain can be found on our Mail server?
Comment: do you use the same DNS server on the exchange server and on the domain computers?
Comment: Hi mzhaase, sorry for the late response. Yes we do!
Answer: I would say that the remote domain has an issue.
You haven't said what records you can see, so you need to do a specific lookup for the MX records - just seeing domain records for a domain is not enough. I own about 20 domains, but you do an MX lookup on most of them you get nothing.
Every case I have seen with this error it has been a problem with the remote domain. Never Exchange. If it was Exchange then it would be more widespread.
Comment: This is the acid test: Your email server can't send email to _anyone_? Probably your server. Your email server can send email to anyone _except_ that one server over there in the corner? Then either your email server and everyone else's happens to be misconfigured in the exact same way and the guy running the email server over there in the corner is the only person in the world doing it right, or they've misconfigured their server. Which seems most likely?


Maximum Cookie Size of current browsers (Year 2018)

Question: From the django docs:

Both RFC 2109 and RFC 6265 state that user agents should support cookies of at least 4096 bytes. For many browsers this is also the maximum size.

Source: https://docs.djangoproject.com/en/2.1/ref/request-response/
Is this still valid today?
What is the maximum cookie size of current browsers?
Comment: @HansPassant thank you very much for the canonical list of browser cookie limits.
Answer: The cookie spec definition in RFC6265 (April 2011) is the current RFC (No new draft and no new RFC) and is supported by all major browsers (IE,Chrome,Opera,Firefox) today.

At least 4096 bytes for the entire cookie (as measured by the sum of all of the cookie names, values, and attributes).

At least 50 cookies per domain, provided they don't go over the above limit.

At least 3000 cookies total.

So all modern browsers support AT LEAST this. Any other limit values are a gamble
See 6.1. Limits in https://datatracker.ietf.org/doc/rfc6265/ for more details
Comment: I note this does **not** mean that browsers support `50 cookies * 4096 bytes == 204,800 bytes == 204KiB per domain`. I find that Safari and Chrome start to reject cookies if the total data for a domain exceeds something between 5-8KB.
Comment: After some more testing, it appears you're right. If providing more than one Set-Cookie headers then the limit of 4096 bytes is applied on the concatenated value of all Set-Cookie headers. You can still create more than one cookie provided the creation is done in only one header. With multiple Set-Cookie headers it seems only the last one works. The only way to reach the 204KB per domain limit is to create the cookies using javascript. Another strange point is cookies created using the Set-Cookie headers aren't inserted in the Chrome's sqllite database but still sent in the next request
Comment: Hi @Dai, i don't know for Safari but the size limit in Chrome is indeed 204,800 bytes per domain. From my tests the size is calculated summing the lengths of hostname + cookiepath + cookiename + unencrypted cookie value. Test done on Chrome 71.0.3578.98. How did you find a limit of 5-8Kb?
Comment: I get warnings in my Chrome developer console when the total size of all `Set-Cookie` headers in a response exceeds 4096 characters. So I guess, it's true that Chrome can store over 4096 characters, but they can't all be set in a single response?
Comment: @Mumrah81 given how upvoted this answer is, I chose to update the wording, which is dangerous, to reflect what Dai pointed out. This is a better question+answer: https://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key
Answer: You can test it out by setting and reading back a cookie size from JavaScript in an iteration if you are interested in modern browsers only.
That is what I was doing in the past. And this is exactly what this site is about, it also includes the limits by browsers.
But keep in mind that the matching cookies will travel with every HTTP requests so they could dramatically affect the perceived response time.
Answer: here is the detail which you can refer - http://browsercookielimits.iain.guru/
Typically, the following are allowed:
300 cookies in total
4096 bytes per cookie
20 cookies per domain
81920 bytes per domain*

Given 20 cookies of max size 4096 = 81920 bytes.


SVN "Can't open file '.../db/txn-current-lock': Permission denied" on import

Question: It has been asked a lot of times here, and none of the answers have worked so far for me.
I'm getting the folowing error on apache error_log
could not begin a transaction  [500, #13]

Can't open file '/var/www/svn/repo/db/txn-current-lock': Permission denied  [500, #13]

when trying to do
svn import -m "Initial" /mnt/logs/ http://localhost/svn/repo/

Info on that file:
ls -l /var/www/repo/db/txn-current-lock

-rwxrwxrwx. 1 apache apache 0 abr 20 12:37 /var/www/svn/repo/db/txn-current-lock

I'm running on CentOS 7.2 and I can access http://localhost/svn/repo tho there's only this there:

repo - Revision 0: /
Answer: After fighting with permissions, I decided to just look again at the "howto" and solved the issue. I basically forgot to type:
chcon -R -t httpd_sys_content_t /var/www/svn/repo
chcon -R -t httpd_sys_rw_content_t /var/www/svn/repo

Hope it helps someone else.
Comment: Befofre that, you shall do `semanage fcontext -a --type httpd_sys_rw_content_t '/path/to/your/svn/repo/files(/.*)?'`


What is the cost of try catch blocks?

Question: How much better is:
 if (condition) {
  try {
   //something
  } catch(SomeEx ex) {}
 }

instead of this:
 try {
   if (condition) {
     //something
   }
 } catch(SomeEx ex) {}

What actually JVM do when I enter try block ?
EDIT:
I don't want to know that in second example always go in to try... Please answer the question.
Comment: It depends on your usage and actual scenario.
Comment: @Nandkumar Tekale: Not it's not.. It is always the same. Since we have the same JAVA.
Comment: Possible duplicate of [Is it expensive to use try-catch blocks even if an exception is never thrown?](http://stackoverflow.com/questions/16451777/is-it-expensive-to-use-try-catch-blocks-even-if-an-exception-is-never-thrown)
Answer: Execution wise at run time, as long as there is no exception, try does not cost you anything. It only costs run time as soon as an exception occurs. And in that situation it is much slower that an if evaluation.
In the JVM spec, you see that there is no extra byte code generated on the execution path:
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12
Comment: T0   aload_0  // Begin try block
Comment: @Smolda - I do not understand your comment. Do you want to say that the `aload_0` in the sample code of the spec is for the try? That is not true. It is the loading of the `this` reference for the method call in the next line. And that is needed no matter if you use try or not. The comment in the sample code is a bit misleading.
Comment: This answer doesn't really explain anything and is unlikely to be correct. As exceptions are mostly a feature of the runtime (the JVM) and not of bytecodes, bytecodes are irrelevant. If you want to evaluate real cost, you would have to look at what the JVM does when it enters a try-block (or what assembler it generates for code that's JIT compiled). In any case it is certainly not free.
Comment: Seems I was somewhat wrong about the cost. It could be free (i.e. equally expensive in the OP's example) but not for the reasons stated here. See http://stackoverflow.com/a/16451908/7647
Answer: try {if (condition) {...}} catch(SomeEx ex) {}

Here you handled the exception if it is arised condition of if also if arised inside if-block.
if (condition) {try {...} catch(SomeEx ex) {}}

Here you handle exception if is arised only inside the if-block. If something goes wrong in if condition then it will not be handled.
So it is depends upon the actual senario.
Answer: From the perfomance point of view it should be the same. Throwing of the exception is a costly  operation (for starters, the stacktrace must be created and populated). The mere existence of the try block has no (or negligible) performance penalty.
See Should java try blocks be scoped as tightly as possible.

What actually JVM do when I enter try block ?

From JLS 14.20.1. Execution of try-catch:

A try statement without a finally block is executed by first executing the try block. Then there is a choice:

If execution of the try block completes normally, then no further action is taken and the try statement completes normally.

If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:

If that block completes normally, then the try statement completes normally.

If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.

If execution of the try block completes abruptly for any other reason, then the try statement completes abruptly for the same reason.

EDIT:
For a complete Exception description see the JVM 2.10 link in The New Idiot's answer.
Answer: if (condition) {
  try {
   //something
  } catch(SomeEx ex) {}
 }

is better to use since it executes the try block if the condition is ok.JVM compiles the try block and validated the catch block or a finally block. I think advantage is not in the compile time but in the run time. Compile time I think no advantage at all
Comment: That is what I said.. can you please answer the question ?
Comment: JVM compiles the try block and validated the catch block or a finally block. I think advantage is not in the compile time but in the run time. Compile time I think no  advantage at all
Answer: Exceptions should be exceptional case , not every time the code runs. So better to check for the condition before trying !
if (condition) {
  try {
    //something
  } catch(SomeEx ex) {}
}

Make sure , if (condition) itself doesn't throws an Exception.
It depends on your usage and functionality . For example this would be better :
if (someObject!=null) {
  try {
     someObject.getSomething(); // getSomething() potentially throws some Exception
  } catch(SomeEx ex) {}
}

What actually JVM do when I enter try block ?

Read JVM spec 2.10.
Comment: @EJP (1)I disagree with you , it is better to avoid a certain NPE than to ask the try to throw it later . (2) it is not testing the same condition twice , please read the comment in the code (3) I would better have my catch block to catch potential checked Exceptions rather than runtime exceptions !
Comment: This is nonsense. If the condition is unlikely the overhead of testing as well as catching is unwarranted, and the suggestion also introduces (a) a timing window problem (b) the problem of testing exactly the same condition twice and (c) the issue of having to write the same error handling code twice. -1
Answer: If you see oracle docs
>try {
    code
}
catch and finally blocks . . .

The segment in the example labeled code contains one or more legal lines of code that could throw an exception.

So,If you feel doubt on your If condition that it will throw an exception  put it inside.Otherwise put outside.

What is the cost of try catch blocks?


Probability distribution estimation

Question: The joint frequency distribution of two discrete random variables $X$ and $Y$ is given in the table below:

$y$

1
2
3
4

1
0.10
0.05
0.02
0.02

$x$
2
0.05
0.20
0.05
0.02

3
0.02
0.05
0.20
0.04

4
0.02
0.02
0.04
0.10

Using $\text{Var}(X)=\sum [x_i−\mathbb E(X)]^2 \cdot \mathbb P(X=x_i)$, we can define the conditional variance of $X$ for a given value of $Y$: $\text{Var}(X|Y=y)$. For example: $\text{Var}(X|Y=1)=\sum[x_i−\mathbb E(X|Y=1)]^2⋅\mathbb P(X=x_i|Y=1)$. Find $\text{Var}(X|Y=1)$.
In order to solve this I estimated this tables below
|       | y     |   |   |   |   |   |
|-  |:-:    |-  |-  |-  |-  |-  |
| x     |       | 1     | 2     | 3     | 4     |   |
|   | 1     | 0.10  | 0.05  | 0.02  | 0.02  | 0.19  |
|   | 2     | 0.05  | 0.20  | 0.05  | 0.02  | 0.32  |
|   | 3     | 0.02  | 0.05  | 0.20  | 0.04  | 0.31  |
|   | 4     | 0.02  | 0.02  | 0.04  | 0.10  | 0.18  |
|   |   | 0.19  | 0.32  | 0.31  | 0.18  |   |

1
2
3
4

X | Y = 1
0.53
0.26
0.11
0.11

X | Y = 2
0.16
0.63
0.16
0.06

X | Y = 3
0.06
0.16
0.65
0.13

X | Y = 4
0.11
0.11
0.22
0.56

W   = E(X | Y = y)

1.79
2.13
2.84
3.22

So next should be estimation of of E(W). In last table I estimated half of this but I can't find how to estimate other half with values 0.19, 0.32, 0.31, 0.18 So can anybody help me how to find this ?
Answer: Are you trying to calculate $\mathrm{Var}(X|Y=1)$? To calculate that, you can use the table (with rows $X | Y = y$ for $y = 1, 2, 3, 4$) you have computed. Since we are interested in the distribution of $X$ conditional on $Y = 1$, you would be interested in the first row. Indeed, you can then simply imagine those four entries as defining your desired distribution, and you can then use the usual formulas to calculate the expected value (e.g. $\mathbb{E}[X|Y=1] = 0.53(1) + 0.26(2) + 0.11(3) + 0.11(4) = 1.82$), and the variance (i.e. using the first formula you wrote).

Probability distribution estimation


how can I duplicates data based on a value in a dataset in scala?

Question: I have a dataset as
col col2 MaxCount
adf def  5
Need output as :
col1 col2 EntryNumber
adf def 1
adf def 2
adf def 3
adf def 4
adf def 5
Is it possible with hive Context . plz help me
Comment: Please tell us what you have tried and where you are stuck.
Comment: I dnt know how  this can be done using HiveConext or SqlContext.
Comment: Is any other way to get the same . please forward your  tips
Comment: Stackoverflow is not a code-writing service. Tell us what you have tried and where you are stuck, and more about your problem. Where did the dataset come from? How was it constructed?
Answer: <code>val input = sc.textFile("filePath")
val result = input.mapPartitions(x => {
  x.flatMap(y => {
    val line = y.split(delimiter)
    val attribute = line(2)
    (i until attribute.toInt).map(i => {
      y+delimiter+i.toString
    })
  })
})
result.foreach(println)
</code>
Comment: with the help of above code we get the result (without using hiveContext or sqlContext)


Duplicate Content

Question: is there any way, to remove the duplicate content, produced by D7?
An Example:
You can reach a node with two URL's:
http://mysite.com/node/3

Or:
http://mysite.com/nodename

The same problem with taxonomy terms
From SEO view, this is very negative...
Is there any way, to fix that?
Answer: It's already handled for you, if you look at the source you'll see the <link rel="canonical" tag which lets search engines know which page to consider the 'original' content.
This is Google (and others) preferred method to handle this type of situation; there's more information on this post.
Answer: Redirect from one URL to the other: use the Global Redirect module. Here is a quote about it (from the module's project page):

... a simple module which:

Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect_admin module. In Drupal 6, the settings page is bundled into the module.

Duplicate Content


Verificar se um option já existe pra não repeti-lo

Question: Olá!
Tenho um problema talvez simples, mas não tô conseguindo pensar em qualquer maneira de resolvê-lo.
Tenho um banco de dados aonde tenho uma tabela de produtos nele. Nessa tabela, tem a coluna cor. Então, estou criando um filtro na hora de pesquisar os produtos no site e como não sei exatamente quais cores estão em estoque, fiz esse while para imprimir as options:
$sql =  "SELECT `cor` FROM `produtos`";
<select id='iCor' name='nCor'>
       <option value=''>Todos</option>";
       while($linha = $result->fetch_assoc()){
            $cor = $linha['cor'];
            echo"<option value='$cor'>$cor</option>";
       }`

Mas esse com essa forma se eu tenho registrado as seguintes cores: amarelo, verde, vermelho, amarelo, vai aparecer 2 options contendo a opção amarelo.
O que eu quero é que de alguma forma, seja verificado se já tem aquele option no select. Se tiver, não faz nada. Se não tiver, coloca a cor como novo option
Answer: Tenta usar essa consulta:
$sql =  "SELECT DISTINCT `cor` FROM `produtos`";

Comment: Não sei porque recebeu um -1, funcionou mesmo!


Exception in multi-Task WCF channel usage (ems)

Question: I receive an exception of type

Exception receiving EMS message: The service did not respond.
  When calling the code below from more than one task.

<code>Task.Factory.StartNew(() =>
{
        var service = CreateChannel();
        try
        {
              return service.GetStuff(string blah);
        }
        finally
        {
               var channel = ((IClientChannel)service);
               try
               {
                    channel.Close();
               }
               catch
               {
                    channel.Abort();
               }
         }
 });
private IService CreateChannel()
{
    lock (_channelFactory)
    {
        return _channelFactory.CreateChannel();
    }
}
</code>
If i remove the Channel.Close() there is no exception.
Any ideas?
Answer: Self Answer
Updating my tibco.ems.wcf assembly fixed this.


Are most webserver benchmarks useless?

Question: There's a plethora of benchmarks out there, comparing Apache, nginx, lighttpd, LiteSpeed/ OpenLiteSpeed, Cherokee etc.
Unfortunately, it seems that most of the benchmarks are of the "small static file" type, which is quite useless...who uses a webserver to serve small static files?
How come nobody runs benchmarks for DEFAULT installs of php applications like:

WordPress
Drupal
phpBB
Menalto Gallery
Magento
OpenCart
etc

This would be a much better indication of what works best under real-usage type conditions, and would give folks a much better sense of the most appropriate server for their needs.
The above popular php applications would probably cover the needs of a huge chunk of webserver users.
Sure, in this kind of benchmark, the performance of MySQL, PHP, etc would come into play and we won't get RAW performance figures for the webserver. But who really cares for RAW numbers anyway? Folks are really only concerned about comparative performance, and that's why they check out benchmarks.
If we start doing this kind of benchmarks, we might finally arrive at the conclusion that server comparisons are moot as there aren't significant performance differences between competing products and that there are other items in the infrastructure/setup that need much more optimization attention.
I am sure that folks who run benchmarks are smart and know all of the above...so how come we still continue getting worthless "small static file" benchmarks?
Answer: The most important benchmarks are the ones you take against your application before making some changes, then re-running them, on your own hardware in your own server environment.
This won't help if you're trying to choose whether to use framework X versus framework Y for your application or configuration, unless you are in a position to test your servers with multiple configurations before going into production.
But you're right in that when you look at published benchmarks, there's many factors that can affect the results. Are they worthless? Maybe not completely; if a particular framework or server is performing well in multiple tests, it'll probably perform well for you. If it's slow, it'll probably be relatively slow.
You may still have other factors to consider. What good is a fast framework if you're not experienced with it and you have to roll out a product on a deadline? Will the people maintaining it have experience on that platform, or be able to learn it quickly? Maybe you have in-house experience with a particular language or server that would reduce maintenance overhead or adding modules or features. Maybe you need to have a platform that is actively maintained so you can be confident bugs will be fixed in a timely manner, or when you need help there is an active community to offer advice. The fastest server isn't much help if you can't get it configured and tuned in the first place, after all.
Comment: I agree with the heart of your answer, but I'd say that the most important benchmarks are the performance profile of your app in Production (a continuous and constantly watched set of metrics.)
Answer: I think you just answered your own question. Static file benchmarks are easy to set up and easy to measure. Once you add an application stack, you're going from one variable (the web server) to possibly dozens.  "What about the PHP configuration? Maybe the MySQL server is starved for RAM? Is the disk configuration correct?" and so forth.
Static benchmarks test one thing: How fast can a given web server service an HTTP request? In general, that's all you want a web server to do. Once you're talking about application servers, the game changes completely.
And to be fair, there are benchmarks for web frameworks and some application servers: http://www.techempower.com/benchmarks/
Comment: Even "static file" benchmarks are measuring more than one factor (the web server, the OS, the filesystem, and the disk subsystem are all involved). The performance of your Linux/EXT3/nginx system with old parallel-ATA disks in a software md RAID will be way worse than AIX/JFS2/nginx with 15K SAS drives in a hardware RAID-1. (Benchmarks are hard, let's go shopping!)
Comment: @voretaq7 Understood. There's lots of things involved. So if I have nginx on one set of infrastructure the results may be different compared to nginx on another set of infrastructure. But if the primary purpose of benchmarking is comparison, then this is immaterial, as even though other things matter, it really does amount to an "all else being equal" situation. Or am I missing something major here?
Comment: @OC2PS the problem is making "all else" equal -- published comparison benchmarks (like Apache vs nginx) are frequently done on disparate systems, so you have to account for that when comparing them. That's why the most useful benchmarks are the ones you do yourself

Are most webserver benchmarks useless?


prove that $\lim_{x \rightarrow 0^+}\frac{1}{x} \int_0^x\sin(\frac{\pi}{t})dt =0$

Question: I want to show that
\begin{equation*}
\lim_{x \rightarrow 0^+}\frac{1}{x} \int_0^x\sin(\frac{\pi}{t})dt =0.
\end{equation*}
Any idea?
Answer: We may just exploit:
$$\int_{\frac{1}{n+1}}^{\frac{1}{n}}\sin\left(\frac{\pi}{t}\right)\,dt=\int_{n}^{n+1}\frac{\sin(\pi u)}{u^2}\,du=\frac{2(-1)^n}{\pi n^2}+O\left(\frac{1}{n^3}\right) $$
that follows from integration by parts.
Comment: @grdgfgr Because $\sin(\pi/x)$ does not converge as $x \to 0^+$. In fact, $\int_0^x \sin(\pi/t) dt$ is continuous but not differentiable at $x$. The point of the problem is that even though it doesn't converge, "morally" it oscillates "evenly" between $-1$ and $1$, in such a way that "everything cancels out" on a small interval $[0,\delta]$.
Comment: Why does Lhopital fail?
Comment: If decide that oscillation cancels the solution, lhopital also works.
Comment: @grdgfgr No, it doesn't. You need the derivative of $\int_0^x \sin(\pi/t) dt$ to exist at zero and it just doesn't.
Comment: Why can't it be $\sin (\pi /x)$
Comment: @grdgfgr: l'Hopital's theorem has some hypothesis that are not fulfilled here, hence we have to tear down this problem by more low-tech ways, i.e. estimations on small sub-intervals of the integration range.
Comment: I have $$\frac{\int_0^x\sin(\frac{\pi}{t})dt}{x}$$ I take the derivative of num and denum $$\sin(\frac{\pi}{x})$$ If oscillations "cancel", this limit is also 0.
Comment: @grdgfgr: the issue is that $\lim_{x\to 0^+}\sin\frac{\pi}{x}$ does not exist.
Comment: @grdgfgr The oscillations cancel when you add up the values in the integral. They don't cancel until then. (Also, "at $x$" in my first comment should have been "at $0$").
Answer: Observe that
$$\int_0^x\sin\bigg(\frac{\pi}{t}\bigg)dt = \int_0^x {t^2 \over \pi}\bigg({\pi \over t^2}\sin\bigg(\frac{\pi}{t}\bigg)\bigg)dt$$
Integrating the right-hand side by parts gives
$$-{x^2 \over \pi}\cos\bigg({\pi \over x}\bigg) + \int_0^x {2t \over \pi} \cos\bigg({\pi \over t}\bigg)\,dt$$
So
$${\int_0^x\sin(\frac{\pi}{t})dt \over x} = -{x \over \pi}\cos\bigg({\pi \over x}\bigg) + {1 \over x}\int_0^x {2t \over \pi} \cos\bigg({\pi \over t}\bigg)\,dt$$
As $x$ goes to zero the first term goes to zero.
Since $|t \cos\big({\pi \over t}\big)| \leq |x|$, the integral in the second term is of absolute value at most ${2 \over \pi}x^2$, so the second term has absolute value at most ${2 \over \pi}|x|$. Hence as $x \rightarrow 0$ the second term goes to zero as well and we see that the overall limit is zero.
Answer: The change of variables $t= 1/s$ gives
$$(1)\,\,\,\,\frac{1}{x}\int_{1/x}^\infty \frac{\sin \pi s}{s^2}\, ds.$$ Integrate by parts to see (1) equals $$ \frac{1}{x}\left [ x^2 \cos (\pi/x)/\pi - 2\int_{1/x}^\infty \frac{\cos \pi s}{\pi s^3}\,ds\right ]$$
In absolute value, the last integrand is no larger than $1/(\pi s^3),$ which is simple to integrate. It follows that (1) is $O(x)$ as $x \to 0^+.$


Accessing unpublished group content

Question: I am using organic groups and I want the owner/reviewer of the group to be able to access an unpublished group content created by members of the group.
I know I can give "View any unpublished content" rights to a global user role, but this will be to strong (I have different reviewers for different groups and single reviewer should not have access to unpublished content of all the groups).
I want to give that right to the specific role in the group and "Organic groups global permissions" simply does not have that option.
I am familiar with hooks system but I am not sure how to approach the issue.
Any ideas?
Comment: You can add your own hook_permission (http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_permission/7) , where input parameter will be id of group(gid) and user id (uid), then check if user (uid) is group administer (gid) and return true if yes
Comment: Gaydabura thanks for the hint. I have found that there is a coresponding hook in the OG module hook_og_permission. I will still have to write some code but I can use http://api.drupalize.me/api/drupal/function/og_field_access_og_permission/7 as an example so it should be simple enough.
Comment: it is even better. good luck
Answer: Have a look at this example implementation which creates a new OG Permission View unpublished content and uses Node Grants to decide who can view unpublished nodes. You now can configure which OG Role in your groups are allowed to view unpublished nodes.
<code><?php
define('MY_MODULE_REALM_VIEW_UNPUBLISHED', 'my_module_view_unpublished');

/**
 * Implements hook_og_permission().
 */
function my_module_og_permission() {
  // Add OG permission to view unpublished nodes.
  return array(
    'view unpublished' => array(
      'title' => t('View unpublished content'),
      'description' => t("Allow user to see unpublished content within the group."),
      // Determine to which roles the permissions will be enabled by default.
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    ),
  );
}

/**
 * Implements hook_node_grants().
 */
function my_module_node_grants($account, $op) {
  if ($op != 'view') {
    return;
  }

  $grants = array();

  // Handle access to unpublished nodes.
  // Get all OG Group IDs the user is allowed to view unpublished nodes in.
  $entities = og_get_entity_groups();
  foreach ($entities['node'] as $entity_id) {
    if (og_user_access('node', $entity_id, 'view unpublished')) {
      $grants[MY_MODULE_REALM_VIEW_UNPUBLISHED][] = $entity_id;
    }
  }

  return $grants;
}

/**
 * Implements hook_node_access_records().
 */
function my_module_node_access_records($node) {
  // Node is unpublished and belongs to a OG group.
  if (!(empty($node->status) && $groups = og_get_entity_groups('node', $node))) {
    return array();
  }

  foreach ($groups['node'] as $nid) {
    $grants[] = array(
      'realm' => MY_MODULE_REALM_VIEW_UNPUBLISHED,
      'gid' => $nid,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 10,
    );
  }
  return $grants;
}
</code>
Comment: To add this no longer works very well. I have implemented this and found that when the user goes to log into the site, it times out because they are not added to the primary/default group. Once I add them, then they can log in but this isn't ideal as we want them to only be added to their specific group.

Accessing unpublished group content


FreePBX: Basic config?

Question: I've just successfully set up an Asterisk+FreePBX install on an Amazon EC2 instance per this guide: http://voxilla.com/2009/10/15/voxillas-freepbx-in-a-cloud-step-by-step-1457 (I've also assigned it an Elastic IP).
I'd love to test it without buying any VoIP trunks yet. I understand that I can do that by just placing internal calls to two phones connected to the Asterisk server, right?
I'm using a softphone: CounterPath eyeBeam.
I can't seem to find any guide or resource online that will tell me what I need to do on the FreePBX side of things to set it up for just routing internal calls, nor what I need to enter in to CP's eyeBeam client (username, auth. name, password, etc.) in order to get it to connect to Asterisk.
Can somebody give me a quick primer? Or at least point me to an easily-digestible resource that could help me out?
EDIT: I did already find this guide, but it sets up the FreePBX to use outside VoIP trunks, which I don't want to purchase just yet.
Answer: It is enough to just add two SIP extensions, Username, display name, password, apply changes, and in your eyeBeam add username, password and the IP address of your Asterisk as Domain (I don't have it installed, the domain part may be called differently).
Yes, it is that simple.
Comment: Great, that worked! The phones connect, but I have no audio... now what?
Comment: No audio on SIP is a fairly common problem, caused by NAT firewalls. Google "SIP no audio", or try http://www.asteriskguru.com/tutorials/sip_nat_oneway_or_no_audio_asterisk.html

FreePBX: Basic config?


Accelerating hough transform algorithm in dm script using C++

Question: Recently I tried to run Vincent Hou's Hough Transform script in https://www.felmi-zfe.at/dm_script/ for an image (1024*1024). The script take around 4mins on my computer. Then I tried to use the sampleInterface example in Gatan DMSDK to transform the dm script into C++ files and compile it into a DM plugin then tried to run it for the same image again. The time consumption was only reduced by 7s. I am not quite satisfied by this result. Then I looked at the generated code and found that the main part for the hough transform algorithm was still in dm-script. There was no C++ generated for that. Just some interface was generated.
Then I am trying to implement the dm script in C++. But I found it difficult to translate some features of dm-script into C++.
The first one is how to translate imgHT[ HT_Col, y0 + tho_ratio*((iRow-y0)*sint+(iCol-x0)*cost) ] += source into C++ code? I tried this:
for (uint32 iRow = 0; iRow < size; iRow++)
{
    for (uint32 iCol = 0; iCol < size; iCol++)
    {
        //imgHT[HT_Col, y0 + tho_ratio * ((iRow - y0) * sint + (iCol - x0) * cost)] += source;
    }
}

But there is no [] operator defined for Gatan::DM::Image class. So I made a comment to the code above.
So here are my questions:

Any suggestions for how to transform the commented line into a C++ code?
Is there a way in DMSDK to obtain data from Gatan::DM::Image class or transform this class to a 2D array (an array pointer to an array)?
Answer: This is not actually a DM-scripting question, but if you want to compute an image-array in the SDK you have to address the native, underlying number array (which is 1D and of a specific number type.)
Typical code for this is found in the SDK example, specifically in the DMSDK\LibrarySuite\LibrarySuite.cpp in the function void PassRealImagePtr( DM_ImageToken image_token )
One gets an image token passed in from which an image object is initialized. Then one creates a data-locker on the image to get access to a pointer to the native data array. The pointer needs to be cast into the appropriate number type.
Comment: Thanks a lot! It worked and greatly reduced the running time, from original ~260s (dmscript) to ~3s. Before I tried GetPixel and SetPixel function in DMPluginStubs.h, but it will take even longer (~10000s) to finish the computation. Directly operating in the memory using image data-locker is the fastest way!
Comment: Yes, this is to be expected. The compiler will not be able to optimize around DM::... calls in the code. GetPixel() is worse than image-expressions (also in scripts) as it creates and release an image-access data-locker for each call.


Overcoming the problem (found in K-means) of clusters of different diameter

Question: I have a theoretical problem, I think it is easier to show it instead of talking about it:

So by visual examination we got 2 clusters, which k-means does not necessarily get, because some points on the edge of the bigger cluster are closer to the center of the smaller cluster than to the center of the bigger one. A possible solution would be to move closer to the second cluster with the centroid of the first cluster. I am not sure whether k-means does this (probably not), but if we have multiple small clusters around the big one, this does not help either. How could we modify the k-means to overcome this? Are there clustering algorithms, which don't have this weakness?
Comment: @ttnphns I have not a clue how to modify k-means to overcome this problem (probably there are many different ways to do that). If you think your proposition with rings is a possible solution, then it is just as good answer as the other, which recommends density based clustering instead.
Comment: Did you even read just the Wikipedia article? Or a clustering book? There is so much more than kmeans.
Comment: @Anony-Mousse I liked to learn k-means, because I watched a video about it, and it was very easy to understand what it does. On the other hand wikipedia is full of mathematical formulas usually without any good explanation, so for a beginner it is close to impossible to learn statistics/clustering from there. I bought some statistics books, but I haven't had the time to read them yet.
Answer: Your example looks like a textbook case where density based clustering works better. Such algorithms look for regions of high density and cluster those. The possibly best-known such algorithm is DBSCAN. We also have a tag dbscan. With decent parameterization, DBSCAN should be able to detect your two clusters.
You may also be interested in How to understand the drawbacks of K-means.
Comment: GMM should also work fine on above toy example, because the clusters are spherical. But yes, except for the cluster shape it is pretty much the motivational example of density based clustering...
Comment: Thanks for the link! So according to it, you have to find the right assumptions before applying any clustering algorithm otherwise the result will be a disaster.


How should I comprehend Modal Mixture?

Question: I'm studying the concept of modal mixture and there's one thing that I immediately got curious about.
Supposedly, the majority of POP music (rock, hip hop, r&b, country, etc) is a mixture of Major and Minor Keys. But Mixolydian and Lydian are the first introduction of a flat and a sharp. Using C Ionian as the "root mode", C Mixolydian adds Bb and Lydian adds F# (aren't these also technically the F Major and G Major keys?) Adding on one more flat/sharp, you get C Dorian (which is also Bb Major?) And then, there is no corresponding mode for D Major? After all of these we finally get to Aeolian with 3 flats which is Eb Major.
So technically, if a song is "in C Major (Ionian) & C Minor (Aeolian)" through the use of say Bb and Ab chords, isn't it also "in Mixolydian and Dorian"? Wouldn't that also make Mixolydian, Lydian, and Dorian "more consonant" than Aeolian if it's exactly the same concept as modulating around the circle of fifths?
Comment: Lecifer - I need to remind you that you need to focus on 1 question in a question post, not multiples! And for @AndyBonner - please remember comments are not the place to post answers.
Answer: "Modal mixture" is not the presence of multiple modes within a piece. The term refers to borrowing harmonic elements from the parallel major or minor of the predominant key.
For example, the current key is C major, but an F minor chord appears: say, in a harmonic progression C F Fm C. The presence of the F minor harmony is often explained by considering it as "borrowed" from the key of C minor.
Comment: @lecifer but we don't compose in modes for most music, most pop/jazz etc has a root in functional harmony and modes can be generally be seen as either a helper for which scale to play on which degree, or borrowed as you have been seeing. Of course some songs change key frequently and this can make for a lot of possible loaned modes! Of course there is music like modal jazz but even this tends to have either simple, slow steps between unrelated modes, or it follows a broadly recognisable diatonic chord progression with key changes and more exotic modes borrowed.
Comment: Well now I am a bit confused. As explained in this video https://www.youtube.com/watch?v=r0rawEpjAcA, his perspective is that maybe we should just consider a song "in the key of C" if it has e.g, 2 chords from C Ionian and 2 from C Aeolian. That's why I thought "modal mixture" didn't just mean "borrowed chords" but rather, that the song is a mixture of modes. And based on the hook theory statistics of the most popular modes Ionian and Aeolian are the most used. His example of this is the song "Are you gonna be my girl" by Jet. It has 2 chords from A Ionian and 2 from A Aeolian in an
Comment: (cont.) "almost 50/50 ratio". It has A Major and D Major from the Ionian key and G Major and C Major from the Aeolian Key. He also uses Hey Joe by Jimi Hendrix as an example and many more that mix in some of the other modes.
Comment: @Lecifer In my 19th-century theory course they used the term "modal ambiguity" for some passages in Brahms where it was hard to say whether it was minor or major. But while it's definitely possible to find examples, I don't think this characterizes "the majority of pop music"; the majority is plain old major or minor, with a significant minority of Mixolydian.
Comment: @Lecifer "Modal mixture" is a term of art with a specific meaning, which is explained very clearly at the very beginning of the video. Can you be more specific about where in the video you found something different?
Comment: @AndyBonner - 'minority' of Mixolydian! That'll mix some up!
Comment: @Aaron Sorry, I meant there is a a lot of other songs that use chords from other modes. Not necessarily in that video, I think he only shows one song that uses a Lydian chord.
Comment: @AndyBonner As in the majority are only in one key correct? I understand I just meant major, minor, or a mixture of those two and sometimes chords of other modes. I started looking into this because of our conversation with the improvising to a drone. If I'm songwriting that way, I'm not sure I'll be able to know what mode I'm writing in lol!
Comment: @OwenM I think i'm sort of having a hard time understanding modes. Thats why I said I don't exactly understand what the difference is between C Mixolydian and F Major?
Comment: @OwenM Isn't it something like the root is still being stressed as C in C Mixolydian, but F is stressed as the root in F major?
Comment: @Lecifer yes, thats broadly it. Say your song is in F for a section, but it spends some time on the C chord. We still 'feel' F as the tonic chord, and it feels like C is part of the journey on the way back to F. Nevertheless, you need a way of contextualising the set of notes you may play over the C chord. You could, say, play the F major scale still, but then your melodic choices would drag the ear back to C. It might be (is) more useful to say 'Play F major still, but focus it around the C while we are on the C chord'. This F major scale focused around a C is useful enough to deserve ...
Comment: ... it's own name, and we call it C mixolydian. You have a similar sub-scale of the major scale of the key you are in for every chord in that key. This serves as a helper for knowing what notes you can play when at various chord-degrees of the key. Modes follow key, and are secondary to key for pop/jazz. Note my description is not accurate across history etc, modes have been around for a long time, way before we structured our system of harmony. But harmony theory and the concept of key pervades almost all modern music now, and certainly in pop/jazz my description is the way we look at it!
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/149193/discussion-between-lecifer-and-owenm).
Answer: I tend to think of "modal mixture" in the following manner. In any key, one can play any chord if it sounds good. There are some chords that are used much more commonly than others. For example, in the key of C major, the subdominant chord is F major; sometimes an F minor chord can sound particularly appropriate. If this F minor chord is used similarly to an F major chord, it's called (inappropriately as mentioned in other answers) a "modal mixture." A chord that's diatonic to the minor mode on the same tonic (a chord from C minor used in C major) is the "mixture." One could also use a major chord in a minor key for example. "Besame Mucho" has a pattern i-iv-V-i (with a few non-chord tones) followed by I-iv-V-i; the use of the major tonic gives a bit of "color." The I or i both act as the tonic in these phrases.
Answer: The 'modal mixture' description is fairly inaccurate! Yes, in a lot of songs, there's 'borrowing' - using notes/chords from the relevant major/minor keys with the same tonic. As in using notes/chords from Cm whilst in the C major key. Very common. And theory does its best to explain the phenomenon with the term parallel keys.
Take that a little further, and we find modes cropping up, in the same sort of way. So, a piece in C major may have notes/chords found in C Mixolydian, or C Dorian, for example. All the theory is trying to do is explain, best it can, where these extras come from, and why.
My take to my students is slightly different: any note, in any key - as long as you know what you're doing, and it sounds good...
Answer: If a piece is 'in' C major, along with the chords made from the notes of the C major scale you can mix in those made from C minor, and label them as 'modal mixture'.  The most frequent 'borrowing' is probably iv, in C major that's the F minor chord.  It also provides an excuse for bVII, the B♭ major chord, which can be hard to explain in functional harmonic theory.
'Modal mixture' is a subset of a wider musical principle: 'Chromatic chords are OK'. Try to free yourself from the idea that diatonic notes/chords are 'correct' and anything else needs a special excuse.  Real music managed this hundreds of years ago!
Comment: "The most frequent 'borrowing' is probably vi, in C major that's the F minor chord" -- You mean iv ?
Comment: Yes.  Thanks.  Feel free to directly edit any obvious slip-ups like this in my posts!

How should I comprehend Modal Mixture?


Is it appropriate to use estimated marginal means when model estimates are not significant but data is unbalanced?

Question: Is it appropriate to use estimated marginal means when estimates (either interaction or main effects) are not significant but the data is unbalanced? I've come across variations of this question on stackexchange (e.g. here), but can't seem to find a definitive answer. Is it dependent upon the particular circumstance (so no right or wrong?). If it is dependent upon the circumstance, hopefully you can help me understand if my approach is fine. In my example, I have a linear mixed effects model (using lmer in R) which I test for differences in offspring body mass between treatments and years. It looks like this:
lmer(bodymass ~ year*treatment + (1|mother.id)

Each mother has several offspring, and some mothers appear in both years. The p-values for the 'year x treatment' interaction, as well as the main effects of 'treatment' and 'year' are all non-significant (alpha > 0.05). Visually, it seems like there is a true biological interaction that I'm not detecting statistically (see plot below). The plot shows the predicted estimates from the model with 95% confidence intervals; sample sizes (i.e., # of subjects) are as follows: Control 2017 = 12, Treatment 2017 = 7, Control 2018 = 18, Treatment 2018 = 19).
Because it looks like there may be potential for a type II error, I calculated the estimated marginal means from the model (using the emmeans pkg). I ran two t-tests to compare the em means (control 2017 - treatment 2017 and control 2018 - treatment 2018), and found that the 2018 comparison was significant (p < 0.001), but not the 2017 comparison. The em mean interaction plot looks similar to the predicted value interaction plot below. I'm guessing that at least part of the reason I don't find a year x treatment interaction in the model is due to imbalance between the years (removal of outliers does not change p-values greatly in original model), so would it be appropriate in this circumstance to use estimated marginal means for reporting pairwise difference from the model? It would also be useful if someone could provide me with an academic reference that discusses how/when marginal means can be used.
Comment: For starters, the tests you described using EMMs involve the main effects as well as the interaction. They are not equivalent to testing the interaction in the anova table.
Answer: Your model includes an interaction term, so it invites the following question:
When you designed your study, did you envision conducting a set of planned comparisons on the basis of this model?
A planned comparison is something you choose carefully when designing your study (hence prior to seeing your data). For example, comparing the mean body mass between treatment and control in 2018 would count as a planned comparison if subject matter considerations indicate that you only expect the mean body mass to differ between treatment and control in 2018.
If the answer to the above question is affirmative, then you can bypass the test of significance of the interaction (which is an omnibus test) and go directly to testing the planned comparisons of interest, as explained in the article https://files.eric.ed.gov/fulltext/ED393916.pdf.
If you were uncertain at the study design phase about what specific comparisons you wanted to make, then you would end up with unplanned comparisons. When dealing with unplanned comparisons, you would first test the significance of the interaction term in your model and then, if the resulting p-value is statistically significant, you would conduct unplanned post-hoc comparisons. As the above-referenced article explains, 'Many "unplaned" or "post- hoc"  tests are available, including Schefe, Tukey, LSD or Duncan tests, etc. Posthoc comparisons usually involve all possible comparisons of means, even though researchers may be only interested in testing only a few of these comparisons'.
See @gung's answer here for a nice explanation of the difference between planned and unplanned (post-hoc) comparisons: Why do planned comparisons and post-hoc tests differ?.
So you have to answer the question I outlined above first and foremost. Then:
If your focus is on planned comparisons, then you can bypass the test of significance of the interaction term in your model and proceed directly to perform these comparisons. If the em means plot helps you towards that goal, then you are fine to use it.
If you are uncertain what comparisons to test, look at the p-value for the interaction term. If that p-value is statistically insignificant, you have no evidence of an interaction and would stop there, since there would be no need for performing post-hoc comparisons. (It is possible that your study has inadequate power for testing the significance of the interaction term. You can look at the point estimate and confidence interval for the interaction term to get an idea of the magnitude of the interaction effect. The study could be inconclusive.)
Addendum
Your model looks like this:
model <- lmer(bodymass ~ year*treatment + (1|mother.id))

If year and treatment are declared as factors in R, whose reference levels are set to 2017 for year and Control for treatment, then your model could be stated as:
bodymass_ij = (beta0 + u_i) + beta1 * year2019_ij + beta2 * treatmentTreatment_ij +

               beta3 * year2019_ij * treatmentTreatment_ij + epsilon_ij

where i indexes the mother, j indexes the offspring, u_i is a random intercept for the ith mother and epsilon_ij is an error term. Also, year2019 is a dummy variable equal to 1 for the year 2019 and 0 for the year 2018. Furthermore, treatmentTreatment is a dummy variable which is equal to 1 for your active treatment and 0 for your control treatment.
Now, I can't tell from your post whether the active/control treatment is applied to the mother or separately to each of the offspring. So my notation above uses year2019_ij and treatmentTreatment_ij, which would be fine if the values of these variables would be expected to change from one offspring to another within the same mother. But if the values of either of these dummy variables would be the same across all offspring from the same mother, the index j would be dropped.
Anyway, in the model as formulated above, you would be interested in the relative effect of Treatment vs Control with respect to body mass (on average) in each of the two years. Let's make this effect more obvious by re-writing the model:
bodymass_ij = (beta0 + u_i) + beta1 * year2019_ij +

              (beta2 + beta3 * year2019_ij) * treatmentTreatment_ij +  epsilon_ij

The effect of interest is captured by the slope of treatmentTreatment_ij and clearly depends on year.
When the year is 2018, the effect of interest is given by beta2 (since year2019_ij = 0 for 2018). In other words, beta2 represents the difference in the mean body mass between Treatment and Control in year 2018.
When the year is 2019, the effect of interest is given by beta2 + beta3 (since year2019_ij = 1 for 2019). Thus, beta2 + beta3 represents the difference in the mean body mass between Treatment and Control in year 2019.
You can perform tests of hypotheses regarding these two effects, beta2 and beta2 + beta3, using the multcomp package in R, for example. The key is to realize that these two effects are linear combinations of the fixed effects coefficients beta0, beta1, beta2 and beta3. Specifically:
beta2 = 0*beta0 + 0*beta1 + 1*beta2 + 0*beta3

beta2 + beta3 = 0*beta0 + 0*beta1 + 1*beta2 + 1*beta3

So set up the following vectors of weights for these combinations in R:
K1 <- c(0, 0, 1, 0)
K2 <- c(0, 0, 1, 1)

Then row bind these together:
K <- rbind(K1, K2)

Assign row names and column names to the matrix K:
rownames(K) <- c("beta2", "beta2 + beta3")

colnames(K) <- c("beta0", "beta1", "beta2", "beta3")

Finally, use multcomp() to simultaneously test your two effects:
model.glht <- glht(model, linfct = K)

summary(model.glht)

This will simultaneously perform two sets of hypotheses:
Ho: beta2 = 0 vs. Ha: beta2 != 0

and
Ho: beta2 + beta3 = 0 vs. Ha: beta2 + beta3 != 0

Simultaneous confidence intervals for beta2 and beta2 + beta3 would be given by:
confint(model.glht)
If you have a covariate in your model (which does not contribute to the interaction between year and treatment), you need to write down your model again:
model:
bodymass_ij = (beta0 + u_i) + beta1 * year2019_ij +

              (beta2 + beta3 * year2019_ij) * treatmentTreatment_ij +

              beta4 * covariate_ij +

              epsilon_ij

The effects of interest are still beta2 and beta2 + beta3, but they are now adjusted for the effect of the covariate. When you proceed to test them or estimated as suggested above, you need to set up K1 and K2 like this:
So set up the following vectors of weights for these combinations in R:

K1 <- c(0, 0, 1, 0, 0)
K2 <- c(0, 0, 1, 1, 0)

Then row bind these together and assign proper names and columns:
K <- rbind(K1, K2)

rownames(K) <- c("beta2", "beta2 + beta3")

colnames(K) <- c("beta0", "beta1", "beta2", "beta3", "beta4")

Everything else is going to be the same as above in terms of testing and estimating beta2 and beta2 + beta3. Of course, the model with covariate would look like this:
model <- lmer(bodymass ~ year*treatment + covariate + (1|mother.id))

Comment: Appreciate the detailed response. At the outset of data analyses, I knew there were differences in weather patterns between the two years, and therefore wanted to know if the groups would respond differently in each year. So I think this is a planned comp. When you say 'then you can bypass the test of significance...and proceed directly to perform these comparisons', does this mean that I should not even run the omnibus test, and skip right to t-tests, or does this mean I should still report both original/omnibus model and t-test results? What if I also have a covariate in the omnibus model?
Comment: I interpret the word "bypass" in the reference I sent to you as skipping the omnibus test altogether, given that your comparisons appear to have been planned at the study design stage. See the addendum to my initial answer.
Comment: Just finished the addendum - it's long but hopefully it will help you understand how to perform the comparisons you are interested in using a package like multcomp. See the vignette for multcomp if you are not familiar with this package: https://cran.r-project.org/web/packages/multcomp/vignettes/multcomp-examples.pdf.
Answer: People seem to have an assortment of pretty rigid practices. I'll just comment that I think ANOVA F tests are kind of overrated. They can be useful for deciding what model is suitable for a dataset; but they do not help much, in my opinion, for doing any meaningful inference.
In particular, if you have fitted a two-way factorial model including interaction, and the residual diagnostics look good, I don't see anything wrong with proceeding to do post hoc means and comparisons without even looking at the ANOVA table. Appropriate multiplicity adjustments should be used, and I think it's important to look at the means themselves, not just the pairwise differences -- both from a subject-matter perspectives -- and probably plot them as well.
I am a lot more comfortable with what is described in the preceding paragraph than I am with some analysis where rigid rules and "significance" criteria are applied, but no diagnostic plots or descriptive plots are examined. I see this kind of routinized method way, way too often.
Not only do I think that little is lost by ignoring ANOVA tables, it is possible that something will be gained. For example, suppose that in skipping the ANOVA and plotting the means, we observe an interaction that would be of scientific interest (but for which there is insufficient data to achieve the magical "P < 0.05" threshold). (is that the situation in the posted question???) This would suggest something potentially important that could be investigated in further experimentation. A devoted user of ANOVA tables may summarily throw the interaction out of the model, hence never having the opportunity to notice this potentially important result. Remember, just because something isn't "statistically significant," that doesn't prove it isn't there; it just means you don't have enough data to be sure it isn't part of the noise.


Email RegEx Javascript with RPC

Question: I have a few codes here of js. And I wanted to put a validation for email and prevents user from submitting a form when it is not valid. Please bear with me since I am new with this technology. Thank you for understanding :)
var session = require('web.session');
var db_name = $("input[name='partner_name']").val();
var contact = $("input[name='contact_name']").val();
var email = $("input[name='email_from']").val();
var url = '/page/website_crm.contactus_thanks';

 $(function(){
        $("#start_trial").click(function(){ // no idea how to put email validation here
                    session.rpc('/custom/createaccount', {
                            db_name : db_name,
                            contact_name: contact,
                            email_from: email
                        });
                    }).then(function () {
                        console.log("Creating user account")
                    });

                   // that won't proceed here
                    setTimeout(function (){
                       window.location = url;
                    }, 5000);

});

Answer: if you want to test if email is ok, lot of solution, this pattern does the job:
var email = $("input[name='email_from']").val();
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

if(!pattern.test(email))
{
  alert('e-mail address is not valid');
}

Comment: I am facing an error which is unexpected token or syntax error
Comment: just forgot `;` fixed now

Email RegEx Javascript with RPC


What can you tell about the span of the following union set?

Question: Consider $\mathbb{C}^5$ and the following three sets, each containing two orthogonal vectors:
$A=\{a_1,a_2 \}$, $B=\{b_1,b_2 \}$ and $C=\{c_1,c_2 \}$.
All these vectors are different and non-zero. Additionally, vectors from different sets are not orthogonal. Clearly, each set spans a two-dimensional subspace of $\mathbb{C}^5$: $\text{dim}(\mathcal{S}_i)=\text{dim}(\text{span}(i))=2$ where $i\in\{A,B,C\}$.
I have the following property: the union of each two sets forms a set of linearly independent vectors, i.e. $\text{dim}(\mathcal{S}_{i\cup j})=4$ for $i \neq j$.
I would like to show that it is not possible that $\text{dim}(\mathcal{S}_{A\cup B \cup C} )=4$.
Does this follow directly from the above (and I'm missing something obvious) or do I need to exploit particular properties of the vectors?
Comment: All the vectors are non-zero, in my case.
Comment: Thanks, I edited the question.
Comment: I'm guessing that you are using $\mathcal{S}_X$ to denote $\text{span}(X)$. But then $\mathcal{S}_i \cup \mathcal{S}_j$ is not a subspace and $\text{dim}(\mathcal{S}_i\cup \mathcal{S}_j)$ is meaningless. You should write $\mathcal{S}_{i\cup j}$
Answer: Consider $$A=\{(1,0,0,0,0), (0,1,0,0,0)\}$$
$$B=\{(0,0,1,0,0),(0,0,0,1,0)\}$$
$$C=\{(1,0,1,0,0),(0,1,0,1,0)\}$$
Comment: Thanks, is a similar construction possible with the additional restrictions that I included in the question? Namely, vectors of different sets are not orthogonal.


Closed form solution for the optimization problem

Question: How do I solve the following optimisation problem where $A$ is a PSD matrix ?
$$\max\limits_{x \in \mathbb R^n\setminus \{0\}} \frac{x^T (a_1 -a_2)} { \sqrt{x^TAx}}$$
Is it a concave optimization problem?
Answer: Since $A$ is positive definite, it's convenient to use the Cholesky factorization of $A$ to write $A$ as $A=R^{T}R$.  Then, let $z=Rx$.  After solving for $z$, you can recover $x$ with $x=R^{-1}z$.  This change of variables is often very helpful with problems involving $\sqrt{x^{T}Ax}$.
Next, solve $c^{T}R=(a_{1}-a_{2})^{T}$ to obtain a vector $c$.
Your problem can now be written as
$\max_{z \neq 0} \frac{c^{T}z}{\| z \|_{2}} $
You can scale any non-zero $z$ by a positive scaling factor without changing the value of the fraction $c^{T}z/\| z \|_{2}$.  Thus without
loss of generality, you can scale the solution so that $\| z \|_{2}=1$.
We can rewrite the problem as
$\max c^{T}z$
subject to
$\| z \|_{2}=1$.
The solution to this problem is obviously $z=c/\| c \|_{2}$. You can then convert $z$ back into $x$.  Any positive multiple of that solution will also be optimal.
Comment: A is not necessarily positive definite, so you can't always compute $R^{-1}$.
Comment: If A is indefinite then the objective function isn't defined for vectors in the null space of $A$.
Answer: This is nothing but the dual norm of the the norm $x \mapsto \|x\|_A:= \langle x, Ax\rangle^{1/2} = \|A^{1/2}x\|_2$ induced by the postive-definite matrix (p.d) $A$, evaluated at the point $a := a_1-a_2$. The value can be computed analytically as $\|A^{-1/2}a\|_2$ and is attained by setting $x = \frac{1}{\|A^{-1/2}a\|_2}A^{-1/2}a$ in the quotient $\langle x, a\rangle /\|x\|_A$. Indeed,
$$
\begin{aligned}
\max_{x \ne 0} \frac{\langle x, a\rangle}{(x^TAx)^{1/2}} &= \max_{y \ne 0}\frac{\langle A^{-1/2}y,a\rangle}{\|y\|_2} = \max_{\|y\|_2 \le 1} \langle y, A^{-1/2}a\rangle = \|A^{-1/2}a\|_2.
\end{aligned}
$$
where we've used the change of variable $y = A^{1/2}x$.
In particular, we've shown that the dual of the norm induced by a p.s.d matrix is the norm induced by it's inverse. That is, that induced norms $\|.\|_A$ and $\|.\|_{A^{-1}}$ are duals to each other.
N.B.
Your problem doesn't make sense if $A$ is not strictly positive-definite,
because for positive semi-definite matrices, the denominator $x^TAx$ can be equal zero for non-zero $x$.
Comment: If the $\max$ were a $\sup$, you can potentially exploit semidefiniteness by finding a sequence $x^n$ for which the numerator goes to $\infty$ while the denominator remains constant.