Distinguishing properties of $\mathbb{Q}$ and $\mathbb{R} \setminus \mathbb{Q}$ that lead to differing cardinalities?

Question: I have what many on here would consider an elementary question, but I would very much appreciate responses that use only elementary ideas, if possible, so that I can understand them.  I would also appreciate detailed rather than brief responses.
By construction, $\mathbb{Q} \subseteq \mathbb{R}$.  The rationals are countably infinite, while the irrationals are uncountably infinite.  This got me thinking about what properties the irrationals have that the rationals do not have that would cause such a huge difference in their cardinalities (although this question isn't specific to their cardinalities -- the rationals have 0 Lebesgue measure and the irrationals have infinite Lebesgue measure).
Both the rationals and the irrationals are dense in $\mathbb{R}$.  So density does not play into cardinality.  But why doesn't it?  There are uncountably many irrationals, and so there are uncountably many intervals $(a,b)$ with irrational endpoints. Since each of these intervals contains a rational number, shouldn't there be uncountably many rationals?  There aren't uncountably many rationals, which means there is at least one rational that is contained in uncountably many of these intervals.  But which one?  Are they all contained in uncountably many of these intervals?  What if we only look at the subcollection of all intervals with irrational endpoints that also have infinitesimally small length (if possible)?  I know I'm rambling now...
I guess my main question is: what properties do the irrationals have that the rationals don't have that lead to the irrationals being uncountable?  Although, I would also like to hear thoughts on my statement above about the density of the rationals.
Comment: With, for instance, digital expansions or continued fraction representations, specifying a real requires an infinite amount of data, while specifying a rational only requires a finite amount. The only difference between rational and irrational is that rationals terminate/repeat.
Comment: @blue That's an _information-theoretic_ distinction (or, arguably, a set-theoretic one); I think the germ of the OP's question here is looking for a _topological_ distinction between $\mathbb{Q}$ and $\mathbb{R}\setminus\mathbb{Q}$, and the 'infinite data' explanations of the irrationals don't really provide that.
Comment: @user46944 no $\sum 10^{n^2}$ is irrational since it doent repeat.
Comment: @user46944 That question can be answered immediately without even thinking: just *create* a nonrepeating sequence that doesn't contain all possible finite strings!
Comment: There's no such thing as 'infinitesimally small length' (in $\mathbb{R}$).  You hit the nose on the head; every rational is in fact contained in uncountably many of these intervals (as might be obvious since for instance, you can just take the intervals $(q-r, q+r): r\in\mathbb{R}^+$ ).  In fact, for any $\epsilon\gt0$, every rational is contained in uncountably many intervals of length $\epsilon$.
Comment: Why can't we talk about infinitesimally small lengths in $\mathbb{R}$?  I have always felt queasy about infinitesimally small numbers, and now I am confused about why they are not applicable in this scenario.
Comment: You can talk about _arbitrarily_ small lengths, but you can't talk about _infinitesimally_ small lengths - there are no such things as infinitesimals in $\mathbb{R}$ (or $\mathbb{Q}$, for that matter).  There are nonstandard theories that do have such things as infinitesimal numbers, but they're not generally regarded as 'the' theory of the reals, for instance.
Comment: I understand the idea of what you are saying.  Irrationals are real numbers with non-repeating, non-terminating decimal expansions, while rational numbers are either repeating or finite decimal expansions.  But I'm not making a rigorous connection as to why this leads there to be *uncountably* many irrationals.  I do understand Cantor's diagonalization argument.
Comment: Also, here is another question that has been bothering me.  If $x$ is an irrational number, does its decimal expansion contain every possible finite string of numbers?  Should I ask a separate question on this?
Comment: @StevenStadnicki I consider it a metrical distinction. The OP is looking for something at the heart of why one is countable why the other isn't. If for some reason they don't find this answer satisfactory, they should say so (and preferably explain why). Of course, how they're different as topological spaces is also a valid question - I am not sure at the moment if it's good for discussing cardinality, though.
Comment: Does .123411223344111222333444... work?
Comment: Yes, that's non-repeating and fails to contain every digit.
Comment: @blue, Thank you for clearing that one up. :)  I think I understand your answer to my original question as well, but I am looking for as many perspectives on the subject as I can get.
Comment: Digits, to whatever base a culture may use, are of at most peripheral interest.
Comment: One could be less artificial and just speak of (equivalence classes of) Cauchy sequences to say the same things, sans the arbitrary choice of base (and choice of using digital representations at all).
Comment: The irrationals can be made into a complete metric space without isolated points, and any complete metric space without isolated points must be uncountable.
Answer: In a metric space one can speak of a sequence of approximations which grow arbitrarily precise in the limit. One can phrase this in terms that do not actually assume there is a limit - namely, through the use of Cauchy sequences. A metric space fails to be complete if one can provide such a sequence of approximations growing arbitrarily precise but fails to converge to something. In a sense, we are specifying something that is not actually there - it is sort of a ghost, it transcends the space. It exists outside, in the completion of that space. One of the ingeniously clever tricks of math was instead of seeking to fully describe something infinite or beyond description, describe how one gets there (even though one never truly gets there). By identifying the destination with the journey, one gains the ability to speak of things like real numbers, limits from analysis, and even more exotic limits that exist in algebra (like, in the category of topological rings, the $p$-adic numbers).
There are different ways of going about "specifying" a real number. In general, any Cauchy sequence (modulo null sequences - those converging to $0$) will do, but kinds of specifications that come with rules are also nice. One can use digital expansions with respect to a chosen base - this is convenient and practical, if artificial. One can use continued fraction expansions (search this on google for more information). One can use Dedekind cuts, as a theoretical tool.
In these sorts of schemes (which are all metrically based - if one wants to use algebra and minimal polynomials to describe elements, or speak of computable/definable reals etc. then things can go a different way), rational numbers require only a finite amount of data to specify, whilst an arbitrary real will in general require an infinite amount of data. (I consider the repetition of digits a finite amount of data.) Since it shows up in all these metrical "specification" schemes, and the reals are defined metrically by such specifications (the reals are the unique archimedean linearly ordered complete field - and completeness refers to these things), I think this answer gets at the heart of why $\Bbb R$ is uncountable while $\Bbb Q$ isn't. To illustrate with binary: choosing a finite sequence of flips of a coin essentially encodes a natural number in binary, of which there are countably many, but choosing an infinite sequence of flips has a sample space of $2^{\aleph_0}$ which is $>\aleph_0$ by Cantor (and this theorem is not just auxillary to the discussion: to have a fair appreciation for set theory, it needs to be absorbed into one's intuition of what it means to be uncountable).
I think it is better to think of $\Bbb Q$ vs. $\Bbb R$ (the first contained in the second) instead of $\Bbb Q$ vs. $\Bbb R\setminus\Bbb Q$; for purposes of discussing cardinality there is no reason to partition $\Bbb R$ into $\Bbb Q$ and $\Bbb R\setminus\Bbb Q$.
Getting to the points you made: the fact that rationals are dense essentially means that we can use them in our specification of real numbers, but it fails to touch on the fact that it can take an infinite number of them to do that job, involving an infinite number of choices (even after getting rid of redundancies via null sequences), and the number of choices is what ultimately controls the cardinality. Yes, every rational $x$ is contained in uncountably many intervals with irrational endpoints - namely $(x-\epsilon,x+\epsilon)$ for every irrational $\epsilon>0$ - but this doesn't mean there are uncountably many rational numbers. If you try to pinpoint why you might suspect this implication of holding in the first place - a potential correspondence between intervals and points that forces $\Bbb Q$ to be uncountable - you will fail to find any meaningful correspondence. Why we begin with that kind of intuition in the first place I'm not sure, but intuition must be honed in light of facts.
Comment: Then the "nebulousness" of this concept to you is much more fundamental than just reals and rationals, it goes to Cantor itself. Like I said, you need to make it intuitive, or else you'll be stuck in that rut. Another explanation for why you haven't received 20 different perspectives other than lack of attention (you did get 7 upvotes and a star, which is above average), is that there just aren't that many. Perhaps there is another one involving topology that forces $\Bbb Q$ to be countable and $\Bbb R$ uncountable - that doesn't reference completeness, a defining property.
Comment: Given the emphasis in this answer on the reals as the completion of the rationals, I'd be curious to see you elaborate a bit more on the $p$-adic numbers in this context.
Comment: @Semiclassical $\Bbb Q_p$ is also a completion of the rationals, and all of the same language I used still applies, just with a different metric. (One can motivate this metric: often we speak of congruences, and getting residues to higher powers of primes means more is known about the original integer - greater precision. By allowing sequences of approximations of arbitrary precision on this view, we get $\Bbb Z_p=\varprojlim\Bbb Z/p^n\Bbb Z$.)
Comment: I actually meant that it might improve the answer further if you were able to incorporate that fact more explicitly. Right now the reader might be forgiven for thinking that the reals are the only game in town as far as completions of the rationals go.
Comment: I've read your post three times.  I took a set theory course, so I am familiar with describing real numbers as Dedekind cuts.  It seems to me the crux of your argument, which I agree with, is that the irrationals contain an infinite amount of "data", while the rationals do not.  This concept is still nebulous to me.  Also, I am wondering if it's possible to find more than one defining characteristic of $\mathbb{R}$ and $\mathbb{R} \setminus \mathbb{Q}$ that leads to these differences in cardinality.  Thanks for your answer.
Comment: @user46944 Is the fact that the collection of infinite binary strings is uncountable, while the collection of finite strings is countable, nebulous? One can make a visual depiction (this is for $\Bbb Z_2$, but the same holds for $\Bbb R$ with only a few details changed) with trees: put down a node, and two child nodes, each having two more child nodes, and each of those having two child nodes, and so on. An integer is a node, while a $2$-adic integer is literally an infinite chain of nodes. Perhaps you should become familiar with more than just Dedekind cuts for describing real numbers.
Comment: @blue I'm not familiar with $p$-adic numbers, but I do understand why the set of infinite binary strings is uncountable.  It can be proved using Cantor's diagonalization argument.  But this begs the question in my mind:  what properties does the set of infinite binary strings possess that make its cardinality differ from the set of all finite binary strings?  The answer to that question is what is fuzzy to me, especially since we are talking about sets of infinite cardinality, where intuition is thrown out of this 100mph moving truck's window.
Comment: By the way, my quest to receive 20 different perspectives clearly didn't work out since not many people were interested enough to answer this question. :(
Comment: @blue Ok, I'll do my best to make this concept intuitive.  I strongly believe I have an over-exposure to finite sets (and also a handicap of trying to visualize infinite mathematical concepts in the setting of this arguably finite world) that keep me from accepting these ideas and moving on.  I'll eventually be able to rationalize it to myself.  Thanks for all of your input, and if you have anything more to add, I'd love to hear it.
Answer: $\mathbb R\setminus \mathbb Q$ has the property of being the complement of a proper subgroup of an uncountable group.
If $G$ is an uncountable group and $H$ is a subgroup with $H\neq G$, then $G\setminus H$ is uncountable.  If $H$ is uncountable, let $a$ be any element of $G\setminus H$, and then $aH$ is an uncountable subset of $G\setminus H$.  If $H$ is countable, then because $G$ is the union of cosets of $H$ and a countable union of countable sets is countable*, $H$ has uncountably many distinct (and therefore disjoint) cosets contained in $G\setminus H$.
*[assuming choice]
Comment: @user46944: I hope you enjoy doing so, but I do not make claims that this approach is particularly geared toward building intuition.  That would be a bonus.  It is just a perspective I find amusing.
Comment: What is so special about $\mathbb{Q}$ that makes it *dense* in $\mathbb{R}$?  $\mathbb{Q}$ is countable, like $\mathbb{N}$ and $\mathbb{Z}$, but neither of these two are dense in $\mathbb{R}$.  $\mathbb{R} \setminus \mathbb{Q}$ is uncountable, but it shares the same property of density as $\mathbb{Q}$, which indicates that density is independent of cardinality (as unintuitive as that seems...) -- so why is density independent of cardinality, when it seems like it shouldn't be?  This really bothers me.
Comment: To answer your first question, staying somewhat in the spirit of this answer, every subgroup of $\mathbb R$ is either dense or has a smallest positive element.  $\mathbb Q$ does not have a smallest positive element.  On the other hand, the complement of any proper subgroup of $\mathbb R$ is dense.  (If the subgroup itself is dense, just take any coset not equal to the subgroup.  If the subgroup is not dense, it is nowhere dense.) No mention of cardinality is needed to verify the claims in this comment.
Comment: I'll work on proving the claims in your comment.  Hopefully it won't be too hard, and maybe it will give me some intuition about this like it seems to have given you.  Thanks for your input!


Prime ideals lying above a prime number in $\mathbb{Q}(\zeta_n)$

Question: If we assume we have a prime number $p$ such that $p\nmid n$, and $\mathscr{P}$ is a prime ideal lying above $p$ in the field extension $\mathbb{Q}(\zeta_n)$, is it always true that $\mathscr{P}\nmid n$?
Comment: Yes. Those prime ideals are factors of (the ideal generated by) $p$, so they are not factors of $n$.
Answer: Yes. If $\mathscr{P} \mid k$, then $\mathrm{Nm}(\mathscr{P}) \mid \mathrm{Nm}(k)$. Since $\mathrm{Nm}(\mathscr{P})$ is a power of $p$ and $\mathrm{Nm}(k)$ is a power of $k$, so this can only happen if $p \mid k$.


Putting a JSON response into a hidden field and retrieving it into a function

Question: I'm retrieving the number of rows contained by a table in my database with the following function using JSON.
function rowCount()
{
    $.ajax({
        headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        datatype:"json",
        type: "GET",
        url: "/wagafashion/ajax/CmsRowCount.htm",
        success: function(response)
        {
            $("#rows").val(response);
        },
        error: function(e)
        {
            alert('Error: ' + e);
        }
    });
}

In the success handler, the response is arriving as expected. There is no problem on the server side.
The response is just mapped with the long type of Java which represents the number of rows in a database table.
I'm putting this response in a hidden field whose id is rows using $("#rows").val(response); in the success handler.
The above function is invoked when the form is submitted using the following jQuery function.
$(function() {
    $('#dataForm').submit(function() {

        rowCount();  //Invokes the above function that makes a JSON request.
        var rows=$("#rows").val();
        alert("rows = "+rows);

        return false;
    });
});

The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time. It alerts the actual value only when I press the submit button once again (without a page refresh).

Also tried to replace the preceding function with the following.
$(function() {
    $('#dataForm').submit(function() {

        rowCount();  //Invokes the first function that makes a JSON request.

        var form = $(this),
        url = form.attr('action'),
        rows = form.find('input[name="rows"]').val();

        alert("rows = "+rows);

        return false;
    });
});

But it didn't work either. Why does this happen? What is the way of retrieving the correct value of that hidden field into the preceding jQuery function?
Comment: Ajax is **asynchronous**. You are trying to access the data **before** the response was received . Please have a look at http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call-from-a-function.
Answer:
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time.

Ajax calls are asynchonrous. When you call rowCount, you start the call, but then rowCount returns and your code continues. The call doesn't complete until later (which is why ajax accepts a callback).
If you trigger the next step in what you're doing from the callback, you'll have the value. You typically do this by having rowCount accept a callback of its own, like this:
function rowCount(callback)          // <==== Accept the callback
{
    $.ajax({
        headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        datatype:"json",
        type: "GET",
        url: "/wagafashion/ajax/CmsRowCount.htm",
        success: function(response)
        {
            $("#rows").val(response);
            callback();              // <==== Call the callback
        },
        error: function(e)
        {
            alert('Error: ' + e);
            callback();              // <==== Probably want to give it a value telling it things failed
        }
    });
}

Then using it:
$(function() {
    $('#dataForm').submit(function() {
        var form = $(this); // <== Grab this outside the callback

        rowCount(function() {

            var url = form.attr('action'),
                rows = form.find('input[name="rows"]').val();

            alert("rows = "+rows);
        });

        return false;
    });
});

If you want to decide whether to allow the form to be submitted on the basis of the callback, you'll have to always cancel the submission, and then trigger submitting it programmatically from the callback if you want to allow it.


Is there symbolism in Brahms No. 1? How does this, and the "struggle between major and minor," square with his views about absolute music?

Question: I've been learning about the War of the Romantics, and I'm trying to understand Brahms's symphony.
I've long seen what I recognize as literary techniques in Brahms's music. For example, in mvt. IV of his 1st Symphony:

Then you go on a musical journey, with the famous, serene main theme and other bits and bobs, when suddenly, after intense buildup, you arrive at:

That always gives me goosebumps. Far and away my favorite moment in music.
It is hard for me to conceive of this as anything other than some symbolic redemption, transformation, or victory.
Also in the first symphony is the conflict of Major and minor keys. Writes Ted Libbey in NPR's "Guide to Building a Classical CD Collection":

Like Beethoven's Fifth and Ninth, Brahms's First is concerned with the conflict of key, and also like them, it aims to achieve transcendence through the triumph of the major mode over the minor in the final movement.

It sounds to me like meaning is being imputed to the work--which I think is amazing and love.
However, this doesn't make sense to me given his philosophy of absolute music. This kind of interpretation seems almost programmatic in nature. Am I misunderstanding his conservatism? Am I correct in my interpretation of the trombone and (later) trumpet line in the fourth movement?
Answer: I'm not sure I'd call the interpretation you quote "programmatic" exactly.  In fact, this sort of characterization might in fact be sort of the essence of absolute music.
As you likely know if you've been reading about this, Brahms was a friend of Hanslick -- the music critic and sort-of philosopher -- who famously characterized music as "tonally moving forms" or "sonically moving forms" or something like that.  (The original sentence is notoriously difficult to translate in its subtleties: "Der Inhalt der Musik sind tönend bewegte Formen.")
Something inherent in that description is a sense of motion and temporal development.  Music is not a static entity to be studied only on the page for Hanslick.  But music's meaning and effects don't come from extramusical programmatic ideas -- they are inherent in the sounds and language and relationships within music itself.
Brahms had slightly different things to say about music, but he shared something of this view of absolute music as being built on a kind of intrinsic musical logic that taps into a deeper meaning than any "program" or series of Wagnerian Leitmotifs or whatever could express.
Whether Brahms himself would use the evocative term "war" between major and minor, I don't know.  But the first symphony certainly has a dramatic arc to it, created partly by the conflict in keys (among other things).
Absolute music doesn't lack drama.  The temporal nature of music requires drama, in fact.  According to 19th-century German aestheticians, it just might lack extramusical references to create that drama.  As Hanslick writes:

The most important factor in the mental process which accompanies the
  act of listening to music, and which converts it into a source of
  pleasure, is frequently overlooked. We here refer to the intellectual
  satisfaction which the listener derives from continually following and
  anticipating the composer's intentions – now, to see his expectations
  fulfilled, and now, to find himself agreeably mistaken. It is a matter
  of course that this intellectual flux and reflux, this perpetual
  giving and receiving takes place unconsciously, and with the rapidity
  of lightning flashes.

The act of listening is therefore about hearing the give and take, the satisfaction of following a musical pattern to its fulfillment, as well as the surprise when it heads in a different direction.  It is still a drama, perhaps one might even say a type of narrative, just one that takes place among inherently musical ideas (rather than representing other things).
We don't need to fall back on some story about alphorns on a mountaintop heralding the coming of a great hero to characterize what's going on, for example, in the first Brahms passage you linked to.  We could instead talk about the inherent tonal tensions, the role of dissonances and clashing harmonies, and perhaps the ultimate arrival of major to resolve the earlier tensions of the piece.
That latter type of interpretation is close to what folks like Brahms and Hanslick saw as the true aesthetic way to appreciate absolute music.
It's when you start talking about "symbolic redemption, transformation, or victory" that things get a bit more dicey.  In the Hanslickian view of the world, it's probably okay to discuss a "transformation" from minor to major, perhaps even a type of conflict between them and maybe even a metaphorical "victory" of one over the other.  All of this is just seen through the lens of the composer and the sounding music conveying musical patterns that are reinforced, then with expectations denied, then finally with a new path emerging tonally at the conclusion.  But if you dive deeper into the "war" and "victory" metaphors or begin to speak of "redemption," you're imputing human emotions or personifying the music in a way that is not necessarily about the musical patterns exclusively anymore.  It's now a psychological reading, to which Hanslick would retort -- "whose psychology"?  The composer's?  Yours?  Some fictional narrative figure or "hero" of the piece?
I'm not arguing in favor of one side or another, by the way.  But the absolutists never denied an element of a temporal arc within music that can create drama and emotion for listeners.  It's just that they preferred to say all of that came from the logic of the music itself (with its melodic and harmonic twists and turns) rather than depending on some external program.
To use an analogy, consider a painting, say a landscape.  A viewer might appreciate technical subtleties like different types of brushstrokes or the use of color palettes or color relationships, but most viewers are also concerned with how the painting evokes an actual image or scene (and how well it does so).  Now imagine an abstract painting, with no discernible subject or attempt at representation.  At this point, discussion of the aesthetic qualities often becomes solely about technique -- contrasts in color, effects of brushstrokes and the like.  I suppose in art criticism, there are some extreme formalists who would say to forget about the representation in painting as well, and to focus on the technical, even in landscapes.
For those who adhered (and still adhere?) to the absolutist philosophy about music, they would say music should be appreciated in that manner of abstract painting.  Any attempts at "images" or "evocations" of non-musical meaning are poor representations at best.  So we should try to explain music's impact by focusing on the technical -- the contrasts of color, the sweeping brushstrokes, etc.  A contrast or conflict with major and minor as a structural device falls under that category, to my mind.
Comment: _Extramusical narrative_ seem the real distinguishing quality. Absolute music doesn't have that, but it doesn't mean there isn't drama, or linguistic-like structure.


How to overwrite td content with an include file with JS?

Question: I have a menu with names of different htm files like this:

I want when I click in one, the content of a td shows the document that I just clicked, I have a for that list this names, and set the calling to the JS function:
<% for (int i=0; i < fileNames.length; i++) { %>

         <%= fileNames[i] %>

<% } %>

I'm using a Jsp that displays the content of the first document by default:

    <%@ include file ="/docs/document1.htm" %>

I'd like something like this in my JS Function:
function refreshContent(element) {
    var name = element.textContent;
    var tdContaner = document.getElementById("documentContaner");
    tdContaner.innerHTML = '<%@ include file ="/docs/'+ name +'.htm" %>';
}

first question: Is it possible do it this way? or Do I need to refresh the page to show new content?
second question: If it's possible, How can I write an include file inside the TD?
Answer: You cannot use JavaScript to insert server side code into the DOM. Server side code needs to be executed by the appropriate runtime / interpreter on the server before the results are delivered to the browser.
To achieve this type of effect, you would need to write an HTTP endpoint which returns just the content of that cell and then use Ajax (usually via the XMLHttpRequest object) to fetch it, and then use DOM methods to insert the result into the cell.
Answer: You can send AJAX from page to load file

        test

if you have jquery on your page use it

        test

UPD. or preload file & name and show/hide them

        <% for (int i=0; i < fileNames.length; i++) { %>

<%= fileNames[i] %>

<%@ include file ="/docs/document1.htm" %>

    <% } %>

with jquery

        <% for (int i=0; i < fileNames.length; i++) { %>

<%= fileNames[i] %>

<%@ include file ="/docs/document1.htm" %>

    <% } %>


Using characteristic functions to establish convergence

Question:
So I have found the Characteristic function of the variable $X_ \lambda$ to be:
$$\psi_{X_\lambda}(t) = \psi_{b(\lambda)(Y_\lambda-\lambda)}(t)=\mathbf Ee^{itb(\lambda)(Y_\lambda-\lambda)}=\mathbf E^{itY_\lambda b(\lambda)}e^{-it\lambda b(\lambda)}=e^{-it\lambda b(\lambda)} \mathbf Ee^{it Y_\lambda b(\lambda)} = e^{-it\lambda b(\lambda)} \psi_{Y_\lambda}(tb(\lambda))$$
Now as $Y_\lambda$ is a Poisson random variable we get:
$$e^{\lambda(e^{itb(\lambda)}-1)-it \lambda b(\lambda)}$$
And this is where I am stuck at I don't know how to continue to establish convergence of $X_\lambda$ any hints?
Comment: $$e^z-1-z\sim\tfrac12z^2\implies\lambda\cdot(e^{itb(\lambda)}-1)-it \lambda b(\lambda)=\lambda\cdot(e^{itb(\lambda)}-1-it b(\lambda))\sim\lambda\cdot\left(-\tfrac12t^2b^2(\lambda)\right)$$
Comment: Would you mind elaborating on your answer please? Sorry if it takes too much time!
Comment: Would you mind elaborating on the parts of my comment which elude you please?
Comment: I don't understand how you arrived at $e^z-1-z\sim\tfrac12z^2$
Comment: This is the expansion of the exponential at zero, which reads $$e^z=1+z+\tfrac12z^2+o(z^2).$$
Comment: Oh right... Sorry for the confusion I thought that the ~ sign meant something like $Z \sim N(0,1)$. I should be able to work it out from here! Thanks for the fast reply
Answer: Expanding on @Did's comment, we have
$$ \psi_{X_\lambda}(t) = e^{\lambda\left(e^{itb(\lambda)}-1-itb(\lambda)\right)} $$
For sufficiently large $\lambda$, this is approximately equal to
$$ e^{\lambda\left(-\frac12 t^2b^2(\lambda)\right)}.$$
Choosing $b(\lambda) = \lambda^{-\frac12}\sigma$ (where $\sigma>0$), we have
$$\lim_{\lambda\to\infty}\psi_{X_\lambda}(t) = e^{-\frac12\sigma^2t^2}, $$
which implies that $$X_\lambda\stackrel{d}{\longrightarrow}\mathcal N(0,\sigma^2).$$
Comment: I have 2 questions:
1) If I choose $b(\lambda) = \lambda ^ {\frac{-1}{2}}$ Then I would get a standard normal distribution right?
2) I don't understand why for sufficiently large $\lambda$ the $O(1)$ terms disappear
Comment: 1) Correct ($\sigma=\sigma^2=1$).
2) That follows from Taylor's theorem.


IIS and Apache on the same machine?

Question: I have a Windows 2003 Server running IIS (due to an ASP Site needing to be hosted).
I wanted to add some non ASP sites (HTML, PHP and MySQL) so I was thinking I could just run apache on 8080.
What confuses me a bit is if someone hits DomiainA.com, IIS intercepts it and forwards it to DomainA.com:8080 where apache is running. I could do this by putting a server side javascript re-direct in the IIS www-root for the domain.
What else can I do that might be more proper?
Answer: Typically this is solved by redirect rules, where the server tells the client the right location (transparent to the user, but he will see the correct URL). In Apache, redirect rules are very easy to employ, globally in the config or locally using .ht* files.
If it is hard to do with IIS, or IIS does not provide an inexpensive (e.g. performance, latency) solution, perhaps you want to run Apache on port 80 and IIS on 8080.
Otherwise, I would not want to maintain two webservers at once if I don't have to. (Sidenote: Apache is superior, so having a seperate IIS to serve ASP actually does make sense)
Answer: As someone else mentioned, there's no reason you can't run a PHP application under IIS.  Having said that, you can configure IIS to only listen on specific IP addresses (by default is will occupy port 80 on every IP on the computer regardless if you have a site configured to use that IP or not).  You could then run Apache on the IP address(es) that are not bound to IIS and have both side-by-side without any trouble.  I would just run the PHP app within IIS unless there is some compelling reason to use Apache.
Answer: PHP runs under IIS. You're going to need to find a better reason than that to run httpd...
Answer: I also recomend the PHP under IIS option.
Buy if you really need the 2 servers working you can use ISA Server:
http://www.microsoft.com/forefront/edgesecurity/isaserver/en/us/features.aspx?pf=true
It allows you, among other things, to do port forwarding.
Answer: Don't do your redirects with JavaScript, that would be bad design.
If you want to handle this without a convoluted setup, just run PHP through IIS and skip the second server.

IIS and Apache on the same machine?


Number of subgroup $G<\Bbb Z^3$ such that $\Bbb Z^3/G\simeq \Bbb Z/3\Bbb Z\oplus\Bbb Z/3\Bbb Z$

Question:
Compute the number of subgroups $G<\Bbb Z^3$ such that $\Bbb Z^3/G\simeq \Bbb Z/3\Bbb Z\oplus\Bbb Z/3\Bbb Z$.

Possible forms of $G$ are $G = \Bbb Z\oplus 3\Bbb Z\oplus 3\Bbb Z$, $3\Bbb Z\oplus 3\Bbb Z\oplus\Bbb Z$ and $3\Bbb Z\oplus\Bbb Z\oplus 3\Bbb Z$. Is there anything more?
Comment: Since you have accepted an answer, you have presumably solved the problem. How many subgroups $G$ did you find?
Comment: Clearly you also have $3\Bbb Z\oplus\Bbb Z\oplus 3\Bbb Z$.
Comment: @Arthur True but I meant nontrivial form. But I edited anyway.
Comment: For every $G$ you found, and any matrix $A$ from $GL_3(\Bbb Z)$ the subgroup $AG$ satisfies $G/AG\cong G/A$.
Comment: The subgroup $G$ must contain $X := 3Z\oplus 3Z \oplus 3Z$.  So the problem is equivalent to computing the number of subgroups of order $3$ in $Z^3/X$, which is an elementary abelian group of order $27$.
Answer: Let's start with a simpler case. Suppose you were asked to count subgroups $G$ of $\mathbb{Z}\oplus\mathbb{Z}$ such that $(\mathbb{Z}\oplus\mathbb{Z})/G\cong \mathbb{Z}/2\mathbb{Z}$.
Your answer suggests two options: $2\mathbb{Z}\oplus\mathbb{Z}$ and $\mathbb{Z}\oplus\mathbb{2Z}$. But is that all? Instead of looking at quotients of subgroups, let's think of the implied homomorphism $f: \mathbb{Z}\oplus\mathbb{Z} \to \mathbb{Z}/2\mathbb{Z}$.
Such a homomorphism is determined by the images of a generating set, for which we can take $(1,0)$ and $(0,1)$. Between them, those images must generate $\mathbb{Z}/2\mathbb{Z}$, but otherwise we are free to choose them. Once we pick them, we get a kernel $G=\ker(f)$ and the required isomorphism will hold.
Your proposed solution identifies the homomorphisms $f((1,0))=1, f((0,1))=0$ and $f((1,0))=0,f((0,1))=1$. Those two are great, but you have another option: $f((1,0))=f((0,1))=1$. The kernel of this homomorphism is a subgroup $G$ made up of those vectors $(a,b)$ such that $a\equiv b\pmod{2}$. That's another legitimate subgroup which is neither of the groups you suggested.
You can apply this approach to the question on hand. Pick a convenient generating set, determine where its elements must be mapped by a surjective homomorphism, and count the kernels. You'll see more than $3$ possibilities.


Js magic need explanation

Question: I'm trying to solve this magic in js:
var a = 1;
console.log(a++ + ++a);

It returns 4 and I can understand that it's 1+3 but what is the sequence of this?
Comment: If you understand what post-increment and pre-increment operators do, it becomes pretty obvious. You just need to read the docs and the knowledge that code is executed from left to right.
Comment: @Jonasw What does `2 + 2` have to do with that?
Comment: If you see code like this in real life, then it was written by a horrible person.  There are good reasons to use `++a` or `a++` depending on the scenario, but having 5 plus signs in a row for any reason is a bad idea for readability, and is just asking for a typo.
Comment: I do yet it doesn't seem obvious. Can you just describe it like 1)... 2)... 3)... in your answer?
Answer: a++ means return the value before incrementing
++a means returns the value after incrementing
So to break down your example:
var a = 1;
console.log(a++ + ++a);

a is set to 1
a++ returns 1, and then a is incremented to 2 (but we don't do anything with it at this point)
++a increments a and returns 3
Then altogether we have console.log(1 + 3) with the 1 coming from step 1 and the 3 coming from step 3.
Answer:
what is the sequence of this

In pseudo spec language:

Evaluate addition (a++ + ++a)

Let lval be the result of evaluating the left operand (a++)

Get the value of a and assign it to oldValue. (1)
Let newValue be oldValue + 1.
Assign newValue to a. (a == 2)
Return oldValue. (1)

Let rval be the result of evaluating the right operand (++a)

Get the value of a and assign it to  oldValue. (2)
Let newValue be oldValue + 1.
Assign newValue to a. (a == 3)
Return newValue. (3)

Return lval + rval. (1 + 3)

Result: 4
Answer: To go into a bit more detail on what Xufox was saying in the comments section:
++a first increments the value of a and then returns an lvalue referring to a, so if the value of a is used then it will be the incremented value.
a++ first returns an rvalue whose value is a, that is, the old value, and then increments a at an unspecified time before the next full-expression (i.e., "before the semicolon").
Postfix increment has higher precedence than prefix increment.
This helped me a lot back in the day and it should help you too..
http://en.cppreference.com/w/cpp/language/operator_incdec

Js magic need explanation


How to isolate one of the terms or derive an expression to arrive at one of them from given expressions

Question: So I have been given 4 expressions and in three variable $a,b$ & $c$. Using these three expressions I have to isolate either of $a,b$ or $c$. However, I have not been able to come up with any equation or expression using which I could possibly isolate one of the terms. By isolate, I mean that given any expression in terms of some variables I should be able to do some operations by which I am able to get one or two variables.
For example:
If
$\;\text{eq1} = a+b+c
\\ \;\text{eq2} = a+b$
Then I must be able to obtain $a,b$ or $c$ by doing some operations and in this example it is simple subtraction.
Expressions given:
$\text{Ex1} = a + b + 2c
\\ \text{Ex2} = c^2 + ab + 2bc + 2ca
\\ \text{Ex3} = 2abc + ac^2 + bc^2
\\ \text{Ex4} = 4((c−a)^2(c−b)^2(4c^2−4bc−4ac+9b^2−14ab+9a^2))$
Expressions I arrived at:
$\text{Ex5} = a^2 + b^2 + 2c^2
\\ \text{Ex6} = 3a^2 + 3b^2 + 4c^2 - 2ab - 4ac - 4bc$
I have not been able to arrive at any solution till now. I think the answer might be to use the expressions to derive some expression for Ex4 and divide it with that to arrive at the answer.
Edit: Wrong terminology was used. Corrected it.
Edit2: The goal is to manipulate the various equations so that after some operations are done on them the result is a,b or c while we only have the above expression to get our answer with.
Comment: How are Eq1-Eq4 equations?  I'm assuming "Eq[insert number]" is the label for the supposed equation, not a variable name.
Comment: In Eq1, $~a + b + c = ~\color{red}{\text{what ?}}$
Comment: I'm sorry for the misunderstanding. I'll edit it. I have written equations but they are just polynomials or expressions in a,b and c.
Comment: @Poke_Programmer If those were linear equations, you could eliminate variables between them and "isolate" $a=\text{something}$. But yours are not linear equations, they are polynomial ones, and eliminating variables between them will result in a *polynomial* equation for $a$ like $p(a)=0$. That's the best you can do, since polynomials of degree $\gt 4$ do not have closed form solutions in general, so you'll not be able to get an expression like $a=\text{something}$ in this case.
Answer:
$$
\begin{align}
u &= a + b + 2c
\\ v &= c^2 + ab + 2bc + 2ca
\\ w &= 2abc + ac^2 + bc^2
\\ z &= 4((c−a)^2(c−b)^2(4c^2−4bc−4ac+9b^2−14ab+9a^2))
\end{align}
$$

The question is not clear and can be interpreted in different ways.

Calculate $\,z\,$ given the values of $\,u,v,w\,$. $\;-\;$ This can be done by eliminating $\,a,b,c\,$ between the four equations, and results (courtesy WA) in:
$$
z = -4 (27 u^3 w - 9 u^2 v^2 - 108 u v w + 32 v^3 + 108 w^2) \tag{*}
$$

Solve the system for $\,a,b,c\,$. $\;-\;$ A system with $4$ equations in $3$ unknowns is overdetermined in general. The condition for solutions to exist is that $(*)$ be satisfied, and in that case eliminating $\,b,c,\,$ between the first $3$ equations gives a sextic equation in $a$ alone (WA):
$$
16 a^6 - 24 a^5 u + a^4 (3 u^2 + 32 v) + a^3 (2 u^3 - 12 u v - 40 w) \\+ a^2 (3 u^4 - 18 u^2 v + 30 u w + 20 v^2) + a (-2 u^3 v + 6 u^2 w + 8 u v^2 - 36 v w) \\+ 4 u^3 w - u^2 v^2 - 18 u v w + 4 v^3 + 27 w^2 = 0
$$
Comment: +1 to your posting.  Personally, if I was on medication which caused me to anonymously downvote your answer, I would subsequently be too embarrassed to step forward.
Comment: Wish the downvoter had left a comment why.
Comment: Can you please explain what you have done in the latter part as I don't understand the terminology. Also I wish to have the result to be a single expression using which one can obtain either a,b or c. So can you also please tell how do we achieve it going from here. I'll also edit the question to make it more clear.
Comment: @Poke_Programmer You can eliminate variables between polynomial equations using [resultants](https://en.wikipedia.org/wiki/Resultant#Application_to_polynomial_systems) or [Gröbner basis](https://en.wikipedia.org/wiki/Gr%C3%B6bner_basis#Solutions_of_a_system_of_algebraic_equations). My answer does that, with two results. First one is to show that you can calculate $z$ from $u,v,w$ directly, without solving for $a,b,c$. Second one is to "isolate" $a$ into an equation that does not depend on $b,c$. It's a sextic, so there is no closed form $a=\ldots$, but you know $a$ is a root of that equation.
Comment: Thank you for the answer. I'll do some reading and try to understand it.


Erro usando uma view para dois controllers

Question: Eu tenho um controller para adicionar um objeto e ela utiliza a view. addObjeto.html
Eu tenho outro controller que é para editar esse objeto, e ao acessá-lo ele preenche toda a view addObjeto.html.
O que iria ser diferente seria só o botão de submit que a depender iria ser "Editar" ou "Adicionar"
Criei uma variável no controller chamada $rootScope.buttonCtrl.
Em que acessar o addObjetoCtrl a variável tinha valor $rootScope.buttonCtrl = true;
E em que acessar o editObjetoCtrl a variável tinha valor $rootScope.buttonCtrl = false;
E na view eu tenho
<button type="button" ng-click="addTarefa()" ng-show="buttonCtrl"
        class="btn btn-default" ng-disabled="tarefa.titulo == null ||
        tarefa.descricao == null || cl.classe==null">
    Cadastrar
</button>

<button type="button" ng-click="editarTarefa()" ng-show="buttonCtrl == false"
        class="btn btn-default" ng-disabled="tarefa.titulo == null ||
        tarefa.descricao==null || cl.classe==null ">
    Editar
</button>

Porém o que acontece é que na view o valor de buttonCtrl está sendo sempre true, logo, somente o botão "Cadastrar" está aparecendo. O que pode ser?
Comment: Você inicializou sua variável como "false"? Você entrou na pagina de Editar e nem assim aparece?
Comment: Você consegue printar na tela o valor de `buttonCtrl` e conferir se ele está realmente correto nas duas chamadas?
Answer:
Criei uma variável no controller chamada $rootScope.buttonCtrl

Nop, você criou uma variável no escopo-raiz ($rootScope). Dois problemas:

Este escopo não pertence ao controller (o escopo do controller
herda de $rootScope);
A criação de variáveis no $rootScope é considerada uma prática ruim.

Entre outras possíveis causas, seu problema pode ser o resultado de um escopo isolado.
O exemplo funcional abaixo ilustra a utilização de escopos locais ($scope). Clique em Executar para vê-lo em ação:

angular.module('myApp', [])
.controller('adicionarCtrl', function($scope){
  $scope.titulo  = "Adicionar";
  $scope.buttonCtrl  = true;
})
.controller('editarCtrl', function($scope){
  $scope.titulo  = "Editar";
  $scope.buttonCtrl = false;
})
;
.painel
{
  display:inline-block;
  width:200px;
  border:2px solid black;
  padding:10px 5px;
  margin:5px;
}


How to find the value of $\alpha$

Question: Let $M$ be a $3 \times 3 $ matrix such that
$M \begin{bmatrix} -2 \\
1\\
0\end{bmatrix}$ = $\begin{bmatrix} 6 \\
-3\\
0\end{bmatrix}$   and suppose that
$M^3 \begin{bmatrix} 1 \\
-1/2\\
0\end{bmatrix}$ = $\begin{bmatrix} \alpha \\
\beta\\
\gamma\end{bmatrix}$  for some $\alpha, \beta,\gamma \in R$ then
$\left|\alpha\right|$ is equal to :
I have figured out that
$\begin{bmatrix} -2 \\
1\\
0\end{bmatrix}$ is an eigen vector of given matrix with eigen value  equal to $-3$ .
But I am stuck after that step. Can somebody help
Thank you.
Comment: @sat091:  You're new here.  Let me strongly recommend you use titles that are informative and help others find this problem (and solution).  $\alpha$ could refer to *anything* in *any* branch of mathematics.  A much better title would be something along the lines of "Solving equations involving powers of matrix."
Comment: You mean eigenvalue $-3$, right?
Comment: Also notice that if $v$ is an eigenvector, also $\zeta \cdot v$ will be an eigenvector for any constant $\zeta$ since eigenvectors are precisely those vectors whose length but not direction is changed by applying the matrix.
Answer: Hint: If $v$ is an eigenvector of a matrix $A$ with eigenvalue $\lambda$, the it is also an eigenvector of $A^3$ with eigenvalue $\lambda^3$.
Comment: so, $-27$ will  be an eigen value of $M^3$ and thus $\alpha = -27, \beta = 27/2, \gamma = 0$ is this correct ?
Comment: @sat091 Yes, that is correct.

How to find the value of $\alpha$


function for all possible regression models in model selection

Question: I have a linear regression model:
$Y~X_1+X_2+X_3+X_4+X_5+X_6+X_7+X_8+X_9$ and I need to create a function that find all possible models (e.g.

$Y = X_1+X_2+X_3+X_4$
$Y = X_2+X_3+X_4$
$Y = X_1+X_3+X_4+X_5+X_6$ etc) and then calculates each model's DIC values.

Can someone help me since I'm not experienced at programming?
Comment: Just out of curiousity, why do you want this technique? Is it to find the most overfit model?
Comment: R has a package for all possible subsets: leaps (on CRAN)
Comment: It's in the context of my internship project where I have to use different model selection criteria for a given dataset
Comment: See the `dredge` function in package MuMIn.
Answer: Just use a backward or forward method to do so.
Forward: Just add and remove all your independent variables and see how each variable affect the model. Then keep adding and subtracting variables until you got a good model.
Backward: Add all variables and then remove them one by one and readd them to evaluate your model.
Comment: On could argue that "just use" should rather be replaced with "don't use": http://stats.stackexchange.com/questions/20836/algorithms-for-automatic-model-selection/20856#20856
Comment: Fitting every model and using a criterion (AIC, BIC, BICc) is a valid way to do model selection for a small number of predictors. Backwards and forward variable selection have fallen out of favor because they produce highly variable results.
Comment: This algorithm does not explore the "all possible subsets" of models requested in the question.


Why do quarterbacks lick their hands even when sitting on the sidelines?

Question: I understand why most QB's lick their hands when they're on the field. I guess it helps with the grip. But why so many of them keep licking their hands even when they are on the sidelines? Is it a bad habit most of them get in? Do they even lick their hands outside the stadium too?
Answer: It's to get a better grip on the ball. Most of them don't lick their hands outside the stadium.


Software Instrument Tempo Issues in Logic Pro X

Question: I am having a lot of trouble understanding the software instrument tracks in Logic Pro and how tempo works within them. If you record into logic using a software instrument as an input, there seems to be no way to separate the track from the project's tempo. I.e., I record into logic at 120bpm and then I speed the project tempo up to 130bpm, the software instrument track speeds up with it. This is fine in some cases, but in others I really want to be able to "unlock" this from the project tempo.
One other incredibly frustrating issue I'm having right now, is that this tempo locking feature seems to be completely throwing off my attempts at recording variable tempo tracks. So I have created a tempo curve from around 110bpm to around 120bpm. I then turn on the metronome and hit record on my software instrument track. I record along to the metronome, and then listen back, and the track is just completely out of time. I think what's happened is that logic has embedded in the track a flat 110bpm tempo, and then while I've sped up with the project tempo while recording, it's not taken that into account. Then once the track is fully recorded, logic goes and speeds up the track again to match the tempo curve. Not what I want! How can I make sense of this?
Answer: Bounce your software track to an audio track. It should then stay at the same speed, unless you specifically ask Logic to change the speed of the audio. You can bounce any midi region using the shortcut Ctrl-B.
Comment: This is the strategy I have been using (though not ideal because I can't modify the midi region now, which would be useful) but I'm still stuck with the variable tempo use case as Logic shifts the tempo of the midi track as soon as i'm done recording it, so there's no point at which it correctly matches the tempo where I can bounce the track.
Comment: idk Logic well-enough, but are you sure there's no master tempo track you need to switch on first? [& btw, but not really relevant to the issue, Logic is Mac-only, so no worries about what the command might be on Win ;)
Comment: You need to bounce the audio while still at the first tempo. You can always edit the midi and then record again, as long as you change the tempo back before bouncing. In the end, this is how any DAW is designed to work: it would be crazy if all midi tracks didn't automatically change speed when you change the tempo. But I do understand what you're trying to do; layers with different tempi are really interesting, but not what most people need to do in a DAW.
Comment: Hello again folks - I think you might be able to do exactly what you want by locking the position of midi notes - I'm just going to try it and then post another answer if it works.
Answer: I wouldn't usually post two answers for one question, but this is a completely different approach, so here we go. Both work, but this might be more what you are looking for...

Record some MIDI data at a particular tempo.
Select the region, right click, then go to SMPTE Lock->Lock SMPTE Position.
Change the project tempo at the point where your region begins.
Unlock the region SMPTE Lock.
Change the project tempo at whichever point you like (for instance, for the whole piece).
Move MIDI region as desired.


Como contar quantos elementos um array possui?

Question: Tenho um array de 10 posições que é preenchido através de uma função,
ARMultiEachMarkerInfoT marcadoresVisiveis[10];

sempre antes de adicionar elementos ao array, a função limpa todos os elementos e preenche de novo. Quero saber qual a melhor maneira de contar quantos elementos o array possui, tentei algo do tipo: contar quantos elementos não nulos o array possui e incrementar um contador mas não obtive sucesso.
Segue a função:
void ReposicionaObjetos(){
    int i;

    //Limpa o array
    memset(marcadoresVisiveis, 0, sizeof marcadoresVisiveis);

    //Preenche o array
    for( i = 0; i < config->marker_num; i++ ) {
        if( config->marker[i].visible >= 0 ){
            marcadoresVisiveis[i] = config->marker[i];
        }
    }

    //... Saber quantos elementos o array possui...
}

Answer: Seria algo assim:
void ReposicionaObjetos(){
    int contaElementosValidos = 0;
    memset(marcadoresVisiveis, 0, sizeof marcadoresVisiveis);
    for int (i = 0; i < config->marker_num; i++) {
        if (config->marker[i].visible >= 0 ){
            marcadoresVisiveis[i] = config->marker[i];
            contaElementosValidos++;
        }
    }
    //faz o que precisa com contaElementosValidos
}

Coloquei no GitHub para referência futura.
Tenho serias dúvidas se esta abordagem de limpar array e popular novamente é a correta, mas como não dei o contexto não posso falar muito.
Comment: Compartilho as dúvidas sobre limpar o array, mas por hora, é suficiente. Simples solução, às vezes foge aos olhos e tentamos procurar algo mais complexo ou simplesmente não sabemos como procurar, enfim obrigado, funcionou exatamente como esperado.


Git Workflow, Nvie Branching Model Ahead and Behind

Question: Following Nvie's git branching model, why do I end up with 'develop' and 'master' each 1 ahead and 1 behind the other after merging the same 'release' branch into both? If the same 'release' branch is merged into each, shouldn't master and develop agree?
x   84a628d      (origin/develop, develop) Merge branch 'release-v3.0.1' into develop
|\
| | x   2e4d60b  (HEAD, v3.0.1, origin/master, master) Merge branch 'release-v3.0.1'
| | |\
| | |/
| |/|
| x | 716ce96    (release-v3.0.1) Version 3.0.1
|/ /
x | fe3b54d      Some more more code
x | 3683892      Some more code
x | 8c0b835      'develop' branch code
|/
x   d051b54      (v3.0) Baseline merge. Merge remote-tracking branch 'origin/master'

$ git log origin/master ^origin/develop
commit 2e4d60b7d6760b4f6b2328ab06150b020b0d279f
Merge: d051b54 716ce96
Author: Todd
Date:   Tue Mar 26 11:27:59 2013 -0400

Merge branch 'release-v3.0.1'

$ git log origin/develop ^origin/master
commit 84a628d96653ed196faa6387c8b208badf23aa75
Merge: fe3b54d 716ce96
Author: Todd
Date:   Tue Mar 26 11:31:53 2013 -0400

Merge branch 'release-v3.0.1' into develop

What am I missing?
Answer: git log origin/master ^origin/develop

This command displays all commits reachable from origin/master but not from origin/develop
git log origin/develop ^origin/master

This command displays all commits reachable from origin/develop but not from origin/master
The output from both these above commands seem to be consistent with the graph you've shown.
If you intend to find out the difference in the contents of the 2 branches, you should be using the git diff command instead.
git diff origin/master..origin/develop

If you want only the list of files which are different, you can use the --name-status option:
git diff --name-status origin/master..origin/develop

In git, a commit's SHA1 is calculated based on the parent commit's SHA1, the commit message, the timestamps, and lot of other such information. Although you've merged the same release-v3.0.1 branch into both master and develop, you've done it as 2 independent merges at 2 different time instants. This would obviously not produce the same commit SHA1 for both.
What you should've done instead is one of the following:
Option 1:
git checkout master:
git merge release-v3.0.1

git checkout develop:
git merge master

git checkout master
# This would be a fast-forward merge
git merge develop

Option 2:
git checkout develop:
git merge release-v3.0.1

git checkout master:
git merge develop

git checkout develop
# This would be a fast-forward merge)
git merge master

This way you would end up with both master and develop branches pointing to the same commit.
You could get to the same state even now by merging either master into develop or the other way around, and doing a fast-forward merge on the other branch.
git checkout master
git merge develop

git checkout develop
# This would be a fast-forward merge
git merge master

Comment: Thanks Tuxdude! What's the point of merging master/develop and develop/master directly if you are trying to follow Nvie's branching model and provide a release branch for continuous work on the develop branch? ... [A successful Git branching model](http://nvie.com/posts/a-successful-git-branching-model/)
Comment: @Todd - The graph you've shown follows Nvie's branching model, but the commands you used to figure out the differences are incorrect. You should be using the `git diff develop..master` command instead to diff the contents of the 2 trees, rather than merely checking the commits using the `git log` command. The reason why I told you about merging develop and master directly, is to make both the branch pointers point to the same commit after a merge from release. How you maintain the branches is totally upto you ;)
Comment: Ahhh... 'diff' does report zero differences as I was expecting for my case! So... 'log' reports on the commits and 'diff' reports the absolute changes between entities (nodes, branches, versions, etc.)!! So it seems that the 'Branches' tab on GitHub is reporting the results of a 'log' and the commit deltas between merged branches. Unfortunately not what I expected and not clear for the uninitiated. Thank you Tuxdude! (sorry I don;t have the rep to up-vote your answer)


Problem with Django url

Question: Going to http://127.0.0.1:8300/projects/cprshelp/edit_file/?filename=manage.py results in a 404 error
urls.py
(r'^projects/(?P<project_name>[\w ,-<>]+)/', include('projects.urls')),

projects/urls.py
(r'edit_file/$', views.edit_file),

What do I need to change to my url files to make this particular url work?
List of valid urls:
^admin/doc/
^admin/
^projects/(?P<project_name>[\w ,-<>]+)/ edit_file/$
^media/(?P<path>.*)$

edit_file function:
def edit_file(request, project_name):
    print '**** project name ' + project_name
    #project = Project.objects.get(name=project_name)

    filename = request.GET['filename']
    #content_of_file = open(project.file_location + filename, 'r')
    #content_of_file = '\n'.join(content_of_file.readlines())

    context = RequestContext(request, {
        #"project": project,
        #"files": get_files_and_directories(project.file_location),
        "filename": filename,
        #"content_of_file": content_of_file,
    })

    return render_to_response("edit_file.html", context)

Comment: Is it an actual 404 or does it tell you that this is an invalid url and give you a list of valid URLs? If the latter, can you post the URLs that it gives?
Comment: show your edit_file view
Comment: See edited problem description
Answer: You need to backslash your - in your regex:
>>> p = re.compile(r'projects/[\w ,-<>]+/')>>> p.search('http://127.0.0.1:8300/projects/cprshelp/edit_file/?filename=manage.py').group()
'projects/cprshelp/edit_file/'
>>> p = re.compile(r'projects/[\w ,\-<>]+/')>>> p.search('http://127.0.0.1:8300/projects/cprshelp/edit_file/?filename=manage.py').group()
'projects/cprshelp/'
>>>

also consider using .get:
filename = request.GET.get('filename','')

Answer: Try changing your project/urls.py to
(r'^edit_file/$', views.edit_file),

Comment: In the valid urls, is there actually a space before 'edit_file/$'?
Comment: I changed ^projects/(?P[\w ,-<>]+)/ to ^projects/(?P\w+)/ and now it works
Comment: I think that the '-' should have been preceded with a backslash. Otherwise, you are defining a range between ',' and '<'.
Comment: Sorry about that. I'll give you an upvote for the right answer nonetheless.

Problem with Django url


Deleting local profile after user logs off?

Question: I am currently using roaming profiles and wante to configure all clients connected to the domain to delete the local profile once the user logs off.
Could this be done via a Group Policy?  Script?
Comment: Is this server running on a VMware host? If so, do you have VMware tools installed? If so, do you have the Shared Folders component of VMware Tools installed? If so, uninstall that component. There's a known issue with cached copies of roaming profiles not being deleted if the Shared Folders component of VMware Tools is installed.
Answer: You probably want the following Group Policy:

Computer Configuration -> Administrative Templates -> System -> User Profiles
Delete cached copies of roaming profiles
Comment: @joesafe: gpupdate /force ?
Comment: I've tried this yesterday, however the copy is still on the local machine.  Would I need any other configuration done as well as the GP?
Comment: What OS are the clients? And is the full profile definitely still there? Log on to a box and compare your own, currently logged on profile folders with that of the 'should be deleted' ones. It may be that certain folders can't be deleted, but the bulk is going.
Comment: In addition to what @BartSilverstrim says, you should also check the event viewer.
Comment: Can't believe I forgot to do gpupdate /force.  Thanks, I will give this another shot and hopefully it will work this time.

Also, the clients are mostly Windows 7 with a couple of XP's around.
Comment: I've done all this, however it still leaves a folder (named: the users username).  This folder is empty.  Is this correct?
Comment: @JoeSafe Yeah, I see that a lot - I think it's to do with files being locked and the like. It's not caused any issues in my experience.
Answer: In addition to configuring profile deletion via Group Policy you might want to check out my free tool Delprof2 which deletes inactive profiles on all versions of Windows both locally and remotely.
You can find more information about Delprof2 here:
http://helgeklein.com/free-tools/delprof2-user-profile-deletion-tool/


Object doesn't support property or method 'format' IE7/8

Question: I am receiving an error message "Object doesn't support property or method 'format'" when running the following code in IE 7/8 Browser and Document Mode. I am using Knob - jQuery Plugin.
<code>// Dial logic
var Dial = function (c, opt) {

    var v = null
        ,ctx = c[0].getContext("2d")
        ,PI2 = 2 * Math.PI
        ,mx ,my ,x ,y
        ,self = this;

    this.onChange = function () {};
    this.onCancel = function () {};
    this.onRelease = function () {};

    this.val = function (nv) {
        if (null != nv) {
            opt.stopper && (nv = Math.max(Math.min(nv, opt.max), opt.min));
            v = nv;
            this.onChange(nv);
            this.draw(nv);
        } else {
            var b, a;
            b = a = Math.atan2(mx - x, -(my - y - opt.width / 2)) - opt.angleOffset;
            (a < 0) && (b = a + PI2);
            nv = Math.round(b * (opt.max - opt.min) / PI2) + opt.min;
            return (nv > opt.max) ? opt.max : nv;
        }
    };
</code>
Comment: You need more context within the rest of your code for this to make sense.
Comment: Which of the assignments throws that error (or is it a variable declaration)? Test them separately. Also, are you sure the error stems from this line - there is no `format` at all?
Comment: No need to test anything, the variable names and the getContext makes it pretty clear that is something that has something to do with a canvas. Since there is no canvas support in IE7/8, which would have taken five seconds to figure out with a Google search, it really does'nt matter much exactly where the error is.
Answer: That's simply that there is no canvas in IE before IE9. You can't do anything besides recommending to your users an upgrade.
See the compatibility table.
HTML5 makes a lot of new applications possible. People wanting to use them can't keep their old browser.
Comment: You can't do anything besides recommend an upgrade? What about libraries that simulate it...like excanvas?
Comment: @Ian Those libraries don't work fast enough as soon as you do something a little more complex than drawing a square and they're generally painful to maintain. In my opinion they're bringing us back to the time where we had to make different codes for IE and Netscape/Firefox...
Answer: You can add canvas support for IE7/IE8 with explorercanvas.


Lista infinita com ionic?

Question: Estou tentando criar uma lista infinita com o Ionic/AngularJS. Essa lista passa um offset para meu webservice paginar as respostas do SELECT. Não estou conseguindo fazer isso e estou procurando um exemplo mas ainda não encontrei.
Estou tentando assim.
Service
var app = angular.module('starter');

app.service('EmpresaAPIService', function($http, AppConstants, HeaderFactory){
    var headersJSON = HeaderFactory.getHeader.headerJSON();

    this.getAllEmpresas = function(offset){
        var _url = AppConstants.webServiceUrl + "/empresas/getAllEmpresas.json";
        var _jsonData = {"offset": offset};

        return $http.post(_url, _jsonData, {
            headers: headersJSON,
        });

    };

});

Controller
var app = angular.module('starter');

app.controller('EmpresaCtrl', function($scope, EmpresaAPIService){

    var offset = 0;
    $scope.items = [];

    $scope.addItems = function(){
        EmpresaAPIService.getAllEmpresas(offset)
        .success(function(data){
            var result = data.result;
            for(var x = 0; x < result.length; x++){
                $scope.items.push(result[x].Empresa);
            }
            offset += 5;

            //console.log(result[0].Empresa.nomeFantasia);
        })
        .error(function(err){
            console.log(err);
        });

    };

});

Html
<ion-view title="Empresas">
  <ion-content class="has-header padding">
    <ion-list>
        <ion-item ng-repeat="item in items track by $index">

{{item.nomeFantasia}}

        </ion-item>
        <ion-infinite-scroll on-infinite="addItems()" distance="1%"></ion-infinite-scroll>
   </ion-list>
  </ion-content>
</ion-view>

Comment: Veja um destes exemplos [«1»](http://learn.ionicframework.com/formulas/infinite-lists/#)[«2»](http://ionicframework.com/docs/api/directive/ionInfiniteScroll/)[«3»](http://codepen.io/elm/pen/Becqp)
Answer: Da uma olhada nesse exemplo: http://codepen.io/d4dilip/pen/rkxyA. Ainda sobre de uma olhada no site do ionic: http://ionicframework.com/docs/api/directive/ionInfiniteScroll/
Código exemplo:
HTML:

    <meta charset="UTF-8">
    <link href="http://code.ionicframework.com/nightly/css/ionic.min.css" rel="stylesheet">

    <title>Infinite App Example </title>

    <ion-content>
        <ion-header-bar >{{items.length}} items</ion-header-bar>
    </ion-content>
    <ion-content class="has-header">
        <ion-list>
            <ion-item ng-repeat="item in items"  item="item" href="#{{item.id}}">
                Item {{item.id}}
            </ion-item>
            <ion-infinite-scroll distance="2"
            on-infinite="loadMoreData()"
            ng-if="!moredata"
            ></ion-infinite-scroll>
        </ion-list>
    </ion-content>

JS:
/**
* Created by singhdi on 2014-07-26.
*/
var app = angular.module("ionicInfiniteScrollApp",['ionic']);

app.controller("InfiniteAppCntrl",function($scope){
    $scope.moredata = false;
    debugger;
    $scope.loadMoreData=function()
    {
        $scope.items.push({id: $scope.items.length});
        if($scope.items.length==100)
        {
            $scope.moredata=true;
        }
        $scope.$broadcast('scroll.infiniteScrollComplete');
    };

    $scope.items=[];
});

No método loadMore voc6e pode usar o teu serviço para retornar os dados. Atenção ao método:
$scope.$broadcast('scroll.infiniteScrollComplete');
Esse deve ser chamado após você atualizar a váriavel com o conteúdo retornado do serviço. Em resumo esse cara irá disparar um comando pro controller do scroll ser atualizado.
Answer: Resolvido.
Controller
var app = angular.module('starter');

app.controller('EmpresaCtrl', function($scope, EmpresaAPIService){

    var offset = 0;
    $scope.items = [];

    $scope.addItems = function(){
        if($scope.items.length > 0){
            offset++;
        }
        EmpresaAPIService.getAllEmpresas(offset)
        .success(function(data){
            angular.forEach(data.result, function(empresa){
                $scope.items.push(empresa);
            })

            $scope.$broadcast('scroll.infiniteScrollComplete');
        });

    };
});

html
<ion-view title="Empresas">
  <ion-content class="has-header padding">
    <ion-list>
        <ion-item ng-repeat="item in items">

{{item.Empresa.nomeFantasia}}

        </ion-item>
        <ion-infinite-scroll on-infinite="addItems()" distance="1%"></ion-infinite-scroll>
   </ion-list>
  </ion-content>
</ion-view>

Lista infinita com ionic?


How are the p-values of the GLM in R calculated?

Question: I have been running some binomial logistic regressions in R on a data set and I realised that the p-values of the estimated coefficients are not computed based upon a Normal distribution. For e.g. I have the following result from the glm() function:
<code>    Coefficients:

                                   Estimate Std. Error z value Pr(>|z|)
    (Intercept)                    -1.6127     0.1124 -14.347  < 2e-16 ***
    relevel(Sex, "M")F             -0.3126     0.1410  -2.216   0.0267 *
    relevel(Feed, "Bottle")Both    -0.1725     0.2056  -0.839   0.4013
    relevel(Feed, "Bottle")Breast  -0.6693     0.1530  -4.374 1.22e-05 ***
</code>
I previously thought that the beta hats (estimated coefficients) are asymptotically normal and the p-value should be calculated using the normal distribution. But it seems from the p-values here that a t-distribution is used to compute them (I think).
I know that the asymptotic condition does not hold when sample size is small but if so, what is the process that causes the estimator to be distributed with a Students distribution? And how do I find out the degrees of freedom for such a distribution?
Answer: It comes from standard normal:
<code>-0.3126/ 0.1410 =  -2.217021
2*pnorm(-2.216) = 0.0266915
</code>
Comment: @skan; and looks like John Fox's `car` package may make this even easier ... https://rdrr.io/cran/car/man/Boot.html
Comment: It actually seems to be 2*pnorm(-1*abs(estimate/std.error)). I had positive coefficients and found out that the pnorm argument needs to be negative number for this to work.
Comment: @JitendraKulkarni ; yes  - your formula is correct (see `summary.glm` which uses `2 * pnorm(-abs(tvalue))` as in your comment) . But you could also use `lower.tail=FALSE` depending on the sign; `2*pnorm(-2.216)` is the same as `2*pnorm(2.216, lower.tail=FALSE)` )
Comment: How can I tell R to use a resampling method to obtain more realistic p-values?
Comment: @skan; There is not a default resampling method within `glm`, But it is straight forward  to roll out your own non-parametric bootstrap.


VBA get address for last empty row and copy

Question: Hi I have a worksheet where the date is stored in columns, I want to write a macro which cuts the data and paste the data in row B. Please see picture attached.
I have already written this code:
Sub test()

    Dim rng, copy_paste_range As Range

    Set rng = Range(Range("C2"), Range("C2").End(xlToRight))

    For Each r In rng

        Range(Range(r.Address), Range(r.Address).End(xlDown)).Copy
        'last_row = ThisWorkbook.Worksheets("Sheet1").Cells(Row.Count, 1).End(xlUp).Row
        LastLine = Range(("B" & Rows.Count).End(xlUp).Row + 2).Select
        LastLine.Paste

    Next r

End Sub

However I always want to leave 1 row empty when I copy the data from every column but I always get an error for:
LastLine = Range(("B" & Rows.Count).End(xlUp).Row + 2).Select
            LastLine.Paste

Can anyone assist ? If you look in the picture I am trying to cut-copythe data from C2:C5 and past it to B12:B15
Comment: Replace `Range(Range(r.Address), Range(r.Address).End(xlDown)).Copy
        'last_row = ThisWorkbook.Worksheets("Sheet1").Cells(Row.Count, 1).End(xlUp).Row
        LastLine = Range(("B" & Rows.Count).End(xlUp).Row + 2).Select
        LastLine.Paste` with `Range(Range(r.Address), Range(r.Address).End(xlDown)).Copy Cells(Rows.Count, "B").End(xlUp).Offset(2)` all in one line.
Answer: You have dimmed the rng as a variant and you should dim r as range as well
Sub Button1_Click()

    Dim rng As Range, r As Range

    Set rng = Range(Range("C2"), Range("C2").End(xlToRight))

    For Each r In rng.Cells
        Range(Range(r.Address), Range(r.Address).End(xlDown)).Copy Range("B" & Rows.Count).End(xlUp).Offset(2)
    Next r

End Sub


Write down all the elements of the quotient group $Z_{18} / \langle 6\rangle$. Is any element of order $5?$ Give reasons for your answer.

Question: Write down all the elements of the quotient  group $Z_{18}  / \langle 6\rangle.$ Is any element of order $5?$  Give reasons for your answer.
I just know order of $Z_{18}  / \langle 6\rangle$ will be
$18 \div 3= 6.$
Where $\langle 6\rangle = \{ 6 , 12 , 0 \}$
But I can't decide how to write elements of this factor group!
I know there can't be a element of order $5.$
Comment: You should learn (and use) MathJax (LaTeX) to format math here.
Comment: Do you have lagrange's theorem?
Comment: Can a group of order six have an element of order five?
Comment: How to write elements of this group?
Answer: The set (group actually, but this is not relevant for this part of the question) $\Bbb Z_{18}/\langle 6\rangle$ is by definition made of the $6$ elements:

$\langle 6\rangle=\{0,6,12\}$
$1+\langle 6\rangle=\{1,7,13\}$
$2+\langle 6\rangle=\{2,8,14\}$
$3+\langle 6\rangle=\{3,9,15\}$
$4+\langle 6\rangle=\{4,10,16\}$
$5+\langle 6\rangle=\{5,11,17\}$

As for the other part, note that the order of an element $aH$ (multiplicative notation) in the quotient group $G/H$ is equal to the least positive integer $n$ such that $a^n\in H$. In fact, by the normality of $H$ in $G$:
\begin{alignat}{1}
&(aH)^n=H \iff \\
&a^nH=H \iff \\
&a^n\in H \\
\end{alignat}
Now back to your case (and to the additive notation): $a+\langle 6\rangle$ has order $5$ in $\Bbb Z_{18}/\langle 6\rangle$ if and only if $5a\in \langle 6\rangle$, which fails for every $a=1,2,3,4,5$. In fact:
\begin{alignat}{1}
&5\cdot1=5\equiv 5 \pmod {18} \\
&5\cdot2=10\equiv 10 \pmod {18} \\
&5\cdot3=15\equiv 15 \pmod {18} \\
&5\cdot4=20\equiv 2 \pmod {18} \\
&5\cdot5=25\equiv 7 \pmod {18} \\
\end{alignat}
Therefore, there isn't any element of order $5$ in $\Bbb Z_{18}/\langle 6\rangle$.
Answer: In general, an abelian factor group has the following structure:
You give me some group $G$ and a subgroup $H$. Then the set
$$\{H + g: g\in G\}$$
is a group, where the group operation is $(H + g) + (H + k) = H + (g+k)$. Note that $H + g$ means the set $\{ h + g: h\in H\}$.
So, let's apply this to $G = \mathbb{Z}/(18)$ and $H = \langle (18) + 6\rangle$. The set of elements is
$$\{ [(18) + 6] + k: k\in \mathbb{Z}/(18)\}.$$
Definitely $[(18) + 6] + 0$ is in this set. And the element $[(18) + 6] + 6$ is actually equal to $[(18) + 6] + 0$. Can you show why they're equal, and fill out the rest of the elements from here?


Using Ionic to access ASP.NET Core functionalities

Question: I have an asp.net core site with regular controllers (not webapi) and I want to build an ionic mobile app which uses same methods and same authentication as I have registered users.
I host my site as a webapp in azure and i use an sql database.
I don't have a clear vision on how to achieve this but I'm thinking of:

Building webapi controllers
Building azure mobile service

What option is better and am I missing another option?
Your advice is appreciated.
Answer: Azure Mobile Apps does not support .NET Core at this time.  So the decision is kind of made for you.


jenkins Role-Based Strategy - project role patterns

Question: I am trying to provide a Role-Based Strategy project role patterns:
  Role to Add: sysadmin
  Pattern: *-stack

While saving those changes, I am getting following error in Jenkins
Stack trace
java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*-stack
^
    at java.util.regex.Pattern.error(Pattern.java:1955)
    at java.util.regex.Pattern.sequence(Pattern.java:2123)
    at java.util.regex.Pattern.expr(Pattern.java:1996)
    at java.util.regex.Pattern.compile(Pattern.java:1696)
    at java.util.regex.Pattern.<init>(Pattern.java:1351)
    at java.util.regex.Pattern.compile(Pattern.java:1028)
    at com.michelin.cio.hudson.plugins.rolestrategy.Role.<init>(Role.java:90)
    at com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy$DescriptorImpl.ReadRoles(RoleBasedAuthorizationStrategy.java:763)
    at com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy$DescriptorImpl.newInstance(RoleBasedAuthorizationStrategy.java:711)
    at com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy$DescriptorImpl.doRolesSubmit(RoleBasedAuthorizationStra

What is the error in my pattern?
Answer: We can use shell regular expression to match the Jenkins projects.In this case we can use
Patter: \S*-stack

Answer: You could consider using regex (.*) in place of *
(.*)-stack

Comment: Well I tried the accepted answer on my Jenkins installation, didn't work for me. Tried with the regex and it worked fine.
Comment: If anyone's looking: `(.*)` works as match all, while `.*` doesn't.
Answer: In case you need to provide access to jobs inside the folder as well as to job in root:
folder_name.*|job_in_root

More information on this can be found here:

https://support.cloudbees.com/hc/en-us/articles/360036425292-Role-Based-Authorization-Strategy-Limit-folder-access


Load folder name as column in delta table

Question: /SRC1/trialbucket=1/1.parquet
/SRC1/trialbucket=2/2.parquet
/SRC2/trialbucket=1/3.parquet
/SRC2/trialbucket=2/4.parquet

All the above parquet files in the folders have the same schema.
eg. Col1,Col2,Col3
I have to load all the files into a delta table with the following schema
Col1,Col2,Col3,Source

data1,data2,data3,SRC1

data11,data22,data33,SRC1
data1111,data222,data333,SRC1
data5,data6,data7,SRC2
data55,data66,data77,SRC2
data555,data666,data777,SRC2

I can do it with each and add the folder name as the last column (.withColumn) but I have to go through 10000 such folders to read all the parquet files and load them into a table which takes a lot of time!
Is there any other way without the for loop to get the folder name and add it to the column?
Comment: [input_file_name](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.input_file_name) may be helpful
Comment: input file name can be anything. The column would be the folder name (SRC1 or SRC2)
Answer: You can use  regexp_extract to get the foot folder name from the input_file_name :
val df1 = df.withColumn("Source", regexp_extract(input_file_name(), "/(.*)/.*", 1))

Comment: this works fine for small number of folders. but not efficient for reading through 10000 folders and loading all the parquet data into a delta table!
Comment: @justanothertekguy maybe you can load the folders per batch and insert into the same delta table at each iteration.
Comment: how would i load them in batch?
Comment: @justanothertekguy by iterating over a list of folders or some pattern that you can use to construct the folder paths, then in each iteration you load a small set of folders and insert into your table .. this might be a new question though.


How to find out if the iPhone is on silent mode?

Question: I have a mailing application. If the user sends a mail successfully, then I need to notify that the mail was sent successfully. For that, I need to know if his phone is on silent mode
(in which case there will be a 'vibrate')  or regular mode (in which case there will be a 'beep'). Can anyone help me with it?
Thanks in advance
Answer: If you use the correct audio session type, iOS will handle this for you:
http://developer.apple.com/library/ios/#documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html
Answer: <code>CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if(CFStringGetLength(state) == 0)
{
    //SILENT

}
else
{
    //NOT SILENT

}
</code>
If the state string is empty then the phone is on silent - otherwise the phone has an audio output
EDIT:
remember to add the AudioToolbox framework and import. – Thomas Clayson
answer taken from (http://iphone-dev-tips.alterplay.com/2009/12/iphone-silent-mode-detection.html)
Comment: ah... beat me to it... :p *deletes my answer*
Comment: You can either put it exactly where you want to use it (after you've sent the message). Or you could put in a method of its own called something like "BOOL phoneIsOnSilentMode()" and return the result of (CFStringGetLength(state) == 0). Then when you want to use it after sending the message call  "if (phoneIsOnSilentMode())" and vibrate if true or play a sound if false
Comment: Hey I have put this snippet in -applicationdidFinishLaunching method and when I try running it on my iPhone, it runs only the first time after install or when I switch off the phone and try again. Why is this happening? Isn't it suppose to run everytime I launch my app. And one more question- the state variable, when I display it in alert, always shows 'speaker' even after my changing the sound settings. How many states are there and how to change them from sound settings of iPhone. That is to say that I could never get the state variable as null, it's always speaker.
Comment: The state of iPhone apps is sometimes stored - so the applicationDidFinishLaunching method isn't necessarily called every time you click on the app icon from the home screen. Regardless, you surely want to make the check just before either playing the sound or vibrating? Otherwise a user might just open your app, begin to use it and then change to silent before sending a message. Then once the message had been sent you would have the wrong information about the audio state. Put the snippet in its own method and call the method after sending the message and before playing the sound or vibrating
Comment: I got it Rick thanks a lot. But I was doing it just for the testing purpose. Anyways, let's assume that I put the code where it should be put but the issue I am facing is that the function is never called at all. I have tried putting my phone on silent mode and testing but it's not called. I am displaying an alert if it's in silent mode just for the sake of testing. So, either I don't know how to set the iPhone on silent mode or there is something else at play. Also, please tell me about the other modes. So that I can program for head phone on and all.
Comment: the mode is always "speaker" no matter whatever I do with the sound settings from my home screen
Comment: Are you using an iPhone or an iPod touch?
Comment: Look at: http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/AudioSessionServicesReference/Reference/reference.html & http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/AudioSessionServicesReference/Reference/reference.html#//apple_ref/doc/constant_group/Audio_Session_Services_Property_Identifiers


PDFsharp/MigraDoc FootNote usage

Question: I'm generating a c# project and I want to add some footnotes to my PDF file. I want to create footnotes which present additional documents on it.
I tried these but none of these are working; nothing shows up on my PDF file.
Paragraph paragraph = document.LastSection.AddParagraph();
FootNote fn = paragraph.AddFootnote();
fn.AddParagraph("¹You should add document one.");

-------------------------------------

paragraph.AddFootnote("¹You should add document one.");

I didn't find what is wrong,
Thanks for help.
Answer: Footnotes do not work with the current implementation of MigraDoc.
Answer: A small workaround. This solution is far from perfect but should work.
First Mark the text with your pseudo footnote mark:
Paragraph p = section.AddParagraph("");
p.AddText("Now comes the text with the footnote"); // the text itself

Font f = p.Format.Font.Clone();
f.Superscript = true;
p.AddFormattedText("1", f); // your pseudo footnote, just a superscripted mark

Then put the footnote explanation below on your page like:
Paragraph pFootnote = section.AddParagraph("");
pFootnote.AddText("________"); pFootnote.AddLineBreak();
Font fFootnote = pFootnote.Format.Font.Clone();
fFootnote.Superscript = true;
pFootnote.AddFormattedText("1", fFootnote); // footnote itself
pFootnote.AddText(" footnote explanation");

PDFsharp/MigraDoc FootNote usage


Thread Safety of LibAv/FFMpeg?

Question: Is LibAV/FFMpeg thread safe? For example. Could I read from a file using AVFormatContext* in one thread and decode the read packet it in another with simple additions of mutexes or is the thread safetyness of the library a "don't know don't care" type deal? I know that libav has basic support for encoder threads but I'm trying more of a blackbox type approach where I break it up into multiple threads (Source -> Decoder -> Filter -> Encoder -> Sink) and trying to understand the complications of such.
Anyone with any experience with ffmpeg and threads and would like to chime in with any other info pertinent to this would also be greatly appreciated.
Comment: I'm not entirely sure so I'm not making this an answer, but I think the basic idea is that the library is thread-safe, but the caller must ensure that individual av objects are accessed by only one thread at a time.
Answer: You can register your own lock manager. The ffmpeg library will control thread safety.
Example:
::av_lockmgr_register(&my_lockmgr_cb);

 //// ..........

int my_lockmgr_cb(void **mutex, enum AVLockOp op)
{
  if (NULL == mutex)
    return -1;

  switch(op)
  {
   case AV_LOCK_CREATE:
   {
    *mutex = NULL;
    boost::mutex * m = new boost::mutex();
    *mutex = static_cast<void*>(m);
    break;
   }
   case AV_LOCK_OBTAIN:
   {
    boost::mutex * m =  static_cast<boost::mutex*>(*mutex);
    m->lock();
    break;
   }
   case AV_LOCK_RELEASE:
   {
    boost::mutex * m = static_cast<boost::mutex*>(*mutex);
    m->unlock();
    break;
   }
   case AV_LOCK_DESTROY:
   {
    boost::mutex * m = static_cast<boost::mutex*>(*mutex);
    delete m;
    break;
   }
   default:
   break;
  }
  return 0;
}

Comment: If you build FFmpeg with `--enable-pthreads`, FFmpeg automatically uses its own default lock manager implementation, so there's no need to call `av_lockmgr_register()`.
Comment: `av_lockmgr_register` is "now" deprecated and is a no-op. At least as of release 4.2.2, maybe earlier. The comment on that function reads "This function does nothing, and always returns 0. Be sure to build with thread support to get basic thread safety.".
Comment: And now `av_lockmgr_register()` is only mentioned in the changelog. It's gone from their git master.
Answer: To expand on the existing answer:
ffmpeg's av_lockmgr_register() is the way to deal with locking.
An ffmpeg build with threads (and a later version than LIBAVCODEC_VERSION_MAJOR 55, LIBAVCODEC_VERSION_MINOR 38 and LIBAVCODEC_VERSION_MICRO 100 - roughly about October 2013, see ffmpeg commit adding default lockmgr) will have a default lock manager that you can just use.
If you need to be compatible with libav then (at the time of writing, September 2016) this does not yet have a default lock manager and you need to provide your own.
Here is a pure C pthread's implementation:
static int ffmpeg_lockmgr_cb(void **arg, enum AVLockOp op)
{
    pthread_mutex_t *mutex = *arg;
    int err;

    switch (op) {
    case AV_LOCK_CREATE:
        mutex = malloc(sizeof(*mutex));
        if (!mutex)
            return AVERROR(ENOMEM);
        if ((err = pthread_mutex_init(mutex, NULL))) {
            free(mutex);
            return AVERROR(err);
        }
        *arg = mutex;
        return 0;
    case AV_LOCK_OBTAIN:
        if ((err = pthread_mutex_lock(mutex)))
            return AVERROR(err);

        return 0;
    case AV_LOCK_RELEASE:
        if ((err = pthread_mutex_unlock(mutex)))
            return AVERROR(err);

        return 0;
    case AV_LOCK_DESTROY:
        if (mutex)
            pthread_mutex_destroy(mutex);
        free(mutex);
        *arg = NULL;
        return 0;
    }
    return 1;
}

which is registered like so:
ret = av_lockmgr_register(ffmpeg_lockmgr_cb);
if (ret < 0)
{
    fprintf(stderr, "av_lockmgr_register failed (%d)\n", ret);
    abort();
}

Thread Safety of LibAv/FFMpeg?


Don't cache custom Front Page domain

Question: I'm working on a module that shows a different frontpage per role. I have three frontpages:

the base www.domain.nl for anonymous users, set in the basic site settings
for users with role_1 they go to sub1.domain.nl\dashboard
for users with role_2 they go to sub2.domain.nl\dashboard

I'm almost there but the frontpage url is set in cache (I think) therefor when I login I get the right frontpage. So I have role_1 en go to sub1.domain.nl. Now when I logout I want to go back to www.domain.nl but I still get redirected to sub1.domain.nl. Even when I close the browser and return to the site I still get back to sub1.domain.nl.
So my question is how can I make sure this response is cleared from cache after loggin out or is not even cached at all? What is the best method to deal with this?
My code till now:
mymodule.services.yml
services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\FrontpageSubscriber
    tags:
      - {name: event_subscriber}

src/EventSubscriber/FrontpageSubscriber.php
<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\TrustedRedirectResponse;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FrontpageSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public function checkFrontRedirection(GetResponseEvent $event) {
    $current_path = \Drupal::service('path.current')->getPath();
    $front_uri = \Drupal::config('system.site')->get('page.front');
    $front_alias = \Drupal::service('path.alias_manager')->getAliasByPath($front_uri);
    $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $isFrontPage = \Drupal::service('path.matcher')->isFrontPage() || $front_alias === $current_alias;

    if ($isFrontPage) {
      $hasRole1 = \Drupal\user\Entity\User::load(\Drupal::currentUser()
        ->id())->hasRole('role_1');
      $hasRole2 = \Drupal\user\Entity\User::load(\Drupal::currentUser()
        ->id())->hasRole('role_2');

        if ($hasRole1) {
          $domain_url = 'https://sub1.domain.nl/dashboard';
          $response = new TrustedRedirectResponse($domain_url);
          $event->setResponse($response);
        }

        if ($hasRole2) {
          $domain_url = 'https://sub2.domain.nl/dashboard';
          $response = new TrustedRedirectResponse($domain_url);
          $event->setResponse($response);
        }
     }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkFrontRedirection');
    return $events;
  }
}

Answer: Could be a caching issue within the browser, Drupal or both. For the browser set cache headers in the response, see https://drupal.stackexchange.com/a/278703/47547.
For Drupal caching add a cache context user.roles:
$response->getCacheableMetadata()->addCacheContexts(['user.roles']);

Furthermore it is recommended to execute a redirect event subscriber only on a master request, this helps to prevent redirect loops:
public function checkFrontRedirection(RequestEvent $event) {
  if (!$event->isMainRequest()) {
    return;
  }
  ...
}

Don't cache custom Front Page domain


SQLSTATE[HY000]: General error: 1366

Question: I'm using Feed Importer to import data from a csv file, and I got this error
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xA0 a TN...' for column 'message' at row 1
All values are in english characters, and I really don't know how to solve this problem
Help please. thanks
Answer: What is the origin of your CSV file? Are you sure that it is properly encoded using UTF-8? This error is coming from an issue with the database handler trying to process non-UTF8 characters (see: http://drupal.org/node/1140194).
The particular character it is having problems according to your error above is the "&nsbp" character or 0xC2 and 0xA0, you'' want to convert your file to UTF-8 or alternatively if you have control over what ever is generating your export, strip it out using php following the advice here
Comment: I tried opening it up in notepad and saved it in UTF-8, but it says the file it's unwritable when I import from the modified file.
Comment: You likely messed something up when you saved it out.  The encoding issue can be a real pain.  If you don't have the source encoding right, converting to UTF-8 won't do mush (it has to know what to convert *from*).  Very often, I just search/replace these bad characters with Notepad++.
Answer: If you got the error while using the db_insert then you can use the following code
$val = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

if it is just matter of one field value.

SQLSTATE[HY000]: General error: 1366


Varnish caching layer vs load balancer

Question: We have around 10-15 different websites which at the moment are hosted on two Rackspace cloud servers with 4GB RAM.  These two servers are totally independent of each other, we randomly choose a server for each new site.
We've recently launched a new site which is quite a memory hog, and has exhausted the memory on it's server several times since going up, causing it to crash.  I'm looking into why this is within the site itself.
But also I think there's a lot I can do with the server architecture. There are two obvious things I could do...
Setup Varnish caching (the type of websites we have will benefit greatly from this).
And setup load balancing between the two servers.
So to do this, I've proposed we get one new cloud instance.  Now my question is what to do with it...
1) Set this up as another LAMP server, and get a load balancer from Rackspace (which are quite cheap) to load balance between all three.  Each running their own version of Varnish to cache the sites.
2) Set up the new box as a Varnish caching layer, and get Varnish to do the load balancing between the two we currently have.
I really like the sound of option 2, as all the caching would happen in one place.  We could also do some cool stuff within Varnish like get it to serve cached pages if all servers were down, and have generally greater control.
Most of the website visitors are anonymous, so could be served a cached site. Most logged in users are editorial staff, so it's more important to prioritise high-availability.
But, in terms of maximising the available resource, I'm not sure what is the best thing to do.
Answer: Choose option 2 and then use a rackspace loadbalancer that does the following:

If varnish cache is up and alive direct all traffic to the varnish instance
If varnish is down load balance between the two remaining webservers

This prevents you from building a single point of failure but you need a reliable healthcheck in your loadbalancer configuration.
Comment: Thanks, agreed this is the best setup.  However we don't have a database server, which means it will have to run on one of the load balanced LAMP servers, which still creates a single point of failure and defeats the point of load balancing.  So I think we're not going for this approach at all now.
Comment: set up a DB instance on both of the machines and use a product like percona cluster. and gone is your last spof :)
Comment: Unfortunatley, Rackspace cloud load balancers can't do any type of "intelligent" switching, so it would require a hardware load balancer or something else.

Varnish caching layer vs load balancer


Getting the Value from a Datatype Dropdown (Umbraco)

Question: I am trying to get the name or shall i say the value of the dropdown pre value created using the umbraco datatype "dropdown"

Now when specifying the "id" it gets the number, how do i get the value of that "id"?
Here is the dropdown populated with the id of the values;

How do i get the value name? And not the ID?
Here is the Surface Controller;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.XPath;
using Umbraco.Core.Services;
using Umbraco.Web.Mvc;

///
/// Summary description for ContactSurfaceController
///

namespace LiquidThinker2015
{
    public class ContactSurfaceController : SurfaceController
    {
        public object XPathModeIterator { get; private set; }

        public ActionResult ShowForm()
        {
            ContactModel myModel = new ContactModel();
            List<SelectListItem> ListOfServices = new List<SelectListItem>();
            XPathNodeIterator iterator = umbraco.library.GetPreValues(1435);
            iterator.MoveNext();
            XPathNodeIterator preValues = iterator.Current.SelectChildren("preValue", "");
            while (preValues.MoveNext())
            {
                string preValue = preValues.Current.GetAttribute("id","");
                ListOfServices.Add(new SelectListItem
                {
                    Text = preValue,
                    Value = preValue
                });
                myModel.ListOfServices = ListOfServices;
            }
            return PartialView("ContactForm", myModel);
        }

        public ActionResult HandleFormPost(ContactModel model)
        {
            var newComment = Services.ContentService.CreateContent(model.Name + " - " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"), CurrentPage.Id, "ContactFormula");

            //DataTypeService myService = new DataTypeService();
            //var SelectedService = myService.GetAllDataTypeDefinitions().First(x => x.Id == 1435);
            //int SelectedServicePreValueId = myService.GetPreValuesCollectionByDataTypeId(SelectedService.Id).PreValuesAsDictionary.Where(x => x.Value.Value == model.SelectedService).Select(x => x.Value.Id).First();

            newComment.SetValue("contactName", model.Name);
            newComment.SetValue("companyName", model.Company);
            newComment.SetValue("emailFrom", model.Email);
            newComment.SetValue("telephoneNumber", model.Telephone);
            newComment.SetValue("dropdownServices", model.SelectedService);
            newComment.SetValue("contactMessage", model.Message);

            Services.ContentService.SaveAndPublishWithStatus(newComment);

            return RedirectToCurrentUmbracoPage();
        }
    }
}

Thanks
Answer: You are using preValue for both Text and Value in your list.
Change it to:
ListOfServices.Add(new SelectListItem
{
    Text = preValues.Current.Value,
    Value = preValues.Current.GetAttribute("id","")
});

Comment: many thanks for this, a simple mistake made which was agonised over several hours. But end result is very pleasing. Thanks again.