How can I compare regression coefficients in the same simple regression model

Question: I think someone can help me to solve this problem. I scanned 40 samples in order to obtain two parameters: BMD and TBS. I have performed a regression analysis in order to study the relationship between BMD (dependent variable) and TBS (indipendent variable).
After that I have damaged the samples with a compression (mechanical) test. Then I rescanned the samples in order to measure BMD and TBS. I have performed a t-test and I have verified that BMD and TBS change after the damage.
Now I want to perform a second regression analysis between BMD and TBS and compare the regression coefficients of this second regression analysis with the first one.
How can I do it? Is there a particular test for this case?
Answer: Have a look at what's discussed here: Testing equality of coefficients from two different regressions.
Though you actually describe a setup with paired samples here, which might give you alternative options.


how to call a sub in same module

Question: I'm looking for a way to go back to the previous after the user reads a large message. The reason for it being in a separate sub is because it has 50+ lines of text and I wanted to cut down on load time. I must have gone all over the internet with not much luck finding an answer. I've tried this but get "process is terminated due to StackOverFlow Exception"
Heres the simple version of my code:
Sub notes()
    Dim a2 As String
    Do Until a2 = ("b") Or a2 = ("B")
        Console.Clear()
        Console.WriteLine("--------------------------------------------------------------------------------")
        Console.WriteLine("General Notes:")
        'more lines of text
        Console.WriteLine("--------------------------------------------------------------------------------")
        Console.WriteLine("Engine Status:")
        'more lines of text
        Console.WriteLine("Press  to go back to the menu")
        a2 = Console.ReadLine()
    Loop
    If a2 = ("b") Or a2 = ("B") Then
        Call Main()
    End If

End Sub

Comment: Assuming that `Sub notes` was called from `Sub Main`, the way to return to Main is to use the Return statement `If a2.ToLower() = "b" Then Return`. Don't try to call Main again.
Comment: Typo: "I'm looking for a way to go back to the previous sub after the user reads a large message."
Answer: After notes sub is completed, e.g a2 = "b" or a2 = "B", the program will automatically return to the main sub (assuming that you called it from there). You can't call the Main sub in the module.

how to call a sub in same module


React Native select default value to 1

Question: I hope you all can help me with this problem, I just want that if the selection is no value, the it will automatic 1, and if not, it will get the value of what the user select in the dropdown (I dont have problem with that), My problem is, I just want that if the user dont select in the dropdown menu, it will get automatic 1.
const submitForm = async(valuesToSubmit) =>
{
 console.log("valuesToSubmit:= ", valuesToSubmit['documentId'])
 let _intfmdocument=0,
 if valuesToSubmit['documentId'] !== null{
    _intfmdocument = valuesToSubmit['documentId']
 }else{
    _intfmdocument = 1
 }
 .....

}

<Select
   isSearchable
   options={docuLoc}
   className={classes.selection}
   value={documentId!== null ? documentId: 1}
   onChange={(itemValue) => {
          setDisplaySelectedDocumentLocation(itemValue)
          setFieldValue("documentLocationsId",itemValue.value)
   }}
   name='documentId'
 />

this is the result of console.log("valuesToSubmit:= ", valuesToSubmit['documentId'])
Answer: Sounds like you really just need to set a default value
Tray adding:
defaultValue={{ label: "whatever the label is", value: 1 }}
somewhere to the  attributes

React Native select default value to 1


Any pointers on how to convert 4/4 to 3/4?

Question: I'm currently studying Music Theory using the RSA grades (formerly known as RockSchool). I'm trying to get through on my own at the moment but I'm half-way through G6 and I'm increasingly feeling the need to get a tutor!
I'm looking at a G6 question that ask for a 4/4 pattern to be converted to 3/4 - I've previously answered questions on converting 4/4 to 2/4 and also 4/4 to compound time signatures and these have not been a problem - for some reason I can't figure these ones out!
Can anyone recommend any online resources or offer any advice as to how I should approach this?
Edit: this is an example of what I'm trying to get my head around. Obviously, I'm not looking for the answers to the questions, I'm looking for any advice as to how to tackle them.
Comment: It's tough to answer without the specific example, but I would bet you're probably not expected to convert it so that it's precisely the same rhythm. I would assume--and maybe I'm wrong!--that what's more important is the general long/short relationships and rhythmic feel of the example.
Comment: Well, do you want to turn a march into a walz?
Comment: Resource recommendations are off topic. Instead just pick any example in 4/4 and ask about it. Also is it transcription or arranging as those are two very different approaches.
Comment: Ah ok, in that case I'll take a picture of one of the questions and post it up later.
Comment: Question updated.
Comment: Can you clarify whether you want the example rebared so that three bars of 4/4 become four bars of 3/4, so you keep the same number of beats? That is much more straightforward than the other possibility which is to renotate the sample so that you have three 3/4 bars, where each 3/4 bar has the same duration as the corresponding 4/4 bar.
Answer: Have a listen, and a look at Fly Me to the Moon. Written in 3/4, but far more commonly played and sung in 4/4. See how the notes are lengthened in each bar to accomodate the extra beat. Notice that the same word/note stays on beat 1, whichever time sig. is used.The same works in reverse from 4/4 into 3/4, with appropriate shortening of other notes in each bar. Probably easier to understand when there are words.
EDIT : due to the slight change in flavour of the actual question, you will end up with exactly the same note values, but spread differently through the new bars.This will involve ties, as some of the notes won't fit exactly into the new time sig. But each and every note will be there, just with different emphasis. It's a theory exercise, probably wouldn't happen in real life!
Comment: Also check out Kashmir by Led Zeppelin..It also uses a 3/4 4/4 combo where the drums and the guitar sync up every 12 beats or something...its pretty genius
Answer: If we're trying to retain the original rhythms of the melodies, I have two suggestions.
First, you can 'force' the melody into 3/4 by converting each note to the note half its duration plus a dot -- a whole note becomes a dotted half note.  This is basically squeezing the 4/4 measure into the walls of the new 3/4 measure.  Try playing this a bit to get the feel of the result.
This is the polyrhythmic approach of 4 over 3 and can be heard in Chopin's Fantasie Impromptu, which is normally too fast to catch but is played slowly here.  (The piece is technically not in 3/4, but if you consider the triplets in the left hand to be a 3/4 setting you have exactly the same idea.)
That can work, but it's a bit harsh rhythmically and maybe you want to achieve that rolling 'three' feel.  For that you can swing a 4/4 into two measures of 3/4, essentially making 6/8, though you can still emphasize the three quarter notes.
If we played Frère Jacques in this manner, we'd have a 3/4 measure with the first four notes played as quarter note, 8th note, quarter note, 8th note.  That's like |Ь БЬ Б|Ь БЬ Б| etc. but with 3/4 emphasized (not 6/8).  It's a bit unusual but it works, by which I mean that it works musically.
To try to give you an aural example, consider this video of Bring a Torch, Jeanette Isabella and try tapping 3/4 to it, emphasizing "one-and-two-and-three-and" to overcome any temptation to hear it as 6/8.  Note:  This example is just off the top of my head.  If I think of a better example I'll post it (and others are welcome to suggest one).
Comment: I think the first part of your answer is heading in the right direction as far as the specific questions go - I've updated the question with a picture of the grade workbook.
Answer: Based on your update, the example you write will have the same number of beats as the original. The three measures of 4/4 (12 beats) of the first example will be converted to four bars of 3/4 (also 12 beats). Thus you're not changing any of the rhythms, you'll just be adjusting a few ties and breaking some note values into two.
One way of approaching this is to mark each beat of the original, and then after every x number of beats (the new meter) provide a heavier mark for the new barline. Then simply translate that rhythm into the new time signature.
In the first example you would mark beats 2, 3, and 4 of the first measure. (You could also mark beat 1 of that measure, but that's a little redundant.) Since you want to convert it to 3/4, beat 4 is your new beat 1. But a quarter note goes right through the new beat 1! So you'll need an eighth note on the "and" of beat three that ties into an eighth note on the downbeat of the second 3/4 measure.
I hope that's clear. Here's a notated example for the first one!


Why this code is working for 1 and 2 yet fails for input that is more than 3?

Question: So I am trying to print patterns in C.
For n = 2
Output:
2 2 2
2 1 2
2 2 2
for n = 3
Output:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
and so on.

My Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    scanf("%d",&n);
    int nn = n;
    int *arr;
    arr = (int*)malloc(n*sizeof(int));
    int f = 0; //flag to check if I reached the mid of the pattern
    int l = 2*n-1; //Lenght of square to be generated
    int temp1 = 0;
    int temp2 = l;
    for(int i = 0;i<l;i++)
    {
        for(int j = temp1;j<temp2;j++) //change values in range temp1 to temp2
        {
            arr[j] = n;
        }
        for(int k = 0;k<l;k++)
        {
            printf("%d ",arr[k]);
        }
        printf("\n");
        if(n == 1)
        {
            f = 1;
        }
        if(f==0)        //For upper half of pattern
        {
            n=n-1;
            temp1=temp1+1;
            temp2=temp2-1;
        }
        else if(f==1) //For lower half of pattern
        {
            n=n+1;
            temp1=temp1-1;
            temp2=temp2+1;
        }
    }
    return(0);
}

I am getting the correct output for n = 2 but when I am inputting anything above 2 the code is crashing.
I am not able to find what should be done. Can someone help me out and tell me what am I doing wrong?
Comment: Can you find which line triggers the crash? What are the values of the variables appearing in that line?
Comment: A hint though: How many elements do you allocate for `arr`? And how many elements of that array do you actually use (for example in the loop `for(int j = temp1;j
Comment: @NoobKing "It"? What is this "it" of which you speak? Probably not a debugger, which would be an appropriate tool for this situation. (If you are unable to use a debugger, diagnostic messages sent to `std::cerr` can go a long way towards locating the crash point.)
Comment: @Someprogrammerdude Got it the array size allocation was wrong.It should be 2*n-1.Thank you
Comment: @JaMiT yes its not a debugger I'll use debugger from now on it was a logical error where I allocated less space for the array. Thanks
Answer: It would be better to check distances by axis and take a maximum of them to be printed.
Something like:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int vertical_distance;
    int horizontal_distance;

    int n;
    scanf("%d",&n);
    for(int i = 0; i < n * 2 + 1; i++)
    {
        for(int j = 0; j < n * 2 + 1; j++)
        {
            vertical_distance   = abs(n - i);
            horizontal_distance = abs(n - j);
            if (vertical_distance > horizontal_distance)
                printf("%d ", vertical_distance);
            else
                printf("%d ", horizontal_distance);
        }
        printf("\n");
    }
    return(0);
}

Also, when I ran your code it worked nicely with large numbers (3, 7, 15).
I just pasted your code to onlinegdb.com/online_c_compiler and ran it. Can you please add the error message that you have got?
(sry for my English)
Comment: The array size allocation was wrong so the program just crashed like the .exe file has stopped working. This is a more elegant solution.Thank you. PS: Your English is fine.
Answer: in this code piece
for(int j = temp1;j<temp2;j++) //change values in range temp1 to temp2
{
      arr[j] = n;
}

j can be bigger than n. but arr malloc space is n. the array overflowed.
it will work with a small change
arr = (int*)malloc(2*n*sizeof(int));

Comment: Thanks for pointing that Out! Actually works with  (2*n-1).


Get value of hash key without loop

Question: I'm trying to get the value of id returned from the response.body function. The only way I got it to work is to loop on elements then assign $record_id to it.
JSON.parse(response.body).each do | k , v |
  if k == 'id'
    $record_id = v
  end

I have similar functions like above used in my code, with the result that the script started to take a long time before it finishes.
Is there is a way I could get the value of first hash without looping?
Answer: record_id = JSON.parse(response.body)["id"]
Answer: Form the ruby documentation of JSON.parse:
my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"

Get value of hash key without loop


Why does $\int_0^1\binom{2n}{n}x^n(1-x)^ndF(x)=\frac{1}{2n+1}$?

Question: Why does $$\int_0^1\binom{2n}{n}x^n(1-x)^ndF(x)=\frac{1}{2n+1},$$
Where $F(x)$ is uniform over the interval $[0,1]$?

It's not clear from simple factoring:
$$\binom{2n}{n}\int_0^1x^n(1-x)^ndF(x)$$
$$=\frac{(2n)!}{n!^2}\int_0^1x^n(1-x)^ndF(x).$$
Comment: $2n! \neq (2n)!$, be careful.
Comment: Are you familiar with the Beta function?
Comment: Yep, more or less.
Comment: For reference to others, I have expanded upon a probabilistic derivation of this statement [here](https://math.stackexchange.com/questions/2685250/the-probability-of-observing-the-mean-draw-from-binomial-distribution/2685523#2685523). The proof is very elegant, and was apparently (according to the reference) the approach taken by Bayes.
Answer: By the binomial theorem,
\begin{align*}
\sum_{k=0}^{n} \left( \int_{0}^{1} \binom{n}{k} x^k(1-x)^{n-k} \, dx \right) z^k
&= \int_{0}^{1} (1 + (z-1)x)^n \, dx \\
&= \frac{1}{n+1} \cdot \frac{z^{n+1} - 1}{z-1} \\
&= \sum_{k=0}^{n} \frac{z^k}{n+1}.
\end{align*}
So we have
$$ \int_{0}^{1} \binom{n}{k} x^k(1-x)^{n-k} \, dx = \frac{1}{n+1} $$
for all $0 \leq k \leq n$.
Comment: How is $\frac{1}{n+1} \cdot \frac{z^{n+1} - 1}{z-1}$ equal to $\sum_{k=0}^{n} \frac{z^k}{n+1}$? Also, isn't $z=1$, in which case the derivation does not work?
Comment: @pafnuti, It is a consequence of a simple algrbraic $z^{n+1}-1=(z-1)(1+z+...+z^n)$. As for the second question, you need not worry about evaluating the expression for specific $z$. You may regard this as equality in formal power series sense.
Answer: Hint.
$$\int_0^1 x^n(1-x)^n\ dx = \frac{\Gamma (n+1)^2}{\Gamma (2 n+2)}$$
And for $n\in\mathbb{N}$ we also have $\Gamma(n+1) = n!$
Put all together and after a little algebra you will notice that
$$\frac{(2n)!}{(n!)^2}\frac{\Gamma (n+1)^2}{\Gamma (2 n+2)} = \frac{1}{1 + 2n}$$
Answer: Claim
$$
\int_{0}^x (x-t)^a t^b\, dt=\frac{\Gamma(a+1)\Gamma(b+1)}{\Gamma(a+b+2)}x^{a+b+1} \quad(a>-1, b>-1, x>0)\tag{0}
$$
Proof
Let $f(x)=x^a$ and $g(x)=x^b$. Then
$$
L[f\star g]=L[f]\times L[g]=\frac{\Gamma(a+1)}{s^{a+1}}\frac{\Gamma(b+1)}{s^{b+1}}=L\left[
\frac{\Gamma(a+1)\Gamma(b+1)}{\Gamma(a+b+2)}x^{a+b+1}
\right]\tag{1}
$$
where
$$
L[f](s)=\int_{0}^\infty f(x)e^{-sx}\,dx
$$
and
$$
(f\star g)(x)=\int_{0}^x f(x-t)g(t)\,dt.
$$
The uniqueness of Laplace transforms for continuous functions yields the result. $\blacksquare$
Now put $x=1$ in equation (0) to get that
$$
\int_{0}^1 (1-t)^a t^b\, dt=\frac{\Gamma(a+1)\Gamma(b+1)}{\Gamma(a+b+2)} \quad(a>-1, b>-1).\tag{2}
$$
Now put $a=n$ and $b=n$ in  equation 2 to yield that
$$
\int_0^1(1-t)^nt^n\, dt=\frac{\Gamma(n+1)^2}{\Gamma(2n+2)}=\frac{(n!)^2}{(2n+1)!}
$$
whence
$$
\binom{2n}{n}\int_0^1(1-t)^nt^n\,dt=\frac{(2n)!}{(n!)^2}\times\frac{(n!)^2}{(2n+1)!}=\frac{1}{2n+1}.
$$
Answer: This is easy and does not require any complicated computations. Moreover, it is possible to prove a more general formula, as in @SangchulLee's answer.
Let $U_1,\dots,U_{n+1}$ be independent $U[0,1]$ random variables. Consider the event $$A = \{U_{1}\text{ is $(k+1)$th in value}\},\ k=0,\dots,n.$$
Then, by symmetry, $P(A) = \frac1{n+1}$.
On the other hand, given $U_1 = x$, the conditional probability of $A$ is $$
P(A\mid U_1 = x) = P(\text{exactly $k$ variables of $U_2,\dots,U_{n+1}$ are less than $x$})\\ = {n \choose k} x^k (1-x)^{n-k}.$$
Therefore, by the law of total probability,
$$
\frac1{n+1} = P(A) = \int_{\mathbb R} P(A\mid U_1 = x)dF(x) = \int_0^1 {n \choose k} x^k (1-x)^{n-k} dx,
$$
as required.
Comment: That's impressive!
Comment: @pafnuti, there are not too many ways to interpret the integrand, so this is quite natural. Also I realized that a more general result can be shown in a similar fashion, see the updated answer.


If hosting only one site on a server with no control panel, is there any advantage to using a virtual host?

Question: The site is hosted on AWS and the website is dropped into the var www html directory. Is there any advantage to setting up a virtual host considering this will be the only domain on the server?
Comment: Are you talking about apache? If so you should use the "apache" tag. I would expect it would provide flexibility, say if you want to add a test site or subdomain in the future.
Answer: The main advantage of placing your web site in a virtual host is that the default (virtual) host, which Apache's syntax doesn't place inside any <VirtualHost> block, will catch requests for any site other than yours. This includes things like localhost (if you didn't make a virtual host for it), the system's IP address, no host specified, etc. Nearly all of such traffic is garbage or potentially malicious, and by default they get a 403, 404 and/or a tiny test page (depending on your distribution), and never hit your web application.
These days, with most web sites moving to HTTPS, it's also a good idea to enable the default HTTPS virtual host (which the default Apache config usually has commented out) with a self-signed certificate such as the snakeoil.crt that Debian systems create. This will prevent such garbage or malicious HTTPS traffic as described above from reaching your web app.


How to put PA speaker so I can't get any feedback?

Question: I'm talking about best position to put PA speaker while me (as a band that consist of lead vocal, 1 backing vocal, an acoustic-guitar (plugged), a bass, and an acoustic-small-drum.) play in a small room (like cafes, or small restaurant), where I can't get any feedback from the speaker.
Should I put it on the side of the stage, or behind me?
Comment: Unless you also use it as a monitor, what's wrong with putting it *in front* of the band (probably at both sides or one side if you only have one)?
Answer: The standard for big gigs is for the PA speakers to be in front of the performers, pointing at the audience. So as not to block the view, they're typically in front and to the side, or above the stage and pointing downward.
The point of this is that the audience gets loud music, while the musicians are in a quieter area, where they can hear the music more clearly (loudness really screws up your perception of pitch and even timing) and microphone feedback is easier to control.
If necessary, performers can have quieter monitor speakers. See: In live performance, what is a "monitor"
For smaller gigs, things might be different. You might all be playing quietly enough that feedback isn't a problem even if the PA speaker is behind you. You might be able to hear enough leaking through the back of the PA speaker to use that as a monitor. You might want to play so loud that you can't contain the PA sound -- since it'll bounce back to you off the walls wherever you put the speaker.
Your other defence against mic feedback is to use a directional vocal mic held very close to the lips.
Answer: The most important part is that no microphones are directly pointing towards any of the speakers. This means that the monitors should be in front of the band, facing towards them, and the audience speakers should be in front of the band (at the sides, so that they're not in the audience's view) and naturally facing away from the band.
The monitors' positions are not that critical when you're using pointed microphones. For instance, the drummer's monitors are often places beside and behind the drummer as well, which works as long as none of the drum microphones are pointing directly to the monitors.
Answer: At one of the venues I play, the room is long and thin, with the stage area in the middle of a long side.Not ideal,but there it is. The p.a. speakers are unusually placed at 2 metres height, level with each side of the stage, pointing towards it.Yes, it sounds a weird set up, but it works. The feedack is minimal, as the mics are not facing the speakers, which act as foldback as well as p.a.As they are flown, there are no stands to get knocked over, but often they could be safe in an ad hoc situation that could copy this.
Otherwise, as others have said, lacking foldback, which is often used unnecessarily, put the p.a. speakers at the side of the stage area, level with the frontmost mics, so that sound can be heard on stage. I try to get the cabinets up as high as possible, in order to send the sound over the audience's head, also it puts them out of line with mics.
Answer: If you have an eq, turn the 100 and the 250 to -12. It works for me and it sounds great too.
Answer: The first duty of a PA system is to enable the performance by letting the musician hear himself.  Then you need to consider what sort of gig it is.  Do the audience want it loud and 'in their face' or do you?  Strategic positioning of even a single speaker can achieve either.  If you have two, even better.  Forget stereo, run 'one for me, one for them'.   In some situations you can forget about the 'one for them'.  I was at a job recently where my friend was providing background music on keyboard/vocals.  The front row had his speakers in their face, he complained he couldn't hear himself.  Everyone would have been happier had the speakers been pointing just at him. Feedback isn't necessarily a problem with a good microphone and moderate volumes.  Don't do anything silly like using compression on the vocals though!
Answer: Positioning is not the only thing that'll help you out here. I've set up stages with speakers behind the performers, facing out into the room, it can be done.
There's a lot of factors which can cause feedback, including the resonant frequency in the room, quality of your equipment, etc. So for any answer to this question you'll have to experiment a little in the venue to find the right solution for you?
Have you tried playing more quietly? I know it's a radical suggestion, but it really can help. This solution may require ego-checking on the part of the band.
You say you're in a small room? How small? Do you really need PA in a cafe? It's worth thinking about.
Always try and locate your feedback before doing anything with the desk, usually you can do this by taking down a channel when feedback is sounding. If the feedback stops, you've found it's source. There may be more than one sound source (e.g. a mic and a guitar) which is feeding back.
There's quite a lot you can do with EQ to mitigate feedback, which is why big, expensive desks have big, complex equalizers. If you can find where the feedback is, try cutting a particular band to see if this stops the feedback. Usually feedback comes in at a single frequency, if you can cut that frequency, you might get more head-room without feedback. Remember, with EQ, a cut always sounds sweeter than a boost.
If you have a graphic equalizer on the master (So, not on a specific channel, going out to the mixer. You could try 'ringing out'. Set the stage up, but have no performers on it. Put every input up, then take up the master until you are close to feedback point. Put up one band on the graphic EQ, if it starts triggering the feedback, put that band lower than the others. Do not let the feedback get very loud or go on for long. Take the master level down if you need to.
You mentioned an electro-acoustic guitar (an acoustic guitar, plugged in), these are often the source of feedback. You might want to consider a 'feedback stopper' or 'soundhole plug' (they have many names) such as this one. http://www.gear4music.com/Guitar-and-Bass/Planet-Waves-Screeching-Halt-Soundhole-Plug/KJN
You also want to look into any effects you're using.

If you're using compression, stop it. There's such a good chance you don't need it, but most compression units kick up the gain, feedback city!
A small amount of phase, chorus or auto-wah might just clear it for you, particularly on the guitar. (or almost any frequency modulating effect). Obviously match this to the style you want to produce. Be very wary of setting up a stage with one of these effects on, then taking it off.

Sorry for the long post, but feedback really isn't just about positioning. Any sound tech will tell you they spend a lot of time fixing it, in a wide variety of ways.
Comment: All good advice.  Just remember that the purpose of eq (and everything else really) is to make your music sound as GOOD as possible, not just as LOUD as possible.
Comment: @LaurencePayne "a cut always sounds better than a boost", "do you really need PA?" - trust me, I know all about better Vs louder. Remember, volume controls go down as well as up"
Comment: But you recommend static "ringing out"?  Sometimes a practical necessity for monitors - the performer WILL ask for "more me" and will, against advice, want the overall volume to keep creeping up - so if it sounds nasty at least it won't feed!
Comment: @LaurencePayne that's true, it can also help at lower volumes if the room's taking off at a particular frequency, find it and cut it. Yep, bands wanting the volume to creep up is... very likely.
Answer: I highly recommend using a digital Mixer for any gig - Behringer has some great stable and reliable gear with the eq you need just for this issue - namely the feedback and room tuning concern.
When a singer asks for more me - pull up the eq on thier channel and overlay the RTA and look for thier "dominant" frequency - and as long as it isn't the frequency you reduced for anti-feedback purposes then give them a little mid to high mid in thier monitor.
Then go to the graphical eq for the mains and pull down that specific frequency just a little.
I have also found that if there are guitars and other instruments in the monitor of the vocalist in question try and eq around the vocals - if you boost slightly for more me then pull those frequencies out of the guitar and keys - your mains will probably sound better as a result as well with that little trick.
I am a firm believer that a band should try and rehearse the show in a location that simulates the club environment as much as possible - even go as far as setting up and rehearsing in a club you play at on a slow night where you can stop and eq various channels on the digital mixer to optimize the sound of the band.
Once the settings are in place the digital Mixer will remember them and sound check will go much smoother next time.


Trying to get the state value after immediate state update

Question: I have declared a variable with usestate like as below
const [currentStepNumber, setCurrentStepNumber] = useState(0);

and then I am updating the state when I click on move function like as below
const handleMove = () => {
   setCurrentStepNumber(currentStepNumber + 1);
   const { label } = Object.values(PROJECT_PHASE).find(s => s.stepNumber === currentStepNumber);
   const projectPhaseID = projectPhaseData.projectPhases.find(a => a.name === label).id;
   console.log(currentStepNumber);
   // need to do API call as well in move function
};

And the currentStepNumber still shows 0 instead of 1 only and i cannot use a timer to trigger and update the values. Is there any other approach to achieve this?
I need to update the currentStepNumber only in move function.
Comment: Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately)
Comment: @ChrisG I've BM'd it since this question is asked almost daily. ;)  Though, the underlying reason is exactly the same... react component lifecycle and reconciliation.
Comment: Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately)
Comment: No it won't i have to other operations as well after updating the state
Comment: Doesn't matter; setting state is async; that's React 101 (also: the stupid "Does this answer your question?" is auto-inserted by SO when you mark as dupe)
Comment: @DrewReese That's the one, thanks
Answer: Might be able to try useEffect:
useEffect(() => {
   const postStepData = async () => {
     try {
         // call the api
         const response = await postDataPromise({...data, currentStepNumber});
         setCurrentStepNumber(0);
         setSomeOtherState(false);
     } catch (e) {
         console.log(e)
     }
   }

   const { label } = Object.values(PROJECT_PHASE).find(s => s.stepNumber === currentStepNumber);
   const projectPhaseID = projectPhaseData.projectPhases.find(a => a.name === label).id;
   console.log(currentStepNumber);
   /*
    * as an example only call api on step 4
   */
   if (currentStepNumber === 4) {
      void postStepData();
   }
}, [currentStepNumber])

const handleMove = () => setCurrentStepNumber(currentStepNumber + 1);

reference:

https://reactjs.org/docs/hooks-effect.html
Comment: thanks for response !! , i need to have api call as well followed by getting that projectPhaseId in the same move function.. With your code can i do that
Comment: Hmm i need to call the api in the current step it self cannot wait until step 4
Comment: @EnigmaState can remove the `if` statement, and just run the api call on each state update?, or handle the cases where it should be called?
Comment: do you mean the useEffect should run if there is any update to currentStepNumber right
Comment: @EnigmaState yep
Comment: any condition need to check inside useEffect before running api call just to watch the current stepnumber or not needed
Comment: @EnigmaState `currentStepNumber` is passed into the dependency array so the example useEffect will only run when `currentStepNumber` is updated. `useEffect(() => {...}, [currentStepNumber])`. If I understand your question, useEffect watches the current step number, and will run if it is updated, so no extra watching of step number is required for useEffect to get called.
Comment: thanks.. i need to run this complete useEffect when only the currentstepnumber changes and if don't include other dependencies i am getting warnings as well.. how can i avoid those warnings React Hook useEffect has missing dependencies:  `projectPhaseData`. Either include them or remove the dependency array `
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/217922/discussion-between-enigma-state-and-jmunsch).
Answer: You should use the new currentStepNumber in React's useEffect:
const MyComponent = () => {
  const [currentStepNumber, setCurrentStepNumber] = useState(0);

  const handleMove = () => {
    setCurrentStepNumber(currentStepNumber + 1);
  };

  useEffect(() => {
    const { label } = Object.values(PROJECT_PHASE).find(s => s.stepNumber === currentStepNumber);
    const projectPhaseID = projectPhaseData.projectPhases.find(a => a.name === label).id;
    console.log(currentStepNumber);
  }, [currentStepNumber])

  return (
    <>{/* some jsx */}</>
  )
}

Comment: thanks for the response, i have to do api call as well once i get the correct projectPhaseId in move function itself..


Authenticated SMTP relay not working if from and user don't match

Question: We have an Exchange 2016 and we have this issue:

on some of our customers servers we must configure some email alerts that are sent through a SMTP connector (with STARTTLS and AUTH-LOGIN enabled)
the destination address is To: email@example.com
the SMTP user is email@example.com
if we specify From: email@example.com then everything is fine
but if we specify From: firstname.lastname@example.com our server reports this error

:
 [S] 235 2.7.0 Authentication successful
 ....
 550 5.7.60 SMTP; Client does not have permissions to send as this sender

The error occurs both if we use a FrontendTransport receive connector or a HubTransport receive connector.
We searched for a solution but we didn't find anything.

Is there a setting that allows to use any From: address when relaying mail for authenticated SMTP users?

Thanks.
Answer: If the server is the mail server for all these domains, it's possible for example to add all these addresses as proxyAddresses in AD, e.g. smtp:email@example.com. If the address already belongs to another account, the account should have a send on behalf / send as permission for that address.
If your server is not a mail server for these domains, please consider that it may not be listed as a permitted sender in SPF, causing these messages to be rejected or treated as spam. Therefore, it may be a better idea to use an email address of your own domain; the one that didn't have this problem in the first place.


Display users who flagged content

Question: In my Drupal 7 project I have users of role A and B respectively. Users of role A can create content and users of role B can flag it.
I'm building a view that displays on A users' account page their content and names of B users who flaggd it.
I have created a view Content (not User) and added relationship Flags: Content flag and consequently field Flags: User uid to display together with content related fields.
In view block I use Grid format. Same content information is displayed several times per each user who flagged it, like  bellow
Content title QWERTY
Users uid  who flagged 1
Content title QWERTY
Users uid who flagged 2
Content title QWERTY
Users uid  who flagged 3
How can I display content information only once and users who flagged in one field separated by comma?
Answer: you need to edit /drupal/sites/all/themes/MYTHEMENAME/template.php
then add the following code.
function MYTHEMENAME_preprocess_views_view_fields($vars){
      if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] != 1){
        $vars['fields']['title']->content = '';
      }
    }

What this code is saying is if your row is not equal to (!=) 1, then don't display anything. Thus, it will print your title only for row 1.

replace MYTHEMENAME with your actual theme name.

replace VIEWNAME with your view's name. example: flagged_content

replace DISPLAY with your view's machine name. You can find this by editing your view, then under Advanced -> other
examples: block, block_1, page, page_1 or default. It's default if you're using your master view.

For user's separated by comma you would have to use css for that.
JS FIDDLE EXAMPLE
PS: I think you would have to change it from grid to html list for your view.

Display users who flagged content


How should I calculate the determinant?

Question: $\left|\begin{array}{cccc}1&a&b&c+d\\1&b&c&a+d\\1&c&d&a+b\\1&d&a&b+c\end{array}\right|=
\left|\begin{array}{cccc}1&a&b&c\\1&b&c&a\\1&c&d&a\\1&d&a&b\end{array}\right|+
\left|\begin{array}{cccc}1&a&b&d\\1&b&c&d\\1&c&d&b\\1&d&a&c\end{array}\right|$
I tried to calculate the determinant but I couldn't do it after separating the determinant by the property.  How should I calculate it?
Comment: notice that the sum in each line is the same (a+b+c+d+1).
Comment: Perhaps you could show what you've done? That way, it might be easier to help-also try to learn maths jax-http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Oh, I didn't notice that the sum of each line is the same.  I know if the determinant has the same row or column, it's 0.  Is there some property about the sum of a line?
Comment: Instead of $a+d$, write $d+a$ and you will see that the two determinants are identical to a permutation of the rows and columns.
Answer: $${\begin{vmatrix}1&a & b &c+d\\1 &b &c &d+a \\1 &c &d &a+b\\1&d &a &b+c &\end{vmatrix}} \space  c_2+c_3+c_4 \to c_4 \\
{\begin{vmatrix}1&a & b &a+b+c+d\\1 &b &c &a+b+c+d \\1 &c &d &a+b+c+d\\1&d &a &a+b+c+d &\end{vmatrix}} \space factor  \space (a+b+c+d)=\\(a+b+c+d)
{\begin{vmatrix}1&a & b &1\\1 &b &c &1 \\1 &c &d &1\\1&d &a &1 &\end{vmatrix}}$$now $c_1-c_4 \to c_1$
$${\begin{vmatrix}0&a & b &1\\0 &b &c &1 \\0 &c &d &1\\0&d &a &1 &\end{vmatrix}} $$
Comment: I was under the wrong impression that I could add only a row to another row for determinant.  Thank you Khosrotash :).
Answer: Looks like homework to me, so I will suggest ideas instead of just the answer.
Take the first row of the original matrix and add it to the third row.  Then add the second row to the fourth row.  How do the new third and fourth rows compare?  What does that imply about the determinant?
Comment: Honestly, it's not my homework.  I know the answer which is 0.  This is the practice to understand determinant profoundly.  Anyway thank you for your idea.
Answer: Compute
$$
\begin{bmatrix}
1 & a & b & c+d \\
1 & b & c & d+a \\
1 & c & d & a+b \\
1 & d & a & b+c
\end{bmatrix}
\begin{bmatrix}
a+b+c+d \\ -1 \\ -1 \\ -1
\end{bmatrix}
$$
Answer: $${\begin{vmatrix}1&a & b &c\\1 &b &c &d \\1 &c &d &a\\1&d &a &b &\end{vmatrix}}=-{\begin{vmatrix}1&a & b &d\\1 &b &c &a \\1 &c &d &b\\1&d &a &c &\end{vmatrix}}$$
because the second determinant is the same as the first by cyclically permuting the columns $2,3$ and $4$, an cyclically permuting the four rows.
Comment: Does a cyclic permutation represent an even or an odd prrmutarion?  Does that depend on how many items are cyclically permuted?  I would indicate that the column permutation us even and does _not_ change the sign of rhe seterminabt, while the column permutation is odd and does change the sign.

How should I calculate the determinant?


Show that the series $\sum\limits_{k=1}^{\infty}\dfrac{(-1)^k}{k+|x|}$ converges pointwise to a Lipschitz function $f(x)$.

Question: Show that the series $\sum\limits_{k=1}^{\infty}\dfrac{(-1)^k}{k+|x|}$ converges pointwise to a Lipschitz function $f(x)$. Is the convergence uniform on $\mathbb{R}$?
I have shown the pointwise convergence part. But I have facing trouble in showing the other two parts, that is, uniform convergence part and Lipschitz part
Comment: Please see [Quick beginner guide for asking a well-received question](https://math.meta.stackexchange.com/questions/35391/quick-beginner-guide-for-asking-a-well-received-question)
Answer: Since the sequence $(k + |x|)^{-1}$ is monotone decreasing for fixed $x$ and uniformly convergent to $0$ , uniform convergence of the series on $\mathbb{R}$ follows from the Dirichlet test or more directly from the alternating series estimate
$$\left|\sum_{k=n+1}^m \frac{(-1)^k}{k+|x|}\right|\leqslant \frac{1}{n+1+|x|}\leqslant \frac{1}{n+1}$$
Comment: how you have got the second inequality from the first inequality?how m got disappeared?
Comment: @rubi76re: For any alternating series $\sum (-1)^ka_k$ where $a_k >0$ and $a_k \downarrow 0$ we have

$$\left|\sum_{k=n+1}^m(-1)^k a_k \right|= \begin{cases} a_{n+1} - (a_{n+2} - a_{n+3}) - \ldots -(a_{m-1} - a_m),\,\, m-n \text{ odd} \\a_{n+1} - (a_{n+2} - a_{n+3}) - \ldots -(a_{m-2} - a_{m-1})- a_m, \,\,m-n \text{ even}\end{cases}< a_{n+1}$$
Answer: The Lipschitz property part can be shown in a straight forward fashion:
$$|f(x) - f(y)|< |\sum_{k=1}^{\infty}\frac{(-1)^k}{k+|x|} - \sum_{k=1}^{\infty}\frac{(-1)^k}{k+|y|}| = |\sum_{k=1}^{\infty}\frac{(-1)^k(|x| - |y|)}{(k+|x|)(k+|y|)}|= |\sum_{k=1}^{\infty}\frac{(-1)^k}{(k+|x|)(k+|y|)}|\cdot ||x| - |y|| \leq |\sum_{k=1}^{\infty}\frac{(-1)^k}{(k+|x|)(k+|y|)}||\cdot|x-y|$$
Set $K: = \sum_{k=1}^{\infty}\frac{(-1)^k}{(k+|x|)(k+|y|)} < \sum_{k=1}^{\infty}\frac{1}{k^2} = \frac{\pi^2}{6}$. Thus, $f$ is a Lipschitz function.
Note that by this argument $f(x) := \sum_{k=1}^{n}\frac{(-1)^k}{k+|x|}$ is a Lipschitz function, and a sequence of $K$−
Lipschitz functions which converges pointwise,  converge uniformly (see Given sequence of $L-$Lipschitz functions which converges pointwise, prove uniform convergence).


Longish delay between two consecutive KeyDown events

Question: I'm kind of writing a little game engine -- purely to understand how these work from the inside. I currently don't want to mess with OpenGL or DirectX, so I stick to drawing on a control with GDI+ and all that WinForms stuff.
Obviously, I need to handle input. More specifically, keyboard events. This, however, poses a problem:
protected override void OnKeyDown(KeyEventArgs e)
{
    Trace.WriteLine(string.Format("KD {0:hh:MM:ss.fff} {1}",
        DateTime.Now, e.KeyCode));
}

This code (even with the shortest repeat delay set in the Keyboard applet in the Control Panel) yeilds the following:
KD 10:02:18.318 Right
KD 10:02:18.570 Right
KD 10:02:18.598 Right
KD 10:02:18.639 Right
KD 10:02:18.667 Right
KD 10:02:18.701 Right

As you can see, there's a 0.25 sec. delay between first two events. This results in sluggish movements of objects on screen, obviously: it first moves slightly to the right, then pauses for a noticeable moment, and then continues on.
How do I resolve that issue? Can this be done in pure WinForms or should I go DirectInput (or whatever is the kosher way nowadays?) route?
Comment: That's wicked how fast this question came up in Google search results.
Answer: Using Windows messages isn't the best way to go for input interaction.
I know nothing about WinForms, but I assume on key events use messages.
I've used DirectInput (v7) many years ago, and it was really fast.
Perhaps GetKeyboardState or GetAsyncKeyState in a game loop are good alternatives.
Comment: @Anton, ok :) DirectInput gives you "direct" access to keyboard's buffer so use it in case you need very accurate input, or in case you want to handle gamepads/joysticks and take advantage of their extra functionalities.
Comment: @Anton, which one? GetKeyboardState or GetAsyncKeyState?
Comment: `GetKeyboardState` turned out to be fast enough, so I never tried `GetAsyncKeyState`.


Is this a good way to Encrypt and decrypt strings data

Question: I have made this simple example below, and trying to encrypt/decrypt string.
But I cannot help wonder if it is the right way to do it.
Have a look below and see that if it will develops problems with different character/string.

const getKey = (key) => {
  let keyNum = 0;
  for (let char of key) {
    let cCode = char.charCodeAt(0) + key.length;
    keyNum += cCode;
  }
  return keyNum;
};

const Encrypt = (str, key) => {
  let text = '';

  let keyNum = getKey(key);
  for (let char of str) {
    let cCode = char.charCodeAt(0) + keyNum;
    // what happend if cCode dose not generate a valid string
    text += String.fromCharCode(cCode);
  }

  return text;
};

const Decrypt = (str, key) => {
  let text = '';
  let keyNum = getKey(key);
  for (let char of str) {
    let cCode = char.charCodeAt(0) - keyNum;
    text += String.fromCharCode(cCode);
  }
  return text;
};

const testText = "hahhaha this is a test - هههههه هذا اختبار";
const testKey = "test Key";
const eText = Encrypt(testText, testKey);
console.log("Encrypt:", eText)
console.log("Decrypt:", Decrypt(eText,testKey))

Please look at the comment above in Encrypt() and let me know if it can really happen
Why I am doing this.
I want to use a simple encryption that work with js(react-native) and C#. I cant find any. That is why I am trying to build a simple plugins. C# will encrypt a js files and upload it to someplace and js will download those js files decrypt them and using Function I will be able to use them
Comment: This is basically just a Caesar Cipher, where the increment is a checksum of the key. It's not a very secure method of encryption.
Comment: [security.se] would be a better place to ask about encryption methods.
Comment: You use statistical analysis to determine the key.
Comment: Why are you bothering with this? Security researchers have been designing high-quality encryption techniques for decades, use what they've developed. Any decent encryption method uses complex mathematics such as prime numbers and factorization, not trivial checksums and addition.
Comment: Why is it not secure, Its almost impossible to decrypt without a key right?
Comment: You can just cycle through different key values to get the messages in milliseconds.
Comment: I want to use a simple encryption that work with js(react-native) and C#. I cant find any. That is what I am trying to build a simple plugins. C# will encrypt a js files and upload it to someplace and js will download those js files decrypt them and using `Function` I will be able to use them
Comment: "*Is this a good way to encrypt and decrypt strings?*" - **No!** [Don't roll your own crypto](https://security.stackexchange.com/q/18197/8749)! "*I cant find any*" - https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API
Comment: @Bergi please read `Why I am doing this`
Comment: @Alen.Toma It's not entirely clear for what purpose you are building this. For fun? Then you probably don't need to care about good crypto. As a learning experience? Then you'll need to learn that encryption is not simple. For a production system even? Something else?
Answer: First this is bad.
If you want a simple test to check your encryption (basic test) just enter the same char as the text and see the repetition of your output, just by that i can discover your key.
If you wish to use good encryption then use libraries made by professionals.
If you really want to build encryption by your self then sit with books and learn the subject, it is a very interesting but also very hard subject to master, no shot cuts here.
Good book to start with - 'Cryptography in C and C++'
Comment: Yes my friend its alot of maths and heavy logic, i really recomand you use professional libraries for your code. good luck!
Comment: That is way to complicated for me and I really do not have the energy to study maths again. This need Maths to be able to study this.


Generalizing a surjection ${\bf GL}(2,\Bbb R)\cong (\bf M,\circ)$

Question: Consider the set of all invertible $2\times 2$ matrices over $\mathbb R$ (I think we can do it over $\Bbb C$ but I didn't look at it) $${\bf GL}(2,\Bbb R)=\left\{\left(\begin{matrix}  a&b \\c &d\end{matrix}\right):a,b,c,d\in\Bbb R,ac-bd\neq 0 \right\}$$
Consider now the set $\bf M$ of all functions of the form
$$f(x)=\frac{ax+b}{cx+d}$$
again with $a,b,c,d\in\Bbb R,ad-bc\neq 0 $. If we identify each of these with a matrix
$$\left(\begin{matrix}  a&b \\c &d\end{matrix}\right)$$ then we can define an isomoprhism between $\rm GL$ and $(\bf M,\circ)$ as groups with operations of matrix multiplications and functional composition, respectively, and identities$$\left(\begin{matrix}  1&0 \\0 &1\end{matrix}\right)=e$$
$$x=\frac{1x+0}{0x+1}=e'$$
since if $$\eqalign{
  & f = \frac{{ax + b}}{{cx + d}}  \cr
  & g = \frac{{ex + f}}{{gx + h}} \cr} $$ then $$f \circ g = \frac{{\left( {ae + bg} \right)x + af + bh}}{{\left( {ce + dg} \right)x + dh + cf}}$$
which corresponds to
$$\left(\begin{matrix}  a&b \\b &c\end{matrix}\right)\left(\begin{matrix}  e&f \\g &h\end{matrix}\right)=\left(\begin{matrix}  ae + bg&af + bh \\ce + dg &dh + cf\end{matrix}\right)$$
and similarily for inversion, $${f^{ - 1}} = \frac{1}{{ac - bd}}\frac{{dx - b}}{{ - cx + a}}$$
and $$\left(\begin{matrix}  \frac  d\Delta& \frac {-b}\Delta \\\frac{-c}\Delta &\frac a\Delta \end{matrix}\right)=e$$
I include the determinant $\Delta=ac-bd$ inside the matrix to avoid any multiplication by scalars considerations.
My question is: How can this be generalized to ${\bf GL}(n,K)$, and what is the theoretical relevance of this? I know Möbius Transformations are important in Complex Analysis, for instance, but I haven't seen any "higher dimesional" equivalent around.
ADD As users noted, for every $a\in \Bbb R$,$$\left(\begin{matrix}a&0\\0&a\end{matrix}\right)\mapsto x$$
so the isomoprhism is actually obtained by quoting ${\bf GL}(2,\Bbb R)$ by $I=\{aI_2:a\in\Bbb R\}$
Answer: This map isn't an isomorphism; all scalars are sent to the identity. The generalization goes by the name of the projective general linear group; this naturally acts on projective space, hence the name, and is the natural target for projective representations, which are important for example in quantum mechanics.
Comment: I have just started linear algebra this quatrimester, so I'd appreciate if you explain some of the above. I know the basics about groups, rings, integral domains and fields to get to define vector spaces, but not much more of abstract algebra than that. For example, I don't understand what "naturally acts on", "the natural target for" mean.
Comment: @Peter: can you ask a more specific question? What I mean is that the action of $\text{GL}(V)$ on $V$ induces various other actions functorially, e.g. the action of $\text{GL}(V)$ on the projective space $\mathbb{P}(V)$ of lines in $V$. This action factors through the projective general linear group $\text{PGL}(V)$ because scalars all act trivially on lines. The second use of "natural" may be regarded as a definition of projective representation.
Comment: Oh, well. My point is I know too little algebra to understand what you're telling me. What does "factors through" mean, for example? I don't about "functors" either, so maybe I'll have to wait a little till I come back to look at this. Also, I now realize that one thing is not clear in my question. I wanted to know what functions correspond to the $n$th dimensional generalization. Maybe a multivariate version of Möbius' Transformations?
Comment: @Peter: it means that the map $\text{GL}(V) \to \text{Aut}(\mathbb{P}(V))$ is the composition of a pair of maps $\text{GL}(V) \to \text{PGL}(V), \text{PGL}(V) \to \text{Aut}(\mathbb{P}(V))$. Again, all I am really saying is that the scalars act trivially on projective space. The functions you want are, as I said, precisely the elements of the projective linear group. These are the appropriate generalization of Mobius transformations to higher dimensions.
Comment: @Peter: in three dimensions elements of the projective linear group may be written down explicitly as pairs of rational functions $\left( \frac{ax + by + c}{dx + ey + f}, \frac{gx + hy + i}{dx + ey + f} \right)$, and this generalizes to higher dimensions. But this gets less useful the higher up you go; it really is better to think about projective space.
Answer: You don't have an isomorphism but just a surjective map $f : \textrm{GL}_2(\Bbb{R}) \longrightarrow \textbf{M}$. The kernel of this map is all scalar multiples of the identity (as you can check) and so by the first isomorphism theorem,
$$\textbf{M} \cong \textrm{GL}_2(\Bbb{R})/ \{ aI\}$$
where $a$ ranges over all non-zero real numbers. The group on the right is called $\textrm{PGL}_2(\Bbb{R})$ (if you are working over $\Bbb{R}$). The generalisation of this is of course when you consider $\textrm{GL}_n(\Bbb{C})/\{aI\}$ that (as you may have guessed) is called $\textrm{PGL}_n(\Bbb{C})$.
I don't really know much about this group except that if you have $\textrm{GL}_n$ acting on say $\Bbb{R}^n$, then you can ask what the associated action will be on the quotient $\Bbb{R}\textrm{P}^{n-1}$ space. Now recall that real projective space $\Bbb{R}P^{n-1}$ is the space of all lines through the origin in $\Bbb{R}^n$. Suppose we let a scalar multiple of the identity act on one of these lines. Then the line just get sent to itself yes? Rather, every element on the line is sent to a scalar multiple of itself. However in terms of projective space, that line is considered as just one point and so any scalar multiple of the identity matrix becomes the "identity matrix"  on $\Bbb{R}P^{n-1}$. That's why we quotient it out to get that the "actual group" acting on $\Bbb{R}P^{n-1}$ is $\textrm{PGL}_{n}$.
Comment: Yes, I missed the fact that $$\left(\begin{matrix}a&0\\0&a\end{matrix}\right)\mapsto x$$ for each $a$. Could you add a little about ${\bf PGL}_n(K)$?
Comment: @PeterTamaroff But you do have an isomorphism between the quotient and the group of mobius transformations.
Comment: What do you mean when you say action? Do you mean a function of the form $\star:K\times V\to V$?
Comment: @PeterTamaroff The action of $\textrm{GL}_n$ on the vector space is the usual one given by left multiplication of matrices.
Comment: @PeterTamaroff See the edit.


What's wrong with the way I use variables in my function?

Question: I have a function that looks like this:
function mymodule_privatemsg_message_validate($message) {
  $uid = $vars['message']->author->uid;

  //if root or help user, message should always go through regardless of length
  if ($uid !== '1') {
    if ($uid !== '3') {

      if (empty($message->thread_id) && strlen($message->body) < 200 ) {
    form_set_error('[body][value]', t('My custom message.'));
      }
    }
  }
}

However, I received a comment that "As side note, you are using $vars, but that variable has not been initialized from the function, nor is a function's parameter."  I don't understand what this means or what I'm doing wrong.  Could someone explain this to me?
Answer: For a variable to be available in the scope of a function, it needs to have been initialised (or it needs to have been initialised in the global scope and imported into the local function using global).
At the moment there's nothing declaring or passing the $vars variable in...it hasn't been initialised, thus you get the warning.
You're passing a variable to the function called $message, which suggests your code should be:
$uid = $message->author->uid;

The confusion with $vars/$variables might be caused by the fact that it's sort of the standard name for the only argument passed to theme functions, e.g.
function MYTHEME_preprocess_node(&$vars) {
  // Use $vars

Comment: Yeah that's definitely a strange one. It's always tricky to debug these sorts of things out of context, there might be something external to that function that's causing the anomaly (although I can't honestly think what that could be). As a sanity check you might try changing that line to `$uid = $message->author->uid;` on your dev site. If it still works, you've lost nothing and the code will at least be logically correct as well as functionally correct. If not then you know there's a bigger problem going on
Comment: @PatrickKenny User IDs are integers, while you are comparing them with a string, using `!==`. See my answer about that.
Comment: Ok, I understand that I failed to declare it properly.  But are you saying the code, as written, should not work?  Because this has been working "correctly" on my site for a few months (which is to say, it at least checks the UID and does discard the message if 1 or 3).
Comment: Hmmm there must be something else going on then. Logically, the checks for `$uid !== '1'` and `$uid !== '3'` will never evaluate to `FALSE` as `$uid` is a `NULL` value, and therefore cannot equal 1 or 3
Comment: Hmm.  Well, I'm afraid to say I don't understand what's going on with the code exactly, but I do know that the module successfully discards UID 3 messages when enabled and UID 3 messages go through when the module is disabled.  I will add this to my list of things to look into one day.
Comment: @kiamlaluno I was going to mention that, but as the $message is probably loaded by DBTNG it might be being attached to the object as a string, meaning the identity check passes. You're right of course though, it's not the best idea either way. Patrick - unless you're 100% sure the `uid` property is a string it would better to use the standard equality operator instead (`!=`)
Comment: He's assigning a NULL value to $uid and then saying `if $uid != 1`, which it's not, so the `if` statement runs. Whether he assigns NULL or 42, the `if` statement should run, no?
Comment: @CharlieS Yep that's right
Answer: The parameters given to hook_privatemsg_message_validate() are $message, and $form which has a default value of FALSE.
$vars is not a parameter passed to the function, nor is a local variable defined from the function. As consequence of this, the value of $vars is NULL. When you try accessing $vars['message']->author->uid, PHP would give you two warnings:

Undefined variable: vars
Trying to get property of non-object

The first warning is because the variable is not defined from the function. If your code would have assigned a value to $vars the warning would not appear. It would also work if $vars is defined as global (with global $vars;), and it was already initialized from another function.
The second warning is because every PHP variable that is not define get an automatic value that is NULL. $vars is NULL, and so is $vars['message'], and NULL is not an object.
The result is that $uid is set to NULL too.
The following code is also wrong.
  if ($uid !== '1') {
    if ($uid !== '3') {
      if (empty($message->thread_id) && strlen($message->body) < 200 ) {
        form_set_error('[body][value]', t('My custom message.'));
      }
    }
  }

With $uid !== '1' you are saying to PHP to check if $uid is a string with a value that is different from '1'. If $uid is set to 1 (the integer), the following code would print "different", not "equal".
$uid = 1;

if ($uid !== '1') {
  print "different";
else {
  print "equal";
}

Differently, the following code prints "equal".
$uid = 1;

if ($uid != '1') {
  print "different";
else {
  print "equal";
}

Also the following code will print "equal". (To the reader, the task to understand why. ;))
$uid = '1a';

if ($uid != 1) {
  print "different";
else {
  print "equal";
}

What you meant to write is the following code, as the user ID for a user object is an integer, not a string.
function mymodule_privatemsg_message_validate($message) {
  $uid = $message->author->uid;

  //if root or help user, message should always go through regardless of length
  if ($uid != 1 && $uid != 3) {
    if (empty($message->thread_id) && strlen($message->body) < 200 ) {
      form_set_error('[body][value]', t('My custom message.'));
    }
  }
}

I am not sure if $message->author is a property defined for $message, but I guess that is what you really need.
As side note, I would rather avoid checking the user ID for a user object, and take any action basing on that value. In Drupal, it is better to check if the user has a permission, using code similar to the following one.
if (user_access('permission to check', $account)) {
  // The user has the permission.
}

$account is an user object.
If you have just a user ID, then you can use the following code.
$account = user_load($uid);
if ($account && user_access('permission to check', $account)) {
  // The user has the permission.
}

The reason for checking the permission instead of user IDs is maintainability of the code. Imagine what happens if you have 100 users, and just 50 of them should see that error message: You should check the value of $uid is not the user ID for those users that should not see the error message. If they have not consecutive values (as it happened in your case, where the user IDs were 1 and 3), you should check each value singularly.
As side note, user_access() always return TRUE for the user #1. In fact, the function contains the following code.
function user_access($string, $account = NULL) {
  global $user;

  if (!isset($account)) {
    $account = $user;
  }

  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

  // ...
}

Notice the control statement uses $account->uid == 1, not $account->uid === '1'.
Answer: If you look at the type signature for that hook, it is
function hook_privatemsg_message_validate($message, $form = FALSE) {
}

$vars is not a function parameter, nor have you declared it as being a gloabl.  Using it as you have should make PHP complain (one of the various undefined variable notices).  As it stands, $uid would therefore be undefined when you try to extact something from $vars.
Comment: I see.  I didn't get a PHP error because this hook is evaluated based on a rule, so it never got printed out to the screen in dev.


Are there any APIs or libraries in .NET for image segmentation of characters for OCR?

Question: I am currently doing a project related to OCR for Tamil characters.
I am now at the segmentation stage.
I am looking for an API or library for projection profiles for
segmentation, that i can use with .NET framework since I am using C#
for development.
Any other technique for segmentation is also fine, I just want to
make use of some existing API or library for this stage.
Your help and suggestions would be very helpful, as I am completely confused
at the moment.
Thankyou
Comment: First you ask: "I am looking for an API or library".  Then you say: "I just don't want to make use of some existing API or library".  Please clarify your question.
Comment: sorry about that, what i meant was "I want to make use of some existing api or library". Corrected it.
Answer: Are you looking for freeware or commercial solutions ?
OCR is mostly available for printed text, handwritten character recognition is still unreliable.
For printed text, the results are strongly dépendent on image quality (contrast, noise, illumination uniformity...).
As the Tamil characters are rather complex, it is far better if the characters are clearly separated from each other. Touching characters will give you nightmares.
If you share a few sample images, I can advise about feasibility of segmentation.


nginx returning 502 even though backup is live

Question: Consider the following nginx config. I have two node js servers running on ports 8008 and 9008 respectively. I'm getting 502 errors in my access.log when I take down the server on 8008. I've verified that the server on 9008 works by interchanging the ports and reloading the config. Why would I be seeing 502 errors?
upstream backend {
    server localhost:8008 max_fails=1 fail_timeout=3s;
    server localhost:9008 backup;
}

server {
    listen 80;
    server_name app.domain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name app.domain.com;
    ssl_certificate ssl/chained.crt;
    ssl_certificate_key ssl/server.key;

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache off;
        proxy_cache_bypass $http_upgrade;
    }
}

Answer: It has to do with Connection: keep-alive. A client with an active connection to the backend wouldn't know of it going down right away and thus try to make future requests over the same connection to the same backend server.


Monotone non-decreasing sequence with upper bound

Question: This is a question from a book that I am reading:
Prove that a monotone non-decreasing sequence of real numbers which is bounded above converges to a limit $a$, and that limit is the least upper bound of the set $\{a_1, a_2, ...\}$. (Similarly, prove the same with non-increasing sequences bounded below, ie $\lim_{n\rightarrow \infty} a_n =$ greatest lower bound.)
My issue with this is that this is perfectly intuitive. It makes complete sense, but I just have no idea how to formulate this in a mathematically formal way.
My attempt goes like this: Let $\{a_n\}$ be bounded above and monotone non-decreasing. Then, $a_n \leq a_{n+1} \leq M$, where $M$ denotes an upper bound. From here, it is clear that there exists some least upper bound of this sequence $\leq M$, denoted $a^*$. For this part, I'm not sure if I can just say that this is clear, even though it does seem obvious. I assume that I could argue by contrapositive, and if I assumed there was no least upper bound then there is no way that this sequence is bounded above.
Then, $a_n \leq a^* \leq M$ for all $n \in \mathbb{N}$. This leads to $0 \leq a^* - a_n \leq M - a_n$. At this point, it looks pretty close to being the definition of the limit. Can I choose $\epsilon = 1$, and note that since $a_n \leq a^*$ for any $n$, then certainly for any sufficiently large $n>N$, $a^* - a_n = |a_n - a^*| < \epsilon = 1$, implying that $a^*$ is in fact our limit.
Comment: You can say that $\{a_1,a_2,\dots\}$ has a least upper bound $a^*$ because the real numbers are [complete](http://en.wikipedia.org/wiki/Completeness_of_the_real_numbers). But the second part of your reasoning is false. You're not allowed to choose an $\varepsilon$. You have to prove the bounds for all $\varepsilon>0$.
Answer: Given $\varepsilon>0$ there exists $N$ such that $a^*-\varepsilon<a_N\leq a^*$.
Let any $n>N$. As the sequence $\{a_n\}$ is monotone non-decreasing, $a_n\geq a_N>a^*-\varepsilon$. But, for all $n$, $a_n\leq a^*$. So, in particular, this means that for all $n>N$, $a^*-\varepsilon<a_n\leq a^*<a^*+\varepsilon$ implying for all $n>N$, $|a_n-a^*|<\varepsilon$.
This is exactly the definition of limit of a sequence, which proves the problem.


how to access to ids of selected names in manytomany relationship django

Question: how to access all ids of Languages through Programmer
class Language(models.Model):
    name = models.CharField(max_length=20)

class Programmer(models.Model):
    name = models.CharField(max_length=30)
    langs = models.ManyToManyField(Language,through='Level')

class Level(models.Model):
    language = models.ForeignKey(Language)
    programmer = models.ForeignKEy(Programmer)
    level = models.CharField(max_length=10)

i tried this ways but no one worked
in Programmer instance : instance.level_set.language_id , instance.level.all.language_id , instance.level.all.language.id and also tried this instance.level_set.language.id
all said Programmer has no attribute ,language , language_id etc
thanks for any advice
Answer: You should try the following in programmer instance
instance.langs.all()

for Language Instnace
instance.programmer_set.all()

django many to many relationship with extra fields
--edit--
under your Languages Model define a function
def __str__(self):
    return self.id

Comment: instance.level_set.language_id would work when Level class has Programmer and Language as Foreign keys but it is not a part of many to many relationship. When you define a many to many relationship, accessing property through column name is much more intuitive as well readable and Django implements that. As in your case instance.langs give the reader an idea that it will contain languages of that instance while  instance.level_set is not that intuitive
Comment: i want to get id of Languages which selected , its all returns the names not ids
Comment: im wonder why this wont work nstance.level_set.language_id , it should work
Answer: Some useful things:

To get all language id's as an iterable:

instance.langs.values_list('id', flat=True)
# <QuerySet [1, 5]>

Level and language id as a list of 2-tuples:

instance.level_set.values_list('language__id', 'level')
# <QuerySet [(1, 'advanced'), (5, 'beginner')]>

Comment: If there is no error message, then there simply isn't a programmer named john that has been assigned a language. The programmer may exist, but then you should query him from the Programmer table. In this case, john should show up in this query: `Programmer.objects.filter(langs__isnull=True)`
Comment: thank you , and what if i want to filter by names from Level something like this . Level.objects.filter(programmer__name='john') this doesnt work , is there something similar that?
Comment: That should work, but maybe your issue is case sensitivity? `Level.objects.filter(programmer__name__iexact='john')`


Help recognize a special matrix

Question: Can anyone recognize the following matrix or at least the implied logic of the $\dots$ entries. It seems clear the matrix is symmetrical and that element $(1,n) = \frac{1}{n}$ and I guess element $(1,2) = \frac{1}{2}$ but what is element $(2,n)$ or $(n-1,n-1)$?

Why ask? I accepted a work assignment (without looking well enough over the material) where I have to write a program the builds the following matrix - I suspect it relates to statistics/probability application.
Comment: I don't think it is a serious question. Tell your dad it's a lost cause and keep going with those other businesses of yours, Chopin.
Answer: The matrix has coefficients $a_{ij}=\frac{1}{i+j-1}$, which is a special case of a Cauchy matrix.
Comment: One can go a step further: It's a [Hilbert matrix](https://en.wikipedia.org/wiki/Hilbert_matrix).
Comment: Yes, exactly. This is written at the Wikipedia link in line $5$ - but your link is much nicer!

Help recognize a special matrix


Como pegar o caminho da subpasta que foi " SELECIONADA " na listbox pelo usuário e salvar o arquivo dentro

Question: O programa que estou criando deve fazer os seguintes passos:

Primeiro o usuário cria uma subpasta para ir salvando os projetos que foram calculados pelo programa, conforme imagem e código abaixo.
Quando o usuário cria uma subpasta, por exemplo "EM01_Projeto de um bloco 4",
ela é criada dentro de um diretório pré-definido (c:\evandro\tad\"EM01_Projeto de um bloco 4")
Como faço para salvar um arquivo onde o nome já fixo no código escrito em C# "Cargas.txt" onde quando o usuário dá um click no botão "Salvar", conforme imagem abaixo, e este comando reconhece o caminho da subpasta aberta ou criada através do textBox_NomeBloco.Text pelo usuário final conforme explicado no item 2?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tad_Bloco1._0
{
     public partial class NovoBloco : Form
     {
        string[] listapasta = Directory.GetDirectories(@"c:\evandro\tad");

    public NovoBloco()
    {
        InitializeComponent();
    }

    private void NovoBloco_Load(object sender, EventArgs e)
    {

        foreach (string p in listapasta)
            listBox_ListaBlocos.Items.Add(Path.GetFileName(p));

    }

    private void button_Ok_Click(object sender, EventArgs e)
    {
        string pasta = @"c:\evandro\Tad\" + textBox_NomeBloco.Text;

        if (Directory.Exists(pasta) == false)
        {
            Directory.CreateDirectory(pasta);
            listBox_ListaBlocos.Items.Add(Path.GetFileName(pasta));
            MessageBox.Show("Pasta criada com sucesso!");
        }
        else
            MessageBox.Show("Esta pasta já existe");
    }

    private void button_Cancelar_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void listBox_ListaBlocos_SelectedIndexChanged(object sender, EventArgs e)
    {
        textBox_NomeBloco.Text = listBox_ListaBlocos.Text;
    }
  }
}

Comment: Explica melhor, pelo menos pra mim a pergunta não está fazendo sentido.
Comment: Daniel eu reformulei a pergunta, talvez acredito que deve estar mais clara!
Comment: Sinceramente eu acho que você não tem uma dúvida, você quer que alguém aqui faça o seu trabalho pra você. Recomendo estudar um pouco de `c#` e `Windows Forms`, está cheio de tutorial na internet pra isso: http://bfy.tw/6ICZ
Comment: Como já falei não sou programador e sim engenheiro civil, só estou desenvolvendo este programa para uso pessoal. Muito obrigado!
Comment: @EvandroMendes Tudo bem que você não seja programador,mas mesmo assim,dê uma pesquisada melhor sobre o assunto que tem dúvidas,caso não encontre,você pode perguntar,mas não querer esperar que outros façam tudo para você.
Comment: Boa noite Daniel                                                                                Como faço para criar um código para salvar um arquivo onde o nome já é fixo no código escrito em C# "Cargas.txt" onde quando o usuário dá um click no botão "Salvar", este comando reconhece o caminho da pasta aberta ou criada pelo usuário final conforme explicado no item 2.
Comment: No método `button_Ok_Click` você salva a última pasta cria no `listBox_ListaBlocos`, certo? Se for isso mesmo, o último registro desse `ListBox` é a última pasta criada: `listBox_ListaBlocos.Items[listBox_ListaBlocos.Items.Count - 1];`
Comment: Isso mesmo Daniel
Comment: O problema era só esse? Seu problema já foi resolvido então? A parte de salvar o `txt` você conseguiu?
Comment: Desculpe Daniel na verdade o listBox é só para o usuário visualizar qual e quantas pastas ele tem. A última pasta está no textBox_NomeBloco
Comment: Na verdade `textBox_NomeBloco.Text` tem a pasta selecionada no `ListBox`, não?
Enfim, se o seu problema já tiver sido resolvido, apague a pergunta, porque ela não está muito boa.
Comment: Realmente, consegui entender bem o que seu programa deve fazer, mas agora você não está falando sua dúvida. Qual sua dúvida? Qual sua dificuldade em fazer o que você listou lá em cima?
Comment: O código lá em cima esta ok. A minha pergunta é como criar um código no segundo forms (a segunda imagem) onde quando eu clico no botão "salvar", este reconhece a subpasta que foi criada pelo usuário no textBox_NomeBloco.Text e salva o arquivo fixo "Carga.txt".
Comment: [Retornar array PHP no JSON em AJAX](http://pt.stackoverflow.com/q/135271/45854)
Answer: Acho dificil alguém formular isso aqui para você, não achei a pergunta muito clara e foi muito especifica a ponto de realmente parecer que você está pedindo o código pronto a alguém... bem, eu não entendi a pergunta mas vou tentar ressaltar alguns pontos....

Você pode escrever um txt com esse simples comando
System.IO.File.WriteAllText("C:\exemplo.txt", "conteúdo");

Se a questão é um botão numa Form secundária salvar um arquivo que está de alguma forma contido na Form Primária você pode tentar usar uma variável Global
Definindo uma variável como "public"
vamos supor que a Form Main deve chamar a Form Exemplo passando pra ela uma string... existem mais de uma forma de fazer isso, tentarei lhe mostrar a mais simples...
public class Main : Form
{
    public Main(){
        InitializeComponents();
    }
    public void Button1_Click(object o, EventArgs e){
        Exemplo form = new Exemplo();
        form.Caminho = "C:\Exemplo.bin";//aqui é onde a Form Exemplo salvará
        form.Conteudo = "Conteúdo de Exemplo";//aqui é o conteúdo a salvar...
        form.ShowDialog();
    }

}
public class Exemplo : Form
{
    public string Caminho;
    public string Conteudo;
    public Exemplo(){
        InitalizeComponents();
    }

    public void Salvar_Click(object o, EventArgs e){
        System.IO.File.WriteAllText(Caminho, Conteudo);
    }

}

Bem, acabei dando meio de mão beijada mas é isso ai... eu prefiro passar o argumento direto pra form, mas acho que isso é mais fácil pra tu
Comment: Marcus André, Falion  muito obrigado pela ajuda de vocês. Eu vou tentar resolver de outra maneira e assim se conseguir obter sucesso no meu código vou colocar aqui. Provavelmente eu  acho que não foi bem clara a minha pergunta, então acho melhor tirar e assim que terminar o código eu insiro aqui. A respeito do meu comentário sobre eu não ser um programador profissional, só respondi desta forma porque fiquei chateado a forma como o nosso amigo Daniel respondeu.
Comment: @Evandro Mendes E aí colega. Conseguiu resolver? Se sim, posta o resultado. Você disse que postaria...


Variavel do context processors não funciona com render_to_string

Question: Em alguns lugares do meu sistema, eu renderizo uma página com render_to_string, pois eu quero renderizar apenas um pequeno conteúdo. Nesses casos eu não recebo minhas variáveis que criei no context_processors. Alguém tem uma solução sem ser passar manualmente a variável no dicionário do render_to_string? Obrigado.
atualização
Depois de uma boa pesquisada descobri que em versões anteriores do Django (encontrei na versão 1.9) existia um parametro no render_to_string chamada context_instance, onde eu passava o RequestContext e ele carregava já o dicionário com as variáveis do context_processors. Porém por algum motivo foi removida das novas versões. Continuo sem ter uma solução para carregar o context_processors no render_to_string. Eu realmente preciso da String contendo o HTML carregado com minhas condições que uso de algumas variáveis do context_processors. Então ainda meu problema persiste.
Answer: Acredito que bastaria você fazer:
html_body = render_to_string(template_name, context, request=request)


Are SAT scores considered discrete? If so, then can we use the normal distribution?

Question: I believe the definition of a normal distribution only applies to continous random variables. But SAT scores are normally distributed and the possible values of an SAT score are discrete.
Comment: The normal distribution only [opproximates](http://en.wikipedia.org/wiki/Central_limit_theorem) the scores distribution.
Answer: SAT scores are certainly not normally distributed.  Besides being discrete, they are restricted to a finite range.  However, it is possible that for some purposes you can treat the normal distribution as a good approximation to the actual distribution.
Comment: The range is not only finite, it is also non negative. Unlike the normal distribution.
Comment: Actually the range (for all three sections combined) is $[600, 2400]$.
Comment: Actually, the range is [0,2400], since there is a -0.25 points for every wrong multiple-choice question. Thus, if a person gets every question wrong, the final score is a zero. However, I don't see how anyone can score that low in real life, so it is a hypothetical range.


$G=\mathbb{Z}_2\times\mathbb{Z}_3$ is isomorphic to?

Question: $G=\mathbb{Z}_2\times\mathbb{Z}_3$ is isomorphic to

$S_3$
A subgroup of $S_4$.
A proper subgroup of $S_5$
$G$ is not isomorphic  to a subgroup of $S_n$ for all $n\ge 3$

What I know is Any finite group is isomorphic to a subgroup of $S_n$ for some suitable $n$(Caley's Theorem), 1 is not true as $G$ is abelian but $S_3$ is not,$4$ violates Caleys Theorem, for 3 I saw that there is an order $6$ element in $G$ namely $(1,1)$ but No element of the subgroup of $S_4$ have order $6$ right? Not sure about 3,  Thank you for the help.
Comment: You might be interested in the following fact: any finite permutation generates a cyclic group of order which is the least common multiple of the disjoint cycles forming the permutation.
Comment: If a group $G$ is isomorphic to a subgroup of $S_n$ for some $n$, then in particular $G$ has to be finite. Therefore NOT ANY group is isomorphic to a subgroup of $S_n$.
Comment: @Mercy Unless you interpret $n$ as taking cardinal values as well.
Comment: @Mercy, I am simply pleased and delighted at your comment.
Comment: @tomasz thank you for the comment, sure I will think.
Comment: I find the statement of Condition 4 completely ambiguous! It is true with one interpretation and false with the other.
Answer: You are correct that $G$ is not isomorphic to $S_3$ but that it is isomorphic t some subgroup of $S_n$ for some $n$ (in fact, any $n\geq 6$ clearly works). Note that $G\cong \mathbb Z_6$, the cyclic group of order $6$. Thus the existence of a subgroup isomorphic to $G$ is equivalent to the existence of an element of order $6$. Any element of $S_4$ is either a $4$-cycle, which has order $4$, a $3$-cycle, which has order $3$, or a product of disjoint $2$-cycles, which have order $2$. Thus $G$ is not isomorphic to a subgroup of $S_4$. Can you think of an element of $S_5$ with order $6$?
Answer: Hint: consider permutations of $\{1,2,3,4,5\}$ that leave a certain set invariant.
Answer: HINT: Consider the permutation $(12)(345)$. (Compare it with $\Bbb Z_2\times\Bbb Z_3$.)
Answer: Your group is isomorphic to $Z_6$.  I think $S_5$ has an element of order $6$, i.e. $(123)(45)$.


Ubercart need to pay depends on user role

Question: I am using drupal 6.20 and Ubercart 2.0
Like what I asked in the subject.
Is there any chance that I can customize a ordering process with or without payment?
For example:
There are 2 roles of users ( Role A and Role B)
Users of Role A need to pay all my products to complete the transaction.
Users of Role B don't need to pay any of my products to complete the transaction.
Actually I want my website to be suitable for 2 kinks of clients:
1. wholesalers (Role A) --- order online but pay through company invoicing system
2. retailers (Role B) --- order online and pay instantly
Appreciate any thoughts and helps on this!
Answer: This question has been solved and just want to put the solution here to help someone has the same interests!
Download the uc_purchase_order module, http://drupal.org/project/uc_po
And give the permission to the user role you want them to purchase through purchase order.
Comment: how can this be achieved with drupal 7 as the module listed UC Purchase Order does not have a drupal 7 version


Não consigo fazer o envio para mais de um e-mail

Question: Tenho o seguinte código para envio de e-mail, porém apenas no primeiro e-mail recebe o segundo não.
$to  = "firstname.lastname@example.com";
$to  .= "email@example.com";

$subject = 'Guarapari Virtual - Corretores On-Line';

$message = "
Prezado cliente!

{$enviar_gc_nome} visitou o Guarapari Virtual e enviou uma solicitação de orçamento para você pelo canal Corretores On-Line.

";
$message .= 'E-Mail: '.$enviar_gc_email.'
';
$message .= 'Telefone: '.$enviar_gc_telefone.'
';
$message .= 'Data da entrada: '.$enviar_gc_dataentrada.'
';
$message .= 'Data da saída: '.$enviar_gc_datasaida.'
';
$message .= 'Número de adultos: '.$enviar_gc_nadultos.'
';
$message .= 'Número de crianças: '.$enviar_gc_ncriancas.'
';
$message .= 'Mensagem: '.$enviar_gc_msg.'
';
$message .= '
';
$message .= 'Obrigado!';

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$headers .= "From: {$enviar_gc_nome} <{$enviar_gc_email}>" . "\r\n";

mail($to, $subject, $message, $headers);

Comment: tente separar os emails com uma vírgula (http://php.net/manual/en/function.mail.php)
Comment: @thiagoalessio fiz, mas continuo recebendo apenas no primeiro email
Comment: separar por vírgula como @thiagoalessio mencionou funciona perfeitamente para mim. Você pode também adicionar o segundo email ao `CC` no header, assim: `$headers .= "\n Cc: firstname.lastname@example.com";`
Comment: @RicardoPontual Infelizmente para mim não está funcionando
Answer: Dessa maneira deve funcionar, pois é o modo recomendado na documentação:
$to  = 'firstname.lastname@example.com' . ', ';
$to .= 'email@example.com';


Formulário na view com sub-formulários em partialView

Question: Caros amigos, tenho uma view que contém apenas @model Projeto.Models.Oc e um form. Dentro deste form, tenho botões que chamam MODAL, esses MODAL possuem partialView que possui outro form e @model Projeto.Models.Rc, @model Projeto.Models.Pc, etc.
Eu queria saber qual a tratativa para esta necessidade, pois acredito que essas strong type na view principal e nas partialViews estão conflitando.
Answer: O <form> deve sempre ficar apenas na View pai. As Views parciais atém podem ter campos do <form>, mas dentro delas você não pode usar <form>, até porque o HTML nem coloca um <form> dentro de outro.
Quanto a especificar os strong types para cada partial, não há problemas, desde que para cada partial seja passado o tipo correto. Ou seja, suponho que para a View pai, que tem a seguinte declaração:
@model Projeto.Models.Oc

As partials sejam chamadas assim:
@Html.Partial("_MinhaPartial", Model.Rc)

Ou então assim:
@Html.Partial("_MinhaPartial", new Projeto.Models.Rc())

Comment: Cigano, estou usando na view Create conforme disse acima, porém, na view Edit, preciso passar o o parametro ticket para que a partialView venha preenchida. Como posso fazer isto?
Comment: Neste caso, você cria um *ViewModel*, que é uma classe com a classe que antes era declarada como `@model` dentro, mais uma *property* chamada `Ticket`. No `POST`, seu Controller recebe como parâmetro esse *ViewModel*.
Answer: Crie propriedades na sua model principal do tipo das models que serão carregadas em suas partials. Assim você só precisa referenciar uma única model em sua view, independentemente do que suas partials views podem carregar. Por exemplo:
public class ModelPrincipal
{
   //Depois de você declarar as propriedades dessa model,
   //declare a propriedade da model que trabalhara na partial View
   public ModelSecundaria modelSecundaria {get; set;}

}

Depois disso alimente em sua Action a sua model, de acordo com o seu negócio e referencie em sua PartialView como se fosse uma propriedade normal:
 @Html.Partial("_MyPartial", Model.modelSecundaria);


Does moving closer to the target reduce first passage time

Question: Given a finite graph $G$ and two vertices $v, w \in G$, denote the mean first passage time from $v$ to $w$ by $T(v, w)$. If $u$ is a neighbour of $v$ and $u$ is closer to $w$ than $v$ (in the sense of graph distance) is it true that $T(u,w) \leq T(v,w)$?
Answer: I presume you're talking about a simple random walk, where from a given vertex you go to any neighbour of that vertex with equal probabilities.  Consider a situation like this:

Vertex $u$ is closer to the target $w$ than $v$, but if you go from $v$ to $u$ you're very likely to go next into the mess at the top of the picture
and stay there for a very long time before you ever get to $w$, while if you go from $v$ to one of the vertices below it
you have probability $1/2$ to get to $w$ on the next move.  In fact, if
the degree of $v$ is $d$, we have
$$T(v,w) = 1 + \dfrac{T(u,w)}{d} + \dfrac{d-1}{d} (1 + T(v,w)/2)$$
so that
$$T(v,w) = \dfrac{2 T(u,w)}{d+1} + \dfrac{4d-2}{d+1}$$
which is less than $T(u,w)$ if $T(u,w) > (4d-2)/(d-1)$.
Comment: So, ff we restrict $G$ to be a regular graph then the property would hold?


How can I pass more variables/trigger preprocess to plugin block?

Question: The block opigno_documents_last_group_block is located in opigno_learning_path/src/Plugin/Block/DocumentsLastGroupBlock.php, which looks like this:
<?php

namespace Drupal\opigno_learning_path\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Url;

/**
 * Provides a documentslastgroupblock block.
 *
 * @Block(
 *   id = "opigno_documents_last_group_block",
 *   admin_label = @Translation("DocumentsLastGroupBlock"),
 *   category = @Translation("Custom")
 * )
 */
class DocumentsLastGroupBlock extends BlockBase {

  /**
   * @var \Drupal\Component\Plugin\Context\ContextInterface[]|mixed
   */
  protected $groupId;

  /**
   * {@inheritdoc}
   */
  public function build() {
    $this->groupId = $gid = $this->configuration["group"];
    $tid = _tft_get_group_tid($gid);
    $content = _tft_folder_content($tid, FALSE, $gid);
    $content = array_slice($content ?: [], 0, 4);
    foreach ($content as $index => $item) {
      $content[$index] = [
        '#theme' => 'opigno_documents_last_group_item',
        '#type' => $item["type"] == 'file' ? 'file' : 'folder',
        '#item' => $item,
        '#label' => $item["name"],
        '#link' => $this->itemLink($item),
      ];
    }
    $build['content'] = [
      '#theme' => 'opigno_documents_last_group_block',
      'content' => $content,
    ];
    return $build;
  }
(...)

and is attached in LearningPathController in this module:
 /**
  * Training document block.
  */
  public function trainingContentDocuments(&$content, $group) {

    // $TFTController = new TFTController();
    // $listGroup = $TFTController->listGroup($group->id());
    $tft_url = Url::fromRoute('tft.group', ['group' =>    $group->id()])->toString();

    $content['tabs'][] = $tft_url = [
     '#markup' => '
' . $this->t('See all') . '
',
    ];

    $block_render =    $this->attachBlock('opigno_documents_last_group_block', ['group' => $group->id()]);
   $block_render["content"]['link'] = $tft_url;
    $content['tab_content']['documents'] = (isset($block_render["content"]["content"]) && !empty($block_render["content"]["content"])) ? [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'documents',
      ],
      'block' => [
        'content' => $block_render["content"],
      ],
    ] : [];

  }

I tried to extend it in custom module: web/modules/custom/npx_files/src/Plugin/Block/NpxFilesDocumentsLastGroupBlock.php:
<?php

namespace Drupal\npx_files\Plugin\Block;

use Drupal\opigno_learning_path\Plugin\Block;

The block opigno_documents_last_group_block is located in opigno_learning_path/src/Plugin/Block/DocumentsLastGroupBlock.php, which looks like this:
<?php

namespace Drupal\opigno_learning_path\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Url;

/**
 * Provides a documentslastgroupblock block.
 *
 * @Block(
 *   id = "opigno_documents_last_group_block",
 *   admin_label = @Translation("DocumentsLastGroupBlock"),
 *   category = @Translation("Custom")
 * )
 */
class DocumentsLastGroupBlock extends BlockBase {

  /**
   * @var \Drupal\Component\Plugin\Context\ContextInterface[]|mixed
   */
  protected $groupId;

  /**
   * {@inheritdoc}
   */
  public function build() {
    $this->groupId = $gid = $this->configuration["group"];
    $tid = _tft_get_group_tid($gid);
    $content = _tft_folder_content($tid, FALSE, $gid);
    $content = array_slice($content ?: [], 0, 4);
    foreach ($content as $index => $item) {
      $content[$index] = [
        '#theme' => 'opigno_documents_last_group_item',
        '#type' => $item["type"] == 'file' ? 'file' : 'folder',
        '#item' => $item,
        '#label' => $item["name"],
        '#link' => $this->itemLink($item),
      ];
    }
    $build['content'] = [
      '#theme' => 'opigno_documents_last_group_block',
      'content' => $content,
    ];
    return $build;
  }
(...)

and is attached in LearningPathController in this module:
 /**
  * Training document block.
  */
  public function trainingContentDocuments(&$content, $group) {

    // $TFTController = new TFTController();
    // $listGroup = $TFTController->listGroup($group->id());
    $tft_url = Url::fromRoute('tft.group', ['group' =>    $group->id()])->toString();

    $content['tabs'][] = $tft_url = [
     '#markup' => '
' . $this->t('See all') . '
',
    ];

    $block_render =    $this->attachBlock('opigno_documents_last_group_block', ['group' => $group->id()]);
   $block_render["content"]['link'] = $tft_url;
    $content['tab_content']['documents'] = (isset($block_render["content"]["content"]) && !empty($block_render["content"]["content"])) ? [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'documents',
      ],
      'block' => [
        'content' => $block_render["content"],
      ],
    ] : [];

  }

I tried to extend it in custom module: web/modules/custom/npx_files/src/Plugin/Block/NpxFilesDocumentsLastGroupBlock.php, but it doesn't really get triggered (I am not sure if I can even extend this this way):
<?php

namespace Drupal\npx_files\Plugin\Block;

use Drupal\opigno_learning_path\Plugin\Block;
/**
 * Provides a documentslastgroupblock block.
 *
 * @Block(
 *   id = "opigno_documents_last_group_block",
 *   admin_label = @Translation("DocumentsLastGroupBlock"),
 *   category = @Translation("Custom")
 * )
 */

class NpxFilesDocumentsLastGroupBlock extends DocumentsLastGroupBlock {

  public function build(){
    return [
      '#markup' => $this->t('Hello, World!'),
    ];
  }

}

However, it doesn't trigger the block, what is the good way to extend this?
Cache cleared&module turned on of course.
class NpxFilesDocumentsLastGroupBlock extends DocumentsLastGroupBlock {

  public function build(){
    return [
      '#markup' => $this->t('Hello, World!'),
    ];
  }

}

Cache cleared&module turned on of course.'
I tried to preprocess this plugin block by hook_preprocess_block, but it doesn't get triggered by this hook, only its 'parent' block does. Also hook_block_build_alter doesn't get triggered by this block (only its parent). I am able to get to this block by hook_block_alter, but it doesn't really help, as I am not able to put some extra variables there, I think.
Could anybody point me in the right direction? I would like to either add extra variables to this block or point it to display some other block or unset it/disable programatically before rendering. I spent plenty of time trying to learn about it and trying different hooks, but no luck so far.
Answer: Thanks for ignoring my question and downvotes! ;) I totally don't understand you people.
However, I managed to understand how to solve my problem and pass variables:
function npx_main_theme() {
  return [
    'opigno_documents_last_group_block' => [
      'variables' => [
        'param1' => 'texttest'
      ]
    ]
  ];
}


Why is lilypond treating this measure with 3⅓ beats?

Question: The problem
I'm currently working on a joke piece to learn the lilypond software and came across this unusual bug.
I currently have this in the code:
\clef "percussion"
c'1^\markup "scream"
\clef "treble"
\time 4/4
r1 r2 r r4 r r r r8 r r r r r r r r16 r r r r r r r r r r r r r r r r32 r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r

yet for some reason lilypond is not putting 4 beats per measure?

It seems to round 3 plus a single triplet note? I'm not sure why this is happening.
Clues
A few time signatures before this I have a measure using a 4/3 time signature which uses 5 beats plus a single quarter note triplet (5⅓ beats).
The two other time signatures that appear between them I do not finish between switching to a different time signature and putting a bar line to show the difference.
I'm still not entirely sure why this happens and how to fix it. Does anybody know how? Thanks in advance.
Edit
The problem was an overflow, and it is solved now. Thank you!
Comment: @AJFaraday  because most of us love music-score jokes.
Comment: You probably don't need a percussion clef just to indicate the scream is unpitched. The x note head is enough. You can notate it all with the treble clef.
Comment: Why the Threatening Music Notation would you be producing this score in the first place?
Answer: If you compile your code separately, you will see that it's OK (for instance, see a lilybin).
So the problem must be elsewhere. Most likely, there are mistakes in the preceding music, and they "overflow" here. The easiest way out is to use bar checks: in your source, you should put | at each place where a barline should occur. Lilypond then checks whether the position of |'s match with the actual barlines, and if not, you get a warning. For instance, if I write \time 3/4 a2 a2 a2 a4, I get one bar with two half-notes, and one with a single half-note (the middle one will start in the first bar and "overflow" into the other), then a new bar with a quarter note. If I, for instance wrote \time 3/4 a2 a2 | a2 a4 |, I get an error on the first bar, because that clarifies that I meant a2 a2 to be a complete 3/4 bar, which it obviously is not.
For more info, have a look at the documentation.  By the way, bar checks are ubiquitous in Lilypond: everybody uses them pretty much everywhere. You should too (if you want to avoid mistakes like this).
Btw., to maintain some readability in your code, you should put one bar per line. At least that's what I found to be most useful.
Answer: Note that 5 beats and one single quarter triplet are not 5⅓, but 5⅔.
Thus the measure does not in fact fit 4/3, but it would need 17/12. This results in missalignment in the following measures. So if you use a single eigth note triplet or a 17/12 measure this will work, as demonstrated here:
{
  \clef "percussion"
  \time 4/3
  c' c' c' c' c' \tuplet 3/2 { c' }
  \time 4/4
c'1^\markup "scream"
\clef "treble"
\time 4/4
r1 r2 r r4 r r r r8 r r r r r r r r16 r r r r r r r r r r r r r r r r32 r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r
}

{
  \clef "percussion"
  \time 4/3
  c'4 c' c' c' c' \tuplet 3/2 { c'8 }
  \time 4/4
c'1^\markup "scream"
\clef "treble"
\time 4/4
r1 r2 r r4 r r r r8 r r r r r r r r16 r r r r r r r r r r r r r r r r32 r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r
}

{
  \clef "percussion"
  \time 17/12
  c'4 c' c' c' c' \tuplet 3/2 { c' }
  \time 4/4
c'1^\markup "scream"
\clef "treble"
\time 4/4
r1 r2 r r4 r r r r8 r r r r r r r r16 r r r r r r r r r r r r r r r r32 r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r
}

By the way: When posting code to illustrate a problem, please make sure to post enough code to actually illustrate it. This makes helping you easier.


how to structure REST API XML response

Question: I'm trying to define how to return XML content from my web API.
Should the root element of the web server response always be called "Content", or should I define a (possibly) different root element for each of the API calls' reponses?  Or do I even need a root key at all?
Answer: I would stay away from trying to define it on your own and go with something standard like wrapping around in Atom or similar. As I mentioned in another answer, there is precedent for this type of thing (no matter whether you use JSON or XML).
Answer: This sort of question demonstrates one of the many reasons JSON is far superior to XML for data. You don't have to name everything.
Recommendation: just use JSON.
Answer: The API we maintain has a single constant root element. Really it is up to you. Other alternatives might be a different roots per data return type, different roots for classes, or as you say, different roots per function.
Our API is structured something like this (not that it is a standard or anything):
<product name common root>
<class name>
<function return data>...</function return data>
</class name>
</product name common root>

We also allow batch calling, so this helps with determining which results are which.
<product name common root>
<class name>
<function1 return data>...</function1 return data>
</class name>
<class2 name>
<function2 return data>...</function2 return data>
</class2 name>
</product name common root>

Comment: Keep in mind that REST is all about transferring representations of states of resources. So your responses need to be clear and intuitive representations of the state of your resources. If you have a resource which is "all orders placed in the last 30 days" and you're using XML, then your root element should be something like `Orders`. And if you have a resource which is "Recent Invoices" then your root element should be named `Invoices`. I don't recommend using the same element name for disparate types of resources.

how to structure REST API XML response