Where do fractional points in UCI ranking come from?

Question: If you look at various UCI rankings, you often see riders that have non-integers as their rankings. For example, if you look at the current UCI World Ranking and this year's UCI World Tour rankings, you can see Froome with 4918.13 and 1205.43 points, Van Avermaet with 2734.57 and 993.57 points.
However, when I look at explanation of UCI ranking points at Wikipedia (current revision), the points awarded for various placings are never fractions. So the best guess is that under some circumstances points are divided between several riders. Checking ranking breakdown for Froome and Van Avermaet I see that in these instances the non-integer points come from team time trials. (I am not sure to which extent these links are permanent, so I will explicitly mention that Froome has 1.43 points from TTT at Tirreno–Adriatico, where Team Sky finished 3rd. Van Avermaet has 8.57 from exactly the same event, BMC Racing Team won this stage.)
Is team time trial the only possibility when points are divided between several riders? What are the exact rules how the points from TTT (or some other situations where the points are split between several riders) are divided among riders?
Comment: I think you should accept your answer, unless you are waiting for a more detailed one. I don't think there's anything more precise than the rules themselves though..
Answer: Points are only split among teammates, points divided evenly in TTT:
It's helpful to look at the team points standings and see that all scores are round numbers, or end in .99, .01, etc. This tells me points are only being split among teammates.
Looking at the UCI website, there have been 2 team time trials (TTT) on the UCI World Tour so far in 2018, the Critérium du Dauphiné and the Tirreno-Adriatico. BMC rider Damiano Caruso scored in both events, and you can see the fractional scoring in his total.
Caruso scored 8.57 points for a 1st place in Tirreno, and if you look through his team, you will find 6 other people receiving the same, for a total of 60 points across the team. He scored 3.57 points in Dauphiné, 1/7th of 25 points split across the team members who raced.
Answer: Here is the relevant excerpt from the UCI Regulartions - Part 2 - Road Races (Internet Archive). This supports what was said in the already posted answer:

Chapter X UCI RANKINGS
  § 1 Elite and Under 23 Men's UCI World Ranking
  ...
  Scale of points
  2.10.008 General provisions
For team time trial events and stages the points on the scale shall be awarded to the team. These points shall be divided equally between the riders finishing the event or the stage. Calculations shall be rounded to a hundredth of a point.


The proof of Riemann's bilinear relations

Question: I am reading the proof from http://page.math.tu-berlin.de/~bobenko/papers/2011_Bob.pdf

I am very confused the step: (from Stokes theorem)
$$\int_Rw\wedge w'=\int_{\partial F_g}w'(p)\int_{P_0}^Pw$$
Can you explains that?
Answer: On the simply connected domain $F_g$, the closed form $\omega$ becomes exact: $\omega = df$, for $f(P) = \int_{P_0}^P \omega$ (and note this integral is path-independent). Then $d(f\omega') = df\wedge\omega' = \omega\wedge\omega'$. The author is writing $\int_{F_g}\omega\wedge\omega' = \int_{F_g} d(f\omega') = \int_{\partial F_g} f\omega'$.

The proof of Riemann’s bilinear relations


Ion-footer-bar em cima do ion-list?

Question: Estou criando uma lista infinita no ionic. Tenho um ion-footer-bar no index e depois dessa lista trazer todas as informações do Webservice no último registro o ion-footer-bar fica sobre o registro. Estou tentando usar o $scope.$broadcast('scroll.resize');, mas não está resolvendo.
Como resolver isso ?
EmpresasCtrl.js

app.controller('EmpresaCtrl', function($scope, $state, $ionicLoading, EmpresaAPIService, AppConstants, APP_MESSAGES){

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

    $scope.loadMore = function(){
        EmpresaAPIService.getAllEmpresas(offset)
        .success(function(data){
        if(data.result.length === 0){
            $scope.moreData = true;
        }else{
            angular.forEach(data.result, function(empresa){
                var image = empresa.Empresa.imagem;
                empresa.Empresa.imagem = AppConstants.webServiceUrl + "/app/webroot/img/empresas/" + image;
                $scope.items.push(empresa);
            })
            offset += 10;
        }

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

        })
      .error(function(err){
        $ionicLoading.show({ template: APP_MESSAGES.internetOut, noBackdrop: true, duration: 2000 });
      });

    };

    $scope.getEmpresa = function(id){
        var params = {id:id};
        $state.go('tab.detalheEmp', params);
    }

});

index.html

    <ion-nav-bar class="bar bar-header bar-assertive" align-title="center">
      <ion-nav-back-button>
      </ion-nav-back-button>
    </ion-nav-bar>

    <ion-nav-view>
    </ion-nav-view>

    <ion-footer-bar align-title="left" class="bar-dark" ng-controller="AnuncioCtrl">

    </ion-footer-bar>

empresas.html

<ion-view view-title="Empresas">

  <ion-content class="padding" has-footer="true" scroll="true">

            <input type="text" ng-model="pesquisar" placeholder="Pesquisa rápida...">

      <ion-list>
          <ion-item class="item item-thumbnail-left"
                ng-repeat="item in items | filter:pesquisar"
                type="item-text-wrap"
                ng-click="getEmpresa({{item.Empresa.id}})" >

{{item.Empresa.nome}}

{{item.Empresa.tipo}}

{{item.Empresa.endereco}}

{{item.Empresa.telefone}}

          </ion-item>
          <ion-infinite-scroll on-infinite="loadMore();" distance="1%" ng-if='!moreData'></ion-infinite-scroll>
     </ion-list>

  </ion-content>

</ion-view>

Answer: Problema resolvido, mais simples do que eu imaginava, apenas adicionei um class na tag <ion-nav-view class="has-footer"> e funcionou perfeitamente.

Ion-footer-bar em cima do ion-list?


Intellij IDEA - Actionscript Project - Cannot connect Debugger version of Flash Player

Question: I installed flash player debugger and cannot able to debug the flash application.
And I got following message in console.
Waiting for Player to connect
Failed to connect; session timed out.
Ensure that:
  1. you compiled your Flash movie with debugging on, and
  2. you are running the Debugger version of the Flash Player.
Dont know how to fix.
Comment: What kind of file are you trying to debug? Pure SWF or HTML wrapper?
Comment: Are you using the standalone debugger version or the browser plugin? If you are using a browser, which one?
Comment: @Timofei  I am using pure swf. @bmleite I am new to intelllij IDEA and  don't know how to view the debugger version it trying to launch. But I installed both browser plug-ins.
Comment: Make sure, that your swf files are launching with the debugger version (in Windows go to Properties of any swf file and set the default application to open it). Or in IDEA: Tools -> Flex -> Create HTML Wrapper. And launch your application in html wrapper. You say, you've installed debugger plugin for browser, so it should work.
Comment: I found that issue is happens due to system default application. It is not the debug version of flash player. In Run/Debug Configuration, I cannot able to set Options for "Launch with" because it is diabled. I can able to set options for just before launching by selecting   Before Launch > show settings. I dont know it is intellij issue or mine.
Comment: You have to select one of the launch types: "HTML wrapper or swf file", "URL" or "Main class", then in "Launch with" option click on the button next to the input (the one with ellipses), on the popup select "Browser" and use the combobox to select the browser you want to use.
Comment: @bmleite eventhough i try to select those different options, "Launch with" option is not enabled. I think it is a bug in intellij,
Answer: If you are using chrome, the default flash player is not the debug version. After installing the Debug version of the player. you must disable the default version in Chrome.
Open Chrome
Go to chrome://plugins
here you should see both versions of the shockwave player. Disable the first one or the one that is located here:
C:\Users\your_username\AppData\Local\Google\Chrome\Application\22.0.1229.94\PepperFlash\pepflashplayer.dll
Now the debug version should be working in Chrome and should also work from Intellij if chrome is your default browser or set as the browser to open on debug.
Answer: Browser
Don't use Chrome to debug your SWF as it contains a non-debugger version of Flash Player. So after installing the Flash Player debugger, use Firefox, for example and make it as default browser.
SWF File
Be sure that you compiled your file as a debug version. To do that, have a look to your project structure. Then on your module and build configuration. In the compiler options, you should be able to check the "Generate debuggable SWF" option.

RUN/DEBUG Configuration
Check in the What to launch option, you selected your swf via HTML Wrapper. Check also that you selected the right Flex SDK in the options panel:

FINALLY
Launch your debug configuration. Intellij will build your project, create an HTML wrapper and launch it in the default browser (Firefox).
Your SWF should then be debuggable. If it still does not connect to the debugger in Intellij, right click in your flash application in Firefox and click Debugger
Answer: Based on the suggestion given by Timofei & bmleite, I fixed it.
When you debug pure SWF, make sure to check the default player is a debug player.  Debug player has "Show Redraw Region" on right click.
Comment: I normally visit http://www.playerversion.com/ to find out which player version I'm running.  Note that since 10.1.??? you can also see the player version by right clicking.
Comment: HI Marty, My requirement is to test without html wrapper. So need to verify the standalone player version.
Answer: IDEA generates html file that embeds swf file for users' convenience. If you open this html from file system, it allows you to debug SWF. If you put it (with the rest of files) to http server, then 'Debug' menu item is disabled in Chrome. In IE it works fine. This is obviously a Flash Player's bug.


How do I apply the `loading="lazy"` attribute to responsive media?

Question: On my Drupal 9 installation when I create an "image" field, Drupal automatically adds the loading="lazy" attribute.
When I create a "media" field with an "Adaptive Image Styles" display, the loading="lazy" attribute is not applied.
How to apply the loading="lazy" attribute to responsive media?
If I go to a media image, there is "lazy" :

If I go to a media image with the adaptive image style, there is no "lazy" :

UPDATED WITH cilefen REPLY
I tested on Drupal 9.4 and it seems that the update does not fix the problem. loading="lazy" is unavailable for "Responsive image" :

While it is available for non-responsive image :

So I rest my question, how to apply loading="lazy" on the "Responsive image" ? This is a big problem for page performance.
Comment: If you are using the Blazy contrib module, this sounds like a feature request for that module: https://www.drupal.org/project/issues/blazy
Comment: @PatrickKenny I don't use a contrib module, it's drupal 9 which adds blazy on all images except for adaptive image styles
Comment: @zoulou66 That is not true. Core adds loading=lazy attribute: https://www.drupal.org/node/3173719
Comment: @cilefen This is what I want on my images, but it does not add it on the media with the adaptive image style
Comment: I updated my question, with screenshots to better explain
Comment: I amended my answer with the most current information.
Answer: This is an active area a research and development in Drupal Core. Although there is no quick fix, this issue is the locus of work. Test the patches and provide feedback.


Is there a name for the guitar-based scale E-G-A-C-D-E?

Question: If you use only the open chords on a guitar, you can walk a bass line using these notes:
E G A C D E
This line tends to be expressed with chords that mix modes. So for example the A chord may contain a C# and the E chord may contain a G#, meaning that there are various way to harmonize chromatic lines.
This results in a tonal language, for lack of a better term, composed of the following set of pitches:

E F# G G# A B C C# D E

You might call this a scale, a gamut, or an aggregate, or just a pitch class set-- I don't really care-- but what I would like to know is if this has a name and what it might be.
Two songs that seem to use it:
Tom Petty - Running Down a Dream
Avril Lavigne + Marilyn Manson - Bad Girl
Comment: With your recent edit, you've changed the meaning of the question in a way that requires additional information. As written, it suggests that for each root, the major or minor chord could be used. This makes the resulting scale C C# D E F F# G G# A  Bb B, but I don't think that's what you're really trying to ask.
Comment: Your initial question was correctly answered by @Aaron. Your heavily edited version says you believe this "scale" to be 5 notes with major triads built on each note. That is not what a scale is. You can build chords from a scale but the notes in a scale do not imply harmony. Todd is correct, CAGED are not the only open major chords that can be played on the guitar although they are the most complete and practical. If you are talking about using those 5 chords CAGED together that's something completely different than referring to them as a scale.
Comment: I don't understand how you derived this scale. Are you only counting the roots of the open chords? Because I know a Bm7 open chord and also an F open chord so why did you leave out B and F?
Comment: @Aaron I did not edit my question to trick anyone, I'm just trying to find the best way to express myself without using the wrong words, which seems to upset some people. Regardless of the terminology I've provided two examples which should help to clarify.
Comment: @ToddWilcox I did not pick and choose the notes to put in this scale, other musicians did. I am just observing. I have not observed Bm7 or F in the uses of this idiom.
Comment: @JohnBelzaguy I've done my best to correct the terminology. If you have any suggestions I'd appreciate it.
Comment: @JohnWu I wasn't accusing you; just pointing out the question needed further clarification. Your most recent update provides exactly what was needed.
Comment: The set of pitches from those major chords is: E F# G G# A B C C# D. You forgot F# found in D major and B found in E major.
Answer: This is the question as I understand it:
If your song is centered on E major as tonic, and you use the major chords E G A C and D in your chord progressions, it seems to mix modes in a certain style that can be found in many pop songs. Is there a name for this style?
I agree it's a common style, and the guitar's open-string chords seem to produce that style automatically. Or at least, when I picked up the guitar at age 11 when I had a chance and nobody was around, and I started to find chords without knowing anything or having any books or anything, simply by trying to put my fingers like I had seen guitar players do, I found the chord progression E - G - D - A - E in a matter of a few minutes. I didn't know the names of the chords or anything, but I liked the sound of it a lot, it felt very fascinating and different from songs I was playing by ear on the piano. So from my own anecdotal evidence, it's justifiable to say it's guitar-based. It's almost as if it was a built-in preset sound in the guitar - just pick up the instrument and that's what comes out by itself.
It took me some years to translate the style to my piano playing and find ways to reason about what was happening with the chord progression: it seemed to move between keys E major and E minor in a fluent way. And not studying music in any institution, it took decades to find out that there are actual names for that moving-between-keys fluidly. One of the words is "modal mixing", like you suspected. Playing a chord from a different mode makes changes to the harmonic context, and this can be called modal mixing. For example going from the E major chord to G major toggles the sharp/natural/flat switch on the G scale position from sharp to natural. And eventually getting back home to E major returns the switch to sharp.
If I compare the style to playing the piano, in my subjective experience, the piano somehow tends to encourage staying inside a key and not do too much modal mixing. I can only guess where that difference comes from, but maybe it's due to having to concentrate on seeing the scale of the key on the piano keyboard, and changing that to a different scale feels like a more serious thing than on the guitar. When playing guitar chords you don't even have to think about what your scale is. You just play your chords and let theory guys analyze it later!
One characteristic trait in this guitar-based style is the lack of or avoiding the so-called leading tone, which in E major would be D#. Likewise, the B major chord is not used. If you'd like to play a B-based chord, B minor would fit the style better. Playing or singing a D# would feel like a breach of style here, unless you do it in a bluesy way, alternating somewhere between D and D#.
However, I'd like to claim that there's a simpler and less fancy name for this style. It's actually shown by Youtube if you have captions on:

It's called rock music.
Comment: Good answer but what about the good ol'fashioned open B7 chord? It's very common in open chord tunes in E
Comment: @JohnBelzaguy Very good question! I feel that using a B7 chord would break away from the style or "tonal language" that the OP means. I don't say that there are no proper dominant V chords in rock music, but this particular flavor - would it be _blues rock_ then? There is a difference in mood when you allow a leading tone to happen vs. when you don't. Maybe my answer wasn't very good, because I wasn't able to pinpoint a clear name. :/
Comment: Point taken, there are many songs that use all or 4 of the 5 CAGED chords and they don't usually contain a B7. Good point about the lack of a leading tone in those chord progressions.
Answer: You'd call it a mode of the pentatonic major. Specifically C pentatonic major. The notes for the basic scale are C, D, E, G, A. Another well-used mode of that scale is the pentatonic minor, running A, C, D, E, G.
A mode is a scale which uses the same notes as a particular major scale, but roots on a different note from the original.
Whilst this may have answered the original question, it's quite possible it doesn't adequately address the heavily edited version. Which is not reflected well in the header.
Comment: +1 This answers the question that's in the title. But the question in the... question is pretty much entirely different.


When using Jeffrey's prior for Normal model, what is $p_J(\theta, \sigma^{2} | y_{1}, ..., y_{n})$ supposed to be?

Question: I'm reading A First Course in Bayesian Statistical Methods by P. Hoff where he is using Jeffrey's prior (J) and Unit information prior (U) for Normal model. For example we can derive Jeffrey's prior for Normal model and get $p_{J}(\theta, \sigma^2) = (\sigma^2)^{-3/2}$ and then obtain a posterior $p(\theta, \sigma^2 | y_{1}, ..., y_{n})$ as the product of prior and likelihood. I don't understand what he means by probability density with subscript J, for example: $p_{J}(\theta, \sigma^{2} | y_{1}, ..., y_{n})$ or $p_{J}(\theta | \sigma^2, y_{1}, ..., y_{n})$. Can someone please explain?
Comment: In the context of the problem, it means the posterior pdf associated with Jeffrey's prior. i.e. it is $p_J(\theta,\sigma^2|y_1,...,y_n)\propto p_J(\theta,\sigma^2)p(y_1,...,y_n|\theta,\sigma^2)$
Comment: Thank you for your answer, so it is only the posterior we obtain as the product of Jeffrey's prior and likelihood? And what is $p_{J}(\theta | \sigma^2, y_{1}, ..., y_{n})$ and $p_{J}(\sigma^2 | y_{1}, ..., y_{n})$ supposed to be and how to derive it?
Comment: In general the posterior is the product of the prior and the likelihood. The subscript J is only to indicate that in the particular example the Jeffrey's prior is used. Consequently the $p_{J}(\theta|\ldots)$ and $p_{J}(\sigma^2|\ldots)$ are the full conditional for the parameters $\theta,\sigma^2$ which are obtained from the full posterior under the Jeffreys prior.
Answer: In general the posterior is the product of the prior and the likelihood. The subscript J is only to indicate that in the particular example the Jeffrey's prior is used. Consequently the
$p_{J}(\theta|\ldots)$ and $p_{J}(\sigma^2|\ldots)$
are the full conditional for the parameters $\theta,\sigma^2$ which are obtained from the full posterior under the Jeffreys prior. You derive them from the full posterior as the distribution depending only on the parameter of interest up to a constant of proportionality.
For example suppose that we have a posterior of the form
$ p(\mu,\lambda|\ldots) \propto \lambda^{\frac{1}{2}}e^{-\frac{\lambda}{2}(x-\mu)^2}.$
Then the full conditional for $\lambda$ is
$p(\lambda|\ldots) \propto \lambda^{\frac{1}{2}}e^{-\frac{\lambda}{2}(x-\mu)^2},$ which is a $Ga\left(\frac{3}{2},\frac{1}{2}(x-\mu)^2\right),$
and for $\mu$
$p(\mu|\ldots) \propto e^{-\frac{\lambda}{2}(x-\mu)^2},$ which after some
algebra is a normal distribution.
Comment: Thank you for your answer. I understand now. For my example, Normal model with Jeffrey's prior, I derived full conditionals $p_{J}(\theta | \sigma^{2}, y_{1}, ..., y_{n}) \propto \texttt{Normal}(\bar{y}, \sigma^2/n)$ and $p_{J}(\sigma^{2} | y_{1}, ..., y_{n}) \propto \texttt{InverseGamma}(n/2, \sum_{i=1}^{n}(y_{i} - \bar{y})^{2}/2)$.
Comment: No problem at all. I am glad i helped!


Exibir balão popup sobre um Label

Question: Gostaria de exibir uma pequena mensagem para o usuário, estilo aqueles quando se passa o mouse, se não me engano seria o atributo

alt="minha mensagem"

porém estou usando asp.net-mvc-5 e estou encontrando dificuldades para fazer. Minha mensagem, gostaria que aparecesse no @Html.LabelFor, e também queria que fosse uma mensagem fixa, acredito que com CSS, jquery ou javascript eu consiga fazer, mas não encontrei nada que me ajudasse.

    @Html.LabelFor(model => model.Celular, htmlAttributes: new { @class = "control-label col-md-2" })

          @Html.EditorFor(model => model.Celular, new { htmlAttributes = new { @class = "form-control celular", id = "txt-tel" } })
          @Html.ValidationMessageFor(model => model.Celular, "", new { @class = "text-danger" })

Comment: [Assim, então](http://www.menucool.com/tooltip/javascript-tooltip)?
Comment: [Isto que você quer](https://jqueryui.com/tooltip/)?
Comment: Semelhante a isto, porém a ideia maior, seria que fosse exibido um balãozinho ao carregar a página, e ele sumisse quando o usuário passasse o mouse em cima, mas neste formato já me ajuda.
Comment: Isso, Obrigado @CiganoMorrisonMendez
Answer: O que você quer é um Tooltip. Há várias bibliotecas que fazem isso. Possivelmente você quer alguma que se comporte como esta aqui.
Tooltips são em JS, então independem do ASP.NET MVC. O uso é feito da seguinte forma:

    Exemplo de texto com Tooltip

Comment: Quando atribuo a classe tooltip meu conteúdo fica oculto
Comment: Veja os exemplos no site que passei. Tem mais exemplos de uso.

Exibir balão popup sobre um Label


How to replace a letter by mouseover with jQuery?

Question: I just wondered how I could change every o to a  by mouseover. How is it possible to do that?

var o = 'o';

$(o).mouseover(function() {
  $(this).textContent = "";
});
* {
  margin: 0;
  padding: 0;
}

section {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: tomato;
  position: relative;
}

article {
  transform: perspective(400px) rotateY(45deg);
  font-family: sans-serif;
  font-size: 4vw;
  text-align: center;
}

Like this post if you like cookies

Comment: css would be your friend
Comment: @DanielA.White Don't you think the cookies tag was funny? And you would solve it only with css? Well, temporary with a hover function, it makes sense. But would it also be possible to let the cookies stay with CSS only?
Comment: jQuery selectors select elements, so the code in the question selects all of the `o` elements, of which there are none. If you replaced all of the "o"s in the text with `o`, that code might work. It would be invalid HTML, but it would work...
Answer: This is one way of doing it...
I'm using jQuery to manipulate the
 tags.  I take the original text and store it in a data:text attribute on that element so there won't be a need to undo any changes to the text.  Then the text is changed and updated within that element.
Then when the mouse moves out of the element, it then restores the original text, and then deletes the temporary data:text attribute.

$("p").mouseover(function() {
  var el = $(this);
  var text = el.text();
  el.attr("data:text", text);

  el.text(
      text.replaceAll( "o", "")
          .replaceAll( "t", "₸" )
          .replaceAll( "a", "ꋫ" ));
});
$("p").mouseout( function() {
  var el = $(this);
  var text = el.attr("data:text");
  el.removeAttr("data:text");

  if ( text && text.length > 0 ) {
    el.text( text );
  }
});

String.prototype.replaceAll = function( search, replace ) {
    var results = this.split(search).join(replace);

    return results;
};
* {
  margin: 0;
  padding: 0;
}

section {
  width: 100%;
  height: 120vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: tomato;
  position: relative;
}

article {
  transform: perspective(600px) rotateY(35deg);
  font-family: sans-serif;
  font-size: 4vw;
  text-align: center;
}

Like this post if you like cookies

Here is more text to explore.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.


Implementing a application HTML help system

Question: We want to implement a application help and documentation system. It should be based on HTML, because there are a lot of existing files and it gives us the most flexibility. Currently we use CHM files. We want to enable internal people (not developers) to edit the contents.
We thought of a stand-alone application that supports TOC, indexing (tags), search, etc. We also thought of using a local web server.
Until now our application uses pure C#, it would be good to keep this.
We are totally clean of web/asp knowledge, so the question is:
Where is a good place to start?
Answer: You can use documentation apps like SandCastle
Which use your XML documentation in your code to generate a help file.
Comment: Thanks for your answer. I'm already using Sandcastle for my source documentation. But i was searching for a help system that ships with my application, for the end-user documentation.
Answer: Finally we ended up implementing a local HTTP server:

Internal people creates HTML content within our internal network
Our own build-tool creates the TOC and a search index and packs all content to a zipped file
The zipped file is packed into the application installation
When the end-user call help from within our application, the local http server is started
The HTTP server uses the HttpListener class
With this, it is possible to have some HTTP queries for special tasks like starting tools of our application by clicking a link without interception of the browser


Como duplicar os registros de uma tabela no BD

Question: Bom eu tenho um BD com alguns registros. E eu gostaria que essa quantidade de registros duplicasse. Não quero fazer loop duplo para mostrar a dupla quantidade, gostaria de literalmente duplicar todos os registros na tabela. Há alguma forma de realizar isso?
Answer: Amigo faz um insert e nos values voce faz um select, assim:
INSERT INTO [Database].[dbo].[Table]
       ([Coluna1]
       ,[Coluna2])
 select Coluna1, Coluna2 from Table
GO

Isso vai duplicar sua tabela, pois ele vai  inserir tudo o que ja existe na sua tabela.
Espero que ajude. []'s
Answer: Utilize um insert junto com um select, os tipos de dados no select e no insert devem ser os mesmos ou compativeis também é possivel utilizar outras clausulas como where, joinetc
INSERT INTO tabela(c1, c2, c3) SELECT c1, c2, c3 FROM tabela

insert select syntax
Comment: Deve ser colocado no lugar de c1 do SELECT, o valor Null se, somente se, c1 for a chave primaria do banco, senão haverá um erro ao tentar duplicar o id.


Como remover um alert depois de selecionar outro em um select

Question: Estou com o seguinte código:
HTML:
<select class="form-control btn-form" id="select-category">
      <option selected hidden>Selecione uma categoria:</option>
      <option value="anu1">Anunciante1</option>
      <option value="anu2">Anunciante/option>
      <option value="anu3">Anunciante3</option>
</select>

JS:
$('#select-category').change(function(){
  if($(this).val() == 'anu1'){
      document.getElementById('alert-anu-1').style.display='block';
  }

  if($(this).val() == 'anu2'){
    document.getElementById('alert-anu-2').style.display='block';
  }
  if($(this).val() == 'anu3'){
    document.getElementById('alert-anu-3').style.display='block';
  }
});

A ideia é ter uma lista e depois quando o usuário selecionar uma opção mostrar um "alert" em bootstrap. Ou seja, se o usuário selecionar o valor "anu1", mostra o alert "alert-anu-1", isso até então está funcionando. O que não estou conseguindo é limpar os valores.
Ex: se selecionar o valor anu1, mostra ele, mas se selecionar o valor anu2, tem que limpar o alert do anu1 e mostrar apenas o do anu2 e assim por diante....
Como poderia fazer isso?
Answer: Você não esta tirando o display, quando coloca com o display = "block" é preciso colocar display = "none", assim vai esconder a mensagem.
$('#select-category').change(function(){
    for(var x=1;x<=3;x+=1) //apaga as 3 mensagens
        document.getElementById('alert-anu-'+x).style.display='none';

    if($(this).val() == 'anu1'){
        document.getElementById('alert-anu-1').style.display='block';
    }
    /*...*/
});

Answer: Acho que basta algo como:
var alerts = $('[id^="alert-anu-"]');
$('#select-category').change(function() {
    alerts.hide();
    $('#alert-' + this.value).show();
});

Assim quando o select muda ele esconde todos os alertas e mostra só o que foi escolhido. Criei a variável alerts para ter esses elementos em cache e evitar ir ao DOM buscá-los muitas vezes.
Comment: Gostei desse jeito, mas não consigo executar. Os meus alerts e os meus valores estão escritos e não estão numerados como no exemplo.
Comment: O meu alert é tipo:
PetBusca. Ferramenta bacana.... Saiba mais....

Comment: @HitchLeonardo não faz diferênça se usas outros nomes para as IDs. Nesse caso podes usar `var alerts = $('[id^="alert-anunciante-"]');`, a chave aqui é `^=` que indica ID __começando com__ "xxx". Se quiseres um exemplo a funcionar junta um jsFiddle ou o código todo na pergunta.


Extend view under status bar on Android 11

Question: We've been trying to migrate our codebase to compile (without using deprecations) against API 30 and have ran into some issues with the broad deprecations dealing with the system UI and window insets.
We're trying to have content drawn under a persistent status bar, but not under the nav bar. (so setDecorFitsSystemWindows doesn't work)
Previously we were doing this:

activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
activity?.window?.decorView?.systemUiVisibility?.let {
    activity?.window?.decorView?.systemUiVisibility = it and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
}

binding.start.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)

I've been able to get the status bar consistently turned light via
window.insetsController?.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)

Using insets the controller, but I can't figure out how to get the view to extend up under the status bar.
I tried messing with the insets but setOnApplyWindowInsetsListener isn't called anymore for their modifications.
Looking all over the web I don't see any non-deprecated way to get this behavior. I'm wondering if this is even possible anymore?
Comment: So basically you want your activity to draw behind a transparent status bar?
Answer: In style
<item name="android:windowTranslucentStatus">true</item>

In Manifest
android:fitsSystemWindows="true"

In my Android 11, The status bar icon color also changes light and dark while scrolling.
Answer: I stumbled upon this resource about Android 11 insets and was able get this working:
https://blog.stylingandroid.com/android11-windowinsets-part1/
The final compat version to get my desired look is this:
        // force view to be full screen and appearance to be light
        //
        activity?.window?.let { window ->
            WindowCompat.setDecorFitsSystemWindows(window, false)
            window.statusBarColor = Color.TRANSPARENT
            val controller = WindowInsetsControllerCompat(window, binding.root)
            controller.isAppearanceLightNavigationBars = false
        }
        // Adjust view to be under status bar
        //
        binding.root.setOnApplyWindowInsetsListener { view, windowInsets ->
            val insetsCompat = WindowInsetsCompat.toWindowInsetsCompat(windowInsets, view)
            val insets = insetsCompat.getInsets(WindowInsetsCompat.Type.navigationBars())
            binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                updateMargins(insets.left, insets.top, insets.right, insets.bottom)
            }
            WindowInsetsCompat.Builder()
                .setInsets(WindowInsetsCompat.Type.navigationBars(), insets)
                .build().toWindowInsets() ?: windowInsets
        }

The important bits I learned was that if you setDecorFitsSystemWindows to false then the onApplyWindowInsets will be called which allows you to custom inset your view however you'd like.
This is working and giving the same (correct) results from our min of api 26 to 30.


Group Theory via Category Theory

Question: I have previously done a course on group theory and now I am doing a reading course on category theory. So as an interesting exercise I have been asked to write an exposition of group theory for someone who already knows category theory but doesn't know any group theory. I have been given the liberty to decide how I build the theory. I already have a vague idea of what is to be done.

However, I would like to hear ideas about what should be done. So I solicit advice on things I should emphasize, the ways I can exploit the given familiarity with category theory for a more economic presentation and/or a exposition through "the path of least resistance". And please feel free to also mention any tips or precautions.
Please refer me to material along this line.

Thanks!
Comment: @sweeneyrod, many people find themselves needing to revise abstract algebra "essentially from the beginning" though, despite knowing more advanced material.
Comment: @sweeneyrod, Maybe (finally!) category theory is coming first (possibly via computer science)
Comment: @sweeneyrod Well, it is not hypothetical. I am an example. I learned about limits and adjunctions before learning, what a centralizer is.
Comment: Quite an odd hypothetical person - I imagine most people who know category theory studied abstract algebra before it.
Comment: I think you'll find [An Invitation to General Algebra and Universal Constructions](http://link.springer.com/book/10.1007/978-3-319-11478-1) useful. The title should make the reason obvious.
Answer: Here's some food for thought (although its nowhere near enough material):

A groupoid is a category in which every morphism is an isomorphism (i.e. all morphisms are invertible). Groupoids are an oidification of the concept "group"; in other words, a group is just a one-object groupoid.
The inclusion $\mathbf{Grp} \hookrightarrow \mathbf{Grpd}$ does not preserve coproducts. Hence the coproduct of groups is part of what gives group-theory its own special flavour, distinct from the flavour of groupoid theory. (Perhaps use the wedge sum of nice topological spaces to motivate the group-theoretic coproduct in its own right, since the fundamental group of a wedge sum is the coproduct of the fundamental groups under certain general conditions.)
A group is just a connected groupoid, up to equivalence. Hence every (small) groupoid is the (groupoid-theoretic) coproduct of a set-indexed family of groups, up to equivalence. Looking at it another way, groups are kind of like the "atoms" from which we can build up any groupoid. (Note that the same relationship does not hold between monoids and categories.)
Let $\mathbf{C}$ denote a category. Then the isomorphisms of $\mathbf{C}$ form a groupoid called the core of $\mathbf{C}$, typically denoted $\mathrm{core}(\mathbf{C}).$ Now consider the automorphism function $\mathrm{Aut}_\mathbf{C} : \mathrm{Obj}(\mathbf{C}) \rightarrow \mathbf{Grp}$ that takes any object $X$ of $\mathbf{C}$ to its group of automorphisms $\mathrm{Aut}_\mathbf{C}(X).$ This cannot be regarded as a functor out of $\mathbf{C}$ in any sensible way. However, it can be regarded as a functor out of $\mathrm{core}(\mathbf{C})$.
The action of a group $G$ on a set (a "$G$-set") is precisely an object of the functor category
$[G,\mathbf{Set}].$ More generally, the action of a group $G$ on a
"foo" is just an object of $[G,\mathbf{Foo}]$, where $\mathbf{Foo}$
is the category of foos. This makes sense even if $G$ is allowed to
be a general groupoid, or even a general category.
This explains why every homomorphism $\varphi : G \rightarrow H$ of groups gives rise to a functor $[H,\mathbf{Set}] \rightarrow [G,\mathbf{Set}]$ "going the other way"; its because $\mathrm{Hom}$ is contravariant in its first argument.
We may consider group objects in any category with finite products (note that we don't even need finite limits; finite products will do). For example, the group objects in $\mathbf{Top}$ (the category of topological spaces) are precisely the topological groups.
Given a monoid $M$, every $M$-set $X$ is associated with a category $\tilde{X}$ called its "translation category," defined as follows. The object set of $\tilde{X}$ is just the underlying set of $X$. Given objects $x,y \in X$, we define that an arrow $x \rightarrow y$ is just a pair $(x,m)$ such that $m \in M$ and $mx = y$. Composition of arrows is by multiplication. Explicitly:
$$(x,m_y)(y,m_z) = (x,m_z m_y).$$
Furthermore, if $G$ is a group and $X$ is a $G$-set, then the translation category $\tilde{X}$ of $X$ is always a groupoid, called the translation groupoid of $X.$ Note also that every monoid acts on itself by left-multiplication. So given a monoid $M$, we may think of $M$ as an $M$-set, and hence we may write $\tilde{M}$ and speak of the translation category of $M$. As a special case, if $G$ is a group, we may write $\tilde{G}$ and speak of the translation groupoid of $G$.
For something a little more advanced, George Bergman has recently shown how to define the concepts of "inner automorphism" and "inner endomorphism" for objects of an arbitrary category. This could be an interesting viewpoint to take in your own report.
Comment: You could add to item 5 that the functor from [H,Set] to [G,Set] has adjoints on both sides (Kan extensions).
Comment: @AndreasBlass, interesting point. I know almost nothing about Kan extensions; how do we know they exist in this case?
Comment: I think the existence of the Kan extensions, for categories of functors into Set, is always true if the domain categories (in this case G and H) are small. But instead of quoting general results, one can also construct these adjoints explicitly in the case at hand.
Answer: You may want to look at Paolo Aluffi's book called Algebra Chapter zero. He begins talking about categories first and then introduces groups. He says a group is a groupoid (category in which every morphism is invertible) with only one object.
Answer: On the [sub]topic of bibliography, there is a reasonable chapter (#4) in Steve Awodey's Category Theory book; the chapter introduces group theory with the help of category theory. Awodey is a philosophy prof at CMU, which probably explains why he put such a chapter in his book; the target audience isn't assumed have first learned group theory as the math undergrads normally do. A version of that chapter (probalby the one that appeared in the first edition of the book) is freely available on a CMU class webpage.
Answer: There are two books which link  category theory and group theory via the use of groupoids. A pioneer in this was Philip Higgins, whose 1971 van Nostrand Notes are now available as free download as Categories and Groupoids (T&G). Following Philip's lead I started investigating groupoids in $1$-dimensional homotopy theory in 1965, and concluded that the groupoid point of view made many things clearer. The book I published in 1968 is now in its third edition and available as  Topology and Groupoids.   A key tool was the fundamental groupoid $\pi_1(X,A)$ on a set $A$ of base points, chosen according to the geometry, which dates from 1967. The above are the only undergraduate  texts in English using this concept.  here is a  mathoverview discussion on many base points, and a  presentation on the background in algebraic topology was given at Galway in  December, 2014. See also my preprint page.
A feature of both of these books is the use of the following construction. Let $G$ be a groupoid with object set $X$ and let $f:X \to Y$ be a function to a set $Y$. Then we obtain a new groupoid which can be written $U_f(G)$ with object set $Y$ and a nice universal property. From this can be deduced the construction of coproducts of groups, and of free groups and free groupoids. This goes a long way to covering point 2 of @goblin's comment. Thus there is a combinatorial groupoid theory which in principle includes combinatorial group theory.
January 23, 2017 I should say that "combinatorial groupoid theory" is my own coinage, but also reflects JHC Whitehead's term "combinatorial homotopy theory".
The areas include those mentioned above and also fibrations and covering morphisms, groups acting on groupoids, (see T&G for all these). Other references are in my groupoids web page.

To answer the comment of goblin: how does one obtain a groupoid from a bundle of groups? The latter can be seen as a disjoint family $\{G_s: s \in S\}$ of groups.
The associated groupoid $G$ has object set $S$ and a group $G_s$ for each $S \in S$, so that $G(s,t)$ is empty if $s \ne t$.
Another feature of the category of groupoids  is the variety of morphisms. For groups there are mainly two  special kinds of morphisms: injective or surjective. For groupoids we also have fibrations, covering morphisms, universal morphisms, orbit morphisms.
There is a special groupoid $\mathcal I$ which has two objects $0,1$ and only one non identity $\iota: 0 \to 1$, and so also only $\iota^{-1}: 1 \to 0$. This seems a completely useless kind of object! But it defines a homotopy theory for groupoids, and also  plays the same role in the category of groupoids as does the integers $ \mathbf Z$ in the category of groups. Further, identifying $0,1$ in $\mathcal I$ in the category of groupoids gives the integers $\mathbf Z$, which explains the fundamental group of the circle!
Comment: Do you know any good sources on combinatorial groupoid theory? (Papers are fine)
Comment: Look also at arXiv:1207.6404
Comment: Amateur question: How does one obtain a groupoid from a bundle of groups?
Comment: To answer this old question, a disjoint union of groups $\bigsqcup _{s \in S} G_s$ can be regarded as a groupoid with object set $S$ and no no non identity arrows between distinct $G_s$.This is an important example.

Group Theory via Category Theory


Can you have constant mean across samples with different distributions?

Question: Can data samples have constant means even if they are from different distributions?
Comment: Short answer: yes - the sample means can be the same.
Answer: Sampling usually implies a random element so you are not guaranteed equal means of the samples (i assume this is what you mean by "constant"). But randomness also means that some samples drawn from different distributions will have equal means.
To be more precise:

Continuous vs. discrete: Samples from continuous distributions have infinitesimal probability of having equal means while the chances are better from discrete distributions.
Probability of outcome: For distributions with discrete outcomes, a very high probability of one of the outcomes increases the chances that the samples will be identical.
Sample size: Large samples sizes decrease probability of EQUAL means for equal discrete distributions and for all different distributions. They increase the probability of getting SIMILAR means (i.e. not exactly equal but close) for all equal distributions.

E.g. in R:
<code># These two different (discrete) Bernoulli samples are very likely to have equal means, i.e. 1
rbinom(n=5, size=1, prob=0.999)  # 5 samples with 99,9% chance of being 1
rbinom(n=5, size=1, prob=0.998)  # 5 samples with 99,8% chance of being 1

# These two are very likely to be different (big sample size) even though they're from the same distribution
rbinom(n=1000, size=1, prob=0.5)  # 1000 samples with 50% probability of being 1
rbinom(n=1000, size=1, prob=0.5)  # 1000 samples with 50% probability of being 1

#These two are almost guaranteed to be different, because they are continuous, even though the sample size is small
rnorm(2, mean=0, sd=1)  # two samples from the standard normal distribution
rnorm(2, mean=0, sd=1)  # two samples from the standard normal distribution
</code>
Comment: Larger sample sizes will decrease the probability of similar sample means if the population means aren't the same.
Answer: No two samples will have exactly the same mean, even if they are from the same distribution. But, if you mean approximately the same, certainly, why not?
e.g
<code>set.seed(123) #Set the seed
xnorm <- rnorm(100, 0, 1) #Normally distributed
xunif <- runif(100, -1,1) #Uniformly distributed
mean(xnorm)
mean(xunif)
</code>
These aren't exactly the same, because of sampling error; you can make them closer by increasing sample size.
Comment: Discrete distributions can easily yield exactly the same sample mean.
Comment: That's true, I hadn't thought of that.
Comment: Do you know of any tests for equality of means that are robust against non-normality and different distributions?
Comment: user40124 - there was a good answer to exactly that question given here on CV just in the last day, which said just about everything I'd have said. I'll see if I can find it... [yep, here it is](http://stats.stackexchange.com/a/88647/805). There are other answers with similar information to be found. ...(ctd)
Comment: (ctd)...  I'd add a couple of things to that: (i) where the data take small integer values, the impact of ties can be substantial; any rank based tests need to account for the non-continuous distributions (one can still compute the permutation distribution); they also don't tend to be so useful for testing location differences if the shapes and spreads couldn't be rendered similar by monotonic transformation; similar remarks apply to permutation tests; (ii) one approach to the bootstrap with different distributions (if your samples are large enough to support it!) is to resample within groups.


How to phrase voices in a fugue?

Question: I am referring to playing fugues on the piano. I have been taught that I can roughly think of it in terms of SATB (soprano, alto, tenor, bass), and also that the top voice should, in general, be emphasized a bit more (louder, noticeably sticking out, even if only subtly or a little bit so). Is this correct?
And what if, say, there are two voices in the treble clef, but the top voice "goes below", i.e has notes lower in pitch than the bottom voice? Should one still emphasize the top voice so that it is still more clearly heard than the bottom voice? For example, in the example below (the piece is in Ab major I think), assuming the top voice is always denoted by stems pointing up and the bottom voice by stems pointing down, should I sound out the Db and the lower Bb so that they are heard more clearly than the higher Bb and G, respectively? (treble clef, second measure, second two 8th notes).

(Excerpt from the last movement of Beethoven's Sonata No. 31, Op. 110)
In general, should I play each note in a particular voice with equal force? I mean, barring when there are accidentals, accents, or obvious downbeats and such: let's say it's a smooth, uniform string of 16th notes going down the piano register, like a descending scale. I made a kinda crude example below. Again, assuming the stems pointing up are top voice and stems pointing down are bottom voice. If the 16th notes in the second measure are the top voice and the same 16th notes in the third measure in the bottom voice, should I play them subtly differently? (This is probably not the best example, sorry.)

Should the determination of the volume, or emphasis of phrasing, of notes in a fugue be more a function of the voice it is in (SATB) or the pitch (which octave/area it is on the piano register)? Does this even make sense? I'm sorry if this is a silly question.
Comment: Or is each voice "of equal importance", and what does that mean?
Comment: "Or is each voice "of equal importance" - yes, but at any moment in time some voices may be more important than others. "What does that mean?" - well, which of the words "equal" and "importance" don't you understand? It means what it means in ordinary English. It's not some weird musical terminology!
Comment: Related question: [How does one maintain voice integrity when longer and shorter notes of the same pitch occur in two voices](https://music.stackexchange.com/questions/108631/how-does-one-maintain-voice-integrity-when-longer-and-shorter-notes-of-the-same).
Answer: What is most important in a fugue is that you first develop a phrasing and character for the theme, complete with musical accents.  The theme(s) are a bit more prominent than the counterpoint(s), but the main consideration is the horizontal rather than the vertical coherence.  Playing "each note in a particular voice with equal force" is what a Midi rendition from a typesetting program might do.  That's a very mechanical rendition that you should not aim for.  Instead, the goal is to play the theme in a self-consistent and satisfactory way doing expressive justice to its elements, and then doing (mostly) the same on each imitation.
When practicing, it is a good idea, once the basic performance is there, to follow one voice at a time actively with your attention while letting the others work "mechanically".  That way you can figure out where your overall rendition falls flat by losing the horizontal connection within a voice and just swamping the separate lines into some semi-sequence of chords/simultaneous notes.
The end goal must be that whenever a listener wants to focus on one voice and hear only that, he will succeed and hear something that is, in itself, a consistent line with its own inherent dynamics and phrasing underscored by what the other voices are doing (assuming that the composer did not already drop the ball on that, of course).
Answer: In a fugue, each voice is of equal importance.  It is unlike a modern solo/accompaniment texture.  I would suggest picking a phrasing for the fugue subject (and counter-subject, if there is one) and focusing on keeping that phrasing consistent, no matter what voice the subject appear in, or what else is going on at the time.
When I practice fugues, I begin by playing each voice individually and singing along, focusing on getting the phrasing to be consistent.  Then I practice until I can play all the parts and sing along with one of the parts.  So, I would practice a four-part fugue at least four times in a practice session: once while singing the topmost part, once while singing the second part, etc.  Sometimes I work on singing one part while playing an adjacent part: I might sing the treble and play the alto, or vice versa, and do the same with alto/tenor, tenor/bass, etc.
It is a maddeningly slow kind of practice, but it develops the independence and horizontal nature of each part.
Answer:
the top voice should, in general, be emphasized a bit more (louder, noticeably sticking out, even if only subtly or a little bit so). Is this correct?

No. You have a great deal of flexibility in fugues. For example, it is often the theme that is of most interest wherever it is placed; in which case you may want to bring it out. In fact, you will probably mostly want to; however there are many extenuating circumstances, for example, a new counter-subject may be making its first appearance in another voice, and you may wish to bring attention to that. Or, it may be a double fugue, with another theme also making an entrance; etc.

should I sound out the Db and the lower Bb so that they are heard more clearly than the higher Bb and G, respectively?

What can be said for sure, is that you should NOT bring out the top note SATB style if different voices are alternating who has the top note. That is guaranteed to muddy the texture. You probably want to sound out the lower notes you are describing. Or you may want to highlight the other voice. But it is definitely one or the other.

In general, should I play each note in a particular voice with equal force?

No!

Should the determination of the volume, or emphasis of phrasing, of notes in a fugue be more a function of the voice it is in (SATB) or the pitch (which octave/area it is on the piano register)?

Complicated stuff. It's worth remembering that harpsichords of all ages, and any keyboard right up through at least the mid 19th century, had a much lighter bass. So to thunder out a voice in the low register will never sound quite like the composer intended. You may want to do it anyway and have a modern effect, like Busoni doubling the low octaves and adding pedal in his Bach arrangements. More pleasing to the modern ear, though, is probably to give low presentations of the theme a slight emphasis, without overwhelming the timbre of the upper voices.
Comment: " It's worth remembering that harpsichords of all ages, and any keyboard right up through at least the mid 19th century, had a much lighter bass." If you are playing a modern piano, you can't make it sound like a 200-year-old piano or a harpsichord whatever you do. Harpsichords and baroque organs are ideal instruments for the contrapuntal music that was written for them, because you can hear 4 or even more independent "parts" clearly *without* the player having to jump through hoops to make that possible. On a piano, you just have to make the best of the (inappropriate) instrument you have.
Comment: So would you say, in my 2nd example, that I should sound out the dotted quarter note C's (all four of them) and play the 16th notes about equally?
Comment: Ha that's a good question! I would have to think about that passage for a while and experiment with it. I don't know whether the repeated notes or the passagework would strike me as foreground or background. Certainly the echo of the middle Cs up high is probably a point of compositional interest and worth bringing out.
Answer: To answer the specific question rather than talking about fugue-playing in general:
Think about the "big picture" of how your snippet of Op 110 fits into the complete fugue. The fugue starts with a conventional Exposition section, where the three voices convenently enter in order from bass to treble. You don't have to do anything special for the listener to hear the three entries of the subject, because each one is the "top line" of the music.
Next there is a short episode where Beethoven repeats the second half of the subject twice in the top voice in a descending sequence, and then continues downwards for a bar and a half, ending with the trill at the start of your music example.
The event after that is the first entry of the subject after the exposition. The subject is in the bass, doubled in octaves, and marked "forte". That's the most important thing for the listener to hear at this point.
The fact that the two upper parts cross over each other is not very important. The two upper parts come together on a unison (middle C) and the listener has no way of knowing (or caring) whether the "top notes" after that are really the treble or the alto part.
Don't lose sight of the basics: this music is meant to be understood by listening to it, not by picking the score apart note by note. But the performer may have to pick the score apart note by note, to figure out what the listener needs to hear!
When the subject has entered in the bass, the second most important thing going on is the dotted quarter notes - the Ab in your snippet, followed by G and Bb in the next bar. They have the same rhythm as the subject, and they sound vaguely like some contrapuntal variation of it, even though they are not exactly a canon, an inversion, or anything else. But they are a signpost as to what sort of counterpoint the listener might expect to hear later on - so make sure they get noticed, and be thankful Beethoven put them at the top of the counterpoint rather than in the middle, which makes it easier for them to be noticed!
Continuing at this level of detail bar by bar would take too long - but that's the sort of "analysis" you need to think about before playing this.
Comment: +1, because this is pretty much how fugue-playing in general works. The voices are _not_ all of equal importance - that changes as the fugue progresses, and the changes can take place in very close succession - but, if the composer is up to snuff, you don't have to do much to bring out the important voices. Beethoven might have been up to snuff, d'ya think? ;)
Comment: Thanks. I am not really ready to attempt this difficult piece, but I just really like it so sometimes I try a little... xD

@Patrx2 yes! All his sonatas are fantastic, and I particularly love the fugal parts.
Answer:
I have been taught that ... the top voice should, in
general, be emphasized a bit more

I hope not. For a first-time listener, each entry of the main subject needs to be clear and equally important. Also lines may cross so the "top" voice is not always on top. A great example of this is the D Major Fugue from Well-Tempered Clavier, Book II. The rapidity at which the subject is repeated and the way the different contrapuntal overlaps occur is astonishing.
P.S. I just found the following video. It's well worth a look.
Amazing Counterpoint: Analysis of D Major Fugue from Bach's Well-Tempered Clavier, Book II
Also, if you want to hear each voice actually in SATB format, you can do no better than this J. S. Bach - Fugue n.5 in D Major BWV 874 from Well-Tempered Clavier II- Jazz-Voices Transcription
This group (The Swingles Singers) recorded a whole album of SATB Bach, Jazz Sebastian Bach much of which can be found on YouTube.

How to phrase voices in a fugue?


Very confused about the Principal branch cut of the complex Log(z)

Question: If I understand correctly the domain of the principal branch of exp(Log(Z)) is restricted from -/+ pi because arg(z) is periodic, therefore without the restriction the function would not be one to one. Also the negative real axis is removed because the Limit, as one approaches the negative real axis is not the same if approached from above or from below. This makes some sense to me
What I am really confused about is the removal of the negative real axis and what effects this has, does this mean you cannot take the Log of any negative number such as (-3+0i) because it is undefined with the principal branch cut.
Comment: What does it mean limit is not the same when we approach from above or below?
Answer: The situation is a little bit more complex than you are describing. Also there are two different concepts you are talking about: just calculating $\operatorname{Log}(-3)$ using the principal branch of the complex logarithm and studying $\operatorname{Log}$ as a function.

There ist not THE principal branch of the complex Logarithm. Depending on how you define the argument, your Logarithm can change. Defining the argument of a complex number $z\in\mathbb C$ as the unique $\varphi\in(-\pi,\pi]$ such that $z=r\cdot e^{i\varphi}$ is just a convention. One might define the argument using $\varphi\in [-\pi,\pi)$ or $\varphi\in [0,2\pi)$ or $\varphi \in [x,x+2\pi)$ for any $x\in\mathbb R$.
The Logarithm of a complex number $z\in\mathbb C^*$ can now be defined as $$\operatorname{Log(z)}=\ln(|z|)+i\arg(z).$$ This yields a function $$\operatorname{Log}:\mathbb C^*\rightarrow\mathbb C,~z\mapsto\operatorname{Log}(z).$$ which is usually called the principal branch Keep in mind that our definition of $\operatorname{Log}$ depends on our definition of $\arg$, so if you decide to define $\arg$ using $\varphi\in (-\pi,\pi]$ and a friend of yours decides to define $\arg$ using $\varphi\in [0,2\pi)$, you will get different principal branches. If you are just interested in the value of $\operatorname{Log}(z)$ for any $z\in\mathbb C^*$, you can use the principal branch without any problems, you don't have to exclude the negative real axis for just calculating the value.
If you want to study the principal branch as a function, you will soon start ask about things like continuity. Only now it is neccesary, to exclude some part of the complex plane to get a continuous, holomorphic function. Again, the way you defined $\arg$ might change what you have to cut out. If you chose to have $\varphi\in (-\pi,\pi]$, then $\operatorname{Log}$ is continuous on $$\mathbb C\setminus\{x\in\mathbb R~|~x\leq 0\}.$$ If you instead chose to have $\varphi \in[0,2\pi)$, then $\operatorname{Log}$ is continuous on $$\mathbb C\setminus\{x\in\mathbb R~|~x\geq 0\}.$$
Answer: Yes, one removes that in order to keep continuity, and differentiability. As pointed out you'll have different limits if you come from above or below and therefore you have no unrestricted limit and without limit you can't define a function continuously there.
This is because one of the central points in complex analysis is the differentiability of functions, so that one very much like to keep.
The principal branch is just something that has been chosen to be the "normal" way of creating a branch. If the situation calls for it one could always create another branch. You do this by first selecting a cut path (other than the negative real axis) and also which value that should be taken at a particular point.
Comment: Thank you, If you wanted to take the log(-3+0i), can you just take a different branch cut ?
Comment: @user299113 Yes, thats what one normally would do if you need it to be defined for negative real numbers. You could then for example cut along the negative imaginary axis.
Comment: Thank you for your answer,  I have spent far to long thinking about this one question and I am running out of study time for an upcoming exam. Now I can move on.


Python Searching from a Wordlist Function Issues

Question:
For one reason or another I am having issues with understanding how to get my word list to search a text file for the list of words I have provided. I did find a way around creating a word list by using "elif" statements but I would like to do this properly. - Python 3.7.x
name = 'Foo'
name1 = 'Bar'
name2 = 'python'
searchfile = open("test.txt","r")
num_lines = 0

for line in searchfile:
    num_lines += 1
    line = line.lower()
    if name in line:
        print ("Found on Line:",num_lines, line)
    elif name1 in line:
        print ("Found on Line:",num_lines, line)
    elif name2 in line:
        print ("Found on Line:",num_lines, line)

I would like to make the "name" variables have a lists of words to search. like so.. But I am getting errors.
name = ("foo","bar","python")
name1 = ("foo1","bar1","python1")
name2 = ("foo2","bar2","python2")

TypeError: 'in ' requires string as left operand, not tuple
maybe if I see the correct code my brain will understand it. Any help would be appreciated.
Comment: Firstly, it is generally considered poor practice to have numbered variables instead of a list. So rather than name='x', name1 = 'y', name2 = 'z', you instead do names = ['x', 'y', 'z']. As far as the list of names go, do you need one or all of the values in each tuple present in order to have a match? Do they need to be in order?
Answer: The simplest way would be to just use a for loop
name = ("foo","bar","python")
for n in name:
    if n in line:
        print ("Found on Line:",num_lines, line)

Answer: It is because in your example name is a tuple and making name in line would try to check if a tuple is inside the line which is string type.
You can iterate over any word you want to check like this
name = ('Foo', 'Bar', 'python')
searchfile = open("test.txt","r")

for num_lines, line in enumerate(searchfile, 1):
    for word in names:
        if word.lower() in line.lower():
             print("Found on Line:", num_lines, line)

In addition if you want to have multiple "names" as you said, you could do:
name = ("foo","bar","python")
name1 = ("foo1","bar1","python1")
name2 = ("foo2","bar2","python2")
names = name + name1 + name2

And iterate for word in names as before. I do not know what are your requirements, but it's better to create
names = ("foo", "bar", "python", "foo1", "bar1", "python1", "foo2", "bar2", "python2")

as a single tuple instead of N tuples.


Limit of sum of series

Question: Let $$\sum_{i=1}^\infty c_i^{(0)}$$
be a positive convergent series. Then the series:
$$\sum_{i=1}^\infty c_i^{(1)}=\sum_{i=1}^\infty \ln(1+c_i^{(0)})$$
is also a positive convergent series.
Generally let take $c_i^{(N+1)}=\ln(1+c_i^{(N)})$ and define the sum:
$$S^{(N)}=\sum_{i=1}^\infty c_i^{(N)}$$
What can we say about the limit:
$$\lim_{N\rightarrow\infty} S^{(N)}.$$
which is certainly exist. Is it zero? Is it nonzero? (given $\{c_i^{(0)}\}$)
Comment: It seems to me that conditions on $c_{i}^{(0)}$ must be very strict to provide any $c_{i}^{(N)}$ being positive
Comment: $\ln(1+c)>0$ provided that $c>0$
Comment: @Mr.T, yes, you are right. I was fool:-)
Answer: A start: Use Comparison. Note that if $x\ge 0$ then $0\le \ln(1+x)\le x$.
Comment: Yes. If you feel in a formal mood, you can prove it by induction.
Comment: You are welcome.  About the additional detail on rate, at first sight I have nothing particularly useful. If the $c_i$ are small, one can get an easy inequality the other way, using (for small $x$) $\ln(1+x)\gt \frac{x}{2}$.  That is much too weak, the rate of decay of the iterated operation is definitely not exponential.
Comment: Then $S^{(N)}$ is strictly decreasing I think.
Comment: Thanks for that point. But I really want a nontrivial estimation, and calculate $S^{(\infty)}$ from $c_i^{(0)}$ if possible :)

Limit of sum of series


XML SAX Parser with PHP7

Question: I need to read an XML file from the top to the bottom, while doing my reseach I found out about SAX Parser, and more exaclty I found this link:
http://www.brainbell.com/tutorials/php/Parsing_XML_With_SAX.htm which works well and is exactly what I need.
But I can't find an exemple of SAX Parser with a PHP class or in a more "PHP7's way" , I was wondering if it was depreciate or it there are any better alternatives nowadays ?
Comment: Have a look at XMLReader (http://php.net/manual/en/book.xmlreader.php)
Comment: Initating the parser is done using `xml_parser_create` in the given example, and thats a function still present in PHP. Is that already fine for you or are you using something more specific?
Comment: It's fine I was just wondering if there are sometings better, I'm going to have a look at XMLReader
Answer: XMLReader (http://php.net/manual/en/book.xmlreader.php) provides a much more modern approach to processing XML piece by piece.  Even the article you refer to has this at the end...

PHP 5.1 comes with XMLReader included by default. This is a wrapper on
  libxml2 and mimics the application programming interface (API) of the
  C# component for reading XML, XmlTextReader. It is much faster than
  SAX and just easier to use.

There are a few examples round about how to use XMLReader-
How to use XMLReader in PHP?

XML SAX Parser with PHP7


Understanding theme hooks and template preprocessors

Question: In hook_theme for the poll module in drupal 7 the following is defined:
function poll_theme() {
  $theme_hooks = array(
    'poll_vote' => array(
      'template' => 'poll-vote',
      'render element' => 'form',
    ),
    'poll_choices' => array(
      'render element' => 'form',
    ),
    'poll_results' => array(
      'template' => 'poll-results',
      'variables' => array('raw_title' => NULL, 'results' => NULL, 'votes' => NULL, 'raw_links' => NULL, 'block' => NULL, 'nid' => NULL, 'vote' => NULL),
    ),
    'poll_bar' => array(
      'template' => 'poll-bar',
      'variables' => array('title' => NULL, 'votes' => NULL, 'total_votes' => NULL, 'vote' => NULL, 'block' => NULL),
    ),
  );
  // The theme system automatically discovers the theme's functions and
  // templates that implement more targeted "suggestions" of generic theme
  // hooks. But suggestions implemented by a module must be explicitly
  // registered.
  $theme_hooks += array(
    'poll_results__block' => array(
      'template' => 'poll-results--block',
      'variables' => $theme_hooks['poll_results']['variables'],
    ),
    'poll_bar__block' => array(
      'template' => 'poll-bar--block',
      'variables' => $theme_hooks['poll_bar']['variables'],
    ),
  );
  return $theme_hooks;
}

In function poll_view_voting($form, &$form_state, $node, $block = FALSE) { there is $form['#theme'] = 'poll_vote';
How does this work and what does this to?
Also there is this function:
function template_preprocess_poll_vote(&$variables) {
  $form = $variables['form'];
  $variables['choice'] = drupal_render($form['choice']);
  $variables['title'] = check_plain($form['#node']->title);
  $variables['vote'] = drupal_render($form['vote']);
  $variables['rest'] = drupal_render_children($form);
  $variables['block'] = $form['#block'];
  if ($variables['block']) {
    $variables['theme_hook_suggestions'][] = 'poll_vote__block';
  }
}

I was able to create a function theme_preprocess_poll_vote(&$variables) which I was able to change the output. Is their a document that explains how this all works?
Answer: I'd suggest you read everything you can in the Theming guide.  It looks like you're specifically looking for this part of it though.


If $f,g$ are continuous functions, then $fg$ is continuous?

Question: Let $X$ be a topological space and let $f:X \to \mathbb{R}$ ,$g:X \to \mathbb{R}$ be continuous functions. Show that $fg$ is continuous.
My work:
To show $fg$ is continuous at $x$ for each $x \in X$, let $y=fg(x)$.
To show if $N_y$ is a neighborhood of $y$, then the pre-image of $y$ is a neighborhood of $x$.
I know that there exists $B_\epsilon(y) \in N_y$ so I want to show that $(fg)^{-1}(B_\epsilon(y)) \in N(x)$
Let $N_x=(fg)^{-1}(B_\epsilon(y))$, I want to find an open set in $N_x$.
Can anyone give me a hint of how to choose such open set or idea how to prove this ?
Answer: Here is an alternative approach:
Claim 1. If $f: X\to\mathbb{R}$ and $g: X\to\mathbb{R}$ are continuous, then $f+g: X\to\mathbb{R}$ is continuous.
Proof. Given a point $x\in X$ and $\epsilon>0$, we want to show that there exists a neighbourhood $N_{x}$ of $x$ such that $(f+g)(N_{x})\subseteq B_{\epsilon}((f+g)(x))$. By continuity of $f$ and $g$, you can find a neighbourhoods $N'_{x}$ and $N''_{x}$ such that $f(N'_{x})\subseteq B_{\epsilon/2}(f(x))$ and $f(N''_{x})\subseteq B_{\epsilon/2}(g(x))$. Now let $N_{x} := N'_{x} \cap N''_{x}$. Then for each $z\in N_{x}$ we have $$|(f+g)(z)-(f+g)(x)| = |f(z)-f(x)+g(z)-g(x)|\leq |f(z)-f(x)|+|g(z)-g(x)| < \frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon$$ so that $(f+g)(z)\in B_{\epsilon}((f+g)(x))$. So $f+g$ is continuous.
Claim 2. If $f:X\to\mathbb{R}$ is continuous, then $f^2: X\to\mathbb{R}$ is continuous.
Here $f^2$ is the function defined by $f^2(x):=(f(x))^2$.
Proof. Given a point $x\in X$, let $\epsilon>0$. Let's assume $\epsilon<1$ for simplicity (this is okay to assume). By continuity of $f$, there exists a neighbourhood $N_{x}$ such that $f(N_{x})\subseteq B_{\epsilon}(f(x))$. Note that for every $z\in N_{x}$, we have $$|f(z)+f(x)|=|f(z)-f(x)+2 f(x)| \leq |f(z)-f(x)|+2|f(x)| \leq \epsilon+2|f(x)| < 1+2|f(x)| = C
$$
where $C$ was defined to be that constant $1+2|f(x)|$. Note that $C$ is independent of $z$, and only depends on $x$. Next, for every $z\in N_{x}$, we have
$$|f^2(z)-f^2(x)| = |f(z)-f(x)|\cdot |f(z)+f(x)| \leq \epsilon\cdot C$$
Thus, $f^2(N_{x})\subseteq B_{\epsilon}(f^2(x))$ and $f^2$ is continuous.
Claim 3. If $f:X\to\mathbb{R}$ and $g:X\to\mathbb{R}$ are continuous, then $f\cdot g: X\to\mathbb{R}$ is continuous.
Proof. Notice that
$$
f\cdot g = \frac{1}{2}\left[(f+g)^2 -f^2-g^2\right]
$$
Now apply claim $1$ to see $f+g$ is continuous. So by Claim 2, all three functions $f^2$, $g^2$ and $(f+g)^2$ are continuous. By Claim $1$ again, $f\cdot g$ is continuous (because it is a sum/difference of these functions).
Comment: @TaylorRendon That is a good question. I believe it follows from the fact that we showed $f+g$ is continuous whenever $f$ and $g$ are continuous. Indeed, if $g$ is continuous, then $-g$ is clearly continuous. Thus, $f+(-g) = f-g$ is also continuous.
Comment: By showing that $f+g$ is continuous, do we have to show $f-g$ is continuos? Or does that just come for free when showing $f+g$ is continuous?
Answer: Since the topology in ${\bf{R}}$ is still the standard Euclidean, it is still a matter of proving this in the classical way that $|f(x)g(x)-f(x_{0})g(x_{0})|\leq|f(x)-f(x_{0})||g(x)|+|f(x_{0})||g(x)-g(x_{0})|$. Now the boundedness of $|g(x)|$ around $x_{0}$ is given by the continuity of $g$ at $x_{0}$ as well. Note that one could see that $|x-x_{0}|<\delta$ is replaced by some neighbourhood $\mathcal{N}(x_{0})$, and the matter of $\min\{\delta,\delta'\}$ should be replaced by the intersection of two neighbourhoods.
Answer: First, define the function $h:X \to \mathbb{R}^2$ by $h(x)=(f(x),g(x))$; since $f$ and $g$ are continuous then $h$ is continuous.
Now, the multiplication function $\cdot:\mathbb{R}^2 \to \mathbb{R}$, $(a,b) \mapsto a \cdot b$ is continuous. Finally, since $(fg)(x):=(\cdot \circ h):X \to \mathbb{R}$, and the composition of continuous functions is continuous, then $fg$ is continuous.


If Liverpool FC win the Champions League does that mean Coutinho wins it as well or if FC Barcelona win Champions league will Coutinho win it as well?

Question: I mean anything is possible in football and I was reading an article about how Coutinho can help FCB in terms of attacking football etc.
When I saw

With Coutinho ineligible to play in Europe for Barcelona this season, Balague says Valverde will use the rest of the domestic campaign to get him to speed in central midfield. Alongside Sergio Busquets, Ivan Rakitic and Paulinho, Coutinho will hone the defensive side of his game.

I did some research and found out since Coutinho already played for Liverpool in the UCL he cannot play under Barcelona.
So if Liverpool win Champions League would Coutinho have a Champions League medal under his belt and same with Barcelona or will it be neither and he misses out of Champions League if either team win it??
I mean he did help Liverpool and as far as UEFA are aware he already played for Liverpool and thus cannot play for Barca.
Comment: You can only win titles with the club you play for, even if you're ineligible to play.
Comment: I don't have sources on me, but you are considered the champion for the club you PLAYED on. You can't play in the same season for 2 clubs on Champions league. If you play on X and move to Y, if X wins you are the champion, if Y wins you are not.
Answer: UEFA Champions League regulations include a section on Trophy and medals, which has three subsections. The only part that directly speaks to medals is 11.03, saying that

[t]he  winning  team  is  presented  with  40  gold  medals  and  the  runner-up  with  40 silver medals. Additional medals may not be produced.

There is no restriction on who these medals can be given to or where they might be placed (unlike the replica trophies).
None of the regulations dealing with registration of players under VII Player Registration) then prevent a player who joined a club but was not registered or fielded in a match from being given one of the medals.
In the absence of any further restriction or requirement from UEFA, it appears the decision of awarding medals to individuals is left to the winning or runner-up club.
Comment: This doesn't address the question though. One thing is being given the medal, the other is given the accolade of champion.
Comment: The title is not the question, it is a reference for finding the question only. Since this answers at least one question made in the question body, it does answer the question. Please make a valid criticism or write your own answer.
Comment: Unless clubs are going to hand them out to people with no associations to the winning club, they're the same thing.
Comment: You can give a Medal to the doctor who fixed your star player's leg in half the time it usually would take, at 90'+1, and that player scored the freekick that gave you the win. It doesn't mean that the doctor is the Champion
Comment: Given that the question asks about medals in particular, I do not see any validity in the criticism.
Comment: Question title does not. And two questions are made on the body
Answer: There are two stages for UEFA Champions League: the group stage, and the knockout stage. Before each of these stages teams have to submit their team members list to UEFA.
In case of Coutinho, he played for Liverpool in group stage and he is going to play in Barcelona in knockout stage of the league. Every team in the knockout stage has to submit their new players list to UEFA after this January transfer window. Coutinho won't be listed in the player list that will be submitted by Liverpool and will be included in FC Barcelona squad for knockout stage. So there is no problem in that he can play the rest of matches for FC Barcelona in UEFA.
Currently he is a FC Barcelona player. It doesn't matter where he was at group stage, or in which team's list he was included earlier. It only matters where he plays while the team wins the league. So in this season if FC Barcelona wins the UEFA Champions league he also wins it.
Comment: This is not true as one player cannot play for two different teams on Champions League the same season. Coutinho cannot play (nor be registered) for Barcelona this season. In fact, you can check for yourself at uefa.com


How to finish $(x+2y)dx-xdy=0$?

Question: I am a bit confused, should be really easy but one step:
$$(x+2y)dx-xdy =0\tag{1}$$
substitute:
$$y = tx$$
derivative:
$$dy =xdt+tdx$$
substitute everything in $(1)$ I got:
$$(x+2tx)dx - x(xdt+tdx)=0$$
Pulling $x$ out:
$$(1+2t)dx = (xdt+tdx)$$
And that is where I'm stuck...
Comment: Separate the variables as:$\frac{dx}{x}=\frac{dt}{1+t}$
Answer: $$(1+2t)dx=(xdt+tdx)\Rightarrow(1+t)dx=xdt$$
$$\Rightarrow\int\frac 1xdx=\int\frac 1{1+t}dt+C$$
$$\Rightarrow \ln |x|=\ln |1+t|+C\Rightarrow |x|=|1+t|e^C \\\ \\\Rightarrow x^2=c|x+y|$$
Comment: You had $(1+2t)dx=xdt+tdx$ so $[(1+2t)dx=xdt+tdx]\~-tdx\implies (1+2t)dx-tdx=xdt\implies (1+2t-t)dx=xdt\implies (1+t)dx=xdt$
Comment: @Holo, so it means we just group parts with the same differentials?
Comment: @d.sci yes, just rearrange the variables to a form we can solve. In this case is grouping up everything with $dx$ on one side and everything with $dt$ on the other
Answer: If we assume $x\neq 0$ then we can rewrite the equation to
$$(x+2y)dx−xdy=0 \implies (x+2y)=x\dfrac{dy}{dx}$$
$$\implies \dfrac{dy}{dx} = 1+2y/x$$
Now substitute $y(x)=xz(x) \implies \dfrac{dy}{dx} = z(x) + x\dfrac{dz}{dx} = 1 + 2(xz)/x$
$$\implies z + x\dfrac{dz}{dx}=1+2z$$
$$\implies \dfrac{dz}{dx}=\dfrac{1+z}{x}$$
$$\implies \dfrac{dz}{1+z} = \dfrac{dx}{x}$$
The last equation can be integrated
$$\ln(1+z(x)) - \ln(1+z(x_0))=\ln x - \ln x_0=\ln\dfrac{x}{x_0}$$
$$1+z(x) = (1+z(x_0))\dfrac{x}{x_0}$$
Resubstitution with $z(x)=y(x)/x$ and solving for $y(x)$ will yield the solution.

How to finish $(x+2y)dx-xdy=0$?


Can I setup an email server to receive emails faster

Question: I'm subscribed to a web service that sends periodic email mailouts.
My task is to get these with the lowest possible delivery latency.
What can I do to minimize latency? And what is a realistic expectation for achievable latency? Is it in the order of milliseconds or seconds?
Supposing I were to set up my own email-server near to the server of the sender... what could I do to minimize latency?
e.g. Can I infer the platform of the outgoing mail-server and if so, can I make use of that information?
Comment: @didjomi very strange. I think decent (even old) mail software uses hash tables or even RDBMS to store email addresses, and the lookup therefore must be even for any of them.
Comment: Well, even the Question is Offtopic (Providing Learning Materials), it is not possible to change the send order - you may try to "cheat" with the mail address by creating aaaa000000_yourname@somewhere because some mail software sort the senders. my old mail list software i was using had this "feature"  some others just dump in the order they entered the emails. However, you did not Provide what hoster you using.
Comment: I've tidied up the question, so that it lies (I trust) within community guidelines. I am free to choose my own mail server technology, but I'm not sure how to figure out what tech the sender is using.
Answer: you could increase the "TCP Window-Size"-Parameter (the "receive Window", "Scaling factor") of the operating system running your mail-server.
Doing that, the sender - if it accepts that which isn't unlikely today - could send larger chunks of TCP-Data without the need to get the correct reception acknowledged by the receiver.
This doesn't reduce the end-to-end Latency, of course - but it reduces the amount of times this latency is taken into account.
Answer:
What can I do to minimize latency?

You can't do anything. You have no access to, nor control of, the sending system nor any of the intermediate systems that the email may flow through. Geographic proximity is unrelated to the speed of the email transmission at the application layer.

And what is a realistic expectation for achievable latency?

You should have no expectation as to achievable latency. SMTP is a "best effort" protocol and to my knowledge none of the SMTP related RFC's specify or designate anything related to ultimate deliverability or the speed thereof.
Answer: You don't have control over what happens at the sender side in their infrastructure, but you can attempt to subscribe with several different mailboxes and domains to see if email addresses are processed alphabetically by mailbox and/or mail domain or for example in order of an ID number that reflects on their sign-up date.
Do a-mail@a-example and a-mail@z-example receive the message before z-mail@a-example and z-mail@z-example ?
Then you can game the system at the sender side because they send out their email messages by ordering the mailboxes alphabetically.
Do a-mail@a-example and z-mail@a-example receive the message before a-mail@z-example and z-mail@z-example ?
Then you can game the system at the sender side because they send out their email messages by ordering the mailboxes alphabetically by domain name.
For my own mail servers, the most delays incoming mail messages incur before they arrive in my mailbox are due to anti-spam and anti-virus measures.
It is up to you and the capabilities of your mail server is you and want to disable those for that particular sender and/or recipient.
Normally the delays start with the reverse DNS lookup of the IP-address the sender is using by the incoming mail server. - You can avoid/minimise that by hard coding the senders IP-address in for example a hosts file.
Maybe your anti-spam and anti-virus solutions feature an exemption list of trusted senders and/or recipients for which you can disable them.


Overiding homepage template problem. "page__front.tpl.php" won't be loaded

Question: I am trying to overriding the homepage by creating a template file named "page__front.tpl.php"; I placed it under the theme folder where page.tpl.php lives.
After refreshing the site, the homepage still loads "page.tpl.php" instead of "page__front.tpl.php."
The cache and the theme registry are cleared.
Answer: The template filename should be "page--front.tpl.php"; you should use hyphens, not underscores.


how to create the caps for udpsrc element in gstreamer?

Question: I want to be run the audio pipeline using udpsrc element. I am going to set the caps (capabilities) of udpsrc
for example gst-launch-0.10 -vvv udpsrc multicast-iface=eth0 uri=udp://188.8.131.52:25012 caps="application/x-rtp, media=(string)audio, payload=(int)96,clock-rate=(int)16000, encoding-name=(string)MPEG4-GENERIC,streamtype=(string)5,profile-level-id=(string)15,mode=(string)AAC-hbr,config=(string)1408,sizelength=(string)13, indexlength=(string)3,indexdeltalength=(string)3"  to set this caps in program i using
g_object_set(G_OBJECT(Source),"caps",gst_caps_new_simple ("application/x-rtp",
                    "media", G_TYPE_STRING, "audio",
                    "payload",G_TYPE_INT,96,
                    "clock-rate", G_TYPE_INT, 16000,
                    "encoding-name", G_TYPE_STRING,"MPEG4-GENERIC",
                    "streamtype",G_TYPE_STRING,"5",
                    "profile-level-id", G_TYPE_STRING,"15",
                    "mode",G_TYPE_STRING,"AAC-hbr",
                    "config",G_TYPE_STRING,"1408",
                    "sizelength",G_TYPE_STRING,"13",
                    "indexlength",G_TYPE_STRING,"3"
                    "indexdeltalength",G_TYPE_STRING,"3",
                    NULL),NULL);

But it shows a segmentation fault so please tell me as soon as possible what to do?.....
Answer: The code look okay (although you leak the caps). To fix the leak do:
GstCaps *caps = gst_caps_new_simple( ....);
g_object_set(source, "caps", caps, NULL);
gst_caps_unref(caps);

To figure out why it segfaults run the app under gdb:
G_DEBUG="fatal_warnings" gdb --args ./my-app <args>

Inside gdb "run" and when it crashed type "bt" to show the backtrace.


blocking ip on linux(CENTOS)

Question: I m blocking an ip from my centos server using iptables:

iptables -A INPUT -s $ip -j DROP
service iptables save

however my ip is still able to access the ip and even view websites hosted on this ip.
what's wrong?
Answer: You'll have to block the outgoing traffic to this ip address not the other-way around.
Use the OUTPUT keyword and the -d flag like this:
iptables -A OUTPUT -d $ip -j DROP

Comment: You'll also need to use the `-d` flag to specify the IP as destination, not source.  And of course you may run afoul of the fact that order is important in `iptables` rules, and slapping one on the end of a chain doesn't guarantee it'll ever do anything at all.

blocking ip on linux(CENTOS)


MongoDB data schema performance

Question: I am trying to understand the internal allocation and placement of arrays and hashes (which, from my understanding are implemented through arrays) in MongoDB documents.
In our domain we have documents with anywhere between thousands and hundreds of thousands of key-value pairs in logical groupings up to 5-6 levels deeps (think nested hashes).
We represent the nesting in the keys with a dot, e.g., x.y.z, which upon insertion into MongoDB will automatically become something like:
{
    "_id" : "whatever",
    "x" : {
        "y" : {
            "z" : 5
        }
    }
}

The most common operation is incrementing a value, which we do with an atomic $inc, usually 1000+ values at a time with a single update command. New keys are added over time but not frequently, say, 100 times/day.
It occurred to me that an alternative representation would be to not use dots in names but some other delimiter and create a flat document, e.g.,
{
    "_id" : "whatever",
    "x-y-z" : 5
}

Given the number of key-value pairs and the usage pattern in terms of $inc updates and new key insertion, I am looking for guidance on the trade-offs between the two approaches in terms of:

space overhead on disk
performance of $inc updates
performance of new key inserts
Answer: The on-disk storage of documents in MongoDB is in BSON format.  There is a detailed description of the BSON format here:
 - http://bsonspec.org/#/specification
While there is some disk savings from using short key names (since, as you can see by looking at the spec, the key name is embedded in the document), it looks to me like there'd be almost no net difference between the two designs in terms of on-disk space used -- the extra bytes you use by using the delimiters (-) get bought back by not having to have string terminators for the separate key values.
$inc updates should take almost identical times with both formats, since they're both going to be in-memory operations.  Any improvements in in-memory update time are going to be the tiniest of rounding errors compared to the time taken to read the document off of disk.
The performance of new key inserts should also be virtually identical.  If adding the new key/value pair leaves the new document small enough to fit in the old location on disk, then all that happens is the in-memory version is updated and a journal entry gets written.  Eventually, the in-memory version will be written to disk.
New key inserts are more problematic if the document grows beyond the space previously allocated for it.  In that case, the server must move the document to a new location and update all indexes pointing to that document.  This is generally a slower operation, and should be avoided However, the schema changes that you're discussing shouldn't affect the frequency of document movement.  Again, I think this is a wash.
My suggestion would be to use the schema that most lends itself to developer productivity.  If you're having performance problems, then you can ask separate questions about how you can either scale your system or improve performance, or both.
Comment: Reading the BSON spec it looks like arrays and documents cannot have any padding for future use. Do you read it the same way? This seems a bit strange: to add a single key in a 100K doc they may need to modify many blocks on disk as up to 100K of data may need to be moved by a few bytes.
Comment: Since most applications are read-heavy, the design of MongoDB is read-optimized.  In terms of I/O, it's faster to read a document if the entire document is in one contiguous location on the disk: the design of MongoDB reflects this.  The price of this is slightly higher I/O requirements when performing only those writes which grow the document.  This design seems to work well in practice.  CF Amdhal's Law and Donald Knuth on premature optimization
Comment: You're right about the spec.  MongoDB can allocate additional space for the document (a padding factor) above what the spec allows:  http://www.mongodb.org/display/DOCS/Padding+Factor  In addition, you can use a manual padding factor when you initially create the document: http://www.mongodb.org/display/DOCS/Padding+Factor#PaddingFactor-ManualPadding
Comment: In MongoDB, when a document outgrows its slot, only that document is moved: the documents around it are left untouched.  When a document is moved, it is moved into a new record which is big enough to hold it's new size (plus any padding factor).  The extra I/O comes from re-indexing,  not from moving other documents.
Comment: So it is as a feared... My comment was not about moving documents but modifying blocks on disk. In my case, documents occupy many blocks on disk. With a BSON encoding format that has no internal padding, when a document changes you may have to update all blocks on disk. That's pretty expensive from an I/O standpoint. A slightly better approach would be to come up with an encoding format that can be tuned to the block size on the storage device and that can add padding occasionally to minimize the likelihood of multi-block updates, e.g., when an array element is removed via $pull.
Comment: You get an up vote for channeling grandpa Knuth. In my case, there is nothing premature, though. These updates are the slowest part of the system and they consume a big portion of the time. Also, whether there is padding or not *within* the document encoding as opposed to just at the end is a completely separate issue from whether the document is stored contiguously on disk. Your point is about eliminating random disk access. My point was about potentially unnecessary block updates on disk. That's apples & oranges.
Comment: If you have a performance problem, I invite you to post a separate SO question about that problem, so that we can diagnose the cause and propose a remedy.  Slow performance is usually handled by good schema design, query optimization, or system tuning.

MongoDB data schema performance


Verificar extensões de arquivos em Python

Question: Preciso verificar as extensões de todos os arquivos dentro de uma pasta, por exemplo:
Pasta:
    arquivo1.txt
    arquivo2.wav
    arquivo3.mp3
    arquivo4.mp3
    arquivo5.mp3
    arquivo6.txt

output:
txt, wav, mp3

alguém sabe como eu posso fazer para verificar a extensão destes arquivos? A lógica em si eu sei fazer, só preciso de um exemplo de como rodar a pasta pegando as extensões
Answer: Pode utilizar a biblioteca pathlib para percorrer o diretório e obter o sufixo de cada arquivo:
from pathlib import Path

path = Path('Pasta')

for filename in path.glob('*'):
    print(filename.suffix)

Veja funcionando no Repl.it
A saída deste código para o exemplo dado seria:
.mp3
.mp3
.txt
.mp3
.txt
.wav

Para gerar um conjunto com os sufixos existentes, bastaria fazer:
suffixes = {filepath.suffix[1:] for filepath in path.glob('*')}

Assim suffixes seria {'mp3', 'wav', 'txt'}
Comment: @ÉderGarcia Nem sei o que está falando :D hahah valeu.
Comment: Erro de digitação em: path = Pach('Pasta')
Answer: Você pode fazer com o pathlib.
Este código retorna o path dos arquivos no local especificado.
import pathlib

path = list(pathlib.Path(".").glob("*"))

for nome_arquivo in path:

    print(nome_arquivo)

Comment: Não lembrava  do "suffix" que o Anderson utilizou na resposta dele. Vivendo e aprendendo!
Answer: Uma outra forma seria usar os.path.splitext(), é uma função específica com a finalidade de separar uma extensão do nome do arquivo.
import os
for nome_arquivo in os.listdir(path):
    nome, extensao = os.path.splitext(nome_arquivo)
    print(extensao)

ou de forma mais resumida:
extensoes = {os.path.splitext(nomearq)[1]
    for nomearq in os.listdir(path)}

Answer: Não sei se isso ajudará alguém mais usei um módulo da biblioteca "os" chamado listdir que lista itens de um diretório de trabalho atual por padrão, mais se passar por parâmetro ele listará o diretório que foi passado, usei também uma estrtutura de repetição "for" que é execelente para mostrar itens de uma lista,e fatiei
com um manipulador de string rfind(x) que localiza o que for passado por parâmetro entre aspas, ele localizar em dados do tipo string.
from os import listdir
for x in listdir('Diretório'):
    print(x[x.rfind('.'):])


jQuery scroll não funciona no chrome no retroceder para página anterior

Question: Eu tenho este código que funciona bem (basta um scroll para baixo) no firefox e no chrome , mas se a seguir carregar no 'retroceder' do navegador (chrome) ele faz trigger logo no load da página sem eu fazer scroll.
No Html tenho:
`<body onunload="">...`

js.js
$(document).ready(function() {

window.scrollTo(0, 0); // ir logo para topo no load da pagina para evitar
                       // que faça trigger à animação sem eu fazer scroll

.......

$(window).scroll(function() {
        if ($(window).scrollTop() > 10){
            var href = $('.toWork').attr('href');
            $('#wrapper').animate({
                "margin-top": "-1000px"
            }, 800, function(){
                window.location=href;
            });
        }
    });
})

Answer: Este comportamento depende do browser e da versão do jQuery que você está utilizando (1.4 e superiores funcionam diferente de versões mais antigas).
Houve uma discussão sobre isso a um tempo atrás no StackOVerflow, não sei se o workaround deles servirá para você, pois a resposta é muito antiga, mas por via das dúvidas, verifique se você está usando a última versão do jQuery.
Comment: Tenho, 1.11.1. Não existe uma maneira de, com código, dar a volta a isso? Com base no código que postei
Answer: Provavelmente você deve estar tentando carregar o jQuery a partir do Google no link:
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"

Isso faz com que o Chrome não execute o script de uma página não segura em uma página segura.
Quando tive esse problema mudei de http para https e rodou normal.
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"