Let $U\subseteq X\times Y$. Show that $\pi_X(U)$ is open in X and $\pi_Y(U)$ is open in Y $\Rightarrow$ U is open does not hold

Question: I have to do this exercise:
Let X and Y be topological spaces and equip $X \times Y$ with the product topology. Define $\pi_X: X \times Y \to X$ by $\pi_X((x,y))=x$, and $\pi_Y:X \times Y\to Y$ by $\pi_Y((x,y))=y$
I have shown that doe every open set $U\subseteq X \times Y$ $\pi_X(U)$ is open in X, and $\pi_Y(U)$ is open in Y, but now I have to show that the opposite does not hold with a counterexample. i.e I have to show that for a subset $Z\subseteq X \times Y$ it will hold that $\pi_X(Z)$ is open in X, and $\pi_Y(Z)$ is open in Y, but Z will not be open in $X \times Y$ with respect to the product topology.
I have found an example for this, where I let $X =\mathbb{R}$, and $Y=\mathbb{R}$, and I let $Z=\{(x,y)|\frac{1}{2}\leq \|(x,y)\|<1\}$. Intuitively I can see that $\pi_X(Z)=(-1,1)$, and $\pi_Y(Z)=(-1,1)$, but I have to show it, because then I will have that $\pi_X(Z)$ and $\pi_Y(Z)$ is open, and I am a little confused on how to do that, and furthermore I can intuitively see that Z is not open in $X\times Y$ wrt. the product topology, but I am a little confused about how to do that.
Comment: Huh?  In the settings of your title, if $U\not\subseteq X\times Y$ then how do you define $\pi_X(U)$ and $\pi_Y(U)$?
Comment: That's a mistake, I don't have to show $U\not\subseteq X\times Y$, I have to show that U is not open. I have corrected that now.
Comment: couldn't we take e.g. $U=\{(x,x) \mid x\in\mathbb{R}\}$? maybe that's easier to show
Comment: A  simple counter-example is $X=Y=\Bbb R$ and $U=(\Bbb R\times \{0\})\cup (\{0\}\times \Bbb R)$.
Comment: @DanielWainfleet will we then have $\pi_X((\mathbb{R}\times\{0\})\cup(\{0\}\times\mathbb{R}))= \pi_X((\mathbb{R}\cup\{0\})\times(\{0\}\cup\mathbb{R}))=\mathbb{R}\cup\{0\}=\mathbb{R}$,  and this is open in $\mathbb{R}$?, and the same with $\pi_X((\mathbb{R}\times\{0\})\cup(\{0\}\times\mathbb{R}))= \pi_Y((\mathbb{R}\cup\{0\})\times(\{0\}\cup\mathbb{R}))=\{0\}\cup\mathbb{R}=\mathbb{R}$, and this will be open. But is $U= (\mathbb{R}\times\{0\})\cup(\{0\}\times\mathbb{R})$ not open in $\mathbb{R}\times\mathbb{R}$, wrt the product topology, and how do I argue that?
Comment: Try applying the first part of my Answer.
Answer: Notation. To avoid confusion,  $(b,c)$ will denote an open real interval and $<b,c>$ will denote an ordered pair.
The "canonical" base (basis) for the product topology on $\Bbb R^2$ is $$B=\{I\times J: I,J\in T_{\Bbb R}\}$$ where $T_{\Bbb R}$ is the topology on $\Bbb R.$
Consider any $<x,y>\in V$ where $V$ is open in $\Bbb R^2$. We have $<x,y>\in I\times J\subset V$ for some $I\times J\in B.$ Now since the set of bounded open real intervals is a base for $T_{\Bbb R},$ there exist positive $r,r'$ with $(x-r, x+r)\subset I$ and $(y-r',y+r')\subset J.$ So  $$<x,y>\in (x-r,x+r)\times (y-r',y+r')\subset I\times J\subset V.$$
In your example, $<1/2,0>\in Z.$ Consider any open  $V$  such that $<1/2,0>\in V$. We have $(1/2-r,1/2+r)\times (-r',r')\subset V$ for some positive $r,r'.$  But now if $s=\min (1/4, r/2,r'/2)$ then $<1/2-s,0>\in V$ but $\|<1/2-s,0>\|=1/2-s<1/2.$ So $<1/2-s,0>$ is in $V,$ but not in $Z,$ so $\neg (V\subset Z).$ Therefore $Z$ is not open.
Remark. We can also do the above paragraph by contradiction: Suppose $Z$ is open. Then in the above paragraph, put $V=Z.$ We get $<1/2-s,0>\in V\setminus Z=Z\setminus Z,$ which is absurd.
Note. In general if $T_x,T_Y$ are topologies on $X,Y$ respectively, and if $B_X, B_Y$ are bases for $T_x,T_Y$ respectively, then $\{b\times b': b\in B_X\land b'\in B_Y\}$ is a base for $X\times Y.$ In particular,  if $C$ is the set of bounded open real intervals then $\{b\times b':b,b'\in C\}$ is a base for $\Bbb R^2$.... It is often convenient to work with bases rather than with the entire topologies.
Answer: A few of the commenters have suggested simpler counter-example than the one that you found. But I think it's still worth it to see how one would show that your own counter-example is actually a legit counterexample.
So let $X = \mathbb{R}, Y = \mathbb{R}$ and $Z = \{(x,y): \frac{1}{2} \leq ||(x,y)|| < 1\}$.
To show that $\pi_X(Z) = (-1,1)$ we do what we often do when showing equalities of two sets, namely we will show $\pi_X(Z) \subseteq (-1,1)$ and $(-1,1) \subseteq \pi_X(Z)$.
Let $(x,y) \in Z$. If $|x| \geq 1$ would be true, then $||(x,y)|| \geq 1$, but this is not possible since $(x,y) \in Z$. Therefore $|x| < 1$, i.e., $\pi_X((x,y)) = x \in (-1,1)$.
For the other direction, let $x \in (-1,1)$, define $y = 0 $ if $ \frac{1}{2} \leq |x| < 1$, $y = \sqrt{\frac{1}{4} - x^2}$ else. (Maybe there is a more clever way to define $y$. The idea is that you just construct it so that $(x,y) \in Z$...). Now you can check that indeed $(x,y) \in Z$, so $x \in \pi_X(Z)$.
The case for $\pi_Y$ is exactly the same.
Finally, to check that $Z$ is not open you can look for a point in $Z$ that has no open neighborhood in $Z$. Good candidates will be points $(x,y)$ such that $||(x,y)|| = 1/2$.
Comment: It is clear for me that $\frac{1}{2}\leq\|(x,y)\|<1$ holds when $y=0$, but I have a hard time checking it when $y=\sqrt{\fraq{1}{4}$, how do I do that?

How can I check that a point in Z has no open neighborhood in Z?
Comment: To show that $(x,y) \in Z$ for $|x| < \frac{1}{2}$ and $y$ as I defined it above, we can simply compute $||(x,y)||$ and show that $\frac{1}{2} \leq ||(x,y)|| < 1$. By definition we have $||(x,y)|| = \sqrt{x^2+y^2}$. Can you take it from here? (substitute the expression above for $y$...)
Comment: A point $z \in Z$ has no open neighborhood in $Z$ if we can't find a radius $r$ such that the open ball with radius $r$ around $z$ is contained in $Z$, i.e., $B_r(z) \not \subseteq Z$ for any $r>0$. Take for example the point $(0,\frac{1}{2})$, which is in $Z$ since it has norm 1/2. If you draw a small circle around it, there are always points inside that circle that are not in $Z$. Do you agree? (Drawing a picture might be helfpul here...)


Ruby on Rails Decryption

Question: The following function works perfect in PHP. How can it be translated in Ruby on Rails.
Please note that both privateKey and iv are 32 characters long.
mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $privateKey, base64_decode($enc), MCRYPT_MODE_CBC, $iv)

I tried to use the following in Ruby but got a bad decrypt error.
cipher = OpenSSL::Cipher.new('aes-256-cbc')

cipher.decrypt
cipher.key = privateKey
cipher.iv = iv

decrypted = '' << cipher.update(encrypted) << cipher.final

Comment: You're not using this for a password, right?
Answer: Here some code which works for me :

def decrypt_data(data, pwd, iv)
    encrypted_data = Base64.decode64(data)
    aes = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
    aes.decrypt
    aes.key = Digest::MD5.hexdigest(pwd)
    aes.iv = iv
    result = aes.update(encrypted_data) + aes.final
end

In my example the password is encrypted with MD5.
I hope this help
Comment: MD5 does not encrypt, it hashes.
Comment: Many thanks for your quick response. However, this does not seem to work for me. I am new to Ruby on Rails. I will be very grateful if you could please tell me how to get the same results in Ruby on Rails as the following php code produces in php
Comment: If I remove + aes.final from the above ruby code, I get a string but it is not readable. I I do not remove + aes.final, I get "bad decrypt" error
Comment: I found this in php doc http://php.net/manual/fr/function.mcrypt-decrypt.php As you can see, the first comment sais "MCRYPT_RIJNDAEL_256 is not equivalent to AES_256". This is probably a way...
Comment: I am still not getting the result the php code produces in php :( I am really stuck with this
Comment: All I am getting is this |&���0~�%��]�}w�;�k�Ȱ�*k�tn�:�p�F���p��.Q���5��k�Օ,�z���Ơ��S�:�+(� �G':Y���B##�6��׻?��X^6*�)2��A�u|z?�NH`xAma�j� _�> �>I���&pK-T&����O�{4�m�@pm��C��j&��@�|�O:H�ER�y�vO��U{J~�G�9� �l1�a�h����A���rP!���n $��1�}EA���K�VXU9�1N9�Hl��aN�ۚ�[����b3?L
Comment: While I am expecting this PSID=edc1419e-9f42-41df-b3c2-796ae2c1b5cc&MSISDN=353870011082&CustomString=YOUR_CUSTOM_STRING&Status=Success&LocalCurrency=EUR&LocalCharge=2.500&LocalCharged=2.500&Mode=TEST&LocalPayout=1.068&YourHomeCurrency=EUR&HCCharge=2.500&HCCharged=2.500&HCPayout=1.068&NetworkId=1
Comment: Is there any padding or block size issue?
Comment: Is there a Ruby equivalent of MCRYPT_RIJNDAEL_256? If I use MCRYPT_RIJNDAEL_256 in PHP and AES-256-CBC in Ruby to encrypt the same data using the same key (32 characters) and iv (32 characters) and then base64 encode the encrypted data, I always get different results.

However, if I use MCRYPT_RIJNDAEL_128 in php and AES-256-CBC in Ruby using a key (32 characters) and iv (16 characters) and then base64 encode the encrypted data, I get the same results.
Answer: You are base64 decoding it in the php example. Are you doing that in the ruby one as well?
require "base64"
Base64.decode64(encrypted)

Other than that, the code looks right to me.
Comment: Many thanks for your quick response

Here is the complete PHP code

    $iv = base64_decode($_REQUEST["bpi"]);
    $enc = $_REQUEST["bpe"];
    $sig = $_REQUEST["bps"];
    $sig2 = hash_hmac("sha256", utf8_encode($iv . '.' . $enc), utf8_encode($privateKey));
    echo(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $privateKey, base64_decode($enc), MCRYPT_MODE_CBC, $iv));

It works fine in PHP

But the above Ruby code gives me a bad decrypt error. I am base64 decoding in ruby as well
Comment: Is there a Ruby equivalent of MCRYPT_RIJNDAEL_256? If I use MCRYPT_RIJNDAEL_256 in PHP and AES-256-CBC in Ruby to encrypt the same data using the same key (32 characters) and iv (32 characters) and then base64 encode the encrypted data, I always get different results.

However, if I use MCRYPT_RIJNDAEL_128 in php and AES-256-CBC in Ruby using a key (32 characters) and iv (16 characters) and then base64 encode the encrypted data, I get the same results.

Ruby on Rails Decryption


Property of odd degree polynomials?

Question: A real polynomial of odd degree has all positive coefficients . Prove or disprove the following statement----
There is a permutation of its coefficients (possibly trivial) such that resulting polynomial has exactly one real root
Comment: You just wait a while, we have some pretty smart people on this site.  :)  sure someone will solve this.
Comment: Have you looked into Sturm's theorem?
Comment: I have the "slightest" idea that you might want to choose a particular permutation, such as "from largest to smallest".  Or maybe "largest on the highest degree term and second largest on the x term.$  My other slight idea is that the derivative is even-degree and also has all positive coefficients.
Comment: @james_bond_007 I think I have a answer without proof. We need to put highest coeff. as constant.
Comment: Putting the largest coefficient as the constant does not always work.  $x^3+12x^2+47x+60$ has zeroes at $-3, -4, -5$.  The partial answer posted below suggests we need to distribute large coefficients around "both ends".
Comment: Can we use the result from    http://math.stackexchange.com/questions/1716027/can-we-permute-the-coefficients-of-a-polynomial-so-that-it-has-no-real-roots        and then consider the derivative of the reqd.  odd degree polynomial is always positive ?
Comment: Anybody with the slightest idea of what can be done ?
Comment: How can that help in this problem ? Please help  :)
Comment: Does constant count as a coefficient ?
Comment: Yes , it does .
Comment: Can anyone figure out what to do ?
Comment: @OscarLanzi That also does not work for $x^5+100x^4+ x^3+x^2+47x+2$, which has 3 roots.
Answer: Partial answer:  For the case of cubic polynomials it's true.
Let $ax^3+bx^2+cx+d$ be a cubic polynomial in $x$ with all coefficients positive and three real zeroes.  All three must be negative and they sum to $-b/a$, thus all are greater than $-b/a$.  This forces the polynomial value at $x=-b/a$ to be negative, but that  value is $(ad-bc)\over a$.
Thus $ad<bc$, but that can't be true for all permutations of a given set of positive numbers.  So at least one permutation of the coefficients fails to give three real roots.
Comment: Did we not assume here that all coefficients are positive?  That is why all real roots must be negative.

Property of odd degree polynomials?


Removing from a collection while in a foreach with linq

Question: From what I understand, this seems to not be a safe practice...
I have a foreach loop on my list object that I am stepping through. Inside that foreach loop I am looking up records by an Id. Once I have that new list of records returned by that Id I do some parsing and add them to a new list.
What I would like to do is not step through the same Id more than once. So my thought process would be to remove it from the original list. However, this causes an error... and I understand why.
My question is... Is there a safe way to go about this? or should I restructure my thought process a bit? I was wondering if anyone had any experience or thoughts on how to solve this issue?
Here is a little pseudocode:
_myList.ForEach(x =>
{
    List<MyModel> newMyList = _myList.FindAll(y => y.SomeId == x.SomeId).ToList();

    //Here is where I would do some work with newMyList

    //Now I am done... time to remove all records with x.SomeId
    _myList.RemoveAll(y => y.SomeId == x.SomeId);
});

I know that _myList.RemoveAll(y => y.SomeId == x.SomeId); is wrong, but in theory that would kinda be what I would be looking for.
I have also toyed around with the idea of pushing the used SomeId to an idList and then have it check each time, but that seems cumbersome and was wondering if there was a nicer way to handle what I am looking to do.
Sorry if i didnt explain this that well. If there are any questions, please feel free to comment and I will answer/make edits where needed.
Comment: Why not using GroupBy? You can group your records by SomeId and then cycle on those groups
Comment: @SebastianoRoncato - Thank you, this did in fact work for me. If you would like to post as an answer I would be happy to mark it as correct.
Comment: This may be possible. I would have to try and see if this would work for me. Thanks for the input!
Comment: Sorry deleted my answer.  I see you mentioned maintaining a list of IDs in your question.  GroupBy is much easier then maintaining a list of IDs.
Answer: First off, using ForEach in your example isn't a great idea for these reasons.
You're right to think there are performance downsides to iterating through the full list for each remaining SomeId, but even making the list smaller every time would still require another full iteration of that subset (if it even worked).
As was pointed out in the comments, GroupBy on SomeId organizes the elements into groupings for you, and allows you to efficiently step through each subset for a given SomeId, like so:
_myList.GroupBy(x => x.SomeId)
       .Select(g => DoSomethingWithGroupedElements(g));

Jon Skeet has an excellent set of articles about how the Linq extensions could be implemented. I highly recommend checking it out for a better understanding of why this would be more efficient.
Answer: First of all, a list inside a foreach is immutable, you can't add or delete content, nor rewrite an element. There are a few ways you could handle this situation:
GroupBy
This is the method I would use. You can group your list by the property you want, and iterate through the IGrouping formed this way
var groups = list.GroupBy(x => x.yourProperty);
foreach(var group in groups)
{
//your code
}

Distinct properties list
You could also save properties in another list, and cycle through that list instead of the original one
var propsList = list.Select(x=>x.yourProperty).Distinct();
foreach(var prop in propsList)
{
    var tmpList = list.Where(x=>x.yourProperty == prop);
    //your code
}

While loop
This will actually do what you originally wanted, but performances may not be optimal
while(list.Any())
{
    var prop = list.First().yourProperty;
    var tmpList = list.Where(x=>x.yourProperty == prop);
    //your code
    list.RemoveAll(x=>x.yourProperty == prop);
}


Merge function not copying into the vector correctly

Question: The merge(iterator, iterator, iterator2, iterator2, outIterator) should take in 5 iterators, split up the vector sent in, then sort the 2 separate vectors, then merge them together into one sorted vector. My method seems to work unless range2 has elements that are less than range1 which will then fail my test.
template<typename Iter1, typename Iter2, typename OIter>
OIter merge(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2, OIter out) {
   // TODO
   auto i = first1;
   auto j = first2;
   while (j != last2 && i != last1) {
       if (first2 == last2) {
           return std::copy(first1, last1, out);
       }
       if (*i < *j) {
           *out++ = *i++;
       } else {
           *out++ = *j++;
       }
   }
   //only one of the ranges has elements copy them over
   if (first2 == last2) {
       return std::copy(first1, last1, out);
   } else {
       return std::copy(first2, last2, out);
   }
}

TEST:
REQUIRE( out == copy_out )

with expansion:
{ 0, 1, 2, 3, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 } = actual

==
{ 0, 1, 2, 3, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 } = expected

Answer: This logic is wrong
//only one of the ranges has elements copy them over
if(first2 == last2)
{
  return std::copy(first1, last1, out);
}else{
  return std::copy(first2, last2, out);
}

it should be
//only one of the ranges has elements left, copy them over
if(j == last2)
{
  return std::copy(i, last1, out);
}else{
  return std::copy(j, last2, out);
}

Also this special treatment
if(first2 == last2)
{
  return std::copy(first1, last1, out);
}

is unnecessary (and misplaced).


Is every z-filter $\mathscr{F}$ the intersection of all z-ultrafilters refining it?

Question: Every z-filter $\mathscr{F}$ on a topological space $X$ is the intersection of all z-primefilters refining it. Is it also true that it is the intersection of all z-ultrafilters refining it? Can you give a proof or counterexample?
Answer: No, this is not the case.
Let's first remark that, while each z-ultrafilter is prime, not every z-primefilter is ultra. To see this, we will give a counterexample on the space $X = \mathbb{R}$.

First take a free ultrafilter $\mathscr{U}$ on the set
  $$N:=\left\{\frac{1}{n}\mid n\in \mathbb{N}\right\}$$
  And define the z-filter
  $$\mathscr{F}:=\{Z\in \mathcal{Z}(\mathbb{R})\mid Z\cap N \in \mathscr{U}\}$$
  This is clearly a z-filter, and it is also prime: take $Z_1, Z_2\notin \mathscr{F}$, then $Z_1\cap N \not \in \mathscr{U}$ and $Z_2\cap N \notin \mathscr{U}$. Because $\mathscr{U}$ is ultra we then have
  $$(Z_1\cap N) \cup (Z_2\cap N) = (Z_1 \cup Z_2)\cap N \notin \mathscr{U}$$
  so $Z_1\cup Z_2\notin \mathscr{F}$ and $\mathscr{F}$ is prime. But it is not ultra because it is stricly contained in the z-ultrafilter $\mathscr{G}$generated by $0$:
  $$\mathscr{G}=\{Z\in \mathcal{Z}(\mathbb{R})\mid 0 \in Z\}$$
  This is because for each $Z\in \mathscr{F}$, $Z\cap N$ is a sequence converging to $0$, and $Z$ is closed so $0\in Z$ and $Z \in \mathscr{G}$. The inclusion is strict as witnessed by the singleton $\{0\}$.

In fact, $\mathscr{G}$ is the only z-ultrafilter that refines $\mathscr{F}$, so the intersection of all z-ultrafilters that refine $\mathscr{F}$ is equal to $\mathscr{G}$ and not $\mathscr{F}$. We will now check that this claim holds.

Let $\mathscr{H}$ be another z-ultrafilter that refines $\mathscr{F}$. It suffices to show that each element of $\mathscr{H}$ contains $0$. Suppose not, let $Z \in \mathscr{H}$ with $0\notin Z$. Because $Z$ is closed, it can also not contain any sequence converging to $0$, so there must be some $m\in \mathbb{N}$ such that
  $$N_m:=\left\{\frac{1}{n}\mid n\geq m\right\}\cup \{0\}$$
  is disjoint form Z. $N_m$ has a finite complement in $N$ and it is a zeroset, so $N_m \in \mathscr{F}\subset\mathscr{G}$. This is a contradiction because then $\mathscr{G}$ contains the disjoint sets $Z$ and $N_m$.


Can things go wrong if we declare objects to be arrows?

Question: I am familiar with categories and also with 'categories without objects'. In fact a category is completely determined by its set of arrows and the objects can be missed. Nevertheless the objects are convenient when it comes to visualisation and have a function in making abstract nonsense a bit less abstract. Normally however I tend to avoid redundancies and in this context the following question arose:

Can anything go 'wrong' if we just interpret the set of objects always as a subset of the set of arrows?

Here off course the objects are identified with the identity-arrows. If this can be practicized then we don't really 'lose' the objects and at the same time we can work in a category without redundancies.
Comment: Yes, you can axiomatize category theory solely with a primitive notion of arrows, among which are a special case of "identity arrows".  I recall this being mentioned in previous posts about axioms for category theory, or perhaps it was more history of category theory.
Comment: I think you answer your question yourself. If this subset of the set of arrows is exactly the set of identity arrows, then nothing can go wrong. :)
Comment: Here's [the post I remembered](http://math.stackexchange.com/a/271315/3111) that mentions Eilenberg and MacLane's 1945 exposition noted the possibility of dispensing with objects (in favor of an arrows-only approach).
Comment: You can safely declare $X = \mathrm{id}_X$ for all objects $X$.
Answer: No, nothing can go wrong, but also it doesn't make life easier. After all, you want to work with morphisms from one object to another object, so that you really need the notion of an object (even if this can be encoded as a morphism). Also, the composition of morphisms is only defined when the first morphism ends where the second morphism starts - and it is good to know when this happens. I'm not aware of any situation where the "object-free" notion of a category is useful.
Answer: Here's what Eilenberg and MacLane noted (p.238) in their seminal 1945 paper:

[Axioms C4-C5] assert that the rule $A\rightarrow e_A$ provides a one-to-one correspondence between the set of all objects of the category and the set of all its identity mappings. It is thus clear that the objects play a secondary role, and could  be entirely omitted from the definition of a category. However, the manipulation of the applications would be slightly less convenient if this were done.


how to interpret the cumulative incidence plot stratifying in two groups

Question: I would like to interpret the cumulative incidence plot in blow. Red line shows cancer and black line noncancers. Event is ability decline. Is it correct to say that the risk of ability decline in cancers in higher that nocncancers. Right? And the difference in cox from score log rank test is p = 0.06. My question is that what is the correct interpretation and is it strange that the probability at the end stopped very close to 1? Any help in appreciated.
I have also checked, I do not have competing risk of death. No death before event happened. I am not sure why the probability reaches one. Why this happened?
For cox I have defined: Age as time, defining Tstart and Tstop:

if status of event = 0, then Tstart = age at inclusion, Tstop = age at end of  follow-up

if status of event = 1, then Tstart = age at inclusion, Tstop = age at event

for considering cancer as a time-varying covariate: For each ID in this condition, I added a new line.

if cancer ==0 and status event = 1, then Tstart = age at inclusion, Tstop = age at diagnosis then also I keep the cancer status ==0
if cancer ==0 and status event = 1, then Tstart = age at diagnosis, Tstop = age at event and then I changed the status of cancer==1.
Also, for those who have diagnosed by cancer in the follow-up, I have chosen the "age at diagnosis" as "age at inclusion". And, if "cancer diagnose age" was after "age at event", these are set as no-cancers.
Comment: Please say more about your data and the Cox model that you used. The start of both groups with 0 events at an age of about 70 is hard to understand. Usually survival is from some defined start time; your plot might be taken to imply that you started with a `cancer` and a `noncancer` cohort all from age 70 and that there were no later cancers in the `cancer` cohort. That seems unlikely. Or you might have used `age` data for each individual at study entry; that would require modeling the left truncation. Please edit the question to provide that information; comments are easy to overlook.
Comment: @EdM I have updated with more information, would you please explain now?
Comment: I added an example of how I would code participants who entered the study as `noncancer` but developed `cancer` during the study, one who ended up with the event and one who didn't.
Comment: @EdM thank you very much. I have one question, should I do first step 1 and 2, I explained to define Tstart and Tstop based on status of event and then add to that (correct) for non-cancers who developed cancer during study? thanks again.
Comment: Yes. Code all of those who started with cancer or those who started non-cancer and never got cancer just as you did. The additional rows of data would be for those who started non-cancer and then got cancer. I provided two such examples, for someone who eventually had the event and another who didn't.
Comment: @EdM Can I consider both competing risk of death and cancer as time-varying covariate together?
Answer: A cumulative incidence plot like this, with at most one event possible per individual, is just a survival curve turned upside down. A survival function is 1 minus a cumulative probability function, and vice-versa.
The cumulative incidence plot in that situation is just the probability that someone in the specified group has had the event, up through the indicated time.

is it strange that the probability at the end stopped very close to 1?

That's exactly what you'd expect if everyone eventually has the event: the probability of having the event in either group is ultimately 1. The only difference might be how quickly it happens. If the last observation time was right-censored rather than an event, you won't quite get up to 1 (just like you don't quite get down to 0 in the survival curve).

if "cancer diagnose age" was after "age at event", these are set as no-cancers.

You can do better than that. You already are using the (Tstart, Tstop, Status) counting-process format for your data to handle (appropriately) the left truncation of Age values. That's the same format used for handling time-varying covariates. You also are already specifying individual IDs to allow for robust cluster estimates of the variances.
So extend that to treat the cancer diagnosis as a time-varying covariate. When a patient is diagnosed with cancer, set that age to the Tstop for the non-cancer situation with right censoring at that age. Then start a new data row for that patient ID, with Tstart being the age at diagnosis, the status changed to cancer from non-cancer, and with the Tstop and Event values that you had previously used.

Is it correct to say that the risk of ability decline in cancers in higher that nocncancers. Right? And the difference in cox from score log rank test is p = 0.06.

By the usual standard of statistical significance (p < 0.05), you couldn't claim that there's a difference. For example, at ages starting around 85 the confidence intervals for the cancer group overlap the point estimates of the non-cancer group. You'll also note that the curves cross back and forth around ages in the 90s. This suggests that a Cox proportional hazards model with time-constant coefficients doesn't fit your data well. Treating cancer status as a time-varying covariate might help, or you might consider modeling it with a time-varying coefficient, maybe with a step function as in Section 4.1 of the R time dependence vignette. That might help illustrate a difference between ages of about 75 to 85.
Data format
I'm not sure that I completely understood how you proposed to code individuals who entered the study cancer-free but developed cancer during the study. Here are examples for two patients. Patient with ID 101 entered the study at age 75, was diagnosed with cancer at age 80, and had the event at age 85. Patient with ID 102 entered the study at age 76, was diagnosed with cancer at age 79, but had not experienced the event by the last follow up at age 88.
ID  Tstart   Tstop  cancer  event
101     75      80      0       0
101     80      85      1       1
102     76      79      0       0
102     79      88      1       0

The cancer column represents the cancer status during the indicated time period. The event column represents whether the "ability decline" event occurred (1) or not (0) at the end of that time period. I used the term event to avoid ambiguity in use of the word "status," which might otherwise represent either the "cancer" status or the "ability decline" status.
Comment: I think what you have explained makes sense and considering cancer status as a time-varying covariate is the correct way to go. But since I am not very familiar with doing this. Could you please clarify more? Then should I split kind of based on cancer = 1 and cancer = 0? I am just a little bit confused about what I have done before and how to change it to what you explained.
Comment: and this should be only done for Noncancers that are diagnosed later? and add two line for these individuals, kind of breaking them. Right?
Comment: @ EdM could you please see my update and what I changed for considering cancer as time-varying covariate is exactly what you mentioned?


Can I use onpopstate with IE?

Question: I'm currently (happily) using jquery to bind a ajax request function to the window.onpopstate event in non-IE browsers.  However, IE never hits my doAjax function.
    // Bind a function to the popstate event to execute ajax requests
    // this allows request to occur on back/fwd browser navigation
    window.onpopstate = doAjax;

Anyone know if there's a way to make IE 8/9 play nice somehow?
Comment: I think `pushState` or `replaceState` functions can trigger this event. When do you expect IE will trigger this event?
Comment: `pushState` / `onpopstate` are not supported on IE < 10.
Comment: @Václav: I'm using the History jquery library to update the url on new ajax page loads. My goal is to fire an ajax page load event any time the url changes so that a user can return to the previous ajax 'page' when they click the back button.
Answer: The solution I have arrived at is to bind both onpopstate and onhashchange to the desired handler.
    // Popstate: load ajax
    window.onpopstate = handlePageWipe;

    // And onhashchange for IE
    if( jQuery.browser.msie ) window.onhashchange = handlePageWipe;

I am using the History jquery library to update the url as I make ajax changes to the page.  Unfortunately, and predictably, IE hasn't caught up and there seems to be no way to alter the url with JS.  History falls back to updating the url's hash state in IE, so this serves my initial goal of binding a url state change to a handler in IE.
Of course this opens up another can of worms because I now have to handle both url changes and hash changes.  Ah well, so it goes...
EDIT:
As @linus points out, we should be charitable and avoid browser detection to give IE an opportunity for reform.
Answer: I would prefer to do like this:
if (window.onpopstate != undefined) {
    window.onpopstate = locate;
} else {
    window.onhashchange = locate;
}

so if "msie" add this functionality you do not depend on old code
Comment: actually it should be window.onpopstate !== undefined
Answer: I'm on a project that uses jQuery history plugin, copyrighted by Takayuki Miwa. The client code initialises the library with $.history.init(callback, ...).
That callback is invoked each time you navigate to/refresh the page, and also each time the page content is updated by means of AJAX, whether for clicks, history back, history forward.
If you are using that same library, you could do the same in order to have code invoked when page content changes, thus dropping the onpopstate/onhashchange thing.
If you are using the more recent History.js from B A Lupton plugin, there's a statechange event you can bind to.
Also, bear in mind that even onhashchange is supported "only" from IE8.
HTH
Answer: this solved me:
if( navigator.userAgent.toLowerCase().indexOf('msie ') )
    window.onhashchange = locate
else
    window.onpopstate = locate

Can I use onpopstate with IE?


How to show that the number of triangles in G is $\frac{1}{6}Tr(A^3)$

Question: Let's suppose we have a graph $G$. How should I show the that the number of triangle of in $G$ is $$\frac{1}{6}Tr(A^3)$$ where A is the adjacency matrix of $G$? I have no idea what should I do first.  Thank you in advance
Answer: Let $A$ be the adjacency matrix. Then $A_{ij}=1$ iff there is an edge connecting $i\leftrightarrow j$. With this in mind, $i\rightarrow j \rightarrow k$ is a triangle iff $A_{ij}A_{jk}A_{ki}=1$. Now sum over $ijk$ and get ${\rm tr}\left(A^{3}\right)$. But wait, you over-count this by exactly the number of permutations on $ijk$, which is $3!=6$. Thus the number of triangles is
$$\text{Number of triangles}=\dfrac{1}{6}{\rm tr}\left(A^{3}\right)$$
Answer: The $i,j$ entry of $A^3$ gives us the number of length three walks $iklj$.
If $i=j$ (and the graph has no loops), such a walk $ikli$ necessarily has $k\ne i$ and $k\ne l$, i.e., is a cycle of length $3$. As the trace is the sum of the diagonal entries, it counts such cycles - but each is counted six times, namely for each starting vertex and walking direction.


Generator of group does not give 1 when raised to power of size of group

Question: According to this, the order of an element of a group is as follows.

The order of an element $a$ of a group, sometimes also called the period length or period of $a$, is the smallest positive integer $m$ such that $a^m = e$, where $e$ denotes the identity element of the group, and $a^m$ denotes the product of $m$ copies of $a$.

I've been asked to show that $34$ is a generator of $\mathbb{Z}^{*}_{659}$
We know that an element is a generator of a group when its' order is equal to the order of said group.
So, given that $34$ is supposedly a generator, its' order will be $659$ (size of $\mathbb{Z}^{*}_{659}$), where $34^{659} \pmod{659} = 1$, however, when I do $34^{659} \pmod{659}$ using modular exponentiation, I get $34$ and not $1$.
So how is $34$ a generator of $\mathbb{Z}^{*}_{659}$ ??
EDIT
$\mathbb{Z}^{*}_{659}$ is the multiplicative group of integers modulo $659$.
Comment: Formatting note:  try `\bmod` or `\pmod`
Answer: The size of $\mathbb Z_{659}^*$ is $658$.  $0$ is not an element of the multiplicative group; it does not have an inverse.
$34^{658}\equiv1\bmod 659$.
Comment: Thanks, I am an idiot.
Comment: That's why $34^{659}\equiv34$


Details about "fingerprinting" algorithms for groups?

Question: where can I find details about "Fingerprinting" algorithms (to test whether two groups are non-isomorphic)

"'Fingerprinting': For every group $G_1,…, G_r$ evaluate various
  isomorphism-invariant properties. Split the list up into several sublists
  such that every sublist contains the groups with certain properties
  only."

—Page 405 from Handbook of Computational Group Theory
Comment: I vote against closing this question. If you plan to vote to close it, and this counter-vote has not yet been cancelled, please, instead of voting, add a comment noting that you have cancelled my counter-vote.
Comment: If you don't want this to be closed, you need to be much more precise about your question. Right now, it's so vague as to be unanswerable.
Comment: Also, I think the answer given on your previous question is adequate. (The algorithms you have found are probably already well-known and inefficient.)
Comment: I also disagree with close votes.
Answer: Handbook of Computational Group Theory says "for a more detailed description, consult Hans Ulrich Besche and Bettina Eick, "Construction of Finite Groups", Journal of Symbolic Computation, vol.27 (1999), p.387–404". Have you tried that?
Comment: The methods described in that paper were not really designed as general non-isomorphism testing algorithms, they were more of a collection of heuristic tests for handling the very large sets of groups that arose during the generation of the small groups (up to order 2000). With a large number $n$ of groups of the same order, even when testing whether a given pair is isomorphic is quick, you want to avoid having to do $\binom{n}{2}$ of these tests. Hence the quick fingerprinting procedure for splitting the large set into smaller subsets.
Comment: The idea here is this: You have $n$ things, in this case groups, and some of them are identical.  You can easily compare any two to see if they are identical, but to sort them into families of identical things, you would have to compare each object with each other, a total of $(n^2-n)/2 \approx n^2/2$ comparisons. If you could pre-sort the objects into $k$ classes, each of size $n/k$, such that two objects in different classes were *never* identical, you would need only compare objects within each class, a total of approximately $k\cdot (n/k)^2/2 = n^2/2k$ comparisons, only $1/k$ as many.
Comment: yes , but it looks like "Fingerprinting" ( as its meaning ) is behind the scenes
Comment: please more information about the topic Professor Holt

Details about “fingerprinting” algorithms for groups?


Scikitlearn: Why are hyperplane coefficients not available if kernel is not linear

Question: I am interested in learning the math behind support vector machines. So far, I understand that SVMs attempt to find hyperplanes that maximize the margin distance between support vectors associated with the classes that you are trying to classify. I also understand that using a kernel allows one to project the data points onto higher dimensions to help classify data that is not linearly separable. I am playing around with an SVM using the Scikitlearn Python library and I found that the .coef_ attribute returns the normal vectors associated with the hyperplanes that are calculated in the fitting procedure. I am interested in looking at these normal vectors to get a sense of how much each feature contributes to calculating the hyperplanes. However, it seems that the normal vectors are only available if you use a linear SVM. I don't see why the normal vectors wouldn't be available if a kernel is used. From what I understand, you are just finding hyperplanes in a space with more dimensions than the number of features in your original dataset. Shouldn't you be able to get the normal vectors to those hyperplanes as well? What am I missing here?
I fully appreciate any insight into this question as I am still a novice when it comes to the math behind a lot of machine learning techniques.
Thanks!
Answer: Your intuition is on the right track. The usage of kernels is what makes SVMs so nice/convenient, since (very informally) it gives us the ability to build a classifier in some higher-dimensional space implicitly without having to operate in that higher-dimensional space, so I can understand why you'd have this question.
The short answer is, theoretically, sure, you could recover the coefficients defining your separating hyperplane if, given your feature map $\phi: \mathbb{R}^n \to \mathbb{R}^p$, you know the explicit form of $\phi$. As an illustrative example, consider the polynomial kernel of degree 2, i.e., $K(x^{(i)}, x^{(j)}) = (x^{(i)\top} x^{(j)})^2$ for some  $x^{(i)}, x^{(j)} \in \mathbb{R}^n$. Some algebra shows that
$$(x^{(i)\top} x^{(j)})^2 = \sum_{k=1}^n \sum_{\ell=1}^n (x^{(i)}_kx^{(i)}_\ell)(x^{(j)}_k x^{(j)}_\ell),$$
which is an inner product between two feature maps of $x^{(i)}, x^{(j)}$. That is, $K(x^{(i)}, x^{(j)})$ can be written in the form $\phi(x^{(i)})^\top \phi(x^{(j)})$, where $d = n^2$ for this case. Further examples of such kernels can be found here, as well as criterion for what constitutes a "valid" kernel.
In practice, I'm not completely sure what the use of seeing the hyperplane coefficients in that higher-dimensional space is.
But if you really, really want the coefficients for your hyperplane in that higher dimensional space, then they can be computed in terms of the coefficients of the dual optimization problem. That is; for coefficients $w, x^{(i)} \in \mathbb{R}^n$, class labels $y^{(i)} \in \{-1, +1\}$, and dual variables $\alpha^{(i)} \in \mathbb{R}^+$, and $i \in \{1, \dots, M\}$:
$$w = \sum_{i=1}^M \alpha^{(i)} y^{(i)} \phi(x^{(i)}) $$
The derivation follows from taking the dual of the primal SVM objective, constructing the Lagrangian, and minimizing in terms of the primal variables (i.e., the hyperplane coefficients) for some fixed $\alpha^{(i)}$.
However, some feature maps are such that $p = \infty$ (i.e., your kernel projects features into an "infinite dimensional" space, which is called a Hilbert space), such as the RBF/Gaussian kernel, which makes it a bit hard to compute the above. To see how this is possible, consider the Gaussian kernel $K(x^{(i)}, x^{(j)}) \triangleq \exp(-\frac{1}{2}\lVert x^{(i)} - x^{(j)}\rVert_2^2).$ We can expand the squared norm term and, recalling that $\exp(z) = \sum_{k=0}^\infty z^k/k!$, we end up with something like
$$\sum_{k=0}^\infty \frac{(x^{(i)\top} x^{(j)})^k}{k!} \exp(-\lVert x^{(i)} \rVert_2^2 / 2) \exp(-\lVert x^{(j)} \rVert_2^2 / 2).$$
Using the multinomial theorem to expand the $(x^{(i)\top} x^{(j)})^k$ term, you can verify that we end up with a valid inner product, giving us a kernel. Alternately, you can analyze each $k$ separately, and, noticing that each term of the infinite summation for fixed $k$ is a rescaled polynomial kernel of degree $k$, interpret the RBF kernel as an infinite sum of polynomial kernels. Thus, we can't really recover the true hyperplane parameters. If you haven't seen this before, it might be surprising that you can (informally) implicitly work in an infinite-dimensional feature space.
Comment: Thank you for your explaination! I need to read more about the dual optimization problem and Hilbert spaces to figure out if recovering the hyperplane weights is feasible/possible for the problem I'm working on.
Comment: I don't think you need to know the details of the dual problem for your question, though it would certainly supplement your understanding of SVMs. The feasibility of recovering the weights should solely depend on the kernel used, since it specifies your feature map, right? I'm still unsure why you need the hyperplane parameters since the image o the feature fmap isn't inherently "meaningful" per se, but feel free to pose a new question if I'm missing something.
Answer: What you're missing here is that the representation of kernels as the sums of nonlinear features is not known. What's known is that these kernel are likely to be representable as those new features, so we use them.
Details. The dual problem involves minimizing a quantity $$\min_\alpha \left[\sum_{ij}y_i\alpha_i\left(\sum_k\phi_k(x_i)\phi_k(x_j)\right)\alpha_jy_j+\dots\right]$$
Where $\phi_k(x)$ is a set of nonlinear features created on the data $X$. So, for some sets of these features it is possible to capture these sums with kernels $K(x_i,x_j)=\sum_k\phi_k(x_i)\phi_k(x_j)$. Then the dual problem becomes $$\min_\alpha \left[\sum_{ij}y_i\alpha_iK(x_i,x_j)\alpha_jy_j+\dots\right]$$
Once the kernel is found we don't need the new features $\phi(x)$ themselves and can proceed working with just a kernel. Moreover, we don't even need to know these new features, and as a matter of fact we usually don't know them. We know the conditions on the functions K(.,.) that would make them the valid kernels, so we can almost arbitrarily try functions as kernels so long they satisfy the conditions, then we don't bother looking for the features.
The reason for using kernels is that they represent rich set of new nonlinear features but can be relatively fast to calculate. As you saw the kernel represents a dot product $\sum_k\phi_k(x_i)\phi_k(x_j)$ where $\phi_k(.)$ is often an infinite set. Instead of messing with dot products of infinite sets of function that potentially can be expensive to compute we get the  result much faster with a kernel.


How to write c# console app that behave like the telnet command on cmd windows?

Question: I want to programmatically sending (and processing the response) message. Instead of open cmd and type in the command manually:

connecting to the server by using command telnet [server_address] [port_number]
send a message
processing the response and send a following message
repeat step 3 ...

How can I achieve this by using c#?
Comment: This is a very vague question. What do you mean by "behave like the telnet command"? In what way should it behave like the telnet command? What do you want your application to actually *do*?
Comment: Based on a description you need regular console application. What exactly you want to automate?
Comment: Probably you looking for smtng like this:
http://stackoverflow.com/questions/14359850/executing-commands-by-using-telnet-in-c-sharp
Comment: so, basically you wish for an application that listen to a certain port and do something once someone send it a message..?
Comment: @BagusTesa I was given a server that I can connect to and send/receive message using telnet. I want to automate the process instead of manually typing the command. I don't know how telnet works, that why I can't tell exactly what I need.
Comment: @vladimirpanf that is what I need, if you post your comment as an answer, I can vote for it
Answer: Telnet library url: http://www.codeproject.com/KB/IP/MinimalisticTelnet.aspx
Previous thread: Executing commands by using Telnet in C#
Cheers.


Remote Desktop Connection to Azure Server using Office365 User not working

Question: I do have the following setup:

Windows Server 2016 VM running on Azure Cloud and joined to Azure Active Directory Domain
Office365 user accounts contained in same AAD as machine is joined to
AAD users (not Office365 users)

My problem now is: None of the Office365 users (created in Office365-Portal) except myself can connect to the azure virtual machine via remote desktop - not even other users that are administrators on Office365 and azure.
But: All users that are created in AAD directly (no Office365 licences, created using AAD-Portal, etc.) can connect via RDP without any problem.
On client side, I tried with azure joined Windows 10 devices, but also with non azure joined Windows 7/10.
Any ideas?
Thanks for your kind help.
Comment: Windows server 2016 can't join to AAD, do you mean Azure AD domain service? your Azure AD is basic or premium?
Comment: Hi Jason, yes, I mean Azure AD domain service. The Azure AD is basic.
Comment: As far as I know, Azure AD and O365 user have same permission, does O365 users and AAD users with same suffix?
Comment: @JasonYe-MSFT If you mean "domain" with "suffix": Yes, it is the same for both user types.I also checked group memberships and tried adding the users as local administrators and remote desktop users on the target machine - unfortunately no change.
Comment: Azure Active directory domain service's users only sync from Azure AD, does your AAD users and o365 users in the same group?
Answer: Any user in Azure AD (regardless if Office365 user or not) needs to change the password after Azure Domain Services have been activated to initiate password sync (see this link).
Thanks Jason for pointing into the correct direction.
Comment: Thank you for your share, please accept it as an answer so that other community will be benefited, thanks:)
Answer: We should add users to AAD DC Administrators group in Azure AD.
Members of AAD DC Administrators can use Remote Desktop to connect remotely to domain-joined machines.

Create an administrative group in your Azure AD directory. This
  special administrative group is called AAD DC Administrators. Members
  of this group are granted administrative permissions on machines that
  are domain-joined to the managed domain. On domain-joined machines,
  this group is added to the administrators group. Additionally, members
  of this group can use Remote Desktop to connect remotely to
  domain-joined machines.

More information about it, please refer to this link.
Hope this helps.
Update:
The root case is that, we should enable password synchronization then change the password.

A few minutes after you have changed your password, the new password
  is usable in Azure Active Directory Domain Services. After about 20
  minutes, you can sign in to computers joined to the managed domain
  using the newly changed password.

More information about change password, please refer to this link.
Thanks for Aaron's share.
Comment: The provided link was partially useful as it pointed the fact out, that users that existed BEFORE activation of Azure AD domain services need to change their password to be able to use domain-joined machines.
After doing so, Office365 users are able to login via RDP, even if they are NOT member of any special group.
Thanks Jason.


What is the distribution of max-min for a Gaussian distribution

Question: For a process N(t), where at any instance of t=T0, the distribution of N(T0) is Gaussain with mu=0:

What is the distribution of max(N(t))-min(N(t))?
From my simulation, it has some non-zero positive mean value and a waveform that looks like Gaussian but has a longer tail on the right side:
Comment: @JarleTufto that looks like an answer in itself.
Comment: Does this answer your question? [Independence of Sample mean and Sample range of Normal Distribution](https://stats.stackexchange.com/questions/151096/independence-of-sample-mean-and-sample-range-of-normal-distribution)
Comment: This seems quite similar to the studentized-range distribution (see https://en.wikipedia.org/wiki/Studentized_range_distribution#Special_form_for_normal_data), but I'm not quite confident enough to put this in an answer ...
Answer: Working with the standard normal case for simplicity, the joint density of the minimum and maximum is
$$
f_{X_{(1)},X_{(n)}}(x_1,x_2)=\frac{n!}{(n-2)!}\phi(x_1)\phi(x_2)[\Phi(x_2)-\Phi(x_1)]^{n-2},
$$
for $x_2>x_1$.  The joint density of the linear transformation
\begin{align}
Y_1&=X_{(n)}-X_{(1)}, \\ Y_2&=X_{(n)}
\end{align}
becomes
\begin{align}
f_{Y_1,Y_2}(y_1,y_2)
  &=f_{X_{(1)},X_{(n)}}(y_2-y_1,y_2)
\\&=\frac{n!}{(n-2)!}\phi(y_2-y_1)\phi(y_2)[\Phi(y_2)-\Phi(y_2-y_1)]^{n-2}
\end{align}
for $y_1>0$.  Hence, the marginal density of $Y_1$ is
\begin{align}
f_{Y_1}(y_1)
  &=\int_{-\infty}^\infty f_{Y_1,Y_2}(y_1,y_2)dy_2
\\&=\frac{n!}{(n-2)!}\int_{-\infty}^\infty\phi(y_2-y_1)\phi(y_2)[\Phi(y_2)-\Phi(y_2-y_1)]^{n-2}dy_2.
\end{align}
At least for $n=2$ and $n=3$ but perhaps also for larger $n$, this integral has an analytic solution.  Resorting to numerical integrations using the R code
<code>dminmax <- function(y1, n) {
  g <- function(y2)
    dnorm(y2-y1)*dnorm(y2)*(pnorm(y2)-pnorm(y2-y1))^(n-2)
  res <- integrate(g, -Inf, Inf)
  n*(n-1)*res$value
}
dminmax <- Vectorize(dminmax)
curve(dminmax(x,5), add)
</code>
produces the plot
Comment: I'm a bit confused in places notationally if you are trying to provide a general solution or if you are treating an $n=2$ special case.


How can I tell if assertions are turned on in Swift?

Question: Let's say I have a function like this:
func findFooById(id: String) -> Foo {
    if let foo = fooList[id] {
        return foo
    } else {
        assertionFailure("Couldn't find a foo with id = \(id)")
    }
}

In debug builds, I want my assertion to trigger so I'm clued into the fact my server is sending me inconsistent data. But in release builds, I want to return an empty foo (return Foo(id: "", name: "", magic: nil)) to keep my UI consistent.
(I'd prefer not to redefine findFooById to return Foo?, as that would force me to deal with nil in every caller. Displaying a blank object is good enough for this rare case.)
How do I achieve this?
Comment: Just putting the `return` statement on the line after the `assertFailure` gives me a "Will never be executed" warning; I could turn this off with a #pragma in Objective-C, but I'm not sure how to do this in Swift.
Comment: I recently read a question here where this was explained. There is some keyword for it. Can't recall the thread :-/
Comment: Found it: put @noreturn in front of the func.
Comment: Does that help though? In the assertionFailure() case @noreturn is implied and that's fine, but when assertions are off and assertionFailure() is a no-op, but that gives me the "Will never be executed" warning on the return that I want in that case.
Comment: Ups. Got it the wrong way. The warning is **because** of the @noreturn.
Comment: According to the API docs, `assertionFailure()` is ignored in optimized builds, so that you can simply add `return Foo(...)` after the assertion. But practically, I found that `assertionFailure()` throws a runtime exception even in optimized builds.
Comment: @MartinR Indirectly my question http://stackoverflow.com/questions/29143855/nil-optional-does-not-crash-in-release is related
Answer: As mentioned in another Stack Overflow answer, you can set flags based on being in Debug/Release modes, which would allow you to do:
#if DEBUG
    assertionFailure("Couldn't find a foo with id = \(id)")
#else
    return Foo()
#endif

However, since assertionFailure is a no-op in optimised builds (which release builds are by default), you should be able to do:
func findFooById(id: String) -> Foo {
    if let foo = fooList[id] {
        return foo
    } else {
        assertionFailure("Couldn't find a foo with id = \(id)")
        return Foo()
    }
}

Comment: That's what I thought, but I found that it throws a runtime exception even in optimized builds, at least with Xcode 6.2. Could be a Swift bug.
Comment: I am not 100% sure this is correct. The way I read http://blog.krzyzanowskim.com/2015/03/09/swift-asserts-the-missing-manual/, it's the Swift optimisation level that controls whether asserts are compiled in, **not** DEBUG/RELEASE. We are running our release builds with -Onone because the Swift optimiser is broken.
Comment: Yes, in my linked page it states "In optimized builds this is a noop", so technically it is not based on debug/release, but by default it is. I will update my answer to make this more clear
Comment: Note comment above: when I implement your second suggestion, I get a compiler warning I can't turn off.
Comment: `func testing() -> [Int] {
        assertionFailure("Failure in non-optimised mode")
        return [Int]()
    }` works for me in both debug and release modes. In which mode are you seeing the error?
Comment: I'm getting the "Will Never Be Executed" warning in debug, but I've got Swift optimisations set to -Onone for debug and release.
Comment: If you're using `-Onone` in both then you may have to use the first solution I provided (the `#if DEBUG`) one
Comment: The "correct" solution in my mind is your second one, but with a way to turn off that compiler warning in all cases (or for the compiler to be smart enough to not emit the warning.) I'll file a bug.
Comment: I don't think it's a bug; it's giving you the error because you're not compiling with `-O`, but rather `-Onone`. Maybe you could make your own version of `assertionFailure` that has the `#if DEBUG` check in it?


How to load and display a view with Ajax in Drupal 7?

Question: This is the first time I've ever tried to load a view using Ajax in Drupal7 and I would be appreciated if you help me from scratch. I've spent hours to learn how to do this but I still failed!
I created a view called image_gallery, it has three blocks called hd,tablet and phone and it displays set of images.I created a tab and I want to display and load these blocks (generally views) with Ajax. this my HTML:

HD

Tablet

Cellphone

                <?php print views_embed_view("image_gallery","hd") ?>

I set the Use Ajax to "yes" in the views UI. this is my jQuery code:
$("#image_gallery_tab ul li").click(function(){
        var id = $(this).attr("id").slice(-1);
        $(".igc").css("display","none");
        if(id==2)
            {
            $.ajax({
                url: Drupal.settings.basePath + 'views/ajax',
                type: 'POST',
                dataType: 'json',
                data: 'view_name=image_gallery&view_display_id=tablet', // Pass a key/value pair.
                success: function(response) {
                  $("#igc2").innerHTML=response.display;
                },
                error: function(data) {
                 alert('An error occured!');
                }
              });
            }
    });

but it displays nothing. what is wrong here and what shall I do?
thanks
Comment: I use your code and it worked great but there is a small problem. After switching between tabs jquery actions does not work. I have two views of comments in two tabs, when I switch between tabs I can not vote comments or reply comments any more. I have used ajax comments, votingAPI and rate module too. None of them work with ajax after switching between tabs. Got it?
Comment: @shekoufeh May be the problem is with your JS code. Since when a new object is created, you need to define **a-live** functions in order to work with new objects
Comment: Related: https://drupal.stackexchange.com/questions/70079/using-ajax-to-access-the-content-of-a-view
Answer: For anyone who ends up here looking for an answer, this is how you do it. First you need to enable "Use AJAX" under Other settings in the view and take note of the "Machine Name" as that is your display ID:

Then, this is how you pull it with JS using jQuery ajax:
$.ajax({
  url: Drupal.settings.basePath + '/views/ajax',
  type: 'post',
  data: {
    view_name: 'your_view_name',
    view_display_id: 'page', //your display id
    view_args: VIEW_ARGUMENT_HERE, // your views argument(s)
  },
  dataType: 'json',
  success: function (response) {
    if (response[1] !== undefined) {
      console.log(response[1].data); // do something with the view
    }
  }
});

Comment: where shuold I put this code? do you write both html and js in a block and load it in a page?
Comment: Note that `view_args` has to be a string.
Comment: will that work even if view does have only block display without any page display?
Comment: finally got it worked!. things missing in your answer is 1. what if drupal is under sub directory 2 what if clean url is not enabled(mod_rewrite). it won't work at all(404 not found). After struggling so many hours finally I found it.
Comment: Link to some documentation would be nice :)
Comment: AJAX isn't getting the TITLE of the Views Block.  I can prepend it but need it to be dynamic because using multiple translations on the site. Is there any way?


"Object is not defined" in TabView

Question: Trying to get this to work in Qt version 5.9
It seems that whenever I create an object within a QML Tab it is unrecognizable by the parent object (or any of the parent's parents, and so on). How do I get the parent objects to recognize the object in the Tab? Or, if impossible, then what is a work-around to call the function of the object within the Tab?
I've boiled down the code to this simplified example:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    Rectangle {
        id: myFunctionCaller

        Component.onCompleted: {
            myParent.myFunction();
            myChild.myFunction();
            myGrandChild.myFunction();
        }
    }

    TabView {
        id: myParent
        property Rectangle grandchild: myGrandChild
        onGrandchildChanged: console.log("Parent recognizes GrandChild");

        function myFunction() {
            console.log("I'm the Parent");
        }

        Tab{
            id: myChild
            property Rectangle grandchild: myGrandChild
            onGrandchildChanged: console.log("Child recognizes GrandChild");

            function myFunction() {
                console.log("I'm the Child");
            }

            Rectangle {
                id: myGrandChild
                function myFunction() {
                    console.log("I'm the GrandChild");
                }
            }
        }
    }
}

I expect this output:
I'm the Parent
I'm the Child
I'm the GrandChild
Parent recognizes Grandchild
Child recognizes Grandchild

However, I get this output:
I'm the Parent
I'm the Child
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.

The error occurs on these lines:
myGrandChild.myFunction();
onGrandchildChanged: console.log("Parent recognizes GrandChild");
onGrandchildChanged: console.log("Child recognizes GrandChild");

Answer: The Tab is a subclass of Loader, so the Rectangle is not created until the Tab becomes active.

Tabs are lazily loaded; only tabs that have been made current (for example, by clicking on them) will have valid content. You can force loading of tabs by setting the active property to true

Thus the id: myGrandChild is only available within the (source)Component automatically created in the Loader.
The solution is, to activate the Tab and address the child with myChild.item
(Not tested)
Comment: So can I assume that the myGrandChild tab is active by default, since it is the only tab in the myChild TabView? If this is the case, then I should be able to call mChild.item.myFunction() correct? I tried this and it hasn't made a difference, I still get "myGrandChild is not defined"
Comment: If you really call `myChild.item.myFunction()` you do not reference myGrandChild. This error has to occure from one of your lines, where you try to reference the `Rectangle` through the `id: myGrandChild` - which is out of scope for all objects but the `Rectangle` itself.
Comment: `myGrandChild.myFunction();` -> `myChild.item.myFunction()`, in `TabView`: `property Rectangle grandchild: myGrandChild` -> `property Rectangle grandchild: myChild.item`, in `Tab`: `property Rectangle grandchild: myGrandChild` -> `property Rectangle grandchild: item`
Comment: You're absolutely right, there was a typo on my end. Thanks!
Comment: Allow me to pose one more question for you: If I visually am looking at Tab1, and something I click should call a function housed in Tab2, even though Tab1 is the active tab (and Tab2 is not) is it still possible to call a Tab2 function? Or is this a bad general practice?
Comment: I would argue, it would be better to seperate the data on which you might act (model) from the tab (view) and call the function on the model, that will change the displayed data in tab2 once this becomes active. As such you are able to turn the tabs inactive without loss of data.

"Object is not defined" in TabView


basic c++ memory allocation and strlen

Question: int _tmain(int argc, _TCHAR* argv[])
{

 char* myArr = new char[5];

 cout << strlen(myArr) << endl;
 return 0;
}

why does it print out 12 (instead of 5)?
edit: Adding myArr[5] = '\0'; fixes the problem. But it takes memory that isn't mine. Is that ok?
Comment: Try running the same program many times. Sometimes it may print some other value; it could be 0, 4, 7, 16, 19 etc..
Comment: When you allocated `char[5]`, your application "owns" 5 bytes, so setting `myArr[3]` (the 4th byte) to zero is perfectly valid, although the first 3 bytes are still not initialized.
Comment: Doing myArr[5] is writing past the end of the array. You are screwing up another data structure (which may or may not lead to a crash). PS. Have you looked at std::string. It does all the memory management for you.
Answer: The memory is uninitialized.  It has "random" data on the heap, so there just happens to be 12 non-zero bytes in it before the first zero (and it is reading past the allocated length).
Allocated memory does not contain (from the application's standpoint) length information.  If you put a 0 in the first byte, then the length would report as zero:
myArr[0] = 0;

If you declare it as follows (with the memory on the stack), the sizeof operator will give the "expected" value of 5.  And as delnan points out (thanks), it is important to note that sizeof is not returning the length of the array but rather the number of bytes.
char myArr[5];
cout << sizeof( myArr ) << endl;

Comment: The second trick won't work for arrays of T when `sizeof(T) != 1`. Use `sizeof(arr) / sizeof(arr[0])`.
Comment: That's a good point.  I will clarify that the sizeof operator returns the number of bytes (not the number of elements).
Answer:
why does it print out 12 (instead of 5)?

Because you invoked undefined behavior , you called strlen() on uninitialized data, so anything could happen.
strlen() expects a c string, that is a sequence of char's that end with a 0 byte.
your new char[5]; just returns memory that's not initialized and not suitable to pass to strlen() until you place a string in there.
Answer: strlen searches for the first null character to determine the length. Since this memory has only been allocated, and not initialized, the first null character could be anywhere.
Answer: strlen returns the length of a null-terminated string. new char[5] returns a pointer to a memory block big enough to store a null-terminated string 5 chars long (4 characters + null terminator). However you did not actually put a string there!
Comment: 4 characters long. You need to use the 5 location for the null terminator.

basic c++ memory allocation and strlen


Calling PHP from C program

Question: I have a php function that I want to run from a C program. The file is '/path/auth.php' and the function is authenticate($user, $pwd). The function will echo either a 1 or 0 if a user has authenticated properly. I need to get this result back into the C program and then run other code based on the results. How should I go about it?
Comment: run how? via http request, or execute the php as a command line script?
Comment: I would just like to run it as a command line script.
Answer:
Add PHP to your environment variable PATH
The command to execute your script is php path/auth.php
Follow this link to write your c code

Calling PHP from C program


Hide Workflow Tab For Given State

Question: I am developing moderation workflow using Workflow modeule. I have created different states for that. And using rules module I am putting node into one of the state based on certain event. It is working fine.
Now to emulate the Moderation process, I wanted to hide workflow tab (that appears on node page) when node is in certain state, and to display tab only when node is in one of the given states.
Is there any way I can achieve this?
-- Many thanks for your time.
Answer: Solved it using hook_menu_alter and adding custom module. I have modified the access callback function to suit my needs.
Here is my code, may help user having same task:
<code>    function mymodule_tab_menu_alter(&$items) {
        $items['node/%node/workflow']['access callback'] =
        'custom_workflow_tab_node_access';
    }

    function custom_workflow_tab_node_access($node = NULL) {

    global $user;

    if ($workflow = workflow_get_workflow_type_map_by_type($node->type)) {
        if ($workflow = workflow_get_workflows_by_wid($workflow->wid)) {
            $roles = array_keys($user->roles);
            if ($node->uid == $user->uid) {
                $roles = array_merge(array('author'), $roles);
            }
            $allowed_roles = $workflow->tab_roles ?
            explode(',', $workflow->tab_roles) : array();

          if (user_access('administer nodes') || array_intersect($roles, $allowed_roles)) {

      /* This is additional Condition*/

      if ($node->type == "article") {
     $current_state = workflow_get_workflow_states_by_sid(workflow_node_current_state($node));
                    if ($current_state->state == "State_name") {
                        return FALSE;
                    } else {
                        return TRUE;
                    }
                } else /*End Additional Condition */{
                    return TRUE;
                }
            } else {
                return FALSE;
            }
        }
    }
    return FALSE;
}
</code>
As above in custom access callback, I have used the same code, just added the additional condition and it solved my issue. :)
-- Thanks

Hide Workflow Tab For Given State


Criterion for unramified prime in number fields

Question: Let $L/K$ be an extension of number fields, $\mathfrak{q}$ be a prime in $\mathcal{O}_L$ and $\mathfrak{p}=\mathfrak{q}\cap\mathcal{O}_K$. If $\mathfrak{p}$ generates the maximal ideal $\mathfrak{q}\mathcal{O}_{L,\mathfrak{q}}$ of the localization ring $\mathcal{O}_{L,\mathfrak{q}}$, then how to prove the ramification index $e(\mathfrak{q}/\mathfrak{p})$ is $1$?
Thanks in advance.
Answer: Let $\mathfrak q = \mathfrak q_1, ... , \mathfrak q_g$ be all the primes of $\mathcal O_L$ lying over $\mathfrak p$.  The definition of the ramification index $e = e(\mathfrak q /\mathfrak p)$ is
$$\mathfrak p \mathcal O_L = \mathfrak q^e \mathfrak q_2^{e_2} \cdots \mathfrak q_g^{e_g}$$
as ideals of $\mathcal O_L$.  If we localize these ideals to $\mathcal O_{L,\mathfrak q}$, we have
$$(\mathfrak p \mathcal O_L)_{\mathfrak q} = \mathfrak p \mathcal O_{L,\mathfrak q}$$
$$( \mathfrak q^e \mathfrak q_2^{e_2} \cdots \mathfrak q_g^{e_g})_{\mathfrak q} = \mathfrak q^e \mathcal O_{L,\mathfrak q}$$
since the other prime ideals $\mathfrak q_i$ generate the unit ideal in $\mathcal O_{L,\mathfrak q}$.
Comment: Also in OP's setting $\mathfrak p \mathcal O_L$ is maximal thus $=\mathfrak{q}$


Emscripten canvas + jQuery - toggle focus

Question: I have an HTML page roughly divided 30% - 70% into two vertical columns. The left column contains a chat feed (handled via Node and Socket.io), and the right column contains an emscripten-generated canvas (with the ID of canvas). The canvas contains a basic 3D world that the user can navigate using standard first-person controls (WASD for movement, mouse to 'look').
By default, the canvas swallows all keyboard events. I've fixed this with the following code in the canvas initialisation procedure:
Module.preRun.push(function () {
    ENV.SDL_EMSCRIPTEN_KEYBOARD_ELEMENT = "#canvas";
});

This allow me to manually focus on the chat box, type a message, and submit it.
The issue I'm running into is that once the chat message has been submitted, I try and return focus to the canvas with the following code (to allow the players to navigate the 3d world with WASD):
 $('#canvas').focus();

This nominally returns focus to the canvas, but mouse and keyboard movement does not work. Oddly, clicking off the tab/browser window and then into the canvas seems to work - focus is returned to the canvas, and I can navigate once more. Manually calling $(window).blur().focus() doesn't do the trick.
Does anyone know how to force focus back to the canvas once a chat message has been sent?
-- UPDATE --
I've added a text input field (with the ID of hiddenField) behind the canvas and I'm using the preRun function to assign key events for the canvas to that field (canvas wasn't working consistently for some reason).
This works fine until the user clicks off the canvas - for example, into the chat field - whereupon the canvas stops responding to any keyboard or mouse input, even though I'm triggering focus back onto the hiddenField (and can see that it's getting it).
It seems that doing anything on the page conflicts with emscripten's focussing behaviour (tied to the window object, I believe) and prevents the canvas from regaining focus.
Surely there's some way of aloowing the emscripten canvas to live alongside other HTML elements?
Answer: You need to make canvas object focusable by adding tabindex="0" attribute.
Then it should be possible to trigger the focus event properly:
document.querySelector("#canvas").focus()

Answer: The best approach I've been able to find to this - indeed, the only way to get the separate aspects of the application (chat & 3D world) working correctly - has been to embed the emscripten canvas in an iframe and use cross-frame function calls when necessary to trigger actions.
Page
    - chat
    - iframe
        -- emscripten-generated page

It's not my first choice of solution, but it's the only one I've managed to get working.
Answer: EDIT:
View full demo via CodePen (includes links to .js resources)
Structure:
Page
    - emscripten-generated-page
       - loop
    - chat
    - script to handle global key input handlers

You must set tabindex on the canvas element (as noted by luke and described on MDN), attach global event listeners via JavaScript's built-in Document interface and then call .triggerHandler() to ensure that canvas returns to it's default state, governed by click:
var chatInputField = $("#message-input");
var canvas = $("#canvas");

canvas.on("click", function(e){
  return document.addEventListener("keyup", game.toggleKeys);
});

chatInputField.on("focusin", function(e) {
    $('#canvas').attr('tabindex', 0);
    return document.removeEventListener("keyup", game.toggleKeys, false);
});

chatInputField.on("focusout", function(e) {
    $("#canvas").triggerHandler('click');
    chatInputField.attr('tabindex', 0);
});

I've tested this, it works. Here's my app.js file for managing key input (see line 297).
https://gist.github.com/shagamemnon/585df8dd215a949b839f8b02199af31b
A caveat: you must explicitly define the behavior of the the tab key inside the game canvas.


Read structure from file c#

Question: I'm trying to read a structure of a text file in a certain way. The text file is kind of a user-friendly configuration file.
Current structure of file (structure can be changed if necessary):
info1=exampleinfo
info2=exampleinfo2
info3="example","example2","example3"
info4="example","example2","example3"

There is no real difficulty in getting the first two lines, but the latter two are more difficult. I need to put both in two seperate string arrays that I can use. I could use a split string, but the problem is in that in the info4 array, the values can contain comma's (this is all user input).
How to go about solving this?
Comment: Would be much easier to choose a well-defined format that can be readily parsed. For example JSON or YAML.
Comment: Want to know the easiest way to make sure a user generates a file you depend on properly?  Give them a program that will generate it for them.  That way you control the production and the consumption.  Then, if you do want to do something like JSON or just XML that's easy to parse, you can take care of any picky things like quotes, brackets, escape sequences, etc.
Comment: As I said - structure can be changed if necessary. If you could plop an answer down using either of these methods - I'm open for suggestions :)
Answer: The reason you're having trouble writing parser is that you're not starting with a good definition of the file format.  Instead of asking how you should parse it if there are commas, you should be deciding how to properly encode values with commas.  Then parsing is simple.
If this file is written by non-technical users who can't be trusted with a complex format (like json), consider a format like:
info1=exampleinfo
info2=exampleinfo2
info3=example
    example2
    example3
info4=example
    example2
    example3

That is, don't mess around with quotes and commas. Users understand line breaks and spaces pretty well.
Comment: Thanks - I decided to do this.
Answer: I'm 100% in favor of @DavidHeffernan's solutions, JSON would be great. And @ScottMermelstein's solution of a program that builds the output - that's probably your best bet if possible, not allowing the user to make a mistake even if they wanted to.
However, if you need them to build the textfile, and you're working with users who can't be trusted to put together valid JSON, since it is a picky format, maybe try a delimiter that won't be used by the user, to separate values.
For example, pipes are always good, since practically nobody uses them:
info1=exampleinfo
info2=exampleinfo2
info3=example|example2|example3
info4=example|exam,ple2|example3

All you'd need is a rule that says their data cannot contain pipes. More than likely, the users would be ok with that.
Comment: Yeah my problem is that I cannot find a good delimiter that will not be used by the user. Pipes are one of them that tend to be actually used by the users.
Comment: @gdscei how about `╪` symbol. I don't think people use it often.
Comment: It would have to be a keyboard-friendly key to be worthwhile - so if pipes are no good, tildes (`~`) or carets (`^`) are the other ones I've seen, but if you can't find a good delimiter, you're probably best not to try this method. You could start using escape characters like JSON does, or encoding like HTML does, but once you start down that route, you're asking for problems, and would be better off forcing your users to learn how to properly write JSON.

Read structure from file c#


Iptables allow only localhost and gmail

Question: I use this in iptables: (want to allow 25 port only for localhost)
iptables -A INPUT -p tcp -s localhost --dport 25 -j ACCEPT
iptables -A INPUT -p tcp --dport 25 -j DROP

It works perfect, but I stopped to receive forwarded mail (it was working OK before).
I have a rule in mail config -> email sent to email@example.com -> forwarded to my gmail
What should I change/add in my iptables to allow this forwarding but port 25 to be closed for public? Maybe add google IP or something else?
Many thanks!
Answer: If this is a standalone host, I suggest you solve this issue within your mailserver, not a firewall. Gmail has every right to change their IP addresses as they see fit at any time and you'll end up having a broken system. Configure your mailserver to accept mails to addresses you allow and possibly from addresses you allow. Alternatively use something like fetchmail to download your mails from Gmail instead of using a forward.
Answer: You should create iptales rule that allow only gmail ip address on port 25.
Gmail's name server ip addresses are as follows.
188.8.131.52
184.108.40.206

It may be different in your country.
You can find using following command in terminal.

nslookup gmail.com

Iptables allow only localhost and gmail


A coin is flipped 8 times. Assume that the coin is fair

Question: A coin is flipped 8 times. Assume that the coin is fair (that is, all outcomes are equally likely). What is the probability that the number of heads is different from the number of tails?
$n|S|=2^8$
Help me with this problem... please
Answer: We can recognize a random variable $X$ follows the binomial law $\mathcal B(8,\frac12)$ and you look for
$$\Bbb P(X\ne4)=1-\Bbb P(X=4)=1-{8\choose4}\left(\frac12\right)^{4}\left(\frac12\right)^{8-4}=1-{8\choose4}\left(\frac12\right)^{8}$$
Answer: The outcome of the experiment is described by a binomial distribution,
with $n=8$ ($n$ is the number of trials), $p=\frac{1}{2}$ (the probability of getting an head), and $X$ is the number of heads.
Of course, you have the same number of heads and tails when $X=4$. This event occurs probability:
$$P(X = 4) = {8 \choose 4}\left(\frac{1}{2}\right)^4\left(1-\frac{1}{2}\right)^{8-4} = \frac{70}{256}$$
Therefore, the probability that the number of tails and heads is different is just:
$$1 - P(X=4) = \frac{186}{256} \simeq 0.73.$$


Doubt in intersection of reflexive relations on a set A

Question:
If we define 2 reflexive relations(say R and S) a set A, then are not they same?

Reflexive relation means for all $\forall x \in A, (x,x) \in R$. Same is the case for S. Then isn't R = S???
if so we consider the theorem, if R and S are reflexive relations then $R \cup S, R \cap S$ are both reflexive. When we define R and S on same set A, are not they R=S? Then theorem becomes trivial right.
Comment: there may be some elements in $R$ or $S$ besides those of the form $(a,a)$
Comment: $=$ and $\le$ are reflexive but not the same
Comment: $R$ and $S$ both contains the same set, the diagonal $D$. That's all we are given. They might not be the same. For example, D and $A \times A$ are both reflexive.
Comment: Got it sir. Thank you
Answer: No reflexive relations on a set do not have to be the same.
For example consider $$A=\{1,2,3\}$$
$$R= \{(1,1), (2,2),(3,3), (1,3)\}$$ and $$ S= \{(1,1), (2,2),(3,3), (2,3)\}$$   Where both relations are reflexive but they are not the same.
As you notice,the intersecton and the union are reflexive in this example but you have to prove it in general.
Answer: No.  For example, on $\mathbb R$, $=$ and $\le$ are both reflexive relations, but not the same.
Answer: No, they are not necessarily the same. $\forall x\in A: (x,x) \in R$ does not mean that these are the only pairs in $R$, there can be many more, which in turn may or may not be in $S$.
For example the relations "have the same parity" and "have the same remainder when divided by $3$" on $\mathbb{Z}$ are both reflexive. $(1,3)$ is included in the first but not in the second, while $(0,3)$ is included in the second but not in the first (Their intersection is the relation "have the same remainder when divided by 6").
Answer: $R$ being a reflexive relation on a set $A$ implies that identity relation $I = \{(x,y):x=y\}$ where $x,y\in A$, is a subset of $R$, $I\subseteq R$. So if two sets $S$ and $T$ are reflexive relations on a set $A$, then we can only conclude that $I\subseteq S$ and $I\subseteq T$. Obviously, $I\subseteq S\cup T$ and $I\subseteq S\cap T$, therefore both intersection and union of the sets $S$ and $T$ are also reflexive.


how to find out the following statements are true or false?

Question: Let $p(x)$ be an odd degree polynomial and let $q(x)=(p(x))^2+ 2p(x)-2$
a) The equation $q(x)=p(x)$ admits atleast two distinct real solutions.
b) The equation $q(x)=0$ admits atleast two distinct real solutions.
c) The equation $p(x)q(x)=4$ admits atleast two distinct real solutions.
which of the following are true?
i know that all the three are true but donot know how to prove them
Comment: $\;p(x)=x^3-1\;$ already proves (b) to be false.
Comment: As well as $p(x) = x$.
Comment: Did you mean $q(x) =0$?
Comment: The essential thing to note for this problem is that odd degree polynomials are surjective. This implies that if we let $u=P(x)$ and substitute it into any of the above equations, whatever solutions for $u$ we get we can find a (not necessarily unique) corresponding $x$ such that $u$ takes on the value of the solution.
Answer: $$q=p\iff p^2+p-2=(p-1)(p+2)=0$$
If $\;p(x)\;$ is given and fixed the above can easily be false, but if you meant $\;p(x)\;$ can variate then it is true.
Again, as before, this depends on whether $\;p(x)\;$ is fixed or if it is asked whether there exists an odd degree polynomial such that etc. Anyway, if
$$\;\deg p=1\implies \deg qp=3\implies qp-4=0\;\;\text{can have at most three different solutions}$$
With (b) is the same, but $\;x^3-1\;$ is an odd degree polynomial with one single real root.
Answer: a) Let $q(x)=p(x)$, then we have $(p(x))^2+p(x)-2 = (p(x)-1)(p(x)+2) = 0$. From here $p(x) = 1$ or $p(x) = -2$. Since $p(x)$ is an odd degree polynomial, it has at least one solution in each case, and the overall equation $q(x)=p(x)$ has at least two real and distinct solutions.
b) I do not see how $p(x) = 0$ can have at least two distinct solutions. However, $q(x) = 0$ does. $(p(x))^2+2p(x)-2 = 0$ has two distinct roots for $p(x)$ and, thus, following the same logic as in a), we conclude that $q(x) = 0$ has at least two distinct roots.
c) $q(x)p(x) = (p(x))^3+2(p(x))^2-2p(x)-4 = 0$, which can be written as $(p(x)+2)((p(x))^2-2) = 0$. This equation has three distinct roots for $p(x)$ and thus $q(x)p(x)=0$ has at least three distinct solutions.
Hope this helps.


Custom field validator comparing original and new values

Question: In my validator, I need to compare the new field value, that was submitted by the user, with the old value. How can I get the original value?
So far, I have this:
class CompareNewOldValuesValidator extends ConstraintValidator {

  public function validate($item, Constraint $constraint) {

    if (empty($item->getValue())) {
      return;
    }
    $value_new = $item->getValue()[0]['value'];

    /** @var ContentEntityInterface $entity */
    $entity = $item->getEntity();
    if (!$entity->isNew()) {
      $value_original = '???';
    }
  }
}

I need to get the field value that was filled in the form before the user changed it, no matter if it is the active version or a draft or an old revision.
Answer: Normally the original entity is stored in the entity object before the user input is applied. If not, you can get it via the loaded revision id, which is preserved when an entity is loaded to keep it save from changes:
if (isset($entity->original)) {
  $original = $entity->original;
}
else {
  $original = \Drupal::entityTypeManager()
    ->getStorage($entity->getEntityTypeId())
    ->loadRevision($entity->getLoadedRevisionId());
}

$value_original = $original->{$item->getFieldDefinition()->getName()}->value;

Comment: In my case, `$entity->original` is not set. But then, the else part works as intended, so the overall solution works.
Answer: I got the old value. I'll share my solution.
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;

class CompareNewOldValuesValidator extends ConstraintValidator {

  public function validate($item, Constraint $constraint) {

    if (empty($item->getValue())) {
      return;
    }
    $value_new = $item->getValue()[0]['value'];

    /** @var ContentEntityInterface $entity */
    $entity = $item->getEntity();
    if (!$entity->isNew()) {
      $entity_old = $this->entityRepository->loadEntityByConfigTarget($entity->getEntityTypeId(), $entity->getConfigTarget());
      $value_old = $entity_old->get($item->getName())->value;
    }
  }
}


Create a Form in a Block using API that sends captured data to email

Question:
Possible Duplicate:
Send email of form data?

So I have a simple three field form which I've created in HTML/CSS, see here:

Now I want to put this into a block module, generate the form fields using Drupal Form API (is this appropriate or should I just stick with my existing HTML markup?). And on submission of the form I want it to email the details to a designated email. Is Drupal Triggers appropriate for this, if not, what is?
Any guidance on where to go with this would be amazing. Thanks so much for your time :)
Answer: Use simple news module which will give you lots of e-newsletter features out of the box.
For new features you can extend above module to suit your specific requirements.
Answer: The easiest way is to create the form using webform module. This will also send an email to a chosen address. Unfortunately this will create just a normal page, not a block.
To show it in a block you'll need to create a view that renders the whole webform (which is a node) or to use mini panels with the same rendered node.
Answer: There are several approaches to this problem,

You can use "webform " module and theme it using $form[theme], your start can be here
you can use Form API to create a custom form. Your good start is FORM API Guide
To trigger a Mail on submission, you can use rules OR triggers OR just a submit function


Excel - VBA: Preciso de apoio para lincar a função Max

Question: Como posso referenciar uma coluna de uma certa sheet através do comando abaixo no VBA?
Application.WorksheetFunction.Max

Answer: Basta referenciar o Range que você precisa.
Exemplo:
Application.WorksheetFunction.Max(Worksheets("Plan1").Range("A1:A10"))

Comment: Grato pelo retorno.
Comment: Estou criando um cadastro de clientes. Em uma Textbox que criei em meu userform, eu quero que seus valores tenham uma ordem de crescimento começando de 1, depois 2 e assim por diante. Assimsendo, criei o código a seguir: TextBox2 = Application.WorksheetFunction.Max(sheet2.Columns(1)) + 1. Quando tento executar o código ele falha nesta linha
Comment: Oi @LázaroGouveia, creio que o ideal seria criar uma outra questão para isso, pois o intuito do stackoverflow é que dúvidas que possam ser comum entre outras pessoas, sejam respondidas aqui e fiquem como uma grande fonte de soluções.
Comment: grato pelo suporte? Sou novo no VBA e gostaria imenso de dominar a linguagem. Existe alguma forma de mantermos contacto de outra forma, além daqui?


Can I use the fixed effects model on cross-sectional data?

Question: I'm just learning econometrics, so I would like to know if I can use fixed effects/random effects on cross-sectional data. I have read many papers where they use these model with data panel, but my data is cross-sectional. I study the effects on students performance.
Comment: You may add the fixed effects or individual dummies by using penalized regression, such as, Lasso or ridge regression. There is a [blog](https://fxdiebold.blogspot.com/2016/06/fixed-effects-without-panel-data.html) that proposes this approach
Answer: The basic fixed effect model is something like:
$$y_{ij} = \boldsymbol{\beta} \cdot \mathbf{x}_{ij} + u_j +  \epsilon_{ij}$$
Typically, either $j$ or $i$ is indexing over time, but there's no reason it can't be anything else. The math doesn't care. $i$ could index over students and $j$ could index classroom.
Answer: The second dimension does not need to be time, or even ordered. You could have pairs of twins, students within classrooms, or exams of individuals where the second dimension is questions. However, whether FE or RE or FD makes sense, depends on your research question and the type of heterogeneity that you want these effects to represent.
Answer: You may add the fixed effects or individual dummies by using penalized regression, such as, Lasso or ridge regression. There is a blog that proposes this approach
Comment: At present this is more of a comment than an answer. You could
expand it, perhaps by giving a summary of the information at the link, or you could
convert it into a comment.


How protocol is communicated between routers web-server and the browser

Question: I'm working on an application which takes HTTP message to and from the routers web server.
The problem i'm facing is in the HTTP basic authentication.
RFC 7617 states:
"the server can reply with a challenge using the 401 (Unauthorized) status code"
What I've seen from the browser HTTP captures that it isn't the case for every router. For example, TPLINK TLWR840N doesn't sends me 401 and i can get the resource by simply transferring http request along with the correct credentials in the form of base64{username:pass} in the http message as shown below.
GET //main/ddos.htm?_=1572950350469 HTTP/1.1
Host: 192.168.0.1
Accept: */*
Connection: keep-alive
Referer: http://192.168.0.1
Cookie: Authorization=Basic YeRtaW46YWRtaW5AMTIz

It gives me the requested content if the password is correctly given otherwise it redirects me to the login page (why this router doesn't follow the 401 protocol?).
I have another TPLINK TL-WR841N router which doesn't take credentials (in http message) in the form of base64{username:pass} as the previous router, but instead it takes credentials in the form of base64(user):md5(password). I have two question about this router (and all routers in general)

I want to know how the router communicates the protocol for credentials to the browser so that i can embed that thing in my application. I have inspected the http messages (in the Chrome/Firefox) but couldn't found the message where the protocol is being communicated.

When i login to TPLINK TL-WR841N router, unlike the previous model, the web browser contains some SessionID in the URL, e.g. the URL shows www.192.168.0.1/SessionID/path/to/resource. I would like to know how this SessionID is communicated to the browser?
Answer: People who write router maintenance applications, as well as people who design graphics cards driver installer screens (looking at you, AMD), do not adhere to any guidelines, best practices or protocols whatsoever.
But they don't need to, either. They've written an application that happens to use HTTP, but you're not obliged to use all of HTTP. They write the frond-end as well as the back-end, so they can closely control their server as well as their client.
The client most likely is a dumb couple of HTML pages that does some requests using JavaScript.
If they were to decide that the web interface authenticates to the server with a request header that literally states LetMeIn: true, then that would work as well.
HTTP does not mandate that the server should return a 401 when that header is missing or bears false, so they don't have to.


Changing Wpf window appearance on Window_Closing

Question: When the user clicks the x to close the application window I want to pop up a message saying "Shutting Down, please wait" and greyout or disable the rest of the window controls.
This is because my application shutdown and cleanup takes a little while, about 20 seconds.
However, wpf commands in the Window_Closing event handler never seem to do anything. I have a tranparent grey-filled border which overlays the window controls and I want to change the visibility from collapsed to visible. The code is called but nothing changes.
It is as if the request is queued but is not called because the window is closing.
Is there some way to flush this request out?
Edit:
Try this code:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    _DisableBorder.Visibility = System.Windows.Visibility.Visible;
    Thread.Sleep(2000);
}

The app will close after 2 sec, but the border will never show. If you add e.Cancel = true, then the border will show after 2 sec.
Comment: That doesn't make any difference.
Comment: private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _DisableBorder.Visibility = System.Windows.Visibility.Visible;
            Thread.Sleep(2000);
        }  Nothing will happen at all with this code. If you put in e.Cancel = true, the border will become visible after 2 seconds.
Comment: The UI will not be updated *within* a method running on the UI-thread.
Comment: Even if I run the line using the dispatcher nothing happens.
Answer: You should make a trick.
Within the "Closing" handler, you should cancel the closing, then show the popup (as modeless window), then disable everything on the main window. When the process is over, you can close both the popup and the main windows programmatically.
I'd not perform anything time-consuming within the closing handler.
Hope it helps.
Cheers
Answer: Calling DoEvents from System.Windows.Forms.Application seems to do the trick..
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   _DisableBorder.Visibility = System.Windows.Visibility.Visible;
   System.Windows.Forms.Application.DoEvents();
   Thread.Sleep(2000);
}

Comment: Will that work in a WPF application? I'm not using windows forms.
Comment: Yes, you just need to add a reference to System.Windows.Forms.  I've done this in a few projects


Meta analysis of proportions that has control group

Question: I have data from a couple studies. The outcome I have is ordinal/likert. For each value I have the proportion of people who had each of the values at a measured end point. For example, in a study I have a record saying 12 people had value 1, 52 had value 2, 28 had value 3. I have these records for every study and each study had 2 conditions that people were in. What sort of meta analysis models would I be using here? I saw some example of meta analysis involving proportions here, but this seems like a different thing than what I'm looking for.
Answer: In this situation, you can do an individual-patient/subject-data meta-analysis, because you can simply recreate the data per person (just create one record per each of the people). Then, you use whatever analysis model you consider appropriate for an individual study (e.g. ordinal proportional odds model), stratify by study (i.e. you assume for the control group outcomes that the probability of each category could be completely different in each study), and assume that your effect measure of interest is either the same in every study (fixed effects meta-analysis) or varies across studies (random effects meta-analysis). Exactly which model you would use would depend on what you want to assume and what effect measure you are interested in.
Alternatively, you could analyze the individual patient data from each study (or take an estimate that the study authors have produced) to obtain the effect measure of interest (e.g. log-odds-ratio for the ordinal proportional odds model; note log transformation is important here, but you can back-transform the final results to the odds-ratio scale) and its standard error. Then, you do a standard inverse variance (for fixed effects) or random effects meta-analysis for the estimates and their standard errors.
The first approach should be superior, if there are small numbers in some categories in some studies, but if all categories are filled with enough people, the two approach may end up giving very similar results. If numbers are very small and/or you have perfect separation (e.g. in some study group 1 has 10% in category 1, while groups 2 has 100% in category 3) or issues like everyone being in a single category in all groups in one study, then perhaps a Bayesian version of the first approach with vague priors might help.