setHorizontallyScrolling causes text to restart in TextView

Question: I have added marquee effect in my TextView and appending text to this TextView at run time. After appending I call setHorizontallyScrolling to avoid text overwriting. But this call causes the text to restart again. Is it possible to stop this restart and continue scrolling? Please help
Answer: I don't believe there is a solution that lets you change the value of the horizontallyScrolling attribute without resetting the marquee timer. You may have to set that value in your layout XML to true before you even start appending new text. If you do that then it SHOULDN'T reset when you just append text and should just continue scrolling.
Comment: You are right Femi. But at this time the text gets overwritten :( Same issue is mentioned in this link http://stackoverflow.com/questions/5631262/marquee-text-gets-overwritten


Help with fingering on Chopin's Nocturne op. 9 no.2 coda

Question:
I am trying to learn this nocturne and this fingering is really confusing to me.
Why are three different, consecutive notes played with the same finger? Should I just "hop" from note to note, since I am holding the pedal? I normally try to play everything legato, unless stated as staccato in the score, as if I didn't have a pedal at all.
Comment: You may well play everything legato, but all those notes are actually *staccato*, (except the last one, (which doesn't count fingering wise!)so there's no need to consider legato playing for them.
Answer: The combination of staccato and legato markings mean that the notes should be separated but not as sharply as a true staccato. Even with the pedal present, the articulation will come across. In this particular case, the pedal markings are also strategic to make the phrase clear.
The fingering comes from Chopin.1 In the absence of a source explaining his reasoning, I propose what I feel are two reasonable explanations.

Using the same finger facilitates -- in fact, requires -- a non-legato touch.
Using the same finger also suggests that Chopin wants an evenness of tone across those notes. I base this on the convention that one changes fingers on repeated notes in part to promote a difference in touch.

As long as these musical goals of a non-legato and even touch are observed, the fingering can be modified as best allows you to achieve the sound.

1 Based on the Preface of the Henle Urtext edition: "Figures in italics stem from manuscript sources, or the first editions, and therefore represent the fingering which has been suggested by Chopin himself." Op. 9 No. 2 is based on the French first edition, with the German edition also consulted (page 123). The particular fingerings in question are given in italics in the Henle score (page 14). Frederic Chopin, Nocturnes, ed. Ewald Zimmermann (1980, Henle).
Comment: How did you find out it was Chopin's fingering? It's good that it hasn't been 'corrected' eh? Quite surprising. Fingers 1 and 2 are deemed too brutish for these high notes; even through the fifth bar.
Comment: @OldBrixtonian Yeah, I'd hate to here the "all thumbs" recording. :-) Anyway, the "Chopin's fingering" claim comes via Henle. I've added a substantial note explaining.


Trying to Find Article by Tukey

Question: I am trying to find a commonly cited paper by John Tukey published in 1960 called "A
survey of sampling from contaminated distributions", from a monograph(?) called "Contributions in Probability and Statistics".
I can not find this article from either a Google search or a database search from my home university's library.
I am wondering if anyone can provide information that would help me locate this article.
Answer: Tukey, J. W. 1960.
A survey of sampling from contaminated distributions.
In Olkin, I., Ghurye, S.G., Hoeffding, W., Madow, W.G. and Mann, H.B. (Eds)
Contributions to Probability and Statistics: Essays in Honor of Harold Hotelling.
Stanford, CA: Stanford University Press, 448-485.
See also e.g. this bibliography.
Comment: Matt, the chances of there being a legal online copy are slim. Try going to the library and enquiring about inter-library loans.
Comment: That wasn't clear to me; the details you give in your question aren't complete and the book title is slightly incorrect. I don't know an online version of the paper.
Comment: When I search google on the title in Nick's answer, the first link I get is exactly that reference in google books - it shows me all but a few pages of the main article and all but a few pages of the appendix. It also seems to omit one diagram and a page from the references. That would be a pretty good start until you can get the actual thing.
Comment: Thanks for the information, but my problem is that I actually have all this information (along with its ISBN, etc), yet I cannot find it in my library's database (and it searches that of other university libraries in its statewide system) nor on Google. I'd like to know if perhaps there is an online copy somewhere. But looking at the bibliography on Tukey, it may be in one of the sites devoted to his writings, so I'll give it a look. Thanks again
Comment: @Glen_b  I think you're right, in that the library is probably going to have to do some digging, but with the holidays that will be a few days. However, the bibliography of Nick's looks like it contains a lot of Tukey's work, it's worth a shot.
Comment: Somebody just upvoted this (thanks). Being reminded of the thread reminds  me to comment that **this paper wasn't included in any of the 8 volumes published of Tukey's _Collected Works._** Several  more volumes were planned, but the project stalled, or faded away, I gather for all too standard reasons: the money ran out.

Trying to Find Article by Tukey


SQLAlchemy declarative extension vs. elixir

Question: I am planning to use SQLAlchemy in one of my projects and i am very interested in declarative syntax of tables.
I was told to use the Elixir Declarative Layer for that, at the same time SQLAlchemy has its built-in declarative extension.
What are the current differences between Elixir and the declarative extension? Advantages/disadvantages?
Comment: The latest Elixir release is from 2009, so not much has changed on that end.  I don't know if I can provide enough detail for a real answer, but the only advantage I can confirm currently is that you might find Elixir's methods of defining relationships more intuitive for simple projects than SQLA's declarative.  The other differences seem to be trivial.
Comment: Similar: http://stackoverflow.com/questions/3957938/what-are-the-benefits-of-using-elixir
Comment: @robots.jpg, i've seen that question, but is has many question and is 1.5 years old. Is it still actual?
Answer: Elixir exists because SQLA Declarative didn't. Now that we have SQLAlchemy declarative, you probably don't need Elixir unless there's a specific way it does things that you prefer. Just be aware that Elixir is a dead project, and you will be stuck with an older version of SQLAlchemy.


The concept behind relaxing music?

Question:

I am interested to start making some songs that are very relaxing, like the one posted above.
The song above is indeed one of the most relaxing songs in the world. But how? What elements in the song make it particularly relaxing? I noticed the chords as they transitioned smoothly with the piano playing in the background. I also noticed the chord progressions, and how different they were.
What is the theory behind relaxing music? How do the chord progressions, instruments, etc. work in relaxing music?
Comment: Please do not close this; it is not opinion-based. Music is all about eliciting certain psychological reactions, and this case is no different. Just look at @prouvaire's answer; there is nothing subjective about it.
Answer: To me, the tempo of the music is the primary factor in what makes a piece of music relaxing. In the video above, the bpm hovers around 55-60 which makes it ideal for synchonisation to your brainwaves/ resting heart rate. (source)

While listening, your heart rate gradually comes to match that beat. It is important that the song is eight minutes long because it takes about five minutes for this process, known as entrainment, to occur. The fall in heart rate also leads to a fall in blood pressure.

Basically your video goes on for almost an hour, which is plenty of time for your body to slow down to match the music.

There is no repeating melody, which allows your brain to completely switch off because you are no longer trying to predict what is coming next.
  Instead, there are random chimes, which helps to induce a deeper sense of relaxation. The final element is the low, whooshing sounds and hums that are like buddhist chants. High tones stimulate but these low tones put you in a trance-like state.

The video above is very atonal and there's a constant low organ-like tone that probably contributes to relaxing the listener.
There's a very questionable "academy" (homeopathy, basically) called British Academy of Sound Therapy which you can read more about. Google doesn't reveal too many of their techniques, but apparently there are lots of people dedicated to figuring out relaxing sounds.
Comment: It's like the sweeping pads represent the inhaling and exhaling of relaxed breathing, too.
Comment: Actually, some parts do kind-of repeat. Good answer though.
Answer: I listened to the piece yesterday with an analytic ear; this brain activity prevented the piece putting me to sleep. My wife remarked that it was very hypnotic and indeed she fell asleep listening.
The factors which I see contributing to this hypnotic ability are

A very dense sonority (the synth pad) which is akin to a warm blanket enveloping one
A fragmentary melody heard in the background (the piano) which is like the thread of a dreams: glimpsed in the distance but not leading anywhere and not making much sense
A very slow rate of harmonic change - as one answer commmented, consonant with the human pulse
A very repetitive harmony: mainly ii-V. There are a few gratuitous sevenths (I7 and IV7) which make things slightly interesting or even jarring. The amount of time spent on what I would consider to be the I chord is very little, thus giving the feeling that the piece is somehow suspended in space (this may be a pun on my part as there are a few suspended chords).
Answer: Those warm, reedy synth pads seem to contribute a great deal. Simpler, smoother waveforms, and additive synthesis would seem to be good directions for a very soft tone.
Pure sine waves make a nice tone for a soft melody, but adding octaves and other harmonies leads to weird phasing effects that can be more alarming.
Answer: Few real key changes - are there any ? I couldn't listen all the way through and stay awake.
Quite a few accidentals, so it's not completely predictable.
Virtually never resolves, seem to be places where you'd expect the root note and major chord, and the root note is just not played.
Comment: good point about not resolving, but given that there isn't really a key for this, technically it's impossible to have a tonic.

The concept behind relaxing music?


SELECT com COUNT e INNER JOIN

Question: Estou realizando uma avalição de PL/SQL e o cenário seria o seguinte:
Esta seriam as tabelas
Dado esse cenário, eu precisava realizar a seguinte consulta:
"Criar uma procedure para imprimir na tela o nome, CPF e quantidade de relacionados de todos os titulares."
Antes de finalizar a procedure, eu estava testando o select de diversas formas, mas não consegui contar a quantidade de relacionados.
Esse SELECT consegui trazer os dados que quero
SELECT DISTINCT`Titular`.`Nome_Titular`, `Titular`.`Cpf_Titular`
FROM `Titular` AS `Titular`
INNER JOIN `Relacionados` AS `Relacionados`
    ON `Titular`.`Idt_Titular` = `Relacionados`.`Idt_Titular`;

Mas tentando trazer a quantidade, não funcionou
SELECT DISTINCT`Titular`.`Nome_Titular`, `Titular`.`Cpf_Titular`, count(`Titular`.`Idt_Titular` = `Relacionados`.`Idt_Titular`) `Qtd_Relacionados`
FROM `Titular` AS `Titular`
INNER JOIN `Relacionados` AS `Relacionados`
    ON `Titular`.`Idt_Titular` = `Relacionados`.`Idt_Titular`;

Quem puder me ajudar, agradeço imensamente.
Comment: *"Mas tentando trazer a quantidade, não funcionou"* o que quer dizer com não funcionou? mas vejo que tem um `count` ai, e te falta um `group by`, dê uma olhada nisso: https://pt.stackoverflow.com/questions/320487/erro-em-um-simples-select-com-group-by-sql-server/320494#320494
Comment: Entendi Ricardo, eu testei dessa forma com group by e funcionou

https://www.invertexto.com/select

mas eu precisava adicionar mais uma coluna, e nela adicionar a quantidade de id's associados a outro id.

Isso seria possivel?
Obrigado por ajudar Ricardo!!
Answer: Consegui resolver o meu problema, eu precisava do seguinte SELECT.
SELECT `Titular`.`Nome_Titular`, `Titular`.`Cpf_Titular`,
    count(distinct  `Relacionados`.`Idt_Relacionado`)
FROM `Titular` AS `Titular`
INNER JOIN `Relacionados` AS `Relacionados`
ON `Titular`.`Idt_Titular` = `Relacionados`.`Idt_Titular`
GROUP BY `Nome_Titular`, `Cpf_Titular`;

Obrigado a todos.

SELECT com COUNT e INNER JOIN


Renaming intervals to avoid fractions

Question: Any two consecutive piano keys make an interval of 1/2 step (e.g. C to C#, or E to F). Why not just rename that to be a whole step, and avoid having to use fractions? Then, for example, C to F would be 5 steps instead of 2.5, and an octave would be 12 steps.
Just wondering if there is a good reason why it is the way it is, other than, "That's the way it has always been." Would music theory be drastically different if intervals had been named this way all along?
Comment: Actually the steps in a major scale are called seconds, so a step in a scale can be either a minor second or a major second. Thus the term step can mean both of these intervals, but unfortunately the term is also used in a different way when you talk about a half step and a whole step.
Comment: Some people count semitones. If you can forget that "semi" means "half" that works. I doubt it would make much difference, because music theory is more a description of what works than a prescription that makes things work.
Comment: so the _steps_ of the major/minor scales will then be called what, steps and double steps? how is that better than whole and half steps?
Answer: Half steps and whole steps (or tones and semitones) are used to build scales, not to define intervals. Intervals consist of two measurements one which is number of semitones the other is letter name distance. So people would never describe the interval of C to F as 2.5 steps, but a perfect fourth (P4). If there ever is a need to talk in pure chromatic steps which can happen when taking outside of letter names, the term semitones will be used (a P4 is 5 semitones) since it is the smaller unit.
The steps are used in context of talking about the distance between one letter name and the next in a scale. The whole step is the typical step size with the major scale consisting of 5 whole and 2 half steps. If the name half and whole are hard to get over, treat them as "small" step and "big" step respectively.
Comment: Since a semitone = 1 fret, guitarists talk about a number of frets - thus C>F is 5 frets. A lot wouldn't even consider P4!
Answer: If we hadn't used 'tone' and 'semi-tone'   (the slightly more cumbersome 'whole-step' and 'half-step' are, I think, a later Americanism)  we'd doubtless have coined something like 'gap' and 'double-gap'.  I doubt that Western music would have leapt straight into Dodecaphonism.
Comment: More cumbersome, perhaps, but certainly less ambiguous, given that "tone" can also be a synonym for "pitch."
Comment: Yeah, I guess.  Though I'm struggling to think of a context where there could be confusion. Got anything?
Comment: The example that prompted my comment was [Tim's comment](https://music.stackexchange.com/questions/103561/where-did-the-term-tone-originate/103565?noredirect=1#comment177863_103565 "The higher the tension the higher the tone? But one tone is a difference in pitch, so that doesn't sound too plausible. – Tim") on an answer to his recent question: "The higher the tension the higher the tone? But one tone is a difference in pitch, so that doesn't sound too plausible"
Answer: Only because it's called Semitone shouldn't mean that you have to think in terms of fractions. Even if it seems a little silly at first, once we think of Semitone as 1 and Tone as 2, everything is clear.
Once you get over the name, you can easily understand and visualize scales as combinations of tones and semitones, i.e. steps and half steps.
For example, major scale: T T S T T T S, which is the same as 2 2 1 2 2 2 1, etc.
Why call the first Tone and the second Semi-tone? I'm no historian by these names didn't start as English names, they were translations of Italian or perhaps Latin names used in the late middle ages, and whatever was first used back then stuck until now.
Comment: Interesting. There are more whole steps than half steps in the major scale, so maybe that influenced the names. As in, "We should call the more common interval in the scale a whole step."
Comment: @DreiCleaner perhaps it was something like that, though the terminology was settled on long before the major scale came into existence.

Renaming intervals to avoid fractions


How to get Acces Token for Google API using Asp.Net MVC 5 Web and OWIN / Katana

Question: Having a Asp.Net MVC 5 Web Role using OWIN Katana Components for OAuth and OpenId. Enabled Google Authentication support inside Startup.Auth.cs (provided by default MVC 5 template).
Everything works fine until authentication but not sure how to request authorizaion token as mentioned here Google Contacts API v3.
Please share pointers to samples or documentation. Thank you.
Answer: Google has multiple authentication protocols.  The one implemented in Katana v2.0 is not OAuth2, so there is no authorization token.  It's only useful for having google confirm who the user is, it does not give you access to their resources.
In Katana v2.1-rc1 (coming this month) support is being added for Google's OAuth2 protocol.
https://katanaproject.codeplex.com/SourceControl/changeset/0eb10848ae18a5f339e7fde8ff1e877242e944dc


Change system file temporary maximum age

Question: The default setting given to delete temp files is after 6 hours minimum. I have users upload files and I want that if it has temp status, delete it after 15 secs. Tweaking the file module code is risky, if I get the exact location to change 6 hours to 15 sec that will do the job.
Comment: That also means you need to have a cron job running every 15 seconds. That job then triggers drush cron maybe. Can you maybe paste a link to the exact line of the file module on git.drupalcode.org you identified being responsible for the 6h minimum into your question?
Answer: The value returned from \Drupal::config('system.file')->get('temporary_maximum_age') is the value that decides when temporary files are deleted. Using the following code, for example, you can change that value to 15 seconds.
\Drupal::config('system.file')->set('temporary_maximum_age', '15');

If you want to change the form as well, which is recommended, use hook_form_FORM_ID_alter() to adjust the system file settings shown in the system_file_system_settings form.
The code currently used for that setting is the following one.
$intervals = [0, 21600, 43200, 86400, 604800, 2419200, 7776000];
$period = array_combine($intervals, array_map([$this->dateFormatter, 'formatInterval'], $intervals));
$period[0] = $this->t('Never');
$form['temporary_maximum_age'] = [
  '#type' => 'select',
  '#title' => $this->t('Delete temporary files after'),
  '#default_value' => $config->get('temporary_maximum_age'),
  '#options' => $period,
  '#description' => $this->t('Temporary files are not referenced, but are in the file system and therefore may show up in administrative lists. Warning: If enabled, temporary files will be permanently deleted and may not be recoverable.'),
];

You can alter the form and adjust it to what you need.
Keep in mind that files are effectively deleted after 15 seconds if cron tasks run at least every 15 seconds.
Comment: @PankhuriSingh you should not change the core file, you can override that from your own custom module, and in order to have the file deleted your corn should run at least every 15sec, that's why I told you it makes no sense to do that. in case you really want to do that every 15 sec then you need to do it without depending on cron tasks.
Comment: Thank you @Ziftman, I did the same and changed 21600 to 15 in /core/modules/system/src/Form/FileSystemForm.php and uploaded a new temp file. However, the file was not deleted automatically after 15 seconds. Please tell me what did I miss.
Answer: Add to local.settings.php
$config['system.file']['temporary_maximum_age'] = 15;

Note that the temporary files are deleted on cron , which is settable to 1h minimum through the back office or less using server cron job https://www.drupal.org/docs/7/setting-up-cron/configuring-cron-jobs-using-the-cron-command


User unregistration

Question: I'm looking for the most Drupal way to allow registered users to request unregistration.
The website would provide a form to request the unregistration from the site, and the administration would then confirm the unregistration.
Is there a module that provides this functionality?
Answer: There is a "Cancel own user account" permission in admin/people/permissions. If you assign it to your authenticated users, they will see a "Cancel account" link in their user profile ("Edit" tab). Would it be enough for your needs?
Additionally, you can configure the way the account is cancelled, in admin/config/people/accounts, in the "When cancelling a user account" section.
Hope that helps,
Comment: Using the configuration mentioned above, you could "disable" the account instead of deleting it. You could also set up a rule so that admins are emailed when a user cancels/disables their account.
Answer: You could use the Webform module to create a form that sends an email to admin users with a link to cancel the account. In the email that is sent, you would just have to use the token for the Current User ID and create a link to cancel the account (yourwebsite.com/user/xxx/cancel) where xxx = their User ID.
The admin would just have to click the link in the email and follow through with the steps to cancel/deactivate the account.

User unregistration


advanced openvpn - how do clients generate their own private keys and get the remote ca to sign their certificate

Question: From answers to this question ive been recommended to not create client keys on the server home to ca.key but rather make the clients create their own private key and simple pass a csr to the ca server to be signed and get it back. This way private keys do not have to be distributed.
Ive googled quite a fair few terms and phrases but i havnet hit anything regarding how to do this. Ive looked at the howto on openvpn and though it discusses this option, it doesnt say how. Can anyone point me to any tutorials etc?
Id also like to know how easy this would be to do for clients, especially if they arent so hot with computers.
Answer: There are a couple of ways.

What we do most commonly, because most of our certificates are issued straight onto hardware tokens and the end users are Windows/IE based, is to automagically generate the key and request from the browser using MS CAPI. It's pretty foolproof and utterly low touch. This would suit you if your users are Windows based and you intend for the certificates to be installed in the local certificate store. Once the certificate is signed then you can provide them a link to collect their certificate and place it straight back into the store alongside the existing private key.
Alternatively, something that we do for non-Wintel users, is to provide them with a complete command that they can copy and run to generate the required output. Typically this is OpenSSL for us but you could reference the utilities packaged with OpenVPN since they should already have that installed. Then they paste the CSR back into a web form, it receives some simple validation and sent back for signing. You then return them the CRT with final instructions of what to do.

My experience is that you need to provide users with details of "what to do" in the least amount of instructions possible. Try to do as much of the work for them as possible and restrict the scope for misinterpretation.
Comment: 1) Sounds extremely cool, but I've no idea where I'd start looking for how to do it ...
Comment: it does sound cool and extremely slick though i think its out of my reach. Perhaps if my nubmers grow i can look more into that or even outsource. Thanks Dan for all your help on both my questions!
Comment: We did something similar to 2 where I worked. We rolled our own installation package with everything pre-configured as much as possible. Then used the MyCertificateWizard app with most fields pre-populated so that the end user only had to put in their email address and choose a password for their key. Then just had them email us their csr. We would verify that they used their work email address and then emailed them back their cert with instructions on how to install it and update the configuration files to use it.
Comment: Like my answer to the other topic, option #1 wasn't the cheapest to implement. But it was eventually deemed necessary given the size. MyCertificateWizard looks pretty good for the purpose. One of the things we're had to be especially careful about is the validation. Always make sure that the CSR content is as expected before you accept it for signing.
Answer: Specially i build client's key and certificate in a remote machine that differ from the openvpn server.
You can find here a nice tuto, i hope that can help you http://www.throx.net/2008/04/13/openvpn-and-centos-5-installation-and-configuration-guide/
Comment: thanks for your link. Ill going to give that a good read after a coffee break!


Are there any issues with installing memcache on a VPS running multiple Drupal sites?

Question: I have a VPS running a few independent Drupal sites (not multi-site). What considerations do I need to make (if any) when installing memcache?
Answer: Make sure your settings.php file has a unique prefix for each site that has memcache enabled.  I got tripped up by this, and everything went berserk. This thread fixed it for me.  Basically, this is the only issue you would have as far as conflicts.
http://drupal.org/node/1416102
Like APC, memcache works indepedently of your sites.  Make sure you have enough memory for it to function correctly.  You can get a rough idea idea by seeing how much disk space all of your drupal databases take up.  Not all tables in each database will be cached of course, but so long as you have that much memory to dedicate to memcache, you are good to go.
Said differently, as an example I have 12 sites on my VPS 4 gigs of RAM total with 1 Gig dedicated to memcache.  I have never had a problem. Total size of databases on disk is around 400 mb.
Comment: Did this answer your question or can I help clarify a bit more?
Answer: Then important thing is that you give each site a different prefix, see http://drupal.org/node/1131468.
Of course, it's the same about memory as with APC. Depending on how much memory you have, you might want to use memcache only for sites which have a high(er) load than others and keep cache of the less used ones in the database or use another cache backend that doesn't sit in memory.


Passar List como parâmetro de expressão LINQ

Question: Tenho uma expressão LINQ em que o resultado é salvo na variável query, que é transformada em lista, esta query retorna uma série de atributos "RA".
Gostaria de passar essa lista de atributos como parâmetro na expressão LINQ resultada na query2. Quero que a query2 me retorne todos os códigos de disciplina em que esses "RA" estão relacionados(Sim, quero passar todos eles de uma vez).
Fiz da forma abaixo porém não obtive resultados, o código compilou, mas não funcionou. Como passo a lista query como parâmetro no where? Devo converter essa lista de 1 um único atributo para um tipo comum? Como faço?
void cargarDados(Int32 disc)
    {
       List<Turma> turmas = db.GetCollection<Turma>("turma").FindAll().ToList();

        var query = (from t in turmas
                     where t.COD_DISCIPLINA == disc
                     select new
                     {
                         t.RA

                     }).ToList();

        var query2 = (from t1 in turmas
                      where t1.COD_DISCIPLINA.Equals(query)
                      select new
                      {
                          t1.COD_DISCIPLINA
                      }).ToList();

        dataGridView1.DataSource = query2;

    }

Answer: Você pode fazer assim;
protected void Page_Load(object sender, EventArgs e)
{
    cargarDados(1);
}

void cargarDados(Int32 disc)
{
    List<Turmas> turmas = new List<Turmas>();// db.GetCollection("turma").FindAll().ToList();
    Turmas turma = new Turmas();
    turma.RA = 1;
    turma.COD_DISCIPLINA = 1;
    turmas.Add(turma);

    Turmas turma1 = new Turmas();
    turma1.RA = 2;
    turma1.COD_DISCIPLINA = 1;
    turmas.Add(turma1);

//----------------------------------------------------------------//
    var RA = turmas
        .Where(t => t.COD_DISCIPLINA == disc)
        .Select(t => t.RA).ToList();

    var query2 = turmas
        .Where(t => RA.Contains(t.COD_DISCIPLINA))
         .Select(t => new
         {
             t.COD_DISCIPLINA,
         })
         .ToList();
//-------------------------------------------------------------//
}

class Turmas
{
    public Int32 COD_DISCIPLINA { get; set; }
    public Int32 RA { get; set; }
}

Comment: Obrigado Marconcilio, funfou, e com boa performance ! Valeu
Answer: Perceba que quando você faz um new { t1.RA }, você na verdade está criando um novo tipo anônimo que não te dará o resultado desejado ao comparar com o tipo da propriedade COD_DISCIPLINA.
Como sugestão final, sugiro fazer tudo em uma query só:
    var query2 = (from t1 in turmas
                  where (from t in turmas
                         where t.COD_DISCIPLINA == disc
                         select t.RA).Contains(t1.COD_DISCIPLINA)
                  select new
                  {
                      t1.COD_DISCIPLINA
                  }).ToList();

Comment: Obrigado Jônatas, aqui funfou
Answer: Faz assim:
void cargarDados(Int32 disc)
        {
            List turmas = db.GetCollection("turma").FindAll().ToList();

        var query = (from t in turmas
                     where t.COD_DISCIPLINA == disc
                     select new
                     {
                         t.RA

                     }).ToList();

        var query2 = (from t1 in turmas
                      where query.Contains(t1.COD_DISCIPLINA)
                      select new
                      {
                          t1.COD_DISCIPLINA
                      }).ToList();

        dataGridView1.DataSource = query2;

    }


append() function is taking a long time to run

Question: Firstly, I just got started in Python and therefore I do not have much knowledge. I tried to search this problem over and I could not find a proper solution.
Just to make a brief: I am studying a traffic accidents database that has almost 165000 rows and 39 columns. One of the steps that I am taking is running apriori algorithm (from apyori lab) in this base.
If you want, you can donwnload the base (.csv) here.
However, in order to do that, I have to transform my pandas database into a list and this is the part that I am having problems.
I am using the following code:
def list_apriori(df):
apr = []
for i in range (0, 164699):
    apr.append([str(df.values[i,j]) for j in range (0,38)])

return apr

I left this code running for almost 40 minutes and it didn't finish, so I thought that maybe there is an improved way to do so.
I've made a test with:
def list_apriori(df):
apr = []
for i in range (0, 50):
    apr.append([str(df.values[i,j]) for j in range (0,10)])

return apr

It finished in less than 5 minutes (which I believe that is a long time given that it is only running in 51 rows and 11 columns).
I also tried to change the computer, but I did not feel any difference.
Do you have any suggestions of if and how I can improve the code in order to run it faster?
Thanks in advance.
EDIT
I believe that the problem was the conversion to string. Thanks @ninesalt for the help!
The code that worked is the following:
def list_apriori(df):
result = df.astype(str)
apr = []
for i in range (0, 164699):
    apr.append([df.values[i,j] for j in range (0,38)])

return apr

Comment: Welcome to StackOverflow.  Please read and follow the posting guidelines in the help documentation, as suggested when you created this account.  [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here.  We cannot effectively help you until you post your MCVE code and accurately describe the problem.
We should be able to paste your posted code into a text file and reproduce the problem you described.
Comment: The operating in your for loop (first code fragment) runs more than 6 millions time because you're doing it 39 times per iteration
Comment: Thanks, i should have read it fully. I will try to do that.
Sorry.
Comment: @MatheusTurchet I am doubt about `df.values[i,j]`. You have to time the `df.values[i,j]` section. Because the python `append` should not take this much time.
Comment: @RamIdavalapati I watched a video that the same code ran in ~4k rows and 20 columns and it took less than 5 seconds. I do agree with you that it should not take this amount of time, but I am not finding the problem.
Answer: Here is exactly what you wanted but without the loops. This takes 3 seconds on my PC and the dataframe is the same size as the one in your example (165000, 39)
import numpy as np
import pandas as pd

arr = np.random.randint(0, 100, (165000, 39))
df = pd.DataFrame(arr)
result = df.astype(str)

firstrow = result.iloc[[0]]
print(firstrow)  # prints first row as a string

Whenever you have something that you think is an expensive operation, there's almost always an easier and more efficient way to do it with the library you're using, you just have to check the docs.
Comment: from what I understood, this just converts all my df in string values (sorry if I am not right). What I want to do is convert them into string and then create a list (which I named apr) with these values.
Comment: @matheusturchet Thats the same thing, the df is a list of lists. What you want to do is go row by row and add the the current 1D list to apr to make it 2D. My answer does the same thing.
Comment: it worked perfectly. thanks! i just do not understand why the code that i wrote was not effective.


Issues with casting inconsistent dates with Apache Drill

Question: I have list of dates which are unfortunately inconsistent:
3/09/2015 15:20:03
29/04/2014
06/03/2012
31/12/2015 06:29:40
13/05/2014
20/02/2010
01/10/2015 23:46:12
17/11/2014
30/10/2015 22:28:00
14/02/2014

I'm trying to cast these objects into a consistent format: date or timestamp but cannot do so with something like this:
 SELECT TO_TIMESTAMP(DATE_OF_BIRTH, 'dd/MM/yyyy HH:mm:ss') FROM PERSON

or
 SELECT TO_DATE(DATE_OF_BIRTH, 'dd/MM/yyyy') FROM PERSON

The resulting error is shown.
UserRemoteException: SYSTEM ERROR: IllegalArgumentException: I nvalid format: "13/09/2015 15:20:03" is malformed at " 15:20:03" Fragment 0:0

How can I get drill to accept multiple formats for conversion.
Answer: If you only want the date, just cast the left-most 10 characters:
SELECT TO_DATE(SUBSTR(DATE_OF_BIRTH, 1, 10), 'dd/MM/yyyy')
FROM PERSON


Django - obtaining a child model from a parent by the childs one to one field?

Question: Good Afternoon,
I have a pair of models like the below:
class DeviceCircuitSubnets(models.Model):
    device = models.ForeignKey(Device, on_delete=models.CASCADE)
    circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE, blank=True, null=True)
    subnet = models.ForeignKey(Subnet, on_delete=models.CASCADE)
    ...

class BGPData(models.Model):
    device_circuit_subnet = models.OneToOneField(DeviceCircuitSubnets, verbose_name="Device", on_delete=models.CASCADE)
    bgp_peer_as = models.CharField(max_length=20, verbose_name='BGP Peer AS', blank=True, null=True)
    bgp_session = models.CharField(max_length=10, verbose_name='BGP Session', blank=True, null=True)
    bgp_routes = models.CharField(max_length=10, verbose_name='BGP Routes Received', blank=True, null=True)
    service_status = models.CharField(max_length=10, verbose_name='Service Status', blank=True, null=True)
    timestamp = models.DateTimeField(auto_now=True, blank=True, null=True)

I am filtering the DeviceCircuitSubnets and then I also want to access the BGPData related model via each filtered item.
service_data = DeviceCircuitSubnets.objects.filter(monitored=True, device__site_id=site_id) \
                                            .select_related('device','circuit','subnet')

I have tried adding bgpdata to the select related and to prefetch but neither are currently working, I am returned with an error stating the model doesn't exist.
how would my query need to look to obtain each one to one field in a query set?
Thank you
Answer: Since you didn't set related_name attribute on OneToOneField, you need to use lower-cased model name for reverse relation:
service_data = DeviceCircuitSubnets.objects.filter(monitored=True, device__site_id=site_id) \
                                            .select_related('bgpdata')

Note also that:

A DoesNotExist exception is raised when accessing the reverse relationship if an entry in the related table doesn't exist


Syntax of an Sqlite query?

Question: When i execute the code below, it always keeps giving me "invalid" even if I replace usertry by a predetermined string.. Is there any syntax problem in my query?
The check login method is in another class that checks for valid login
<code>    public void checklogin(String usertry){

    DatabaseHelper dbh = new DatabaseHelper(LoginActivity.this);
    DatabaseAdapter dba = new DatabaseAdapter(LoginActivity.this);
    db= dbh.getReadableDatabase();
    TextView usernametry = (TextView) findViewById(R.id.usernametry);
     usertry = usernametry.getText().toString();

    Cursor mCursor = db.query(dba.TABLE_USERS,new String[]{dba.COLUMN_ID,dba.COLUMN_NAME},  dba.COLUMN_NAME + "=" + "?", new String[]{usertry},null,null,null,null);

     if  (mCursor.moveToFirst()){
         Toast.makeText(LoginActivity.this, "Yaaaay", Toast.LENGTH_LONG).show();
     }

      Toast.makeText(LoginActivity.this, "invalid", Toast.LENGTH_LONG).show();
        }
}
</code>
Here is my DB adapter class:
<code>  public class DatabaseAdapter {

public static final String COLUMN_ID = "ID";
public static final String COLUMN_NAME = "Name";
public static final String COLUMN_AGE = "Age";
public static final String COLUMN_GENDER = "Gender";
public static final String COLUMN_WEIGHT = "Weight";
public static final String COLUMN_HEIGHT = "Height";
public static final String COLUMN_ACTIVITY = "Activitylevel";
public static final String COLUMN_CALORIES = "numCal";
public static final String FOOD_ID = "food_ID";
public static final String FOOD_NAME = "food_name";
public static final String FOOD_CALS = "food_cals";
public static final String FOOD_FAT = "food_fat";
public static final String FOOD_PRO = "food_protein";
public static final String FOOD_CRAB = "food_crabs";

public static final String TABLE_USERS = "users";
public static final String TABLE_FOOD = "food";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "nutriwellness.db";

private static final String CREATE_TABLE_USERS = "create table users( id integer primary key autoincrement, "
        + "Name text, Age integer, Gender text, Weight text, Height text, Activitylevel text, numCal float );";

private static final String CREATE_TABLE_FOOD = "create table food( food_ID integer primary key autoincrement,"
        + "food_name text,food_cals integer, food_fat integer, food_protein integer, food_crabs integer );";

private SQLiteDatabase database;
private DatabaseHelper dbHelper;

private String[] allColumnsofuserstable = { COLUMN_ID, COLUMN_NAME,
        COLUMN_AGE, COLUMN_GENDER, COLUMN_WEIGHT, COLUMN_HEIGHT };

private String[] allColumnoffoodtable = { FOOD_ID, FOOD_NAME, FOOD_FAT,
        FOOD_PRO, FOOD_CRAB };

public DatabaseAdapter(Context context) {

    dbHelper = new DatabaseHelper(context);
}

public static class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 5);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(CREATE_TABLE_USERS);
            db.execSQL(CREATE_TABLE_FOOD);
        } catch (SQLException e) {

            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading database from version " + oldVersion
                        + "to version " + newVersion);

        db.execSQL("DROP TABLE IF EXISTS users");
        onCreate(db);

    }

}

public DatabaseAdapter open() throws SQLException {
    database = dbHelper.getWritableDatabase();
    return this;
}

public void close() {
    dbHelper.close();
}

// create a user
public long createUser(String name, String age, String gender,
        String weight, String height, String level, float calnum) {

    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, name);
    values.put(COLUMN_AGE, age);

    values.put(COLUMN_GENDER, gender);

    values.put(COLUMN_WEIGHT, weight);
    values.put(COLUMN_HEIGHT, height);
    values.put(COLUMN_ACTIVITY, level);
    values.put(COLUMN_CALORIES, calnum);

    return database.insert(TABLE_USERS, COLUMN_ID, values);
}

// delete a user by ID
public boolean deleteUser(long rowId) {
    return database.delete(TABLE_USERS, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieve a list of all users
public Cursor getAllUsers() {
    return database.query(TABLE_USERS, allColumnsofuserstable, null, null,
            null, null, null);

}

// retrieve a particular user
public Cursor getUser(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_USERS,
            allColumnsofuserstable, COLUMN_ID + "=" + rowId, null, null,
            null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

// update a user
public boolean updateUser(long rowId, String Name, int age, String gender,
        String weight, String height, String level, float calnum) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, Name);
    values.put(COLUMN_AGE, age);

    values.put(COLUMN_GENDER, gender);

    values.put(COLUMN_WEIGHT, weight);
    values.put(COLUMN_HEIGHT, height);
    values.put(COLUMN_ACTIVITY, level);
    values.put(COLUMN_CALORIES, calnum);
    return database.update(TABLE_USERS, values, COLUMN_ID + "=" + rowId,
            null) > 0;
}

// FOOD METHODS !

//Create a new food row
public long createFood(String name, int food_cal, int food_fat, int food_proteins, int food_carbs){
    ContentValues Fvalues = new ContentValues();
    Fvalues.put(FOOD_NAME, name);
    Fvalues.put(FOOD_CALS, food_cal);
Fvalues.put(FOOD_FAT, food_fat);
    Fvalues.put(FOOD_PRO, food_proteins);
    Fvalues.put(FOOD_CRAB, food_carbs);
    return database.insert(TABLE_FOOD, FOOD_ID, Fvalues);
}

// delete a Food by ID
public boolean deleteFood(long rowId) {
    return database.delete(TABLE_FOOD, FOOD_ID + "=" + rowId, null) > 0;
}
// retrieve a list of all FOOD
public Cursor getAllfood() {
    return database.query(TABLE_FOOD, allColumnoffoodtable, null, null,
            null, null, null);

}

// Retrieve a specific Food

public Cursor getFood(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_FOOD,
            allColumnoffoodtable, FOOD_ID + "=" + rowId, null, null,
            null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

// Update a food

public boolean updateFood(long rowId,String name, int food_cal, int food_fat, int food_proteins, int food_carbs){
    ContentValues Fvalues = new ContentValues();
    Fvalues.put(FOOD_NAME, name);
    Fvalues.put(FOOD_CALS, food_cal);
Fvalues.put(FOOD_FAT, food_fat);
    Fvalues.put(FOOD_PRO, food_proteins);
    Fvalues.put(FOOD_CRAB, food_carbs);
    return database.update(TABLE_FOOD, Fvalues, FOOD_ID+"="+rowId, null)>0;
}
}
</code>
Answer: Obviously this Toast message will always been shown, even if your query works. You should try something like :
<code>if  (mCursor.moveToFirst()){
         Toast.makeText(LoginActivity.this, "Yaaaay", Toast.LENGTH_LONG).show();
     }else{
         Toast.makeText(LoginActivity.this, "invalid", Toast.LENGTH_LONG).show();
     }
</code>
But I guess this is not the real problem, but I don't see any other problems. Maybe we need to see your DatabaseAdapter class.
Comment: Have you checked whether your _database_ is getting loaded in **DDMS**

Syntax of an Sqlite query?


How to find $\lim_{n\to\infty}\Big(\sum_{k=1}^n\sqrt{\frac{1}{k}-\frac{1}{n}}-\frac{\pi}{2}\sqrt n\Big)$?

Question: I'm looking for the asymptotic of the series $\displaystyle S(n)=\frac{1}{2}\sum_{k=1}^n\int_k^n\frac{dx}{x\sqrt{x(n-x)}}\,$ at $\,n\to\infty$
The first term can be found, for example, via switching to Riemann sums, changing the order of integration, and is equal to $\frac{\pi}{2}$. To find the next term I performed integration and got
$$S(n)=\frac{1}{n}\sum_{k=1}^{n-1}\sqrt{\frac{n}{k}-1}=\frac{1}{\sqrt n}\sum_{k=1}^{n-1}\sqrt{\frac{1}{k}-\frac{1}{n}}=\frac{1}{\sqrt n}\sum_{k=1}^{n-1}f(k)\tag{1}$$
To get the flavour of the next asymptotic term I used the Euler-Maclaurin formula
$$\sum_{k=1}^{n-1}f(k)\sim\int_1^{n-1}f(k)dk+\frac{1}{2}\big(f(1)+f(n-1)\big)+\frac{1}{12}\big(f'(n-1)-f'(1)\big)+ ...\tag{2}$$
At $n\to\infty$ the first term (the integral) gives $\frac{\pi}{2}\sqrt n-2$; other terms in (2) give non-zero values at $k=1$. Evaluating a couple of such terms, I got
$$\sum_{k=1}^{n-1}f(k)\sim\frac{\pi}{2}\sqrt n-2+\frac{1}{2}+\frac{1}{24}=\frac{\pi}{2}\sqrt n-1.4583$$
The numeric evaluation at WolframAlpha for $n=1000$ gives
$$ \sum_{k=1}^{n-1}f(k)-\frac{\pi}{2}\sqrt n\,\bigg|_{n=1000}=-1.46046$$
All this strongly resembles $\displaystyle \zeta\Big(\frac{1}{2}\Big)=-1.46035...\,\,$; at  $\,n=10000\,$ we get even better agreement.

Questions:

How can we prove that $\,\,\displaystyle \lim_{n\to\infty}\Big(\sum_{k=1}^n\sqrt{\frac{1}{k}-\frac{1}{n}}-\frac{\pi}{2}\sqrt n\Big)=\zeta\Big(\frac{1}{2}\Big)\,\,$?
Can we get next asymptotic terms (at least, several of them) analytically ?
Comment: @KamalSaleh $\zeta(s)$ is defined everywhere except for $s=1$ (as a complex function)
Comment: It is based on heuristics and numerics. Looking at Sangchul Lee's answer if we expand $1/\sqrt{1-s/n}$ then $$S(n) \sim \frac{\pi }{2} + \frac{1}{{\sqrt n }}\sum\limits_{m = 0}^\infty  {\binom{m - 1/2}{m}\frac{1}{{n^m }}{\left( { - \frac{1}{2}\int_0^n {\frac{{s - \left\lfloor s \right\rfloor }}{{s^{1 + 1/2 - m} }}{\rm d}s} } \right)}} .$$ Thus we need that, in some sense, $$
 - \frac{1}{2}\int_0^n {\frac{{s - \left\lfloor s \right\rfloor}}{{s^{1 + 1/2 - m} }}{\rm d}s}  \sim \zeta \left( {\tfrac{1}{2} - m} \right).
$$
Comment: I belive the asymptotic expansion of $S(n)$ is $$
S(n) \sim \frac{\pi }{2} + \frac{1}{{\sqrt n }}\sum\limits_{m = 0}^\infty  {\binom{m - 1/2}{m}\frac{{\zeta (1/2 - m)}}{{n^m }}} .
$$
Comment: @Gary. Could we know how you did arrive to this beautiful result ? Thanks & cheers :-)
Comment: $\zeta(1/2)$ is undefined, isn't it?
Comment: It can be defined as $\lim_{n\to\infty}\Big(\sum_{k=1}^n\frac{1}{\sqrt k}-2\sqrt n\Big)$
Comment: @Gary, looks very nice. Could you share your ideas?
Answer: Starting from the equality $ \frac{\pi}{2}\sqrt{n} = \int_{0}^{n} \sqrt{\frac{1}{x} - \frac{1}{n}} \, \mathrm{d}x$, we get
\begin{align*}
\sqrt{n}\left( S(n) - \frac{\pi}{2} \right)
&= \sum_{k=1}^{n} \sqrt{\frac{1}{k} - \frac{1}{n}} - \frac{\pi}{2}\sqrt{n} \\
&= \sum_{k=1}^{n} \sqrt{\frac{1}{k} - \frac{1}{n}} - \int_{0}^{n} \sqrt{\frac{1}{x} - \frac{1}{n}} \, \mathrm{d}x \\
&= \sum_{k=1}^{n} \int_{k-1}^{k} \biggl( \int_{x}^{k} \frac{\partial}{\partial s} \sqrt{\frac{1}{s} - \frac{1}{n}} \, \mathrm{d}s \biggr) \, \mathrm{d}x \\
&= \sum_{k=1}^{n} \int_{k-1}^{k} \biggl( \int_{k-1}^{s} \frac{\partial}{\partial s} \sqrt{\frac{1}{s} - \frac{1}{n}} \, \mathrm{d}x \biggr) \, \mathrm{d}s \\
&= -\frac{1}{2} \int_{0}^{n} \frac{s - \lfloor s \rfloor}{s^{3/2}\sqrt{1 - s/n}} \, \mathrm{d}s  \\
&= -\frac{1}{2} \int_{0}^{0.2022 n} \frac{s - \lfloor s \rfloor}{s^{3/2}\sqrt{1 - s/n}} \, \mathrm{d}s + \mathcal{O}(n^{-1/2}).
\end{align*}
Then by the dominated convergence theorem, this converges to
$$ -\frac{1}{2} \int_{0}^{\infty} \frac{s - \lfloor s \rfloor}{s^{3/2}} \, \mathrm{d}s = \zeta\left(\frac{1}{2}\right) $$
as $n \to \infty$. (Note that $\zeta(s) = -s \int_{0}^{\infty} \frac{x-\lfloor x \rfloor}{x^{1+s}} \, \mathrm{d}x $ for $0 < \operatorname{Re}(s) < 1$, see the entry 25.2.8 of DLMF.)
Comment: Thank you for your nice solution!
Comment: In line three, the inner integral in $s$ is with the range $k-1\le x\le s\le k$. In line four, you integrate in $x$ with the range $k-1\le s\le x\le k$ which seems wrong to me. It should be, I think: $$\int_{k-1}^s\frac{\partial}{\partial s}\sqrt{\frac{1}{s}-\frac{1}{n}}\,\mathrm{d}x$$On the inside
Comment: @FShrike, You are absolutely correct. Indeed we need the integral $$\int_{k-1}^{s}\mathrm{d}x=s-(k-1)=s-\lfloor s\rfloor$$ for each $k-1<s<k$. Let me fix the bounds accordingly.
Comment: I may suppose 0.2022 factor is related to the current, 2022 year AD :)
Comment: @FShrike, Indeed I simply picked a number in $(0,1)$ that looks fun and reasonably arbitrary to signal that any fixed number between 0 and 1 can be used. :)
Comment: Doing my own calculation, I think $\int_0^{\alpha n}$ for any $0<\alpha<1$ fixed will do. The error term can be bounded by: $$0<|\text{error}|<\frac{1}{\sqrt{n}}\cdot2\alpha^{-3/2}\sqrt{1-\alpha}$$
Comment: The $0.2022$ factor is a little mysterious for me. I understand you want to reduce the range to make sure there is no problem as $s\to n$ - to make the DCT viable - but that specific number and your specific $+\mathcal{O}(n^{-1/2})$ error suggest there is a deliberate method you used to find $0.2022$ (this is an approximation I expect). What is that method, may I ask?
Answer: Observe that
$$
\frac{{{\mathop{\rm Li}\nolimits} _{1/2}^2 (z)}}{2} = \sum\limits_{n = 2}^\infty  {S(n)z^n } , \quad |z|<1,
$$
where $\operatorname{Li}_s(z)$ is the polylogarithm. (This follows by integrating $
\frac{1}{z}{\mathop{\rm Li}\nolimits} _{ - 1/2} (z){\mathop{\rm Li}\nolimits} _{1/2} (z) = {\mathop{\rm Li}\nolimits}'_{1/2} (z){\mathop{\rm Li}\nolimits} _{1/2} (z) = \frac{1}{2}({\mathop{\rm Li}\nolimits} _{1/2}^2 (z))'
$.) The asymptotics of $S(n)$ for large $n$ is controlled by the singularity of the left-hand side at $z=1$. The polylogarithm may be expanded into a series
$$
{\mathop{\rm Li}\nolimits} _{1/2} (z) = \sqrt \pi  ( - \log z)^{ - 1/2}  + \sum\limits_{k = 0}^\infty  {\frac{{\zeta (1/2 - k)}}{{k!}}\log ^k z}
$$
provided $|\log z|<2\pi$. This gives
\begin{align*}
\frac{{{\mathop{\rm Li}\nolimits} _{1/2}^2 (z)}}{2} & =  - \frac{\pi }{{2\log z}} + \sum\limits_{k = 0}^\infty  {( - 1)^k \sqrt \pi  \frac{{\zeta (1/2 - k)}}{{k!}}( - \log z)^{k - 1/2} }  + F(z)
\\ & = \frac{\pi }{{2(1 - z)}} + \sum\limits_{k = 0}^\infty  {( - 1)^k \sqrt \pi  \frac{{\zeta (1/2 - k)}}{{k!}}( - \log z)^{k - 1/2} }  + G(z)
\end{align*}
as $z\to 1$, where $F(z)$ and $G(z)$ are holomorphic at $z=1$. Accordingly,
$$
\sum\limits_{n = 2}^\infty  {\left( {S(n) - \frac{\pi }{2}} \right)z^n }  = \sum\limits_{k = 0}^\infty  {( - 1)^k \sqrt \pi  \frac{{\zeta (1/2 - k)}}{{k!}}( - \log z)^{k - 1/2} }  + G(z)
$$
as $z\to 1$. The behaviour of the right-hand side near $z=1$ is
$$
\sqrt \pi  \zeta (1/2)(1 - z)^{ - 1/2}  - \sqrt \pi  \left( {\zeta ( - 1/2) + \frac{{\zeta (1/2)}}{4}} \right)(1 - z)^{1/2}  + \mathcal{O}((1 - z)^{3/2} ) + \mathcal{O}(1).
$$
Singularity analysis shows that the $n$th Maclaurin coefficient of this function is
$$
\frac{{\zeta (1/2)}}{{n^{1/2} }} + \frac{{\zeta ( - 1/2)}}{{2n^{3/2} }} + \mathcal{O}\!\left( {\frac{1}{{n^{5/2} }}} \right)
$$
as $n\to +\infty$. Consequently,
$$
S(n) = \frac{\pi }{2}+\frac{{\zeta (1/2)}}{{n^{1/2} }} + \frac{{\zeta ( - 1/2)}}{{2n^{3/2} }} + \mathcal{O}\!\left( {\frac{1}{{n^{5/2} }}} \right)
$$
as $n\to +\infty$. This is in agreement with the conjectured asymptotic expansion
$$
S(n) \sim \frac{\pi }{2} + \frac{1}{{\sqrt n }}\sum\limits_{m = 0}^\infty  {\binom{m - 1/2}{m}\frac{{\zeta (1/2 - m)}}{{n^m }}} , \quad n\to +\infty.
$$
It seems that when doing the singularity analysis, many terms cancel each-other leaving us with a clean result. The proof of the general asymptotic expansion remains open for now.
Comment: Thank you for your solution and general approach to the problem! It is fascinating for me to see how professional methods lead to the answer - some of them a beyond my abilities )
Comment: @metamorphy Thank you. That is exactly what I tried but somehow could not get the expansion for g at the origin. I looked at $f(\mathrm{e}^t)-f(\mathrm{e}^{t+2\pi \mathrm{i}})$, which is wrong.
Answer: We may use the integral version of Euler-Maclaurin formula to obtain an asymptotic formula with explicit big O error term. For any integer $a<b$ and continuously differentiable $f(x)$ on $[a,b]$ there is
$$
\sum_{k=a}^bf(k)=\int_a^bf(x)\mathrm dx+\frac12f(a)+\frac12f(b)+\int_a^b\overline B_1(x)f'(x)\mathrm dx,\tag1
$$
where $\overline B_n(x)$ denotes $n$'th periodic Bernoulli polynomial. Therefore, we see that when $a=1$, $b=n$, and $f_n(x)=\sqrt{x^{-1}-n^{-1}}$ there is
$$
\sum_{k=1}^nf_n(k)=\underbrace{\int_1^nf_n(x)\mathrm dx}_{S_1}+\frac12+\underbrace{\int_1^n\overline B_1(x){-x^{-2}\over2\sqrt{x^{-1}-n^{-1}}}\mathrm dx}_{S_2}+O\left(\frac1n\right).\tag2
$$
For $S_1$, substitution $x=nt$ gives
\begin{aligned}
n^{-1/2}S_1
&=\int_{1/n}^1\sqrt{t^{-1}-1}\mathrm dt \\
&=\int_0^1t^{1/2-1}(1-t)^{3/2-1}\mathrm dt-\int_0^{1/n}t^{-1/2}\left\{1+O(t)\right\}\mathrm dt \\
&=\frac\pi2-\int_0^{1/n}t^{-1/2}\mathrm dt+O(n^{-3/2})=\frac\pi2-2n^{-1/2}+O(n^{-3/2}),
\end{aligned}
so we have
$$
S_1=\frac\pi2\sqrt n-2+O\left(\frac1n\right)\tag3
$$
For $S_2$, note that the integral of $\overline B_1(x)$ is bounded, so integration by parts gives
\begin{aligned}
S_2
&=-\frac12\int_1^{n/2}\overline B_1(x)x^{-3/2}\left(1-\frac xn\right)^{-1/2}\mathrm dx+O(n^{-1/2}) \\
&=-\frac12\int_1^{n/2}\overline B_1(x)x^{-3/2}\left\{1+{x\over2n}+O\left(x^2\over n^2\right)\right\}\mathrm dx+O(n^{-1/2}) \\
&=-\frac12\int_1^{n/2}\overline B_1(x)x^{-3/2}\mathrm dx+O(n^{-1/2}) \\
&=-\frac12\int_1^\infty\overline B_1(x)x^{-\frac12-1}\mathrm dx+O(n^{-1/2}).
\end{aligned}
If we plug $a=1$, $b=+\infty$, and $f(x)=x^{-s}$, we have
$$
\zeta(s)=\frac12+{1\over s-1}-s\int_1^\infty\overline B_1(x)x^{-s-1}\mathrm dx.
$$
Therefore, we obtain
$$
S_2=-2-\frac12-\zeta\left(\frac12\right)+O\left(1\over\sqrt n\right).\tag4
$$
Now, plug (3) and (4) into (2), so we obtain
$$
\sum_{k=1}^n\sqrt{\frac1k-\frac1n}=\frac\pi2\sqrt n+\zeta\left(\frac12\right)+O\left(1\over\sqrt n\right).
$$
Comment: Thank you very much for your original solution! I also tried to use the Euler-Maclaurin' formula but failed to make it rigorously and to get the answer
Answer: This supplements the answer by @Gary, to justify the asymptotics conjectured there: $$S(n)\underset{n\to\infty}{\asymp}\frac\pi2+\sum_{k=0}^{(\infty)}\binom{k-1/2}{k}\frac{\zeta(1/2-k)}{n^{1/2+k}}.$$
From the answer, we take $2\sum_{n=2}^\infty S_n z^n=f(z):=\operatorname{Li}_{1/2}^2(z)$, hence $S(n)=\frac1{4\pi i}\int_L\frac{f(z)}{z^{n+1}}\,dz$, where $L$ is any simple contour encircling $z=0$ (in the domain of analyticity of the integrand).
In our case, $f(z)$ is analytic on $\mathbb{C}\setminus\mathbb{R}_{\geqslant1}$, and we have $f(z)=O(\log|z|)$ as $z\to\infty$. So, if we take $L$ to be the circle $|z|=R$ with a notch around $\mathbb{R}_{\geqslant1}$, the integral along the circle vanishes as $R\to\infty$ (assuming $n>0$). Thus, we can replace $L$ by $L_1$, where $L_a$ is the  Hankel contour encircling $\mathbb{R}_{\geqslant a}$: $$S(n)=\frac1{4\pi i}\int_{L_1}\frac{f(z)}{z^{n+1}}\,dz\underset{z=e^w}{=}\frac1{4\pi i}\int_{L_0}e^{-nw}f(e^w)\,dw.$$
Now use $f(e^w)=\big[(-\pi/w)^{-1/2}+\sum_{k=0}^\infty\zeta(1/2-k)w^k/k!\big]^2$ for $|w|<2\pi$, noted in the answer. We replace $L_0$ by the contour consisting of the circle $|w|=r$ and the edges of the cut along $[r,\infty)$. As $r\to0$, the integral along the circle tends to $(-2\pi i)\cdot(-\pi)$, hence
$$S(n)=\frac\pi2+\int_0^\infty e^{-nx}g(x)\,dx,\qquad g(x):=\frac1{4\pi i}\lim_{t\to 0^+}\big[f(e^{x+it})-f(e^{x-it})\big].$$
From the above we get $g(x)=\pi^{-1/2}\sum_{k=0}^\infty\zeta(1/2-k)x^{k-1/2}/k!$ for $0<x<2\pi$, and the claimed asymptotics follows by Watson's lemma.
Comment: Thank you very much for proving the proof of full form of asymptotics! Really, very impressive, and far beyond my skills )
Answer: This does not answer the question.
Let
$$f(n)=\zeta \left(\frac{1}{2}\right)+\frac{\pi}{2}\sqrt n-\sum_{k=1}^n\sqrt{\frac{1}{k}-\frac{1}{n}}$$ Computing
$$\Delta_p=10^{p+1}\,f\left(10^p\right)$$
the results
$$\left(
\begin{array}{cc}
p & \Delta_p \\
 1 & 1.04871059298 \\
 2 & 1.04038414635 \\
 3 & 1.03952666777 \\
 4 & 1.03944068157 \\
 5 & 1.03943208058 \\
 6 & 1.03943122046 \\
 7 & 1.03943113444 \\
\end{array}
\right)$$
Comment: @Svyatoslav. For sure but no proof. What is amazing is the pattern. Fortunately, Gary provided something really interesting. I would like to know more. Cheers :-)
Comment: Your evaluation provides strongly evidence that $\zeta(1/2)$ is the limit


.htaccess : blocking proxy

Question: so there is this guy spamming my phpBB2 forum since he's banned. He keeps coming back with proxies, and I would like to block them using my htaccess. My forum is located at http://www.site.com/forum/ I put a .htaccess file in /forum/, which contains the following, as found somewhere on the net:
<code>RewriteEngine on
RewriteCond %{HTTP:VIA}                 !^$ [OR]
RewriteCond %{HTTP:FORWARDED}           !^$ [OR]
RewriteCond %{HTTP:USERAGENT_VIA}       !^$ [OR]
RewriteCond %{HTTP:X_FORWARDED_FOR}     !^$ [OR]
RewriteCond %{HTTP:PROXY_CONNECTION}    !^$ [OR]
RewriteCond %{HTTP:XPROXY_CONNECTION}   !^$ [OR]
RewriteCond %{HTTP:HTTP_PC_REMOTE_ADDR} !^$ [OR]
RewriteCond %{HTTP:HTTP_CLIENT_IP}      !^$
RewriteRule ^(.*)$ - [F]
</code>
I heard this is pretty accurate. So I tried, and the web proxy was unable to reach the page. But it worked like 5 minutes, and now it's not blocking anything... I tried different proxies, web based or not, and nothing was blocked... I'm wondering if I did anything wrong, the htaccess looks correct to me !
If you guys have an idea, that would be awesome. I always find my answers on Stackoverflow, so I thought I should ask here :P
Cheers
Answer: I hope you understand that IF you will make your proxy-blocking rules work this will forbid not only the spammer but all the users using proxies.
You can try logging X-Forwarded-For header
(e.g. if you are using apache, add "%{X-Forwarded-For}i" to logformat) . This should give you real visitor ips in access log unless the spammer is using anonymous proxies. Then match the timestamp of his post against http access log (use a few seconds time window) and you should get his real ip. It may just work.
if the spammer is using anon proxies you may need to moderate your posts. You should do it anyway. Accept automatically posts from well known users and moderate the posts of new/untrusted users. I don't know phpbb but it probably supports moderation.
EDIT__
If you really want to block (bad) proxies try using mod_spamhaus , it should block the ips reported for spamming and open proxies. See spamhaus website to get an idea on what ips are being reported. I can't think of any mod_rewrite rules that could block anonymous proxies (I keep thinking about it)
Comment: yes I understand and that is my point. What I'd like to do is prevent people from using web proxies and such to browse the forum, register and post. Most members don't use proxies, it's a simple forum actually. But some use proxies to avoid bans.
So this solution looks better to me than logging all IP, because there are thousands of proxies servers and it would be time consuming to ban each IP I found in this log... With the htaccess thing, I wouldn't have to worry about most easy proxies, which people use. For better proxies, I can still range ban.
Comment: Anyway for phpbb2 there is no moderation queue for newest members, unfortunately. A newly registered member has the same rights as an old chap. And the moderation team is quite fast for banning idiots :) But well, I'd rather keep them away with their proxies...

So my question is just if anyone has an idea why this code used to work, but not anymore. Seems very odd, since it worked once...

Thanks for your answer ;)
Comment: maybe try mod_spamhaus? updated my answer
Comment: I don't have access to the root server stuff, but I'll take a look thanks
Answer: 3 things I do for my work's website that help eliminate 99.9% of all our contact form spam:
1) measure the time that passes from when the contact form loads to the time it was submitted. If someone submits the form within <10 seconds, it has to be a computer because theres no way a human could answer all the required questions in that time, even with an address population plugin. You might consider a similar tactic to prevent scripts from rapidly posting.
2) If the contact message contains multiple or suspect urls, flag as spam. Preventing multiple url links might not be acceptable for a bulletin board situation but if you can spot any particular unique url pattern in the spam posts, you might be able to filter these posts.
3) we have a false hidden email address field human users would never see, so if the form is submitted with the hidden field having a value we know it wasnt a human... may be you could do something similar with a false comment box?
These may not work for you since they would to be implemented at the PHP level and not apache, and they're only really effective against automated scripts, but hopefully atleast it gives you some ideas for additional ways to handle your spam problem

.htaccess : blocking proxy


Como interceptar o evento de save do projeto no vssdk?

Question: Atualmente estou desenvolvendo uma extensão do visual studio 2017 onde preciso saber quando alguma alteração no projeto for persistida.
Ex.: Quando eu adiciono uma nova referência no projeto (sei que existe eventos para quando a referência for adicionada/alterada/removida, mas não atendeu minha necessidade), o projeto é marcado como pendente de ser salvo. Eu preciso interceptar quando ele for salvo (melhor se for antes de salvar)
Tentei os evento Dte.Events.DocumentEvents.DocumentSaved, mas não é disparado no salvar do projeto; DTE.Events.SolutionEvents e DTE.Events.SolutionItemEvents não possuem nenhum evento do tipo que preciso
Isso é possível?
Answer: De acordo com este link da MSDN, você precisar criar referências dos objetos Events e DocumentEvents, senão eles serão coletados pelo Garbage Collectore serão inutilizados.
Exemplo:
private EnvDTE.Events events;
private EnvDTE.DocumentEvents documentEvents;

MeuConstrutor()
{
    events = DTE.Events;
    documentEvents = events.DocumentEvents;
    documentEvents.DocumentSaved += OnDocumentSaved; // <- Adicione seu event handler aqui.
}

Answer: O que funcionou pra mim como uma luva foi implementar a interface IVsRunningDocTableEvents3 fazendo override no método OnBeforeSave.
Dessa forma eu sabia exatamente quando o projeto estava para ser salvo e realizar as ações que precisava.
Ex.:

uint cookie;
var runningDocumentTable = (IVsRunningDocumentTable)GetGlobalService(typeof(SVsRunningDocumentTable));

runningDocumentTable.AdviseRunningDocTableEvents(new RunningDocTableEventsHandler(), out cookie);

using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace YourProject
{
    internal class RunningDocTableEventsHandler : IVsRunningDocTableEvents3
    {

        #region Methods

        public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
        {
            return VSConstants.S_OK;
        }

        public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
        {
            return VSConstants.S_OK;
        }

        public int OnAfterSave(uint docCookie)
        {
            return VSConstants.S_OK;
        }

        public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
        {
            return VSConstants.S_OK;
        }

        public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
        {
            return VSConstants.S_OK;
        }

        public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
        {
            return VSConstants.S_OK;
        }

        public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
        {
            return VSConstants.S_OK;
        }

        public int OnBeforeSave(uint docCookie)
        {
            /////// MY CODE ////////
            return VSConstants.S_OK;
        }

        #endregion Methods
    }
}


Invoke method for dll in WindowsForms

Question: I have a dll which contains this function:
int __stdcall PrnText(char *printtext);

In Windows Forms i have this code to invoke the dll:
[DllImport("Printing.dll", EntryPoint = "PrnText", CharSet = CharSet.Ansi)]
public static extern int PrnText(char *printtext);

When i call the function in C# code i get an error like this : " cannot cast string to char*
PrnText("Hello World");

What parameter should i give to PrnText() to make it work?
Later edit:
  Parameter: printtext
  pointer to string containing text to be printed

Comment: Looks like it is related to an [answered question](http://stackoverflow.com/questions/1658269/char-pointer-from-string-in-c-sharp).
Answer: The CLR knows how to convert a string to an unmanaged char* at runtime. You should use a signature which accepts a string, as such:
public static extern int PrnText(string printtext);

Note that this will work only if the parameter is input only.
Comment: Do you mean input by the user ? Like a textbox or something?
Comment: It will only work if the code you're calling does not need to edit the string. In that were the case, you'd need to pass a `StringBuilder`, since strings are immutable.
Comment: @Emil No, I mean input only as in the dll function is not changing the `char*` in any way.
Comment: @EmilDumbazu: no, it means you can only pass a string as an input parameter to your native code - it won't be able to modify it. If your native function needs to mutate a string, pass a `StringBuilder` instead.
Comment: could you give me an example with StringBuilder ?
Comment: see this question: http://stackoverflow.com/questions/2179270/pass-c-sharp-string-to-c-and-pass-c-result-string-char-whatever-to-c-s
Comment: Or in other words, the C declaration is wrong.  It should have declared the argument as `const char*`.  This is a common oversight.

Invoke method for dll in WindowsForms


Limit of Stirling approximation theorem

Question: This limit I tried to solve it by using Stirling approximation and here is the limit and my tried
$\lim_{0\to\infty }\frac{ \sqrt[n]{\dbinom{n}{1} \dbinom{n}{2} \dbinom{n}{3} \dbinom{n}{4} \cdots \dbinom{n}{n} } }{e^{\frac{n}{2}} n^{\frac{-1}{2}}}=? $ ..... I tried to evaluate the numerator by Stirling approximation and the denominator and got that
$\lim \limits_{n\to \infty }\frac{\sqrt{2\pi n} e^{\frac{-3}{2} n}n^{\frac{2n+1}{2} }}{\left[ 1! 2! 3! 4! \cdots n! \right] \left[ \left( n-1\right) ! \left( n-2\right) ! \left( n-3\right) ! \cdots 0! \right] }$...  My problem that I can't evaluate the denominator..  what should I do next to solve this limit?.  Any hint?  Thanks.
Comment: May I ask where this limit comes from? It reminds me of the `$e$ hidden in Pascal triangle' thing discovered (so to speak) as late as 2012 (or 2009 depending on what officially counts) by Harlan Brothers.
Answer: Using the Euler-Maclaurin Sum Formula, we get
$$
\frac2n\sum_{k=1}^n(k\log(k)-k)\sim n\log(n)-\frac32n+\log(n)-1\tag{1}
$$
Since $\binom{n}{k}=\frac{n!}{k!\,(n-k)!}$, it follows that $\prod\limits_{k=0}^n\binom{n}{k}=\frac{n!^{n+1}}{\color{#C0C0C0}{0!}1!2!\cdots n!\cdot n!(n-1)!\cdots1!\color{#C0C0C0}{0!}}=\frac{n!^{n+1}}{\left(\prod\limits_{k=1}^nk!\right)^2}$
Therefore,
$$
\begin{align}
\left[\prod_{k=0}^n\binom{n}{k}\right]^{1/n}
&=\frac{n!^{\frac{n+1}n}}{\left(\prod\limits_{k=1}^nk!\right)^{\frac2n}}\tag{2}\\
&\sim\frac{n!^{\frac{n+1}n}}{\left(\prod\limits_{k=1}^n\sqrt{2\pi k}k^ke^{-k}\right)^{\frac2n}}\tag{3}\\
&=\frac{n!}{2\pi\left(\prod\limits_{k=1}^nk^ke^{-k}\right)^{\frac2n}}\tag{4}\\
&\sim\frac{n!}{2\pi n^{n+1}e^{-\frac32n}e^{-1}}\tag{5}\\[12pt]
&\sim\bbox[5px,border:2px solid #C0A000]{\frac{e^{\frac n2+1}}{\sqrt{2\pi n}}}\tag{6}
\end{align}
$$
Explanation:
$(2)$: rearrange terms
$(3)$: use Stirling to approximate $k!$
$(4)$: $\sqrt{2\pi k}$ comes out of the product to the $\frac2n$ power as $2\pi n!^{\frac1n}$
$(5)$: apply $(1)$
$(6)$: use Stirling to approximate $n!$
This seems to be good:
at $n=1000$, the left side is $4.79983\times10^{215}$ and the right is $4.81333\times10^{215}$
at $n=10000$, the left side is $3.217057\times10^{2169}$ and the right is $3.218208\times10^{2169}$.
Comment: @user256952: added some explanation.
Comment: Sir.  I need small explanation for this $ \left( \prod \limits^{n}_{k=1}k! \right) ^{\frac{2}{n} }$ in the 2 step how we get it?

Limit of Stirling approximation theorem


Why does converting date to_char() throw ORA-01830 error when placed in a case-then?

Question: I have been using this code for a long time, and it works fine:
to_char(v_emailRow.first_stamp, 'dd.mm.yyyy')
However, today I needed to add the following condition
case when v_cardCode = 'C1' then v_date else to_char(v_emailRow.first_stamp, 'dd.mm.yyyy') end.
As soon as I added the case-then statement, whenever the to_char() needed to be executed, it began always throwing ORA-01830: date format picture ends before converting entire input string error. If I remove case-then, it works as usual, if I add it back, the error immediately returns.
I have tried writing a test script, googling, but I cannot find the issue. The same value is being converted in both cases, why does one of them work and the other throws an error?
Comment: We would need DDL for your table as well as some sample data to be able to replicate the error.  But to guess at this, I would suspect v_date might be a date variable.  So then your CASE would be attempting to return a mix of DATE data types and CHAR data types which would cause problems.  Try with a TO_CHAR on v_date?
Comment: @Stilgar you are correct, v_date is a date variable. Very likely that's the issue, didn't think of that. Thanks in advance.
Answer:
when v_cardCode = 'C1' then v_date else to_char(v_emailRow.first_stamp, 'dd.mm.yyyy')
whenever the to_char() needed to be executed, it began always throwing ORA-01830: date format picture ends before converting entire input string error

v_date, as the variable name suggests it's a DATE data type, while applying TO_CHAR converts date to a STRING. Therefore, having two different data types is causing the error.
Try below CASE in your SQL:
case
  when v_cardCode = 'C1'
  then to_char(v_date, 'dd.mm.yyyy')
  else to_char(v_emailRow.first_stamp, 'dd.mm.yyyy')
end


Are there sports in which being smaller than your adversary can be a distinct advantage?

Question: Many sports put forward tall players. I know that everybody can play any sport, but I've noticed that in professional teams (basketball, volleyball, soccer, tennis, ...) there is a tendency to see tall people.
It's maybe due to advantages that high sizing can provide. It's depending of each sport.
So I would like to know if there is some sports for which the fact to be smaller than his adversary can be a distinct advantage?
Comment: I think is not possible to find a unique right answer. You will probably find a list of good answers: one for each sports
Answer:
So I would like to know if there is some sports for which the fact to be smaller than his adversary can be a distinct advantage?

Yes they do exist.
But here's one example:
In horse racing, having a smaller and lighter rider is more advantageous.
It lets the horse sprint faster because there's less weight on its back.

Source: taken of wikipedia
Answer: Gymnasts are also usually quite small, there is actually some debate over whether gymnastics can affect growth (but I don't think there is much evidence behind this).
According to this website American gold medalist Gabrielle Douglas is

four feet, eleven inches, and 90 pounds

.
http://www.boston.com/sports/blogs/statsdriven/2012/08/the_bodies_of_champion_gymnast.html
Also height isn't always an advantage in soccer, just look at the average height of the Barcelona team (Messi, Xavi, Iniesta, Pedro etc).
Comment: Height is important in soccer, just differently per area. As a winger, being shorter allows you to move with more control. Defenders, and center forwards needs height in order to win headers. etc.
Answer: In cricket being short may not help you in selection in the team. But if a player is a batsman, he may get some advantages in batting. (or disadvantages for tall players do not apply)

Tall players have to bend more than short players while batting.
Bowlers have to bowl under their shoulders otherwise it will considered a No ball (after two bouncers). So they have to shorten their length.
They can play yorker length ball better than tall players because normally short players have high backlift and tall players have to keep the bat lower while playing the shot.

However, if you are a bowler (specially fast bowler), being a taller is an advantage.
Answer: I can think of a couple instances where it is an advantage for the athlete to be small. They are both "racing" situations, and the athlete in question is a "controller."
The first is the "coxswain" (caller) on a rowing team. His function is necessary, but the smaller he is, the less burden on his teammates.
The second, as someone else pointed out, is a jockey on a horse, where the jockey has the dual role of controlling the horse and not being a burden on the horse.
Answer: In Curling athletes with a low center of gravity (smaller one generally) are helped in the stability of the slip.
The stability of the slip is one of the most important feature to be a strong curler.
During the action of broom is important the hands and back power, while during the slip is important to have muscolar legs, so power and compact athletes have a slight head start
Answer: Besides all sports that have been mentioned already, I would like to add shorttrack to that list. Being short and having little weight gives the rider an advantage to be more agile while fighting for the best positions and taking over other riders.
However, this does not mean that taller riders cannot compete with the best, since they might bring more power. Ter Mors, for example, is often by far the tallest rider on the ice.
Answer: Distance running is another sport where a smaller athlete may have an advantage. When work = mass * distance, an athlete with smaller mass will do less work to cover the distance. If two athletes have the same capacity for rate of work - that is, they can do the same amount of work in a given span of time - the lighter one will win a race. There are limits to this - at some point being lighter limits your capacity to do work - but in general lighter is better for distance runners.
Comment: I suspect this applies to a lot of endurance sports.
Comment: Probably. The tradeoffs between the mass needed to increase work capacity (for lack of a better phrase) and the lack of mass which lets you cover more distance with the same work are going to be slightly different with every sport. Is smallness an advantage in road cycling, for example? There's relatively little penalty for additional mass in distance swimming that I can think of, assuming it's not dead weight. But ultimately physics has the final word.
Answer: Shooting
From wikipedia: in shooting sports, a shorter shooter can maintain better balance when standing for long periods of time holding a gun, as well as keep their gun steady.
Answer: Motorsports, like most other racing sports, typically favors drivers that are lightweight, which gives smaller, lighter drivers an advantage.
While most motorsport organizations feature a minimum chassis weight in the regulations, this often does not take driver weight into consideration. This allows cars with lighter drivers to have a slight weight advantage against cars with heavier drivers.
This is prevalent in open-wheel racing, particularly karts, where the karts themselves are all but equal in weight, and the differences mainly come from the driver's weight.
TL;DR, Regulated car weight + lighter driver allows for faster, more agile movement vs. cars with heavier drivers.
Answer: Rock climbing
Lead climbing and bouldering nowadays tends to favour smaller / lighter people than taller / heavier. I know this can end up as a long debate, but for a shorter person looking for a sport this is something to look into!
Answer: I do gymnastics for many years and many boys in our training are smaller than the average guy. I think when you have to control your whole body it is easier when you haven't a tall body. Also you have to be quickly with your legs and my taller girlfriend in training for example ist often to slow for some jumps.
So I can say to be smaller is in gymnastics an advantage.
Answer: There are some sports where tall people better fit, for example basketball. Actually it's only basketball I can think of. As a soccer player my whole life, I can say that short attacking players are better than tall players. I can give you a simple example:

Diego Maradona
Lionel Messi
Romario
Wesley Sneijder
Xavi Herández
Andrés Iniesta
Edgar Davids
Alexis Sanchez
Zola
Philipp Lahm

These world class players are all less than 170 cm. Another thing, Diego Maradona and Lionel Messi are the best soccer players ever! Although there are sports where you need to be tall, it all depends on your talent and your hard work.
Comment: Those are surely very strong player, but is not possible to say that in football being small is an advantage
Comment: There are many examples of players as great as these who are taller than 170cm, sometimes substantially so. Just among those reaching at least 180, you find Cruyff (180), Figo (180), Totti (180), Raúl (180) Laudrup (183), Shevchenko (183), Ronaldo (Brazilian, 183), Zidane (185), Ronaldo (Portuguese, 185), Bergkamp (185), Rivaldo (186), Maldini (186), Henry (188), van Basten (188), Gullit (190), Sócrates (192), Ibrahimoviċ (195), and many others. Other than their height, the common feature of all these players is their outstanding technical ability.


Flutter list query

Question: Im trying to check a list inside list and then show it as ViewList
for example
const Sport = [
  {
    "Name": "James",
    "SportTaq": ["Soccer", "American football"],
  },
];
and then check list witch include loud Soccer
print(Sport.where((item) => item["SportTaq"].contains("Soccer")));
but it did not work can you help me with it please
Answer: You can do something like this:
<code>void main() {
  const Sport = [
    {
      "Name": "James",
      "SportTaq": ["Soccer", "American football"],
    },
    {
      "Name": "Bob",
      "SportTaq": ["American football","basketball"],
    },
  ];

  print(Sport.where((item) {
   List sports = item["SportTaq"];
   return sports.contains("Soccer");
  }).toList());
}
</code>
Comment: Hello @MouhammadAlhajjiTheRiver if it works can you vote and accept as an answer clicking on the checkbox?

Flutter list query


What could cause ML predictions to be multimodal when the inputs are unimodal?

Question:
This appears to be a systematic issue that occurs with the whole range of data points:

In general, what are some possible causes for discrepancies like this? I know it's impossible to pinpoint the exact cause without seeing my script and data, but I'm clueless as to how to even start debugging this.
I'm using XGBoost.
Comment: I don't quite see what is unclear about this question.
Comment: Some context would provide helpful clues concerning the possibilities: what ML method, what kind of data?
Answer: This can happen for at least two different reasons.

Your predictor has different distributions in the training and the prediction step. If your predictor values during training cluster in one part of space, you have many training response values corresponding to this part of predictor space. And of course, if your predictor values cluster in a different part of space during prediction, your predicted response will cluster around values in that part of predictor space.
So check whether the distributions of your predictors are similar.
Now, let's assume the distributions of your predictors are similar. One reason for the effect you observe could be that the actual mean response to your predictors is multimodal, but the actual responses you see may be swamped by noise. If you have enough data, your model may pick up on the actual underlying multimodal signal, and your (point!) prediction may reflect this.
An example. Here is the actual mean response to a single predictor:

Let's assume we have 5,000 observations of the predictor, which are uniformly distributed in [-1,1]. We also have the corresponding values of the response. Because of noise, the response is unimodal (note that this histogram does not show the predictor any more!):

Since we have a lot of data, our model picks up on the multimodal relationship between the predictor and the response. Here is a plot of the predicted response against the predictor:

(Note how this is much wigglier than the actual relationship above. There is a lot of overfitting going on here. But that is not the main issue.)
If we now again take uniformly distributed predictor values and plot a histogram of the associated predicted responses, we get multimodality:

Bottom line: don't just look at histograms of responses. Plot observed and predicted responses against predictors. Also, consider looking not only at point predictions, but at full predicted densities, e.g., by sampling from them and plotting histograms from these resamples. If you do this for predictor values that are similarly distributed as in your training data, the resulting histograms should look similar to histograms of your training responses.

R code:
<code>mean_response <- function(predictor) -.5*predictor^4+.4*predictor^2+.1
predictor_plot <- seq(-1,1,by=.01)

plot(predictor_plot,mean_response(predictor_plot),type="l",xlab="Predictor",ylab="Mean response")

set.seed(1)
predictor_train <- runif(5e3,-1,1)
response_train <- rnorm(length(predictor_train),mean_response(predictor_train),.1)
hist(response_train)

library(randomForest)
model <- randomForest(response_train~predictor_train)
predictions <- predict(model,newdata=data.frame(predictor_train=predictor_plot))
plot(predictor_plot,predictions,type="l")
hist(predictions)
</code>


Programa executa normalmente porem tem momentos que para no meio da execução e nao sai do lugar

Question: Este programa é para sortear numeros para a mega sena. Consegui o resultado que queria, mas tem momentos que o programa para ou no meio ou no inicio da execução.
O usuario coloca a quantidade de palpites que ele quer. Mais o problema que estou tendo é que se o usuario pede 10 palpites, as vezes executa todos, mais tem vezes que nao, e ele nao apresenta erros.
from random import randint
from time import sleep
lista = [[]]
num = 0
cont = 0
print('=' * 30)
print('      JOGA NA MEGA SENA')
print('=' * 30)
quantos = int(input('Qual a quantidade de palpites: '))
print(f'===== Sorteando {quantos} Jogos =====')
while quantos != 0:
    quantos -= 1
    cont += 1
    for i in range(0, 6):
        num = randint(1, 60)
        if num not in lista[0]:
            lista[0].append(num)
        else:
            while num in lista[0]:
                num = randint(1, 60)
                lista[0].append(num)
        if i == 5:
            lista[0].sort()
            print(f'Jogo {cont}:{lista[0]}')
            sleep(1)
            for l in range(0, 6):
                lista[0].pop()

No caso  estou usando lista dentro de lista por conta de exercicios do curso. Se alguem puder me ajudar nisso fico grato.
Comment: Pode nos explicar as linhas 19~21? `while num in lista[0]`
Comment: é que os numeros nao podem se repetir, entao, esse while é para q se o numero que foi gerado aleatoriamente se repetir ele gerar outro e adicionar e so saira desse loop se for gerado um outro numero aleatorio
Comment: essa foi a forma que encontrei para gerar um outro valor diferente do que tem dentro da lista. e entao adicionar outro
Comment: Mas essa lista vai crescendo infinitamente e no final você faz `lista[0].pop()` apenas 6 vezes. O que significa que em algum momento todos os números vão estar na sua lista e não terá nenhum para sortear.
Comment: Aliás, isso é um loop infinito, pois a sua condição `while num in lista[0]`, mas você faz `lista[0].append(num)`, ou seja, você adiciona o número na lista e depois continua o loop se ele estiver na lista. A condição sempre será verdadeira.
Comment: Eu entendi oq voce quiz dizer. Mais ele so entra nessa condição se ja tiver aquele numero la dentro.
entao no caso teria que por um .pop() no final desta condição em especifico né?
Comment: Não, pois não faria sentido você adicionar na lista e depois remover da lista. Faz um teste de mesa e reveja a condição que está usando.
Comment: ele nao gera uma lista infinita, pq quando tem 6 numeros dentro da lista eu do um print desses numeros e depois apago um por um com um for.
Comment: ta bom obg. Eu vou dar uma boa revisada nesse codigo. o problema que estou tendo msm é que acredito eu que ele esta se perdendo em algum momento nos loops
Comment: Na dúvida, teste. Adicione um `print` dentro desse laço e veja: https://ideone.com/K6E6uv
Answer: O problema está na sua lógica para não repetir os valores:
num = randint(1, 60)
if num not in lista[0]:
    lista[0].append(num)
else:
    while num in lista[0]:
        num = randint(1, 60)
        lista[0].append(num)

A ideia aqui é adicionar o num apenas se ele ainda não está em lista[0], porém o seu while definirá um laço infinito, visto que a condição while num in lista[0] sempre será verdadeira já que você sempre adiciona num em lista[0].
Você pode simplificar essa lógica fazendo:
num = randint(1, 60)
while num in lista[0]:
    num = randint(1, 60)
lista[0].append(0)

Ou seja, sorteia um valor, enquanto ele estiver em lista[0] sorteia um novo valor. Adiciona o valor em lista[0] apenas quando o laço finalizar.
Alterando isso seu código já funcionará.
Alternativa
Você pode usar a função random.sample para simplificar o seu código. Ele já irá retornar um conjunto de valores únicos sorteados do seu conjunto.
from random import sample

quantos = int(input('Qual a quantidade de palpites: '))

for i in range(quantos):
    print( sorted(sample(range(1, 61), 6)) )
    #                    +----------+  |
    #                          |       |
    #             Conjunto de valores  |
    #                                  +-- Número de valores sorteados

Veja funcionando no Ideone
Comment: nossa, cara. vlw, tava a dias quebrando a cabeça com esse exercicio.
Nao sabia da existencia dessa função em random. Vou fuçar essa função aqui.


Solve the system of non-homogeneous differential equations using the method of variation of parameters

Question: My exam question reads as follows:
Given the system:
$y'_1=y_1-y_2+\frac{1}{\cos \left(x\right)}$
$y'_2=2y_1-y_2$
Solve it using the method of variation of parameters, before that describe that method for solving systems of non-h. differential equations.
I'm not sure on how to solve this system, that is only remember learning about homogeneous systems so not sure even on how to describe the general case. Either way after some googling I find out that as always the solutions is given as $Y=Y_h+Y_p$ and finding the solution to the homogeneous system is something I know how to do. But then how can I find the particular solution?
Comment: @Moo none, (buffer text to reach enough chars)
Answer: I will map it out and you can fill in the details. We are given
$$y'= Ay + g = \begin{pmatrix}1 & -1 \\ 2 & -1\end{pmatrix}y+\begin{pmatrix}\dfrac{1}{\cos x} \\ 0\end{pmatrix}$$
Using eigenvalues / eigenvectors (or other approaches), we find the homogeneous solution
$$Y_h(x) = c_1\begin{pmatrix}\sin x + \cos x \\ 2\sin x\end{pmatrix} + c_2 \begin{pmatrix}-\sin x \\ \cos x - \sin x\end{pmatrix}$$
For Variation of Parameters (there are other approaches too), we will follow Example 2
$$Y = \begin{pmatrix}\sin x + \cos x & -\sin x \\ 2\sin x & \cos x - \sin x \end{pmatrix}  \implies Y^{-1} =
\begin{pmatrix}
 \cos x-\sin x & \sin x \\-2 \sin x & \sin x + \cos x
\end{pmatrix}$$
We now form
$$Y^{-1} g = \begin{pmatrix}
 \cos x -\sin x & \sin x \\-2 \sin x & \sin x + \cos x
\end{pmatrix} \begin{pmatrix}\dfrac{1}{\cos x} \\ 0\end{pmatrix} =
\begin{pmatrix}
 \sec x ~(\cos x - \sin x) \\
 -2 \tan x
\end{pmatrix}
$$
Next we integrate the previous result
$$\displaystyle \int Y^{-1}g ~dx = \begin{pmatrix}
 x+\ln (\cos x) \\
 2 \ln (\cos x) \\
\end{pmatrix}$$
We can now write the particular solution $Y_p(x) = Y \displaystyle \int Y^{-1}g~ dx$
$$Y_p(x) = \begin{pmatrix} \cos x (x+\ln (\cos x))+\sin x (x-\ln (\cos x)) \\2 (x \sin x +\cos x \ln (\cos x))\end{pmatrix}$$
Now write
$$Y(x) = Y_h(x) + Y_p(x)$$


Ajuda em struct C, não conseguindo alimentar

Question: Galera bom dia, estou criando esse código simples, só pra ler, e exibir, essas informações de um vetor, do tipo struct.
Só que ao executar esse código, no ato da execução, não consigo alimentar nem a data nem a filiação, como está explícito na imagem lá em baixo, como se não tivesse espaço entre eles.
Como solucionar?
Segue o código:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

struct bilhete{
  int idade;
  char nome[30];
  char fi[30];
  char data[30];
 };

int main() {
 struct bilhete identidade[5];
int cont;

for (cont = 0 ; cont <=5 ; cont++){
         fflush(stdin);

    printf("Informe o nome: \n");
    gets(identidade[cont].nome);

    printf("Informe a idade: \n");
    scanf("%d",&identidade[cont].idade);

    printf("Informe a filiacao: \n");
    gets(identidade[cont].fi);

    printf("Informe a data: \n");
    gets(identidade[cont].data);

}

// EXIBIR
for (cont =0 ; cont <=5 ; cont++){
    printf("Nome: %s",identidade[cont].nome);
    printf("Idade: %d",identidade[cont].idade);
    printf("Filiacao: %s",identidade[cont].fi);
    printf("Data: %s",identidade[cont].data);

}

system("pause");

return 0;
}

Comment: [Citando a minha própria resposta em uma outra pergunta](http://pt.stackoverflow.com/a/139832/132): Nunca, jamais, em hipótese nenhuma use a função `gets`. Essa função é horrorosa, e é universalmente e unanimemente odiada em meio aos programadores C. O motivo é que é simplesmente impossível utilizar essa função de forma segura. Sempre que ela é usada, o seu programa já ganha de presente um rombo gigantesco pelo qual ele pode falhar catastroficamente da mesma forma como o seu programa está falhando. Não existe forma correta de se utilizar esta função, todas as formas de uso dela são incorretas.
Comment: Leia isto: http://pt.stackoverflow.com/q/42981/101 e isto: http://pt.stackoverflow.com/q/111697/101
Comment: Quanto ao `fflush(stdin)`, veja [essa minha outra resposta](http://pt.stackoverflow.com/a/96012/132).
Answer: Primeiramente, em seu for, o cont não deve ser <= a 5 e sim < que 5. pois todo vetor em C vai de 0 a N-1.
Os métodos tem tipos diferentes de leitura, o gets funciona igual ao scanf('%[\^n]',...) a diferença é que no scanf você consegue tratar como você quer ler a informação. Para corrigir esse erro, use o scanf e passe o seguinte formato para a leitura: "\n%30[^\n]".
Essa instrução não separa os tipos de valores, ele simplesmente lê o que estiver no terminal. Então se coloca o \n no começo, faz com que a leitura da informação ocorra depois da quebra de linha (não há necessidade de usar no %d, %s, %f, %i, %lli, ...; tem a necessidade de usar em %[^\n], %c).
O %30[^\n] irá ler os próximos 30 caracteres até a quebra de linha. Como quebra de linha também é caractere, caso não use o \n no começo, o leitor identifica uma quebra de linha e entende como se já tivesse lido a instrução, pois isso que o sistema pula a leitura.
for (cont = 0 ; cont < 5 ; cont++){
    printf("Informe o nome: ");
    scanf("\n%30[^\n]",identidade[cont].nome);

    printf("Informe a idade: ");
    scanf("%d",&identidade[cont].idade);

    printf("Informe a filiacao: ");
    scanf("\n%30[^\n]",identidade[cont].fi);

    printf("Informe a data: ");
    scanf("\n%30[^\n]",identidade[cont].data);
}


Storage Pool Keeps Disconnecting After Reboot on Hyper-V

Question: I have a File Server installed on Hyper-V with Windows Server Datacenter 2012. I created a Storage Pool in the Hyper-V Session.
When I reboot the host, the server hyper-V session is in saved status. I noticed that the host picked up the storage pool with a yellow triangle. I have tried combinations of the following commands I found online. After I run the commands the triangle goes away, but I still cannot boot the Hyper-V.
In order to boot the hyper-V I would have to delete the storage pool from the host and placing the HDDs in offline mode. Now the HyperV boots, however if I boot just the HyperV then its good. When I reboot the Host the StoragePool disappeared.
<code>Set-StoragePool -FriendlyName NAS | -IsReadOnly $False
Get-StoragePool -FriendlyName NAS | Get-VirtualDisk | Set-VirtualDisk -IsManualAttach $False -Access:ReadWrite
Get-StoragePool -FriendlyName NAS | Get-VirtualDisk | Connect-VirtualDisk
Get-Volume

Get-VirtualDisk
Set-VirtualDisk -FriendlyName NAS -IsManualAttach $False

Get-VirtualDisk | Where-Object {$_.IsManualAttach -eq $True}
Get-VirtualDisk | Where-Object {$_.IsManualAttach -eq $True} | Set-VirtualDisk -IsManualAttach $False
</code>
Comment: Your PS scripts are synactically wrong
Answer: Storage Spaces is only supported on physical hardware.  If you're trying to pass the disks through to a VM, you're going to see the host recognize a foreign storage pool on every reboot, as you described.
You should run the storage pool on the host, not the guest.  Then put a fixed-size VHDX on the virtual disk from the storage pool.  Then attach that VHDX to the VM.  You'll see the same behavior that you're hoping for, but it will actually work.
Most people who are doing what you're doing say that their reason for trying it that way is that it will perform better.  It won't unless you're running many hundreds of thousands of IOPS through the system.   And if you're doing that, just create more than one VHDX.
Lastly, you should change the default on your VM so that it shuts down cleanly when the host shuts down, and the restarts when the host restarts.  As long as you're running a guest OS that's recent, this will work faster and more cleanly than saving the guest.