Question about beats and their inheritance of accents on the rhythm

Question: I see that I've created a lot of confusion with my original question, so I have decided to send the author of "How to read Music in 30 Days, English 2022 Ed." a detailed question that should clearly state my concern.
As it contains quite a lot of text and sketches, these are now attached in handwritten form (I hope this doesn't lead to any forum rules being broken):
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/142205/discussion-on-question-by-iwab-question-about-beats-and-their-inheritance-of-acc).
Answer: NOTE: Most of this answer makes less sense than it used to because the asker has almost completely re-written the question. The image at the bottom of this answer is the most current content here. I'm leaving the rest in case it is helpful in other ways and/or the question is reverted or re-edited in some way.

Neither 1 nor 2 is correct, but 1 is definitely wrong, while 2 is close but missing some details.
I've been taught, and I hear in almost all music, the following (q means quaver or 1/8 note):
Q q Q q Q q | Q q Q q Q q |
The first quaver is the strongest, and then the quavers that fall on beats 2 and 3 are weaker, but they are stronger than the quavers that make up the second half of each beat.
The emphasis may be very very slight, but to my ears it's definitely there. A similar pattern exists in all time signatures, as in there's a hierarchy of emphasis where the first beat gets the most and subdivisions usually have slightly less strength as the note values get smaller.

Regarding the 2/4 example, it would be similar to 3/4 but one beat shorter:
Q q Q q | Q q Q q
4/4 time can have a very slight extra emphasis on beat three:
Q q Q q Q q Q q | Q q Q q Q q Q q

Your last diagrams corrected:

Note that the big S at the start of the first beat is meant to indicate a stronger accent than the smaller s-es.
One other thought I've had: The strength of accents for a measure of music is different when the music in that measure is different - even with the same time signature. The accents I've written into the image above only apply as I've written them when the measure is filled with quavers. If other note values appear in a measure, then the accents are adjusted accordingly. It wouldn't be feasible to lay out here all of the accent patterns for all of the possible rhythms in a measure.
Comment: @It'sHEDLEY Perhaps. But neither 1 nor 2 is correct.
Comment: @iwab I can't quite decipher your comment. My answer is not meant to be compatible with the other answers. If it seems like it contradicts another answer, then that's intentional. Beyond that, what I'm trying to communicate is that in music there are **multiple levels of accent**. The most accented is the very first part of the first beat of each measure, and there are other softer accents in other parts of a measure. Also I wonder if I'm not clear on what you mean by "pulse". If the meter is 3/4 or 4/4 or 2/4 then there are accent patterns for their meters. "Pulse" is not relevant, AFAIK
Comment: The question is rather ambiguous (to some), but from what you say, surely no. 2 is way more correct than no. 1. And the example OP shows is for something somewhat different. As in there is nowhere in it where two consecutive notes could be at the beginning of a bar. Or have I missed something?
Comment: @Tim I don't understand your comment. Two consecutive notes at the beginning of a bar? Do you mean two quavers in the first beat? Because that's clearly in the asker's examples.
Comment: @ToddWilcox based on It'sHedley's anwere your edit confused me more. I thought that if stated "accent on 1. Beat. per measure" in 2-4 it's Beat1 so Q q and then Beat2 so q q. You wrote the quaver >rhythm< as if it was a 4-4 >pulse<.
Comment: @iwab If you're struggling with the level of detail in my answer and want to just know whether you should play more like 1 or 2 in your question, then **2 is almost correct and 1 is not**. You shouldn't play like 1 in any case. If you play like 2 then that's going to be at least acceptable in most cases but not ideal.
Comment: @ToddWilcox I know that there are multiple ways, in a two-four >beat< it's S w| S w, in a three-four it's S w w| S w w and in a four four it's S w s w| S w s w, but all those examples are for the pulse (the underlying, steady throb that can be felt in music, "beat" sometimes refer to one instance of it). Now we can build >rhythm< above the pulse (that's what sheets show) and if we state we have a 3/4 >pulse< and now build a rhythm with 1/8 notes on top of that I wanted to know how the defined accent from >beat< goes over to the >Rhythm< that's actually played.
Comment: @iwab If you haven't already, take a look at the other linked posts (in the "linked posts" list as well as linked in my comments). In particular, [Rhythmic/Metric Stress Patterns](https://music.stackexchange.com/q/103975/70803) addresses the question in your most recent comment to ToddWilcox.
Comment: @iwab I tried to make it very clear in my answer how the quavers work. Quavers on the beat have the exact same emphasis as crotchets on the beat. Quavers off the beat (on the "and" of a beat) have less emphasis than anything else - they are the weakest. Including the off-beat quaver during beat one.
Comment: @ToddWilcox oooh, I always thought that accent is strictly tied to the pulse and I have somehow "translate" it to the rhythm, because my book always state that "beats" have accents.
Comment: @iwab Does your book also state that "pulses" and "beats" are the same thing? I don't understand exactly what you're trying to say with "pulse" and where you got that term. Beats do have accents. Also subdivisions of beats have accents. And subdivisions of those subdivisions also have accents. But you only apply a stronger or weaker feel to a **note** that **starts** on a beat or subdivision. If you're holding a note you don't vary the accent as you hold it. And if you don't play any notes during a beat or subdivision, then those stronger or weaker feelings are bypassed and ignored.
Comment: @ToddWilcox it provides following definition: "Pulse" - The Pulse is the constant beat underlying the music. It is steady and consistent. The pulse is assigned a note value so that it becomes a quarter note beat, or a... . "Beat" - this term has several but related uses. It's often another word for pulse, but can also refer to one instance of it (that is, one pulsation)
Answer: The word "beat" has different meanings depending on context. "Beat" sometimes refers to an entire time duration, but it also can mean the beginning of such a duration.

"A quarter-note gets one beat" means a quarter note lasts one unit of time.
"Beat one gets the accent" means that the onset of the first time duration is stressed in comparison to the beginnings of other durations.

When speaking of meter, the metrical emphasis is presumed to apply only to the note occurring at the onset of the first beat.

In a first beat of two quavers, only the first quaver would receive emphasis.
In a first beat comprising a semiquaver rest followed by three semiquavers, none of the notes would receive emphasis.
In a first beat in which a crotchet is tied over from the previous measure, there is no emphasis.

When one says that a particular beat gets an emphasis, the emphasis applies to the note at the onset of that beat, not to all notes comprising the duration of that beat.
Comment: @iwab Yes, 2/4 and 4/8 are essentially identical in the way the eighth notes are emphasized. In x/4 time, in any pairing of two eighth notes in a single beat, the first of the pair is stronger. Your hand-written diagram suggests that the two eighth notes comprising beat 2 are of equal emphasis. The first eighth note of beat two is stronger than the second eighth note of beat two, and the first eighth note of beat one is stronger than the first eighth note of beat two.
Comment: Would the last image I added be therefore correct?
Comment: @iwab Yes, with the additional detail that beat two would be weaker than beat one, but stronger than the second quavers of each beat. Something like `S w s w | S w s w`. See also [Where the accent should be when the beat is made up of different notes](https://music.stackexchange.com/q/103591/70803) and [How simple time and compound time signatures change the rhythm](https://music.stackexchange.com/q/103586/70803).
Comment: @iwab Another way to say it (which is covered in the answers to the posts linked above) is that each beat has its relative strength, and each part of a beat also has a relative strength. Four quavers in 2/4 time will receive an accent pattern very similar to four crotchets in 4/4 time. Another post that might help: [Rhythmic/Metric Stress Patterns](https://music.stackexchange.com/q/103975/70803).
Comment: I think your answers somehow helped me, but your comment confused me a little. In my handwritten image the buttom should be the pulse consisting of two beats per measure and the top is the rhythm build on top of that pulse. If you tell me that my rhythm should actually be S w s w that somehow contradicts your original answere. For the rhythm accent S w s w I would need a beat of 4/8.
Comment: Oh ok that's interesting. Based on your definition I thought it's "If the Beat is 4/X than emphasize the first Note of Beat1 and Beat3 per Measure." But with 2/4 I only have two beats with S w, so I thought it can only be the first note emphasized of beat 1 and since beat2 isn't emphasized at all then also not note 1 from beat 2
Comment: @iwab note1 from beat2 is emphasized in comparison to note2 from beat2. Your book might have been more clear to have said "the onset of beat1 contains the *primary* stress within the measure."
Comment: @iwab 2/4 and 4/8 are effectively identical, given four eighth notes in one measure. For this reason, 4/8 is rarely used.
Answer: This all seems very confused, and I'm not sure the answers so far are helping to clarify… so let's take a different approach.
Let's start with a clock, tick-tocking in time.
Tick is always stronger than tock, so in 2/4 time, your clock would simply be going
Tick tock Tick tock
In 3/4 time it would go
Tick tock tock Tick tock tock
OK, so we don't have a real clock any more, but you can still imagine this.
If we add quavers, then we could use this instead - you can say this out loud to help. Keep your main tick tock at the same speed, but add a new sound in between.
Tick a tock a tock a Tick a tock a tock a
As we sub-divide away from our strong Tick each new element becomes weaker than the last.
Comment: "Why?" Who knows, but it's not. Humans just don't tick that way ;) Incidentally, did you know most clocks don't actually go 'tick tock' at all, they just go 'tick' - the rest is human perception, forcing things into patterns.
Comment: There is a degree of logic, it's just not the one you seem to be trying to apply. Best thing would be to go off & actually **listen** to some music structured in this way & hear it for yourself. You really cannot argue this out on any non-musical logic basis, you have to accept from other musicians that this is how it works in practise. "Belonging to the mathematical group which comprises beat 1" is not the way this works. 'Beat 1' is over & done with as soon as you have a new note to play, wherever it might be.
Comment: Yes, that artificial "a" is just an supportive element to evenly put 2 Quavers in one "Tock", so one in [Tock1; Tock1.5[ and the other in [Tock1.5; Tock2[. But when those 2 Quavers belong to Tock1 then I don't understand why the accent ("..") isn't an inherited trait for both: "Tick"("Quaver", Quaver) and not Tick"("Quaver", "Quaver") how I thought..
Comment: that's mostly true but in theoretical interpretations and logic it's natural that if a parent element have a specific trait (here Beat1), then it's children elements have it also (here the 2 Quavers).
Comment: "theoretical interpretations and logic" of what? You're really over-thinking this & trying to apply some kind of mathematical species logic to something that simply doesn't use the same values. I cannot say it any clearer than 'each sub-division is weaker than the last'.
Comment: I thought there must be some degree of logic behind the framework of musical notation, how would I know that it's mostly the first note per beat per measure that's accented if it's just statet that Beat1 is accented? Then somebody had to tell me that the trait of Beat1 just goes over to the first element.
Comment: @iwab - the tick a (or tock a) often isn't even even. It could be 2/3 tick and 1/3 a, or 3/4 tick and 1/4 a, just to make you aware. BUT - the 1st part of any bar is normally the emphasised part, otherwise we wouldn't know where the bar lines belong, and not be able to give a time signature to the music.
Comment: @Tim - I was trying to simplify as much as possible, as the OP seems to really have hold of the wrong end of the stick here.
Comment: I'm darned sure you're right - hence my vtc. Even after my seemingly futile effort to answer the original question!
Comment: @Tim (at)Tetsujin I think I've got it, I've added an second example in my question that might make it more clear :-)
Answer: I suspect you are assuming accent is only a matter of dynamics, that accent is achieved by loudness. The details of your post all look to me like "how much of the duration of the first beat should I play louder than all the rest."
The problem with that is the accent of beat one is more conceptual that just dynamics. You could play an entire phrase of music with a crescendo without undermining the idea of beat one is accented. Even more emphatically you could have rests on beat one, silence, and still maintain the beat one accent. Rhythmic concepts like syncopation and hemiola also contradict the accented beat one idea. But on "day 4" we don't want to get ahead of ourselves.
The passage of the book describes accent at a very basic level. I don't know how the rest of the book covers the topic, but I assume it doesn't go into issues of beat subdivisions and meter, or else you would not have asked this question.
Re-read that page carefully. The author does not say accent is only achieved by playing a beat strongly. The author does not say beat one is always accented.
I would look at that passage of the book like this. If you had some music which was only quarter notes with no pitch changes (that is essential what the notation shows) the obvious way to play that and achieve some sense of an accented beat one (which would then define a conceptual bar line) is to apply a (dynamic) accent on some of those notes at a regular period.
That book is probably a "fundamentals of music" type text so it isn't going to get into a deep discussion of meter. It just wants to introduce the idea of how to count beats, beat grouping, and the bar line. Do not read it too literally and apply it to performance dynamics.

How are notes weighted if the accent is on first beat?

They are weighted, dynamically accented, any way you like.
This part of the book is not trying to explain that.
I agree with Tim's answer that the onset, the very first moment, of beat one is what is accented. In that sense your example of two quavers on beat one would put a dynamic accent on the first quaver but not the second. I've never read a performance rule of thumb that was so prescriptive. It's just a literal misapplication of a metrical concept to the art of performance.
I think one practical thing should be mentioned about beat one and how its accent is typically and most obviously manifest in music. The accent of beat one is what defines the bar line and two very important things are organized around the bar line: phrase starting and ending, and chord changes. Those are structural elements rather than dynamic elements.

I've started learning music theory and have a question

It's good to have questions and use them to probe a text. But if you're working with Ellul, How to Read Music in 30 Days: Music Theory for Beginners, I would try writing those questions down and set them aside so you can work through the 30 days without getting side tracked. It will be a lot to absorb and you probably want it to flow into your mind unrestricted by questions. At least for that first "30 days." Get it in first, then question it in a second phase. Some questions may be answered within the text but not until you put all the pieces together. Other questions may lead you to other texts. And don't forget that real scores and great performance recordings are often the best textbooks. Look for answers from the great musicians.
Answer: A beat doesn't really have a duration value, it's more like a moment in time.
Consider an analogy with a clock:  At what time is it noon?
If you are just looking at just the hours, you could kinda (somewhat clumsily) say that "noon is an hour long".  Whereas if you are counting minutes you might think of it as only a minute long (with 11:59 being before noon, and being 12:01 being after noon).  But you could also count seconds ... etc.
Really, noon is just an instantaneous moment; without any duration value at all (a single point).
(But, whatever units you are counting, surely you wouldn't say that 12:00 and 12:30 are both "at noon", would you?)
Similarly, it's more precise to say that beats don't really have durations, instead consecutive beats are separated by a duration value.

Generally, the first beat of the bar has the strongest accent, other beats get some kind of medium accent, and any other moment get a weak accent.
Further subdivisions (semiquavers) would introduce more weak/weaker moments in the gaps.
A few simple examples
(using S for strong, M for medium, and w for weak)
A bar of 3/4 filled with crotchets:
1   2   3   |
S   M   M   |

And now filled with quavers:
1 & 2 & 3 & |
S w M w M w |

A bar of 2/4 filled with crotchets:
1   2   |
S   M   |

And now filled with quavers:
1 & 2 & |
S w M w |

So, your option 2 is good, but it'd be even better if you used a mix of "Quaver"s and "quaver"s, to show the difference between the medium and the weak:

Quaver - quaver - Quaver - quaver - Quaver - quaver
Comment: @iwab Consider a conductor's baton: it marks the beats with continuous motion, it turns sharply on the beat moment; it doesn't stop at any point and wait for the "beat" to end before moving to the next beat, does it?
Comment: "A beat doesn't really have a duration value, it's more like a moment in time." I started a discussion about this yesterday: https://www.reddit.com/r/musictheory/comments/10bq3y7/how_would_i_even_play_2_notes_in_one_beat/?utm_source=share&utm_medium=android_app&utm_name=androidcss&utm_term=1&utm_content=share_button
Comment: Excerpt: "Yes, a beat takes up time."
"Music is continuous in time, each "beat" is the slice of time between the beginning of the beat, and the beginning of the next beat."
"A beat is a length of time. Not a singular point." So I concluded the mathematical definition where a beat starts and ends must be the half open time interval "[Beat_x; Beat_x+1["
Comment: that might be true but doesn't provide me the idea you want to make clear.
Comment: I find your answer genuinely confusing. While we frequently refer to "beat X" to mean "the beginning of beat X", it's not true that beats don't have duration. The whole point of a beat is that it has duration — that it divides time into discrete units.
Comment: It's an interesting concept, but I'll need time to consider.
Comment: @It's…HEDLEY
I suppose the term "beat" is overloaded with only slightly different meanings.
For we do say the second quaver in the bar occurs *on* the "&" *of* beat 1,
but a note played at this time certainly isn't "*on* the beat".
Answer: It's not the beat that's stressed as much as the first sound made in each bar. So, the 1st quaver, or even semiquaver, is the most stressed note in any bar. That's how we can determine where the beginning of each bar is, thus what the time signature will be.
EDIT: this answer is based on the question, which only gives the choice of stress between the 1st quaver, or the 1st two quavers. The comments (thus dvs) are presumably based on what else was read into its wording. It's pretty obvious that if there's no note on beat 1 there can't be emphasis there, but that's not the premise of the question, in fact, it's really a different question. Think on it!
Comment: @iwab It's not wrong, it's just a confusing use of language. The word "beat" is used both to refer to the entire duration and the moment at which the duration begins. Here it refers to the moment at which the duration begins.
Comment: Oh ok, so is the definition provided by "How to Read Music in 30 Days by Ellul" wrong? (I've added a picture in my question)
Comment: Sorry, Tim, but this is not worded properly. What if the first note in the bar doesn't come at 1? Or what if 1 is syncopated?
Comment: @ojs - that's immaterial to the question. Which only concerns the first  or first and second quaver in the particular bar. Please read the question!
Comment: @user1079505 - the 1st note does indeed come on the 1st beat, please read the question!


Genus of Petersen graph

Question: Determine (with a proof) the genus of the Petersen Graph

I tried drawing it and I think the answer is 1 but I'm not sure how to prove it
Comment: [wikipedia agrees](https://en.wikipedia.org/wiki/Category:Graphs_of_genus_1)
Answer: If you can find a way to draw the Petersen graph with exactly one crossing, then it suffices to note that it fails to be planar because it contains a $K_{3,3}$ minor.
Comment: over here, https://www.cut-the-knot.org/do_you_know/CrossingNumber.shtml, it is noted that the crossing number is 2, and it might actually not be possible to approach the question in this manner. I am wondering if there's any way to do this without explicitly drawing it on a torus.

Genus of Petersen graph


Irrational number $\sqrt2$ proof

Question: I have seen the proof that  $\sqrt2$ is irrational
However I'm a bit confused. The proof goes something like this. first assume $m$ and $n$ are integers such that $$ \frac{m}{n}  = \sqrt{2} $$ $$ \frac{m^{2}}{n^{2}}  = 2 $$ $$m^{2}  = 2 n^{2}$$  $\implies m^{2} $ is divisible by $2 \implies m$ is divisible by 2. Let $2q = m$. Then $$m^{2}  = 4 q^{2} = 2n^{2}$$ $$ n^{2}  = 2 q^{2}$$ This means that $n^{2}$ is divisible by $2 \implies n$ is divisible by $2$...... Hence $\sqrt{2}$ is irrational. $$$$If $ m^{2} $ is divisible by $2$ how do we know that $m$ is also divisible by $2$? If you say it's a prime number then I can argue that I didn't need to do all these steps. I could have just said that its factors don't multiply to $2$ hence $\sqrt{2}$ is irrational
Comment: because m is an integer. it $(m^2)$ cannot have only one multiple of $2$. it must have at least two multiple of $2$.
Comment: For the proof you also have to assume that $m$ and $n$ are co-prime, i.e. share no prime factors. You can do this because you otherwise could reduce the fraction. The square of an integer, say $N^2$, has the same distinct prime factors as $N$. The factors will just be an even multiple in the square.
Comment: http://math.stackexchange.com/questions/917983/the-proof-of-sqrt2-is-not-rational-number-via-fundamental-theorem-of-arithm
Answer: Suppose that $m$ is odd, then $m=2k+1$, and thus
$$m^2=(2k+1)^2=2(2k^2+k)+1$$
and thus $m^2$ is odd too. That prove that if $m^2$ is even then $m$ is even too.
You can generalize this result : If a prime number $p\mid m^s$ for $s\in\mathbb N$ then $p\mid m$. Indeed, let $m=p_1^{\alpha_1}...p_n^{\alpha_n}$ the decomposition of $m$ in prime factor. Then $$m^s=p_1^{s\alpha_1}...p_n^{s\alpha_n}$$
and thus all prime that divide $m^s$ also divide $m$.
Answer: To prove that if $m^2$ is even then $m$ is even, we proceed by contradiction. So suppose that $m$ is odd but $m^2$ is even. Then $m=2k+1$, so $m^2=4k^2 + 4k+1$. In particular, $m^2=4k(k+1)+1$ is one more than an even number, which is a contradiction.
Answer: As the answer above put it, you can get it by contradiction.
If you want to deal with the square root of a general prime $p$, you can use the fundamental theorem of arithmetic: if $m^2$ is divisible by $p$, then it must have a prime factor of $p$, and all prime factors of $m^2$ are also prime factors of $p$.
To answer your last point: it is possible for a number to be a prime and still a product of two rational numbers $(3 = \tfrac{2}{1}\frac{3}{2})$.  The square roots are irrational, because you impose the condition that it must be the product of two equal numbers.
Answer: $\frac{m^2}{n^2}=2\implies m^2=2n^2\implies 2\mid m\implies 2\mid n \implies 2^2\mid m\implies 2^3\mid n$ etc...  so that $m$ and $n$ are each divisible by arbitrarily many $2$'s, an absurdity...
Or, assume $\frac mn$ is reduced,  then you get a contradiction when they are both divisible by $2$...
Answer: Your entire proof is based on the assumption that m and n are integers. Till this assumption holds true. There is no fallacy in the argument.
But, Lets say m and n can be anything. That is, we don't assume anything for m andn. Then, your statement

m^2 is divisible by 2 => m is divisible by 2

no longer holds true. for eg: m=k*sqrt(2).
 Then m is not divisible by 2. But m^2=2*k^2 is divisible by m.
Hence, by contradiction sqrt(2) is irrartional.
Comment: How do this answer the question?
Comment: Precisely $m$ and $n$ are integers, so that $m/n$ is rational and from there you can prove the contrapositive.

Irrational number $\sqrt2$ proof


Updating an image that is re-uploaded periodically

Question: I have a webcam script that sends a JPG via FTP to my webserver every 10 seconds (overwriting the original).
How can I get jQuery to refresh that image? I tried:
window.onload = function() {
            $('body').prepend('');
            setInterval(runAgain, 12500);
        };

        function runAgain() {
            $.ajax({
                url:'ww.jpg',
                cache:false,
                beforeSend:function() {
                    $('#cam').remove();
                },
                success:function() {
                    $('body').prepend('');
                }
            });
        }

Note: I don't want to refresh the page if I can help it.
Answer: A dirty way is appending a timestamp or a random number at the end of the image src, to prevent the caching, like
img src="image.jpg?random=[RANDOM]"
where [RANDOM] is the timestamp or the random number
Comment: +1 It doesn't *look* nice (and it forces an image reload every time, whether it changed or not), but it works.
Comment: Ugly - yes, working - yes. Problems - nope.. :) points and rep for you!
Answer: It looks like you have the problem with the caching - browser already has the image in the cache and doesn't load it again from server. The simplest way is to add the random parameter that will make the browser think that it is the other image:
...
url:'ww.jpg?' + Math.random()
...

It is possible to achieve the same effect with serverside tune-ups, but this way is probably least intrusive and easier to implement.
Comment: ... or you can use timestamp instead of random number: (new Date().getTime())
Comment: Yes, probably it is even better.
Answer: You actually only need to refresh the src. Of course you should use a cache buster to avoid browser caching the image destonation. A solution in this case would be random query string parameter.
$(function() {
    var $img = $('', {
        src:  'ww.jpg'
    }).appendTo(document.body);

    setInterval(function() {
        $img.attr('src', function(_, src) {
            return [src, '?', ~~(Math.random() * 40000)].join('');
        });
    }, 12500);
});

Answer: function updateLogo() {
    var base_src = "http://www.google.com/logos/2011/graham11-hp-start.png";
    var logo = $('#logo');
    var timestamp = new Date().getTime();
    // uncomment the timestamp part if your server supports an extra parameter to prevent caching
    logo.attr('src', base_src);// + '?_ts=' + timestamp);
};

setInterval(updateLogo, 1000);

If your server supports an extra parameter in the image URL you'll prevent caching the image.


Tried to create 2 record set type=TXT in Route53

Question: I'm trying to add a second TXT record to a domain, but I get the following error:

Tried to create resource record set type='TXT but it already exists

Can I add two records at the same domain?
Answer: If you are adding it in the WebUI, then your text box with have multiple entries supported in quotes, one per line.
Example:
"ms=M23445345"
"v=spf1 include:spf.protection.outlook.com -all"

Answer: You would enter all the TXT values at the same time... even the one that already exists.
Example CLI:
route53 --zone example.com -c --type TXT --name example.com --values "text1","text2","text3"

Example WebUI:
"txt=ABC123"
"txt=CDE456"

See here as well: https://superuser.com/questions/573305/unable-to-create-txt-record-using-amazon-route-53


Header e footer no mpdf não funciona por nada

Question: Estou com um problema com o mpdf e realmente preciso de ajuda.
Não consigo colocar o header e footer no relatório por nada, mesmo colocando SetHTMLFooter e o SetHTMLHeader não funciona.
Tentei a versão 7.0, 6.1, 6.0 e 5.7 e nada....
Não sou programador php, esse sistema caiu no meu colo.
Segue o codigo:
$CSS:

$header:

                                RELATO DIÁRIO

Nível de -------------

$footer

                VITEC - VP Tecnologia da Informação

$corpo

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In vel augue euismod erat hendrerit tempus. Nunc vehicula ex nec consequat efficitur. Praesent felis est, laoreet quis bibendum at, dictum sed tortor. Vivamus et magna at nulla egestas tempor. Phasellus at volutpat magna. In pretium sem egestas luctus porta. Etiam sed interdum neque. Duis a enim sit amet diam tempor efficitur at non magna.

.......

codigo de geração de relatorio:
$inicioCorpo= "
";
$fimCorpo="
";
$pdfCompleto = $css.$inicioCorpo.$corpo.$fimCorpo;

$mpdf = new mPDF();
$mpdf->SetHTMLHeader($header, "O");
$mpdf->SetHTMLHeader($header, "E");
$mpdf->SetHTMLFooter($footer, "E");
$mpdf->SetHTMLFooter($footer, "O");
$mpdf->charset_in='windows-1252';
$mpdf->WriteHTML($pdfCompleto);
$mpdf->Output();
exit;

Comment: só o header e o footer que não vão?
Comment: Não duplique a pergunta em outras [1](http://pt.stackoverflow.com/q/146551/91), [2](http://pt.stackoverflow.com/q/146233/91) vc pode editar ela a qualquer hora adicionando novos detalhes.
Comment: isso somete o header e o footer, o resto esta funcionando perfeitamente
Answer: se tiver erro "Warning: Cannot modify header informati on " no functions.php
Deve alterar na linha 66 e 67 no arquivo includes/functions.php
$str = preg_replace_callback('/&#([0-9]+)\;/m', function($m){ return code2utf($m[1],$lo); }, $str);

$str = preg_replace_callback('/&#([0-9]+)\;/m', function($m){ return codeHex2utf($m[1],$lo);}, $str);

Comment: Quando for adicionar código, formate-o selecionando ele e clicando em `{}` em seguida.


How to do integration tests on an mvc controller that calls httpcontext.current

Question: I need to do integration tests on an ASP.Net MVC controller that calls HttpContext.Current in each of it's methods.  I have tried various approaches and done plenty of research already, although I feel like there is something i am missing.  I have gone the routes of:

Asp.Net core:  I had found a hack on stack overflow using asp.net core test host courtesy of Stefan Steiger (How to get HttpContext.Current in ASP.NET Core?).  This is a great solution.  However, upon an attempt at implementation and further reading, it appears that this will only work with an aspnetcore controller and is not backward compatible.  I am aware of a shim however I cannot find any instruction on how to use it.
Spinning up iis express using a batch file and making the calls.  The issue i got with this approach is that i need to be able to debug in the tests.  I tried attaching the visual studio debugger however this was for some reason not working.  I kept getting the message on the breakpoint "The breakpoint will not currently be hit. No symbols have been loaded for this document".
I've also researched how to launch the project with the test controller programmatically but could not find how to launch a visual studio web project programmatically. (looked in to launching it via a process and msbuild)
Currently i am testing using owin self host, however, the HttpContext.Current is null in the controller (obviously).  If there is a way around this, it is the most preferable method.

Any advice on how to get these tests done would be greatly appreciated.
Thanks,
Edit, I am attaching using the following method:
 private static bool AttachToIIS(int tries = 10, int threadsleep = 500)
    {
        System.Threading.Thread.Sleep(1000);
        bool isAttached = false;
        int count = 0;
        while (isAttached == false && count < tries)
        {
            _DTE dte = (_DTE)Marshal.GetActiveObject("VisualStudio.DTE.14.0");
            Processes processes = dte.ActiveWindow.DTE.Debugger.LocalProcesses;
            foreach (EnvDTE.Process process in processes)
            {
                System.Diagnostics.Debug.WriteLine("process: " + process.Name);
                try
                {
                    if (process.Name.Contains("iis"))
                    {
                        process.Attach();
                        isAttached = true;
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
            }
            System.Threading.Thread.Sleep(threadsleep);
            count++;
        }
        return isAttached;
    }

The one oddity is that when i attach to the debugger (I am no COM expert), it attaches the debugger of the visual studio instance that was opened first.
Comment: Update:  I went the route of spinning up iis express and attaching the debugger.  The trick was to run iis on one thread and the request on another thread; the controller is hit and debuggable and the httpcontext.current is not null.  However, this only happens if iis is running previous to the test being ran.  So, when i run it without iis already running, the breakpoint in the controller is not hit, however it is hit when the test is run with iis previously running.  I'm sure this has something to do with processes.
Comment: Update:  I am just spinning up iis express in the background and keeping it running; then calling out to the server in the unit tests.  The one oddity is that when i attach to the debugger (I am no COM expert), it attaches the debugger of the visual studio instance that was opened first.
Answer: Depending on why you use HttpContext.Current, you could modify your code to use the HttpContext property of the Controller class instead.
Then you can create a custom ControllerContext for your tests that can contain an HTTP context as well. Note that MVC is more intelligent than the old ASP.NET because it uses HttpContextBase which you can inherit and even mock a completely custom HTTP context in your tests.
Relevant links:

https://www.danylkoweb.com/Blog/how-to-successfully-mock-httpcontext-BT
ASP/NET MVC: Test Controllers w/Sessions? Mocking?
How to mock the Request on Controller in ASP.Net MVC?
ASP.NET MVC unit test controller with HttpContext
Comment: Thanks, we ended up just altering the controller endpoint, using an ioc container to inject a 'shim' implementation of an interface that returns the  test version of an IHttpContextManager (which returns an HttpContext) when testing, and the actual Current HttpContext when run.  Thanks again!!!


Correr script em maquinas XP

Question: Tenho um script a correr correctamente em maquinas 7, mas em XP não corre.
Se correr localmente, faz o que se pretende, mas via GPO não.
O script verifica a OU do computador, verifica um ficheiro .csv e coloca icons respectivos no desktop do utilizador.
Com gpresult, diz que corre.
Na consola das políticas dá um erro:

An unknown error occurred while data was gathered for this extension.
  Details: Not found

Script:
$links = Import-Csv -Path \\Share$\links.csv

function GetPCOU{
   $SysInfo = New-Object -ComObject "ADSystemInfo"
   $Computer = [ADSI]("LDAP://{0}" -f $SysInfo.GetType().InvokeMember("ComputerName", [System.Reflection.BindingFlags]::GetProperty, $null, $SysInfo, $null))
   return ([ADSI]$Computer.Parent).OU
}

for($i=0; $i-le $links.length-1; $i++){

    if ($links[$i].ou -eq (GetPCOU)) {
        $shell = New-Object -ComObject WScript.Shell
        $desktop = [System.Environment]::GetFolderPath('Desktop')

        $shortcut = $shell.CreateShortcut("$desktop\app1.url")
        $shortcut.TargetPath = $links[$i].xx
        $shortcut.Save()

        $shortcut = $shell.CreateShortcut("$desktop\app2.url")
        $shortcut.TargetPath = $links[$i].xy
        $shortcut.Save()
    }
}

Links file:
Ou, app1, app2, appz
OU1, http://xpto.com, http://xxx.xx, http://hhhh.dd
OU2, xxxx, yyyy, zzzz,

Pergunta no SOen
Answer: Olá,
Sei que vc já tem o script pronto.
Mas, já pensou em utilizar as Group Policy Preferences.
vc consegue fazer tudo isso por lá.
https://technet.microsoft.com/en-us/library/cc731892(v=ws.10).aspx
http://blogs.technet.com/b/grouppolicy/archive/2008/03/04/gp-policy-vs-preference-vs-gp-preferences.aspx
Adriano.

Correr script em maquinas XP


Fast and efficient way to convert character matrix to numeric data frame?

Question: The original data is
df1 = structure(c(3, 5, 0, 0, 5, 8, 6, 8, 0, 0), .Dim = c(5L, 2L))

The following command gives me a matrix of characters, and I need to convert it to a data frame of numerics.
install.packages("rcdd")
library("rcdd")
foo = makeV(points = d2q(df1))[,-c(1,2)]

What would be the fastest way, since it is used in a loop and meant to be repeated many times?
Comment: @akrun I think `"mode<-"(foo, "double")` should be faster.
Comment: a function from the rcdd package. Added, thanks.
Answer: I don't think it is the best method, but i publish it, at least it while serve as reference to beat:
library("rcdd")
library(microbenchmark)

df1 = structure(c(3, 5, 0, 0, 5, 8, 6, 8, 0, 0), .Dim = c(5L, 2L))
foo = makeV(points = d2q(df1))[,-c(1,2)]

microbenchmark(
  data.frame(cbind(as.numeric(foo)[1:nrow(foo)],
                   as.numeric(foo)[-c(1:nrow(foo))]))
)

Mean time is 105.77 microseconds


vuejs display number of times a v-if condition is met

Question: I am working with VueJS. Given a markup which looks like this:
<template v-for="item in some_counter">

   [[ item.some_param2 ]]

</template>

I would like to display the number of times the condition is met. So, if the condition is met 3 times, I would like to see the
 markup like so:

1, some_value1

2, some_value2

3, some_value3

where 1,2,3 are the times the condition is met.
How do I go about achieving this?
Comment: Possible solution using CSS only https://stackoverflow.com/questions/37830238/is-there-any-way-to-insert-an-elements-index-child-number-as-text-within-the
Answer: You can implement this by watching a property:
On your Vue instance:
export default Vue.extend({
  data { occurrences: 0 },
  computed: { myProp: function() { return this.item.some_param1 !== 'None' } },
  watch: {
    myProp: function (val, oldVal) {
      if (val && !oldVal) {
        // myProp has changed from true to false
        this.occurrences++
      }
    }
  }
})

Then if you want to display a
 for each occurrence, you can do it with a v-for:

  This is the {{ index }}th time the condition has become true.

Answer: I guess you should to filter your data:

new Vue({
  el: '#app',
  data: {
    items: [
      { some_param1: 'foo1', some_param2: 'bar1' },
      { some_param1: 'None', some_param2: 'bar2' },
      { some_param1: 'foo3', some_param2: 'bar3' },
    ],
    filteredItems: []
  },
  mounted () {
    this.filteredItems = this.items.filter(item => item.some_param1 !== 'None')
  }
})
p {
 margin: 0;
}

   {{ index + 1 }}, {{ item.some_param2 }}


Initial Value Problem: Integration Clarification

Question: I wanted to clarify an integration procedure. It relates to Example 7, found here:
https://www.saylor.org/site/wp-content/uploads/2012/09/MA102-5.5.4-Equations-and-Initial-Value-Problems.pdf
When I integrate the acceleration function:
a = -4sin2t
I get:
v = 4cos2t^2 / 2 + C
Can someone help clarify why the link shows:
v = 4cos2t / 2 + C?
Answer: you have to solve the integral $$-4\int \sin(2t)dt$$ Setting $$z=2t$$ and we get $$dt=\frac{1}{2}dz$$ and our integral will be $$-2\int \sin(z)dz=-2\cdot (-1)\cos(z)+C$$
Comment: Why didn´t you use variable $z$ in the last line ?
Comment: it was only a typo of mine thank you for the hint!
Comment: Thank you for this... I see now where I was going wrong :)


How to link the file icon to the file and to hide the filename?

Question: I have uploaded files to be displayed in a table together with some other informations (title, tags etc). One row of this table the filename which links to the downloadable file. Next to the filename a file icon is displayed be daefault, which isn't linked.
That's how it looks now:

I want the filename to be hidden and the file icon linked to the downloadable file.
What functions would I have to override to make that happen? Or what other way may exist?
Comment: I haven't got anything handy to test on, but for a quick fix you might try hiding the text with CSS, e.g. `#table-id .column-class a { display: inline-block; text-indent: -9999em; }`. The text will still be read by screen readers which would probably be beneficial
Answer: The problem with generic file display is that icon is not linkable, therefor a CSS solution is useless.
So in order to make the icon linkable you need to create another file display formate or alter theme_file_link
My solution is to add additional display formate, code as follow:
/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
    'mymodule_link_icon' => array(
      'label' => t('Linkable icon'),
      'field types' => array('file'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'mymodule_link_icon':

      foreach ($items as $delta => $item) {

        $file = (object) $item;

        $url = file_create_url($file->uri);

        $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');

        $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

        $options['attributes']['title'] = check_plain($file->filename);

        $options['html'] = TRUE;

        $link_icon = '' . l($icon, $url, $options) . '';

        $element[$delta] = $element[$delta] = array('#markup' => $link_icon);
      }

      break;
  }

  return $element;
}

After you implement the above code in a module and enable it, make sure to change field formatter option in your view to Linkable icon
Comment: Ah I see, that would be the clean solution: adding another field formatter which would be availabe as an option globally.
Comment: @koivo Yes exactly
Comment: Your idea is good but this module isn't useful for me.  When I enabled the module the code was printed in all pages of my website and an error was registered when I tried to edit my view.
Comment: @cabita can you create a new question for your issue and I'll try to answer it, just make sure to point it out to me, when you post your question.
Answer: Finally with a lots of help, I created a views-view-field--nameofmyview--nameofmycontenttypefield.tpl.php inside the sites/all/themes/mytheme/templates folder.
First I clicked on that link inside that view:

There a lot of templates are suggested referring to different fields of that view. I had to choose and create one template as suggested from field content: file (id: nameofmycontenttype_field).
Every suggested template has another range, where to take effect. Clicking on field content: file (id: nameofmycontenttype_field) also shows you the default code you have to add to that template file.
As said in the beginning, I created views-view-field--nameofmyview--nameofmycontenttypefield.tpl.php and after some dpm($rows) and finding out which variables, obects and arrays I need I had to add the following code inside that template file:
<?php
if (!empty($row->field_nameofmycontenttype_field["0"]["raw"]["fid"])) {

  $file = file_load($row->field_nameofmycontenttype_field["0"]["raw"]["fid"]);
  $icon = theme("file_icon", array("file"=>$file));
  $url = file_create_url($file->uri);

  $output = l($icon, $url, array("html"=>true));

  print $output;
}
?>

...and that works fine for me. Clickable icons linking to the original file. Only visible in the frontend though, not in the backend preview.
That one helped me a lot, too: http://drupal.org/node/600798 (but it's for D6).
Answer: I tried a little trick to solve this. Cause I had the same problem.

I override theme_file_link() and place the icon inside the .
To hide the file name, I use CSS, and hide the text-link.
 function ufdesign_file_link($variables)
 {
  $file = $variables['file'];
   $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' =>            $icon_directory));
  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
  'attributes' => array(
  'type' => $file->filemime . '; length=' . $file->filesize,
  ),
 );

  // Use the description as the link text if available.
 if (empty($file->description)) {
   $link_text = $file->filename;
  }
  else {
   $link_text = $file->description;
   $options['attributes']['title'] = check_plain($file->filename);
   }
    return '' . $icon . ' ' .    l($link_text,    $url, $options) . ' ';
  }

//And the CSS
.brochurelink {
 float: left;
 padding: 0.5em;
 text-align: left;
 width: 176px;
 white-space: nowrap;
 overflow: hidden;
 text-overflow: ellipsis;
 max-width: 11px;
}

Answer: Edit file  file.module in path /modules/file
Returns HTML for an image with an appropriate icon for the given file.

@param $variables
An associative array containing:
  -file: A file object for which to make an icon.

icon_directory: (optional) A path to a directory of icons to be used for files. Defaults to the value of the "file_icon_directory" variable.

alt: (optional) The alternative text to represent the icon in text-based browsers. Defaults to an empty string.

@ingroup themeable

function theme_file_icon($variables) {
  $file = $variables['file'];
  $alt = $variables['alt'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);
  $url = file_create_url($file->uri); /*Thêm đường dẫn file */
  return ''; /* Thêm link vào icon */
}

Then using css to hide the filename.
Thanks Mahyar Farshi for share.


What are the dimensions, angles of a Gibson Les Paul standard pots cavity?

Question: I am working on building a prewired set of pots and want to mount them on a piece of plastic that can drop into the cavity of a standard les paul. I have been looking for the dimensions and found this image:

But the image is too blurry to make out what the measurements say. If someone knows or can provide the distances between each shaft hole, and the diameter of the round bored out cavity one of the four pots get installed in, I can figure out the necessary angles from there.
Comment: Why don't you enlarge the images until they're life sized? Might need to do some paper folding, but It'd get there.
Comment: I don't have a les paul to compare it to. Otherwise, I would just take the measurements directly.
Answer: Schemtics are tricky, there's 3 things you can do:

This link contains many blue prints of a Gibson Les Paul. There are no measurements on each axis. However, on each PDF there is a scale. Use the scale as a reference point, print out the diagrams and use a ruler to get exact sizing. Easy!
This photo contains scaling for the cavity and POT's however the radius of the POT's must be taken into consideration as seen here.
Try emailing Gibson for shcemtics, there shouldn't be any issues (worth a shot).

When you're making your pre-wired kit, make sure to solder all the cables off the POT's into the centre of cavity so that the cables are not facing the wood of the cavity which will cause placement issues. Common and silly mistake that I learnt the hard way.
Comment: Thank you for these ideas. I ordered a jig and I've been playing with it over my screen in inkscape. So far, I'm fascinated to learn that the shaft hole alignments are not a symmetrical rhombus as I expected. Nor are they even a symmetrical trapezoid. I'm going to compare the jig I have with the PDFs. Once I have precise measurements, I'll add them here as a comment and accept the answer.
Comment: This has exactly what I needed: https://www.electricherald.com/diagrams/lespaul/Gibson-Les-Paul-1950s.pdf
Comment: Awesome! Glad you made use of it.
Comment: This still doesn't seem to be adding up. Have the measurements changed between a 1950 and modern LP? I have a 22mm wide speed knob. When I draw a circle 22mm wide in inkscape, it's a perfect match. But when I use the 1950 dimensions in inkscape, my jig doesn't line up.  I think I'm doing something wrong, so I'm keeping this accepted as an answer
Comment: Make sure the scale is still accurate after printing the diagrams, if it's not you'll just measure the scale and do some easy algebra for making your own scale. Seriously while you're trying to work all this out it will be worth a shot of emailing Gibson.


A counterexample of Riemann mapping theorem in high dimension

Question: There is an exercise (1.1.16) in Huybrechts: the polidisc $B_{(1,1)}(0)\subset\mathbb C^2$ and the unit disc $D$ in $\mathbb C^2$ can not be biholomorphic.
The hint is to compare the automorphisms of these two sets. The unitary matrices is a subgroup of the group of biholomorphic maps of $D$ which leaves the origin fixed. Clearly, the group of unitary matrices of $\dim 2$ is not abelian and the group of biholomorphic maps of $B_{(1,1)}(0)$ is transitive. If we can show the group of biholomorphic maps of $B_{(1,1)}(0)$ which leave invariant the origin is abelian, then this will complete the proof.
If we set $f_1(z_1,z_2)=(z_2,z_1)$ and $f_2(z_1,z_2)=(e^{i\pi/3}z_1,e^{i2\pi/3}z_2)$, then these are clearly in biholomorphic maps of $B_{(1,1)}(0)$. However, $f_1\circ f_2\neq f_2\circ f_1$.
Please tell me where is the problem. Any hint is helpful. Thx.
Answer: Your observations are correct, there is an error in Huybrechts' book. A slightly simpler counterexample is $f_1(z_1, z_2) = (z_2, z_1)$ and $f_2(z_1, z_2) = (-z_1, z_2)$. Maybe he means that the group of biholomorphisms of the form $(f_1(z_1), f_2(z_2))$ is abelian, but then I don't see how that helps with the proof.
Comment: the group of biholomorphims of $U$ and of $V$ are isomorphic if you have a biholomorphism  $U \to V$
Comment: I am aware of that, but how is that relevant here? The exercise in Huybrechts asks the reader to show the group of biholomorphisms of the polydisc leaving the origin invariant is an abelian group. As the OP demonstrates, it is not an abelian group. I am merely confirming that the OP is correct, and Huybrechts is mistaken.
Comment: I thought you said "if it was abelian it wouldn't help anyway". And there is a good chance to use the $U \simeq V$ property for showing there is no biholomorphism $D \to B_{1,1}$
Comment: If the group of all biholomorphisms leaving the origin invariant was abelian, then there would be a contradiction, but if the subgroup I mentioned was abelian, there would be no contradiction.
Comment: Thanks for your reply. I am just guessing that the identity component of the group is abelian.


PHP tab - form validation

Question: i use the code to split a form in to parts in different tabs...
   <?php
session_start();
require_once('./server_validation/lib.php');?>
<!doctype html>

  <meta charset="utf-8">
  <title>jQuery UI Tabs - Default functionality</title>

<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

 <form name="my_form" id="my_form" method="post" action="d1.php" enctype='multipart/form-data'>

Nunc tincidunt

Proin dolor

Aenean lacinia

 <input type="text" name="textfield" id="textfield" />

   <input type="text" name="name" id="name" />

  <input name="" type="submit" value="submit" />

 </form>

tabs are working fine ad i can pass the data...
tabs from source
http://jqueryui.com/tabs/
But the problem is while validating the fields...
This is the working executed php file code..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <link rel="stylesheet" href="css/style.css" type="text/css">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<form name="my_form" id="my_form" method="post" action="reg.php" enctype='multipart/form-data'>

  <input type="text" name="name" id="name" />

  <input type="text" name="textfield" id="textfield" />
  <input name='Submit' type='submit' value='Submit' />

</form>

validation source:
http://anvweb.com/blog/server-side-form-validation-with-jquery-plugin-and-php/
Validation works fine in normal forms without tab... but not working in tabs.. wast is the problem??? thanks in advance...
Comment: can you do a fiddle please
Comment:  what does this return
Comment: It returns the validation rules which is done by another js script.. it works in normal forms,,, but nor working in tab formatted forms...
Comment: according to jquery validation u need to have in each input field i guess
Comment: can you paste the working code too i.e without tabs ??
Comment: http://jsfiddle.net/ve6KS/ check this and tell me the issue
Answer: fiddle:
http://jsfiddle.net/ve6KS/3/
Html:
<form name="my_form" id="my_form" method="post" action="d1.php" enctype='multipart/form-data'>

Nunc tincidunt

Proin dolor

Aenean lacinia

 <input type="text" name="textfield" id="textfield" />

            <input type="text" name="name" id="name" />

            <input type="text" name="dd_number" id="dd_number" />

        <input name="" type="submit" value="submit" />

</form>

jquery:
$(function() {
    $("#tabs").tabs();
    $('#my_form').validate({
        ignore: [],
        rules: {
            "name": {"required": true, "minlength": 2, "maxlength": 30},
            "dd_number": {"required": true, "maxlength": 20},
            "textfield": {"required": true, "minlength": 2, "maxlength": 30}
        }
    });
});

Comment: thanks a lot... working fine... But when i use the same code i can't get the result in my page.. same problem exists...
Answer: Change the ignore settings in your validate call to a selector you don't use. by default ignore has ":hidden", and that's the reason why the components in hidden tabs don't get validated (i.e. they will pass, whatever their value is). by changing the ignore selector to a selector you will never use (like, e.g. ".jksfdhskhfbskeyh"), your fields will be validated as usual.

PHP tab - form validation


Neural Nework and mathematical programming

Question: I am solving a scheduling problem where staff members cannot have overtime. For this problem, I have an integer programming model and solve it using the CPLEX solver. A simplified version of this model looks like the below:
$$\begin{align*}
\min Z &= X C^\mathsf T\\
XB^\mathsf T &\geq b\\
X &\in Z_{\geq0}\end{align*}
$$
Given the complexity of the problem, I would like to approximate the overtime component of the problem for each given solution $X$ (e.g., the number of scheduled patients). For this, I have built a simulation model, run it for several different potential values of $X$ (input values) and calculated the total overtime (output values). Now, I need a way to build a LINEAR approximation equation in $X$ and include it in the above optimization model. One way is to use regression analysis and fit an algebraic model to predict the overtime.
However, I would like to know whether I could use a neural network to derive a linear algebraic equation in $X$ and predict the overtime for different values of $X$? I have found this article, but it seems that the resulting equations are not linear due to the presence of activation functions. Note that I do not want to use the neural network to solve the problem. I just want to use the neural network to derive a linear algebraic equation in $X$ and include it as a constraint set in the above model.
Answer: You are right, the activation functions prevent the neural network (NN) from being a linear function, unless you only use linear activation functions, but then it would be again just a linear model. It's this nonlinearity in the activation functions which makes them perform so well in some situations.
If you want to obtain a linear model, you should fit a linear model. Even if you would find a way to use a NN and somehow apply some constraints that makes it learn a linear model, this wouldn't be better, and likely worse, than fitting a linear model.
Answer: We can use the ReLU activation function and derive a linear equation from a neural network. Further information is presented in this paper (doi: 10.1007/s10601-018-9285-6)
Comment: I don't know what you mean by "derive a linear equation from a neural network", but a ReLU neural network doesn't give you a linear map and the paper you refer to is also not claiming that. You get a piecewise linear map.
Comment: When I asked for a linear equation, I was referring to equations that could be incorporated into linear programming. Please see pages 298 and 299 in the paper.


Columns names from entity using LINQ

Question: I was able to get the columns names by using this:
var props = typeof(FMCSA_NPR).GetProperties();

But it is also giving me the names of other tables which have a foreign relation with the specified table.
Is there a way by which I can only get the column names? What do we call column names when referring table as entity in Entity Model?
Comment: Why do you care which properties belong to the entity's table?
Comment: I only need to show table column names not the related foreign tables.
Comment: @ItiTyagi what if your entity has Complex Type, which is stored in same database table? E.g. `Address` property, which is stored into `Address_City` and `Address_Zip` columns?
Comment: I dont get what are complex types, all I know is I need to show only column names, and like address, I have split address into multiple fields.
Comment: @ItiTyagi See [Complex Types](http://msdn.microsoft.com/en-us/library/vstudio/bb738472(v=vs.100).aspx). Also it's not possible to know whether property is mapped to database or not, if you are not using attributes for mapping
Answer: You can list the non-navigation properties of entities by accessing the conceptual model (CSpace):
var oc = ((IObjectContextAdapter)db).ObjectContext;
var cs = oc.MetadataWorkspace.GetEntityContainer(oc.DefaultContainerName,
                                                 DataSpace.CSpace);

foreach (var entitySet in cs.EntitySets)
{
    var props = string.Join(",", entitySet.ElementType.Properties);
    Trace.WriteLine(string.Format("{0}: {1}", entitySet.Name, props));
}

(Where db is your DbContext object).

Columns names from entity using LINQ


Configuring resiliency settings Entity Framework 6.02

Question: I'm trying to configure resiliency settings for EF6.02. I have an application which in one point of execution writes a log entry to database. The application is not depending on the SQL-server so if the server does not respond, I want the application to abandon the INSERT query (through SaveChanges of the DbContext) and continue execution immediately.
Using default settings, the debug log outputs ten

"A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll"

After the ten tries, it throws an exception and my code continues. But I want just one try and for example 2 s command timeout. According to documentation on MSDN, default resiliency method for SQL server is:

DefaultSqlExecutionStrategy: this is an internal execution strategy that is used by default. This strategy does not retry at all, however, it will wrap any exceptions that could be transient to inform users that they might want to enable connection resiliency.

As the documentation mentions, this strategy does not retry at all. But still I have ten retries. I have tried to create a class which inherits DbConfiguration but I have not found any documentation on how to change this.
Can anyone help me reduce the number of retries?
UPDATE: Below is code based on suggestions
using System;
using System.Data.Entity;
using System.Data.Entity.SqlServer;
using System.Data.Entity.Infrastructure;
using System.Runtime.Remoting.Messaging;

namespace MyDbLayer
{
    public class MyConfiguration : DbConfiguration
    {
        public MyConfiguration ()
        {

          this.SetExecutionStrategy("System.Data.SqlClient", () => SuspendExecutionStrategy
          ? (IDbExecutionStrategy)new DefaultExecutionStrategy()
          : new SqlAzureExecutionStrategy());
        }

        public static bool SuspendExecutionStrategy
        {
            get
            {
                return (bool?)CallContext.LogicalGetData("SuspendExecutionStrategy") ?? false;
            }
            set
            {
                CallContext.LogicalSetData("SuspendExecutionStrategy", value);
            }
        }
    }
}

And code writing to SQL
try
    {
        using (MyEntities context = new MyEntities ())
        {
            Log logEntry = new Log();
            logEntry.TS = DateTime.Now;

            MyConfiguration.SuspendExecutionStrategy = true;
            context.Log.Add(logEntry);
            context.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        logger.Warn("Connection error with database server.", ex);
    }
    finally
    {
        //Enable retries again...
        MyConfiguration.SuspendExecutionStrategy = false;
    }

Answer: Did you try execution strategy suspension?
Your own DB configuration would be like this one:
public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        this.SetExecutionStrategy("System.Data.SqlClient", () => SuspendExecutionStrategy
          ? (IDbExecutionStrategy)new DefaultExecutionStrategy()
          : new SqlAzureExecutionStrategy());
    }

    public static bool SuspendExecutionStrategy
    {
        get
        {
            return (bool?)CallContext.LogicalGetData("SuspendExecutionStrategy") ?? false;
        }
        set
        {
            CallContext.LogicalSetData("SuspendExecutionStrategy", value);
        }
    }
}

then you may define non-retriable command like this:
public static void ExecWithoutRetry(System.Action action)
{
    var restoreExecutionStrategyState = EbgDbConfiguration.SuspendExecutionStrategy;
    try
    {
        MyConfiguration.SuspendExecutionStrategy = true;
        action();
    }
    catch (Exception)
    {
        // ignore any exception if we want to
    }
    finally
    {
        MyConfiguration.SuspendExecutionStrategy = restoreExecutionStrategyState;
    }
}

and finally your regular DB code with retriable and non-retriable commands may look like this:
using (var db = new MyContext())
{
    ExecWithoutRetry(() => db.WriteEvent("My event without retries"));
    db.DoAnyOperationWithRetryStrategy();
}

Comment: Thanks for your help. Is all this code needed to decrease the number of connection retries in Entity Framework 6?? (!)
Comment: @ElToro, maybe I misunderstood your question. If you want to disable retries for all SQL commands then just change `MyConfiguration` constructor like this: `this.SetExecutionStrategy("System.Data.SqlClient", () => new DefaultExecutionStrategy()`. My solution disables retries only for a specific part of you code writing events.
Comment: No you were right from the beginning. I was just stunned over how complicated (even though your beautiful code). I though an easier way would be possible. For example: "context.Connection.NumberOfExecutionRetries = 0". But many thanks!
Comment: I've wrapped non-retriable command with `ExecWithoutRetry()` method for clearer logic flow. I'm doing like this myself and unfortunately I was unable to find another shorter way of combining retriable and non-retriable commands.
Comment: Strange, I just tried your original code and still multiple retries are executed...
Comment: I can see using the debugger that the constructor is called upon start and the property SuspendExecutionStrategy is called when I change the property but still it retries 10 times...
Comment: @ElToro, I would like to see your actual code in order to be able to help you.
Comment: Please see my updated post. The DbConfiguration is in the same assembly as the Entity Data Model. I´m not using Code-First.
Comment: @ElToro, I suppose that something is wrong with your `Log` entity (maybe some required field is not initialized?). I've checked exactly your code but could not reproduce your issue. What message outputs your `logger.Warn("Connection error with database server.", ex)`?
Comment: when i start the server eveything works as expected so it´s nothing with the entity. The error is the regular "no server in the other end" exception (I´m not at the office right now sorry).
Comment: @ElToro, I tried stopping SQL Server and DB but only 1 connection try occured in both cases (even when retries are ON). Also you might notice already that even with retries policy ON there is only a narrow list of errors which cause retries: `This execution strategy will retry the operation on TimeoutException and SqlException if the Errors contains any of the following error numbers: 40613, 40501, 40197, 10929, 10928, 10060, 10054, 10053, 233, 64 and 20`. So probably ten events in your log are written outside of DB operation.
Comment: I will look at this when I get back to the office. The events in are not in my log, they are an in the Visual Studio debug log. So I do not receive them to my application but the SaveChanges() does not return until those ten retries have been performed..
Comment: I have tested this again. According to debug output I see 11

"A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll"

After the 11 retries, I receive one exception in my application:

{System.Data.SqlClient.SqlException (0x80131904). bla bla bla (Error 40) at "System.Data.Entity.Core.EntityClient.EntityConnection.Open()"

So I receive only one exception, but since my connection timeout is set to 1 second, I have to wait 11 seconds for that exception...
Comment: I also tried this:

DefaultExecutionStrategy strategy = new DefaultExecutionStrategy();
strategy.Execute(() => context.SaveChanges());

But it also retries 10 times which makes it take > 10 seconds before the exception is thrown.

I fear that this has nothing to do with Resiliency settings but with something with the System.Data.SqlClient...
Comment: @ElToro, I see that `EntityConnection.Open()` implementation also uses execution strategy, so you have to call `MyConfiguration.SuspendExecutionStrategy = true` before `new MyEntities()`. If it does not work then you may try also `new DefaultExecutionStrategy().Execute(() => {context = new MyEntities();})` or even open connection explicitly before calling `context.SaveChanges()`
Comment: Thanks for all your help, how can I "repay" you without marking your solution as the answer? Your solution was actually the solution to my question but not the solution to my problem :-)
Comment: I could not because my account is new and I have no reputation. I marked your solution as answer instead...
Comment: @ElToro, thank you for such a generous reward! Sorry that my answer was not what is finnaly helped you to solve the problem!
Answer: I found it. I just needed to add "Connection Timeout=X" where X is seconds to the connection string and everything worked without needing to modify ExecutionStrategies etc.
Adding this before executing query solved it
contextInstance.Database.Connection.ConnectionString = context.Database.Connection.ConnectionString + ";Connection Timeout=2;";

Comment: You shouldn't append to the connection string in code. Change the connection string itself instead. Your code goes against the whole concept of dynamic configuration and makes configuring your app non-intuitive.
Comment: Since I´m using different timeouts for different queries, I can´t see how that can be performed my changing the connection string in the config file.


How to add FormsAuthentication cookie to HttpClient HttpRequestMessage

Question: I am trying to authenticate inside integration test by calling FormsAuthentication.SetAuthCookie("someUser", false);
After that I do need to call WebAPI and not receive unauthorized exception because I have authorized attribute applied.
I am using this code to create auth cookie :
var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
    var ticket = FormsAuthentication.Decrypt(cookie.Value);

    var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
        ticket.IsPersistent, userData.ToJson(), ticket.CookiePath);
    var encTicket = FormsAuthentication.Encrypt(newTicket);

    /// Use existing cookie. Could create new one but would have to copy settings over...
    cookie.Value = encTicket;

Now I want to add this cookie to HttpRequestMessage inside new HttpClient and send this with my regular request in integration test.
I don't know how to add that auth cookie to HttpRequestMessage ?
Answer: For manipulating cookies, you need to use WebRequestHandler along with HttpClient. For example,
 var handler = new WebRequestHandler();
 var client = new HttpClient(handler);
 // use handler to configure request such as add cookies to send to server

CookieContainer property will allow to access cookies collection.
On different note, I doubt if creating FormsAuthentication cookie on client will work. A same encryption key would be needed on both client/server. The best approach would be to replay the login request for actual web API - most probably, it would be a POST to login page with user credentials. Observe the same over browser using tool such as Fiddler and construct the same request within your http client.
Answer: Almost 6 years late, but still may be helpful. The solution based on this one:
https://blogs.taiga.nl/martijn/2016/03/10/asp-net-web-api-owin-authenticated-integration-tests-without-authorization-server/
First, while creating Owin TestServer you have to create DataProtector:
    private readonly TestServer _testServer;
    public IDataProtector DataProtector { get; private set; }

    public Server(OwinStartup startupConfig)
    {
        _testServer = TestServer.Create(builder =>
        {
            DataProtector = builder.CreateDataProtector(
                typeof(CookieAuthenticationMiddleware).FullName, DefaultAuthenticationTypes.ApplicationCookie, "v1");

            startupConfig.Configuration(builder);
        });
    }

Then generate cookie like this (use DataProtector created in previous step):
    public string GeterateCookie()
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "your-role"),
            new Claim(ClaimTypes.UserData, "user-data"),
            new Claim(ClaimTypes.Name, "your-name")
        };

        var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

        var tdf = new TicketDataFormat(DataProtector);
        var ticket = new AuthenticationTicket(identity, new AuthenticationProperties {ExpiresUtc = DateTime.UtcNow.AddHours(1)});

        var protectedCookieValue = tdf.Protect(ticket);

        var cookie = new CookieHeaderValue("yourCookie", protectedCookieValue)
        {
            Path = "/",
            HttpOnly = true
        };

        return cookie.ToString();
    }

Make sure to set required claims, initialize ClaimsIdentity according to settings provided to UseCookieAuthentication method, and setting correct CookieName.
The last step is to add CookieHeader to your request:
    public Task<HttpResponseMessage> RequestAsync(HttpRequestMessage request)
    {
        request.Headers.Add("cookie", GenerateCookie());
        return _client.SendAsync(request);
    }


Is the location of mmssms.db hidden when using a file manager?

Question: I am trying to find the location of android telephony folder and look for the mmssms.db sqlite database and i can't seem to find anything.
I want to copy that file to my computer so that i can read it using php.Is the location of that file hidden.I have tried looking for it using Es File Explorer and i couldn't find it.
Is it possible to view the location of the sqlite database using a file explorer?.
Answer:
Is it possible to view the location of the sqlite database using a
  file explorer?

I think file manager apps cant read db file, use apps like SQLite Explorer instead.
Comment: @NotModerator I mean something like this : https://play.google.com/store/apps/details?id=com.xuecs.sqlitemanager
Comment: Installing the app that can recognize the sqlite3 and db extensions is one thing,finding the location of mmssms.db is another.
Comment: @NotModerator i remembered i can copy the `db` file, but i dont remember which apps to use @@ I think i pull it from DDMS (Eclipse)


The supplied phased action failed with an exception in Eclipse

Question: I'm trying to build a Gradle project in eclipse and this error is displayed when I import the project I want to work on.
I have tried to create a new project it builds successfully
Error Message
Java and Gradle versions
Comment: Double click the error line; a stack trace is probably going to show. It's not reasonable to expect to be able to debug "There is a problem. Gooooooood luck with it! Tata!", which is what you're asking for now. (I'm relying a little bit on eclipse giving you _something_ more than this nebulous error, usually double clicking gets you there).
Comment: may be https://stackoverflow.com/questions/68321708/could-not-run-phased-build-action-using-connection-to-gradle-distribution
Answer: in the Gradle build file
if(JavaVersion.current() != JavaVersion.VERSION_1_8) throw new GradleException("This project requires Java 8, but it's running on"+JavaVersion.current()) sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8
And this is the description of the error
The supplied phased action failed with an exception. A problem occurred configuring root project 'IntroToUnitTesting'. A problem occurred evaluating root project 'IntroToUnitTesting'. This project requires Java 8, but it's running on 18
Comment: Hello, and welcome to Stack Overflow ! I suggest you edit your question instead of answering your own question with details on said question. Answers are meant to be helpful to people having a similar issue and this might be misleading to other readers.


Installing python34-devel on CentOS does not solve unable to execute 'gcc' error

Question: Running on CentOS Linux release 7.3.1611 (Core)
with - Linux version 3.10.0-514.26.2.el7.x86_64 (email@example.com) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC)
<code> Virtualenv location: /mypath/to/project
    + pipenv install -r requirements.txt
    Requirements file provided! Importing into Pipfile…
    Installing dependencies from Pipfile.lock (767e9d)…
    An error occurred while installing lz4==0.11.1! Will try again.
    Installing initially–failed dependencies…
    Collecting lz4==0.11.1
      Using cached lz4-0.11.1.tar.gz
    Building wheels for collected packages: lz4
      Running setup.py bdist_wheel for lz4: started
      Running setup.py bdist_wheel for lz4: finished with status 'error'
      Complete output from command my/project/path/bin/python3.4m -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-74k3sh5f/lz4/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmp1swmfp_jpip-wheel- --python-tag cp34:
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.linux-x86_64-3.4
      creating build/lib.linux-x86_64-3.4/lz4
      copying lz4/deprecated.py -> build/lib.linux-x86_64-3.4/lz4
      copying lz4/__init__.py -> build/lib.linux-x86_64-3.4/lz4
      copying lz4/lz4version.py -> build/lib.linux-x86_64-3.4/lz4
      copying lz4/version.py -> build/lib.linux-x86_64-3.4/lz4
      creating build/lib.linux-x86_64-3.4/lz4/block
      copying lz4/block/__init__.py -> build/lib.linux-x86_64-3.4/lz4/block
      creating build/lib.linux-x86_64-3.4/lz4/frame
      copying lz4/frame/__init__.py -> build/lib.linux-x86_64-3.4/lz4/frame
      running build_ext
      building 'lz4._version' extension
      creating build/temp.linux-x86_64-3.4
      creating build/temp.linux-x86_64-3.4/lz4
      creating build/temp.linux-x86_64-3.4/lz4libs
      gcc -pthread -Wno-unused-result -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Ilz4libs -Ipy3c -I/usr/include/python3.4m -c lz4/_version.c -o build/temp.linux-x86_64-3.4/lz4/_version.o -O3 -Wall -Wundef
      unable to execute 'gcc': No such file or directory
      error: command 'gcc' failed with exit status 1
</code>
Tried to install - python34-devel package but it didnt help
Comment: Install gcc, the installer is trying to compile stuff
Comment: @ geckos I am using Puppet to install packages and below code solved the error, as it comes as $ yum search gcc
package { 'gcc':
      ensure => 'installed',
    }
Comment: I had never used puppet, so the above comment helps you!?
Answer: I am using Puppet to install packages and below code solved the error, as it comes as
<code>$ yum search gcc package { 'gcc': ensure => 'installed', }
</code>
– vpd


Can i run multiple instances of Android Monitor simultaneously?

Question: I have 2 android devices running 2 different versions of my app.
I want to monitor their memory usage etc. using Android Monitor.
The problem is that Android Monitor allows me to monitor only either one of them at a time.

I know i can run 2 instances of Android Studio and this way i get 2 instances of Android Monitor but i'm looking for a better solution.
So how can i monitor 2 devices simultaneously using the Android Monitor and only one instance of Android Studio?
Or maybe someone could point me to a third party software that can monitor android devices?
Cheers, Robert
Answer:
So how can i monitor 2 devices simultaneously using the Android Monitor and only one instance of Android Studio?

You can't. You can swap between the devices to see both, but there is no way to see both device's logs at the same time with only one AS instance
Comment: I see, that's a shame. How about my second question? :D


How to check for the accuracy of prediction

Question: I am doing a personal project to see how well does FIFA potential player stats predict the actual overall stat after 3 years.

Meaning, if a player has a potential of 85 in 2015, how accurate should I expect it to be to predict the overall player score in 2018. Should I use R2 for this? Maybe MAPE?
I also want to check if the histogram of errors (potential_2015 - overall_2018) has a normal distribution. Do I need to use Chi-squared for this?
If the prediction is overestimating the player, I would like to know by how much. Should I use Standard Deviation on the errors?

If you have a list of key statistical tests, I would appreciate if you could list them so I can research and learn.
Thank you,
Answer:
Here is a list of point forecast accuracy measures. The entire textbook is very much recommended. Also relevant:

MAPE vs R-squared in regression models
What are the shortcomings of the Mean Absolute Percentage Error (MAPE)?
Mean absolute error OR root mean squared error?

There is a number of normality tests, the most common is the Shapiro-Wilks test. In 15 years of forecasting, I have never seen anyone test normality of forecasting errors, but you may have reasons for doing so. Note that normality tests address a question we already know the answer to: since your stats are (presumably) nonnegative, your errors are bounded, but the normal distribution is unbounded, so the errors can't be normally distributed. A test may still be useful in assessing whether they are "too" non-normal. As above, this is assuming you have a reason to be interested in this.
You can simply calculate the error per player, or if you have multiple forecasts and actuals for a player, take the mean error. The standard deviation (of what?) will not be very useful.
Comment: The book at this link goes heavily into the theory of forecasting and the different methods. I haven't read the whole thing but I remember the parts of it I did read being pretty good.  Even though it's econometrically focused, a lot of the material is general. Of course, take a look before you purchase because there's a lot material on the net and Stephen's answer is useful also.  https://www.amazon.com/Economic-Forecasting-Graham-Elliott/dp/0691140138/ref=sr_1_5?keywords=econometric+forecasting&qid=1637309187&sr=8-5
Comment: Thank you @Stephan,

1. After checking your resources and going into the rabbit hole I decided to use MAE or RMSE instead of MAPE, as I don't want to put emphasis on negative errors.

2. My goal to test the normality of errors is because it should  **not** follow a bell curve, as my assumption is that the forecast has a bias to overestimate players potentials. Graphically, the histogram should be skew right (error: actual - potential).
I'll use Shapiro-Wilks, thank you.

3. I found I can use Mean Bias Error.
Comment: Thanks for the feedback, just one comment: whether the errors are normally distributed or have a bias is not a contradiction, they could be both, e.g., normally distributed with a nonzero mean. It looks like you are mainly interested in whether the forecasts have a nonzero bias. A t-test would be appropriate, without worrying about the normality.


Better to Minimize Absolute Error or Sum of Squared Error?

Question: I have an Excel model which predicts the number of customers for a given month. The prediction depends on a churn rate. I have the absolute error (actual vs predicted), along with squared error and sum of square error.
My question is:
Would it better to find a churn rate that minimizes the absolute for each period (year, month) or find a churn rate that minimizes the sum of squared errors? Does the former even make sense to do?
Comment: This depends on your loss function, I think.
Comment: An alternative is to explicitly consider the count nature of your data and use Poisson or Negative Binomial models. This is more important if you care about generating good confidence intervals for things, and is theoretically possible, though perhaps not practical, in Excel.
Answer: If you minimise absolute error, you are implicitly assuming that your errors are Laplacian distributed and if you minimise mean-squared error, you're implicitly assuming they're normally distributed.
Due you have any reason a-priori to believe one of the other? Are your tails long? Pedantically, users are discrete, so are either appropriate ? If the numbers are quite large, continuous isn't a bad approximation but if your numbers are small, you might consider a discrete distribution leading to an entirely different distribution.
A-priori arguments aside, train a model using least squares, and then plot a histogram of your prediction errors $y_{i} - \hat{y}_{i}$. Does this distribution look normal? Train the model using absolute error and plot $y_{i} - \hat{y}_{i}$, does this distribution look Laplacian?
Comment: The conclusions you draw about "implicitly" themselves make the implicit assumption that you are using maximum likelihood.  As @Richard Hardy suggests in a comment to the question, it's often more appropriate to consider the loss function rather than exploring distributional assumptions.
Comment: yes, that's fair. Would your default approach not be to use max-likelihood or max posterior unless you had a good reason to use something else?
Comment: My default is to explore the loss with the client in an effort to gather information relevant to deciding on an appropriate procedure.
Comment: @whuber The choice of a loss function depends on the goal of modelling, the structure of residuals, and enough different considerations that I would have a hard time giving anyone explicit instructions as to how to do that. Even a slight change in modelling goals can imply different loss functions and results. Not a simple topic, then.
Comment: @Carl I believe you might be conceiving of "loss" a little differently than I am.  In decision theory the loss is a primary consideration before any modeling is even done.  It measures the cost of suboptimal decisions.  That's not necessarily the same thing as the "loss" used for fitting models, although the concepts are very close.  The statistician, though, is not free to impose a different loss function on their client solely because "modeling goals" might have changed.
Comment: @whuber "Impose" is a tad presumptuous here. How would you know, for example, that a problem is ill-posed, serendipity perhaps? And which would be the appropriate variance reduction goal for regularization, guesswork perhaps? Next, consider what is more costly, fitting the tail of a function incorrectly or the bulk of it? Or perhaps neither? I wish it were as simple as you are implying, I really do wish so.
Comment: @Carl It sounds like you and I are discussing completely different things.  A statistical decision problem isn't even posed at all until a loss or class of loss functions has been specified.  Depending on the loss, "variance reduction," tail fitting, etc., could be irrelevant.  I'm sorry this might be coming across as simple, because it's anything but simple.
Comment: @whuber Essentially, all models are wrong and our job is finding models that are more useful. Doing that means simultaneously comparing models paired with loss functions that prove to be appropriate to each model and not just comparing loss functions in a vacuum.
Comment: @gazza89 we can use square or absolute error even without precise distributive assumptions.


Bits Required to Store Values

Question: How many bits are required to store three different values?
My guess is 8 times 3 = 24 bits.
I'm confused because I learned in class that a 8-bit byte can only hold a value between 0 and 255. Does this mean to store a value above 255 we need more than 8 bits?
Comment: How did you arrive at your guess?
Comment: "Does this mean to store a value above 255 we need more than 8 bits?" - yes, exactly. But from this observation, you already know that you need much fewer than 24 bits to store 3 values.
Answer: A bit is either 0 or 1. So it can store 2 values.
Two bits can store 2*2 values, 4.
Three bits can store 2*2*2 values, 8.
And so on.
So to store 3 values, you need at least two bits.
You need more than 8 bits to store more than 256 values, yes, because 2^8 is 256.
Answer: TL;DR: two digits.
In any number base system, the number of values that can be held by a single digit is equal to the base number, so for the regular base-10 number system, that would be 10 (0 through 9). To hold higher numbers, you give yourself more digits: this would be the ones place, tens place, hundreds place, etc you learned in school.
Once you start giving yourself more digits, then it's just a matter of combinations: in a two-digit base-10 number, how many combinations are there? 00 through 99, so 100; with three digits, 000 through 999, so 1000.
The name bit is nothing more than the special name given to the digit in base-2 (otherwise known as binary). It can hold exactly two values, 0 and 1. To get more, you'd have to give yourself another digit, e.g., the ones place, the twos place. And even more digits: the fours place, the eights place, etc. Again, it's nothing but combinatory math. Two base-2 digits (or binary digits, or bits) can hold values 00 through 11, so 4; with three bits 00 through 111, so 8; with four bits 00 through 1111, so 16; with eight (a byte) 00000000 through 11111111, so 256.
So, in order to hold three values - e.g., 0 1 and 2 base-10 - you'd need two digits: 00 01 and 10 binary.

Bits Required to Store Values


drupal with more than 100000 nodes, performance increase to vey high

Question: I have a drupal site with more than 100000 nodes and counting.
I want to know, how can I increase the site performance dramatically.
There are certain days when traffic is high and the site becomes really slow.
 The site also uses views heavily and the frontpage is panels based.
With the same resources I have now, what can I do to increase the performance.
Comment: Stack Overflow is for specific questions involving programming (i.e. code). Your question is likely better served on [Pro Webmasters.SE](http://webmasters.stackexchange.com).
Comment: Hi, Mark. thanks for the info, I really did not know about the Pro Webmasters.SE
Answer: Have a read of Drupal caching, speed and performance, that should give you an idea of where to start. From the sound of it, caching would be a good idea.
Answer: I would second fredley's suggestion to read up on Drupal Caching speed and performance on the link he has provided. However a quick way to optimize your site would be to use the boost module. ( http://drupal.org/project/boost ). Boost caches the HTML output of each URL (when accessed). Subsequent access to the same URL, causes the cached HTML to be sent and so PHP scripts don't need to run and consequently, neither is the database accessed. Your Apache server is blindingly fast at serving HTML pages so your server load goes down and responsiveness goes up. Boost is very intelligent e.g. if someone comments on a node it will expire that page and so on.
Please note that Boost only makes sense if your site is for anonymous users. For logged in users you will need to employ other strategies e.g. memcache etc.
Please also make sure simple things in the performance settings of your drupal site like CSS aggregation ("CSS optimization") and Javascript aggreation ("JS optimzation"), default caching options etc are enabled.
There is a lot of information available on performance optimzation so it can be overwhelming at first. If you're a book kind of person then check out https://www.packtpub.com/drupal-6-performance-tips-to-maximize-and-optimize-your-framework/book
Comment: I wish all of my website wasn't behind password protection.  There aren't any anonymous users and this means I cannot use boost.
Answer: To increase performance you really need to do some profiling and find out what it is you should be optimizing. It's easy to optimize all sorts of things, but you need to find out what the problem is on your site.
For high traffic sites, a good cache strategy, is very important.
You can consider using Pressflow, to cut off some of the performance hit there is to Drupal suporting php 4.


Special case of Riesz-Thorin Interpolation Theorem $L^{p_0} \cap L^{p_1} \to L^1$

Question: Let $1 \le p_0,p_1 \le \infty$ and consider a linear map $T : L^{p_0} \cap L^{p_1} \to L^1$ such that there exist constants $M_0, M_1 > 0$ so that
$$(\forall f \in L^{p_0} \cap L^{p_1}) \quad \|Tf\|_{L^1} \le M_0 \|f\|_{L^{p_0}} \text{ and } \|Tf\|_{L^1} \le M_1 \|f\|_{L^{p_1}}.$$
I need to prove that for $t \in \langle 0,1\rangle$ we have
$$(\forall f \in L^{p_0} \cap L^{p_1}) \quad \|Tf\|_{L^1} \le M_0^{1-t}M_1^t \|f\|_{L^{p_t}}$$
where $p_t$ is defined by $\frac1{p_t} = \frac{t}{p_1} + \frac{1-t}{p_0}$.
This is a special case of Riesz-Thorin Interpolation theorem, outlined e.g. here. The proof of this special case is supposed to be simple and is omitted from most proofs. However, I seem to be missing something here.
My attempt:
By multiplying inequalities $\|Tf\|_{L^1}^{1-t} \le M_0^{1-t} \|f\|_{L^{p_0}}^{1-t}$ and $\|Tf\|_{L^1}^t \le M_1^t \|f\|_{L^{p_1}}^t$ we get
$$\|Tf\|_{L^1} \le M_0^{1-t}M_1^t \|f\|_{L^{p_0}}^{1-t}\|f\|_{L^{p_1}}^{t}.$$
Now there is the simple interpolation inequality
$$\|f\|_{L^{p_t}
}\le \|f\|_{L^{p_0}}^{1-t}\|f\|_{L^{p_1}}^{t}$$
but it is in the wrong direction. I'm sure I need to use it somehow.
Comment: My hazy recollection is that you still use the three-lines lemma, but its simpler
Answer: I believe its like this...let me first recall bits of that proof. The inequality $\|Tf\|_{q_\theta} \le  M_0^{1-\theta} M_1^\theta  \|f\|_{p_\theta}$ is equivalent to
$$ \sup_{\substack{\|f\|_{p_\theta}=1\\ \|g\|_{q_\theta'}=1}
    } \int_Y (T f)g \le  M_0^{1-\theta} M_1^\theta  $$
Where the sup is over all functions $f\in L^{p_\theta}(X)$ and $g\in L^{q_\theta}(Y)$.
In the given proof that assumes $q_{0,1}\neq1$ and $p_{0,1}\neq\infty$, this LHS ends up being reduced to a double supremum only over simple functions(which are a dense subclass), at which point its equal to $F(\theta)$, where
$$\frac{1}{p(z)}=\frac{1-z}{p_{0}}+\frac{z}{p_{1}}, \quad \frac{1}{q^{\prime}(z)}=\frac{1-z}{q_{0}^{\prime}}+\frac{z}{q_{1}^{\prime}},\\f_{z}(x)=\sum_{j=1}^{n}\left|a_{j}\right|^{\frac{p_\theta}{p(z)}} \frac{a_{j}}{\left|a_{j}\right|} \chi_{A_{j}}, \quad g_{z}(x)=\sum_{\ell=1}^{m}\left|b_{\ell}\right|^{\frac{q^{\prime}_\theta}{q^{\prime}(z)}} \frac{b_{\ell}}{\left|b_{\ell}\right|} \chi_{B_{\ell}},
\\
F(z)=\int g_{z} T f_{z} = \sum_{j=1}^{n} \sum_{\ell=1}^{m}\left|a_{j}\right|^{\frac{p_\theta}{p(z)}} \frac{a_{j}}{\left|a_{j}\right|}\left|b_{\ell}\right|^{\frac{q^{\prime}_\theta}{q^{\prime}(z)}} \frac{b_{\ell}}{\left|b_{\ell}\right|} \int_{B_{\ell}} T \chi_{A_{j}}$$
Lets also ignore $p_\theta = \infty$ for now (see end of post). If you reflect on what $q'(z)$ is used for, its to interpolate between the $q_0'$ and $q_1'$ norms; but for us, these are all just $\infty$. So we can just replace $q'_\theta/q'(z)$ by $1$, and just use $g$ in place of $g_z$. Another issue is that simple functions with compact support are not dense in $L^\infty$. But now that we don't need to introduce the function $g_z$, we do not need to consider only step functions for $g$, and can allow the sup to range over the entire space $L^\infty$. Therefore: lets consider the following function $F$ instead:
$$ F(z) := \int_Y g Tf_z
=
\sum_{j=1}^{n} \left|a_{j}\right|^{\frac{p_\theta}{p(z)}} \frac{a_{j}}{\left|a_{j}\right|}\int_{Y} g T \chi_{A_{j}}$$
The $p_0=p_1=p_\theta$ ($\leqq \infty$)  endpoint, for any $q_{0,1}$ is recovered by the Lebesgue interpolation you mentioned $\|Tf\|_{q_\theta} \le \|Tf\|^{1-\theta}_{q_0}\|Tf\|_{q_1}^{\theta} \le M_0^{1-\theta} M_1^\theta \|f\|_{\infty}$.
That should cover all cases. The most detail I've ever seen explicitly written about the edge cases is in Tao's blog-notes. He suggests monotone convergence which also works; I basically verified this here.
Comment: It seems ok, thanks.
Comment: Thanks, but are you sure that $$\sup_{\substack{\|f\|_{p_\theta}=1\\ \|g\|_{q_\theta'}=1}
    } \int_Y (T f)g \le 1$$ is sufficient in the case of $p_\theta = \infty$ or $q'_\theta = \infty$? Step functions are not dense in $L^\infty$. I thought that was the reason we had to consider these cases separately.
Comment: @mechanodroid oh, yes that sounds very important. How about the following - the whole point of using step functions is that when you make it depend on $z$, you get an analytic function (that's reasonably bounded). Since we don't need $g$ to vary in $z$, we can just leave $g$ ranging over all functions in $L^{q'_\theta}$? I'll edit the answer to say something like this when I get to a computer
Comment: Also, my apologies, and thank you for the comment, as this is firmly in the land of 'no one has checked my work before' :)
Comment: @mechanodroid I thought for a long time before daring to comment on Tao's post, and I've come to the conclusion that monotone convergence also works, which I've typed out in a linked answer (and so I won't be commenting there). In fact if you reduce to simple functions that aren't compactly supported instead, then I think you recover the density in $L^\infty$  (I guess this is 'halfway between' just allowing all $g\in L^\infty$ and the MCT argument)
Comment: Hi, @CalvinKhor I think that this cannot be applied in $q_\theta' = \infty$ since the function $F$ is not analytic in interior of strip. Can you explain it more?
Comment: @probafds123 it has been nearly 1 year since I wrote this :) so I am rusty. But it looks analytic to me; whats the problem? I note that in this case I gave a second definition of $F$, I take it that you are disagreeing that this is analytic?
Comment: Sorry! It was my mistake. Thank you. @CalvinKhor
Comment: @probafds123 thank you for checking the proof carefully! I have asked many people to look but few were interested


MVC: System.Web.HttpException: A public action method 'Delete' was not found on controller

Question: I have a Html helper method that calls a Delete method on my controller.
public static MvcHtmlString DeleteEmployeeOtherLeave(this HtmlHelper html, string linkText, Leave _leave)
{
    return html.RouteLink(linkText, "Default",
        new { _employeeOtherLeaveId = _leave.LeaveId, action = "Delete" },
        new { onclick = "$.post(this.href); return false;" });
}

On my controller I have;
[AcceptVerbs(HttpVerbs.Delete)]
public ActionResult Delete(int _employeeOtherLeaveId)
{
    EmployeeOtherLeaf.Delete(_employeeOtherLeaveId);

    return RedirectToAction("Payroll");
}

But I get this runtime error message;
    System.Web.HttpException: A public action method 'Delete' was not found on controller

Answer: It's possible that your action isn't being invoked by an HTTP request that is sending the correct "DELETE" verb in this case.  Try updating your AcceptVerbs attribute to take a POST instead.
Answer: You are sending a POST request whereas your controller action expects a DELETE verb. So:
public static MvcHtmlString DeleteEmployeeOtherLeave(this HtmlHelper html, string linkText, Leave _leave)
{
    return html.RouteLink(linkText, "Default",
        new { _employeeOtherLeaveId = _leave.LeaveId, action = "Delete" },
        new { onclick = "$.ajax({url: this.href, type: 'DELETE'}); return false;" });
}

Comment: I have had problems with this solution when testing in IE. I asked on the MVC forum and they said I should post POST instead. See http://forums.asp.net/t/1658625.aspx/1?The+DELETE+Http+works+in+FF+but+not+in+IE. Now I get this error again I am back to square one. Sorry about that.
Answer: or you can also change your verb in your form method attribute to delete either method should work