Repeating an operation infinitely makes any convex $n$-gon a regular $n$-gon?

Question: For any convex $n$-gon $P_{0,1}P_{0,2}\cdots P_{0,n}$, let us consider the following operation :
Operation : Let $k=0,1,\cdots$. Take $n$ points $P_{k+1,i}\ (i=1,2,\cdots,n)$ outside of $n$-gon $P_{k,1}P_{k,2}\cdots P_{k,n}$ such that every $P_{k,j}P_{k,j+1}P_{k+1,j}\ (j=1,2,\cdots, n)$ is an isosceles right triangle whose right angle is $\angle P_{k,j}P_{k+1,j}P_{k,j+1}$ where $P_{k,n+1}=P_{k,1}$.
Then, here is my question.
Question : Is the following true for any convex $n$-gon ?
$$\lim_{k\to\infty}\frac{P_{k,2}P_{k,3}}{P_{k,1}P_{k,2}}=\lim_{k\to\infty}\frac{P_{k,3}P_{k,4}}{P_{k,2}P_{k,3}}=\cdots=\lim_{k\to\infty}\frac{P_{k,n}P_{k,1}}{P_{k,n-1}P_{k,n}}=\lim_{k\to\infty}\frac{P_{k,1}P_{k,2}}{P_{k,n}P_{k,1}}=1.$$
In other words, "If we repeat the operation infinitely for any $n$-gon $P_{0,1}P_{0,2}\cdots P_{0,n}$, then do we get a regular $n$-gon ?"
Motivation : I've found that the answer for $n=3$ is YES. However, I have no good idea for $n$ in general. Can anyone help?
Proof for $n=3$ : Let $S_k$ be the area of a triangle $P_{k,1}P_{k,2}P_{k,3}$. By law of cosines in a triangle $P_{k,1}P_{k,2}P_{k,3}$, we get
$${P_{k+1,2}P_{k+1,3}}^2={P_{k,1}P_{k+1,2}}^2+{P_{k,1}P_{k+1,3}}^2-2P_{k,1}P_{k+1,2}\cdot P_{k,1}P_{k+1,3}\cos\angle P_{k+1,2}P_{k,1}P_{k+1,3}.$$
Since $\cos\angle P_{k+1,2}P_{k,1}P_{k+1,3}=\cos(\angle P_{k,2}P_{k,1}P_{k,3}+90^{\circ})=-\sin\angle P_{k,2}P_{k,1}P_{k,3}$, we get
$$\begin{align}{P_{k+1,2}P_{k+1,3}}^2=\frac 12{P_{k,3}P_{k,1}}^2+\frac 12{P_{k,1}P_{k,2}}^2+2S_k\qquad(1)\end{align}.$$
By the same argument above, we get
$$\begin{align}{P_{k+1,3}P_{k+1,1}}^2=\frac 12{P_{k,1}P_{k,2}}^2+\frac 12{P_{k,2}P_{k,3}}^2+2S_k\qquad(2)\end{align}.$$
$$\begin{align}{P_{k+1,1}P_{k+1,2}}^2=\frac 12{P_{k,2}P_{k,3}}^2+\frac 12{P_{k,3}P_{k,1}}^2+2S_k\qquad(3)\end{align}.$$
By $(1)(2)(3)$ and $S_K\gt 0$, we get
$${P_{k+2,2}P_{k+2,3}}^2\gt \frac 12{P_{k+1,3}P_{k+1,1}}^2+\frac 12{P_{k+1,1}P_{k+1,2}}^2$$$$\gt\frac 12\left(\frac 12{P_{k,1}P_{k,2}}^2+\frac 12{P_{k,2}P_{k,3}}^2\right)+\frac 12\left(\frac 12{P_{k,2}P_{k,3}}^2+\frac 12{P_{k,3}P_{k,1}}^2\right)\gt\frac 12{P_{k,2}P_{k,3}}^2.$$
Hence, we know that $2^n{P_{k,2}P_{k,3}}^2\ge 2^{\frac n2}{P_{0,2}P_{0,3}}^2$ when $n$ is even and that $2^n{P_{k,2}P_{k,3}}^2\ge 2^{\frac{n-1}{2}}{P_{1,2}P_{1,3}}^2$ when $n$ is odd. In either case, we can see $\lim_{k\to\infty}2^n{P_{k,2}P_{k,3}}^2=\infty.$
By $(2)-(1)$, since we get ${P_{k+1,3}P_{k+1,1}}^2-{P_{k+1,2}P_{k+1,3}}^2=-\frac 12\left({P_{k,3}P_{k,1}}^2-{P_{k,2}P_{k,3}}^2\right)$, we get
$${P_{k,3}P_{k,1}}^2-{P_{k,2}P_{k,3}}^2=\left(-\frac 12\right)^n\left({P_{0,3}P_{0,1}}^2-{P_{0,2}P_{0,3}}^2\right).$$
Hence we get
$$\left(\frac{P_{k,3}P_{k,1}}{P_{k,2}P_{k,3}}\right)^2=1+\frac{(-1)^n\left({P_{0,3}P_{0,1}}^2-{P_{0,2}P_{0,3}}^2\right)}{2^n{P_{k,2}P_{k,3}}^2}\to 1$$
when $k\to\infty$, which leads
$$\lim_{k\to\infty}\frac{P_{k,3}P_{k,1}}{P_{k,2}P_{k,3}}=1.$$
By the same argument above, we get
$$\lim_{k\to\infty}\frac{P_{k,1}P_{k,2}}{P_{k,2}P_{k,3}}=1.$$
Since we can easily get
$$\lim_{k\to\infty}\frac{P_{k,2}P_{k,3}}{P_{k,1}P_{k,2}}=\lim_{k\to\infty}\frac{P_{k,3}P_{k,1}}{P_{k,2}P_{k,3}}=\lim_{k\to\infty}\frac{P_{k,1}P_{k,2}}{P_{k,3}P_{k,1}}=1,$$
we now know that the proof for $n=3$ is completed.
Update : I added a word 'isosceles'. I crossposted to MO.
Comment: The newly added points create right triangles. Does the right angle have to be on the newly added point in that triangle?
Comment: @user96614: Yes. In my question, yes.
Comment: This question ended up being related http://math.stackexchange.com/questions/868051/iterativ-centroid-triangle-sequence/868184#868184
Answer: I'm posting an answer just to inform that the question has received an answer by Jeremy Rickard on MO.
He mentioned that it's true if $n$ is prime with some details. Also, j.c. showed a counterexample.


Polymer Custom Element Shadow DOM issues

Question: I am attempting to use the Polymer shadow DOM " $ " object.
document.querySelector("recent-activity-section").$

This code should return an object that looks like this:
Object {recent-activity-section: section#recent-activity-section, recent-activity-div: div#recent-activity-div, list: core-list#list}

In fact, using the Chrome Dev Tools console, it does.
However, inside of the "created" function in the javascript file that goes along with my custom element, I get the following:
undefined

Perhaps I'm using something wrong?
Answer: Instead of using the created method, which is one of the first ones triggered in the element's lifecycle, you would probably have more luck using domReady, which is, according to Polymer official docs:

Called when the element's initial set of children are guaranteed to exist. This is an appropriate time to poke at the element's parent or light DOM children.


Instalar biblioteca Curl Python 3.4.4

Question: Alguém possui um link do .zip para instalar a biblitoca "import pycurl"
Uso Windows e Python 3.4.4
Answer: Baixe pycurl-126.96.36.199.win32-py3.4
Extraia na pasta e execute no cmd pip install pycurlpycurl-22.214.171.124.win32-py3.4

Instalar biblioteca Curl Python 3.4.4


Configuration of recording target by using the onvif interface

Question: I have several cameras with Onvif profile S. Each has the current firmware installed.
It seems there is no possibility to configure the recording target by using the Onvif interface on this profile? (I found it in the core specifications, but the cameras are responding with errors on that method)
But it seems strange, since it's possible to configure the recording target by using the GUI and the vendors own API. (I have Axis and Samsung cameras)
Comment: Have a look at the communication with some packet sniffing software. Typically there are very manufacturer specific messages sent and received in this area of ONVIF implementations.
Comment: Thanks for the advice. I tried it by using WireShark, but was unable to find methods for this actions at this point. (To be honest.. I don't even know why the cameras have the profile S. The cameras have edge recording functionality and there is a special Onvif profile G for this kind of devices)
Comment: Perhaps the vendors implement this outside of the onvif protocol.
Comment: Yes, I fear this could be the case. The Axis cameras have an own API and I'm able to use this interface to do that.. But this makes the ONVIF API worthless for me, since I'm trying to accomplish a vendor independent implementation.. If I need to implement the storage configuration with vendor specific methods, I could use the API of the vendors for the whole functionality. :S
Answer: Okay, I have an answer for my question.
Onvif defined the methods for configuring storage settings in the newest version, 2.5. Since my newest camera with the current firmware only supports 2.1, I simply do not own any camera with support for storage configuration and so I need to wait until the vendors implement the methods from newer specifications.


JQuery - How can I check that onclick event already called for a button?

Question: I have an input (type: button), and I want to call for that an onclick event. But sometimes I added the input button later, and then I have to call again the event. So I have an input button with 2 onclick event. How can I check that onclick event already called for that?
Thanks
Comment: Use a single delegated event on a parent element.
Comment: http://api.jquery.com/one/
Comment: __But sometimes I added the input button later__ what do you mean by this?
Comment: What you mean by "I want to call for that an onclick event"? Are you using a jquery `.click()` or `.on()` api? If yes, then you are not **calling** and `onclick()`, you are just hanging a function inside the `onclick()`. You will need to hang this handler to every new button!
Comment: Sometimes I have to add the input button into a form later with ajax.
Answer: var counter=0;
$("#btn").onClick(function(){
    counter+=1;
    // do some
});

then u can check the value of counter:
if (counter>0){
    alert("clicked before");
}

Answer: Instead of binding event handlers again for dynamically generated elements, you can delegate the event handler to a static (preferable the closest parent element which is not dynamically generated) parent element using the on() method.
For example:
$(document).on("click",":button",function(){});

Will work with the buttons you generate dynamically in future as well. So no need to bind events again which is causing the issue for you.


Factorization of polynomials into polynomials of smaller degree

Question: how 'hard' is the find the factorization of POlynomials ?
i mean for example if we had $ x^4-1 = (x^2-1)(x^2 +1) $
this is easy but if we put the polynomial in general
$$ x^6 -5x^3 +4x^2 -7x^3 =0 $$
then in general how can we 'factorize ' a polynomial into polynomials of lower degree?
Comment: Factoring is very hard.  Even testing for reducibility is hard.
Comment: Your polynomial may have a typo, because $-5x^3-7x^3=-12x^3$.
Answer: Obviously we have
$$
x^6 -5x^3 +4x^2 -7x^3 =(x^4 - 12x + 4)x^2,
$$
where the first factor is irreducible over $\Bbb Q$.
In general factoring is hard, but there are several algorithms - see wikipedia. For polynomials of lower degree it thus no problem to obtain a factorisation.
To show that a polynomial like $x^4-12x+4$ is irreducible, one often can use the extended Eisenstein criterion. Also, a direct computation is possible for low degree, and several other criteria.


Chord alteration references? ("inside" vs. "outside")

Question: Originally, I asked the question immediately below and it created some confusion. My revision appears below the original.
#
What books or references do you recommend which teach about altered chords as they exist inside the given key? Allow me to explain by way of an example... Take My Funny Valentine, for instance. Great tune, lovely changes. It's in the key of Cm (using both harmonic and natural minors). The G7#5 leading back to the Cm caught my attention as an altered chord that exists within the context of the C harmonic minor scale.
Looking at the whole of natural, harmonic, and melodic minors, we can create a fair amount of chromaticism (b6, 6, b7, 7, 1). What I am attempting to piece together are which altered chords can fit where inside the context of these scales. In other words, I am attempting to learn how to intelligently apply these alterations without leaving the key (however I am allowing for some stretch of the key definition by including these three different minor keys).
Of course, we can create further tension by going beyond (or "outside" of) the current key context, but for now it is these "inside" alterations that interest me the most as a potential vehicle for spicing up some changes. Thanks in advance for your recommendations.
#
I should have used the term "alteration", however my example suggested "altered" instead. (I have amended the title.) I did not intend to limit the scope to altered dominant chords; my intent was to map the diatonic ("inside") alterations within the context of each mode for the three minor scales, plus the bii tritone sub as well. I have recently begun this exercise for my own benefit, and I was seeking to corroborate my answers. (As a guitarist, my voicings will be more limited than some of the potential keyboard solutions.) Thanks for your feedback.
Comment: Between your question and the one answer currently posted, it seems that there is confusion between an Altered chord and an Alteration. An Alteration is an extension that is either raised or lowered compared to the major or perfect intervals that are Extensions (tensions). So, in Cmaj7 #11, though it occurs naturally in G Major, the #11 is an alteration. I have seen two Altered chords, Dom7 b9, #9, #11, b13; and Dom7 b9, #9, #11, Natural 13.  It seems that the first is the most common. So in your example, G7#5 (b13 as some would call it) is not an altered chord but a chord with an alteration.
Answer: Alterations are mostly used with dominant chords moving to a chord with a root a perfect fifth below their root, i.e. G7(alt) moving to Cm. You can use a dominant chord to approach any stable chord in your key (these dominant chords are called secondary dominants), but using them also means altering (at least) one scale tone. E.g., for the IV chord in C minor (which could be an Fm7 or an F7) you could use C7 as a secondary dominant, but then you need to alter the scale tone eb to e. So you see that within the key the possibilities are restricted. It is only the V chord (G7), which is usually altered. However, in minor this means just using ordinary (unaltered) scale notes as tensions for G7: eb (#5/b13), ab (b9), bb/a# (#9). Just the #11 for G7 (c#) is not part of the minor key.
Some other chords (in C minor) where the #11 is inside the key are:
Ebmaj7/#11, F7/#11, Abmaj7/#11
You can use these to add some color to your progressions without altering any notes of the key (even though I don't understand this self-imposed restriction).
Note that all these 'alterations' sound very normal and not really unexpected, simply because they are all notes already contained in the key. Altering a dominant chord in a major key is a very different matter, because here all the alterations mentioned above are NOT part of the major scale.
As far as I know there is no book on this exact topic. A very good general book on jazz harmony is The Chord Scale Theory & Jazz Harmony by Nettles and Graf. However, to get the most out of it you should know your basic music theory before you start working through it.
Comment: Using a note that is outside the scale, say for a secondary dominant, is not necessarily an alteration, at least not within the realm of Extensions/Alterations.  Also, Altered chords are probably used just as commonly, if not more, to move somewhere other than down a fifth.  Altered chords make for great tri-tone and minor third substitutions.  Within the Jazz context, alterations are so common that anything 'being in the key' doesn't really have the same weight as it does in more strictly diatonic settings.
Comment: A note outside the scale is an alteration of an original scale note, indeed not necessarily an alteration of a chord tension, this is what I meant by 'alteration' in that context. Furthermore, tritone subs usually do not have altered tensions other than the #11, otherwise you would 'undo' the implicit alteration of using a tritone sub, because the unaltered tensions of a tritone sub are just the altered tensions of the original chord.
Comment: Yes, the note is altered from that which is within the scale of the key but not an alteration for the chord.  Undoing the implicit alterations of the substitution is exactly why one might want to use an Altered chord.  The chord itself is quite dissonant but having those common tones from the scale makes it fit with a less jarring effect.
Answer: Even if your interest may not be in classical music, you need to work on classical harmony, for it is the basis of any tonal music (jazz, etc, included). There are many books on classical harmony, but one I suggest you look at is Tchaikovsky's Guide to the Practical Study of Harmony, as it is short and well explained, and freely (and legally) available at IMSLP.org.
Answer: I've never heard the terms "inside" or "outside" but from the other answers, it seems if "inside" refers to chromatic alterations which do not change key and "outside" refers to those which do. (There may be "boundary" cases that could be analyzed either way.)
Classically, there are quite a few chromatic alterations that do not cause one to hear a key change. The most common (as already mentioned) are secondary dominants (AKA applied dominants) like using D7 in the key of C in a progression like D7-G7-C. This can be extended to many progressions based on the Circle of Fifths like C-E7-A7-D7-G7-C. Other simple alterations are using the tonic or subdominant minor where the major chord would be expected. The Neapolitan Sixth and Augmented Sixths can also be used without leaving the "current" key.
Schoenberg suggests that one only effects a key change when the characteristic notes of the "first" key are "neutralized." Thus "modulation" to a new key depends on long-range relations. A non-modulatory example: C-A7-D7-G7-C-C-Am=dm=G7=C). The notes "foreign" to the first key should be confirmed. C-Am-dm-G7-C-A7-D7-G-C-Am-D7-G-A7-D7-G-D7-G... used the F# in the new key in contrast to its use in the old key. The F# hangs around.
The minor keys are a bit tricky in that there are two notes (steps  6 and 7) that are mutable. Both forms may occur without leaving the key and may even occur simultaneously (in different voices.) The idea of neutralization still works except in moving to the relative key (similar problem in major). The simple VII7-III movement isn't enough to modulate to III (c-f-Bb7-Eb can be ambiguous) so more work is needed. This is why early Baroque liked pieces to modulate from i to III or I to V as moving in and out of these pairs of keys is hard to make aurally convincing.


MySql Use of Max on Date for Aging Report with excluding a specific condition

Question: I need to prepare a forecast aging report for projects finishing in coming months. Data lied in various tables - all having a common post_id field. Lets see my table structure first (I will mention only relevant columns).

table1 : 01c_posts (ID, post_title,......)
table2 : 01c_project (id, post_id, end_date, .....)
table3 : 01c_enquairy_products (id, post_id, confirmed_amount, .....)
table4 : 01c_update (id, post_id, status_id, status_date,.....)
table5 : 01c_status (status_id, status, .....)

01c_update having multiple status for every `post_id.
Now, I have prepared following SQL which has no error but giving multiple lines for every project according to the numbers of their status in update table - so the sum of confirmed_amount in table3 will be multiple of number of status for relevant project.
    SET SQL_BIG_SELECTS=1;
    select a.post_id, b.post_title,
    sum(if(month(a.end_date) = 1 and year(a.end_date) = 2018,c.confirmed_price, 0)) as "Jan",
    sum(if(month(a.end_date) = 2 and year(a.end_date) = 2018,c.confirmed_price, 0)) as "Feb",
    sum(if(month(a.end_date) = 3 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Mar",
    sum(if(month(a.end_date) = 4 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Apr",
    sum(if(month(a.end_date) = 5 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "May",
    sum(if(month(a.end_date) = 6 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Jun",
    sum(if(month(a.end_date) = 7 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Jul",
    sum(if(month(a.end_date) = 8 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Aug",

    max(d.update_date), d.status_id
    from 01c_projects a
    inner join 01c_posts b on a.post_id = b.ID
    inner join 01c_enquairy_product c on a.post_id = c.post_id
    inner join 01c_updates d on a.post_id = d.post_id
    where a.post_id not in (select post_id from 01c_updates where status_id = 25 or status_id = 24)
    group by b.post_title
    having max(d.update_date)
    order by a.end_date

Can someone guide me where i'm missing?
Comment: Maybe `GROUP BY b.post_id` instead of `b.post_title`?
Comment: every post have a unique title, problem is somewhere in max(update_date) - it should take one date only which has a maximum value for a specific post_id, but its taking all date entries and increasing number of rows
Answer: ok, got is resolved. Final solution is given below so other can get a help if needed
    select a.post_id, b.post_title,
sum(if(month(a.end_date) = 1 and year(a.end_date) = 2018,c.confirmed_price, 0)) as "Jan",
sum(if(month(a.end_date) = 2 and year(a.end_date) = 2018,c.confirmed_price, 0)) as "Feb",
sum(if(month(a.end_date) = 3 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Mar",
sum(if(month(a.end_date) = 4 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Apr",
sum(if(month(a.end_date) = 5 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "May",
sum(if(month(a.end_date) = 6 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Jun",
sum(if(month(a.end_date) = 7 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Jul",
sum(if(month(a.end_date) = 8 and year(a.end_date) = 2018, c.confirmed_price, 0)) as "Aug",

d.update_date, d.status_id
from 01c_projects a
inner join 01c_posts b on a.post_id = b.ID
inner join 01c_enquairy_product c on a.post_id = c.post_id
inner join 01c_updates d on a.post_id = d.post_id
where a.post_id not in (select post_id from 01c_updates where status_id = 25 or status_id = 24)
AND d.id in
(select id from 01c_updates filter join (select post_id, max(update_date) as update_date from 01c_updates
    group by post_id ) sfilter on
    filter.post_id = sfilter.post_id
    and filter.update_date = sfilter.update_date)
group by b.post_title
order by a.end_date


Where are the field formatter settings?

Question: When I'm managing a display for an entity and select a field formatter, some formatters have options available (see screenshot 1).
However, when I use that same field formatter in Views, there's no way to set my options.  How can I set my options?

This works.

This doesn't have a way to select options.
Comment: Normally the settings are loaded automatically via ajax when you select a formatter. There is no cog.
Answer: 4k4's comment was helpful in that it indicated the correct behavior.  This isn't what was happening; the POST requests were returning correctly, but I assume they're not returning a correct part of the dialog to replace.
However, with this knowledge in mind, I was able to use Configuration Management to export the View and the Entity view display, pull the appropriate setting names from the Entity view display, and manually apply them to the View YAML and reimport.  It's imperfect, but knowing that this should be possible was a great help in finding a workaround.

Where are the field formatter settings?


How can I stop the textarea from disappearing?

Question: I have a form that adds comment from the user:

<textarea name="comment" id="comment_box" placeholder="Share your thoughts" cols="175" rows="9"></textarea>

<input type="button" name="add_comment" id="add_comment_button" value="Add comment"
 onclick="add_comment_js('comment_form','{$type}')">

Once I click on the button "Add comment" the textarea disappears (I think using jquery), no css files included.
A big functions.js file is linked also, I suspect this method inside the javascript file has to do with the disappearance:
  function add_comment_js(form_id,type)
  {
    var formObjectData = $('#'+form_id).serialize()+'&mode=add_comment';

    $.post(page,formObjectData,
    function(data)
    {
        if(!data)
            alert("No data");
        else
        {
            if(data.cid)
            {
                get_the_comment(data.cid,"#latest_comment_container");
                $("#"+form_id).slideUp();
            }
        }
    },'json');
}

Why is the textarea hiding after I post the comment? What's wrong?
Comment: Comment out functions.js temporarily and see if your theory is correct.
Comment: post the code for the complete form, probably .slideUp() is messing up
Comment: Whatever JSON object you are getting from your $.post function, the "cid" key is set and therefore the .slideUp() method is being called on the text box.  Check to make sure that data.cid is in fact set (you might need to try "data.cid!==undefined")
Comment: @Nicolas, when I do that, the comment won't be posted when I press the button and thus I can't test it.
Comment: `$("#"+form_id).slideUp();` makes it slide up, out of view. You should be able to comment out that line.
Answer: $("#"+form_id).slideUp(); is hiding the form when this function runs. Remove that line and the textarea should persist. Slideup "Hides the matched elements with a sliding motion." Here's the jQuery API reference for that function.
Answer: remove this line form your code
$("#"+form_id).slideUp();

final result should look :
function add_comment_js(form_id,type)
{
    var formObjectData = $('#'+form_id).serialize()+'&mode=add_comment';

    $.post(page,formObjectData,
    function(data)
    {
        if(!data)
            alert("No data");
        else
        {
            if(data.cid)
            {
                get_the_comment(data.cid,"#latest_comment_container");
            }
        }
    },'json');
}

Comment: I downvoted because Brent was first and deserved the acceptance. This kid just stole his solution and posted the full code block.
Comment: @Nicolas yeah :) anyway didn't saw Brent's post till i've submited mine


Ruby on Rails Gemfile Development and Javascript

Question: I'm working on porting a JS library to rails. This will be my first gem that I'm attempting to create and I seem to have run into a bit of a snag.
The issue that I have is that there will necessarily be some JavaScript elements to the gem. However, I seem to be unable to find out how to do this.
Example:
/lib/rotrails.rb
module RotRails
    def self.isSupported
        #Call JS function "isSupported() in /vendor/assets/javascript/rotrails.js
    end
end

/vendor/assets/javascript/rotrails.js
Function isSupported() {
     return !!(document.createElement("canvas").getContext && Function.prototype.bind);
}

Any assistance on how to solve this problem as well as pass the result back to the Rails Gem would be appreciated.
Update: To clarify, the rails part is logic calculations and the JavaScript is the frontend for the program. I am looking for the most logical way to have the two communicate or a reference to how to work with JavaScript when creating gemfiles.
Thanks!
Comment: You know that JavaScript runs on the client, and the Ruby runs on the server, right?
Comment: Ajax? http://www.w3schools.com/ajax/default.ASP
Comment: @Amit Not that way, there isn't. You can't invoke arbitrary JS methods in your Ruby code. You shouldn't have to anyways; perform your feature detection on the client, and act accordingly. Your Rails server should almost never need to be concerned with what the browser supports.
Comment: I do, yes, there must be a way to have the two talk with each other.
Comment: Then let me rephrase the situation. There will be logic calculations happening on the backend (Rails), and drawing happening on the frontend (JavaScript). What would be the most correct way to communicate the needed data from one to the other and back again?
Comment: JS on the client and Rails on the server. You can use JQuery ajax calls from the client to the server. The server can't call the client at all, unless you use either 'long calls' or websockets.
Answer: Did you consider to use (or simply try) https://rails-assets.org/ instead of porting your js library manually ?


Xcode 6.1 Suddenly show error in all my projects

Question:

I have Copy a project folder from github into my new project But it's show some error.
So I have deleted that project(Deleted my new project too).
But suddenly xcode 6.1 show build error when i run in device for all my project also all in files.
like attached images.
I dont know why it's happened.
Hope someone try to resolve this!
Comment: I think you deleted any framework accidentally, so check  for framework i.e. Security Framework..
Comment: If all your projects are giving error maybe something got messed up in derived data. Try clearing that up by using this http://stackoverflow.com/questions/24039932/how-to-delete-derived-data-in-xcode6
Comment: But its show an error all my projects's all files , also Build phases not show any library with name  security . FYI: There is no error when run with simulator.
Comment: Then try to Cleanup your xcode derived  Data  go to --->OS X Mavericks ▸ Users ▸ your system ▸ Library ▸ Developer ▸ Xcode ▸ DerivedData
Comment: hi @Jitendra i have cleared derived data from xcode menu Window->Organisor->projects and remove all items after restart xcode but its not done.
Comment: @Mohanraj - Please attach a zoomed in screenshot so that the error is visible. What exact error are you getting?
Comment: Hi @z22 , please have a look my edited question.
Comment: try adding security framework again
Comment: I cant able to add Security frame work because its not show in build phases search after click + button.
Comment: @Mohanraj please check this path for security framework ,if unavailable then add security framework there and then add on your project from build phase...     Path-->     Applications ▸ Xcode  ▸ Contents ▸ Developer ▸ Platforms ▸ iPhoneOS.platform ▸ Developer ▸ SDKs ▸ iPhoneOS.sdk ▸ System ▸ Library ▸ Frameworks
Answer: Thanks to every one to help me,
In this issue was happened even i am create a new project
But I have some work to continue , so simply i was reinstall my xcode application and its work now.
Answer: Your first error:

Security/Security.h not found

Means that you need Security.Framework, seems you are removed it.
For the rest errors it is seems you are removed Foundation.framework.
If you are using RCS(svn, git)(if not, I strongly recommend to start using it) , and you don't done any major changes, I will suggest to revert your last changes.
Comment: Hi @IAmDav I have add Foundation.framework to Build phases.  but cant find Security.Framework by seraching. also i have checked with old projects and there also the same issue as Build error .
Comment: Hi @Mohanraj, What you mean by "old proejcts"? Do you have any working state of your app? then revert local changes.
Do you getting the same errors after adding Foundation,framework?
Comment: The Security.Framework in the iOS framework, so you can find it by typing the name, ,after + button in embedded binaries.
Comment: old project means before meet this issue has some working projects, they also produce same build error when i ht run button.


Conditionally format all the cells with dates of the current week

Question: I have a table that looks like this:
<code>some text    14.09.2022
some text    15.09.2022
some text    23.10.2022
</code>
And I need to conditionally format each cell in the second column if the date in that cell is during the current week.
I have tried different solutions from the Internet[^1], but neither works for me: each time Google Sheets says my formulas are wrong. Any help?
[^1]: For example, I have tried to adopt the formula found here.
Answer: Try below custom formula in CF rule.
<code>=WEEKNUM($C2)=WEEKNUM(TODAY())
</code>


How add query to EntityListBuilder

Question: I want to add a query to filter my entity list table.
class CommandesLignesEntityListBuilder extends EntityListBuilder {

  use LinkGeneratorTrait;

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['id'] = $this->t('ID');
    $header['produit'] = $this->t('Produit');
    $header['quantite'] = $this->t('Quantité');
    $header['prixHT'] = $this->t('Prix HT');
    $header['TVA'] = $this->t('TVA');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\boutique\Entity\CommandesLignesEntity */
    $row['id'] = $entity->id();
    $row['produit'] =$entity->getProduit();
    $row['quantite'] =$entity->getQTE();
    $row['prixHT'] =$entity->getPrixHT();
    $row['TVA'] =$entity->getTVA();

    return $row + parent::buildRow($entity);
  }

}

This show me all lines. How can I filter this with a query? For example, how can I get only lines with price greater or equal to 100?
i would like a permanent query for this EntityListBuilder sub-class.
Answer: If someone is looking for the same, this is how i use filter on my entityListBuilder :
I override the method getEntityIds for build my logic :
   protected function getEntityIds() {
        $query = $this->getStorage()->getQuery()
            ->sort($this->entityType->getKey('id'))
            ->condition('commandes_id',1,'=');

        if ($this->limit) {
            $query->pager($this->limit);
        }
        return $query->execute();
    }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {

    $header = array(
        'id' => array(
            'data' => $this->t('N° produit'),
            'class' => array(RESPONSIVE_PRIORITY_LOW),
        ),
        'nom' => array(
            'data' => $this->t('Nom'),
        ),

        'quantite' => array(
            'data' => $this->t('Quantité'),
        ),

        'prixHT' => array(
            'data' => $this->t('Prix HT'),
        ),

        'tva' => array(
            'data' => $this->t('TVA'),
        ),

    );

    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\boutique\Entity\CommandesLignesEntity */
    $row['id'] = $entity->id();
    $row['produit'] =$entity->getProduit();
    $row['quantite'] =$entity->getQTE();
    $row['prixHT'] =$entity->getPrixHT();
    $row['TVA'] =$entity->getTVA();

    return $row + parent::buildRow($entity);
  }

Comment: I +1 this as an alternative, but just to clarify, the load method calls getEntityIds by default, so the query should probably be modified in getEntityIds rather than in load. That way someone might call getEntityIds and get completely different results.
Answer: Although not exactly a duplicate of How to make EntityListBuilder sortable? it is essentially the same answer as Berdir wrote,

You'd have to implement the query logic yourself.

For instance, BlockListBuilder overrides getEntityIds to add a condition on the theme key.
However as Berdir also notes,

For content entities, I would strongly recommend to rely on the views
  integration instead. List builders are limited in functionality and
  mostly useful for config entities only.

How add query to EntityListBuilder


How to show that this short exact sequence does not split

Question: Consider the Short Exact sequence
$0\rightarrow C_0((0,1))\rightarrow C([0,1])\rightarrow \mathbb{C}\bigoplus\mathbb{C}\rightarrow 0$
where the map from $C([0,1])\rightarrow \mathbb{C}\bigoplus\mathbb{C}$ sends $f$ to $(f(0),f(1))$. How does one show this sequence does not split in terms of C* algebras. i.e. there does not exist a *-homomorphism inducing a right split. I consider the map $(a,b)$ to the continuous function starting at $a$ and ending at $b$ by Tietzes extension theorem. Why can this not be made to be a *homomorphism?
Answer: There is no "the" continuous function that you want. So you are not really defining your section. If the sequence were to split, the claim is that for any $a,b$, you can find $g_{a,b}\in C[0,1]$ such that $g(0)=a$, $g(1)=b$ and, more importantly, the map is a $*$-homomorphism: that is, $$g_{a_1+a_1,b_1+b_2}-g_{a_1,b_1}+g_{a_2,b_2}, \ \ \ g_{a_1a_2,b_1b_2}=g_{a_1,b_1}g_{a_2,b_2}.$$
I wouldn't know how to try to construct such an assignment, nor to check that it is possible.
But there are equivalent conditions to the existence of sections. If you had a right section, that means that the sequence splits (hence the name): that is, you should have
$$
C[0,1]\simeq C_0(0,1)\oplus\mathbb C^2.
$$
This is impossible, since the algebra on the left has two projections, while the algebra on the right has four. So the sequence does not split as algebras, you don't even need C$^*$-algebras.


Sharepoint Designer XLST XSL IF/Choose Statement

Question: Can anyone tell me what is wrong with this code I'm using in SharePoint Designer:
<xsl:choose>
    <xsl:when test="number((ddwrt:DateTimeTick(ddwrt:GenDisplayName(string(ddwrt:Today())))- (ddwrt:DateTimeTick(ddwrt:GenDisplayName(string(@Date_x0020_only))))) div 864000000000) >  7 div 864000000000 and <= 14 div 864000000000">

  WEEK 1
            <xsl:text xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" ddwrt:whitespace-preserve="yes" xml:space="preserve"> </xsl:text>

    </xsl:when>
</xsl:choose>

It works if I take out the <= 14 div 864000000000 part but I'm essentially trying to label something if it's aged between 7 and <=14 days but can't seem to get this to work.
Here is the error:
SharePoint Designer cannot render the XSLT in this Data View. Try to undo your changes or re-insert the Data View.

Failed setting processor stylesheet : 0x80004005 : Expression expected. number((ddwrt:DateTimeTick(ddwrt:GenDisplayName(string(ddwrt:Today())))- (ddwrt:DateTimeTick(ddwrt:GenDisplayName(string(@Date_x0020_only))))) div 864000000000) > 7 div 864000000000 and --><=<-- 14 div 864000000000

Updated:
Thanks you very much @matthias_h and @Jason Aller
So here is the code I ended up using:
<xsl:variable name="X"

                        select="number((ddwrt:DateTimeTick(ddwrt:GenDisplayName(
                        string(ddwrt:Today())))-(ddwrt:DateTimeTick(ddwrt:GenDisplayName(
                        string(@Date_x0020_only))))) div 864000000000)">

                </xsl:variable>

            <xsl:if test="$X > 0 div 864000000000 and $X <= 7 div 864000000000">

                <xsl:text> WEEK 1</xsl:text>

            </xsl:if>

            <xsl:if test="$X > 7 div 864000000000 and $X <= 14 div 864000000000">

                <xsl:text> WEEK 2</xsl:text>

            </xsl:if>

            <xsl:if test="$X > 14 div 864000000000 and $X <= 21 div 864000000000">

                <xsl:text> WEEK 3</xsl:text>

            </xsl:if>

            <xsl:if test="$X > 21 div 864000000000">

                <xsl:text> Escalation</xsl:text>

            </xsl:if>

So this works now in the Sharepoint designer preview section it looks like this:
11/7/2014 11:56 AM Escalation
11/7/2014 11:56 AM Escalation
11/7/2014 11:56 AM Escalation
11/26/2014 8:47 AM Escalation
12/18/2014 3:10 PM WEEK 2
But is showing up in the browser like this:
11/7/2014 11:56 AM  Escalation
11/7/2014 11:56 AM  Escalation
11/7/2014 11:56 AM  Escalation
11/26/2014 8:47 AM  Escalation
12/18/2014 3:10 PM  Escalation
12/29/2014 1:48 PM  Escalation
For some reason its calling them all escalation.  Any suggestions?
I really appreciate the help.
Update 2
Thanks @matthias_h
To answer your questions:
1.) Yes it is correct in SPD preview but incorrect in the browser.
2.) This is what the value is in SPD
11/7/2014 11:56 AM Escalation 0.00000000006134259259259259
11/7/2014 11:56 AM Escalation 0.00000000006134259259259259
11/7/2014 11:56 AM Escalation 0.00000000006134259259259259
11/26/2014 8:47 AM Escalation 0.00000000003935185185185185
12/18/2014 3:10 PM WEEK 2     0.000000000013888888888888888
These are what the values look like in Browser
11/7/2014 11:56 AM   Escalation  53
11/7/2014 11:56 AM   Escalation  53
11/7/2014 11:56 AM   Escalation  53
11/26/2014 8:47 AM   Escalation  34
12/18/2014 3:10 PM   Escalation  12
You think it has something to do with me divided everything by 864000000000?
The reason I did that is becuase it wasn't diplaying the date difference properly in the browser.
So I used this solution: http://sympmarc.com/2013/01/page/2/
Again thanks for the help
Comment: Could you please show more of the stylesheet and the XML input, too? This would enable us to reproduce your problem. Thanks!
Comment: Have you considered setting up a `` to hold the portion encased in `number()` and performing a comparison in the form `var > 7 and var <= 14`?
Comment: Two questions to understand the issue in the updated code - 1) is the preview output ok and only the browser output wrong and 2) what is the value of `$X`? Can you print it out with `<xsl:value-of select="$X/>' as test after it's declared and check if you get diff values on preview and browser?
Comment: Sorry @matthias_h Please see the original post update 2.  I'm new to this forum and am not sure how I can format text properly in the comment section.
Comment: Don't mind, no need for excuses. You can click `help` below the _Add Comment_ button to get info about formatting, and btw it's always better to add additional information to the original post instead as comment, so people can see the full question including updates instead of having to go to the comments. Also, it should be avoided to have extended discussion in comments and to use SO chat instead, but for using this feature you need a reputation of 20. I just check the update, but maybe it's better to add this as a new question because the first question is solved and this is a follow-up.
Comment: To avoid misunderstandings: the value of `$x` in the preview is `0.000000000013888888888888888`, and the same `$x` in the browser is `12` ?
Comment: Yes. It's apparently a weird issue with sharepoint designer and sharepoint server. The reason I made my formula using the 864,000,000,000 is because in the browser it would show up as the decimal value.  This is the original solution I used to fix the issue and might clarify the problem: http://sympmarc.com/2013/01/07/calculate-days-between-two-sharepoint-list-dates-in-xsl/
Comment: If I don't need to use that method I would prefer not to but it seems to be my only solution.
Comment: I've checked the mentioned sharepoint links and can't give any advice as I'm more into xslt and not SP and would need more info (e.g. if it's possible to differentiate in SP between SPD view and browser view or, if not, if it would be ok to have the correct results only in browser view etc.), but I recommend the following: your xslt issue is already solved, now you have a specific SP problem. Put this in a _new question_ with a new specific title as now it's a diff issue. Then it's easier to get more attention that there is a new problem to solve as this question is already marked as answered
Comment: @matthias_h sounds like a plan. I appreciate all the help you've given me. Thanks a lot.
Answer: I can't test the full expression because of missing namespace and functions, but I think there is following syntactical error, just as example:
<xsl:when test="value > 14 and < 7">

should be
<xsl:when test="value > 14 and value < 7">

I suggest - for readability to have the expression in the number()  as variable, e.g.
<xsl:variable name="testString"
      select="number((ddwrt:DateTimeTick(ddwrt:GenDisplayName(
      string(ddwrt:Today())))-(ddwrt:DateTimeTick(ddwrt:GenDisplayName(
      string(@Date_x0020_only))))) div 864000000000)">

and then to check if
<xsl:when test="$testString > 7 div 864000000000
                and $testString <= 14 div 864000000000">

will work.
Also, if you have no xsl:otherwise or other xsl:when cases, you could adjust to xsl:if instead.
Comment: wow.  Thanks @matthias_h

That was way easier then what I had.  I am a beginner when it comes to coding so forgive my formatting of code.

Here is what I ended up doing:

Tried to post the code but its too long.  I will edit my original post so you can see.

My new problem now though is that it works perfectly in sharepoint designer, that is when i see it in the preview section, but it says the same thing for each row in the browser.  All of them say escalation.  Is there something im doing wrong?


Determine which CSS Framework is used with Selenium

Question: I am writing a Programm which crawls through various Webpages and does some tests using Selenium.
Now I want to find out which CSS Frameworks are used on these Websites to get some statistics.
Right now I just check with the FireFox Webdriver if on there are .css Files linked in the page which have the name of a specific Framework:
 Iterator<WebElement> divWebElementIteratorCSS = webDriver.findElements(By.xpath("//link[@rel='stylesheet']")).iterator();
and then I check if the name of the found .css Files contains the name of one of the CSS Frameworks I would like to check:
if ( src.contains( frameWorkName ) && cssFrameWorks.get( frameWorkName ) == false ) {
    result.addAttribute("Framework", "STRING", frameWorkName);
    result.setPercent( 100 );
    result.setSuccessful( true );
    cssFrameWorks.put( frameWorkName, true );
}

The Hashmap frameWorkName contains all the names of the Frameworks I am interested in.
Now my problem: If the administrator of the site renamed the .css file of the framework, my test does not work! Is there a safe way to check this, which works even if the .css has a different name?
Comment: what is a "CSS framework"? Do you have an example?
Comment: Something like Bootstrap, Foundation or YAML!
Comment: Why do you need to know this information? What use does it have to you, whether they used YAML or something else?
Comment: My boss wants to have a statistic, which frameworks are used for responsive design support by our partners (there are way to many to do it manually or just ask).
Answer: I think @AaronDigulla's answer is pretty clear.
An alternative that I can think of though, is when you iterate through those, do a GET on that css file, then do a quick scan through the documentation at the beginning.  For example, a CSS file might contain...
/*  CSS Framework vX.X
 *  Author: Some Author
 *  License:
 *    Some ridiculously long license
 */

This would alleviate your file name changes issue.
Answer: I know no reliable way to determine which CSS (or JavaScript) frameworks are being used in a web site.
If you're lucky, then the admins will use a global URL (like the CDN links provided by jQuery).
When people start to rename files, you can try to download the CSS file and fingerprint it (create a checksum).
That will fail, of course, when people change those files. This can happen automatically; wro4j is a framework that will compile all JavaScript and CSS resources into one big file each automatically.
I'm also a bit worried why you would need this information. Instead of trying to figure out which framework is being used (and which version) look for the actual CSS styles that are being applied which might influence your tests.


Dimension of minimal sufficient statistic

Question: Is this true that "dimension of every minimal sufficient statistic is less than any sufficient statistic (minimal or not)"?
Comment: if by "less" you mean "less than or equal to" this is correct since _a minimal sufficient statistic is a function of any sufficient statistic_.
Comment: @Xi'an: This looks like n answer, could you make it one?  https://stats.meta.stackexchange.com/questions/5402/is-a-quick-and-dirty-answer-better-than-no-answer/5411#5411
Answer: Since a minimal sufficient statistic$$T:\mathcal X\longmapsto \mathbb R^p$$is (i) sufficient and (ii) a function of every sufficient statistic$$S:\mathcal X\longmapsto \mathbb R^q$$that is, there exists $$t:\mathbb R^p\longmapsto \mathbb R^q$$ such that$$T(x)=t(S(x))$$it is necessary that$$p\le q$$Otherwise, if $p>q$, since $T(X)$ belongs to the $q$-dimensional manifold$$t(\mathbb R^q) = \{\tau;~\tau=t(s),\ s\in\mathbb R^q\}\subset\mathbb R^p$$there exists a reparameterisation of $T$ of dimension $q$.


Why does unet have classes?

Question: import torch
import torch.nn as nn
import torch.nn.functional as F

class double_conv(nn.Module):
    '''(conv => BN => ReLU) * 2'''
    def __init__(self, in_ch, out_ch):
        super(double_conv, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_ch, out_ch, 3, padding=1),
            nn.BatchNorm2d(out_ch),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_ch, out_ch, 3, padding=1),
            nn.BatchNorm2d(out_ch),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        x = self.conv(x)
        return x

class inconv(nn.Module):
    def __init__(self, in_ch, out_ch):
        super(inconv, self).__init__()
        self.conv = double_conv(in_ch, out_ch)

    def forward(self, x):
        x = self.conv(x)
        return x

class down(nn.Module):
    def __init__(self, in_ch, out_ch):
        super(down, self).__init__()
        self.mpconv = nn.Sequential(
            nn.MaxPool2d(2),
            double_conv(in_ch, out_ch)
        )

    def forward(self, x):
        x = self.mpconv(x)
        return x

class up(nn.Module):
    def __init__(self, in_ch, out_ch, bilinear=True):
        super(up, self).__init__()

        #  would be a nice idea if the upsampling could be learned too,
        #  but my machine do not have enough memory to handle all those weights
        if bilinear:
            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
        else:
            self.up = nn.ConvTranspose2d(in_ch//2, in_ch//2, 2, stride=2)

        self.conv = double_conv(in_ch, out_ch)

    def forward(self, x1, x2):
        x1 = self.up(x1)
        diffX = x1.size()[2] - x2.size()[2]
        diffY = x1.size()[3] - x2.size()[3]
        x2 = F.pad(x2, (diffX // 2, int(diffX / 2),
                        diffY // 2, int(diffY / 2)))
        x = torch.cat([x2, x1], dim=1)
        x = self.conv(x)
        return x

class outconv(nn.Module):
    def __init__(self, in_ch, out_ch):
        super(outconv, self).__init__()
        self.conv = nn.Conv2d(in_ch, out_ch, 1)

    def forward(self, x):
        x = self.conv(x)
        return x

class UNet(nn.Module):
    def __init__(self, n_channels, n_classes):
        super(UNet, self).__init__()
        self.inc = inconv(n_channels, 64)
        self.down1 = down(64, 128)
        self.down2 = down(128, 256)
        self.down3 = down(256, 512)
        self.down4 = down(512, 512)
        self.up1 = up(1024, 256)
        self.up2 = up(512, 128)
        self.up3 = up(256, 64)
        self.up4 = up(128, 64)
        self.outc = outconv(64, n_classes)

    def forward(self, x):
        self.x1 = self.inc(x)
        self.x2 = self.down1(self.x1)
        self.x3 = self.down2(self.x2)
        self.x4 = self.down3(self.x3)
        self.x5 = self.down4(self.x4)
        self.x6 = self.up1(self.x5, self.x4)
        self.x7 = self.up2(self.x6, self.x3)
        self.x8 = self.up3(self.x7, self.x2)
        self.x9 = self.up4(self.x8, self.x1)
        self.y = self.outc(self.x9)
        return self.y

When I was reading UNet architecture I have found that it has n_classes as output.
class UNet(nn.Module):
    def __init__(self, n_channels, n_classes):

but why does it have n_classes as it is used for image segmentation?
I am trying to use this code for image denoising and I couldn't figure out what will should the n_classes parameter be, because I don't have any classes.
Does n_classes signify multiclass segmentation? If so, what is the output of binary UNet segmentation?
Answer: Answer

Does n_classes signify multiclass segmentation?

Yes, if you specify n_classes=4 it will output a (batch, 4, width, height) shaped tensor, where each pixel can be segmented as one of 4 classes. Also one should use torch.nn.CrossEntropyLoss for training.

If so, what is the output of binary UNet segmentation?

If you want to use binary segmentation you'd specify n_classes=1 (either 0 for black or 1 for white) and use torch.nn.BCEWithLogitsLoss

I am trying to use this code for image denoising and I couldn't figure out what will should the n_classes parameter be

It should be equal to n_channels, usually 3 for RGB or 1 for grayscale. If you want to teach this model to denoise an image you should:

Add some noise to the image (e.g. using torchvision.transforms)
Use sigmoid activation at the end as the pixels will have value between 0 and 1 (unless normalized)
Use torch.nn.MSELoss for training

Why sigmoid?
Because [0,255] pixel range is represented as [0, 1] pixel value (without normalization at least). sigmoid does exactly that - squashes value into [0, 1] range, hence linear outputs (logits) can have a range from -inf to +inf.

Why not a linear output and a clamp?

In order for the Linear layer to be in [0, 1] range after clamp possible output values from Linear would have to be greater than 0 (logits range to fit the target: [0, +inf])

Why not a linear output without a clamp?

Logits outputted would have to be within [0, 1] range

Why not some other method?

You could do that, but the idea of sigmoid is:

help neural network (any logit value can be outputted)
first derivative of sigmoid is gaussian standard normal, hence it models the probability of many real-life occurring phenomena (see also here for more)
Comment: I saw this sigmoid final layer several times, and I can't figure it out. Why not a linear output and a clamp? Why not a linear output without a clamp? Why not some other method?
Comment: @Gulzar updated my answer, does it make more sense?
Comment: I don't understand what logits have to do with a linear layer output. If there is no sigmoid, and the output physics is really pixel intensity, there is no point that I see going through a logistic function. For example, the very basic autoencoder examples online on MNIST also work with a linear final layer (or with sigmoid), and linear layers don't have vanishing gradients problems. So, I still don't understand the use of sigmoid for non logistic data.
Comment: @Gulzar it has nothing to do with vanishing gradient. In case of classification logits are the outputs from linear layer (sigmoid transforms logits into probabilities). Those are in the +/- infinity range. Your pixel values are [0, 1] and you use MSE as a criterion (unless pixels are only 0 and 1 which is usually not the case). Your neural network can output any real value and sigmoid will simply squash it, hence __it does not have to output bounded values between 0 and 1__ (as this task is much harder and easy to get wrong, e.g. predict pixel value being 1.02, obviously wrong).
Comment: @Gulzar remember that end goal of OP is denoising instead of segmentation, in case of segmentation appropriate loss is enough in PyTorch.

Why does unet have classes?


What can i do with a stack in openslack

Question: I am wondering what is a stack in openslack.
It seems to be components (network, containers and stuff)
Can i mix thoses items with docker containers for example ?
Thanks
Answer: OpenStack version of AWS cloudformation (infrastructure as a code) is performed trough HEAT (OpenStack Component). A "stack" is a set of resources that can be deployed in the cloud. What are those resources ?: Everything that can be created withing the cloud environment:
- A network port...
- A set of instances (virtual machines).
- A load balancer.
- A storage device (block or object).
Basically, you use a template (or a set of templates) in order to create a complete infrastructure inside the cloud (database servers, web servers, a load balancer for the web servers, maybe the storage too... etc.).
The template uses a common language to define those components and how are they created in the cloud.
Note that, many "AWS Cloudformation" objects can be defined in OpenStack HEAT templates, but, HEAT also has it's very own set of objects definitions for OpenStack.
At the end of my site you will find a sample HEAT template for a stack that include servers, loadbalancer and autoscalling:
https://tigerlinux.github.io/recipes/openstack/index.html
Also, more examples directly from the OpenStack community:
https://git.openstack.org/cgit/openstack/heat-templates/tree/hot

What can i do with a stack in openslack


PowerBI - How to set thousands separator from DB imported tables

Question: Im having issue with PowerBi Dashboard setup. I have imported the data from mssql tables and i want to display numbers with thousands separators to increase readability.
Like: 248754728457 to 248,754,728,457
enter image description here
I really digged through the internet and many stack pages but without a luck. Either have no option in specific tab or other thing.
May you help me?
Answer: Alright i finally found it. Maybe it helps somebody:
I went into edit powerquery and set each column as fixed decimal number and applied
then i went into data view (from report view) into column view
then i clicked on the column change its format to decimal number and clicked comma button below as separator.


Create a document in Firestore that includes a reference to an existing document in another collection

Question: I'm attempting to post new documents to a collection which contain references to existing documents.
Here is my code:
var admin = require('firebase-admin');
var serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://DBURL.firebaseio.com'
});

var db = admin.firestore();

db.collection('myFunCollection').add({
  someBool: false,
  someNumber: 13.2,
  video: 'videos/Izdm35CsW6kqv2UxZEX0',
  user: 'users/pb7La4kzEaBow4iWvmxZ'
});

video and user reference existing documents in other collections, but when I run this code, the fields are stored as strings rather than references. The documentation notably does not describe how to do this.
How can I post these values as references?
Answer: Figured it out – by using "db.doc('{path}')"
var admin = require('firebase-admin');
var serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://DBURL.firebaseio.com'
});

var db = admin.firestore();

db.collection('myFunCollection').add({
  someBool: false,
  someNumber: 13.2,
  video: db.doc('videos/Izdm35CsW6kqv2UxZEX0'),
  user: db.doc('users/pb7La4kzEaBow4iWvmxZ')
});


Nginx Clean URLs don't work

Question: I tried this: How do I enable clean URLs with Nginx?
And I tried this: https://www.digitalocean.com/community/questions/how-do-i-enable-clean-urls-with-nginx-for-drupal
So, I tried these:
 location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/var/run/php-fpm.sock; # fastcgi_pass unix:/tmp/php5-fpm.sock;
 }

And I tried these:
server {
     listen       80;
     server_name  example.org;

     location / {
         root   /path/to/drupal;
         index  index.php;
         error_page 404 = @drupal;
     }

     location @drupal {
         rewrite ^(.*)$ /index.php?q=$1 last;
     }
 }

And clean URL's don't work. The site runs at ip address in a subdir 127.0.0.1/dev
It has its own config at /etc/nginx/sites-available/dev and symlinked to /etc/nginx/sites-enabled/dev
This is my current sites-available/default config:
 root /var/www;

 # Add index.php to the list if you are using PHP
 index index.html index.htm index.php;

 server_name _;

 location / {
 # First attempt to serve request as file, then
 # as directory, then fall back to displaying a 404.
 # try_files $uri $uri/ =404;
 try_files $uri $uri/ @rewrite;
 expires max;
 }

 location @rewrite {
   # Some modules enforce no slash (/) at the end of the URL
   # Else this rewrite block wouldn't be needed (GlobalRedirect)
   rewrite ^/(.*)$ /index.php?q=$1;
 }

 # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
 #
 location ~ \.php$ {
 include snippets/fastcgi-php.conf;

 # With php7.0-cgi alone:
 # fastcgi_pass 127.0.0.1:9000;
 # With php7.0-fpm:

 fastcgi_pass unix:/run/php/php7.0-fpm.sock;

 }

 # deny access to .htaccess files, if Apache's document root
 # concurs with nginx's one
 #
 location ~ /\.ht {
  deny all;
 }
}

This is my current sites-available/dev config:
server {

        server_name dev;
        root /var/www/dev; ## <-- Your only path reference.

        # Enable compression, this will help if you have for instance advagg module
        # by serving Gzip versions of the files.
        gzip_static on;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        # This matters if you use drush prior to 5.x
        # After 5.x backups are stored outside the Drupal install.
        #location = /backup {
        #        deny all;
        #}

        # Very rarely should these ever be accessed outside of your lan
        location ~* \.(txt|log)$ {
                allow 192.168.0.0/16;
                deny all;
        }

        location ~ \..*/.*\.php$ {
                return 403;
        }

        # No no for private
        location ~ ^/sites/.*/private/ {
                return 403;
        }

        # Block access to "hidden" files and directories whose names begin with a
        # period. This includes directories used by version control systems such
        # as Subversion or Git to store control files.
        location ~ (^|/)\. {
                return 403;
        }

  location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
 }

        # Fighting with Styles? This little gem is amazing.
        # This is for D6
        #location ~ ^/sites/.*/files/imagecache/ {
        # This is for D7 and D8
        location ~ ^/sites/.*/files/styles/ {
                try_files $uri @rewrite;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }

}

I restart nginx server by running sudo service nginx restart
Comment: what message do you get in your clean URLs config page? admin/config/search/clean-urls
Comment: that test failed, default message
Answer: Your question is about Drupal 7 right ? Try replacing
# For Drupal <= 6
location / {
    index index.php;
    try_files $uri $uri/ @rewrite;
    expires max;
  }

by
# For Drupal >= 7
location / {
    try_files $uri /index.php?$query_string;
}

Then reload nginx.
This is a full example working vhost fir Drupal 7 :
server {

    listen 18.104.22.168:8000;
    server_name example.com www.example.com
    root /var/www/example.com /web;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }
    #Drupal private folder (see https://github.com/perusio/drupal-with-nginx#private-file-handling)
    location ^~ /sites/default/protected {
      internal;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
        allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        try_files $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        # Block httpoxy attacks. See https://httpoxy.org/.
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_read_timeout 180;
        # PHP 7 socket location (change it to fit your config)
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    # Fighting with Styles? This little gem is amazing.
    location ~ ^/sites/.*/files/styles/ {
        try_files $uri @rewrite;
    }

    # Handle private files through Drupal. Private file's path can come
    # with a language prefix.
    location ~ ^(/[a-z\-]+)?/system/files/ {
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}

Comment: Why is 'listen' set to '126.96.36.199:8000' what's that? If I enter my server IP nginx won't restart. also what's '/web' part? Anyway I tried your config, but it breaks site now. CSS files won't load for example.
Comment: You have to change both IP and port accordingly to your config. By default port 80. I'm behind Varnish, this is why I wrote port 8000 in my example, sorry if it confused you.
Comment: I don't access the website via domain. I enter it via IP address e.g. http://127.0.0.1/dev and if I do that css files won't load and site loads all text in white. so I have to comment out the listen part to fix it. E.g. "listen 127.0.0.1:80;" (IP edited of course) and don't you need semi-colon at the end? It's not in your code. And clean urls still dont pass the test.
Comment: This is a bit out of the scope of your question :) I can't fully setup your remote  install, try to put these parameters in the server part at the beginning : `listen YOUR_SERVER_IP:80;`, then below `listen 80;`, then below if it was working `server_name dev;`, and below `root /var/www/dev;` , then the rest on sample nginx vhost.
Comment: awesome, works for drupal 7. Finally removed that annoying `?q`! Thanks for sharing

Nginx Clean URLs don't work


Ler arquivos em python

Question: bom... eu tenho um arquivo com as seguintes coisas :
if
else
(
)
'
"
print

e o seguinte codigo :
arq = open('system/commands.txt','r')
arquivo = arq.readlines()
for l in range(0,7):
    print(arquivo[l])

palavra = input('Digite a palavra : ')

if palavra == arquivo[l]:
    print('certo !')

e queria saber como eu faço quando eu digitar a palavra que está escrita no arquivo ele aparecer o print('certo'),
no caso o comando acima nao está funcionando e queria saber o por que !
o comando vai até a parte do input depois não acontece nada
Comment: 0 1 2 3 4 5 6 7, é inclusivo o 0 do range, fica esperto.
Answer: O problema está relacionado com a sua variável l; Ela é definida pelo for:
for l in range(0,7):
    print(arquivo[l])

Quando este for executa, a variável l vai incrementando de 0 a 6 e o print vai imprimir as 7 linhas do arquivo na tela. Em seguida, a variável l usada no for ficará com o último valor que ela assumiu, ou seja, 6.
Continuando o programa, mais abaixo você faz uma comparação:
if palavra == arquivo[l]:

Esta linha está comparando a palavra digitada com a sétima palavra da lista arquivo, pois o valor de l é 6, que é o valor que ficou de sobra nesta variável ao terminar o for acima;
Ou seja, arquivo[l] é equivalente a arquivo[6] (pois o valor de l neste ponto é 6) o que é uma referência à palavra "print".
Se você digitar a palavra print, vai receber a mensagem certo; caso digite qualquer outra coisa não vai receber nenhuma mensagem.
Comment: Funcionou, mas no caso como eu faria para ele ler todos as palavras do arquivo e se for igual ele executa o print?
Comment: @HyPe para isso você teria que comparar com todas as palavras do arquivo, e não só com uma; Existem várias formas de fazer isso, uma delas seria colocar a comparação dentro do `for`, outra seria usar o operador `in`, etc

Ler arquivos em python


Spring Webflux : How to return HTTP 200 response with body when the called service returns HTTP 201 without body with WebClient?

Question: I have a microservice (Java+Spring Boot) that receives HTTP requests, and then I invoke a REST API call over HTTP to another service. The called service returns HTTP status 201(no response body), but I need to return HTTP 200 with the response body.
I am using WebClient to call the other service and for 201 status I am using bodyToMono(Void.class).
So how do I return HTTP 200 response body for the clients of my microservice? What's the best practice? Also how to write a Component Test for the service which is invoking the external service which returns HTTP 201?
Update: The current code looks like:
webClient.builder())
        .post()
        .uri("/employee")
        .body(Mono.just(employee), Employee.class)
        .retrieve()
        .onStatus(status -> status.equals(HttpStatus.NOT_FOUND), response -> Mono.just(new NotFoundException("404 occurred", HttpStatus.NOT_FOUND.name())))
        .bodyToMono(Void.class)
        .block();

Thanks
Comment: Please dont write code in comments, you can see its completly unreadable. Edit your question to include the code.
Comment: Share your code, please.
Comment: `
webClient.builder())
        .post()
        .uri("/employee")
        .body(Mono.just(employee), Employee.class)
        .retrieve()
        .onStatus(status -> status.equals(HttpStatus.NOT_FOUND), response -> Mono.just(new NotFoundException("404 occurred", HttpStatus.NOT_FOUND.name())))
        .bodyToMono(Void.class)
        .block();

`
Comment: Please don't use `.block()` in reactive stack unless you have a really good reason.
Comment: @JoãoDias, correct
Comment: @Toerktumlare, apologies, I will update the post
Answer: If I understand your problem. I think solving like this.
           WebClient
            .builder()
            .build()
            .post()
            .uri("/employee")
            .exchange()
            .flatMap(response -> {
                return response
                        .mutate()
                        .body("success")
                        .build()
                        .bodyToMono(String.class);
            });

Comment: Please do not include new requirements "as you go" as it will make it impossible to answer the question. You ask one question and get one answer. By including new requirements tells us you have not done proper research before asking, not thought out your question and that all you want is a "copy paste solution"
Comment: thanks for the code snippet. I am also throwing Exception in case of 404. Also I need to return a custom object not string.
Comment: @Diego Rocha, thanks for the code snippet, however if i want to the body to return is not a string class, but a Custom Class like MyResponse?


95% confidence interval for mean of a large sample

Question: I have a large sample of experimental observations for different categories (specifically, the runtime of an algorithm in different scenarios). I want to plot the mean runtime for each category/scenario and also show the 95% confidence interval using R.
According to the central limit theorem, the mean of each category should be normally distributed (because it is based on a large number of independent observations).
I know how to plot the means as scatter plot and how to add error bars. I'm just unsure about the 95% confidence interval. The 95% confidence interval is the interval in which a new value lays with 95% probability? Or is only the actual mean in the interval with 95% probability?
I found this code on calculating the confidence interval:
error <- qnorm(0.975)*sd/sqrt(n)

Where n is the sample size and sd is the standard deviation. Unfortunately, it lacks further explanation. What exactly is qnorm(0.975) and why do we choose 0.975 to get the 95% confidence interval?
Comment: Requests for statistical tutoring belong on CrossValidated.com
Comment: Also see `?qnorm` and maybe the [Wikipedia Simple English page for confidence intervals](https://simple.wikipedia.org/wiki/Confidence_interval). While this is certainly topically more appropriate for crossvalidated, I think they appreciate users who do a bit of background reading as much as we do.
Answer: qnorm is the quantile function for the normal distribution.  More details are available by typing ?qnorm.  You pick 0.975 to get a two-sided confidence interval.  This gives 2.5% of the probability in the upper tail and 2.5% in the lower tail,  as in the picture.
Answer:
The 95% confidence interval is the interval in which a new value lays with 95% probability?

No. If you sample very often and compute a 95%-CI every time, than the true value will be within 95% of those confidence intervalls. Sound disturbing? It is.
The standard deviation of the mean is called it's 'standard error'.
The qnorm-part has been explained by G5W.
Comment: With "true value" you mean the actual mean as opposed to the sample mean, right?
Comment: Right. Be carefull not to mix standard deviation of a distribution and standard error of the mean up. They are very different. If you want to go deeper into what a confidence intercal is and is not - if you really, really want that, read the "cookie" answer from Keith Winstein in this thread: http://stats.stackexchange.com/questions/2272/whats-the-difference-between-a-confidence-interval-and-a-credible-interval
Comment: Is there a difference between the standard error of the mean and the confidence interval?
Comment: The standard error of the mean is a single number and the confidence interval consists of two (a lower and an upper border)?
Comment: But `error <- qnorm(0.975)*sd/sqrt(n)` does compute the confidence interval doesn't it? So it's always a certain deviation from the sample mean in both directions that expresses the confidence interval, e.g., mean +/- 1? Or is it also possible that the confidence interval is not symmetric, e.g., [mean-1, mean+2]? I guess not, as we are assuming a normal distribution of the mean.
Comment: No, that calculation of `error` is not itself a confidence interval, it computes the *half-width* of the interval. If you ask me where my car is and I say the back of my car is 3.6m from the front of it, it doesn't give you much of a clue about where to start looking for it. You need two numbers (left and right end or mean and half width both work). Yes, some confidence intervals are not symmetric, but in this case a symmetric one is being discussed.


What type of VPS stats should I look for?

Question: I have a few websites that average a total of 10,000 uniques a day across my network. I also have a few mobile apps that pull xml data maybe 5,000 calls a day. My sites aren't anything major just a few wallpaper websites and few other small sites, nothing real database intensive.
I currently own a dedicated server and I feel like it's overkill for my network. I'm looking into getting a Virtual Private Server (VPS). I was just wondering what kind of stats I should be looking for to support my network of sites.
Thanks
Comment: Did you mean VPS?
Answer: Well, the easiest thing to do would be to look at your current usage on your dedicated server. Things like how much RAM it's using, disk space used, and so on, and use that as a guide for what to get on a new VPS.
One thing that I would specifically look out for is how much bandwidth you use. Dedicated boxes usually (AFAIK) have a high bandwidth limit, but VPSes usually have a smaller limit. Wallpapers also aren't exactly known for being bandwidth friendly either...
Since you already own a dedicated server, I'm going to assume that you have enough experience admin-ing your own server, so I'd suggest looking at 'true' VPSes that run on Xen or KVM. I help with admin-ing a (heavily loaded) OpenVZ-based VPS, and I hate the 'burstable' RAM, among other things.


product of closed sets

Question: If A and B are two closed sets of $R$  is A.B closed?
By A.B  I mean the set $\sum_{i=1}{^ n} a_ib_i$  where $a_i \in A,b_i\in B,n\in N$
How to view A.B geometrically?
I am new to this subject.Sorry if the question sounds something wrong
Comment: Are $A$ and $B$ subsets of $\mathbb R$? (or some other set on wich multiplicaton and addition are defined). What **exactly** is meant by "the set $\sum a_ib_i$"? Make that clear in your question (not in a comment).
Comment: If we have two sets and $\dim A = a, \dim B = b$, then their product will have $dim (A \times B) = a + b$. So please check again with your definition, as summation you provided is not possible in case $A$ and $B$ have different number of members (if they are finite) or are infinite.
Answer: Without further clarification from the OP, I am interpreting the question as "$A,B$ are subsets of $\mathbb{R}$, and $A \cdot B =\{ab \,| \, a\in A,b \in B\}$".
If $A,B$ are closed sets in $\mathbb{R}$ with standard topology, then $A\cdot B$ may not be closed in $\mathbb{R}$. An example is $A=\{0\} \cup \{\frac{1}{n} \,|\, n\in \mathbb{N}\}$, and $B=\mathbb{N}$,then $A \cdot B=\{0\} \cup \mathbb{Q}_{+}$, which is not closed in $\mathbb{R}$.
Comment: Thanks for your interpretation.Can u please help me to view A.B geometrically
Comment: @learningmaths. Note my definition of $A\cdot B$ is different from yours. But in the example I given, they refer to the same set since $\{0\} \cup \mathbb{Q}_+$ is closed under addition. $A \cdot B=\bigcup_{b\in B}Ab$, while $Ab$ can be viewed as a scaling of $A$. If $b\neq 0$, $x\to xb$ is homeomorphism, so $Ab$ should be closed. But the problem is that arbitrary union of closed sets may not be closed.
Answer: First, see user5527's answer.
Now, if $A$ and $B$ are closed and bounded subsets of $\mathbb R$, so that they're compact, then the answer is yes. The Cartesian product $A\times B$ is a compact subset of $\mathbb R^2$, and the set of products $A\cdot B$ is its image under a continuous map.
Comment: Oops, I just changed my user name. Sorry for the inconvenience.

product of closed sets


Cross-validation on really small datasets

Question: Let's say I have a small dataset:
data <- replicate(4,rnorm(13))

I want to test the out-of-sample predictions of a regression model as a function of increasing training set size (increasing by 10% in each increment).
I use the following procedure:
test.set <- 3

#for each iteration increase the test set by 10%
train.set <- (nrow(data)-test.set) * seq(0.1,0.9,0.1)
train.set <- train.set[train.set>1]
results <- vector()

  y=0
  for (t in train.set){
    y=y+1
    trainSize <- t
    train <- sample(1:nrow(data),trainSize)
    test <- sample(1:nrow(data),test.set)

    test.data <- data[test,]
    train.data <- data[train,]

    #fit a linear regression:
    train.data <- as.data.frame(train.data)
    model <- lm(train.data[,1] ~., data=train.data[,2:4])

    #get predictions:
    test.data <- as.data.frame(test.data)
    predictions <- predict(model,test.data)

    #calculate out of sample R squared (1-SSE/TSS):

    error <- 1 - sum( (test.data[,1] - predictions)^2 ) / ((nrow(test.data)-1) * var(test.data[,1]))

    results[y] <- error
  }

I repeat this procedure several times and take the average of the repetitions.
My problem is that I get unreliable results. I am assuming this is because the dataset is really small. What could I do to get more reasonable estimates?
Comment: Can you explain in what way your results are weird?
Comment: I rephrased it as 'unreliable'. basically the estimates are way off and the model doesn't seem to be improving with increasing training set size
Comment: basically my question is: I only have 3 instances in the test set. is that large enough to get reliable estimates? what else could I do?
Answer: (Disclaimer: I did not check the code, and that would be more appropriately asked on codereview.sx)

My problem is that I get unreliable results. I am assuming this is because the dataset is really small. What could I do to get more reasonable estimates?

There are (at least) two small sample size problems mixed here:

because you have too few training cases, your models (including the surrogate models of the cross validation) are not only bad on average, but also unstable (i.e. vary much if a few training instances are exchanged).
because you have too few test cases, your test results themselves are uncertain as well. So the results you observe may be (approximately) described as
learning curve (= average performance as function of $n_{train}$) +
model instability (= variance due to training sample size) +
test variance (= variance due to test sample size) +
testing bias (depending on how exactly you formulate your scenario, i.e. wrt. to  $n_{train}$ or  $n$)

For simulations, you can at least partially unmix the training and test sample size contributions to the total uncertainty by a reference measurement of the model performance with a separate large independent test set.
If there isn't any further data (i.e. real application, no simulation), make sure that the model itself is stable (low complexity/highly regularized and/or use an aggregated model): the instability contribution to variance is the one thing here that you can influence and you anyways need to do this, because unstable always means high generalization error. Stability can be checked by iterated/repeated cross validation or out-of-bootstrap validation. In addition, the variance contribution due to model instability cancels out over many runs of the cross/out of bootstrap validation.
Once you know that this component of the variance is negligible, you can attribute the variance you observe to the finite test sample size. Note that the $n$ is the number of distinct cases that have been tested, regardless of how many runs you did. With that, you can calculate e.g. hereconfidence intervals.
Obviously this will not reduce the uncertainty as it is fundamentally caused by too few samples - but it will allow you to judge what you can (or cannot) conclude from your data. With that (possibly + simulations), you may be able to convince you supervisor/boss/customer that more samples are needed.

I only have 3 instances in the test set. is that large enough to get reliable estimates?

Typically, no.
For classification with 0/1 loss function, the situation is even worse than for regression, and there we found that for sample sizes < 100 test cases the test error is typically so large that not much can be said at all. I'd expect the situation to be somewhat nicer for regression/calibration, but unless your are superlucky and have basically noiseless data, 3 test cases will not be sufficient to draw any kind of practical conclusions.
Here's a paper we wrote about the situation for classification:
Beleites, C. and Neugebauer, U. and Bocklitz, T. and Krafft, C. and Popp, J.: Sample size planning for classification models. Anal Chim Acta, 2013, 760, 25-33.
DOI: 10.1016/j.aca.2012.11.007
accepted manuscript on arXiv: 1211.1323

If you need to discuss in more detail, I'd be willing to help e.g. writing a shared paper about this. I'm in chemometrics, and the topic would certainly be of practical importance.
Comment: thanks a lot for your answer! Do you have any ideas what kind of techniques could be used to alleviate this problem? For example what if I do not have access to a larger sample from the same population?
Comment: please see the updated answer


Spaces in file path

Question: I'm creating a console application in C#, and I want to check if a specific file (foo.exe). But when the path contains spaces (C:\A Folder With Spaces\) it checks if foo.exe exists at this directory: C:\A.
Question: How can I check inside of a folder that contains spaces?
Comment: use the '@' sign for a string literal: @"C:\A Folder With Spaces\"
Comment: @ro-E Nope, that doesn't work
Comment: could you paste the actual code? @bramhaag
Answer: If (File.Exists(@"C:\A Folder With Spaces\foo.exe")
{
    //the @ sign makes the spaces be taken literally.
}

Answer: It looks like you are passing the name of the file as command-line parameter. In this case the split at the space is done by Windows cmd command processor when you pass C:\A Folder With Spaces\ as parameter. To fix this, enclose the file name in doublequotes:
c:\test>myprog.exe "C:\A Folder With Spaces\foo.exe"

Answer: Sounds like you're supplying the path as an argument to the console application? In which case enclose the path argument in quotes

Spaces in file path


Why is IIS 7.5 flushing file cache very often?

Question: We're running a Win 2008 R2 server with IIS 7.5 for serving image files.
It's only used for static content, and file caching has been set up to cache files for 10 minutes.
However the IIS frequently completely flushes the cache (seen by using Perfmon)
It's not application pool recycling, it's not because the TTL has expired, so now I'm at a loss :-(
I've included a screenshot of the perfmon graph where you can clearly see the issue.
Is there anywhere I can see WHY it's doing these flushes ?
(Note: I'm aware I could maybe detect it by attaching a debugger to the process, but that's not an option because it's a production server, and it cannot handle the slowdown a debugger would cause)
Answer: Finally found the answer to the problem.
We had this in our web.config for the site (despite not running any managed code on the site)
<code><caching enableKernelCache="true">
</code>
After changing this to false the IIS stopped doing these full flushes. It still flushes some files regurlarly, but it's no longer a complete flush (around 50k files stay in cache)
Our file cache hit % has increased from 5% to 33%, so this definately helps a lot.
Not sure why kernel caching causes this behaviour, but I can live with the slight overhead of caching in usermode.
Thought I'd add this as an answer to help others with similar issues.
Answer: How often are the unique URLs to the images accessed?  If the URLs haven't been fetched for 120 seconds by default, they're flushed.
See UriScavengerPeriod registry key in http://support.microsoft.com/kb/820129.

Determines the frequency of the cache scavenger. Any response or fragment that has not been accessed in the number of seconds equal to UriScavengerPeriod is flushed.
Comment: I'm not using Output caching so I thought the UriScavengerPeriod wasn't used. I will try changing it and see if it makes a difference. In general though the URLs are accessed multiple times per minute, so I don't think this is the cause. Also I'd expect it to only flush some files, rather than completely emptying the cache.
Comment: Tried increasing UriScavengerPeriod now, it didn't change anything unfortunately :-(
Comment: I forgot to mention the 2 in 10 default rule for caching.  File has to be considered hot to get into cache which is access 2 in 10 seconds.  Multiple times per minute might not be frequent enough. But that doesn't seem to be your issue since you already built cache up, then it empties.
Comment: See http.sys caching description in detail at http://blogs.iis.net/rickjames/archive/2007/11/01/fun-with-http-sys-caching.aspx.  That sawtooth graph certainly looks like something is causing the app pool to crash or recycle.

And #2 on this page is close to what you show: http://blogs.msdn.com/b/friis/archive/2011/01/12/debugging-and-tuning-http-sys-output-cache-on-w2k8r2-iis-7-5.aspx
Comment: Make sure nothing is touching the files to change them every few minutes as that could trigger a flush.
Comment: Sorry I forgot to mention I've tweaked the 2 in 10 rule, on our server it's set to 1 in 10, meaning every file goes into the cache. As for the http.sys caching description in your link, yes it looks very much like my case, however I'm not using http.sys for caching (not using output cache, using file cache) I will however attempt to switch to output caching instead, and see if it makes a difference. As for touching the files, new files are constantly uploaded to the server, and new folders are being created. No files are modified though. Could this perhaps be the cause ? And is it disablable ?


How do i create an edit button for my profile?

Question: My Question is. How can i create an button to edit my profile ?
After I click a Save button or something like that it should overwrite the information in the DB.
Thats my HTML Code:

Profil

Username:

<?php echo $username; ?>

Password:

*******

Lohn 1.Lehrjahr:

<?php echo $salary_first_year; ?>

Lohn 2.Lehrjahr:

<?php echo $salary_second_year; ?>

Lohn 3.Lehrjahr:

<?php echo $salary_third_year; ?>

Lohn 4.Lehrjahr:

<?php echo $salary_fourth_year; ?>

         <button class="btn_edit" onclick="">EDIT</button>

It should appear textboxes when I click on the button.
Comment: your buttons is already on the place, it's at the bottom of your code `...`. Just bind corresponding `onclick` event, and you are fully done.
Comment: Then you need to deal with a page reload. You could create a link to another view, which would be your edit view... Edit on that page you can display the whole user content in input fields and edit them
Comment: I want to perform this just with php, no javascript.
Comment: Don't know how i should code this onclick event.
Comment: As farside stated thats what you should do, but do you know javascript? I see your tag has php and html so you want to perform this specifically with php?
Comment: @j.walt you need to handle it with javascript or with PHP. Just learn some basics.
Comment: J.Walt, neither do I. It's totally up to you how to code this logic, and what it should contain. You may read a bit of [information here](http://stackoverflow.com/questions/1525664/jquery-how-to-bind-onclick-event-to-dynamically-added-html-element) or at other answers. You are asking about very basic things in JS.
Comment: can you please edit your question to give more information and what do you want with the information? Stored in DB or simply echo on screen? And what did you try so far with **php** to make it succeed
Comment: @j.walt, find [my answer](http://stackoverflow.com/a/37158378/4354249) below. it contains some references you need to read first, before asking really trivial, basic things.
Comment: @noa-dev, you advice is not really good. because with href - the form contents would be lost, it simply would redirect the guy to your URL. Find out my answer with the form submit below.
Comment: @Farside I would expect to print out the user data on the edit page as well, so actually no information would be lost. If he wants to do everything in PHP he wont come around a page reload which either would result in a new query request to fetch data OR to read data from stored session variables
Answer: There are two ways to proceed for you, and both would require reading and learning, as it seems you gotten really basic knowledge how PHP works and how JS works.

you may create the simple form, with submit button, which will submit to PHP handler and will reload the page.
You can write JavaScript handler onclick, and to bind it to your button, and it will do the job via AJAX call, without reloading of page.

Hope this helps you start with some education first. Start here => PHP Manual: Dealing with Forms
Answer: You could have your profile displayed in a span with editable false. Then when you click the button it can check user creds on the db and set editable true. Next you will need a save button where the user can update the profile vale that was initially displayed in the span.
More specifically and less dangerously you can have a button to upload a new profile image or something like that...alternatively you could hit the edit button and change all the displayed values to input fields. There really are a lot of way's to go about it, what specifically have you tried so far in php?
if (userAuth && UserEditProfile){
    echo editablePage;
}else{
    echo profile;
}

Comment: That was kind of my idea. but I dont know exactly how this could be done. How can i change the displayed values to input fields ?
Comment: You can check user credentials against a database and then redirect to a supplementary page that has the display fields replaced with handles.


Mustache null value

Question: I have an array of objects which have a key with a value that can be either true, false or null.
var a = [
            {
                something: true
            },
            {
                something: false
            },
            {
                something: null
            }
        ];

And Mustache should cover all of those cases in different way.
For example, for true it should print:
 true

For false:

false

and for null:
 null

Is there a way to write an if/else statement for 3 different types of values in Mustache?
Comment: You probably want to use functions in the Mustache hash. Check [this example](https://github.com/janl/mustache.js/#functions).
Answer: A simpler way is like this:
{{#parentId}}{{.}}{{/parentId}}{{^parentId}}null{{/parentId}}

In the above example, parentId is output if it has a value, and the literal text null is output if it is not.
Answer: I've used Mustache functions to solve it. You can add a method to the object that will be passed to the Mustache.render method:
Basically you need to iterate through the object to add new method, so you end up with something like this:
var a = [
            {
                something: true,
                somemethod: function () {
                    return function (text) {
                        if (this.something === null) {
                            return "
" + text + "
";
                        } else if (!this.something) {
                            return "" + text + "";
                        } else {
                            return "" + text + "";
                        }
                    }
                }
            },
            {
                something: false,
                somemethod: function () {
                    return function (text) {
                        if (this.something === null) {
                            return "
" + text + "
";
                        } else if (!this.something) {
                            return "" + text + "";
                        } else {
                            return "" + text + "";
                        }
                    }
                }
            }
        ];

And later on you can use the following in the template:
{{#somemethod}}this text will be used{{/somemethod}}

Mustache null value


File not found exception in Windows C#

Question: The application runs well the first time when I open a file, read its content and save it. But when I open the same file again, I get a file-not-found exception. How do I refresh the stream?
FileStream usrFs = null;
try
{
    usrFs = new FileStream(xmlSource, FileMode.Open, FileAccess.Read,
    FileShare.ReadWrite);
}
catch (IOException)
{
    MessageBox.Show("File not found in the specified path");
}

XML
<?xml version="1.0"?>
<MenuItem BasePath="c:\SampleApplication">

Stack trace
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at SampleApplication.MainForm.ProcessDocument(BackgroundWorker worker, DoWorkEventArgs e) in C:\Users\273714\Desktop\CRAFTLite - VSTS\SampleApplication\MainForm.cs:line 179

Comment: can You provide us with full track of exception?
Comment: post the `StackTrace` of the exception
Comment: Do you start another process and use it or just close and run it again?
Comment: i dont close the application. i just run it again.
when i close the application and run, i dont get the error.
Answer: You can try this:
    using (FileStream usrFs = new FileStream(xmlSource, FileMode.Open,
      FileAccess.Read, FileShare.ReadWrite)
     {
       ...
     }

Answer: After reading the file, when you have finished reading or writing, close the filestream...
finally
{
   fileStream.Close();
}

And  IOEXCEPTIONS WILL be of different types and you are just displaying message that file not found. In your case, the exception will not be file not found... It will be file already open by another process.
Comment: tried adding finally..even then am getting same error while opening previously opened file
Answer: You're getting an IOException which can be caused by a number of issues.  If you want to check for the file not being found you should check for System.IO.FileNotFoundException.  Without any additional information, it's difficult to tell exactly what is causing the problem.
One issue is that currently you're not closing the filestream.  You need to call usrFs.Close() in a finally method.  Or better yet, use the using keyword to ensure the file is closed.
using( var usrFs = new FileStream(xmlSource, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )
{
    // do things here
}
// usrFs is closed here, regardless of any exceptions.

Comment: i get cannot implement type system.io.filestream when i use the above

File not found exception in Windows C#