How can I identify Gregorian modes in Bach music?

Question: I'm learning these Gregorian modes things and I'm trying to identify these modes in a Bach music, Invention 8 F Major, for example:

The music starts at F in Ionian mode. But I think It changes when getting at 2, 3 and at 4. If it really changes, changes for which mode? I'm completely lost, any kind of help will be good!
Comment: cf. [these excellent works on the modes of Gregorian chant](https://isidore.co/calibre/browse/search?query=id:5977+or+id:5978+or+id:5974+or+id:5975+or+id:3332+or+id:3327)
Answer: By the time of Bach, most of the old church modes were no longer being used. The Ionian mode stuck around, but in a common-practice context we usually call it "major." The Aeolian mode also stuck around, however it was consistently modified to usually have a raised leading tone, and often have a raise submediant as well. When the 6th and 7th scale degrees are consistently altered according to function, "Aeolian" is no longer an appropriate term, and we should code the mode "minor." The other modes temporarily fell by the wayside.
The chunk of the eighth invention that you have posted in your question is unequivocally in F Major throughout, there aren't any modulations or mode changes. When you look at music of the Baroque, Classical and Romantic eras, you shouldn't be looking for mode changes. You should be looking for chord changes at the local level, and key changes (shifts of tonic, not shifts of mode) at the larger level. There will occasionally be mode changes, but only from major to minor or vice-versa. The further you get into the Romantic era, and, especially once you start looking into the twentieth century, the more likely it will be that you might see the re-emergence of the other modes. Pop/Rock music, for example, is often modal. Otherwise, you generally have to go back to the Renaissance and Medieval music to find most of the modes used consistently.
Comment: Not only in F major, but for fully five measures articulating an F major harmony.
Comment: @Patrx2 And even the sixth measure is just a tonic substitute vi chord.
Comment: Yup, and even at that, the vi is acting as ii of V, as it is V7 of V (in 2nd inversion) that follows. Bach gets to walk the bass down by thirds _and_ reinterpret vi to effect a modulation to the dominant.
Answer: Don't confuse a 'modal scale' with a 'Mode'!
The whole song is in a 'Mode' and in Bach's times they didn't even call this aeolian or ionian anymore but simply major and minor.
Of course, the scale starting from the II (G) of your tonic (F) has the same interval structure than a dorian scale would have on its root (G-dorian). But unlike in F-major the whole 'Mode' of G-dorian is 'dorian' - but in F-major it obviously is 'major' - (or 'ionian' if you prefer to express it with terms of 'Modality').

In case you wanna make a deeper dive into this:
Difference between Modality, Tonality and Chord-naming conventions in a more practical way?
Answer: Bach did write some modal music - for example, the Dorian fugue.
However, Bach was at the forefront of developing the diatonic system, so in most of his work, modes do not generally apply. To identify modes in general, you need to check the range of the voices and the note that the piece ends on.
Comment: I think that Bach's "Dorian" fugue is actually in D-minor. The key-signature is that of C-major (A-minor) but most of the Bs are flatted and the Cs are often sharped. There was a baroque (literally) tradition of writing minor-key pieces with one less flat than is common now. (I don't know what they did with sharp minor keys which are rarer in mean-tone tuning.) I tried this for fun a few times but it seemed that what one gained by not having to sharpen the sixth note was lost in flattening it other places.


Finding the $n$th number on a sequence

Question: We define $S(i)=2^i-S(i-1)$ and we know that $S(0)=0$. Is it possible to derive a non recursive formula for $S(i)$?
Comment: Did you try anything ? Compute the first $10$ terms.
Comment: They are: $S(0)=0$ , $S(1)=2$ , $S(2)=2$ , $S(3)=6$ , $S(4)= 10$ ,  $S(5)= 22$ ,  $S(6)= 42$ ,  $S(7)= 86$,  $S(8)= 170$
Comment: https://www.wolframalpha.com/input/?i=s(0)%3D0+,+s(n)%3D2%5En-s(n-1)
Comment: Now if you take the ratios of consecutive elements, you will observe that it converges to $2$, hinting that the sequence is asymptotically $c2^i$.
Answer: By an educated guess, divide the recurrence by $2^i$ and define $T(i):=S(i)/2^i$. Then
$$T(i)=1-\frac{T(i-1)}2.$$
The homogeneous solution (equation $T(i)=-T(i-1)/2$) is obviously $T(i)=c/(-2)^i$, and a particular solution of the non-homogeneous equation is $T(i)=2/3$. So with the initial condition $T(0)=0$
$$T(i)=\frac23(1-(-2)^{-i})$$ and
$$S(i)=\frac23(2^i-(-1)^i).$$

Alternatively, set $T(i)=(-1)^iS(i)$ so that the equation becomes
$$T(i)=T(i-1)+(-2)^i$$
so that the solution is by recurrence
$$T(i)=T(0)+\sum_{k=1}^{i-1}(-2)^k.$$
Answer: The most easy way to find the closed form is just to start writing the first members of te sequence down till you see a pattern:
\begin{align}
S(1)=&2\\
S(2)=&2^2-2\\
S(3)=&2^3-(2^2-2)=2^3-2^2+2\\
S(4)=&2^4-(2^3-(2^2-2))=2^4-2^3+2^2-2\\
\end{align}
Now you note that your sequence might be $S(n)=\sum\limits_{k=0}^{n-1}(-1)^{k}2^{n-k}$. I hope you know the closed form of this sum:
\begin{align} S(n)=2^n\sum\limits_{k=0}^{n-1}(-\frac 1 2)^k=2^n\frac{1-(-\frac1 2)^{n}}{1-(-\frac 1 2)}=\frac{1}{3}2^{n+1}(1-(-\frac 1 2)^{n})=\frac1 3 2^{n+1}-\frac 2 3 (-1)^{n}\end{align}
Now you have this, you can prove it by induction. I hope this helps.
Answer: HINT: $$S(i)=2^i-S(i-1)$$ $$S(i-1)=2^{i-1}-S(i-2)$$ $$S(i-2)=2^{i-2}-S(i-3)$$ $$\ldots$$ $$S(1)=2^1-S(0)$$
Hope it is clear now.
Answer: Sloane's A078008 gives $S(n)=\tfrac{1}{3}(2^{n+1} + 2\, (-1)^{n+1})$.
We can check it's true for $n=0$.  Now assume it's true for $n=k-1$ for some $n \geq 1$.  Then
\begin{align*}
S(n) &= 2^n-S(n-1) \\
 &= 2^n-\tfrac{1}{3}(2^n + 2\, (-1)^n) \\
 &= \tfrac{1}{3}(3 \cdot 2^n - 2^n - 2\, (-1)^n) \\
 &= \tfrac{1}{3}(2^{n+1} + 2\, (-1)^{n+1}).
\end{align*}
Thus verifying this formula by induction.
Answer: $S(i)=\frac{-2}{3}((-1)^i-2^i)$

Finding the $n$th number on a sequence


Find character table for symmetric group $S_3$

Question: This group contains all permutations of 3 elements, so it has order 3!=6.
Its three congruency classes are {1}, {(1,2),(1,3),(2,3)}, {(123),(132)}. As we know that the number of congruency classes equals the number of irreducible characters, we know that there are 3 irreducible characters (of degrees, say, $a,b,c$, such that $a^2+b^2+c^2=6$).
The two most obvious representations are the trivial one and the sign one, both of degree 1. Hence $a=b=1$, and therefore $c=2$.
How can I find $c$? My book says to use the orthogonality relations (i.e. irreducible characters form an orthonormal system), but I don't really see how.
Comment: Given two vectors $(a,b,x)$ and $(c,d,y)$ with $a,b,c,d$ known, can you find $x$ and $y$ such that they become orthonormal?
Comment: Sorry, to get started, you also have $x$ known in this case actually.
Answer: You have already find two representations and the dimension of the last one, so you have the table :
$$\begin{array}{|c|c|c|c|}
\hline
         & \text{Id} & (i,j) & (i,j,k) \\
\hline
1\!\!1   &     1     &   1    &    1    \\
\hline
\epsilon &     1     &  -1    &    1    \\
\hline
\chi     &     2     & \alpha & \beta \\
\hline
\end{array}$$
Do you know why the first entry of the last row $\chi(\text{Id})=2$ ? Now, to find $\alpha$ and $\beta$, you can use the orthogonality of the columns. For example, we know that $(1,1,2) \cdot (1,-1,\alpha)=0$ so $2\alpha=0$.
Comment: So $1\!\!1$ is the trivial representation, $\epsilon$ the sign representation, and $\chi$ the representation we're looking for.

Is the 2 just what I found when I wrote c=2?

So in that case $\beta=-1$ and we're done?

Thanks!
Comment: Yes the 2 is $c=2$ : for any character $\chi$ of dimension $d$, we have $\chi(\text{Id})=d$. And indeed $\beta=-1$.
Comment: how do you get the first 2 rows?
Answer: Not what you asked, but first here's the "natural" way to construct the third irreducible representation: $S_3$ has a natural 3-dimensional representation as permutation matrices. An obvious invariant subspace is $\{(u,v,w)\ | \ u+v+w=0\}$. Then the quotient is two-dimensional and irreducible.
Now to actually answer your question, yes, you can do this with the orthogonality relations. Let $x,y$ be the unknown character values (as you've noted, the character must send $1$ to $2$). Call your character $\chi$. Then $\langle\chi,1\rangle=0$ and $\langle\chi,sign\rangle=0$. This will give you two linear equations in the two unknowns $x$ and $y$, so you'll be able to find a unique solution.


Bayes Estimator with Two Parameters

Question:
In a Bayesian approach to simple linear regression, suppose the intercept $\Theta_1$ and slope $\Theta_2$ of the regression line are a-priori independent with $\Theta_1\sim N(0,\tau^2_1)$ and $\Theta_2\sim N(0,\tau^2_2)$  Given $\Theta_1=\theta_1$ and $\Theta_2=\theta_2$, data $Y_1,...,Y_n$ (responses in the regression model) are independent with $Y_i\sim N(\theta_1+\theta_2x_i, \sigma^2)$, with the $x_i$ being the predictors.  The variance $\sigma^2$ is known, and $x_1,...,x_n$ are constants summing to $0$.
Find the Bayes estimators of $\Theta_1$ and $\Theta_2$ under squared error loss.

Here's where I'm confused; the expressions for the PDFs of the posterior distribution of each estimator are dependent on the other unknown quantity; hence so should their expected values (which is the Bayes estimator).
For example, holding $\theta_2$ constant, I calculate that:
$$f_{\Theta_1}\propto \frac{\exp((\sum\theta_1+\theta_2x_i-y_1)^2/2\sigma^2)}{(2\pi\sigma^2)^{n/2}}\cdot\frac{\exp(-\theta_1^2/(2\tau_1^2))}{\sqrt{2\pi\tau_1^2}}$$
But clearly this quantity is dependent on $\theta_2$! So clearly I've done something wrong here, but I don't know how to do this properly.  What are the Bayes estimators for both $\Theta_1$ and $\Theta_2$?
Answer: The prior distribution of the pair $(\Theta_1,\Theta_2)$ is
$$
\text{constant} \cdot \frac 1 {\tau_1\tau_2} \exp\left( \frac{-1} 2 \left( \frac{\theta_1^2}{\tau_1^2} + \frac{\theta_2^2}{\tau_2^2} \right) \right) \, d\theta_1 \, d\theta_2.
$$
The likelihood is
$$
L(\theta_1,\theta_2) = \text{constant} \cdot \exp\left( \sum_{i=1}^n (\theta_1 + \theta_2 x_i - y_i)^2 \right).
$$
\begin{align}
(\theta_1 + \theta_2 x_i - y_i)^2 & = \theta_1^2 + \theta_2^2 x_i^2 + y_i^2 + 2\theta_1\theta_2 x_i - 2\theta_1 y_i - 2\theta_2 x_i y_i \\[10pt]
\sum_{i=1}^n (\theta_1 + \theta_2 x_i - y_i)^2 & = n\theta_1^2 + \theta_2^2 SSXX + \text{constant} + 2\theta_1\theta_2\cdot0 - 2\theta_1 n \overline y - 2\theta_2 \mathbb x \cdot\mathbb y
\end{align}
You'll have some algebra to do, but when you multiply the likelihood by the prior you should get
$$
\text{constant} \cdot \exp(\text{quadratic form in $\theta_1,\theta_2$}) \, d\theta_1\,d\theta_2.
$$
This will be a normal distribution, and the mean and variance can be read off from the form of this function. The mean should be a vector with two scalar components and the variance should be a $2\times2$ positive-definite matrix giving the two variances of scalar random variables and their covariance.
Comment: From the expressions you've derived, I don't see how it's possible to get this into quadratic form.  And should the expressions in the exponent of your likelihood function be divided by $-2\sigma^2$?
Comment: I've spent the past 4 hours trying to get this to work and I'm still nowhere. Are you sure you can do it this way?

Bayes Estimator with Two Parameters


Multi-language with domain name specific doesn't work

Question: I am working on a multi-language website. I am setting content in both English and French.
When I use path prefix as my detection method, it works fine, like poc-local.com and poc-local.com/fr. When I use domain as my detection method, it doesn't work, like fr.poc-local.com.
I am getting a 302 error, and "the page isn't redirecting properly" error. How can I fix this?
Comment: Hi ,I found this link https://www.drupal.org/node/1735762. I am new to drupal and how to apply these patches???
Comment: elan, the patch provided there is for Drupal 6 version, so it won't work for you. [see picture](http://i.stack.imgur.com/89Bc0.jpg)
Comment: Ok Ok I am sorry.
Answer: I found the answer for this.
I have installed global redirect module and now it's working.
https://www.drupal.org/project/globalredirect
But Now I am having another one problem.My language Switcher block is not working.When I switching from one language to another language the recently switched language url displaying for all languages...


How to embed the Netbeans Souce Code Editor in a Swing application?

Question: Is there a way to embed the Netbeans source code editor in a Swing application without writing the app as a whole Netbeans Platform application?
Best regards,
David
Comment: I don't know of anybody that has done it, but I can't see any reasons why you can't do it. Your biggest problems are going to be working out what your dependencies are going to be. Maven may be quite a large help with that.
Answer: Please see:
http://www.antonioshome.net/kitchen/netbeans/nbms-standalone.php


returning index from JSON returned array

Question: Hi guys I was wonder how you can return the index based on ID with the following.
<code>$friends = '{
   "data": [
      {
         "name": "Paul",
         "id": "12000"
      },
      {
         "name": "Bonnie",
         "id": "120310"
      },
      {
         "name": "Melissa",
         "id": "120944"
      },
      {
         "name": "Simon",
         "id": "125930"
      },
      {
         "name": "Anthony",
         "id": "120605"
      },
      {
         "name": "David",
         "id": "120733"
     }
   ]
}';

$obj = json_decode($friends);
</code>
for example, I want to get print the name based on ID.  I've had a go at using array_search but it didn't like the structure of the array.  I will be using it inside a sql loop and passing the ID from the query to return the name string from the array.
<code>print $obj->{'data'}[0]->{'name'};
//where 0 is returned index based on a defined ID.
</code>
thanks a lot
Answer: You will need PHP 5.3 in order to utilize the following closure and enhanced ternary operator (prints name if record is found; otherwise, prints 'No record found.'):
<code>$findById = function($id) use ($friends) {
  foreach (json_decode($friends)->data as $friend) {
    if ($friend->id === $id) return $friend->name;
  }
  return;
};

echo $findById('125930') ?: 'No record found.';
</code>
Nice thing about this is that you can pass this callable around and it will remember the scope it was defined with. This means that you can pass any ID but the $friends array will always be available to the closure.
Answer: The json_decode makes your variables into objects. To do a search, you could use:
<code>// The extra true at the end makes it decode to associative arrays
$json = json_decode($friends, true);
findByName($json, 1234);

function findNameById($obj, $id) {
   foreach($obj as $o) {
      if($o['id'] == $id) return $o['name'];
   }
   return false;
}
</code>


Prove that $\mathbb{Z}_n$ has an even number of generator for n>2

Question: My proof of this question is as following
Let $x$ be the element of the generator for the cyclic group $\mathbb{Z}_n$, so that that the order of $x$ is $n$, i.e. $x^n=x^{n-1}\circ x=x\circ x^{n-1}=e$, so $x^{n-1}$ must be the inverse of $x$ in the group. Then because $\gcd(n,n-1)=1$, then the order of $x^{n-1}$ is $n/1=n$. Therefore $x^{n-1}$ is a generator of the group $\mathbb{Z}_n$, since $<x>=<x^{n-1}>$. Hence for every element $x$ that is the generator of the group $\mathbb{Z}_n$, we can always have its inverse element $x^{n-1}$ or $x^{-1}$ as another generator of the group. i.e. if I find odd numbers of generator for the group, I must have an even number  of generators, or if I find even number of generators, I must have an even number of generators as well.
I don't know if my proof is correct enough so I want to see what your guys thinking. And perhaps if it is possible, I have a second question which I don't know how exactly to prove. here is the statement
A group with a finite number of subgroups is finite.
I intuitively suggest this must be true but I can't write reasonable proof for it.
Thanks.
Comment: For the second question, see https://math.stackexchange.com/q/22996/62967
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark $\checkmark$ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).
Comment: What's this cyclic group $\Bbb Z_n$ with a multiplicative law?
Comment: You should probably say how you know that $x$ and it's inverse are not equal to each other. Also, since you're working in an abelian group whose operation is denoted additively, it might be easier to read if you use $-x$, $nx$ , etc rather than the abstract multiplicative notation.
Comment: Using that the number of generators is $\varphi(n)$ is an easier approach.
Answer: More abstract: suppose that the group $G$ is cyclic; then, for each generator $x$, also $x^{-1}$ is a generator, because $x^k=(x^{-1})^{-k}$.
Suppose $x=x^{-1}$; then $x^2=1$ (or $e$, if you prefer this notation; I don't) and therefore $|G|\le2$.
Thus, if $|G|>2$, we have $x\ne x^{-1}$, for every generator $x$, and thus we can divide the generators into pairs.

Hint for the second question: any group is the union of its cyclic subgroups; if the number of subgroups is finite, none of the cyclic subgroups can be infinite.
Comment: Thank you. I can't exactly catch what you mean by that if the number of subgroups is finite, none of the cyclic subgroups can be infinite.
Comment: I mean how you connect the idea between number of subgroup, and the order of a cyclic subgroup()
Comment: @oscarmetalbreak If a cyclic group is infinite, it has infinitely many subgroups (it is isomorphic to the integers); the existence of only finitely many subgroups rules this case out. Thus we have a finite union of finite cyclic groups.
Comment: Please tell me if I understand it correctly. Because a group is a union of its cyclic subgroups. So finite number of subgroups indicates finite number of cyclic groups. And the cyclic group must be of finite order, since infinite cyclic groups produce infinite number of subgroups. Hence a group being its finite number of cyclic subgroup of finite order must be a finite group.
Comment: @oscarmetalbreak That's it.
Answer: I like it.  Alternatively, the number of generators of $\Bbb Z_n$ is $\varphi(n)$, where $\varphi$ is Euler's totient function.  A basic fact about $\varphi$ is that it's values are always even.
For your second question, the hint is to look at cyclic subgroups, noting that the infinite cyclic subgroup, $\Bbb Z$, has infinitely many subgroups.
Comment: We have not been taught the Euler's totient function yet so I don't know how to use $\varphi$.
Comment: Oh well.  You will meet it.
Answer: Let $\mathbb{Z}_n$ be cyclic group of order $n \gt 2$ then either $n = 2^s$ such that $s \gt 1$, say if $s = 1$ then $n = 2^1 = 2$ but $n \gt 2$ so $s$ has to be more $1$.
Then no. of generators of $\mathbb{Z}_n$ = no. of elements of order $n=$
$$ \varphi(n) = \varphi(2^s) = 2^s - 2^{s-1} = 2^{s-1}(2-1) = 2^{s-1}$$
which is divisible by $2$ for $s$ more than 1, so $\varphi(n)$ is even.
If $n$ is not of the form $2^s$ then $n$ must be of the form $p^kt$ such that $p$ is prime greater than $2$, $p$ and $t$ are co-prime and $n$ is $t$ multiple of $p^k$ then
(Can you guess further steps of the proof?)

 Spoiler
 $\varphi(n) = \varphi(p^kt)$ $= \varphi(p^k)* \varphi(t)$ $= (p^k - p^{k-1})* \varphi(t)$ $= p^{k-1}(p-1)* \varphi(t)$. Note that $p$ is prime more than $2$ then $p$ must be odd and $p-1$ must be even and as $\varphi(n)$ is multiple of $(p-1)$ then $\varphi(n)$ must be even.

Hence $\mathbb{Z}_n$ must have even no. of generators if $n$ is more than 2. Infact you can generalize above result for any cyclic group with order more than $2$.


How can I align the output program correctly? Once there was a 2 digit number, the alignment is being disoriented

Question: It is a program that takes information then saves it to a marklist file and then outputs it again and then the output is  not properly aligned to the rows above. How can I align the output program correctly? Once there was a 2 digit number, the alignment is being disoriented.Notice that the output is not properly aligned
#include<iostream>

//fstream is needed because we will use file systems.
#include<fstream>

using namespace std;

/*declaring fstream global variable used
  to open, write, read and close files in this program.*/
fstream storage;

struct student_profile{
    char FName[100];
    char LName[100];
    char reg_year[100];
    char course[100];
    char id[100];
    int no_courses;
    char course_Name[100];
    char course_code[100];
    int credit_hour;
    int quiz_one;
    int quiz_two;
    int quiz_three;
    int mid;
    int assignment;
    int lab;
    int final_exam;
};

/* creating structure variable from student_profile.
   the name this structure variable is student.
   it is used to hold name, last name, id etc
*/
student_profile student;

/* function used to register student.
   it accept student details then it write those data to file.
   so student details will be saved in text file for later use.
*/
void function_to_register(){
 cout<<"        Write First Name of student: ";
 cin>>student.FName;
 cout<<"        Write Last Name of student: ";
 cin>>student.LName;
 cout<<"        Write Registration year: ";
 cin>>student.reg_year;
 cout<<"        Write Course of student: ";
 cin>>student.course;
 cout<<"        Write number of courses that student learns in this semester and register them one by one\n";
 cout<<"        Number of courses: ";
 cin>> student.no_courses;

/* for loop used to register multiple courses for one student
   based on the student's number of courses entered.
 */
 for(int a=1; a<=student.no_courses; a++) {
 cout<<"         Write course Name: ";
 cin>>student.course_Name;
 cout<<"         Enter grade for quiz one: ";
 cin>>student.quiz_one;
 cout<<"         Enter grade for quiz two: ";
 cin>>student.quiz_two;
 cout<<"         Enter grade for quiz three: ";
 cin>>student.quiz_three;
 cout<<"         Enter midterm grade: ";
 cin>>student.mid;
 cout<<"         Enter assignment grade: ";
 cin>>student.assignment;
 cout<<"         Enter lab grade: ";
 cin>>student.lab;
 cout<<"         Enter final exam grade: ";
 cin>>student.final_exam;
 storage.open("marklist.txt",ios::app) ;
   storage.write((char*)&student, sizeof(student));
   //storage.write(student,sizeof(student));
 storage.close();
 }
}

 /* function used to calculate grade of each course.
    we call this function when the program is displaying grade of student.
 */
void grade_calculator(int totalMark) {
    if(totalMark>=90 && totalMark<=100)
        cout<<"A+";
    else if(totalMark>=80 && totalMark<90)
        cout<<"A";
    else if(totalMark>=70 && totalMark<80)
        cout<<"B";
    else if(totalMark>=60 && totalMark<70)
        cout<<"C+";
    else if(totalMark>=50 && totalMark<60)
        cout<<"D";
    else if(totalMark>=0 && totalMark<50)
        cout<<"F";
    else
        cout<<"NG";
    }

/* function used to display registered students on the screen.
   this function gets the registered student from that file
   we used above to store student details.
*/
void seeRegistered() {
 storage.open("marklist.txt",ios::app);
 storage.close();

 storage.open("marklist.txt",ios::in);
 storage.read((char*)&student, sizeof(student));

 while (storage.eof()==0) {
  cout<<"\n\n\n";
  cout<<"  Full Name: "<<student.FName<<"  "<<student.LName<<endl;
  cout<<"  Registration Year: "<<student.reg_year<<endl;
  cout<<"  Faculty: "<<student.course<<endl;
  cout<<"  *****************************************************************************\n";
  cout<<"  ******************************STUDENT MARK LIST******************************\n";
  cout<<"  *****************************************************************************\n";
  cout<<"  Subject    Quiz1   Quiz2   Quiz3    Mid   Assignment    Final   Total   Grade\n";
  cout<<"  _____________________________________________________________________________\n";

/* for loop used to print all courses and their marks
   for a single student.
*/
     for(int t=1; t<=student.no_courses; t++) {
        int totalMark;
        totalMark= (student.quiz_one+student.quiz_two+student.quiz_three+student.assignment+student.mid+student.final_exam)/6;
        cout<<"  "<<student.course_Name<<""<<student.quiz_one<<"      "<<student.quiz_two<<"       "<<student.quiz_three<<"       "<<student.mid<<"       "<<student.assignment<<"         "<<student.final_exam<<"       "<<totalMark<<"      ";
        grade_calculator(totalMark);
        cout<<endl;
        storage.read((char*)&student,sizeof(student));
     }
  }
storage.close();
}

/* This is the main function which will be  executed before all functions,
   So in this program when the user select one option then by
   the help switch statement the user redirects to appropriate function.
 */

 int main() {
 char select;

/* while loop that help us to excute the program all time.
   this means the program will not exit without our interest.*/
 while(1) {
  cout<<endl; cout<<endl; cout<<endl;
  cout<<endl;
  cout<<"     **********************************************\n";
  cout<<"     *  STUDENT REGISTRATION AND MARK LIST SYSTEM *\n";
  cout<<"     **********************************************\n";
  cout<<"     *\n";
  cout<<"     Enter 1 To Register New student \n";
  cout<<"     Enter 2 To Show Registerd Students and Their Grade \n";
              /*
                you can improve this in which the displayed record is sorted (ascending/descending)
                */
  cout<<"     Enter 3 To Search for a student \n";
  cout<<"     Enter 4 To Edit a student record\n";
  cout<<"     Enter 5 To Delete a student record\n";

  cout<<"     Enter 0 To Exit \n";
  cout<<"     : ";
  cin>>select;

  switch (select) {
         case '1':
            function_to_register();
            cout<<"          Student Registered succsesfully \n";
           break;
           case '2':
     seeRegistered();
            break;

  }
 }

}

Comment: Sidenote: Not all languages that contain the letter C are the same, please don't spam tags, it attracts downvotes.
Answer: use std::cout<<setw(num_of_spaces)


Android everytime I add an ID to a view I have to make a clean install

Question: Everytime I add an ID to a view or create a new view with an ID I have to make a clean install, i.e uninstall manually the app on devices then reinstall through Eclipse. If I don't, nothing works properly, some views doesn't show up or others bugs like that.
Anyone has any idea about what's causing this issue ?
(when I remove the id and then recompile, everything is back, but I can't add ids)
EDIT My error: I was missing the default values with sharedpreferences, I don't understant what is wrong
EDIT I found out what was my mistake: I was storing IDs of views in settings in sharedpreferences (to know what the user selected) and use those IDs to conststruct views according to what the user had chosen. But when we add a new ID Eclipse regenerate R.java with new IDs for ALL views to keep them in order (according to the order they appears in layouts) in ascendent order and the smallest possible
If I have R.java like:
public static final int first_id=0x7f020021;
public static final int second_id=0x7f020022;
public static final int third_id=0x7f020023;

and I if I add a view between the second and the third view and add an ID to this view, R.java is regenerated and it goes like:
public static final int first_id=0x7f020021;
public static final int second_id=0x7f020022;
public static final int fourth_id=0x7f020023;
public static final int third_id=0x7f020024;

Comment: Hmm, can you check if you have `build automatically`, in projects I think, checked?
Answer: Maybe try cleaning your project?
Comment: Can you explain in little more in depth whats going wrong and what you did/do to solve the problem?
Comment: Oh ok so whatever you do to mess up, you save in the Shared Preference which then messes up the app.. That's crazy dude. Could you copy and paste your code? I know you cant do the error but maybe your eclipse code?
Comment: I have a ScrollView with text views inside, I read a SQLite database to construct those textviews. When I add a new view to my app and an id to it (for the layout of that activity or another activity), then, the database is not read, (sometimes the asynctask to read it throw an exception, but I can't reproduce that to show you the exception)
And the settings that I store in sharedpreferences are messed up

To solve this I manually uninstall the app on device and then run it again through Eclipse and it's ok
Comment: It's a long code so I will post the essential. With some toast I manage to find where where was the bug, and indeed it's with sharedpreferences, I'm adding this + thanks, you saved my app


Get all views of an app- every moment?

Question: I need to find a way to create some class that is always alive in the app. This class doesn't know anything about the other classes in the project. It will be able to "follow" all UIViews on screen-so every moment I can check(loop) over the views and get a pointer to each of them.
It has to run live, and always check positions of views (is it a memory problem?)
Why a pointer? because I need to know everything about it, so if its some kind of moving animation, or maybe it has some meta data like tags, etc. so only knowing there is some view at a certain position is not enough.
Is it possible in iOS ?
Comment: I'm not exactly sure what you want me to show in an example. If you have the window then you can traverse it's subviews using it's `subviews` property. You can do this recursively all the way done to the views with no children
Comment: What do you mean by run live? Do you want to be able to access the views tree at any time you want or do you want to get notified on any changes to that tree (view added/removed/resized etc)?
Comment: I would like to only get data about them when ever I want, not affecting them at all, just get access to them, so I can check all sort of things such as position, color, tags, meta data, etc
Comment: The real purpose is to check them all the time, and set some "if statements" to some things
Comment: You should have a reference to the rootWindow in your app delegate - you can traverse the view hierarchy from there
Comment: @Paul.s thanks, can you show some simple example to get me going?
Comment: @Paul.s for example evey time any view is out of screen, even part of it, I need to get a pointer of it.
Comment: You probably want to update your question to be more specific if you are wanting actual examples. Also sounds like you would need to profile this as constantly polling all the views in your application sounds like it could be expensive and bad for battery usage
Comment: You are right I will edit it. So you think the best way is to send any view's pointer to some high class that will always keep an eye on them?
Answer: The whole idea sounds like an antipattern. However, …
Simply traverse the view tree and add a KVO handler to every view for every interesting property.
- (void)traverseSubviewsOfParentView:(UIView*)view
  for( UIView* subview in view.subviews )
  {
    [view addObserver:self forKeyPath:@"frame" options: NSKeyValueObservingOptionNew];
    …
    [self traverseSubviewsOfParentView:subview context:NULL];
  }

Then implement the observation method:
-(void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context
{
  if( [@"frame" isEqualToString:keyPath] )
  {
    // Do what you want to do
  }
  …
}

Additionally you have to observe the subviews property of every view to get notified, when a view is inserted or removed.

Get all views of an app- every moment?


Purview Message Encryption: Require OTP codes for all recipients, and bypass MS365 tenant logins for all outgoing emails

Question:
Related: MS365: Sending encrypted to remote tenants occasionally fails with "user not in tenant"

As in the previous message, we are sending outgoing encrypted messages via MS365 and some remote tenants are unable to view messages.
Before the forced move to Purview in July 2023, when accessing encrypted emails you had the option to request an OTP instead of logging in with your tenant to access things.
We have the option of OTPEnabled: True on our OME configuration (according to PowerShell Get-OMEConfiguration but since the migration to Purview, we can't force everyone to use OTP or even see the "Get OTP code via email" option.
Has anyone figured out a way to force OTP code via email instead of MS365 login in order to get access to a given encrypted message?  If we can force everyone to need OTP codes instead of using MS365-integrated login that'd be great, but I'm not sure where to enforce that, does anyone know how to do that in Purview encryption since legacy OME settings are no longer present?
Answer: So, I was on a call with Microsoft on the related-linked issue in my question yesterday, and blatantly asked them about whether forcing OTP for everyone was possible.  According to Microsoft support, it turns out that there is no way to force OTP for everyone anymore, and that was primarily a legacy Outlook Message Encryption option that is not available in Purview (but available if you use on-prem Exchange still and not MS365 Exchange Online or Hybrid Exchange).
In the Purview world, if someone has an Entra ID (MS365) or a Microsoft account, they must use that to authenticate.  For all other receivers, they get OTP prompts in a default Purview setup that Microsoft is now forcing everyone into.
Another -1 to Microsoft for making things that much more complicated and difficult for people.
Answer: I'am not an expert is in the subject, but I think the value you want to modify is SocialIdSignIn to False.

-SocialIdSignIn The SocialIdSignIn parameter specifies whether a user is allowed to view an encrypted message in the Microsoft 365 admin
center using their own social network id (Google, Yahoo, and Microsoft
account). Valid values are:
$true: Social network ID sign in is allowed. This is the default
value. $false: Social network ID sign in is not allowed. Whether the
recipient can use a one-time passcode or their Microsoft 365 work or
school account is controlled by the OTPEnabled parameter.
Comment: Tried that, didn't do anything almost as if we *can't* shut off SocialIdSignIn.  I'll try this again, but it's almost like Microsoft is telling Entra users to 'screw yourselves' because this is a very broken implementation (see "related" thread for why)
Answer: To enforce one-time passcode (OTP) authentication via email instead of MS365 login for accessing encrypted messages, you can utilize the email one-time passcode feature:
https://learn.microsoft.com/en-us/azure/active-directory/external-identities/one-time-passcode
Comment: Thanks for your feedback. I need starting some more research on this. will give any update late.
Comment: This doesn't really answer the question.  It explains under *what conditions* it comes into play, but doesn't let us actually *disable* the use of Entra / MS365 logins or social IDs and force OTP, which is the goal here.  And yagmoth555's answer doesn't solve it either, it still forces things to use MS365.  It's like Purview ripped out a feature that was highly desired.


Custom Views Bulk Operation using Batch API

Question: I am using Views Bulk Operation for updating custom value. I created a custom Operation using hook_action_info. How can I use Batch API with my custom action if I have to Operate on maximum nodes.
Answer: Go to VBO settings (when editing the view, next to Style: Views Bulk Operations) and for your operation select the "Use Batch API" radio button under "To execute operations".
Comment: It showing `Access Denied` in `?q=batch&op=start&id=13` url If I select all the rows. Not for single row.
Comment: Oh sry Its VBO issue, I read in readme.txt.
Comment: Thnx buddy.. :D


When $ac \gt bd$ is true?

Question: Suppose $a \gt b$ and $c \gt d$ . What's the conditions for $a$ , $b$ , $c $ and $d$ for which  $ac \gt bd$ being true ? Also how we can prove it ?
I tried many positive numbers and it was true but I don't know how prove it .
Comment: Note that the strongest thing of this kind you can always say is what you get from $a-b\gt0, c-d\gt 0$ which means $(a-b)(c-d)\gt 0$ or $ac+bd\gt ad+bc$. But this is weaker than the original because it is true whenever $a-b$ and $c-d$ have the same sign (they could both be negative as well as both positive).
Answer: No, it's wrong.
Try $a=5$, $b=-6$, $c=2$ and $d=-3$.
For positives $a$, $b$, $c$ and $d$ it's true because
$$ac-bd=ac-bc+bc-bd=c(a-b)+b(c-d)>0$$
Comment: What about when $a , b , c , d$ are positive ?
Comment: @S.H.W I added something. See now please.
Comment: If you want prove $c(a-b) + b(c-d) \gt 0$ you should use the expression that I wrote again !
Comment: @S.H.W Since $a>b$  and $c>d$, we have $a-b>0$ and $c-d>0$. I used your expressions exactly.
Comment: Yes , you're right . Thanks !
Comment: @S.H.W You are welcome! Good luck!
Answer: If all the numbers are positive, then:

Since $a>b$, and $c>0$, you have $ac>bc$
Since $c>d$, and $b>0$, you have $bc>bd$

Putting the two inequalities together gives you $ac>bd$.
Comment: And how we can prove first statement ?
Comment: @S.H.W which "first statement"?
Comment: @S.H.W If you mean $a>b, c>0\implies ac > bc$, that statement is an axiom.
Comment: Okay , Thanks a lot .

When $ac \gt bd$ is true?


How to parse generic response using Codable

Question: Every API have three parameters in the response.

Code : indicate whether API Success or fail(1 or 0)
Message : a string
Data: can be Array of object or single object.

i have created base model.
struct ResponseBase<T:Codable> : Codable {

    let code : String?
    let data : [T]
    let message : String?

    enum CodingKeys: String, CodingKey {
        case code = "Code"
        case data = "Data"
        case message = "Message"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        code = try values.decodeIfPresent(String.self, forKey: .code)
        data = try values.decodeIfPresent([T].self, forKey: .data)
        message = try values.decodeIfPresent(String.self, forKey: .message)
    }
}

struct SocialWarmer : Codable {

    let createdDate : String?
    let lookUpId : String?
    let lookupKey : String?
    let lookupValue : String?
    let parentId : String?
    let statusFlag : String?
    let type : String?
    let updatedDate : String?

    enum CodingKeys: String, CodingKey {
        case createdDate = "CreatedDate"
        case lookUpId = "LookUpId"
        case lookupKey = "LookupKey"
        case lookupValue = "LookupValue"
        case parentId = "ParentId"
        case statusFlag = "StatusFlag"
        case type = "Type"
        case updatedDate = "UpdatedDate"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        createdDate = try values.decodeIfPresent(String.self, forKey: .createdDate)
        lookUpId = try values.decodeIfPresent(String.self, forKey: .lookUpId)
        lookupKey = try values.decodeIfPresent(String.self, forKey: .lookupKey)
        lookupValue = try values.decodeIfPresent(String.self, forKey: .lookupValue)
        parentId = try values.decodeIfPresent(String.self, forKey: .parentId)
        statusFlag = try values.decodeIfPresent(String.self, forKey: .statusFlag)
        type = try values.decodeIfPresent(String.self, forKey: .type)
        updatedDate = try values.decodeIfPresent(String.self, forKey: .updatedDate)
    }

}

Following is Code For API Request.
class BaseApiClient {

    static let `default`  = BaseApiClient()

    private init() {

    }

    func fetch<model:Codable>(request:APIRouter,decoder : JSONDecoder = JSONDecoder()  ,onSuccess: @escaping ([model]) -> Void) {

        if Connectivity.isReachable {
            (UIApplication.shared.delegate as! AppDelegate).addProgressView()
            Alamofire.request(request).responseJSON { (response) in
                switch response.result {
                case .success( let apiResponse) :
                    DispatchQueue.main.async {
                        (UIApplication.shared.delegate as! AppDelegate).hideProgrssVoew()
                    }
                    if let responseData = apiResponse as? [String:Any] , let status  = responseData["Code"] as? String , status == "SUCCESS" {
                        do {
                            let responseModel  = try decoder.decode(ResponseBase<model>.self, from: response.data!)
                            onSuccess(responseModel.data!)
                        }
                        catch let error as NSError {
                            print("failed reason : \(error.localizedDescription)")
                        }

                        print(model.Type.self)
                        print(model.self)

                    }
                    else {
                        UIApplication.shared.gettopMostViewController()?.presentAlerterror(title: "Erorr", message: "Service not Avilabel" ,okclick: nil)
                    }
                case .failure(let error) :
                    UIApplication.shared.gettopMostViewController()?.presentAlerterror(title: "Erorr", message: error.localizedDescription, okclick: nil)
                }
            }
        }
        else {
            (UIApplication.shared.delegate as! AppDelegate).hideProgrssVoew()
            UIApplication.shared.gettopMostViewController()?.presentAlerterror(title: "Error", message: "connnection not avilabel", okclick: nil)
        }
    }

}

Following is code For calling API.
BaseApiClient.default.fetch(request: APIRouter.GetSocialWarmerType) { (response: [SocialWarmer]) in
    print(response)
}

But this model and API method will not work if data is single object.
What I am trying to achieve is to create single model and appropriate changes in API method that can parse both array of object and single object.
Comment: Unrelated, those `init(from:)` methods are unnecessary in your `Codable` types.
Comment: I'd also suggest just using Alamofire `response` rather than `responseJSON`. There's no point in having Alamofire parse your JSON if you're then going to parse it again.
Comment: You said that `Code` will "indicate whether API Success or fail(1 or 0)". But you then define it to be a `String?`. Seems if it is 1 or 0, that it should be `Int`. I'm also unclear about the notion that all three types of `ResponseBase` are optionals? Are you not guaranteed that at least `Code` is always there?
Comment: Finally, I'd suggest that the generic only employ the constraint of `Decodable` (not `Codable`). In practice, it's not likely to be a big deal, but `ResponseBase` doesn't really care whether the type in the response can be both encoded and decoded. It only cares that it can be decoded.
Answer: Finally I have Found one Workaround.i have Created two base class one for array of object and one for single object.
struct ResponseBaseArray<T:Codable> : Codable {

    let code : String?
    let data : [T]?
    let message : String?

    enum CodingKeys: String, CodingKey {
        case code = "Code"
        case data = "Data"
        case message = "Message"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        code = try values.decodeIfPresent(String.self, forKey: .code)
        data = try values.decodeIfPresent([T].self, forKey: .data)
        message = try values.decodeIfPresent(String.self, forKey: .message)
    }
}

struct ResponseBaseObject<T:Codable> : Codable {

    let code : String?
    let data : T?
    let message : String?

    enum CodingKeys: String, CodingKey {
        case code = "Code"
        case data = "Data"
        case message = "Message"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        code = try values.decodeIfPresent(String.self, forKey: .code)
        data = try values.decodeIfPresent(T.self, forKey: .data)
        message = try values.decodeIfPresent(String.self, forKey: .message)
    }
}

Following is Code For Api methods.
class BaseApiClient {

    static let `default`  = BaseApiClient()

    private init() {

    }

    func fetch<model:Codable>(request:APIRouter , decoder: JSONDecoder = JSONDecoder() ,onSuccess: @escaping (model) -> Void) {

        if Connectivity.isReachable {
            (UIApplication.shared.delegate as! AppDelegate).addProgressView()
            Alamofire.request(request).responseJSON { (response) in
                switch response.result {
                case .success( let apiResponse) :

                    DispatchQueue.main.async {
                        (UIApplication.shared.delegate as! AppDelegate).hideProgrssVoew()
                    }
                    if let responseData = apiResponse as? [String:Any] , let status  = responseData["Code"] as? String , status == "SUCCESS" {
                        do {
                            let responseModel  = try decoder.decode(model.self, from: response.data!)
                            onSuccess(responseModel)
                        }
                        catch let error as NSError {
                            print("failed reason : \(error.localizedDescription)")
                        }
                    }
                    else {
                        UIApplication.shared.gettopMostViewController()?.presentAlerterror(title: "Erorr", message: "Service not Avilabel" ,okclick: nil)
                    }
                case .failure(let error) :
                    UIApplication.shared.gettopMostViewController()?.presentAlerterror(title: "Erorr", message: error.localizedDescription, okclick: nil)
                }
            }
        }
        else {
            (UIApplication.shared.delegate as! AppDelegate).hideProgrssVoew()
            UIApplication.shared.gettopMostViewController()?.presentAlerterror(title: "Error", message: "connnection not avilabel", okclick: nil)
        }
    }

}

Following is Code for Calling Api.
BaseApiClient.default.fetch(request: APIRouter.GetSocialWarmerType) { (rsult:ResponseBaseArray<[SocialWarmer]>) in
            print(rsult.data)
        }

if your Api return single object than use ResponseBaseObject.
BaseApiClient.default.fetch(request: APIRouter.GetSocialWarmerType) { (rsult:ResponseBaseObject<SocialWarmer>) in
            print(rsult.data)
        }

but still this solution will only work if you already know your Api will return single object or array of object.
Comment: "but still this solution will only work if you already know your Api will return single object or array of object" ... Any given endpoint should always an array or always a single instance. If you have in-house API that is changing the structure of the response based upon whether it found one result or many results, then you should fix that rather than coding clients around a poor web service design. Note, the generic, `ResponseBase`, should still be able to handle both types, though, but at the calling point, you should know the precise structure of the response.
Answer: Your response object should just use T, not [T]:
struct ResponseObject<T: Decodable>: Decodable {
    let code: String
    let data: T?
    let message: String?

    enum CodingKeys: String, CodingKey {
        case code = "Code"
        case data = "Data"
        case message = "Message"
    }
}

Then, when you specify the type for the generic, that's where you specify whether it is a single instance or an array.
For example, when you decode single instance, it is:
let responseObject = try JSONDecoder().decode(ResponseObject<Foo>.self, from: data)
let foo = responseObject.data

But for an array, it is:
let responseObject = try JSONDecoder().decode(ResponseObject<[Foo]>.self, from: data)
let array = responseObject.data

Here is a sample playground:
struct ResponseObject<T: Decodable>: Decodable {
    let code: String?
    let data: T
    let message: String?

    enum CodingKeys: String, CodingKey {
        case code = "Code"
        case data = "Data"
        case message = "Message"
    }
}

struct Foo: Codable {
    let value: Int
}

do {
    let data = """
        {
            "Code": "some code",
            "Message": "some message",
            "Data": {
                "value": 42
            }
        }
        """.data(using: .utf8)!

    let responseObject = try JSONDecoder().decode(ResponseObject<Foo>.self, from: data)
    let foo = responseObject.data
    print(foo)
} catch {
    print(error)
}

do {
    let data = """
        {
            "Code": "some code",
            "Message": "some message",
            "Data": [
                {
                    "value": 1
                }, {
                    "value": 2
                }, {
                    "value": 3
                }
            ]
        }
        """.data(using: .utf8)!

    let responseObject = try JSONDecoder().decode(ResponseObject<[Foo]>.self, from: data)
    let array = responseObject.data
    print(array)
} catch {
    print(error)
}


Função - Alteração de formato de data em formulário preenchido X em branco

Question: Estou com uma dúvida. Preciso corrigir uma data em um formulário, porem se o campo estiver vazio, ele passa reto pela função e não executa. Se o mesmo estiver previamente preenchido, ele faz a alteração.
Inicialmente realizei assim, sem a validação do campo vazio:
  $(document).ready(function AcertaDataInsp() {

  var data = $("#dataInspecao").val();
  var aData = data.split("-");
  var datacompleta = aData[2]+'/'+aData[1]+'/'+aData[0];
  $("#dataInspecao").val(datacompleta);

  });

Minha dúvida é, como faço a função pra executar somente se o campo estiver preenchido? Hoje se executo a função acima, no formulário ele preenche assim "undefined/undefined/"
Answer: Se entendi, basta colocar um if verificando se o valor de data tem alguma coisa e executar o resto do código. Se estiver vazio, não entra no if e não executa o resto do código:
$(document).ready(function AcertaDataInsp() {

   var data = $("#dataInspecao").val();

   if(data){
      var aData = data.split("-");
      var datacompleta = aData[2]+'/'+aData[1]+'/'+aData[0];
      $("#dataInspecao").val(datacompleta);
   }
});

Comment: Funcionou desta forma. O detalhe do campo indefinido desapareceu. Vou testar em situações de data preenchida também.
Answer: Olá, William. Esse input que você está tentando formatar é do tipo date ? Se não for, recomendo que você utilize o input date juntamente com o evento .on('select', callback). Assim, você conseguirá formatar a data com a classe Date do próprio JS, da maneira que você desejar. Ou de uma maneira mais simples:
$(document).ready(function AcertaDataInsp() {
    $("dataInspecao").on('select', function(event) {
        var data = $("#dataInspecao").val();
        var aData = data.split("-");
        var datacompleta = aData[2]+'/'+aData[1]+'/'+aData[0];
        $("#dataInspecao").val(datacompleta);
    });
});

Comment: O formato que vem do banco está formatado no padrão data internacional em forma de String.


Exercise of Invertible matrix and other commutable

Question: What is the appropriate substitution to demonstrate the commutability and existence of the inverse
Let the matrix $A$ $3\times 2 $. Show that the following matrices are conmutable
a) $\left ( A\left ( A^{T}A \right )^{-1}A^{T} \right )^{3}-\left ( A\left ( A^{T}A \right )^{-1}A^{T} \right )+I-B$;
$\left [ \left ( A\left ( A^{T}A \right )^{-1}A^{T} \right )^{3}-\left ( A\left ( A^{T}A \right )^{-1}A^{T} \right )+I-B \right ]^{-1}$
b) Show that if $A^{3}=0$,
 then $A+I$ is invertible matrix,
where $0$ null matrix and $I$ identity matrix
Thanks for the help
Answer: (a) Follows from the definition of the inverse of a matrix. Say your expression is matrix C, then as long as $C$ is invertible, it commutes with its inverse.
(b) $(A+I)^{-1}=A^2-A+I$. This follows from $I=I-A^3=(I+A)(I-A+A^2)$. You can verify it is both right and left inverse.


Adjunction space quotient properties.

Question: Let $X\cup_f Y$ be an adjunction space. Let $q:X\coprod Y \rightarrow X\cup_f Y$ be the associated quotient map,
where $\sim$ is generated by $a\sim f(a)$ for all $a$.
Show that $q$ is injective.
My attempt:
Case 1: Let $(x_1,0),(x_2,0)$ ( I will write it as $x_1,x_2$) be in $X$. So $q(x_1)=q(x_2)\implies [x_1]=[x_2]$. Hence, $x_1\sim x_2$.
This means that there exists $a_1,a_2....,a_n$ in $X\coprod Y$ such that
$a_1=x_1$ and $a_n=x_2$ and for each $i=1,2,...,n-1$.
$a_iRa_{i+1}$ or $a_{i+1}Ra_i$ or $a_i=a_{i+1}$ $(*)$
Clearly, the first and second cases can't hold. Hence, $x_1=x_2$.
Case 2: Suppose $x\in X$ and $y\in Y\backslash A$, then clearly $x\neq y$. I must show that $[x]$ and $[y]$ are disjoint. This is clearly the case, since it contradicts all of the three cases in $*$.
Case 3: Suppose $x\in X$  and $y\in A$. Then clearly $x\neq y$.
The two other cases follows similarly.
Is my attempt correct?
Comment: $q$ is not injective. For example the wedge product $A\vee B$ is an example of an adjunction space and the quotient map sends both base points to the wedge point. In general $a$ and $f(a)$ map to the same point under $q$, so it can't possibly be injective unless $A$ is empty and $f$ is the empty function. Are you sure you've stated the problem correctly?
Comment: The initial problem was to show that the restriction of q to X is a topological embedding. Oh. I see. I was supposed to show that q restricted to X is injective. That is certainly the case, as shown in the first case. But where does my proof not hold above?
Comment: Case 3. Although it's clear that $x\neq y$ because they're in different spaces, it's still possible that $q(x) = q(y)$, namely when $x = f(y)$.
Comment: @William. Perfect.  Thanks. That is clear. I really appreciate it. Stating the first case to show the restriction to X is injection, suffices, right? Would you advise in writing it differently?
Comment: It seems a little vague to me (the word "clearly" is always a red flag :p If it's really clear then it should be easy to write down a justification). I will think about how I would phrase it and then write something down later.
Comment: @William For instance,  $a_{n-1}Rx_2$ would mean that $x_2\in A$. So the first case cannot hold. Note first $x_2$ is in the disjoint union. In other words, q does identify different points in X.
Comment: I meant to say does not
Comment: I think I figured out the missing piece that would make it more rigorous for me: somewhere you need to invoke the fact that *$f$ is well-defined*. I will write down what I have in mind in my answer.
Answer: $q$ is not necessarily injective on all of $X\sqcup Y$. In fact by definition $q(a) = q(f(a))$ for all $a \in A$, so $q$ is globally injective iff $A$ is empty. Your argument in case $3$ is not valid.
I think you have the right idea for Case 1 but I would get rid of the "clearly"s as follows. Let's say a "trivial relation" is one of the form $p\sim p$ and an "atomic relation" is one of the form $a\sim f(a)$ for $a\in A$; then every relation $p\sim p'$ which isn't trivial can be written as a sequence of atomic relations. Suppose now that $x\sim x'$ for $x \neq x' \in X$. Since there are no atomic relations between elements of $X$ or between elements of $Y$, there must be a sequence
$$x = x_1\sim a_1 \sim x_2 \sim \dots a_n \sim x_n = x'$$
alternating between elements of $X$ and $A$. But for $1\leq i < n$ we would have $x_i \sim a_i \sim x_{i+1}$ and so $x_i = f(a_i) = x_{i+1}$, where we're implicitly using the fact that $f$ is well-defined. It follows that we must have $x = x'$. (I think this argument is basically the same as what you were going for, this is just the way it makes sense to me.)
By a similar argument you can prove that $q$ is injective on $Y$ iff $f$ is injective, since the function $f^{-1}\colon im(f) \to A$ would be well-defined. (But still $q$ cannot be injective on all of $X\sqcup Y$ unless $A$ is empty.)
Answer: Maybe you're aiming for this well-known fact: if $f: A \to Y$ and $A$ is closed, then $q$ restricted to $X\setminus A$ is an open embedding.

Adjunction space quotient properties.


$f: R\rightarrow [0,\infty] $ is measurable

Question: Let $f: R\rightarrow [0,\infty] $ is measurable. Then, $\int_{R} f= c$ where $0< c< \infty $
\begin{equation}
\lim \int n \,  \log \left(1+ \left(\frac{f}{n}\right)^{\alpha} \right) =
 \begin{cases}
    \infty & \text{if} & 0< \alpha < 1 \\
    c & \text{if} & \alpha =1 \\
    0 & \text{if} & 1 < \alpha < \infty \\
  \end{cases}
\end{equation}
We need to check that if $\alpha \geq 1$, the integrands are dominated by $\alpha f$ and if $\alpha < 1$, apply Fatou's lemma.
 But, I don't solve this question. Please help me.
Answer: Let us show that $\log (1+t^{\alpha}) \leq \alpha t$ for $t \geq 0$ and $\alpha \geq 1$. For this note that the derivative of $\alpha t -\log (1+t^{\alpha})$ is $\alpha -\frac {\alpha t^{\alpha -1}} {1+t^{\alpha}}$. This is non-negative because $1+t^{\alpha} > t^{\alpha-1}$ for all $t \geq 0$. Since $\alpha t -\log (1+t^{\alpha})$ vanishes when $t=0$ we see that is is non-negative for all $t \geq 0$. This proves our claim. We have proved that the integrand in the given integral is dominated by the integrable function $\alpha f$ when $\alpha \geq 1$. Apply DCT to finish the proof when $\alpha \geq 1$.
Now let $\alpha <1$. The $nlog(1+(\frac f n)^{\alpha})\to \infty$ whenever $f >0$. [This is because $log (1+x) \sim x$ as $x \to 0$]. By Fatou's Lemma we get $\lim \inf \int nlog(1+(\frac f n)^{\alpha}) \geq \infty$ since $f>0$ with positive measure and $\int_{f>0} \infty =\infty$. [$f>0$ with positive measure  because $\int f =c >0$].
Comment: Thanks Dear Kavi Rama Murthy.


IIS Remote Manager is missing icons for a specific site

Question: I have a developer that came to me with and issue. He is remotely managing one of his sites on one of our development servers and all of a sudden he lost all of the icons in IIS for this specific site..
All other sites display his icons correctly and when I have him test on another computer everything displays correctly.. So what could have gone wrong on his machine? It was working but is now not working.. Any help here would be greatly appreciated.. Never seen this before and cant seem to figure out what caused it to just go away.. There should be so many more options for him.. Plus if you can see he lost the ability to see the folders on this site also.. And it is every site on this server.. But like I said it is just on his computer, he goes to a different computer he has access to everything..
Guess I cant post a picture.. But if you need to see it I can send it to you if you need to see what I am talking about..
Comment: Could it be a permissions issue? Is it only that developer or can other users see the icons fine. Regarding posting a picture, if you provide a link, someone with higher rep usually comes along and edits your post for you.
Comment: Yes its just this Developer.. Everyone else seems to be seeing everything fine.. And like I said he logs into a different machine he sees everything correctly. And verified he is in the same AD group as everyone else.. And it worked before but all of a sudden stopped and started to show nothing for him but one icon..
Comment: I have tried adding the picture different ways, uploading, providing a link and just adding a hyperlink to the image and it wont let me post it saying I cant post pictures.. even as a hyperlink..
Comment: Come to find out he was ignoring the prompt that he was getting saying that there were new versions of the tools to download on his machine that are on the server.. He just hit Cancel instead of selecting them and hitting ok to install the DLL's and enabling them..
Answer: Come to find out he was ignoring the prompt that he was getting saying that there were new versions of the tools to download on his machine that are on the server.. He just hit Cancel instead of selecting them and hitting ok to install the DLL's and enabling them.


Does SNI really require TLSv1 (insecure)?

Question: From the Apache 2.4 docs:

The first (default) vhost for SSL name-based virtual hosts must include TLSv1 as a permitted protocol, otherwise Apache will not accept the SNI information from the client and it will be as if the client did not support SNI at all.

I want to have multiple TLS enabled sites on my server, each giving a different certificate. For security reasons, I only allow TLSv1.1 and TLSv1.2. Is there a secure way to turn on SNI?
A snippet from my config:
<code><VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    DocumentRoot /var/www/example.com
    SSLEngine on
    SSLProtocol all -SSLv2 -SSLv3 -TLSv1
    [other SSL options]
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.org
    Redirect permanent / https://www.example.org/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.org
    DocumentRoot /var/www/example.org
    SSLEngine on
    SSLProtocol all -SSLv2 -SSLv3 -TLSv1
    [other SSL options]
</VirtualHost>
</code>
Comment: I suspect that's an error. Does the configuration work?
Comment: encountered  the same problem...
Answer: The wiki is contrasting TLSv1 from earlier protocols, not later protocols.  SNI works fine with TLSv1.1 and TLSv1.2.
Comment: So you mean it should read "TLSv1 OR LATER" indicating a TLS level must be present.
Comment: In a sense yes. It just requires TLS extensions which are TLS1.0 and later only.  TLSv1 is ambiguous, but in a doc that talks about an openssl .9.8 prerequisite take it with grain of salt.

(Tried to edit the wiki, but it's notoriously slow.)


Hide the displayed article in a most viewed/popular sidebar

Question: In an article panel page, i have a sidebar with the Most Viewed articles as per RAdioactivity module. If the main article that I am viewing is one of the Most viewed, I want to hide that article link in the sidebar but instead display the rest of the Most Viewed articles links. How can I do this using Panels, mini Panels, views?
Answer: I figured it out by going to Advanced > Contextual Filter. Choose Content: Nid. Then
under "WHEN THE FILTER VALUE IS NOT AVAILABLE", pick "Provide default value", Type = 'Content ID from URL'. Under "More", check on 'exclude' checkbox.


Could someone point me how adbd dump view hierarchy?

Question: I just asked this question: Are there ways to get android app view hierarchy from another android app?
I searched the android source a lot, and read the source code hierarchyviewer, seems that hierarchyviewer attached to adb, and then adb use socket connect to adbd runs on the emulator or device.
My device is rooted. Now i'm trying to make my android app connect to local adbd via socket, or call adbd functions via JNI.
Can someone hint me how adbd dump the system's view hierarchy?
Many thanks.
Answer: The HierarchyViewer server does not accept connections from local sockets. The only way to use HierarchyViewer is from the desktop.


Dotnetnuke (DNN) on azure websites - Are upgrades and module installs persisted?

Question: I signed up for the free azure website (not web role) and installed DNN 7 from the app catalog. So far so good.
My concern: The last time I checked (and I could be wrong) the application package that is published to azure is immutable and if you want to make changes to it, you must publish a whole new package to azure. Since DNN allows for upgrades and module installations, are these changes persisted? Can you still upgrade DNN by FTP'ing the upgrade package over the installation? If not how do you do it? I know about the dotnetnuke accelerator for web roles but I want to stick with the azure websites for now.
Answer: The immutable thing is for Web Roles, not Azure Web Sites. If you make a change to a web site, it is persisted.
Comment: That's good to know. I couldn't find this info on azure documentation. Thanks.


Arrays associativos

Question: Galera trabalho faz um tempo como designer/front-end, mas só agora estou estudando php e estou com uma dúvida.
Preciso criar um array associativo com 20 alunos contendo: matricula, nome e altura. E mostrar os 5 alunos mais altos da turma, mostrando somente a matricula do aluno e a altura.
Qual a melhor maneira de realizar esse exercício?
Answer: Use a função usort, para ordenar o array, a função auxiliar cmp define qual será o critério da ordenação e for exibe apenas os cinco alunos mais altos.
$alunos = [
        ['nome' => "Doge", "matricula" => "M1", "altura" => 1.70 ],
        ['nome' => "João", "matricula" => "M2", "altura" => 1.90 ],
        ['nome' => "Pedro", "matricula" => "M4", "altura" => 1.50 ],
        ['nome' => "Mario", "matricula" => "M3", "altura" => 1.60 ],
        ['nome' => "A1", "matricula" => "M5", "altura" => 1.90 ],
        ['nome' => "A2", "matricula" => "M6", "altura" => 1.88 ]

];

function cmp($a, $b) {
    return $a["altura"] < $b["altura"];
}

usort($alunos, "cmp");

for($i=0; $i<5;$i++){
    echo $i .': '.  $alunos[$i]['nome'] .' - '.$alunos[$i]['altura'] .'
';
}

Output:
0: A1 - 1.9
1: João - 1.9
2: A2 - 1.88
3: Doge - 1.7
4: Mario - 1.6

Uma variação da solução seria usa array_splice() para remover todos itens a partir da quinta posição e usar um foreach.
array_splice($alunos, 5);

foreach($alunos as $item){
    echo $item['nome'] .' - '. $item['altura'] .'
';
}

Comment: Muito obrigado, resposta muito valiosa me ajudou muito!!!!
Comment: Muito boa explicação, obrigado mesmo!!!

Arrays associativos


Can't figure why I can't hook up my AJAX handler through WordPress

Question: So I'm trying to follow the instructions here like a recipe book and am coming up for short. When I submit the form below, a POST request to http://thesite/wp-admin/member-update returns 404. As I understand, that request is supposed to trigger my function member_update() because of I set
<?php

add_action( 'wp_ajax_member-update', 'member_update' );

?>

at the beginning of my page. I can't figure out why it isn't working. The rest of the relevant code is the form
   <form method="POST" action="member-update"  enctype="multipart/form-data">

                                Full name:

                                <input type="text" name="fullname" value="">

                                Title:

                                <input type="text" name="title" value="">

                                Bio (approx 150 chars):

                                <input type="textarea" name="bio" value="">

                                Sort order:

                                <input type="textarea" name="sord" value="">

                                Pic:

                                <input type="file" name="pic">

                                <button type="button" class="member-update-button wp-core-ui button-primary" id="remv-btn">Remove</button>
                                <button type="button" class="member-update-button wp-core-ui button-primary">Add</button>

                    <input type="hidden" name="memberAction" value="" />

    </form>

and the JS to handle the button clicked on the form
        jQuery('.member-update-button').click( function() {
                var parentForm = jQuery(this).closest('form');
                var formUrl = parentForm.attr('action');
                var formMethod = parentForm.attr('method');
                var postData = parentForm.serializeArray();
                jQuery.ajax(
                    {
                        url: formUrl,
                        type: formMethod,
                        dataType: 'json',
                        data: postData,
                        success: function(retmsg)
                        {
                            alert(retmsg); // test for now
                        },
                        error: function ( )
                        {
                            alert("error"); // test for now
                        }
                    }
                );
        } );

and the PHP function at the bottom of the page
<?php

function member_update()
{

    $message = '';

    $message .=  'Action : ' . $_POST['memberAction'] . '.   ';
    $message .=  'Name: ' . $_POST['fullname'] . '.    ';
    $message .=  'Title: ' . $_POST['title'] . '.    ';
    $message .=  'Biography: ' . $_POST['bio'] . '.    ';
    $message .=  'Sort order: ' . $_POST['sord'] . '.    ';
    $targetFileName = basename($_FILES['pic']['name']);
    $targetFileNameAndPath = 'assets/' . $targetFileName;
    $message .= 'Target file: ' . $targetFileName . '.    ';
    $message .= 'Target file (with path): ' . $targetFileNameAndPath . '.    ';

    $thismbr = new TeamMember($_POST['fullname'], $_POST['title'], $_POST['bio'], $_POST['sord'], $targetFileName);

    $thisAction = $_POST['memberAction'];

    if ($thisAction == 'add')
    {

        $addMemberResult = $T->addMember($thismbr);

        if ($addMemberResult->succeeded)
        {
            $message .= "Successfully added member to list\n";

            if (move_uploaded_file($_FILES['pic']['tmp_name'], $targetFileNameAndPath))
            {
                $message .= "Successfully added " . $targetFileName . " to assets folder\n";
            }
            else
            {
                $message .= "Encountered problem when trying to add " . $targetFileName . " to assets folder\n";
            }
        }
        else
        {
            $message .= "";
        }
    }
    elseif ($thisAction == 'update')
    {
        // ...
    }
    elseif ($thisAction == 'delete')
    {
        // ...
    }
    else
    {
        $message .= 'Didn\'t recognize action';
    }

    echo json_encode($message);

}

?>

Any idea what I'm doing wrong?
Comment: using incorrect url for wordpress ajax
Comment: You are using the WordPress AJAX approach in the wrong way. First, the ajax URL is http://yourdomain/wp-admin/admin-ajax.php that endpoint handle all the ajax request. Second, you need to define the handlers for private and public request, please read https://codex.wordpress.org/AJAX_in_Plugins
Answer:     jQuery('.member-update-button').click( function() {
         var parentForm = jQuery(this).closest('form');
         var postData = parentForm.serializeArray();
            jQuery.ajax({
                url: "<?php echo admin_url('admin-ajax.php'); ?>",
                data: {action: 'member_update', postData: postData},
                type: "POST",
                dataType: 'json',
                success: function(retmsg)
                {
                    alert(retmsg); // test for now
                },
                error: function ( )
                {
                    alert("error"); // test for now
                }
            });
    });

try this...


What test would you use for my data. I think independent t-test?

Question: I have two groups:

Group 1, I ask them how willin to start once monthly pill and mark their response between 1-10.
Group 2, I first ask them how willin once daily pill, then I ask them once monthly.
I want to compare: How willin would subjects be to start a once monthly pill for hypertension between the two groups. I think those I ask once daily first would be more willin for once monthly.
What test would you use for my data. I think independent t-test? I have 200 total responders.
Comment: Do you want to include age, race and Bender information in that comparison? Are the people in both groups the same people?
Comment: People in both groups are different. I wanted to first do normal analysis then do subgroup analyses and capture age, race, and gender.
Comment: And my other question?
Comment: People in both groups are different. I wanted to first do normal analysis then do subgroup analyses and capture age, race, and gender.
Answer: In a strict sence, the t-test is for metric data and your data (or residuals) will never meet normality assumptions. One could therefore argue, that a rank sum test was more appropriate and with that n, it should have good power.
On the other hand, the t-test is pretty robust at n=200 and it is better known in some audiences.
It is a borderline case, in which both possibilities can be defended. If you might have to defend it against someone very strict, a rank sum test may be advantageous.
Comment: Thank you for the response! I had a couple questions for my own general curiosity. 1) For the rank sum test, to confirm, my data would still not meet assumptions as the data isn't paired and doesn't come from the same population? 2) By rank sum test, in this case, the Mann–Whitney U test is more appropriate than the Wilcoxon signed-rank test? 3) At n=100, would the t-test still be considered robust? 4) Using subgroup analyses with age if n=50 (25 in each group), would that be acceptable or is the sample size too small for subgroup analyses?
Comment: 1) yes, it's a test for independent data 2)They come to identical results/are interchangeable. Name it as you want. 3) Matter of taste, usually yes. Some say >30, some >50, just stay reasonable. 4) subgroup analyses will lead to multiple testing and alpha inflation, which is probably the bigger problem to consider. Personally, I'd prefer the nonparametric alternative.


Multiple versions of the same menu, based on associated term?

Question: I am trying to create a site with different portals. Each portal displays content filtered to that person's user tag, i.e. Student, Staff, etc. It's easy to create a view that displays nodes with that user tag (taxonomy term), but I am looking to have a user tag-specific menu. Many items in my menu structure apply to multiple user tags, some to only one or the other. How can I have the portal page display a menu that only contains nodes with the appropriate tag?
I know that if I used actual Drupal roles I could give permissions to the pages, and then when someone is logged in with the appropriate role, they only see the pages that they have permission to see. This is the same idea, but I don't want to require users to log in. Only access the menu through a specific portal.
Hopefully I described that well enough, thanks for any suggestions!
Answer: I've done this just recently by implementing a single menu that shows different links depending on the context (in your case the context is a portal). The one menu will have all the links for all portals, and is set to rebuild itself on each context containing the relevant links for that context. You can do this as follows.

Implement hook_node_access_records() and hook_node_grants() to create viewing access records on the nodes that only allows for them to be viewed on the portal to which they belong.
Alter the canonical route for nodes to provide a custom access callback. This access callback will include a check on whether the user has viewing access to the node. This will ensure that nodes only show up in the menu when on the portal to which they belong.
Create a custom cache context for your portal, so that the menu can be set to vary by portal.
Set your menu block to have the portal cache context, so that the menu is rebuilt for each portal, showing the correct menu items for the given portal.

1) Implement node grants
Node grants involve two hooks, hook_node_access_records() and hook_node_grants().
First, hook_node_access_records(). This hook is called upon node save. In it you perform calculations to determine upon which portals the node will be accessible. For your setup, you will set a record for each portal the node can be accessed at. Example:
function hook_node_access_records(NodeInterface $node) {
  $grants = [];

  // A grant needs to be added for each portal on which the node should be accessible.
  $grants[] = [
    // This will always be the same.
    'realm' => 'portal',
    // This will be the identifier of the portal.
    'gid' => 'portal_1,
    'grant_view' => 1
    'grant_update' => 0,
    'grant_delete' => 0,
  ];

  return $grants;
}

How you get the GID (the portal ID) of the node will depend on how your system is set up. It sounds like your portals are set up using taxonomy terms. If that's the case, in hook_node_access_records() you can query that field to get the values from the taxonomy field and set your grants accordingly.
Next is hook_node_grants(). This hook is called anytime a node is accessed. This check will check if the user is on a portal, and add a grant for the current portal.
function hook_node_grants(AccountInterface $account, $op) {
  if ($op == 'view') {
    if ($portal = some_function_that_gets_the_current_portal_id()) {
      $grants = [];
      $grants['portal'] = $portal;
      return $grants;
    }
  }
}

This code will return a grant for the current portal. If the node being accessed also belongs to the current portal (by matching a grant set in hook_node_access_records()), viewing permission will be shown.
2) Alter canonical node paths with a custom access callback.
With the above two hooks implemented, viewing access permissions for the node have been taken care of. However, the route is still accessible, as access permissions on the route only check if the user has 'access content' permission, and doesn't include a check on whether user has permission to access the node the route displays. When building menus, route permissions are checked, not access permissions on the node. So the next permission is to override the route, and provide a custom access callback that also checks whether the user has viewing access on the node. This way, due to the node grants set in steps one and two, when the menu is rebuilt, it will only add items to the menu if the user is on the portal the items belong to.
To do this, first an event subscriber is created to alter the routes:
namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setRequirement('_custom_access', 'Drupal\my_module\Access\PortalNode::access');
    }
  }

}

The above class will alter the entity.node.canonical route, giving it a custom access callback. The next thing to do is create Drupal\my_module\Access\PortalNode::access() and include the check on viewing permissions for the node. This class will look like:
namespace Drupal\example\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PortalNode implements ContainerInjectionInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a PortalNode instance.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   */
  public function __construct(
    AccountProxyInterface $currentUser
  ) {
    $this->currentUser = $currentUser;
  }

  /**
   * {@inheritdoc}
   */
   public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }

  /**
   * Custom access callback for node canonical routes.
   *
   * @param \Drupal\node\NodeInterface
   *   The node whose canonical route is being accessed.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   An access result that either provides or denies access.
   */
  public function access(NodeInterface $node) {
    // Allow access if the user has 'access content' permission (the default)
    // as well as viewing permission on the given node.
    return AccessResult::allowedIf(
      $this->currentUser->hasPermission('access content')
      &&
      $node->access('view')
    );
  }

}

Finally, the event subscriber needs to be registered in my_module.service.yml so it is picked up, and the route is altered:
services:
  my_module.route_subscriber:
    class: Drupal\my_module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

3) Add a custom cache context for portals.
As your menu will need to differ by portal, it must have a cache context set for portal. There may already be a cache context you can use that matches the Drupal functionality behind your portals. You can check existing cache contexts here: https://www.drupal.org/docs/8/api/cache-api/cache-contexts#core-contexts
If the cache context you need does not exist, you'll need to create a custom cache context. Here's an example: https://medium.com/@joshirohit100/cache-context-drupal-8-part-2-10088f67012e
4) Set the menu block to vary by the portal cache context
At this point everything is mostly set up, however, the first time the menu is built, that version of the menu will be shown the same on all portals, as it has not been set to vary by portal cache context. Your system needs to have the menu block vary by portal - ie. variations of the menu must exist for each portal, since each portal will have a different list of links in the menu.
To do this, you'll implement hook_block_alter() in order to add a custom cache context on the menu block. You'll need to get the ID of the menu from your system. Let's assume it's "portal-administration".
/**
 * Implements hook_block_alter().
 */
function my_module_block_alter(array &$definitions) {
  $definitions['system_menu_block:portal-administration']['class'] = 'Drupal\my_module\Plugin\Block\PortalAdministrationMenuBlock';
}

Finally, the class defined in hook_block_alter() is created. It's extends the system default menu class, and adds the portal cache context to the menu block:
namespace Drupal\my_module\Plugin\Block;

use Drupal\system\Plugin\Block\SystemMenuBlock;

class PortalAdministrationMenuBlock extends SystemMenuBlock {

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $cache_contexts = parent::getCacheContexts();
    $cache_contexts[] = 'portal';

    return $cache_contexts;
  }
}


Are constructivists in favor of the Property of Baire?

Question: Since the Axiom of Choice proves the law of excluded middle, constructivists reject it. Does this mean that constructivists are in favor of the negation of Choice?
I take this further: Perhaps constructivists are in favor of an axiomatic system stronger than $\mathsf{ZF \neg C}$. Since this system is alone "too negative", I speculate that, constructivists are in favor of accepting a "positive" axiom that clashes with Choice, such as the Axiom of Determinacy or the Property of Baire.
So do the majority of constructivists actually do this? Personally I am not currently a constructivist, but I would be a fan of the Property of Baire if I had to convert to constructivism.
Comment: I'll let a constructivist answer, but my perception is that neutrality and relativism ("depends which topos you're working in") are more in vogue than outright believing things that contradict classical math.
Comment: I think by "the property of Baire" you mean "all sets of reals have the property of Baire"?
Comment: @spaceisdarkgreen Yes.
Answer: tl;dr In the first section I explain why constructive rejection of choice would not necessarily mean being in favor of negating it. Sections II and III talk about the status of choice itself, and why many constructivists prefer not to take even positive anti-Choice axioms. Finally, Section IV provides a partial answer the question you probably intended to ask (the one about anti-Choice axioms in mathematics without LEM in general, rather than the philosophical constructivism)
I. Constructivists are a diverse bunch, not cogs in some kind of unified political movement. There are no chief whips to tell you whether you can or cannot use various axioms. At best, there are some identifiable schools whose adherents reliably take various axioms (such as the Russian school of constructive mathematics, associated with Markov's principle; or Intuitionism, associated with Brouwer's fan theorem), but not all constructivists belong to any of these.
Moreover, not many people who work primarily (or even exclusively!) in constructive mathematics have constructivist convictions. Most of the highest-profile contributors to constructive mathematics advocate some form of mathematical pluralism [1].
At this point, constructive mathematics usually just refers to mathematics done without the principle of excluded middle, and without other principles, such as the full axiom of choice, that would imply it. Constructivists themselves might decide to do constructive mathematics, usually for some kind of philosophical reason [2].
Accordingly, the fact that constructivists are forced to reject the Axiom of Choice in no way implies that they'd all be in favor of its negation. Certainly, constructivists universally reject e.g. excluded middle, but that does not mean they are in favor of negating it! (See also the Denial section of Bauer's Five Stages essay.)

II. There's more than meets the eye about "Choice implies Excluded Middle", though.
Consider the following principle: "if $\forall x \in A. \exists y \in B. \varphi(x,y)$ holds, then we  have a function $f: A \rightarrow B$ so that $\forall x \in A. \varphi(x,f(x))$ holds". It looks exactly like the Axiom of Choice ruled out by Diaconescu's theorem (take $\varphi(x,y)$ to denote $y\in x$). Nonetheless, the principle is validated by the Brouwer-Heyting-Kolmogorov interpretation, and is in fact a fully provable theorem of Martin-Löf's Constructive Type Theory!
How do we explain this? How can the status of this principle be so so different in constructive type theory and constructive set theories?! Well, Diaconescu's proof uses multiple principles about sets and set-formation, not just the Axiom of Choice in isolation. Accordingly, the interaction of all the principles used in the proof lead to Excluded Middle, not any one of them. We can put the blame on Choice and reject it, or we can choose to weaken some other principle to prevent the proof from going through. E.g. a more thorough analysis might identify set theory's ability to form unrestricted quotients as the culprit, or in some cases even instances of separation). The former leads to the observation that "extensional Choice" or "setoid Choice" does imply Excluded Middle, even in type theory. The introduction of propositional truncations (which might itself be a subject of some controversy in some schools) and Homotopy Type Theory allows ever more stringent analyses about what sorts of choice principles should be admissible -- and indeed endless debates about which of these principles even deserve the name Axiom of Choice. The Coq Choice facts page provides a good, referenced summary of Choice principles in type theory.
At this point one should mention the fact that some forms of Choice tend to have quite tame consequences over constructive mathematics, even when they have wild consequences over a corresponding classical system. Adding the Axiom of Choice in the form $(\forall x \in \mathbb{N}. \exists y \in \mathbb{N}. \varphi(x,y)) \rightarrow \exists f: \mathbb{N} \rightarrow \mathbb{N}. \forall x \in \mathbb{N}. \varphi(x,f(x))$ to higher-order Peano Arithmetic yields a far more powerful system. Adding it to higher-order Heyting arithmetic has no arithmetic consequences at all.

III. So, how often do constructivists take positive axioms that altogether clash with Choice? In my experience, not that often.
First of all, the Brouwer-Heyting-Kolmogorov interpretation fully justifies Choice: if you practice constructivism because you find the BHK interpretation compelling in some sense, it makes no sense to take axioms that contradict it.
Second of all, a constructivist usually sacrifices Excluded Middle not on a whim, but to achieve some higher constructive goals. Goals such as the existence property, that from a proof of $\exists x. \varphi(x)$ you can without creative work extract some kind of object $t$ that actually satisfies $\varphi(t)$ [3]. Similarly, the disjunction property, which states that from a proof of $A \vee B$ you can without creative work extract either a proof of $A$ or a proof of $B$. These both fail in classical systems.
When the constructivist sacrifices Excluded Middle to obtain a constructive system obeying such desirable properties, it wouldn't really make sense to then adopt a new principle which breaks these properties. This rules out Determinacy, which asserts the existence of winning strategies for various games, but does not provide any methods for finding these strategies (hence breaking the existence property), or even the identity of the winner (hence breaking the disjunction property).
Even universalizing principles, which state that the only examples of some phenomenon are the nice, constructible ones, may in fact seem undesirable from this perspective! Consider the functor $\mathrm{Hom}(\mathbb{N}, -): \mathrm{FinSet} \rightarrow \mathrm{Set}$ and the inclusion functor $\iota: \mathrm{FinSet} \rightarrow \mathrm{Set}$. I once proposed (a more general form of) the following axiom, convenient for category theory: $\mathrm{Nat}(\mathrm{Hom}(\mathbb{N}, -), \iota) \cong \mathbb{N}$. This would constitute a straightforward generalization of the Yoneda lemma, which gives that for a finite set $F$, the natural transformations $\mathrm{Hom}(F, -)$ to the inclusion functor $\iota$ correspond to elements of $F$. It's a positive principle, and not compatible with full Choice since it implies the non-existence of nonprincipal ultrafilters. Moreover, it's easy to see that the only natural transformations from $\mathrm{Hom}(\mathbb{N}, -)$ to $\iota$ that you can actually construct are in fact the evaluation maps at some natural number. And yet this principle is still non-constructive: if you hand me a natural transformation from $\mathrm{Hom}(\mathbb{N}-)$ to $\iota$, I won't be able to constructively recognize which natural number you used to construct it!
The late Troelstra's Uniformity Principle also has a nice topological/constructive universalizing motivation, and breaks LEM (and Choice) in various satisfying ways when added to constructive set theory. Yet it also fails to retain constructive character, similarly to my Yoneda-type axiom above.
It's also worth mentioning that positive anti-Choice principles tend to give you some Choice -- even classically, where Determinacy implies Countable Choice, although it contradicts full Choice. In constructive set theories, you would not want to admit principles which constructively contradict full Choice, but give you some Choice: a little Choice goes a long way toward Excluded Middle.

IV. If you give up on retaining the constructive character of your system, you can add several principles to a constructive set theory (or a topos) that contradict Excluded Middle. The Kock-Lawvere axiom in smooth topoi is a famous example: it contradicts the theorem of classical algebra stating that fields lack zero-divisors. This is the domain of pluralism, more so than constructivism (although I wouldn't rule out a constructive interpretation of smooth topoi one day).
But even in Boolean topoi, failures of Choice are useful: see about $G$-$\mathrm{Set}$ here. Alas, I personally don't know any "mathematically natural" Boolean topoi which would obey some analogue of Determinacy, or other positive anti-Choice principles (except insofar as the Boolean-valued models of set theory itself are "mathematically natural").
Finally, in type theory, you can sometimes get around the phenomenon discussed above, that postulates tend to break existence properties, by taking negated or double-negated forms of your axioms. The Coquand et al. paper on the subject is very nice. However, by doing this, one gets back precisely to the realm of the "too negative" axioms!

[1]  I will not talk about the views of pluralists here, and what axioms they take or not take. Partly because I'm not one of them, and partly because some pluralists seemingly have a whole lot of time and opportunity to talk about it, so information about their views is easy to come by.
[2]  But this is not a necessity either: e.g. I'm philosophically a more extreme constructivist than most, but all my work uses LEM, because I prefer to focus on academic opportunities over philosophical purity. I wish things would be different, but fat chance of that.
[3] In the study of proof theory and pure logic, one calls this the existence property. There is an unfortunate terminological clash, where in constructive set theories, the "existence property" refers to a subtly different principle (one that, funnily enough, tends to fail for these systems). In set theories, the so-called "numerical existence property" is much closer to what we simply call the existence property in logic. Canonicity in type theory is again closely related.


Chi-square with unbalanced design

Question: I am a Ph.D. candidate of Applied Linguistics. Currently I am involved in a research study about English teachers' provision of corrective feedback on English L2 learners' errors. I have divided the teacher participants into two groups.
I want to juxtapose the groups in terms of the number (frequency) of corrections they supply in response to the learners' errors. I suppose I should apply chi-square test.
However, as the group sizes are different (10 teachers in group A and 15 teachers in group B), I am sort of uncertain about the applicability of chi-square test.
I want to know if there is any statistical test that is capable of dealing with frequency data while not impacted by the lack of equality in group size.
Comment: I am not sure the group size is the main problem here, more details could be useful. Does every teacher teach the same students in turn, were they randomly attributed to a class or are they just teaching whatever students they have at the moment? Where do this frequencies come from? A fixed/known number of learners' error? How and why do you want to use a Chi2 test? What's the underlying question?
Answer: Chi-square makes no assumptions about equality of group sizes.
The correction rates for the two groups can be compared (and indeed, different amounts of work per teacher within each group can be dealt with by the use of exposures, so if the A group marked twice as much work each as the B group that would also be fine).
Am I right to assume the groups are looking at the work of different students, rather than the same pool of students being marked twice?
I'd be inclined to use Poisson regression (where, for example, the model can be elaborated relatively easily, if required), but if you condition on the total number of corrections it would become a binomial test of a known proportion, which can also be done as a chi-square.
It would be good to explain what the underlying aim is more clearly, without using words like 'test', 'chisquare' or 'design' - you say 'juxtapose' - but that simply means to place unlike things together, which suggests you need a table. What do you want to find out about and why would hypothesis tests answer your underlying questions of interest?
---
Example of how to do the binomial / chi-square calculation:
Possible objection: Assumes the groups are internally homogeneous (i.e. there's no variability in the underlying rate of corrections within group - the observed variation is due to random variation around the shared level). (Other assumptions, like independence, are probably uncontroversial.)
Say the correction counts - on the same set of items, but different students - are as follows:
<code> A: 27 30 32 34 40 30 24 30 32 19 43 31 29 27 23    total: 451

 B: 32 50 43 37 39 39 38 47 31 38                   total: 394
</code>
If the rate of correction is the same for both groups, the total number of corrections should be proportional to the number of teachers.
That is, the sum of the A sample is expected to be a fraction 15/(10+15) (=60%) of the overall number of corrections. The total number of corrections across all teachers is 845.
The expected number of corrections in group A is 845 x 0.6 = 507, and in group B is 845 x 0.4 = 338.
The chisquare (for my made up data!) is
$$(451 - 507)^2/507 + (394 - 338)^2/338 = 15.46$$. The d.f. is 1.
As a binomial, we just test that the A proportion is 60%:
The observed total count in A is binomial(n=845,p=0.6); with a two-tailed test, we could use the normal approximation to the binomial proportion and get:
$Z = \frac{451/845 - 0.6}{\sqrt{0.6 (1-0.6)/845}} = -3.932$
(the square of this Z is the chi=square value above; its two-tailed p-value is the same as the p-value for the chi-square)
The exact binomial calculation is also quite readily done, but I won't labor the point.
---
A more complicated - but more defensible - analysis would be to fit a mixed logistic model, where  'teacher' is a random effect. This would allow for the fact that teachers have individual variation in their correction rate.
Comment: I have 30 teachers and for each teacher there is a single student. I have divided the teachers into two groups based on their education. Group A teachers have Ph.D. Whereas group B have B.A. . The question to be answered is whether groups A provide more error correction (i.e. frequency) than group B. Groups A has more teachers than group B. I wonder if I can use chi2 test while there are two unequal groups.
Comment: My null hypothesis is that teachers' education does not impact the rate of their error correction provision.
Comment: "*I wonder if I can use chi2 test while there are two unequal groups.*" --- That was already covered in my answer. The answer is yes, though the direct binomial test, while essentially equivalent, is probably more readily understood/informative.
Comment: I have edited some details into my answer, and explained  a reasonable objection to the chi-square approach, as well as a potential solution to that objection.
Comment: I got the point. If the groups' rates are different, I can run chi2 or binomial without calculating proportions. If the rates are equal, I have to calculate proportions and then run the test. Am I right?
Comment: No. You can do any of those calculations either way.

Chi-square with unbalanced design