Evaluate: $\tan^2 \frac{\pi}{18}+\tan^2 \frac{5\pi}{18}+\tan^2 \frac{7\pi}{18}$

Question: Evaluate:    $$\tan^2 \frac{\pi}{18}+\tan^2 \frac{5\pi}{18}+\tan^2 \frac{7\pi}{18}$$
Tried in various ways but to no avail ,
$$\tan\left(\frac{\pi}{2}-\frac{2\pi}{18}\right) = \tan^2 \frac{7\pi}{18}$$,
$$\tan\left(\frac{\pi}{2}-\frac{4\pi}{18}\right) = \tan^2 \frac{5\pi}{18}$$,
$$\tan\left(\frac{\pi}{2}-\frac{8\pi}{18}\right) = \tan^2 \frac{\pi}{18}$$
Comment: @lonestudent: Compare [Guidelines for context edits and rewrites](https://math.meta.stackexchange.com/q/32402/42969) on meta, in particular "Do not expand the question with so much context that it changes fundamentally." and "What sort of context can be edited into a question?"
Comment: @lonestudent I do not see any comments in which the *original asker* of the question indicates that your edits are in line with their own thinking.  Editing a question to add material which is not clearly the author's intent is a violation of the consensus standards of the site.  Again, please read https://math.meta.stackexchange.com/q/32402/ .
Comment: The following pair of identities, referenced in [an older answer](https://math.stackexchange.com/a/173649/137524), may be useful: $$\sum_{k=1}^{n-1}\tan^{2}\frac{k \pi}{2n}
= \frac{\left(n-1\right)\left(2n - 1\right)}{3},\\\sum _{k=1}^{m}\tan^2 \frac {k\pi } {2m+1}=m(2m+1)$$ Specifically, consider the cases $n=9$ and $m=4$ respectively.
Comment: What identities did you try using? Is this part of a larger question that might have some relevant context?
Comment: No , they only asked me to calculate the value of that , that is the whole question
Comment: Well, [Wolfram Alpha](https://www.wolframalpha.com/input?i=tan%5E2%28pi%2F18%29%2Btan%5E2%285pi%2F18%29%2Btan%5E2%287pi%2F18%29) says the answer is 9, so the hard part is going to be proving that. I assume you have some set of trig identities that would provide a hint, but I don't know exactly how to approach this.
Comment: I guess we can use the fomula $tanxtanytanz=tanx+tany+tanz$.
Comment: But that only works if the angles add up to $\pi$?
Comment: I tried to improve the question, as I can .
Comment: Well, my intention is not to harm the site, but to contribute to it.  This edit is rare.  I clearly didn't think this was homework.  Added publicly observable and reasonable context to the question. If the moderators suspend me for this reason, I'll leave this comment in advance. Thanks .
Comment: @lonestudent Please do not use edits to hijack someone else's question.
Comment: @XanderHenderson What is "hijack" ? Google translate obviously failed . By saving the question from being PSQ, being closed, excessive downvotes, deletion, I have ensured that it will useful for future users.  Moreover, the context I've added doesn't include attempts instead of OP, also it doesn't blatantly violate any policy.  The context I am providing is the publicly observable context.  Finally, please note that not all moderators around the world may agree with that action .
Comment: With respect to the word "hijack", the relevant definition is (2) from https://www.merriam-webster.com/dictionary/hijack:  "to take or take control of (something) as if by hijacking", as related to (1b) "to commandeer (a vehicle in transit)".  Your edits take control of the question away from the original asker.  Personally, I would prefer questions like this deleted (as this is essentially a homework problem), but the *compromise* that we have reached on this site is that we will tolerate homework questions *if* the askers of those questions provide context.
Comment: It is the *asker's* responsibility to provide that context.
Answer: In this answer, we show that :
$$
\begin{align}\bbox[5px,border:2px solid #C0A000]{\tan^2\frac{\pi}{18}+\tan^2\frac{5\pi}{18}+\tan^2\frac{7\pi}{18}=9}\end{align}
$$
and
$$
\begin{align}\bbox[5px,border:2px solid #C0A000]{\tan\frac{\pi}{18}\tan\frac{5\pi}{18}\tan\frac{7\pi}{18}=\frac {\sqrt 3}{3}}\end{align}
$$

You can observe that,
$$
\begin{align}\left|\tan \frac{\pi}{6}\right|=\left|\tan \frac{5\pi}{6}\right|=\left|\tan \frac{7\pi}{6}\right|\end{align}
$$
or
$$
\begin{align}\tan^2 \frac{\pi}{6}=\tan^2 \frac{5\pi}{6}=\tan^2 \frac{7\pi}{6}\end{align}
$$

Then, let us recall the $\tan (3x)$ formula in terms of $\tan x$ :
$$\tan (3x)=\frac {3\tan x-\tan^3x}{1-3\tan^2x}$$
By squaring both side of the identity and substituting $\color{#c00}{\tan x=y}$ you have :
$$\tan^2(3x)=\frac {9y^2-6y^4+y^6}{1-6y^2+9y^4}$$
By setting $x_1=\dfrac {\pi}{18}$ and $x_2=\dfrac {5\pi}{18}$ and $x_3=\dfrac {7\pi}{18}$, then substituting $\color{#c00}{y^2=u}$, we see that $\tan^2(3x)=\dfrac 13$, where
$$
\begin{align}u_1&=\tan^2 \frac {\pi}{18}\\
u_2&=\tan^2 \frac {5\pi}{18}\\
u_3&=\tan^2 \frac {7 \pi}{18}\end{align}
$$
which leads to the following :
$$
\begin{align}&\frac {9u-6u^2+u^3}{1-6u+9u^2}=\frac 13\\\\
\iff &3u^3-27u^2+33u-1=0\end{align}
$$
Finally, by applying the Vieta's formulas , you reach the following result :
$$u_1+u_2+u_3=\dfrac {27}{3}=9\thinspace .$$
which is equivalent to :
$$
\begin{align}\tan^2\frac{\pi}{18}+\tan^2\frac{5\pi}{18}+\tan^2\frac{7\pi}{18}=9\end{align}
$$
and since
$$
\begin{align}\tan\frac{\pi}{18}\tan\frac{5\pi}{18}\tan\frac{7\pi}{18}>0\end{align}
$$
then again by Vieta's formulas we have :
$$
\begin{align}u_1u_2u_3&=\frac 13\\
\implies \sqrt {u_1u_2u_3}&=\frac {\sqrt 3}{3}\end{align}
$$
which means that,
$$
\begin{align}\tan\frac{\pi}{18}\tan\frac{5\pi}{18}\tan\frac{7\pi}{18}=\frac {\sqrt 3}{3}\thinspace .\end{align}
$$

Note that, you can also prove that some other identities . For instance, try to show that :
$$
\begin{align}\bbox[5px,border:2px solid #C0A000]{\tan^4\frac{\pi}{18}+\tan^4\frac{5\pi}{18}+\tan^4\frac{7\pi}{18}=59}\end{align}
$$
Comment: It uses triple angle identities for tangent function, and square it. Can this be generalized?
Comment: @MathFail Generalization in which sense, exactly? To construct any possible explicit formula for $\tan^2a+\tan^2b+\tan^2c$ ? Or $$\begin{align}\tan^n\frac{\pi}{18}+\tan^n\frac{5\pi}{18}+\tan^n\frac{7\pi}{18}\end{align}$$
I like to find formulas but,  I have no motivation to expand the answer but see .e.g.(which is trivial) $$\begin{align}\bbox[5px,border:2px solid #C0A000]{\tan^4\frac{\pi}{18}+\tan^4\frac{5\pi}{18}+\tan^4\frac{7\pi}{18}=59}\end{align}
$$ By the way, I still see, my first boxed and last lines formula involve some typos (missing squaring) . Editing can make people tired .
Answer: For example, for $(\cos(θ) + i\sin(θ))^6$
Real part
$$\cos(6θ) = 32\cos^6(θ) - 48 \cos^4(θ) + 18 \cos^2(θ)-1$$
Imaginary part
$$\sin(6θ)=32\cos^5(θ)\sin(θ)-32\cos^3(θ)\sin(θ)+6\cos(θ)\sin(θ)$$
Let the polynomial $64x^3-96x^2+36x=3$, if $x=\cos^2(θ)$ then
$$\cos(6θ)=\frac{1}{2}$$
$$6θ=2k\pi\pm\frac{\pi}{2}$$
$$θ=\frac{1}{18}(6k\pm1)\pi$$
The roots are $\cos^2(\frac{\pi}{18}), \cos^2(\frac{5\pi}{18}), \cos^2(\frac{7\pi}{18})$
The equation whose roots are the reciprocals of teh above roots is
$$3x^3-36x^2+96x-64=0$$
And the sum of roots is
$$\sec^2(\frac{\pi}{18})+\sec^2(\frac{5\pi}{18})+\sec^2(\frac{7\pi}{18})=12$$
Your case is similar
Answer: Note that: $\tan \frac{5\pi}{18}=\cot\frac{2\pi}{9}$ and  $\tan \frac{7\pi}{18}=\cot\frac{\pi}{9}$. Then we have
$$\begin{align}
S&=\frac{1}{\cos^2\frac{\pi}{18}}-1+\frac{1}{\sin^2\frac{2\pi}9}-1 +\frac{1}{\sin^2\frac{\pi}9} -1\\
\\
&=\frac{4\sin^2\frac{\pi}{18}}{4\sin^2\frac{\pi}{18}\cos^2\frac{\pi}{18}}+\frac{1}{\sin^2\frac{2\pi}9} +\frac{1}{\sin^2\frac{\pi}9} -3\\
\\
&=\frac{1+4\sin^2\frac{\pi}{18}}{\sin^2\frac{\pi}{9}}+\frac{1}{\sin^2\frac{2\pi}9}-3\\
\\
&=\frac{4\cos^2\frac{\pi}{9}\left(1+4\sin^2\frac{\pi}{18}\right)}{4\cos^2\frac{\pi}{9}\sin^2\frac{\pi}{9}}+\frac{1}{\sin^2\frac{2\pi}9}-3\\
\\
&=\frac{1+4\cos^2\frac{\pi}{9}\left(1+4\sin^2\frac{\pi}{18}\right)}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{1+2(1+\cos\frac{2\pi}{9})\left[1+2(1-\cos\frac{\pi}{9})\right]}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{7+6\cos\frac{2\pi}{9}-4\cos\frac{\pi}{9}-4\cos\frac{\pi}{9}\cos\frac{2\pi}{9}}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{7+6\cos\frac{2\pi}{9}-4\cos\frac{\pi}{9}-2(\cos\frac{\pi}{3}+\cos\frac{\pi}{9})}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{6+6\cos\frac{2\pi}{9}-6\cos\frac{\pi}{9}}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{12\cos^2\frac{\pi}{9}-6\cos\frac{\pi}{9}}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{12\cos\frac{\pi}{9}\left(\cos\frac{\pi}{9}-\frac12\right)}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{12\cos\frac{\pi}{9}\left(\cos\frac{\pi}{9}-\cos\frac{\pi}{3}\right)}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=\frac{24\cos\frac{\pi}{9}\left(\sin\frac{2\pi}{9}\sin\frac{\pi}{9}\right)}{\sin^2\frac{2\pi}{9}}-3\\
\\
&=12-3\\
\\
&=9 \end{align}$$
Answer: Let $x=(\tan 10^{\circ})^2$. Then $\cos 20^{\circ}=\frac{1-x}{1+x}$ and from $\cos60^{\circ}=4(\cos20^{\circ})^3-3\cos20^{\circ}$ we get $3x^3-27x^2+33x-1=0.$ Similarly for the other two.


Absolute Beginner wants to play Jazz Piano

Question: Alright people, I have successfully tamed the beasts calling themselves my "parents". Now I am a free mind with money of his own to play music again.
I have a CTK-451 which basically is a 61 keyboard with unweighted and insensitive keys left from my childhood. Ha!
Jazz is what moves my spirit and so I want to get into music by what i like. Classical is very enjoyable also but Jazz is more "rock" and "let's move", which is what drives me to it every time.
When shown notes and I can tell you which is which and play it... slowly ... out of rhythm. Practice Practice Practice. I am aware of some basics of the circle of fifths but I am no prodigy.
Would you recommend me to take basic piano lessons first anyways(based on classical). If yes, I would "train" for the lessons on classical and study/play jazz in the rest of the free time.
What else could I practice?
For the keyboard I will get a full key, weighted(+sensitive) with midi or usb, piano.
Comment: +1 from me because I'm interested in this too but would also like to see whether people recommend learning to read music of learning/ playing 'by ear'
Comment: This question (and answers) might help you: http://music.stackexchange.com/q/410/9198
Comment: Aren't there jazz piano lessons anywhere nearby you? I'd be guessing most of the basics (getting your posture right, learning the keyboard) would be the same at first, but could diverge quite quickly.
Comment: Something that may help here - www.coursera.org has free online classes from the Berklee School of Music - one of them is an introduction to jazz improv, which starts in 6 days.
Comment: @tarun, it does ask that you have basic improv background though.  Might be a little advanced for someone just starting.
Answer: don't take classical lessons. It doesn't prepare you adequately for jazz. The problem is that classical teachers don't teach you about chords (harmony) and they don't encourage you to play by ear or to improvise - all of which are fundamental to jazz. So, my recommendation is to find a jazz pianist in your city, someone who plays in a way that you like, and ask them for weekly lessons. They can take you from the roots in blues, ragtime, that sort of thing, show you how to voice chords, how to play bass lines, and build your musical vocabularly on the road towards jazz.
Comment: I would like to read some more opinions on his suggestion.
Comment: I found my classical teacher to be this way. This doesn't sound like the standard, but I struggled heavily as I was trying to learn rock music with a classical focused teacher. The result was her encouraging me to buy sheet music of rock/pop books and playing them verbatim, with no education on what a chord was. I left there and started taking lessons from a rock teacher and my world opened up.
Comment: You can never know enough music if you want to play, so I don't entirely agree with this advice. However, Michael has a point. Improvisation uses an entirely different side of the brain than when you are striving to recreate a piece of sheet music accurately. Both are musical exercises and one informs the other, but they are not the same. Mainly you can't skip to a solution. Hurry slowly (festina lente, I think is the Italian expression.) Go after it from every possible approach, but is is essential to find someone to demonstrate how it is done - more a mentor than a teacher.
Answer: As a classically-trained pianist who is now beginning to learn jazz piano, I would recommend taking classical piano lessons because with that comes classical music theory which is an important thing to understand, regardless of your chosen style.
Once you are suitably adept with classical piano, you could then begin to learn the features and practices of the jazz genre, as I am. However, since you are only beginning to learn the piano then you are probably in a good position to try to learn about classical music and jazz at the same time. You could take lessons with a classical trainer, and then study jazz alongside it.
Regardless of how you structure your learning, I would advise learning classical piano, because it is a good place to start and you can then branch out into many different styles, using your knowledge of basic western notation. The fundamentals remain the same - time signatures, key signatures, the twelve-semitones octave etc.
Basically: take classical lessons,  buy jazz books, study classical and jazz theory.
Hope this helps.
Comment: I get that is your experience, but does it mean it's necessarily the right way? Especially if OP has no interest in playing classical music — this could very well be discouraging
Comment: OP describes classical as 'very enjoyable', and I was careful not to say that it is the **right** way. My answer says: `I would advise...`. I wasn't trying to say that the way I learnt is the best way, by any means. I was trying to recommend it though, and I think my answer balances the two.
Comment: Yeah i have thought about pretty much the same but was not sure if this wouldn't be "too much". I'll try it this way. I bought a book from Frank Sikora(its on german; dunno if its available in english) which was advoctaed as one of the best on jazz improvisation/theory and as a pretty straightforward book. The thing about the tutor is the monthly pay 65-85€/month and especially the driving time i could practice. I prefere autodidactic measures most of the time anyways but i would need quality resources nontheless. "Pebber Brown" on YT has straightforward videos about music theory. Any other?
Comment: In the UK, ABRSM are some of the best providers of theory books, and they also run exams. With practical, I don't really know - I have always relied on a teacher. A search of Amazon would probably give you some good results.
Comment: I also suggest learning classical playing first. Sight reading and theory are so important. These days theory includes jazz anyway, and once you can play you can take impro lessons. You have to have the foundations to build upon. I say this because it is so very hard for the other musicians when some guy turns up thinking being able to play somebody else's riffs by heart makes you a jazz musician, while not even knowing what transposition etc is.
Answer: I never took classical piano lessons, but it does help to a degree. It helps with sight reading, should you ever decide to sit in a session and everyone are reading charts arranged for originals, etc.
It helps with basic chords. Mostly Major and minor triads in different inversions, with different bass notes from the same chord. (typical feature in classical music), diminished and augmented chords.
Lots of these types of chords are found throughout latin/cuban music and gospel.
In saying that, Jazz is all about feel.
I have been playing jazz piano/ latin/ blues etc professionally for over 20 years now, and I also teach jazz piano.
I have seen the great advantages of classical technique through most of my Japanese students. (I live in Japan) It's a common thing here for kids to take up piano at such a young age. So by the time I receive any students wanting to learn "jazz" (usually in their teens) A lot of the technique is already taken care of, and I can then focus on the feel, and introduce to them new rhythms, harmonies, scales, chord progressions, and sounds.
Thelonius Monk had terrible looking fingering to many pianists, BUT he had GREAT feel, introduced amazing ideas, and figured out his own technique.
It all depends how far you want to take it.
If you want to play like Oscar Petersen but can not play fast runs like he can, that's when classical training from a GREAT TEACHER will help you. Ofcourse you need to put in the work.
If you want to sound AMAZING without those fast runs, then just focus on your feel, by listening to as many great recordings as possible, and trying to mimic what you hear. Rhythm, melody. There are great jazz tutorials online.
here are some cats that never had any classical training:
Answer: A classical education ultimately prepares you for sight-reading and reproduction.  But in the process, there is of course a lot of execution skills as well as getting exposed to a lot of different thoughts and media.
There is no way to get exposed to music better than playing it.  Should someone wanting to be a poet recite other people's poetry?  How else is he going to acquire a feeling for the meters?
Saying to skip a classical education since you want to play Jazz anyway seems to me like wanting to skip grammar since you want to become a modernist writer anyway.  Or wanting to skip perspective since you want to become a cubist.
To be an artist worth listening to, you need to be in control of your execution.  A classical education is all about control of execution.  What is lacking is the control of variation, so yes, at some point of time you'll likely match your teachers' interests and specialization to your own.
But the basics are pretty much the same, and there is certainly also "migratory" material like Scott Joplin's piano ragtimes which you can pull off just fine using classical education but which are sort of stepping stones into non-classical interpretation.
Comment: most jazz musicians did not have a classical education, so I think one needs to look at the road they took


Codeigniter Ajax Upload image

Question: I'm currently developping some forms for my school project with CodeIgniter.
The idea is that I have a form with image upload. I'm trying to do it dynamically with Ajax but it seems not working at all. I tried the non-dynamic version with php and It works perfectly, my images are in my folder and I have no problem with it.
I tried like 5 or 6 plug-ins with no results, it is certainly my fault but I don't know where I did a mistakes.
<---Controller--->
if($result = $this->images_model->add_bdd())
{
    $data['uploaded'] = $result;
    $data['message_upload'] = 'Image uploader avec succès.';
    $this->template->set_title('Upload successful');
    $this->template->view('add_places',$data);
}
else
{
    $this->template->set_title('Upload failed');
    $this->template->view('add_places');
}

<--Model-->
function add_bdd()
{
    $config = array(
                'allowed_types' => 'jpg|jpeg|tiff',
                'upload_path' => $this->gallery_path,
                'max_size' => 2000,
                'remove_spaces' => TRUE,
                'overwrite' => FALSE
            );

    $this->load->library('upload',$config);
    if ($this->upload->do_upload())
    {

        $data_img = $this->upload->data();
        $exif = $this->exif_extractor->coords($data_img['full_path']);
        $data = array(
                'titre' => 'titlecontent',
                'url' => base_url('images/'.$data_img['file_name']),
                'url_min' => base_url('images/'.$data_img['raw_name'].'_min'.$data_img['file_ext']),
                'alt' => 'cover_contentName',
                'id_users' => $this->session->userdata('id'),
                'date_upload' => date('Y-m-d H:m'),
                'date_modified' => date('Y-m-d H:m'),
                'lat' => $exif[0],
                'long' => $exif[1],
                );
        $this->db->insert('pictures',$data);
        return $exif;
    }
    else
    {
        return false;
    }
}

<--View-->
<form action="http://localhost:8888/project/images/add" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="userfile" value="Image de couverture"  />
<button name="upload" type="button" id="upload">Upload</button>
<input type="submit" name="submit" value="Publish Place"  />
</form>

Can anyone give me a jQuery plugin to upload images dynamically and send back to the script my images with the path and others data that I want to return ?
I can't paste like all the code I made for jQuery, but I really need help about it. It's been 2 days that I'm on it!
Thanks for your help.
Answer: Does the add_bdd() function return false?
I have used CodeIgnitor to do this very thing and I have found that the filters you specify are usually why you do not get the file uploaded.  You should add more code to the section where if ($this->upload->do_upload()) is false and print out the debug code using the following:
echo $this->upload->display_errors();

See here for more info: http://codeigniter.com/user_guide/libraries/file_uploading.html
Keep in mind that if you are calling this via AJAX, you will need a means to see the debug result such as printing the echo'ed debug result to an HTML element on your calling page.  You could also print the iformation using a tool like Firebug.
Comment: I have no errors when I uploaded it by the normal way. I just need a plugin working with my code, I don't know how I can do achieve it. This is really special.

If you can give me an example of one of your ajax file upload, it could be useful. Thanks in advance for your help.
Answer: Without the Javascript code there's little anyone can do for you.
Check out this tutorial on Nettuts+ which goes into depth of the basic idea that you're after so that you better understand, debug and adjust your code.
Also, I barely use jQuery plugins as I find it easier to code one that better suits the needs of my current project so I can't recommend any.
Comment: Thans you @Spyros for your answer. I tried your tutorial on monday and It didn't works because jQuery is version 1.7 and the script works up to 1.2 so you have an error. I found a way to resolve my problem. I'm going to post it tomorrow with full code and explain. (much easier and up to date)
Answer: Thanks for you help, I change my dynamic about the script so now, it works perfectly with what I have to do.
There is the script for my upload system :
<-- VIEW (upload_img)-->

[Select files]
[Upload files]</a

<-- CONTROLLER -->
function index(){
    if($this->_access())
    {
        $this->template->add_include('js/jquery.js')
                       ->add_include('js/browserplus.js')
                       ->add_include('js/plugins/plupload/plupload.full.js')
                       ->add_include('js/imgfunc.js');
        $this->template->view('upload_img');
    }
    else
    {
        redirect(site_url());
    }
}

function upload_image_spot()
{
    if($query = $this->images_model->upload_image_spot())
    {
        echo json_encode($query);
    }
    else
    {
        echo $this->upload->display_errors('', '');
    }
}

<-- MODEL -->
   function upload_image_spot()
{
    $config['upload_path'] = realpath(APPPATH. '../images/spots');
    $config['allowed_types'] = 'jpg|jpeg|tiff|png';
    $config['max_size'] = 3062;
    $config['encrypt_name'] = TRUE;
    $this->load->library('upload', $config);
    if($this->upload->do_upload('file'))
    // file means the file send to the website for upload, this is the name of field for Plupload script
    {
    $data_img = $this->upload->data();
    $copies = array(
            array('dir' => 'images/spots/large/', 'x' => 1000, 'y' => 600),
            array('dir' => 'images/spots/thumb/', 'x' => 100, 'y' => 60)
    );

    $this->copies($data_img,$copies);

    return 'whatever'; // Not real data, I don't wanna post them here
    }
}

<-- JS-SCRIPTS -->
First of all include :
-jQuery
-browserPlus
-Plupload
(Plupload Script)
Now add this script in an empty file:
var uploader = new plupload.Uploader({
    runtimes : 'gears,html5,flash,silverlight,browserplus',
    browse_button : 'userfile',
    container : 'container',
    max_file_size : '3mb',
    url : 'yourUploadFunctionCI',
    flash_swf_url : 'plugins/plupload/js/plupload.flash.swf',
    silverlight_xap_url : 'plugins/plupload/js/plupload.silverlight.xap',
    filters : [
        {title : "Image files", extensions : "jpg,jpeg,JPG,JPEG,tiff,png"},
    ]
});

uploader.bind('Init', function(up, params) {
});

$('#uploadfiles').click(function(e) {
    uploader.start();
    e.preventDefault();
});

uploader.init();

uploader.bind('FilesAdded', function(up, files) {
    $.each(files, function(i, file) {
        $('#filelist').html("");
        $('#filelist').append(
            '
' +
            file.name + ' (' + plupload.formatSize(file.size) + ') ' +
        '
');
    });

    up.refresh();
});

uploader.bind('UploadProgress', function(up, file) {
    $('#' + file.id + " b").html(file.percent + "%");
});

uploader.bind('Error', function(up, err, msg,file) {
    $('#filelist').append("
Error: " + err.code +
        ", Message: " + err.message +
        (err.file ? ", File: " + err.file.name : "") +
        "
"
    );
    console.log(msg,up,err);
    up.refresh();
});

uploader.bind('FileUploaded', function(up, file,response) {
    $('#' + file.id + " b").html("100%");
    var data = jQuery.parseJSON(msg.response);
    console.log(data);
});

Do your own customization and that's it, no need extra script like you can see on website like copy/paste all script from a php file to a controller, just add 'file' inside do_upload and everything's gonna work fine !
Have a nice day guys, hope it's help.
Simon

Codeigniter Ajax Upload image


Altering Create New account tab link in user login page

Question: I tried using form alter for menu of tabs in /user page, that shows
"create new account", "login", request password
is it possible for us to alter the link so that the create new account can go to "customlink" instead of "user/register"
in drupal 7?
thank you!
Answer: Well, you could use hook_menu_alter() to change the call back function of that menu item:
function MY_MODULE_menu_alter(&$items) {
  $items['user/register']['page callback'] = 'my_custom_function';
}

And then you could redirect to a new page in the callback:
function my_custom_function() {
  drupal_goto('customlink');
}

Comment: Even more succinct: `$items['user/register']['page callback'] = 'drupal_goto'; $items['user/register']['page arguments'] = array('customlink');`
Comment: Yeah - that makes more sense...
Comment: the 1st one works thank you!!! for the 2nd one, that needs to go into the hook menu then.. both works great though thank you!


triangle inequality for a certain norm

Question: Let $d$ be a metric on a (say real) vector space $E$, with the property
$$d(x,x+cy)=|c|d(x,x+y)$$ for all $x,y\in E$ and scalars $c$. I am trying to prove that $x\mapsto d(x,0)$ defines a norm.
The triangle inequality gives me trouble (the others are easy): I need $d(x+y,0)\leq d(x,0)+d(y,0)$ for all $x,y\in E$.
Some thoughts: setting $y=\lambda x$ and $c=-1$ in the 'property' gives $d(x,(1-\lambda)x)=d(x,(1+\lambda)x)$, in particular $d(x,0)=d(x,2x)$.
The usual triangle inequality for $d$ gives $d(x+y,0)\leq d(x+y,x)+d(x,0)$, so also $2d(x+y,0)\leq d(x+y,x)+d(x+y,y)+d(x,0)+d(y,0)$.
I need  something like translation invariance, or express $d(x+y,0)$ in terms of $d(y,0)$ ('get rid of the sum').
Some hints/suggestions? Thanks!
Comment: Are you sure your condition is sufficient? I get the idea ; you want the metric to be compatible with scalar multiplication, but maybe this is not enough, because none of your axioms allow compatibility with addition.
Comment: @PatrickDaSilva: I am sure insofar as this is an exercise in lecture notes (perhaps I should have added this in my question). I share your thoughts on addition compatibility...but perhaps there is some trick.
Answer: Be it homework or not – this is a very fine problem indeed!
It is enough to consider a plane $E$ with points $z=(x,y)$. Let $|z|:=\sqrt{x^2+y^2}$ denote the euclidean norm.
(i) Claim: For each line $g\subset E$ there is a constant $\lambda_g$ such that for all $z$, $w\in g$ one has
$$d(z,w)=\lambda_g\ |z-w|\ .$$
Proof. Let
$$g:\quad t\mapsto z(t)=a + t\ u\ ,\qquad |u|=1$$
be a parametrization of $g$ with euclidean arc length as parameter and put
$$d^*(s,t):=d\bigl(z(s),z(t)\bigr)\ .$$
Then by the basic property of $d(\cdot,\cdot)$ we have for arbitrary $s$, $t\in{\mathbb R}$:
$$d^*(s,t)=d^*\bigl(s,s+(t-s)\bigr)=|t-s|d^*(s,s+1)$$
and similarly
$$d^*(s,t)=d^*(t,s)=d^*\bigl(t,t+(s-t)\bigr)=|t-s|d^*(t,t+1)\ .$$
For $t:=0$ the last two equations imply $|s|d^*(s,s+1)=d^*(s,0)=|s|d^*(0,1)$. It follows that $d^*(s,s+1)=d^*(0,1)=:\lambda_g$ for arbitrary $s\in{\mathbb R}$, whence
$$d\bigl(z(s),z(t)\bigr)=d^*(s,t)=\lambda_g |t-s|=\lambda_g\bigl|z(t)-z(s)\bigr|\ ,$$
as claimed.
(ii) Claim: The scaling factor $\lambda_g$ depends only on the direction vector $u=(\cos\phi,\sin\phi)$ of $g$. In fact there is a continuous function $\lambda:\ S^1\to{\mathbb R}_{>0}$ such that $\lambda_g= \lambda(\phi)$.
Proof. It is enough to consider the following situation: Let $g_1$ be the line $y=1$ and $g_2$ be the line $y=-1$, and let $p_i:=\lambda_{g_i}$. We have to show that $p_1=p_2$. Consider for small $\phi >0$ the line
$$ g_\phi:\quad t \mapsto t \ (\cos\phi,\sin\phi)\ .$$
The line $g_\phi$ has a certain scaling factor $\lambda(\phi)$ and intersects $g_1$ at the point $b:=(\cot\phi, 1)$. Put $(0,0)=:o$, $(0,1)=:a$. Then we have by the triangle inequality for $d$:
$$d(a,b)-d(o,a)\leq d(o,b)\leq d(o,a)+d(a,b)$$
or
$$p_1\cot\phi - d(o,a)\leq \lambda(\phi)\ {1\over\sin\phi}\leq d(o,a)+p_1\cot\phi\ .$$
Multiplying by $\sin\phi>0$ we obtain
$$p_1 \cos\phi -d(o,a)\sin\phi \leq\lambda(\phi)\leq p_1\cos\phi+d(o,a)\sin\phi\ ,$$
from which we conclude $\lim_{\phi\to 0+}\lambda(\phi)=p_1$. By symmetry (arguing on the left side) we also have $\lim_{\phi\to 0-}\lambda(\phi)=p_1$, so that in fact $\lim_{\phi\to0}\lambda(\phi)=p_1$. Using symmetry again it follows that $p_2=p_1$. Since the lines $g_1$, $g_2$ had nothing special about them it follows that any two parallel lines have the same scaling factor $\ \bigl(=:\lambda(\phi)\bigr)$; in particular the scaling factor of $g_0\colon\ y=0$ is also $\ =p_1$, which proves the continuity of the function $\lambda(\cdot)$. In particular, this function is bounded away from $0$ and $\infty$.
(iii) It follows from (i) and (ii) that the metric $d(\cdot,\cdot)$ is translation invariant. We now define the associated norm by
$$\|z\|\ :=\ d(o,z)\ .$$
The identity $\|\alpha\ z\|=|\alpha|\ \|z\|$ is obvious, and
$$\|z+w\|=d(0,z+w)\leq d(o,z)+d(z,z+w)=d(o,z)+d(o,w)=\|z\|+\|w\|$$
proves the triangle inequality for the norm.
Comment: Something's not clear in your proof of (i) : You show that $d^*(s,t)$ depends only on $d^*(s,s+1)=d^*(t,t+1)$ up to the scaling factor $|t-s|$, but nothing shows that $d^*(s,s+1) = d^*(0,1)$. It is not explicitly clear, and I must say I don't even see why it would hold.
Comment: @Patrick Da Silva: I have inserted an additional line. Hope it is clear now.
Comment: Thank you very much for your answer! Especially Claim 2 and its proof are quite clever.

triangle inequality for a certain norm


Ajax function with Jquery returns 400 error

Question: I'm using Jquery with Spring MVC.
I have an index.jsp:

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
    integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
    crossorigin="anonymous">

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
    integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
    crossorigin="anonymous">

    <form>

                Name:

                <input type="text" class="form-name" id="name" placeholder="Paolo">

    </form>

As you can see when one inserts a letter in the input box I run $ajax with jQuery.
My HTTP POST request is correclty sent but I have a 400 error.
This is my simple Controller class:
    @Controller
public class MyController {

    @RequestMapping(value="/myController", method = RequestMethod.POST)

    @ResponseBody
    public String getData(@RequestParam(value="name") String name) {

        return name;
    }
}

My DispatcherServlet for Spring MVC is correclty setted.
How can I solve?
Comment: Try with `data: { name : $("#name").val(), }`
Comment: I have tried but it does not work. I have the same 400 Bad Request error.
Comment: Can you add the stacktrace of the server, when you got this eror?
Answer: A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.
Your ajax call would be
$.ajax({
        url : "myController",
        type: "POST",
        data:{"name": $("#name").val()},
        success : function(result) {
                 alert(result);
               }

       });

Comment: Thank you! It works.
So I have to format my request in key-value pairs, right?


How to Make an Instrument's Melody Sound Right With a Vocal Melody?

Question: Every time I add a melody with a distinct rhythm (from say the piano) to my vocal melody, I notice that the music starts sounding confusing and irritating. Some songs have riffs (ie a melody of an instrument) and have a vocal melody. Examples to these are Payphone by Maroon 5 and Shape of You by Ed Sheeran.
In Shape of You, there's a distinct melody of an instrument, and there's the vocal melody. I don't know if there are any rules to follow when I try to make a vocal melody sound good with the melody of an instrument.
Could someone explain to me?
Answer: Oh boy, this is a big one.
Yes there are rules, or rather there are methods and tricks. You need to have good counterpoint between the vocal and the instrumental line. Then you need to use your ears  to write counter-melodies that complement and enhance the vocal. Really you're just writing a two part counterpoint, but often the counter-melody may be harmonic-based figure which is easier (like the strings in 'bittersweet symphony'.)
Putting two melodies together is a skill and usually needs some knowledge of harmony and counterpoint, although good ears may be enough.
Comment: Peter, I haven't read your answer: we are using exactly the same words *Yes there are rules ...* This makes me smile.
Answer: The two terms you have to differ here are homophony and polyphony. If you try to set a simple instrumental 2nd voice you can e.g. write just descending notes of a scale (this might be half notes playing single tones of the fitting chords.)
The other term (polyphony) is connected with counterpoint. Yes, there are lots of rules how you can write in interesting and good sounding counterpoint: This can be completely different theme or contain  motif-imitations of the main tune. If you look up some rules for counterpoint, you'll find there advises for voice leading and intervals, good balance of consonances and dissonances phrasing. But this you don't learn by reading rules, the best you are making music (also analyzing, playing, listening, writing).
Btw.:
I've learned my "counterpoint"

by playing thousands of hymns and improvising,
singing canons
playing Euphonium in a Brass bandd


How to make media description show on form view when used as entity reference

Question: Drupal 9...
I have a content type of "Resource" which uses a field "download" which references the media type "document", but when I upload a file to the field, it gives me no opportunity to enter a description for the newly uploaded file.
Resource content type
Field_download  (entity reference to Media Type = Document)
Media Type: Document

field_description (text  -- required)

field_media_document (file -- required -- enabled description field)

1 - New Resource content type… upload the media file

2 - the media upload box appears

3 - Selected the file I want to upload - it is here that I want to enter the file's description.  The help text even says "Fill in any required fields and save..." but no required field appears.

4 - Insert the media, now that it has been uploaded

5 - The new "Resource" node shows the new file, but still no opportunity to enter description
Answer: I had this same issue and found the solution:

If you want to be able to add a new file with a description using Media library then visit
/admin/structure/media/manage/document/form-display/media_library
and enable the "Document" field.

Source: https://www.drupal.org/forum/support/post-installation/2022-08-24/how-to-use-description-when-inlining-link-to-media-documents-d9#comment-14669785


How to use add-type with -path and also -language csharpversion3?

Question: I've been using add-type in Powershell to dynamically compile in some C# classes I want to use. Works great except it's 2.0 only.
I just discovered the -language csharpversion3 option, but it does not work with -path. How can I work around this?
[Edit: removed bit about ReadAllText - I was mistaken.]
Answer: Here's the workaround: read the file as text.
$script = [io.file]::readalltext($scriptpath)
add-type $script -lang csharpversion3

I might as well paste in the rest and make this answer useful in some way.. I have a debug flag that lets me generate the DLL so I can more easily break in with the debugger, inspect it with Reflector, etc.
$cp = new-object codedom.compiler.compilerparameters
$cp.ReferencedAssemblies.Add('system.dll') > $null
$cp.ReferencedAssemblies.Add('system.core.dll') > $null

# optionally turn on debugging support
if ($debugscript)
{
    # delete old unused crap while we're at it
    dir "$($env:temp)\-*.dll" |%{
        del $_ -ea silentlycontinue
        if ($?) { del $_.fullname.replace('.dll', '.pdb') -ea silentlycontinue }
    }

    $cp.TreatWarningsAsErrors = $true
    $cp.IncludeDebugInformation = $true
    $cp.OutputAssembly = $env:temp + '\-' + [diagnostics.process]::getcurrentprocess().id + '.dll'
}

$script = [io.file]::readalltext($scriptpath)
add-type $script -lang csharpversion3 -compilerparam $cp

This adds some additional functionality if $debugscript is set to true:

Compile with warnings as errors
Generate a PDB
Use a specific DLL/PDB name (in the temp folder) that is tied to the process ID so each session gets its own. This is good for iterating on changes to the .cs.
Deletes the old dll's and pdb's, also good when iterating.
Answer: I don't know if it exactly what you need, but you can enable .NET 4 support in powershell. Remember that by default it use .NET 2. To do this you need to add in $PSHome an XML with this name powershell.exe.config and this content:
<?xml version="1.0"?>
<configuration>
        <startup useLegacyV2RuntimeActivationPolicy="true">
                <supportedRuntime version="v4.0.30319"/>
                <supportedRuntime version="v2.0.50727"/>
        </startup>
</configuration>

After that any code targeted to a bigger .net version will work, for example look this:
Slytherin>> gc new.cs
using System.IO;

public static class testeo
{
        public static string joinP(string[] arr)
        {
                return Path.Combine(arr);
        }
}
Slytherin>> $arr = "uno", "dos", "tres", "cuatro", "cinco"
Slytherin>> Add-Type -Path .\new.cs
Slytherin>> [testeo]::joinP($arr)
uno\dos\tres\cuatro\cinco

That method use Path.Combine with N arguments that is defined in .NET4. In .NET2 Combine can only handle up to two arguments. I test other example that use anonymous delegates, one of the characteristics of C#3:
Slytherin>> $sharp = [IO.file]::readalltext((resolve-path new.cs))
Slytherin>> add-type  -typedef $sharp -Language CsharpVersion3
Slytherin>> gc .\new.cs
using System.IO;
using System;
using System.Linq;

namespace grantest
{

public static class testeo
{
        public static void joinP(string[] arr)
        {
                arr.ToList<string>().ForEach(x=>Console.WriteLine(x));

        }
}
}
Slytherin>> [grantest.testeo]::joinP($arr)
uno
dos
tres
cuatro
cinco
Slytherin>>

One last example if you try the next code it doesn't going to work
Slytherin>> $sharp = [IO.file]::readalltext((resolve-path new.cs))
Slytherin>> $sharp
using System.IO;
using System;
using System.Linq;

namespace grantest
{

public static class testeo4
{
        public static string joinP(string[] arr)
        {
                arr.ToList<string>().ForEach(x=>Console.WriteLine(x));
                return Path.Combine(arr);
        }
}
}
Slytherin>> Add-Type -TypeDefinition $sharp
Add-Type : c:\Users\voodoomsr\AppData\Local\Temp\5ikkmpfn.0.cs(3) : The type or namesp
ace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly
reference?)
c:\Users\voodoomsr\AppData\Local\Temp\5ikkmpfn.0.cs(2) : using System;
c:\Users\voodoomsr\AppData\Local\Temp\5ikkmpfn.0.cs(3) : >>> using System.Linq;
c:\Users\voodoomsr\AppData\Local\Temp\5ikkmpfn.0.cs(4) :
At line:1 char:9
+ Add-Type <<<<  -TypeDefinition $sharp
    + CategoryInfo          : InvalidData: (c:\Users\voodoo...bly reference?):Compile
   rError) [Add-Type], Exception
    + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddType
   Command

other try specifying the language parameter
Slytherin>> add-type -TypeDefinition $sharp -Language CSharpVersion3
Add-Type : c:\Users\voodoomsr\AppData\Local\Temp\v3r5whoc.0.cs(13) : No overload for m
ethod 'Combine' takes '1' arguments
c:\Users\voodoomsr\AppData\Local\Temp\v3r5whoc.0.cs(12) :         arr.ToList<string>()
.ForEach(x=>Console.WriteLine(x));
c:\Users\voodoomsr\AppData\Local\Temp\v3r5whoc.0.cs(13) : >>>         return Path.Comb
ine(arr);
c:\Users\voodoomsr\AppData\Local\Temp\v3r5whoc.0.cs(14) :     }
At line:1 char:9
+ add-type <<<<  -TypeDefinition $sharp -Language CSharpVersion3
    + CategoryInfo          : InvalidData: (c:\Users\voodoo...s '1' arguments:Compile
   rError) [Add-Type], Exception
    + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddType
   Command

This is happen because where using a method of .net4 and apparently if you say that the language is version 3 automatically use .net 3 libraries . In order to make this work you need to add System.Core as referenced assembly and forget about the language parameter(the enumeration of possible values doesn't have Csharpversion4) so its going to use the 4 version, because we enable it before.
Slytherin>> Add-Type -TypeDefinition $sharp -ReferencedAssemblies System.core
Slytherin>> [grantest.testeo4]::joinP($arr)
uno
dos
tres
cuatro
cinco
uno\dos\tres\cuatro\cinco

Good luck, and happy coding.
Comment: Yup, I have my own Powershell configured to support 4.0. It's not really portable though. I can't require everyone here who uses my script has their local Powershell hacked. Not to mention turning on 4.0 support slows down startup time significantly. Thanks for the answer but I think my princess is in another castle.
Comment: yea it slow down incredibly for that reason I have 2 powershell executables, one configured with 2runtime and one with 4runtime. I use the 4 when i'm developing and need to test and play with code and version 2 when i need to run some 2runtime script fast. Just copy the executable and name it for example powershell2.exe, for that executable create the powershell2.exe.config with only the 2 runtime enabled,:)


What is the "default revision"?

Question: I'm using the Workflow module in Drupal 8 and I saw this checkbox on the "add a state" screen (/admin/config/workflow/workflows/manage/help/add_state):

Default revision When content reaches this state it should be made the default revision; this is implied for published states.

What exactly is meant here by "default revision"?  Why is it implied for published states?
Comment: Just FYI, as I understand it, some of the terminology and concepts for revisions aren't completely stable yet, see eg. [#2940575](https://www.drupal.org/project/drupal/issues/2940575), [#2942907](https://www.drupal.org/project/drupal/issues/2942907), [#2875154](https://www.drupal.org/project/drupal/issues/2875154), [#1643354](https://www.drupal.org/project/drupal/issues/1643354).
Answer: So that means it will become the active revision shown to users. So if a revision is published its got to become the default revision as it will be shown as the page content for normal users
When you select "Archived" for a piece of content you'd want that to become the default revision too so that when users look at the page they'd see access denied. But you wouldn't have the published option ticked for "Archived"
And draft you wouldnt want to become the default revision because it's not supposed to be shown to users in that state

What is the "default revision"?


How do I prevent the feed aggregator creates blank nodes when cron is run?

Question: I've recently taken over the management and development of a Drupal 6 site and one of the problems plaguing this installation is that blank nodes authored by "Visitor" keep popping up.

I've narrowed the issue down to the RSS aggregator and it seems like the nodes are being created when this runs durring the cron job. Has anyone seen this before? If so how do I go about fixing this? If not, does anyone have an idea where to look in order to resolve this?
Comment: Which modules are installed on the site? Aggregator, the module that Drupal comes with, doesn't create nodes from the aggregated content. You can see it in action on Drupal.org: http://drupal.org/aggregator.
Comment: There are a slew of modules installed, some custom, some from drupal.org.  I'm no longer sure the problem is with the RSS aggregator, I see a log entry of `action 05/17/2011 - 9:11am Saved  ` that I think is related to this issue thogh.
Comment: For sure there is a module that creates nodes, but creates them in the wrong way. You can see the nodes that result posted by "Visitor" don't have a title, nor a correct content type; both are empty, in your screenshot.
Answer: Take a look at the Scheduler module. It creates blank nodes if you have some crappy nodes in scheduler table.


Function classes on posets, which are closed under certain operations

Question: Let $(S,\leq)$ be a poset. Let $\Omega = \{f : S \to \mathbb R : f \text{ is monotone decreasing}\}$ be the set of all decreasing functions i.e. those such that $f(x) \leq f(y)$ for all $x \geq y$. Then, $\Omega$ has a few desirable properties :

$0 \in \Omega$ (The identically zero function).

For $f,g \in \Omega$, we have $f+g \in \Omega$.

For $f,g\in \Omega$, we have $\max\{f,g\} \in \Omega$ and $\min\{f,g\} \in \Omega$.

$\Omega$ is closed under pointwise convergence of functions.

These properties are desirable to me, because I am performing an iterative procedure like so : let $\mathbb R^{ S} = \{f : S \to \mathbb R\}$. Given a linear operator $P : \mathbb R^ S  \to \mathbb R^{ S}$, I write up sufficient conditions on $P$ so that $P:\Omega \to \Omega$ ($P$ involves the maximum, minimum and sum operations). Then, by beginning with some $f_0 \in \Omega$, and defining $f_n = Pf_{n-1}$, I ensure that (using some Banach FPT procedure) the $f_n$ converge to $f \in \Omega$ such that $Pf = f$. This $f$ is a fixed point with structure of $P$.

I wish now, to find similar sets like $\Omega$, so that with conditions for $P$ to be preserving that class (and hoping $f_0$ belongs in that class), I can find and prove the existence of various structured fixed points of $P$.

Question : Can somebody come up with more kinds of subsets of $\mathbb R^{S}$ such that each of the properties listed above (for $\Omega$) is also satisfied by that class?

Here are some non-examples : convex and concave functions don't fall in here because of the $\min$ , $\max$ non-closure respectively. These are important classes ruled out, but I am hoping there are still enough examples around.
Note : If anybody wants a concrete poset to work on, please consider $\mathbb N^3$ with the lattice partial order. Answers restricted to just this poset are also acceptable.

Further context : The function $f$ satisfying $Pf=f$ is a "two policy comparison" function. So, I have an optimal control problem where I must compare two policies, and $f$ describes the difference between these policies pointwise. Providing structure on $f$ (more precisely on the sign of $f$) gives a structure to when one policy is preferred to the other : an important example of this is monotone policies in queue theory (where $f$ is , in fact monotone decreasing). This is how this problem links to optimal control.
Comment: there is a tag called lattice-orders, I put that in. Integer-lattices ought to mean a different thing.
Comment: Thanks for that @WillJagy.
Answer: There are ridiculously many examples; far too many to classify.  Here's a rich family I encountered on my attempt at classification.
First, let $\{G_s\}_{s\in S}$ be any sequence of closed submonoids of $(\mathbb{R},+)$.  This includes $0$ and any discrete subgroup, so we already have at-least-continuum-many possibilities.  Second, pick $c\in S^2\to\mathscr{P}(\{\leq,\geq\})$ where $\mathscr{P}$ is the power-set operator.  Then it is easy to verify that $$V(G,c)=\{f:{{R\in c(s,t)}\implies f(s)\mathrel{R}f(t)}\}\subseteq\prod_{s\in S}{G_s}$$ satisfies your conditions.
There are still more examples; the key problem is that we can "lose track" of which increments correspond to which functions.  For example, suppose $S=[2]$ and $$\mathcal{X}=\{f:{f=0}\vee f\text{ strictly increasing}\}$$  If $\mathcal{X}\subseteq V(G,c)$, then $G=(\mathbb{R},\mathbb{R})$ and $c(1,2)={\leq}$.  But $(1,1)\in V(G,c)\setminus\mathcal{X}$.  One might hope to rectify this, by make $c$ not just an order relationship, but a full additive monoid of possible differences.  I still don't think that's enough to classify, but I can't prove it.
Moreover, you place no conditions on $S$; you probably want to restrict $S$ to be at-most-countable.  Otherwise, pointwise convergence begins to break down, since sequences are only countably long: taking the pointwise closure of the vector space generated by the standard basis $\{\delta_s\}_{s\in S}$ does not give $\mathbb{R}^S$, but rather $\{f:\mathrm{supp}{f}\text{ countable}\}$.
Comment: Oh boy, thanks for the answer. It's a great read : it turns out that the generality discussed in this problem is kind of what I needed in more general applications. Yes, thankfully $S$ is countable : it's a subset of $\mathbb Z^3$. I will now take a look some suitable structure and contractive operators on this space for future applications (right now, it turns out I don't need the heavy machinery, but this has opened up a huge can of ideas).


Docker containers in Azure pipelines in privileged mode possible?

Question: we are starting to use docker containers in our Azure pipelines.
For one scenario we would need to run the docker container in privileged mode and I am wondering whether Azure pipelines supports "privileged" container execution?
Thank you
Answer: If docker containers are located in Docker Hub or Local Machine, you could run the docker containers in privileged mode.
You could try to run the following script: docker run --privileged [image_name]
steps:
- task: Docker@2
  inputs:
    containerRegistry: 'DockerServiceConnectionName'
    command: 'login'
- script: docker run --privileged [image_name]

You could refer to this ticket about the Azure Container.

Azure Container Instances does not expose direct access to the underlying infrastructure that hosts container groups. This includes running privileged containers and thus it is not supported currently.
Comment: In our self-hosted agents I could make such a call like mentioned above and I did not get any errors during the execution. Does that mean it works or could it be that I get runtime errors because the privileged mode is not completely enabled?


Question not closing

Question: This question shows me that it has 0 votes to close. Review history shows it has at least 4, including one from a site moderator.
Why don't I see the close votes?
And would a moderator vote not immediately close the question?
Answer: EconJohn reopened the question—I guess because it was edited with some effort shown.
Comment: @denesp got ya.
Comment: I see. I thought I would be able to vote to close again in this case, but I cannot. Thanks for the info!
Comment: @denesp That is what I did. I just require the user to edit the question and that is what he did, if the site wishes to close it again I wont reopen it.
Comment: @EconJohn That is your privilege and I appreciate you tackling these questions. The problem is that I cannot vote on this question anymore, and I guess the other people who already voted cannot vote on it again either, so I don't think there will be enough people to vote to close it anytime soon. Perhaps consider leaving reopening decisions to the popular vote.

Question not closing


C++ virtual method problem

Question: I have two structs, in which I'm trying to overwrite a method in the base struct.
The base struct is defined as:
 template <class T>
 struct compareFunction : public std::binary_function<T,T,bool> {
    virtual bool operator() (const T & first, const  T & second) {
        //This function is always called
        return first < second;
    }
 };

The struct I'm attempting to subclass with is defined as:
template <class Key, class T>
struct valuecomparer : public compareFunction<std::pair<Key,T> > {
    std::binary_function<Key, Key,bool> comparer;

    bool operator() (const std::pair<Key, T>& x, const std::pair<Key, T> & y) {
            //This function is never called
            Key tx = x.first;
            Key ty = y.first;
            if(tx < ty) {
               return true;
            } else {
               return false;
            }
    }
};

I don't see what I'm doing wrong here, any help would be greatly appreciated.
Ideally, the method in valuecomparer would be called instead of the method in compareFunction.
It is being called basically like this (not necessarily valid syntax,but trying to get idea across):
typedef compareFunction<T> cmpType; //Inside a class definition, T is std::pair<int,double>
valuecomparer<int,double> compareVar;
compareVar.comparer = std:less<int>();
cmpType x = compareVar;
x.compare(std::pair<int,double>(8,20.0),std::pair<int,double>(8,25.0));

Apparently after switching the storage from a pure struct to a struct pointer in the class that is using the base struct (and consequently derived struct), everything works.  Thanks for all the help :)
Comment: @Seth: The overriden subclass function is never called it seems.
Answer: According to the code you've posted, in order to have a overridden derived class' function to be called, you MUST call it from a pointer or reference to the base class type, not an object whose type is of the base class itself.  So when you create code like this:
cmpType x = compareVar;
x(std::pair<int,double>(8,20.0),std::pair<int,double>(8,25.0));

that's always going to call the function definition in the base-class since there is no function that can be used for the polymorphic derived function call.  The copy-constructor only copies over the v-table entries and associated members from the base-class.  So when you call a method on an object of the base-class type, even if you've created that object from a copy of a derived class, you still end up with the base-class method calls.  You would have to-do something like this:
cmpType& x = compareVar;
x(std::pair<int,double>(8,20.0),std::pair<int,double>(8,25.0));

Now when the operator() method is called on x, the correct v-table entry is used, that is the overridden version of operator() inside of valuecomparer.
Comment: I didn't even see if this is right, but +1 for length and the effort it required.
Comment: This is not correct - only a single type is passed to the base template, that of `pair`.
Comment: `struct valuecomparer : public compareFunction` -- this is wrong, now the `operator()` of the base class looks like `bool operatr()(Key const& left, Key const& right`, but the derived class wants `pair`s to compare.
Comment: Okay, I've fixed the post ... thanks for pointing out any errors.
Answer: The problem is, from your pseduo-code, you're slicing your comparer:
typedef compareFunction<T> cmpType; //Inside a class definition, T is std::pair<int,double>
valuecomparer<int,double> compareVar;
compareVar.comparer = std:less<int>();
cmpType x = compareVar;                     // *** SLICED HERE ****
x.compare(std::pair<int,double>(8,20.0),std::pair<int,double>(8,25.0));

The easiest solution, given the context, would be the change the declaration of x to be a reference to cmpType, instead of a full-blown instance.
Edit:
Looking closer, the above will not work, at all (you said it was psuedo), but given the intent, looks like you've meant:
valuecomparer<int,double> compareVar;
compareVar.comparer = std:less<int>();
compareFunction<pair<int, double> > x = compareVar;                     // *** SLICED HERE ****
x.compare(std::pair<int,double>(8,20.0),std::pair<int,double>(8,25.0));

Answer: If you're using your valuecomparer for a std::map, then you're missing the fact that an item in the map is defined as std::pair<const Key, Val>. See the const part? :) Add that to your std::pair<>s. If that isn't the problem, report back where and how you actually use those functors.

C++ virtual method problem


Theming node add form: "An unrecoverable error occurred" when uploading file

Question: I am theming the node add form in drupal 7 for a custom content type. I have proceeded as indicated here.
As a test I managed to write my custom tpl.php file and get everything displayed correctly as it was in the original version without that tpl.php file. One of the field in the form is a file which gets uploaded with file widget.
My problem with my new form is that: when I click the "Upload" button for the file field in my form I get the following error:

An unrecoverable error occurred. The uploaded file likely exceeded the
  maximum file size (128 MB) that this server supports.

But the file I am trying to upload is only about 100k!
I do not get this error when I use the regular form (i.e without using my custom tpl.php) file.
Here are the functions I implemented in my module:
/**
 * implements hook_theme
 *  to theme node add form
 *
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
               'mycontenttype_request_node_form' => array(
                                            'render element' => 'form',
                                            'template' => 'templates/mycontenttype-request-node-form',
                                            // this will set to module/theme path by default:
                                            'path' => drupal_get_path('theme', 'bootstrap_subtheme'),
                                            ),
               );
  }

/**
 * Preprocessor for theming ('mycontenttype_request_node_form').
 *
 */

function mymodule_preprocess_softsound_request_node_form(&$variables) {

  $variables['myreq'] = array();
  $hidden = array();

    foreach(element_children($variables['form']) as $key) {
          $type = $variables['form'][$key]['#type'];
    if($type == 'hidden' || $type == 'token'){
      $hidden[]= drupal_render($variables['form'][$key]);
    }
    else {
      $variables['myreq'][$key] = drupal_render($variables['form'][$key]);
    }
  }

    //$variables['myreq']['hidden'] = implode($hidden);
    //$variables['myreq'] = implode($variables['myreq']);

}

And here is my mycontenttype-request-node-form.tpl.php file:

      <?php  print $myreq['title']; ?>

   <?php print $ssreq['field_description']; ?>

   <?php print $myreq['field_myfile']; ?>

   <?php print $myreq['additional_settings']; ?>

   <?php print $myreq['actions']; ?>

<?php print drupal_render_children($form); ?>

Any hints as to why I get the unrecoverable error relating to file size I mentioned above and how to get rid of it?
Thanks,
baba
Answer: The problem was that i called drupal render on all elements of the form in my preprocess function and that I also called drupal_render_children in my tpl. This was redundant and caused errors.
my preprocess function now reads:
function mymodule_preprocess_softsound_request_node_form(&$variables) {

   $variables['myreq'] = array();

  $variables['myreq']['title'] = drupal_render($variables['form']['title']);
  $variables['myreq']['field_description'] = drupal_render($variables['form']['field_description']);
  $variables['myreq']['field_myfile'] = drupal_render($variables['form']['field_wavfile']);

}

and my tpl.php now reads:

           <?php print $myreq['title']; ?>
           <?php print $myreq['field_description']; ?>

   <?php print $myreq['field_myfile']; ?>

<?php print drupal_render_children($form); ?>

thanks to Rashad Majali for the answer


Geodesic hyperbolic metric

Question: For a hyperbolic metric on the upper half plane $H = \{(u,v)\in \mathbb{R}^2 \ | \ v>0\},$ how can I prove that the vertical lines are geodesics and that the intersection of any circle centered on $x-\text{axis}$ with $H$ is a geodesic?
The definition I have for geodesic is:
Let $\alpha : [a, b] \to \Sigma$ be a regular parameterized curve then we call it geodesic if its tangent vector is parallel along $\alpha.$
Comment: What have you tried? What definition of a geodesic are you using? (Edit your post with this information so that those answering can do so more effectively.)
Comment: From your given definition this is just a computation: parametrise the curves by length and compute the covariant acceleration $\nabla_{\alpha '} \alpha'$.
Answer: The problem can be solved synthetically as follows. The vertical ray, e.g. the $y$-axis, is invariant under the reflection $(x,y)\mapsto (-x,y)$. The reflection is an isometry and therefore the vertical line must be a geodesic.
To show that the semicircles are geodesics, use an isometry sending one of its endpoints to infinity. The result is a vertical ray hence a geodesic as already shown.
If the semicircle passes through the origin, just use $z\mapsto 1/z$. Otherwise use a horisontal translation first.
Comment: Thanks! If I were to use $\nabla_{\alpha '} \alpha'$ how will I go about doing that?
Comment: First you need an explicit formula for the nabla in terms of the $\Gamma$ symbols. Then parametrize the vertical line by the exponential function (this gives a unit speed parametrisation with respect to the hyperbolic metric).  Applying your formula to that will give $0$.

Geodesic hyperbolic metric


How do I add a flat rate?

Question: I have installed the following modules in an existing Drupal site.

Commerce and Commerce UI
Customer and Customer UI
Price
Line Item and Line Item UI
Order and Order UI
Checkout, Payment, Product
Product Reference
Cart and Product Pricing
Tax
Product UI
Tax UI
Payment UI
Shipping
Shipping Flat Rate

The shop is working fine as expected.
I'm trying to set up different shipping rates, so I'm following the instructions on the project page for the Flat Rate module. However, when I go to Store > Configuration > Shipping there is no option to add a flat rate service.
What am I missing?
Answer: On Store > Configuration > Shipping there are few tabs like Shipping services and Shipping methods; below them, there is another set of tabs which include Flat rate. That should be chosen before the Add a flat rate service link becomes visible on that page.

How do I add a flat rate?


Drupal Views Slideshow + Galleria

Question: Image Gallery with the use of View slideshow does a trick for me.
what I need :
But for thumbnails & for main image galleria provide image crop with 4 options like height, width etc.
Is there any way that we can use custom image style that we have added from back-end to create those thumbnails?
Please Guys Suggest. I stuck in this since many time.
Answer: Use jCarousel module for slideshow. I think this is what you want.

Drupal Views Slideshow + Galleria


Ruby on Rails - Upload de arquivos

Question: atualmente possuo um requisito de permitir ao usuário efetuar upload de arquivos PDF e DOCX em minha aplicação com limite de tamanho. Como posso desenvolver esta funcionalidade utilizando o Rails?
Os arquivos físicos serão salvos na nuvem da AWS, e desejo somente manter as informações do arquivo no meu banco de dados.
Answer: Existem várias gems que ajudam muito:
https://github.com/carrierwaveuploader/carrierwave
https://gorails.com/episodes/file-uploading-with-carrierwave
http://shrinerb.com/rdoc/files/doc/direct_s3_md.html
https://gorails.com/episodes/file-uploading-with-shrine
https://gorails.com/episodes/direct-file-uploads-to-s3-part-3
https://github.com/refile/refile
https://gorails.com/episodes/file-uploads-with-refile
É questão de escolher a que te parecer mais adequada, no fim, todas operam mais ou menos parecido.

Ruby on Rails - Upload de arquivos


Não consigo achar o motivo do FormatExcpetion

Question: Pessoal boa noite to com um probleminha em um programinha basico de teste que estou fazendo alguém poderia me ajudar ?

Erro: A cadeia de caracteres de entrada não estava em um formato incorreto. (FormatException)
em System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
     em System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
     em System.String.System.IConvertible.ToInt32(IFormatProvider provider)
     em System.Convert.ToInt32(Object value)
     em MySql.Data.Types.MySqlInt32.MySql.Data.Types.IMySqlValue.WriteValue(MySqlPacket packet, Boolean binary, Object val, Int32 length)
     em MySql.Data.MySqlClient.MySqlParameter.Serialize(MySqlPacket packet, Boolean binary, MySqlConnectionStringBuilder settings)
     em MySql.Data.MySqlClient.Statement.SerializeParameter(MySqlParameterCollection parameters, MySqlPacket packet, String parmName, Int32 parameterIndex)
     em MySql.Data.MySqlClient.Statement.InternalBindParameters(String sql, MySqlParameterCollection parameters, MySqlPacket packet)
     em MySql.Data.MySqlClient.Statement.BindParameters()
     em MySql.Data.MySqlClient.PreparableStatement.Execute()
     em MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
     em MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
     em MiniCrud_Aula_PC.DAO.cadastrarCarro(Carro c) na C:\Users\Filipe\documents\visual studio 2010\Projects\MiniCrud_Aula_PC\MiniCrud_Aula_PC\DAO.cs:linha 41
     em MiniCrud_Aula_PC.frm_Principal.Salvar_Cadastro() na C:\Users\Filipe\documents\visual studio 2010\Projects\MiniCrud_Aula_PC\MiniCrud_Aula_PC\frm_Principal.cs:linha 239
     em MiniCrud_Aula_PC.frm_Principal.bt_Salvar_Click(Object sender, EventArgs e) na C:\Users\Filipe\documents\visual studio 2010\Projects\MiniCrud_Aula_PC\MiniCrud_Aula_PC\frm_Principal.cs:linha 62
     em System.Windows.Forms.Control.OnClick(EventArgs e)
     em System.Windows.Forms.Button.OnClick(EventArgs e)
     em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
     em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
     em System.Windows.Forms.Control.WndProc(Message& m)
     em System.Windows.Forms.ButtonBase.WndProc(Message& m)
     em System.Windows.Forms.Button.WndProc(Message& m)
     em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
     em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
     em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
     em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
     em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
     em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
     em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
     em System.Windows.Forms.Application.Run(Form mainForm)
     em MiniCrud_Aula_PC.Program.Main() na C:\Users\Filipe\documents\visual studio 2010\Projects\MiniCrud_Aula_PC\MiniCrud_Aula_PC\Program.cs:linha 18
     em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
     em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
     em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
     em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
     em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
     em System.Threading.ThreadHelper.ThreadStart()

    private const string insertCarro = "insert into tbl_Carro (marca, modelo, ano, cor, estado, valor) values (@marca, @modelo, @ano, @cor, @estado, @valor);";
    private const string countCodigo = "select COUNT(id) from tbl_Carro";

    public int cadastrarCarro(Carro c)
            {
                int codigo = 0;

                using (MySqlConnection conectar = new MySqlConnection(conexao))
                {
                    using(MySqlCommand comando = new MySqlCommand(insertCarro, conectar))
                    {
                        try
                        {
                            conectar.Open();

                            comando.Parameters.AddWithValue("@marca", MySqlDbType.VarChar).Value = c.Marca;
                            comando.Parameters.AddWithValue("@modelo", MySqlDbType.VarChar).Value = c.Modelo;
                            comando.Parameters.AddWithValue("@ano", MySqlDbType.Int32).Value = c.Ano;
                            comando.Parameters.AddWithValue("@cor", MySqlDbType.VarChar).Value = c.Cor;
                            comando.Parameters.AddWithValue("@estado", MySqlDbType.VarChar).Value = c.Estado;
                            comando.Parameters.AddWithValue("@valor", MySqlDbType.Decimal).Value = c.Valor;

                            comando.ExecuteNonQuery();

                            comando.CommandText = countCodigo;

                            codigo = Convert.ToInt32(comando.ExecuteScalar());

                        }
                        catch (MySqlException)
                        {
                           MessageBox.Show("Ocorreu um erro ao executar a inserção do carro no banco de dados!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            conectar.Close();
                        }
                    }
                }
                return codigo;
            }

class Carro
    {

        public int Id { get; set; }
        public string Marca { get;set; }
        public string Modelo { get; set; }
        public int Ano { get; set; }
        public string Cor { get; set; }
        public string Estado { get; set; }
        public double Valor { get; set; }

        public Carro()
        {
        }

        public Carro(int _id)
        {
            Id = _id;
        }

        public Carro(int _id, string _marca, string _modelo, int _ano, string _cor, string _estado, double _valor)
        {
            Id = _id;
            Marca = _marca;
            Modelo = _modelo;
            Ano = _ano;
            Cor = _cor;
            Estado = _estado;
            Valor = _valor;
        }

        public Carro(string _marca, string _modelo, int _ano, string _cor, string _estado, double _valor)
        {
            Marca = _marca;
            Modelo = _modelo;
            Ano = _ano;
            Cor = _cor;
            Estado = _estado;
            Valor = _valor;
        }
    }

Comment: Qual a linha em que a exceção acontece?
Comment: @carlosfigueira Na linha que executo o comando pela primeira vez comando.ExecuteNonQuery();
Comment: Poste a exceção completa (mensagem + *stack trace*), fica mais fácil de saber o problema. Outra informação que também pode ser útil é a definição da classe `Carro`
Comment: @carlosfigueira Pronto coloquei StackTrace + a Classe
Answer: O método SqlParameterCollection.AddWithValue recebe como parâmetros o nome do parâmetro e o valor do parâmetro. Você está passando para ele o nome e o tipo do parâmetro. Como você passa um SqlDbType como o valor do parâmetro, alguma conversão (provavelmente para um dos parâmetros numéricos) está falhando.
Tente trocar este método pelo SqlParameterCollection.Add(string parameterName, SqlDbType sqlDbType), que deve resolver este problema.
Comment: Obrigado, parei de informar o tipo e passei a informar o valor do do parametro com o AddWithValue e funcionou. Muito Obrigado e Boa Noite :)


When is bootstrapping helpful and used?

Question: When is bootstrapping helpful and when should it be used?
I have watched several videos so I understand what bootstrapping does (samples with replacement from a single sample many times and create a bootstrapped sampling distribution). If we are interested in means or difference in means, I understand that a t-test can be used and bootstrapping should be used for more unusual measures like medians (eg. median home price) or proportions (eg. proportion of voters that vote for a given party). To pinpoint why exactly bootstrapping is used for these cases, is it because a t-distribution does not accurately capture the distribution of the median home prices or proportion of voters? I have seen examples that use hypothesis testing and CIs for a proportion without using bootstrapping, so I wanted to clarify my understanding of why and when to use it.
Answer: I will use your t-test example to try to demonstrate why we would use bootstrapping in some cases but not in others.
The reason we use t-tests to compare sample means is because of the central limit theorem. The CLT states that if our sample ($X_1$, $X_2$, ...) meet certain conditions, then our sampling mean, $\bar{x}$, will follow a normal distribution. However, we don't know what the variance of the normal distribution is so we have to estimate it. Accounting for that uncertainty means that our sampling distribution of $\bar{x}$ will follow a t-distribution with n-1 degrees of freedom.
However, the Central Limit Theorem gives us no guarantees on distribution of the median. If our sample was n=5, the distribution of the median would be the distribution of $x_{(3)}$, the third order statistic, which would very much depend on the distribution of the $X_{i}$s, which we may not know. This is where bootstrapping comes in.
This is where bootstrapping comes in. We know that the median of our sample is going to be a good estimator of the population median, but we don't really have any idea how variable that sampling distribution is going to be (unless we know the distribution of the $X_i$s exactly). Bootstrapping is the easiest way to get an accurate estimator of the variation in the sampling distribution of any complex mathematical function of the data (such as the median, or any other statistic).
Bootstrapping is equally valid for use on the mean. However, we often prefer the t-distribution approach because bootstrapping is only an asymptotic approach, which means the guarantees that bootstrapping provides a good estimate of the variance only hold as your sample size goes to infinity. Often they work well for smaller samples, but imagine what bootstrapping would do if your sample size was 1, you're calculated statistic would always be the same and so your estimate of the variance would be 0. So clearly somewhere between 1 and infinity bootstrapping begins to give good results.
Comment: Thanks for your response! To recap, we use t-distributions to estimate the population mean because of the CLT (because CLT essentially says that sampling name will be normal if it meets independence and size conditions). However, this does not apply for medians and we have to construct our own bootstrapped sampling distribution to estimate the population parameter. Is there any other measurement (other than means) that CLT applies to?
Comment: Yes, that makes complete sense. Thank you! And just to double check does the X_i  that you refer to represent the observations in a given sample, or the samples in a sampling distribution?
Comment: Individual observations that make up your sample
Comment: No, the central limit theorem applies only to means. However, there are many other situations where we might know something about the distribution, where we can derive confidence intervals from what we know without resorting to bootstrapping. Using the example above, if we knew our $X_i$s came from a normal distribution, we can know the distribution of the median without bootstrapping
Comment: Great thank, that's what I thought but I just wanted to clarify.
Answer: Bootstrapping is useful when there is no closed-form analytic estimator for a statistic. For example, the variance of a conditional survivor probability estimated by bootstrapping may produce estimates with nominal type I probability coverage). For another example, when a particular distribution is unknown (and therefore closed-form analytic estimators of its moments or other statistics are unknown), as when measuring phenomena that do not have precise mathematical theory undergirding their distribution (e.g., distributional measures of BMI or of smoking intensity in a population).
Bootstrapping can also be a useful tool in simulations for evaluating the performance of approximate estimators.
Comment: Thanks for your response! You mention this idea of closed-form analytic estimators and we use bootstrapping when those are unknown. Other than means, what do we have known closed-form analytics estimators for?
Comment: @JaneSully If browse a bunch of the distributions' description pages on Wikipedia (e.g., [gamma](https://en.wikipedia.org/wiki/Gamma_distribution), [beta](https://en.wikipedia.org/wiki/Gamma_distribution), [exponential](https://en.wikipedia.org/wiki/Exponential_distribution), [Poisson](https://en.wikipedia.org/wiki/Poisson_distribution), etc.), you will very frequently see formulas for things like the means & variances of these distributions given the distributions' parameters (sometimes mean and variance *are* the parameters... as with the normal distribution). You're welcome. Welcome to CV!
Comment: Sometimes for other moments as well.

When is bootstrapping helpful and used?


Which data structure to store co-authorship?

Question: I have a list of authors with title of the book and the year of publication, for example:

Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea: Java Concurrency in Practice, 2006
Ken Arnold, James Gosling and David Holmes: Java Programming Language, 2005
...

I was wondering what data structure would be best to store information about co-authors, book they have written together and year of publication.
I would like to later use this information to draw graphs (in JUNG, I'm using java), where each author would be node and the edge would be each book they co-authored. Separate graph would be drawn for every year. I was thinking of using multimap:
Map<Year, Map<Author, List<Map<Co-author, Title>>>>

but maybe this is overcomplicated?
Thanks in advance for any help.
Answer: How about placing a set of authors and title in an object, named, for example, 'Book'? That way, your data structures could be simply
class Book {
    List<Author> authors;
    Title title;
}

Map<Year, Set<Book>> booksInYears

The graph-drawing algorithm could work like this:
for (Book book : booksInYears.get(aYear))
    for (Author author1 : book.authors)
        for (Author author2 : book.authors)
            if (author1 != author2)
                drawEdge(author1, author2, book.title);

drawEdge method would first check if both authors have corresponding nodes already drawn (for example using a set containing authors with already drawn nodes, or perhaps an Author => Node map) and draw needed nodes, and then draw an edge between them.
Answer: Just create a JUNG graph out of it; JUNG will handle the data structures.  That is, nodes will be Authors and edges will be Coauthor relationships (which would consist of information about the work).
That said, having worked with co-authorship graphs in the past, you may want to consider the more natural representation of coauthorship as either a bipartite graph (Authors vs Works) or a hypergraph.  That way you don't need to redundantly represent the work multiple times.
Answer: I Think this is a bad idea to structure your data like that, why not use the polymorphism concept?
Why not creating Class Book , containing stuff like year of publication, name etc..
Than create another entity such as Class Author, and construct between the two Book will contain List<Author> coAuthors , and Author can contain List<Book>


how to create a rake task for use with rspec

Question: I am trying to implement the following rake task from the CMS wiki
namespace :test do
  task :prepare do
    ENV['FROM'] = 'folder-name'
    ENV['TO']   = 'site-identifier'
    Rake::Task['comfortable_mexican_sofa:fixtures:import'].invoke
  end
end

I created test.rake with the above contents and put it in lib/tasks/
$ bundle exec rake:test

gives me: bundler: command not found: rake:test.
My search for documentation leads me to explainations of:  RSpec::Core::RakeTask.  I assume these are different things.  My question is:  How do I execute the above rake task?    Any help would be greatly appreciated.
Answer: Your command is trying to run rake:test, which isn't a known command. You can see this by doing which rake:test.
I think you meant
bundle exec rake test

You can also do
bundle exec rake -T

To see the list of available tasks that have documentation.
For further reference on bundle exec see the bundler documentation.


Slickgrid - number of columns showed in dom

Question: I'm about to test a website with Selenium. There is implemented a table with SlickGrid.
I have the Problem that when I read in a row i get only 29 columns but there were about 40 (in real).. This cause to 100% to the virtualised scrolling.
I'm wondering, what's the default amount of columns which appears in the dom?
Answer: It took me a while to resolve how it's done and I can say it's a bit tricky. There is no such thing as a "default amount" of columns, this amount is getting computed, see below for a bit of technical details.
You can check the slick.grid.js files line 1787. There is a function cleanUpAndRenderCells(). This is responsible for calculating and rendering the cells which aren't on the grids canvas. For example when you scroll the horizontal scrollbar, this function gets called and based on the direction of the scroll they check if the next set of cells aren't on canvas and can fit the canvas, they append the cells to the DOM.

For the matter of reading the row values
I see two possible ways of doing that using javascript.

If you are using a data array as datasource:
data[grid.getSelectedRows()[0]]

If you are using a DataView as datasource:
grid.DataView.getItemById(0)

Both will return an Object with property names of columns.

However I'm not sure how/why would you integration test this, the slickgrid package is already tested, you can check it here.


Left hand training for right handed guitar players - to improve coordination.

Question: Ok, this question will probably be opinion based, but I try my best to write it, so it can be answered.
My problem: When playing guitar (I am right handed) I lack some speed and coordination in my left hand to do maybe trills (right word? I mean something like this |--5h7p5h7p5h7--|) or vibrato properly. I just can't get my hand to do what I want.
My theory: I compared the ability of both hands to perform certain tasks, like tapping a rhythm and get faster while doing it or moving it in certain ways with a certain speed, and as expected, my left hand wasn't as good at it as the right hand.
The question is not about doing tremolo or trills properly, in theory, I already know that, it's just my left hand, which is not trained enough.
The question is, is it common to do certain exercises for the left hand to increase control or maybe even perform tasks with your left hand you would probably do with your right hand (e.g. learn writing with your left hand)?
Are there some well known exercises or (to drill down the opinion based part) any literature describing something like this or is it just a matter of doing excercises for the particular technique to gain better control with the left hand?
Usually, I would ask for your opinion or experience with such exercises, but I know that's not wanted on SE. Decide if this question is too opinion based.
Comment: My theory: it's more to do with the fingers than the hand itself.Individual fingers are what do the tricky bits with guitar playing. Find excercises that get fingers moving separately. Bet you typed the question with two fingers! Try typing just with left hand fingers, for a start.
Comment: Yes, good objection. When I speak of my left hand I actually mean my fingers, but also the whole hand at the example of vibrato.
Answer: I was having the same problem as a beginner and wondered the exact same thing.  I even tried switching to playing guitar the other way around (fretting with my dominant right hand).  That's when I discovered something interesting.
You see by the time I became frustrated with my seemingly clumsy left hand because of the things it could not seem to do as well as the right (such as vibrato), I had learned to play most of the common open and barre chords and developed a modicum of right hand strumming technique that allowed me to accomplish the basic strumming patterns.  So when I picked up a friend's left handed guitar and tried to play it, all of a sudden my right hand was more clumsy than the left.  And I couldn't strum with the left hand with any semblance of rhythm or timing or accuracy.  It did not take long to conclude that it would probably take longer to train my fingers and hands to play left hand guitar than it did right hand guitar (probably not actually longer but at that moment my right hand seemed clumsier than the left).
In other words, there was obviously a task specific learning that took place during my practice and playing sessions that eventually enabled my left hand to instantly contort into completely unnatural and awkward shapes to play a C chord followed by a G chord followed by a D chord followed by a B minor Barre chord.  My right hand could not even form any of these chords - much less seamlessly transition between any of them.
I have also learned that now I can do things with my left hand on guitar that I never thought I would be able to do.  And when you are finally able to effortlessly execute a hammer on or vibrato or fast trill - you will wonder why it was ever difficult in the beginning - and will have a hard time understanding why everyone can't do it. But if you try it with your opposite hand - you will be reminded of how difficult it used to be.
And guess what?  Once you master a fretting hand technique with your left hand and suddenly find it automatic and easy to do - and then you try it with your right hand and find it impossible to do with any semblance of fluency, you will still find most things easier to do with your right hand.  But the task specific learning where you trained your left hand to execute a particular technique or movement smoothly and flawlessly - allows your left hand to be totally coordinated  while your right hand seems clumsier than your left when attempting to do that particular thing.  But yet in other areas - your right hand is still dominant.
Bottom line:  It just takes patience, dedication, desire, and continual deliberate and intentional practice (ideally after learning the correct technique from a good teacher). If you want to master a particular technique or skill, spend a given amount of time each time you pick up your guitar on deliberate practice on that technique or skill.  You can work on several different techniques each practice session.  Just devote a period of time to each technique (say ten minutes). Maybe keep a guitar handy at work and pick it up when there is a lull and practice the specific technique you are trying to develop the coordination for. In other words do it several times each day for short periods so you don't get too frustrated with your seeming lack of coordination.  Eventually it starts to come together and work. And you will forget that you weren't born with a natural ability to pull it off flawlessly.
Have fun learning new things on guitar.  It's a lifelong process that never ends.  Enjoy the journey.
Comment: Thanks for the, as usual, detailed answer. I think you are right. I thought, when I train to have a better control in my left hand, as with some excercises or writing with my left hand, would improve my ability to learn the techniques, but I think the movements needed for the guitar are too special to have them trained that way. I would probably only train these new movements but I would have no improvement on the guitar. Do you agree?
Comment: Makes you  (or me) wonder whether if you'd started left handed, it would have turned out even better! Many, many times I've said that right-handed folk should actually be able to play better in a left-handed way. There's a couple of my answers which reflect on this. Borrowing a leftie at a gig was always going to be a problem, though...
Comment: @MatthiasNicklisch  Yes I totally agree.  Specific movements tend to be hand dependent for some reason.  Try writing left handed and you will see what I mean.  But I know left handed folks who write right handed because their elementary school teacher made them write with their right hand.  They can't write with their left hand nearly as well - despite the fact they do almost everything else left handed.
Comment: @Tim - I know right?  I have wondered the same thing.  Like who decided that right handed people should use their left hand to fret.  Maybe the guitar was invented by a lefty and future emulators of the original prototype (or whatever instrument the guitar evolved from) never questioned the logic.  Today it seems that in any guitar store they have 1 left hand guitar for every 100 right hand guitar and the lefty guitar is only available in two models vs. 50 different models for righties.  Which is why lefties beginning guitar should play a "right hand" guitar.
Answer: There are two main approaches to this: Muscle memory (technique) and biomechanics. They are synergistic.
Muscle memory in your left hand is surely poorer then your dominant hand, due to the obvious reasons. To improve this would be simply to simply play more and do technique related excercises like picking drills and scales etc.
Biomechanically, your muscle in your left hand are weaker due to misuse compared to your dominant hand. I think this is a largely ignored aspect of guitar playing.
To fret, do trill, and to vibrato accurately with control requires you to have strong and stable finger and wrist extensors. This is why players always have problems with so called poor "technique" (fretting too hard, poor finger dexterity when chording and issues with accuracy). The poor technique is a result of maladaptive compensatory finger movements and activation patterns.
I recommend doing finger extensor exercises

How often do you actually perform the movement of finger extension in daily life? Its likely those muscles are 'dead' - weak and poorly activated.
On the other hand avoid grip exercises like squeezing tennis balls or finger trainers, because in most individuals we perform a gripping action many times over the course of day (picking things up, turning a door knob). Its not likely these muscles are weak.
Treat guitar playing like you would any other physical activity or sport. The average professional football player does not maintain a high level of performance simply by doing field and play drills. They hit the gym equally hard.
Source: Purchasing a dedicated finger extensor training device significantly improved my playing. My fretting and chording speed and accuracy is greatly improved. Fatigue and poor finger isolation is also no longer an issue. I am an experienced player, but I'm pretty sure this would greatly help new players even more.
Comment: 'Muscle memory in your left hand is surely poorer then your dominant hand, due to the obvious reasons.' - What obvious reasons?
Comment: I assume the OP isn't ambidextrous, so his left hand isn't as accustomed to small, dexterous micro-movements like his right hand (e.g. writing).
Comment: Yes, I understand, but why would this affect muscle memory?
Comment: Never mind, we probably mean different things by 'muscle memory'.
Comment: Ah, I don't actually mean the actual capacity of potential muscle memory. I just mean the existing spastic and unconditioned state of the less utilized left hand. I'm basing this on the wikipedia definition.


As nota1 e nota2 acusam erros e não visualizo o armazenamento no array. Alguém pode ajudar? Muito obrigado

Question: <code>namespace mediaDe5Alunos
{
    class Program
    /*faça um programa para cálcular a média de duas notas de 5 alunos, mostrar a média da sala e de cada aluno e um relatório dos alunos*/
    {
        static double calculo (double nota1, double nota2)
        {
            double media = (nota1 + nota2) / 2;
            return media;
        }

        private static double lerNota()
        {
            return double.Parse(Console.ReadLine());
        }

        public struct Aluno
        {
            public string nome, nota1, nota2, media;
        }

        static int a = 0;

        static void Main(string[] args)
        {

            Console.WriteLine("Programa de notas");
            Console.WriteLine("Escolha uma opção: \n1- inserir nome do aluno \n2- relatório de alunos \n3- mostrar media \n4- sair do programa");
            int opcao = int.Parse(Console.ReadLine());

            if (opcao == 1)
            {

            Aluno[] aluno = new Aluno[3];

            Console.WriteLine("Inserir nome do primeiro aluno");
            aluno[a].nome = Console.ReadLine();
            Console.WriteLine("Insira a primeira nota");
            aluno[a].nota1 = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Insira a segunda nota");
            aluno[a].nota2 = Convert.ToString(Console.ReadLine());
            double media = calculo(nota1, nota2);
       //     Console.WriteLine("A média do(a) aluno(a) " + nome + " é: " + media);
            aluno[a].media = Convert.ToString(media);

                //        for (int a = 0; a < nome.Length; a++)
                //         foreach (string A in aluno)
                {
                    Console.WriteLine(a);
                }
            Console.WriteLine("==============================================");

            }
            else if (opcao == 2)
            {
                Console.WriteLine("Relatório de alunos");
            }

            else if (opcao == 3)
            {
                Console.WriteLine("Mostrar media");
            }

            else if (opcao == 4)
            {
                Console.WriteLine("Sair");
            }

            else
            {
                Console.WriteLine("Escolha uma opção válida");
            }
            Console.Read();
        }

    }
}
</code>
Comment: Quais erros ele acusa? A partir de qual linha?
Answer:
Modificação 1: inseri outra barra no comentário da class;
Modificação 2: declarei nota1 e nota2 como double;
Modificação 3: usei um Convert.ToDouble na passagem da variável;

O problema era que seu método calculo recebia dois doubles e você estava passando duas strings.
<code>    namespace mediaDe5Alunos
    {
    class Program //faça um programa para cálcular a média de duas notas de 5 alunos, mostrar a média da sala e de cada aluno e um relatório dos alunos/
    {
        static double calculo(double nota1, double nota2)
        {
            double media = (nota1 + nota2) / 2;
            return media;
        }
        private static double lerNota()
        {
            return double.Parse(Console.ReadLine());
        }

        public struct Aluno
        {
            public string nome, media;
            public double nota1, nota2;
        }

        static int a = 0;

        static void Main(string[] args)
        {

            Console.WriteLine("Programa de notas");
            Console.WriteLine("Escolha uma opção: \n1- inserir nome do aluno \n2- relatório de alunos \n3- mostrar media \n4- sair do programa");
            int opcao = int.Parse(Console.ReadLine());

        if (opcao == 1)
        {

            Aluno[] aluno = new Aluno[3];

            Console.WriteLine("Inserir nome do primeiro aluno");
            aluno[a].nome = Console.ReadLine();
            Console.WriteLine("Insira a primeira nota");
            aluno[a].nota1 = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Insira a segunda nota");
            aluno[a].nota2 = Convert.ToDouble(Console.ReadLine());
            double media = calculo(aluno[a].nota1, aluno[a].nota2);
            //     Console.WriteLine("A média do(a) aluno(a) " + nome + " é: " + media);
            aluno[a].media = Convert.ToString(media);

            //        for (int a = 0; a < nome.Length; a++)
            //         foreach (string A in aluno)
            {
                Console.WriteLine(a);
            }
            Console.WriteLine("==============================================");

        }
        else if (opcao == 2)
        {
            Console.WriteLine("Relatório de alunos");
        }

        else if (opcao == 3)
        {
            Console.WriteLine("Mostrar media");
        }

        else if (opcao == 4)
        {
            Console.WriteLine("Sair");
        }

        else
        {
            Console.WriteLine("Escolha uma opção válida");
        }
        Console.Read();
        }

    }

}
</code>
Comment: Obrigado pela resposta. Fiz as auterações "public string nome;
            public double nota1, nota2, media", deixei a média como  double tbm, mas a nota1 e nota2 ainda tem erro (sublinhado vermelhor). E o array não mostra o valor armazenado. Muito obrigado Lucas.
Comment: De nada! Eu que agradeço. :)