How should I write a SATB piece in Musescore with respect to its voice soundfont?

Question: I'm currently writing a vocal piece for a high school SATB chorus in Musescore. Throughout the composition process, I've been using the Musescore playback, which presents all voice syllables in a Choir Ooh soundfont. This is my first time writing a(n) SATB peice.

How am I supposed to know whether the layers of lyrics will make sense with the harmony? Or how the piece is influenced by the gender of voices? Are those even pertinent questions?
What am I missing in terms of composition by referring the soundfont?

Is it recommended that I regularly ask the choir to learn and recite their current parts to test playback? If so, how regularly?
Answer: It depends.
One of the best pieces of advice for writing music in Musescore or any other score editor is to compose with pencil and paper first, sitting at the piano if you have one. Computers are great tools for typesetting music, but don't always help with the actual process of composing. As Brian says, playback is a nice sanity check but if you rely on it you won't learn to hear the parts in your head. That said, some composers never leave their DAW so ymmv.
Whether the interplay of the lyrics and melody/harmony is important is something only you can answer. There's a long and august choral tradition of setting any old (usually religious) text to music without considering the words at all, but equally there are composers and songwriters who think very carefully about how both the sound and meaning of words and syllables fit with the melody, and how the words sung by different voices weave in with each other. Whether different syllables work better with different harmonies, or whether different sequences of syllables work better with different chord progressions, is something only you (and your ears) can decide.
By relying on a soundfont you are mainly missing out on a) the actual sound of the human voice and b) the consonants. There's a lot of auditory information in the consonants, for example plosives and sibilants are very different. If you really want to get into detail, vowels will sound different (and be easier/harder to produce) when you get to the higher notes. I would think primarily of the pitch of singers' voices rather than their gender myself, but countertenors definitely don't sound like altos. Again, only you can decide whether that matters.
You also miss out on the limits of your singers' ranges, their tessiture, and their lung capacity. Real singers like to breathe every now and again, and will thank you for bearing this in mind.
The good news is that the soundfont in your head takes all this into account, or at least you can train it to with practice and experience.
In general I would try to avoid giving a choir new parts too often, though it depends on the choir and your relationship with them. If you want to actively involve the group as collaborators in the composing process it can be fun and productive but it does change the dynamic between you, and tends to work better with smaller groups.
Remember no two choirs are the same. Think about what your choir are able to sing well, and also what they enjoy singing. Composing for a community choir has a very different set of constraints than composing for a professional chorus. A high school choir would be somewhere between the two, but depending on the high school it could be nearer one than the other.
Answer: "Are those even pertinent questions?" I think the answer is no. Think about how songs get translated from one language to another -- yesterday I found myself supposed to be singing "Time to say goodbye", or "Con te partiro" as it said on the orchestral scores. (They were lucky; we didn't even get a score - "Sing the melody on 'ah'"!) No-one thinks about changing the harmony because Italian has different vowels from English, let alone that the words are completely different.
I think you could be relying too much on the playback, but this would mean that you are not hearing the harmony in your head before you write it down; the playback is a very useful check, but that should be all. You should also be able to check you are getting the effect you imagined by playing through on a keyboard. I also think you have to be prepared for something not being as effective as intended, and you might want to revise parts of the piece. To that end, much better than getting the choir to learn the parts would be to find the best 4 (or more) singers who can more or less sight-sing, and run through with them (and listen to their feedback). Hope this helps.
Comment: "Think about how songs get translated from one language to another" Generally quite badly ;)
Comment: What is important about hearing the harmony in my head? I can recall thinking of a chord, but being unable to spell it, therefore unable to use it. Beyond that, what makes it more necessary?
Answer: First, I'd suggest the choral 'ooh' sounds are probably the LEAST useful sounds for previewing what a harmony will sound like!  Unless you're scoring a 1940's Disney cartoon, substitute wind instrument sounds.
You're missing the point that, although computer sounds give a very useful preview of what your music will sound like, it IS only a preview.  You and your 'inner ear' still have to take ultimate responsibility for writing singable parts that give the required effect.  Make sure YOU can sight-sing each part, both in terms of endurance and 'finding the note'.  Know each voice's limits of range, and stay away from them for the bulk of the music.  Identify with the singers - I guess you've sung yourself?  If not, join a choir, NOW!
You'll get some surprises when you start doing this.  Some things just won't work - discard them.  Some will work, but with a surprising effect!
Beware of one thing.  Particularly with amateur choirs, the way they first learn a piece will be what you get - despite you handing out revised parts!


How to make content translation available for front page?

Question: On my front page I have a language selector (English / French). The default language is French. The translation works only in the content of page (in the views) i want make the translation work in the front page.
Can someone help me please to do this? I have tried several times but could not get it to work ...
Answer: The relative URL to display as the front page is specified within admin/config/system/site-information . If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.
Refer to the community documentation about Variable translation for details about how to translate text and settings that are stored in Drupal as variables. Here is a quote from that page:

The Variable translation module, part of the Internationalization (i18n) package, allows you to translate text and settings that are stored in Drupal as variables. These variables include text such as 'site name' and 'site slogan', as well as settings like 'Default front page' and 'Default 404 page'.

The Variable translation module has a dependency on the Variable module.
And these are the specific steps required to make a variable multilangual (mentioned on that community page):

Enable the Variable translation module included with the Internationalization package
Go to Administration > Configuration > Regional and language > Multilingual settings
Click on the Variables tab
Select the variables that will be multilingual
Click Save configuration button

Obviously, in this case in step 4 the variable to be selected is "Default front frontpage", within "Site information".
Finally, this is what remains to be done (another quote from that same page):

Once you have the correct settings, they'll be marked with "This is a multilingual variable" when you go to the corresponding administration pages (Figure 2). You must switch the site language while in the administration pages to set the variables for each language. A language switcher link will appear at the top of each administrative page that has multilingual variables.

"That's all" what's needed to specify a language specific value for the frontpage of your site ...


jquery working in jsfiddle, but not on site

Question: I know people have submitted similar questions, but I've been through the answers as well and not seen a solution that works. I wrote a script that sorts my list of portfolio items in jsfiddle. It looks something like this:
 $(document).ready(function(){

    $( ".music-button" ).click(function() {
      $('.project-thumb-inside').not('.music').addClass('hidden').removeClass('visible');
      $('.music').addClass('visible').removeClass('hidden');
    });

 )};

On jsfiddle, the script works, but when I plug it into my site's footer, it does not do a thing. Would anyone know why?
I've put everything (stylesheet and all) into jsfiddle, and my site works: http://jsfiddle.net/LbgPF/2/
But when I go to my actual website, my script does not work: http://www.rileydra.com/00_dra/work/branding-and-identity/
I've spent quite a bit of time on this but still think the solution is something simple that I'm overlooking.
Edit: changed the script excerpt to better show the error of my ways.
Comment: It's never a good sign when you have multiple functions that perform the same action for different elements, you should be able to abstract it using a common class for your elements, also next time some javascript is not working look at your browser's console, all errors are logged there, right now you're getting `Uncaught TypeError: Property '$' of object [object Object] is not a function` which you can fix with @Arun's answer
Comment: Good, one more thing, you should add `e.preventDefault()` in your function to prevent the default action when clicking the anchor links because right now it scrolls the page to the top
Comment: I see exactly the same results in jsfiddle and on the site linked.
Comment: I just noticed that error in firebug. And I did initially have it as just one function, but thought that might be what's causing the problem. Now that you got things working, it's going to go back as a single expression.
Comment: Ha. Dear lord, that was exactly was I was looking up how to do. Thank you so much.
Answer: You have used noConflict in your page, so $ does not point to jQuery. so instead of using $ in your script you need to use jQuery.
Change the script in sort.js to
//here the shortcut version of dom ready is used, also the jQuery instance is passed as a parameter to the callback function which we assigns to a local parameter $, so we can use $ to refer jQuery inside the callback method
jQuery(function($){

    $( ".technology-button" ).click(function() {
        $('.project-thumb-inside').not('.technology').addClass('hidden').removeClass('visible');
        $('.technology').addClass('visible').removeClass('hidden');
    });

    $( ".retail-button" ).click(function() {
        $('.project-thumb-inside').not('.retail').addClass('hidden').removeClass('visible');
        $('.retail').addClass('visible').removeClass('hidden');
    });

    $( ".real-estate" ).click(function() {
        $('.project-thumb-inside').not('.real-estate').addClass('hidden').removeClass('visible');
        $('.real-estate').addClass('visible').removeClass('hidden');
    });

    $( ".publishing-button" ).click(function() {
        $('.project-thumb-inside').not('.publishing').addClass('hidden').removeClass('visible');
        $('.food').addClass('visible').removeClass('hidden');
    });

    $( ".music-button" ).click(function() {
        $('.project-thumb-inside').not('.music').addClass('hidden').removeClass('visible');
        $('.music').addClass('visible').removeClass('hidden');
    });

    $( ".churches-button" ).click(function() {
        $('.project-thumb-inside').not('.churches').addClass('hidden').removeClass('visible');
        $('.churches').addClass('visible').removeClass('hidden');
    });

    $( ".health-button" ).click(function() {
        $('.project-thumb-inside').not('.health').addClass('hidden').removeClass('visible');
        $('.health').addClass('visible').removeClass('hidden');
    });

    $( ".food-button" ).click(function() {
        $('.project-thumb-inside').not('.food').addClass('hidden').removeClass('visible');
        $('.food').addClass('visible').removeClass('hidden');
    });

    $( ".finance-button" ).click(function() {
        $('.project-thumb-inside').not('.finance').addClass('hidden').removeClass('visible');
        $('.finance').addClass('visible').removeClass('hidden');
    });

    $( ".entertainment-button" ).click(function() {
        $('.project-thumb-inside').not('.entertainment').addClass('hidden').removeClass('visible');
        $('.entertainment').addClass('visible').removeClass('hidden');
    });

    $( ".education-button" ).click(function() {
        $('.project-thumb-inside').not('.education').addClass('hidden').removeClass('visible');
        $('.education').addClass('visible').removeClass('hidden');
    });

    $( ".all-button" ).click(function() {
        $('.project-thumb-inside').addClass('visible');
        $('.project-thumb-inside').removeClass('hidden');
    });

});

Comment: I could kiss you right now. Thank you. This solved it for me.


Simple string replacement in views output?

Question: In Drupal 7, for a view where I wanted to replace every instance of 'am' with 'a.m.' (with a similar replacement for pm/p.m.) in the output, I did this:
function mymodule_views_post_render(&$view, &$output, &$cache) {
  if ($view->name == 'target_view') {
    $replace_pairs = array(
      ' am ' => ' a.m. ',
      ' pm ' => ' p.m. ',
    );
    $output = strtr($output, $replace_pairs);
  }
}

How do I achieve the same result in Drupal 8? The documentation for the D8 version of hook_views_post_render() is broken/incomplete, but it does mention strtr(), so I imagine something similar should work.
I've already figured out that my if statement will need to test against $view-storage->id() instead, and I've noticed that $output is an array (rather than a string) in D8, but I'm not seeing anything appropriate to target in that array. I am new to D8; can someone show me the way?
Answer: In your custom module, create module_name.views.inc file and add following code.
<?php
use \Drupal\views\ViewExecutable;
use \Drupal\views\Plugin\views\cache\CachePluginBase;

function custom_module_views_post_render(ViewExecutable $view, &$output, CachePluginBase $cache) {
  if ($view->id() == 'VIEW_NAME') {
    $html = \Drupal::service('renderer')->renderRoot($output['#rows']);
    $replace_pairs = array(
      ' am ' => ' a.m. ',
      ' pm ' => ' p.m. ',
    );
    $html =  strtr($html, $replace_pairs);

    $output['#rows'] = $html;
  }
}

Replace VIEW_NAME with your view name and clear drupal cache.
Comment: Nice trick, normally you should use renderRoot() only for responses in a controller. If you use it in other places like here you have to extract the cache data and add it to $output. Otherwise nodes or what is listed in the view won't get refreshed when modified in the database (this depends on the configuration of the view, not all views will be affected).
Comment: Note that this hook can be invoked from within a custom theme (instead of a module) if that makes more sense for the modifications that are being made and that there is no requirement for it to be placed in _module_name.views.inc_, though that may be the best practice.


Uma tabela de telefone para cada cliente ou uma só para todos clientes?

Question: Atualmente na faculdade aprendemos assim:
Tem uma entidade cliente, esse cliente tem seus atributos e um deles é o telefone, quero que seja possível o cadastro de vários telefones, criamos uma só tabela, nela vai ter o id do cliente e o telefone, assim podemos cadastrar vários telefones com o mesmo id do cliente.
Não fica mais pesado pra fazer a pesquisa dos telefones de um só cliente? Vai ficar tudo junto os telefones dos clientes em uma só tabela.
Nas empresas fazem desse jeito? Ou cada cliente terá uma tabela própria na hora que um novo é cadastrado?
Comment: Sua pergunta recebe a resposta mais genérica que exite (rs), DEPENDE DE CADA CASO. Quando você fala "Nas empresas" depende de cada empresa, não dá para comparar uma estrutura de armazenamento como a do Google por exemplo com a estrutura da lojinha do bairro (exemplo extremo eu sei). Em resumo para mim um join entre cliente e telefone (se bem indexado) é mais factível (contanto que esteja dentro da necessidade do projeto)
Comment: estuda sobre modelagem de dados no banco, vai te esclarecer todas essas duvidas
Answer: Se existisse uma regra única já teria tudo pronto e não precisaria ninguém mais pra fazer. As empresas não pagam programadores para fazer o que já está feito. Programadores são pagos para criar a melhor solução para aquele problema específico, o problema dela, que atende todos os requisitos, e geralmente o desenvolvedor é que deve achar esses requisitos, inclusive os que nem o usuário sabe. Por isso não importa o que alguém já fez, ou se muitos o fazem assim.
O que costuma ser certo é ter vários telefones na própria tabela do cliente. Simples assim, e rápido. Raro ver um motivo para que os telefones sejam cadastrados em outra tabela, e se acha que deve fazer isso deve achar uma boa justificativa. Tabela extra sempre custa mais caro e deve-se evitar até que traga um benefício compensador. Seu caso tem um benefício assim?
Mas se separar não vejo problema algum em fazer como está pensando. Se você vê, deveria justificar. Se fizer certo não é lento.
E se está dizendo que cada cliente deve ter uma tabela só pra cadastrar esses telefones, a resposta é um definitivo não. Se tiver 1 milhão de clientes você vai criar 1 milhão de tabelas só pra os telefones? Isto não faz sentido e provavelmente esbarrará em um problema técnico além de ficar inadministrável.
Coloquei no GitHub para referência futura.
Comment: Não se fizer certo.
Comment: Obrigado pela resposta, o exemplo do telefone foi bem básico, me surgiu essa dúvida porque parece demorado pesquisar uma tabela inteira para achar os itens só daquele id do cliente dentre possivelmente milhares.
Answer: O cenário que está colocando deve ser pensado em relação ao SGBD (Sistema Gerenciador de Banco de Dados) que irá utilizar, mais especificamente, o modelo de SGBD.
Vou considerar dois modelos: Relacional (como PostgreSQL) e Orientado a Documentos (como MongoDB).
Modelos Relacionais
Em modelos relacionais, o padrão de boas práticas e modelagem está embasado na Normalização de dados, onde uma das formas normais descreve a necessidade de as propriedades de entidades (campos de uma tabela), não serem multivalorados.
Desta maneira, para resolver, usando o cenário que você citou, um cliente com vários telefones, o ideal é sim criar uma tabela Cliente e uma tabela Telefone onde cada cliente terá n telefones e cada telefone pertencerá a 1 cliente, fazendo o relacionamento por chave primária do cliente (id do cliente) ser adicionada como campo de chave estrangeira na tabela de telefones.
Sua dúvida quanto à performance, veja, SGBDs relacionais foram criados para lidar com altos volumes de dados e resolver da forma mais performática possível os relacionamentos entre tabelas. Tecnicamente a solução simples é criar índices para a chave estrangeira, o que permite à engine executar planos inteligentes nos momentos de consultas.
Portanto como exemplo teríamos o modelo a seguir:

Modelos Orientados a Documentos
Estão dentre uma categoria mais ampla definida como Modelos Não Relacionais ou NoSQL, especificamente os Orientados a Documentos permitem a modelagem de dados de um documento inteiro como um registro em uma coleção (nome dado às tabelas).
MongoDB por exemplo armazena um documento no formato BSon (Binary Json) e permite, na verdade na maioria dos casos, orienta, a "desnormalização" de dados, isto é, no caso específico de campos multivalorados, eles são bem-vindos.
Veja, como os bancos relacionais, estes também são projetados para lidar com altos volumes de dados, mas em geral, por minimizarem a necessidade de resolver relacionamento (joins) entre várias tabelas, a performance em muitos casos é maior pois todos os dados estão armazenados juntos.
Por exemplo para Cliente e telefones, o modelo poderia ser com o campo Telefones armazenando um array:
Cliente {
   nome: "João",
   cpf: "00000000000",
   telefones: ["42-9999-9999", "41-0000-9999"]
}

Cuidado com a modelagem
Por fim, concordo com @maniero quando é enfático quanto à usar uma tabela ou coleção de telefone para cada cliente, isto sim seria totalmente fora de contexto, pois teria de criar tabelas por exemplo: Telefone_1, Telefone_2, Telefone_X, uma para cada cliente, inviável do ponto de vista técnico prático, e totalmente fora de qualquer orientação de boa prática e literatura tanto na modelagem de dados Relacionais como NoSQL.


Minimizing a function of a complex variable

Question:
Given complex numbers $z_1,z_2,z_3,\ldots,z_n \in \mathbb{C}.$ Does
  there exist a $z \in \mathbb{C}$, for which the function  $$f(z) =
 \sum_{j=1}^n |z-z_j|$$ achieves a global minimum? If yes, then find
  $z$.

Not sure how to approach this problem. Any advice?
Comment: I'm not convince this should really be called a problem on complex numbers, as opposed to mere points in the plane.  The difference is the way in which complex numbers are multiplied.
Comment: This is not really a complex analysis question, since you only use properties of vectors in $\mathbb{R}^2$.  Is this homework?
Comment: $f$ is continuous. Hence it attains a minimum on every nonempty compact subset of $\mathbb{C}$. What other property of $f$ then guarantees the existence of a global minimum?
Comment: I think I once solved the problem of finding the minimum value of the sum when $n=3$, by hand.  It's doable but moderately onerous. ${}\qquad{}$
Answer: This is equivalent to the geometric median problem in $\mathbb{R}^2$. That is: for each $z_j$, define
$$\bar{z}_j \triangleq \begin{bmatrix} \Re z_j \\ \Im z_j \end{bmatrix}$$
Then the geometric median is the solution of
$$\bar{z}=\arg\min \sum_{i=1}^n \|z-\bar{z}_j\|_2.$$
To recover your answer, $z=\bar{z}_1+j\bar{z}_2$. Note that if we were minimizing the sum of squared distances/magnitudes, the simple mean $z=n^{-1}\sum_j z_j$ would be the answer.
According to this article, when the points are not collinear, the geometric median is unique. When all of the points lie on a straight line, the minimum is achieved at any one-dimensional median, which may not be unique.
There is no closed-form solution for arbitrary $n$. However, it's a simple convex optimization problem, so a variety of approaches can be applied to it. For example, with my Matlab toolbox CVX it can be expressed thusly, assuming the complex values $z_j$ are stored in the vector z_in:
cvx_begin
    variable z complex
    minimize(sum(abs(z-z_in))
cvx_end

CVX effectively makes use of the $\mathbb{R}^2$ mapping above, and converts the model to a second-order cone program (SOCP). The equivalent
SOCP standard form is
$$\begin{array}{ll}
\text{minimize} & \textstyle \sum_j y_j \\
\text{subject to} & \| \bar{z} - \bar{z}_j \| \leq y_j, ~ j=1,2,\dots,n
\end{array}$$
where the variables are $\bar{z}\in\mathbb{R}^2$ and $\bar{y}\in\mathbb{R}^n$ and
the values $\bar{z}_j$ are defined above. There are plenty of solvers out there that can handle SOCP, so there's no need to use CVX if you don't want to.
Wikipedia describes Weiszfeld's algorithm, and claims it converges almost always. Expressed in this complex form, we have
$$z^{(i+1)} = \frac{ \sum_j z_j / | z_j - z^{(i)} | }{ \sum_j 1 / | z_j - z^{(i)} |}$$
The article claims that difficulties arise if the initial iterate (or presumably any others) coincides exactly with one of the points. It seems to me that the geometric mean would be a good initial point in practice, save this one caution.
Comment: There are plenty of references in the Wikipedia article; consider studying them. I've edited my post to link to one making the collinearity claim above.
Comment: Also, this: http://math.stackexchange.com/questions/881144/is-the-non-existence-of-a-general-quintic-formula-related-to-the-impossibility-o Looks I was wrong about $n>3$; there is a formula for $n=4$, but not $n\geq 5$.
Comment: Thanks for the LaTeX tune-up @Michael Hardy!
Comment: Im not really familiar with convex optimization - I was hoping we could perhaps derive a closed form for $z$ in terms of the $z_j$'s ? Also I noticed that for n=3 $z$ is the Fermat-Point - well that seems to be a special case of the Geometric Median concept - which you have pointed out. Also, can a given set of points in Euclidean Space have more than 1 geometric medians ?
Comment: "There is no closed form solution for arbitrary n>3" - Is there a formal argument for this ? Wikipedia states " it has been shown that no explicit formula, nor an exact algorithm involving only arithmetic operations and kth roots can exist in general." - but without references .


In SSRS how can I change 1 type of border style without affecting the others when multiple cells with different styles are selected

Question: Here's my problem. In a SSRS 2008 Tablix I have a block of cells that have different border styles already set (eg the top cell has a solid border on top, the bottom cell has a solid border on the bottom and all the others nothing). When selecting a group of cells, as soon as one of the cells has a different value for a parameter, the parameter value goes blank.
That's usually not a problem, but in the case of multi-value parameters (eg. size, location, borders) the different values cannot be expanded by pressing the + sign.
https://i.stack.imgur.com/rXJ7D.png
vs
https://i.stack.imgur.com/mP9RP.png
So, if I want to change a value I have to enter all the values separated by commas on the "header" of that property. By doing that I am forced to set values for all of the sub-values, even though I want to change just one of them. I tried leaving the values as blank hoping it would keep the current value but it does not seem to work.
Anyone knows how to achieve this? I hope this makes sense.
Answer: It looks like bug in Report Designer (or Report Builder)
Answer: You could try downloading the report as an RDL file and edit it directly in a text editor.
Then re-upload it when you're done.


How to deal with module conflicts ("anti-dependencies")?

Question: I have a module that specifically doesn't work with another module. I want to know if there is a way to check if that module is enabled and abort installation for example or gray out the installation box so that my module can only be installed if that other module is disabled.
It's like inverse dependencies!
Is there any way of doing this properly in Drupal?
Answer: The module just needs to implement hook_requirements(); a requirement could be that a module is not installed, and if the module returnes an error from hook_requirements(), then it will not be installed.
The module should implement code similar to the following one:
function mymodule_requirements($phase) {
  $requirements = array();
  // Ensure translations don't break at install time
  $t = get_t();

  if ($phase == 'install') {
    if (module_exists('other_module')) {
      $requirements['mymodule'] = array(
        'title' => $t('My module'),
        'value' => $t('My module is not compatible with Other module.'),
        'severity' => REQUIREMENT_ERROR,
      );
    }
  }

  return $requirements;
}

Answer: You can use hook_requirements for this. You specifically need to check for $phase == 'install', and then return the proper array containing REQUIREMENT_ERROR.
The Simpletest module for Drupal 6 has a good example of aborting installation if certain conditions aren't met.


Is Counterpoint always possible?

Question: I've searched for this question online many times, but never found anything close to an answer:
Given a cantus firmus, is it always possible to do counterpoint with it?
The rules don't appear to answer the question with an easy yes, but someone may have written a mathematical/musical paper proving this statement. Does anyone know of a reference?
Later: I am currently working with Peter Westergaard's formulation of counterpoint, so those are the rules I'd be most interested in, with (for the moment) first species, two line counterpoint. If there is a reference to any formulation (Fux, etc.), I'd be interested in that, too.
Comment: I can imagine a simple tenor derived of e.g. where it is hard to write a satisfactory counterpoint of 2 voices (first species) . S. The "primitive" tune of the first phrase *Zion hört die Wächter singen* C-E-G-G-G-G-A-G = triad + changing sixth. But what Bach has written to this tune has become one of the most famous c.p.
Answer: There is some mathematical analysis about the subject. There were a few cantus fermi that could be proved not to have a satisfactory counterpoint. Generally, most melodies do admit of some type of counterpoint.
Comment: "Proved"? How on Earth can you they formally define "satisfactoriness"?
Comment: In the paper, they looked at whether one could avoid all parallels  and poor melodic skips. It's not that one cannot write a counterpoint that sounds good; one cannot write a counterpoint that doesn't violate certain (arbitrary) constraints.
Comment: After I posted my original question, I realized that I'd left this unclear. Currently, I am working with Peter Westergaard's formulation, so I could specify using that to formulate 1st-species 2-line counterpoint.
Answer: I think this question can only be answered if you know not only the constraints on species counterpoint (as the OP clarified to Westergaard's formulation), but also the constraints on what constitutes a "proper" cantus firmus.
Westergaard (I'm assuming we're talking about his tonal theory book) is working with a set of rules of species counterpoint that are designed to introduce tonal theory.  Thus, there are a lot of unwritten assumed constraints on his first-species counterpoint that are basically laying the groundwork for coherent harmonic progressions (as Fux does as well).  If you literally read only the rules he officially states for first species, and you assume a cantus firmus that doesn't wildly violate basic tenets for melody or bass line he has elsewhere laid out, I don't see how you could possibly fail to have a possible counterpoint line.  In some cases, it may not be very musical and might not incorporate the tonal characteristics he seems to be aiming for, but in terms of strict adherence to his species constraints, I don't see how you could generate a cantus firmus that follows his melodic principles and wouldn't have a counterpoint solution.  (Westergaard's constraints are a lot more lax than many authors.)
For an example of what I mean by "unmusical," one could simply imagine a cantus firmus ending with a stereotypical octave leap down, then fourth up for a cadence, but then insisting on creating a counterpoint below that CF.  The result would sound absurd, but I don't think it would technically violate Westergaard's explicit constraints on first species.  It would certainly violate the spirit and intent behind his method, though.
Introducing further constraints would lessen the chances of producing something unmusical but still "acceptable" to the explicit rules, but if you did so, then the reasonable constraints on a "valid" cantus firmus should probably be tightened up too, resulting in little chance of a CF with no solution.
This latter idea has been thoroughly investigated by computer programs modeling solutions since the 1950s.  (A brief summary of that history, with some useful sources at the end, can be found here.)  One of the most useful articles that I recall reading on this topic is David Lewin's "An Interesting Global Rule for Species Counterpoint" (In Theory Only 6/8, March 1983).  Lewin's "global rule" produces more generally "musical" solutions for a given CF, but it does place heavy constraints on solutions.  In general there, one needs to work backwards from the final cadence, which is the most constrained and trickiest part.  Again, I think Lewin mostly presupposes a "reasonable" cantus firmus that doesn't violate general late Renaissance melodic principles.  But, for example, if you tried to combine Lewin's rules with some of Westergaard's more "tonal" cantus firmi, and then insisted on doing something silly like using Westergaard's bass-line-like cantus firmus as the top melody, then of course you couldn't find a viable solution.  But in that case, Westergaard's CF would violate Lewin's melodic principles to begin with, so I'm not sure that's a valid test.
So, in general, I'd say even with severely constrained species rules, as long as the cantus firmus is "reasonable" (and following the same severe constraints in its own generation), counterpoint solutions are probably available.  However, to speak of mathematical proof would require a more formal statement of the rules.  While the rules for generating counterpoint are usually fairly explicit in many species methods, the rules for creating a "valid" cantus firmus are often not stated as explicitly, making this question impossible to answer for many cases.
Comment: I've sung some actual renaissance pieces where the tenors did the octave-down-fourth-up figure while the basses sang a descending scale.  Surprising, but not actually absurd.  I don't know what Amy later theorist would have made of it, however.
Comment: @phoog - Sure.  I know precisely the kind of cadences you're talking about, which were even more common in the 1400s, and often involved voice-crossing. I doubt those moments you mention were only two-voice first-species, though.  Were they?  Following Westergaard's rules, assuming tenor line G-G-C, you'd need a bass line something like C(12th below)-E-C, which is an absurd way to end a 2-voice cadence (either tonally or in Renaissance style).  Obviously there are lots of things you can get away with contrapuntally with more voices and other rhythms.
Comment: Correction on previous comment: "Amy" should be "any."  There was no voice crossing of the bass and the tenor, but I'm sure the tenor was crossing other voices, because, as you correctly surmise, this was not two-voice counterpoint.  And, come to think of it, the last tenor interval might have been an ascending fifth (so an octave leap from a 10th above the bass to a 3rd above the bass, then jumping up a 5th as the bass descends a 2nd).  I wish I could remember what piece it was; I just remember being struck by how bass-like the tenor line was.
Answer:
Given a cantus firmus, is it always possible to do counterpoint with it?

By the time we get to Handel, he says yes, even if his countersubjects are often mostly rests.
We'd have to move this question to mathoverflow to find someone dogged enough to find a counterexample, a c.f. so pathological that counterpoint would be impossible.
You may have to qualify what kind of canti firmi you consider relevant.
Comment: And mathoverflow would refer me back here. 8-) I've developed an interest in algorithmic music composition recently, and a lot of what I read/work on falls between the cracks.
Answer: I can imagine a tenor derived from e.g. an early invocation that doesn't fit to a note-to-note c.p. But such practices are historical nonsense: trying to apply the rules of Fux to music that was not "written" for polyphony.
Because:
First step to train the rules of Fux would be to compose a good c,f.
The aim of studying c.p.  must be to overcome the speciesc and break out of the rules of Fux.

Is Counterpoint always possible?


How to share Apache2 virtual host configuration between two linux servers?

Question: What is the best option to share configuration directives between Apache2 servers. This is required in order to employ stable load balancing. The most important directives are those that define the virtual hosts.
Any kind of help is much appreciated.
Comment: Google "configuration management" and consider one of the tools, particularly Ansible.
Answer: We define one host as the "master", also (as per most distributions these days) the virtual host configuration is kept in a folder /etc/apache2/vhost.d/ and allocated a file per virtualhost.
e.g.
www.example.com.conf
customers.example.com.conf
suppliers.example.com.conf
... and so on..

Then a cron'd rsync that copies from the "master" to the other servers.
Answer: There are a number of ways to solve this:

put the config on centralized storage, for example NFS or CIFS.
use a versioning system (git, svn, etc) to store the configurations and check them out on the webservers
sync configuration from one server to the other using rsync or scp

You could consider combining the 2nd option with some provisioning tool like Puppet or CFengine so that Apache will be reloaded when the central configuration changes.
Answer: I use a unified configuration for our development, staging, and production servers.  Most of the configuration is the same for all of them.  Where they're different, I put the differences either into virtual host definitions, or in <IfDefine> sections, for example:
<IfDefine DEVELOPMENT>
...
</IfDefine>

Each server starts with a command-line switch that tells which server it is.  For example, on the development server I put
export APACHE_ARGUMENTS="-DDEVELOPMENT"

into /etc/apache2/envvars (that's for Debian - for RedHat you'd put OPTIONS='-DDEVELOPMENT' into /etc/sysconfig/httpd).  So besides its virtual hosts, the development server has all of the configuration within the <IfDefine DEVELOPMENT> sections.
When the configuration changes, I commit the changes to version control, usually in development, and push them to the other hosts.


prove that BEDF is cyclic

Question:
In triangle $ABC$, points $D$ and $E$ are chosen on side $CA$ with $AB=AD$ and $BE=EC$ ($E$ lying between $A$ and $D$). Let $F$ be the midpoint of the arc $BC$ of the circumcircle of ABC. Show that $BEDF$ is cyclic.

Note that if $I$ is the incenter of triangle $ABC,$ then $\angle BIC = 90 + \angle A/2$ (since $\angle BIC = 180 - \angle IBC - \angle ICB = 180-(\angle B + \angle C)/2 = 90 + \angle A/2$). Also, since $AD = AB, \angle ADB = 90-\angle A/2$ and $\angle BDC = 90 + \angle A/2$. So $BIDC$ is cyclic. It also seems like $BICF$ is cyclic, but I'm not sure how to prove this.
Comment: could you include a picture that shows what you are talking about?
Comment: We need $AB<AC$ for $E$ to be between $A,D$.
Answer: This is really quite easy, no drawing the incenter fancy stuff. It's sufficient to show that $\angle BDA=\angle BFE$. Because $\triangle BDA$ is isosceles, $\angle BDA=90-\angle A/2$. Obviously $EF$ is the perpendicular bisector of $BC$, so $\angle BFE=\angle BFC/2=(180-\angle A)/2$. Done. Here's a (bad) diagram (if anyone can make it smaller that would be great):

prove that BEDF is cyclic


Deploying Drupal 7 with read-only DocumentRoot, especially concerning image handling

Question: I'm deploying a Drupal 7 application in an environment where the web server's DocumentRoot is mounted read-only (so Drupals root directories and all directories below are not writable). For storing files a separate directory outside of DocumentRoot is provided which is mounted read/write. This directory is accessible from a separate web server instance (which only serves static files without executing PHP code, e.g. static.example.com).
What I did:

setting file_public_path to said writabke directory
implementing hook_file_url_alter to modify URIs in the public scheme to point to the separate web server instance

Everything seems to work fine (CSS, ...), except for delivering images. Drupal's concept for delivering images is whenever a requested image resolution isn't found on disk, the thumbnailing mechanism is invoked instead. The thumbnailer creates a new image, which is delivered to the requesting browser and stored below sites/default/files. Subsequent requests deliver the image directly from the disk (using Apache's rewrite rules, so PHP isn't involved any more).
Since we are using varnish in front of the web server, I'd prefer a different way of handling images:

images are served from a different virtual host (e.g. image.example.com)
thumbnailed images are never written to disk
instead a Cache-Control header is sent using a reasonable long max-age value, so varnish's LRU expiration mechanism can keep the often used images in memory and discard unused images

Any ideas how to accomplish this?
Comment: It would require some serious work yes, but I wouldn't call it hacking as this can be done from a custom module without modifying any Drupal core files. However I would call hacking accomplishing anything but pure presentation (ie. HTML, CSS and JavaScript to alter them) in a theme's files.
Comment: Sounds like something impossible without some serious hacking. I prefer other way around - configure all paths so that images are always served from `/sites/*/files/images` and then mount a share from image.example.com to that directories. The rest is minor and can be accomplished at theming level, for example.
Answer: When an generated image is not available, the page callback is image_style_deliver(). This callback first generate the image (after some access and concurrency checks) and then stream the file as response (through the file_transfer() function).
Using hook_menu_alter(), you can override the image generation callback to redirect to the static domain once the image has been generated. Ensuring the generated files are always served from the static domain. On the static server, you can add a rewrite rule to redirect request for a not yet generated image to the non-static domain. Ensuring the files are generated, even when requested from the static domain. Because of the redirections, Varnish should be able to cache the files as soon as they have been generated.
Edit: Not creating the image derivatives as files on disk does not seems to be an option. Drupal uses its Image Toolkits wrapper API (GD and ImageMagik are usually used a backend) to generate the image and this API does not seems to offer a way to generate images in memory. If you really want/need to remove the generated files, you can do it in a cron job using image_style_flush() via hook_cron().
Comment: hook_outbound_url_alter() may be an option for forcing the images to use the static domain.
Answer: A response of sorts:

1.~images are served from a different virtual host (e.g.
  image.example.com)

You can use NFS to mount Drupal's sites/default/files directory to an images.example.com document root, or perhaps an equivalent network directory mount method for your OS.

2.~thumbnailed images are never written to disk

I don't know if that is possible in Drupal, maybe you can override the file stream wrapper handler, so that relevant file operations are handled differently.

3.~instead a Cache-Control header is sent using a reasonable long max-age
  value, so varnish's LRU expiration mechanism can keep the often used
  images in memory and discard unused images

The virtual definition host for images.example.com can set the relevant response headers for Varnish to cache those images.


can ABC notate multiple chords over a single held note?

Question: In ABC notation, is there a way to notate a long held note with multiple guitar chords?
The naive approach

"F" "D7" "F#dim" C8- |

produces this, which isn't right

The obvious approach of splitting up the long note

"F" C4- "D7" C2- "F#dim" C2- |

produces this, which is ok, but I thought I'd ask to see if there's anything closer to printed sheet music, which would just show a whole note, and the chords space out to suggest the second two are on the last two beats of the measure.
Comment: The use of dashes is common. F - D7F#o for a full bar. Problem with that is some use '-' (dash) as a sign meaning minor: G- means Gm. Or a slash (/) meaning play the same cchord again. F/D7F#o. But that's confusing too... By the way, the blue areas are - simply blue!
Answer: ABC allows for chord symbols to be attached to "extra space" in the score.

6.1.2 Typesetting extra space
y can be used to add extra space between the surrounding notes; moreover, chord symbols and decorations can be attached to it, to separate them from notes.
...
Note that the y symbol does not create rests in the music. (ABC 2.2 spec)

The code looks like this:

"F" (C8 y "D7" yy "Fdim7" y | C)

And generates this output:
<code>X:
K:
L: 1/8
T:Multiple chords against single note
"F" (C8 y "D7" yy "Fdim7" y | C)
</code>
Answer: You can separate the chord from the rhythm of the melody with different voices. Whether you should use completely separate voices or a voice overlay will depend on the complexity of the parts.

With separate voices:
(see the Manual: 3.1.1 Voices and Systems, 3.1.2 Positioning Voices)

X: 1
M: 4/4
K: C
L: 1/4
%%score (1 2)
[V:1]
%%MIDI gchord c2cc
"F"x2 "D7"x "F#dim"x | \
%%MIDI gchord z
x4 :|]
[V:2]
[L: 1/4]
C4- | C/ z/ z z2 :|]

With a voice overlay:
(see 3.1.4 Voice Overlay)

X: 1
M: 4/4
K: C
L: 1/4
C4- & \
%%MIDI gchord c2cc
"F"x2 "D7"x "F#dim"x | \
C/ z/ z z2 & \
%%MIDI gchord z
x4 :|]
Comment: I tried these at https://www.abcjs.net/abcjs-editor.html and get strange-looking results. The former places the rests at the bottom of the staff (to accommodate the invisible second voice), and the latter aligns the chords a bit off and the tie goes to the end of the (second) measure rather than the second C.
Comment: @Aaron Yeah, I don't know what is going on with ABC. Your example threw an error on my editor and didn't compile at all, and my examples apparently don't work with ABCjs. Something problem with the versioning I guess ... Agh.  My examples seem to follow the manual I've been looking at, and work fine on my machine.
Comment: When you tried my code, did you add in the various tags I omitted? (X, M, ...)
Comment: @Aaron Oh, ha ha. I was copy-pasting the code that was rendering above, i.e. with `X:`,`K:` blank.  When I fill these in i.e. `X: 1`,`K: C`, it does compile without error, and looks right, But the chord changes don't make it to the midi file (even when I add `%%MIDI gchord c2cc`).
Comment: One mystery solved. :-) I don't know about the MIDI part, though.


How to export Group module entities with the Features module?

Question: I'm trying to find a way in D7 to export groups created with the Group module using the Features module. I have managed to export Group Types and Group Roles, but haven't found a way of doing the same with Groups.
I need to do this to create an initial set of groups when the feature is enabled.
Any help greatly appreciated!
Answer: Have a look at the UUID Features Integration module, which provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. It depends on the UUID and Features module. Some more info aboout this module(from its Community documentation):

Drupal's core entities are supported by default within the UUID module, but if you want to export content contained within custom entities, you will have to implement UUID support using their API.

The challenge with the UUID Features Integration module is that its documentation is not complete (yet). So for adding UUID Features support for custom content entities (such as Groups), refer to the module's includes/ folder and use one of the existing implementations as an example.
2 more documentation issues that may be of some help also:

Issue # 2310115.
Issue # 2236497.


Html Tags in notification.alert Phonegap

Question: I have a alert in phonegap using notification.alert. It is working fine. What i want now is how can i give HTML content in its message. Something like this
navigator.notification.alert(
     "Call the Help Desk for assistance at: 1(800)309-0136",
      function() { },
     "Having trouble signing in?"
);

So that when the user clicks on the telephone number i can call that number. I tried above code it simply displays the  tags as text. Please help.
Answer: I don't think you can use html in the notification alert body.
Instead you could use navigator.notification.confirm to make the call. Like this:
function onConfirm(button) {
    if(button == 'Call') {
        document.location.href = 'tel:1(800)309-0136';  //make the call
    }
}

navigator.notification.confirm(
    'Having trouble signing in?',                                            //title
    'Do you want to call the Help Desk for assistance at 1(800)309-0136?',   //message
     onConfirm,                                                              //callback
    'Call,Exit'                                                              //buttonNames
);

Comment: Thank you So much @DZL... I have implemented the workaround as you mentioned.


Relationship between node and other nodes related by node reference to same parent

Question: I've been stuck on this all day and I need help.
I have a video node that has a relationship (node reference) with a playlist node.
There are multiple videos referencing that playlist and there are multiple playlists.
Now here is my issue...
I have my node that plays my video and a view that lists all other videos in the same playlist to the bottom of the node. The views display plugin i'm using is EVA: Entity Views Attachment. This works apart form the fact I don't know now to filter it to only show a list of videos that are in the same playlist (referencing the same playlist node). I am able to get the ID or tokens (eg: field_video_playlist) from the video node and pass as an argument but when I setup contextual filter and relationships in the EVA view it returns nothing.
Without the contextual filter and relationship in the view it returns ALL videos.
Any help with this would be very much appreciated.
C
Comment: Have you tried to add a value (`nid` for example) to that contextual filter manually ? If yes and it didn't work it's more possible that something is wrong with your query,ie your contextual filters or relationships.
Answer: Start with a view that lists Content of type video.
In the ENTITY CONTENT SETTINGS use:
Entity type: Node
Bundles: Video
Arguments: Use the ID of the entity the view is attached to.

This adds the EVA field to all nodes of type Video and provide the node id to Views. I suppose you have gotten about this far.
Now add a contextual filter to the View, and choose the Content: nid. This value will be populated by EVA as just specified in the arguments. This makes the view aware of the node we are currently viewing. If you want to hide the current node from the playlist, you can select exclude hidden behind the more fieldgroup.
Then add a relationships from the playlist back to the video called Entity Reference: Referencing entity.
This includes all other video nodes associated with the same playlist in the view.

As you can see in my preview, when I view Video 1 (node id 2 because 1 was for the playlist), I see the other 2 videos in the playlist (I chose to hide the current node in the contextual filter).
If you DO want to include the current video in the view (you left exclude unchecked) it becomes a bit more complicated as you will need to use an extra relation: Entity Reference: Referenced entity. Then alter the other reference to use the reference of this one (you might have to change the order).
Then make sure all your fields and filter make use of the last relationship, so they display the title of the attached nodes and not the title of the initial node. It should look something like this:
Comment: I had a spare moment. It was actually less complicated than I rememberred. More detailed description and screenshot attached.
Comment: Probably at the start. You should create a view of content (nodes). Just start over. Since you are using node reference, you should use those equivalent relations instead. (I assumed you used the entity reference module.) Just create one relation from video node to the playlist node, and a reversed one from the playlist back to the video.
Comment: Thanks @Neograph734 - I'm still struggling with this. Any chance you can expand on your instructions. I must be doing something wrong.
Comment: @cybercampbell Can you update the question with one or more screenshots of the Views configuration? It is kinda hard to guess what part you missed ;)
Comment: I tried loads of variation but took them out. Right now showing all is better than showing none as the site is live. I just not clear on a few of the instructions. Are points 1 & 2 instructions or comments on what to do?
Comment: Those are instructions on the references you have to add.
Comment: for the playlist field, what do I set for the Formatter? to I set the relationship? if yes to what? I think this is where I get confused.
Comment: Ok.. I'll add everything again and upload screenshot. Thanks, I appreciate the help.
Comment: The formatter does not really matter, we will not display the values (you can safely exclude them from display). We'll use the database value for filtering. One should be without relation. The other should be with the second relation (reverse entity relation from playlist to video).
Comment: From the `ENTITY CONTENT SETTINGS` what am I passing as arguments?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/39732/discussion-between-cybercampbell-and-neograph734).
Comment: I cannot chat right now. I will be able to provide further assistance in a few hours. Update your question with a screenshot and I will get back to you with a more detailed answer.
Comment: I don't see Entity Reference in the list and I don't have Node and an option under Entity Type. Where did I go wrong?
Comment: Tried and still no luck. Please see private message.


Puppet apt site.pp h

Question: New to puppet, so probably something simple. Cannot understand why the below manifest does not work.
When run on an agent I get the following error:
Could not parse for environment production: Syntax error at '='; expected '}' at /etc/puppet/manifests/site.pp:14
node 'linuxlab' {

include apt

apt::unattended_upgrades {
  origins             = $::apt::params::origins,
  update              = '1',
  download            = '1',
  upgrade             = '1',
  autoclean           = '7',
}

}

Answer: You don't use = to pass parameters to a class.
=> is used for that.
= is used to assign values to variables.
So that code should be changed to:
node 'linuxlab' {

  include apt

  apt::unattended_upgrades {
    origins             => $::apt::params::origins,
    update              => '1',
    download            => '1',
    upgrade             => '1',
    autoclean           => '7',
  }
}

Puppet apt site.pp h


Interpreting the logarithm as a sum of simple poles along the negative real axis

Question: I've heard it remarked that you can basically consider $\log z$ to be a function which has simple poles everywhere on the negative real axis (with a constant "residue density" at each pole).  This would be something like
$$ \log z = \int_0^\infty \frac{dx}{z + x} $$
But of course the integral on the right-hand side actually diverges.  We actually get
$$ \int_0^\infty \frac{dx}{z + x} = \lim_{b \to \infty} \int_0^b \frac{dx}{z + x} = \lim_{b \to \infty} \left( \log(z + b) - \log(z) \right) = \infty $$
In physics, there are a variety of methods for subtracting out the divergent part of such a limit to get a finite answer (various flavors of regularization and renormalization).  I'm wondering whether there is a standard approach here so that something similar can be done to "rescue" the first equation above from the divergent part of the integral.
Another way of phrasing the problem above is that I showed that the Stieltjes transform of a constant on the interval $(-\infty, 0]$ does not exist.  But perhaps there is another density function $\rho$ so that $\log z$ is the Stieltjes transform of $\rho$.
$$ \log z = \int_0^\infty \frac{\rho(x)}{z + x} dx $$
What is $\rho$?  Well, the Stieltjes inversion formula says that it should be given by
$$ \begin{align} \rho(x) &= \lim_{\epsilon \to 0} \frac{\log(x+i\epsilon) - \log(x-i\epsilon)}{2\pi i} \\ &= \frac{(\log |x| + \pi i) - (\log |x| - \pi i)}{2\pi i} \\ &= 1 \end{align} $$
But this gets me exactly back to the integral that I started with, which is divergent!  Hopefully I am just missing something obvious.
Edit: Alternate statement of question
There has been a lot of confusion in the comments below about what I am looking for, so let me restate it in a very narrow way.  I would be satisfied with either of the following:

A sequence of meromorphic functions $f_n(z)$ with simple poles along the negative real axis with the following properties:
a. The poles become dense in the limit $n \to \infty$.
b. $\lim_{n \to \infty} f_n(z) = \log z$

A proof that there is no such sequence.
Comment: $\log z = \int_0^\infty (\frac{1}{z + x}-\frac1{1+x}) dx$ and those are not poles. This integral says that $\log z$ on $\Bbb{C}-(-\infty,0]$ is a limit of a sequence of meromorphic functions with poles on the negetive axis. Compare with the Cauchy integral formula.
Comment: Sure, I understand that they are not actual poles. It is the limit of a sequence of functions with denser and denser (but more lightly weighted) poles. But the question is where we can justify this interpretation in such a way that the integral makes sense. Your integral does not come with a justification.
Comment: I missed a minus sign. You meant the derivation of my integral, right?
Comment: No, I'm not asking for a proof of the equality. I'm asking what the *interpretation* is here. I can interpret my first equation as "Take the limit of $\lim_{\Delta \to 0} \sum_{k=0}^{\infty} \frac{\Delta}{z+ k\Delta}$.  Isn't it neat that you get a logarithm?"  (Except that you don't.)  This is an interpretation of a logarithm that is different than the standard one and sounds interesting. My question is an attempt to find such an interpretation that actually works.
Comment: Also, I am hoping that an answer will explain what I'm doing wrong with the Stieltjes transform and/or the inversion formula.
Comment: If you're not convinced that this interpretation would be neat, let me give you an example of a neat observation that immediately falls out of it. "Why does the logarithm have a branch cut?" "Well, you can kind of define it that way, i.e., it is basically the sum of simple poles along the negative real axis."

From a conversation I had years ago, I was under the impression that this interpretation was (while not exactly well-known) something that has already appeared in the literature and/or been used as a pedagogical tool.
Comment: @reuns The problem is that I am not looking for a formula. I am looking for a formula with an interpretation. There are a lot of integrals that result in $\log z$, but I'm trying to figure out one that matches the interpretation in the title. If my comments above don't make sense, then I will thank you for your effort and wait for someone who understands the question.
Comment: The problem with your 'continuous set of poles' idea is the Cauchy integral formula.
Comment: Why exactly is that a problem?  You can't do a contour integral through the branch cut because the function isn't defined there.
Answer: The correct formula is
$$\log z = \lim_{T\to \infty} \log(z)-\log(1+\frac{z-1}{T+1})$$ $$=\lim_{T\to \infty} (\log(T+1)-\log(1))-(\log(T+z)-\log(z))$$ $$= \lim_{T\to \infty} \int_0^T (\frac1{1+x}-\frac{1}{z + x}) dx=\int_0^\infty (\frac1{1+x}-\frac{1}{z + x}) dx$$
There is no distribution such that $\log (x+iy) = \frac1{x+iy}\ast \rho$ because this distribution would have to be $C+1_{x>0}$ yielding a divergent integral.
Comment: Your last sentence sounds like you are trying to address the Stieltjes transform part of my question, but I don't see the connection. Are you assuming that you can only use Stieltjes transforms on probability distributions?
Comment: Of https://en.wikipedia.org/wiki/Distribution_(mathematics) probability distributions are a small subset of those
Comment: I know what distributions are. I just don't see why it is a problem to have a distributions which is 1 for all $x>0$.  That is a perfectly good distribution.
Comment: Yes but the convolution of $1_{x>0}$ with $1/(x+iy)$ doesn't converge.
Comment: Ok. So I'm pretty sure your last sentence is exactly equivalent to what I showed in the question.
Comment: So, my overall interpretation of this answer is as follows. We can rearrange this to $\frac{\log z}{z -1} = \int \frac{1}{(1+x)(z+x)} dx$. This shows that $\frac{\log z}{z -1}$ is the Stieltjes transform of $\frac{1}{1+x}$. This looks correct but doesn't really answer my question.
Comment: Again I don't understand your comments. $\log z =\int_0^\infty (\frac1{1+x}-\frac{1}{z + x}) dx$ is the regularized  Stieltjes transform you asked for. What do you want more ? And the inverse transform assumes some regularity conditions.
Comment: Regularization requires an interpretation to show that you have not modified the original problem.  (There are many examples of this in physics, but I am not sure whether you would be familiar with any of them.)  One common approach is to set up another problem with an extra parameter (say, $\alpha$) that becomes equivalent to the original problem under a certain limit (say, $\alpha \to 0$).  The regularization succeeds if this limit produces a finite answer.  If you instead just take some arbitrary action to get rid of the infinity, then you have probably modified the original problem.
Comment: I think that I will just make the question extremely specific.  This is more specific than I would like to be, but I think it will help you understand.
Answer: By fiddling around with my original suggestion above, I have one solution that meets my criteria:
$$ f_n(z) = - \sum_{k=0}^{n} \frac{1}{n\frac{z}{1-z} + k} $$
This has poles at $z=-\frac{k}{n-k}$ for $0 \le k < n$ which becomes dense on the negative real axis as $n \to \infty$.
If we let $a=\frac{nz}{1-z}$, then
$$ f_n(z) = \psi(a) - \psi(a+n+1) $$
where $\psi$ is the digamma function.  As $n \to \infty$, $a \to \infty$, and the leading asymptotic behavior of $\psi(z)$ is $\log z$ as $z \to \infty$.  So we get
$$ f_n(z) \sim \log\left( \frac{a}{a+n+1} \right) \sim \log\left( \frac{1}{1 + \frac{1-z}{z} + 0} \right) = \log z $$
This works in a technical sense, but it seems more complex than it needs to be.  I would accept any answer which is more elegant, especially if it can be expressed in a Stieltjes-transform-like form.


Drupal Webform Customization

Question: I'm using drupal 7, and I'm having a lot of trouble using the webforms.
I have a set of radio buttons, but each radio button needs to have an associated input field with it.
Code example:
<code><input type="radio" name="derp" /> option 1 : option 1 quantity desired: <input type="number" />
</code>
Note that this would span multiple rows, and is just to show the "layout" I am trying to achieve.
How can I add a "set" of input elements to a webforms radio select field?
Optional to answer but extra question: when I try to inject javascript into the webform using the markup option, my code is simply printed out onto the screen instead of being interpreted. Anybody know why?
Comment: Maybe you should try to use the form api in drupal.
Answer: You'll have to create your own webform component to ensure that validation and saving work as you intend. Look at an exisiting webform component to see how its done.

Drupal Webform Customization


How to add CSS to Google Chart's Table without entering a value

Question: I have a Google Chart Table that is already populated with Data. I just want to add in colours for each column.
Right now I have:
dataTable.setCell(1,1,{'style': 'background-color: red;'})
But this breaks the chart.
Thank you.
Answer: dataTable.setCell is used for setting a lot of things, I would instead use dataTable.setProperty.
data.setProperty(1,1,'style','background-color:red') gives you the desired effect, and don't forget that you need to allowHTML in your options with options = {allowHtml:true};
Link to JSfiddle where you can see how.


How to find the PDF for Y=|X-1|?

Question: Given $X\sim N(0,1)$ and $Y=|X-1|$. Find the PDF of $Y$.
I tried to discussed when $x>1$ and $x\le1$, but this gives me two different functions and I have no idea how to combine them.
However, when I tried to use the CDF method, i.e.find the CDF of $Y$, I got $F_Y (y)=\int_{1-y}^{1+y}f_X(x)$ where $f_X(x)$ is the PDF of $X$. Then I got stuck on solving the integral.
Comment: You can in general avoid the integration by differentiating under the integral sign.
Answer: Observe that \begin{align} F_Y(y)&=P(|X-1|\leq y)\\&=P(1-y\leq X\leq1+y)\\&=F_X(y+1)-F_X(1-y).\end{align}
Differentiate both sides using the chain rule to get the result.

How to find the PDF for Y=|X-1|?


Problema com Mascara Moeda e calculo

Question: Tenho uma função que é chamada aqui:
 $("#valorPrimeiroPedido").focusout(function () {
        var valor = $("#valorPrimeiroPedido").val();
        calcularValorMercadoria(valor);
    });

$("#valorPrimeiroPedido").val() já me traz o valor formatado (ex:R$:1.500,56). Quando perde o foco ele chama a função abaixo, passando o valor formatado. Ai está o erro. Não consigo calcular o IPI e mostrar no HTML.
 function calcularValorMercadoria(valor) {

            var _valorPedido = CurrencyFormat(valor);
            var _valorPedidoComIPI = _valorPedido * 1.1;

            console.log(_valorPedido);
            $("#ipi").html("Valor do pedido com IPI: R$ " + CurrencyFormat(_valorPedidoComIPI));
        }

Erro: Uncaught ReferenceError: *CurrencyFormat is not defined*.

Quando eu tiro a mascara CurrencyFormat, o valor retornado é: R$ NaN
Estou usando algumas bibliotecas:

<link href="~/Areas/Representantes/Script/cliente/ClienteEstilo.css" rel="stylesheet" />

Resumo: Eu preciso pegar o valor no formato Real, calcular o IPI e mostrar o calculo também no formato Real e depois salvar no formato float (no SQL).
Comment: É preciso usar o `replace` para remover o `R$` e substituir a vírgula pelo ponto.
Answer: É necessário remover alguns caracteres como letras e vírgulas para poder realizar cálculos no JavaScript.
Como você está usando a biblioteca jquery.maskMoney.min.js, basta utilizar a evento unmask. Este evento irá retornar os valore sem os caracteres supracitados, por exemplo:
'R$ 1.234,56' => 1234.56

Dessa forma, o JavaScript irá conseguir converter para um valor númerico e assim poderá realizar o cálculo.
Exemplo comentado:

/* Aplica a máscara no campo */
$(function() {
  $('#valorPrimeiroPedido').maskMoney({
    prefix: 'R$ ',
    thousands: '.',
    decimal: ','
  });
})

/* Calcula o valor da mercadoria */
$("#valorPrimeiroPedido").focusout(function() {

  /* Captura o valor sem máscara (sem o R$) */
  let valor = $('#valorPrimeiroPedido').maskMoney("unmasked")[0];

  calcularValorMercadoria(valor);
});

/* Função para calcular o valor da mercadoria */
function calcularValorMercadoria(_valorPedido) {
  let _valorPedidoComIPI = _valorPedido * 1.1;

  console.log(_valorPedido);
  $("#ipi").html("Valor do pedido com IPI: R$ " + CurrencyFormat(_valorPedidoComIPI));
}

/* Função para retornar os valores com "máscara" */
function CurrencyFormat(value) {
  return new Number(value).toLocaleString("ptb",{
    style: "currency",
    currency: "BRL"
  })
}

<input type="text" id="valorPrimeiroPedido" />

Sobre o erro abaixo

Uncaught ReferenceError: CurrencyFormat is not defined.

O erro abaixo acontece pois a função CurrencyFormat não foi criada.
Comment: Muito obrigada, é isso mesmo.. funcionou
Comment: estranho, fiz o mesmo código alterando nome de variável e aparece aqui: TypeError: numer01.maskMoney is not a function

Problema com Mascara Moeda e calculo


Study this improper integral $ \int_0^1 \frac{dt}{\sqrt{t}\,\sqrt{1-t}\,\sqrt{1-\alpha\,\sqrt{1-t}}}$

Question: I'm trying to study the behavior of this improper integral
$$ \int_0^1  \frac{dt}{\sqrt{t}\,\sqrt{1-t}\,\sqrt{1-\alpha\,\sqrt{1-t}}}$$
for:$$\alpha>0 $$
While I just can't understand the behavior around $\alpha=1$, inasmuch
 for $\alpha\rightarrow1^- $ seems to converge, while for $\alpha=1$ obviously diverges.
Addition:
Writing the integral as
$$ \begin{equation} \int_0^1  \frac{t^{-\frac{1}{2}}\,(1-t)^{-\frac{1}{2}}}{\sqrt{1-\alpha\,\sqrt{1-t}}}\:dt  \end{equation}\:(*)$$
it is observed that the numerator, and the extremes of integration are similar to Euler Beta function.It is possible to use this similarity to study the convergence or divergence of the integral as function of $\alpha$ ?
Extra Addition:
for $\alpha\rightarrow0$ the integral converges in that:
$$ \int_0^1 {t^{-\frac{1}{2}}\,(1-t)^{-\frac{1}{2}}}dt=\beta(\,\frac{1}{2},\,\frac{1}{2})=\pi$$
This obviously implies that for $\alpha<0$ the integral (*) converges
Answer: Write $t=\sin^2 2\theta$ so your integral is $$\frac{4}{\sqrt{1-\alpha}}\int_0^{\pi/4}\frac{d\theta}{\sqrt{1-\frac{2\alpha}{\alpha-1}\sin^2\theta}}=\frac{4}{\sqrt{1-\alpha}}F\left(\frac{\pi}{4},\,\sqrt{\frac{2\alpha}{\alpha-1}}\right),$$ with $F$ an incomplete elliptic integral of the first kind. Unfortunately the second argument is imaginary, so for convergence interests let's start over. The integral is $$\int_0^{\pi/4}\frac{4d\theta}{\sqrt{1-\alpha\cos 2\theta}}.$$The integrand is bounded for any $\alpha<1$, but for $\alpha=1$ is equal to $$2\sqrt{2}\int_0^{\pi/4}\csc\theta d\theta\ge2\sqrt{2}\int_0^{\pi/4}\theta^{-1} d\theta=\infty.$$
Comment: @Christian For $\theta\in [0,\,\pi/4]$, $\cos 2\theta\in [0,\,1]$ so the integrand has extrema $\{\frac{1}{\sqrt{1-\alpha}},\,1\}$. Multiplying this by $\pi/4$ givies bounds on the integral.
Comment: Of course! sorry it is trivial you're right
Comment: Thank you. I find myself with your steps, but how to prove that the integral is bounded for all alpha<1, especially for theta tending to zero ?


Running a JS function automatically multiple times through jQuery

Question: I am currently adding a feature to a genealogy website I am currently working on which is based on the Webtrees open source software.
So here is where I am at:

So originally, the software allows the user to press the individual node to expand/compress its content. And that works through the following code:
<code>TreeViewHandler.prototype.expandBox = function(j, i) {
    if (jQuery(i.target).hasClass("tv_link")) {
        return !1
    }
    j = jQuery(j, this.treeview);
    var p = j.parent(),
        o = j.attr("abbr"),
        n = this,
        l, k;
    if (p.hasClass("detailsLoaded")) {
        k = p.find(".collapsedContent"), l = p.find(".tv_box:not(.collapsedContent)")
    } else {
        l = j;
        k = j.clone();
        p.append(k.addClass("collapsedContent").css("display", "none"));
        var m = this.loadingImage.find("img").clone().addClass("tv_box_loading").css("display", "block");
        j.prepend(m);
        n.updating = !0;
        n.setLoading();
        j.load(n.ajaxUrl + "getDetails&pid=" + o, function() {
            "function" === typeof CB_Init && CB_Init();
            j.css("width", n.zoom / 100 * n.boxExpandedWidth + "px");
            m.remove();
            p.addClass("detailsLoaded");
            n.setComplete();
            n.updating = !1
        })
    }
    j.hasClass("boxExpanded") ? (l.css("display", "none"), k.css("display", "block"), j.removeClass("boxExpanded")) : (l.css("display", "block"), k.css("display", "none"), l.addClass("boxExpanded"));
    this.getSize();
    return !1
};
</code>
What I'm trying to do is I'm trying to make the button I placed on the top left, which is to expand/compress ALL boxes in one click work. The one in showing/hiding females already work.
<code>$(document).ready(function(){
    var female = false
    $(".tv_hidefemales").click(function(){
        if (female == false) {
            $(".tvF").hide();
            female = true
        } else {
            $(".tvF").show();
            female = false
        }
    });
    $(".tv_expandCompress").click(function(){
        tvHandler.expandBox($(".tv"), 0);
    });
});
</code>
Comment: probably you may have added the same script file multiple times.
Answer: I figured that I can just take advantage of a looping jQuery .click() function.


Exchange 2010 Mail Contacts get assigned internal SMTP addresses by the recipient policy

Question: This environment has been upgraded from Exchange 2007 to a new Exchange 2010 server.
There are several thousand email contacts that reside under the Federation_Contacts OU. Under the Email Addresses tab for each Mail Contact, their correct SMTP address (firstname.lastname@example.com for example) is assigned as Primary. But somehow each one got assigned internal email addresses at our company also (email@example.com and firstname.lastname@example.com)
Now the problem is emails to these contacts bounce back with #550 5.1.1 RESOLVER.ADR.ExRecipNotFound; not found
We have to go and delete the internal SMTP addresses that got erroneously created and uncheck the automatically update addresses based on recipient policy setting.
My question is:
1-How do we mass delete those internal email addresses for these mail contacts, taking care not to affect our internal users?
2-How do we stop Exchange (more precisely i guess, the recipient policy) from creating those internal addresses for new mail contacts?
Answer: I used Powershell to disable updating email address from recipient policy:
Get-MailContact -OrganizationalUnit "domain.local/OU" | set-mailcontact -emailaddresspolicyenabled $false

Then i used ADModify.net to strip off the secondary SMTP addresses assigned to contacts. It worked like a charm.
Answer: Had the same problem (a bit late) so I took your "script" and updated it. You need to disable email address policy to be applied to contacts in Exchange and it will partially solve the problem.
1) Expand Microsoft Exchange On-Premises
2) Expand Organization Configuration
3) Select Hub Transport and go to Email Address Policies Tab
4) Edit each one leaving Users with external e-mail addresses without check box and Contacts with external e-mail addresses.

It will partially solve the problem because the default policy can't be disabled so I ended up having domain.local email addresses by default added to new contacts anyway.
So I wrote a script based on the one provided in question (the one in question had some bugs where multiple addresses from same domain were assigned and it was making a lot of noise) that will remove any email addresses that are not external and it will also make sure the old contacts won't get policies reapplied.
####
# Input variables
####
$domains = @("*@domain.com","*@domain.pl","*@evotec.pl", "*@domain.local")
$ou = "evotec.local"

####
# Removing internal domains from contacts
####
$domains | foreach {
$domain = $_;
write-host "Preparing for removal of addresses with domain name:" $domain
$Contacts = Get-MailContact -OrganizationalUnit $ou -Filter {
                EmailAddresses -like $domain -and name -notlike "ExchangeUM*"
            } -ResultSize unlimited -IgnoreDefaultScope
$Contacts | foreach {
    $contact = $_;
    $email = $contact.emailaddresses;
    #write-host "1. " $contact
    #write-host "2. " $contact.name
    #write-host "3. " $email
    #write-host "4. " $contact.identity
    $email | foreach {
        if ($_.smtpaddress -like $domain)
            {
                $address = $_.smtpaddress;
                write-host "[*] Removing address" $address "from Contact" $contact.name;
                Set-Mailcontact -Identity $contact.identity -EmailAddresses @{Remove=$address};

            }

    }
}
}
####
# Setting up email address policy to disabled for all contacts
####
write-host "Preparing all contacts for disabling email address policy"
$Contacts = Get-MailContact -OrganizationalUnit $ou -Filter {
                EmailAddresses -like $domain -and name -notlike "ExchangeUM*"
            } -ResultSize unlimited -IgnoreDefaultScope | Where {$_.EmailAddressPolicyEnabled  -eq $true}
$Contacts | foreach {
    $contact = $_;
    write-host "[*] Setting up email address policy to disabled for" $contact.name
    $contact | set-mailcontact -emailaddresspolicyenabled $false
    }

The final step is to set it up as Task Scheduler as new contacts will keep on getting the non-editable (in supported way at least) default policy. This setup at Exchange server will run just fine. Make sure to run it with correct permissions.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; C:\ExchangeScript\RemoveLGBSEmailsFromContacts.ps1"
Answer: First of try to identify the policy that might be the one samping these addresses.
You can fine-tune it to be applied to just mailboxes or contacts...
... or create a new one for just contacts.
To clean up the mess powershell is there for you if you need to do bulk changes.
Answer: Get-MailContact | Set-MailContact -EmailAddressPolicyEnabled:$false
This should do the trick for ALL mail contacts!


Neglecting a small part of a square root and then simplifying

Question: I'm trying to verify the following algebraic step from an old textbook, but I'm having trouble getting the same result.
The starting point is here:
\begin{equation}
1 = \frac{\rho_{si}a}{2\epsilon_0} \ln \frac{\frac{\Delta l_i}{2} + \sqrt{a^2 + \left( \frac{\Delta l_i}{2} \right )^2}}{-\frac{\Delta l_i}{2} + \sqrt{a^2 + \left( \frac{\Delta l_i}{2} \right )^2}}
\end{equation}
Here I'm supposed to assume $a << \Delta l_i$. I see two ways to do this immediately:
(1) in the numerator, assume that $\sqrt{a^2 + \left( \frac{\Delta l_i}{2} \right )^2} \approx \sqrt{\left(\frac{\Delta l_i}{2} \right )^2}$
(2) in the denominator, perform a Taylor series expansion of $\sqrt{a^2 + \left( \frac{\Delta l_i}{2} \right )^2}$ and throw out the higher order terms to taste.
Doing this, I get
\begin{equation}
1 = \frac{\rho_{si}a}{2\epsilon_0} \ln \frac{\Delta l_i}{-\frac{\Delta l_i}{2} + \frac{\Delta l_i}{2} + \left(\frac{1}{2}\right) \left(\frac{a^2}{\frac{\Delta l_i}{2}}\right)}
\end{equation}
which simplifies to
\begin{equation}
1 = \frac{\rho_{si}}{2\epsilon_0} \ln \frac{\Delta l_i^2}{a}
\end{equation}
However, the book has
\begin{equation}
1 = \frac{\rho_{si}a}{\epsilon_0} \ln \frac{\Delta l_i}{a}
\end{equation}
in other words, I've come up with one too many $\Delta l_i$ in the numerator. I've checked the Taylor expansion twice now, and also verified that the rest of the chapter uses $\Delta l_i$, not $\Delta l_i^2$ in subsequent steps.
What am I missing? (The book isn't clear on how the simplification was carried out, only that $a$ should be neglected versus $\Delta l_i$.)
Comment: Actually it seems you are missing a factor of 2. In your computation, you had $a^2$ in the denominator, how did that become just $a$? And then, after you fix that, you have $\ln\dfrac{\Delta l_i^2}{a^2} = 2\ln\dfrac{\Delta l_i}{a}$.
Comment: @mathguy Aha! I see that I was greedy and ignored the log operator. I fixed the typo so my mistake is clearer. If you put that as an answer, I will accept it.
Comment: No need, it's good enough as a comment :-)
Answer: @mathguy refuses to take credit, but they're the one who spotted it.
The simplification I performed erroneously tries to factor an $a^2$ term from outside the log operator. The expression I should have gotten was
\begin{equation}
1 = \frac{\rho_{si}a}{2\epsilon_0} \ln \frac{\Delta l_i^2}{a^2}
\end{equation}
which you can extract the power from and move outside the log:
\begin{equation}
1 = \frac{\rho_{si}a}{2\epsilon_0} \ln \left(\frac{\Delta l_i}{a}\right)^2 = \frac{\rho_{si}a}{\epsilon_0} \ln \frac{\Delta l_i}{a}
\end{equation}
This lines up with the book's derivation.


Problem with the schema structure produced by Schema module

Question: I am using the Schema module (7.x-1.2) on Drupal 7.34. This is the code I am using for a module I created.
function myid_schema(){
  $schema = array();

  $schema['myid_templates'] = array(
    'description' => 'TODO: please describe this table!',
    'fields' => array(
      'template_id' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'template_name' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'varchar',
        'not null' => FALSE,
      ),
      'portrait' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'boolean',
        'not null' => TRUE,
      ),
      'template_width' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'numeric',
        'not null' => TRUE,
        'default' => 0,
        'precision' => 0,
        'scale' => 0,
      ),
      'template_height' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'numeric',
        'not null' => TRUE,
        'default' => 0,
        'precision' => 0,
        'scale' => 0,
      ),
    ),
    'primary key' => array('template_id'),
  );

  return $schema;
}

function myid_install() {
  drupal_install_schema('myid_templates');
}

After installing the module, it throws this error.

Notice: Undefined index: boolean:normal in DatabaseSchema_pgsql->processField() (line 229 of C:\xampp\htdocs\drupal-7.34\includes\database\pgsql\schema.inc).
PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "NOT" LINE 4: portrait NOT NULL, ^: CREATE TABLE {myid_templates} ( template_id serial, template_name varchar NULL, portrait NOT NULL, template_width numeric(0, 0) NOT NULL default 0, template_height numeric(0, 0) NOT NULL default 0, PRIMARY KEY (template_id) ); Array ( ) in db_create_table() (line 2720 of C:\xampp\htdocs\drupal-7.34\includes\database\database.inc)

Why does it throw an error? How do I fix it?
Answer: Drupal doesn't have a boolean type for DB schema, and there's no automatic fallback for a type it doesn't know about, so you end up with the invalid portrait NOT NULL instead of portrait boolean NOT NULL in the create statement.
To fix, just add a pgsql_type to the column. DatabaseSchema_pgsql::processField() knows what to do with it.
'portrait' => array(
  'description' => 'TODO: please describe this field!',
  'type' => 'int', // Keep it portable
  'pgsql_type' => 'boolean',
  'not null' => TRUE,
),


Bounds on Fourier coefficients by total variation

Question: The following is a question from the book Fourier and Wavelet Analysis
by George Bachmann, Lawrence Narici, Edward Beckenstein (Section 4.3, Question no. 8).
Question: The Fourier sine and cosine coefficients $c_n$ of $f\in BV[-\pi,\pi]\subset L^1_\Bbb R[-\pi,\pi]$ satisfy $$|c_n|\le \frac{1}{n\pi}V(f,[-\pi,\pi])$$
and these estimates cannot be improved.
But when I consider the following function $f:[-\pi,\pi]\to \Bbb R$ by
$$f(x) = \left\{
 \begin{array}{1 1}
  0  & \mbox{if } & -\pi\le x <0 \\
  1 & \mbox{if } & 0\le x\le\pi
 \end{array}
\right.$$
Then the Fourier cosine coefficients $a_0=1, a_n=0$ and $b_n=\frac{1}{n\pi}(1-(-1)^n)$ for $n\in\Bbb N$. Also $f$ is of bounded variation with total variation $V(f,[-\pi,\pi])=1$. Thus $f$ satisfies the above requirement of the question.
But for $n$ odd, $|b_n|=\frac{2}{n\pi}$. Thus we obtain that $|b_n|>\frac{1}{n\pi}V(f,[-\pi,\pi])$ for odd values of $n$.
Now my question is that is the above estimate in the question correct?
Answer: I think you are right. \begin{align*}
\int_{0}^{\pi}\sin((2n+1)x)dx  & =\frac{1}{2n+1}\int_{0}^{(2n+1)\pi}\sin
t\,dt=\frac{1}{2n+1}\int_{0}^{(2n+1)\pi}\sin t\,dt\\
& =\frac{1}{2n+1}\sum_{k=0}^{n-1}\int_{2k\pi}^{(2k+2)\pi}\sin t\,dt+\frac
{1}{2n+1}\int_{2n\pi}^{(2n+1)\pi}\sin t\,dt\\
& =\frac{1}{2n+1}\sum_{k=0}^{n-1}\int_{0}^{2\pi}\sin t\,dt+\frac{1}{2n+1}%
\int_{0}^{\pi}\sin t\,dt\\
& =0+\frac{2}{2n+1},
\end{align*}
so $b_{2n+1}=\frac{2}{(2n+1)\pi}$. I went to check the original paper Izumi and there are two mistakes. One is that $2\pi|a_n|$ should be $\pi |a_n|$ and the other is that they forgot the absolute value in $|\cos nx|$. So you get
$$
\int_{-\pi/(2n)}^{\pi/(2n)}|\cos nx|dx=\frac{1}{n}\int_{-\pi/2}^{\pi
/2}\left\vert \cos t\right\vert \,dt=\frac{2}{n}%
$$
where $t=nx$ so $dt=ndx$. So they actually prove that $|a_n|\le 2V/\pi n$.


Finding eigenvalues of a lower/upper triangular matrix

Question: If we have a matrix:
\begin{equation*}
A =
\begin{pmatrix}
1 & 3 & 0 \\
0 & -8 & 0 \\
0 & 0 & 5
\end{pmatrix}
\end{equation*}
Now the matrix is in upper triangular form and $\det(A) = 1 \times (-8) \times 5$ and
$\operatorname{tr}(A) = 1 - 8 + 5$
can we say that $\{1,-8,5\}$ are eigenvalues of $A$ and why?
Comment: Elementary row operations do not respect the eigenvalues: if $A$ is obtained from $B$ by performing an elementary row operation on $B$, then it is not necessarily the case that $A$ and $B$ have the same eigenvalues. This is trivial to see if you for elementary row operations that involve multiplication by nonzero constants different from $1$, but also others. For example, the matrix $\left(\begin{array}{rr}1&0\\0&-1\end{array}\right)$ has eigenvalues $1$ and $-1$; exchanging  rows gives you the matrix $\left(\begin{array}{rr}0&-1\\ 1&0\end{array}\right)$, with eigenvalues $i$ and $-i$.
Comment: The fact that the determinant equals $a\times b\times c$ and the trace equal $a+b+c$ does not imply in and of itself that the eigenvalues are $a+b+c$. For example, the eigenvalues of the diagonal matrix with diagonal entries $1$, $-1$ and $0$ are different from the eigenvalues of the diagonal matrix with diagonal entries $2$, $-2$, and $0$, but both have the same determinant and the same trace.
Comment: @YoussefMohamed, you keep using the ambiguous phrase *operations*. There are different kinds of operations. *Row operations* do not preserve eigenvalues, nor do *column operations* on their own. However, the operation of simultaneously applying an elementary row operation on one side of the matrix and the inverse column operation on the other side *does* preserve the eigenvalues, i.e. $A \mapsto E^{-1}AE$, where $E$ is an elementary row operation.
Comment: We can say the eigenvalues are the diagonal entries because the diagonal entries are precisely the values of $\lambda$ for which $A-\lambda I$ is non-invertible.
Comment: Or the matrix $\left(\begin{array}{cc}0&2\\2&0\end{array}\right)$ has eigenvalues $2,-2$; adding the second row to the first row gives $\left(\begin{array}{cc}2&2\\2&0\end{array}\right)$ has eigenvalues $1\pm\sqrt{5}$.
Comment: A triangular matrix's eigenvalues are precisely the diagonal entries. This is not *because of* the trace and determinant, however. For example, $118$ can be written as the sum of a triple of nonzero integers in four different ways, each triple of which has the same product. So knowing that you have an upper triangular matrix with determinant equal to $37800$ and trace equal to $118$ would not allow you to determine the eigenvalues; they could be $14$, $50$, and $54$; or they could be $15$, $40$, and $63$; or they could be $18$, $30$, and $70$; or they could be $21$, $25$, and $72$.
Comment: Ok so operations on the matrix change eigenvalues ,I'll reformat the question to be about eigenvalues of lower/upper triangular matrices
Answer: For any matrix the roots of the polynomial  $p(\lambda) = \det(A- \lambda I)$ are the eigenvalues.
In the particular if $A$ is upper triangular then this determinant is simply
$$ (a_{11}- \lambda)...(a_{nn} - \lambda)$$
Hence the eigenvalues of $A$ can be read of the diagonal since they are precisely the values for which the above polynomial is equal to $0$.


Error code ElasticPoolOverStorageUsage

Question: I'm trying to create a new database in our Azure SQL elastic pool and getting the following error code.
<code>    Error code: ElasticPoolOverStorageUsage.
</code>
We have a total space of 32GB and based on the Elastic pool data storage graph, we have used only 65% of its total storage, leaving us with another 35% i.e.11GB.
I'm trying to create a new blank database and not getting anywhere.
I would appreciate any idea where I'm going wrong.
Answer: The error is pretty clear:
<code>400 ElasticPoolOverStorageUsage - Attempting to write data to a database when the storage limit of the elastic pool has been reached.
</code>
If you really have used only the 65% contact Microsoft Support.
And share the answer, I'm intrigued.

Error code ElasticPoolOverStorageUsage


Can you build a model based on coefficients with Pr>0.05?

Question: I have a data set of 3 independent variables and 28 cases (sample size). I have tried both train-test linear regression and k-fold cross validation for making the linear regression model. In both methods I get coefficients for my variables that have a Pr> 0.05. Given that I have R-squared value >0.9, can I use this model? If the coefficients have Pr values > 0.05 can I report them?
<code>> summary(model1)

Call:
lm(formula = data1$survival ~ ., data = train1)

Residuals:
    Min      1Q  Median      3Q     Max
-44.678 -25.424  -6.127  23.094  72.827

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) 55.878837  12.312291   4.538 0.000134 ***
X1          -0.028698   0.055040  -0.521 0.606871
X2          -0.697045   1.211960  -0.575 0.570550
X4          -0.005916   0.038547  -0.153 0.879307
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
</code>
and the RMSE:
<code>    > RMSE1
[1] 3.172029e-14
</code>
Answer: Yes, you should not purposefully hide information, especially, based on p-values. Building a model using p-values as a criterion is now well documented to be pretty bad in many ways.
Comment: Thank you. I understood from your answer that I must report the P values, but what I'm asking is that is this model in general reliable and worthy of being reported? Considering that I have a good R-squared (not the R-squared above).


Who should own /var/www?

Question:
Possible Duplicate:
How should I structure my users/groups/permissions for a web server?

I've seen a few answers to this on the internet, but I'm looking for a definitive answer. I have a new Ubuntu 12.04 LTS server with LAMP. Apache is set to run as "www-data" and /var/www is set as having "root" as the owner and "root" as the group. The permissions for /var/www are "drwxr-xr-x" which I believe translates to 755 numerically.
I know that /var/www should not be owned by "www-data" because then buggy/malicious code could have a field day. However, should I keep it as root:root (inconvenient) or should I change it to ubuntu:ubuntu, the default user that Ubuntu preconfigures for you to log in with? Should the permissions remain at 755?
I've been administrating systems for a while with no big security issues, but I'm trying to get really serious about security, double-check everything, and make sure that there are no gaps in my knowledge.
Comment: This is pretty abstract, and it depends entirely on the application and its filesystem usage patterns.
Comment: Is this a read-only environment? Do your want to use ACLs?
Answer: We really can't answer this question - it depends on your environment.
The major concern here is someone uploading, for example, a PHP script that does malicious things to a directory they can browse to, and getting your web server to run that code by browsing to the script they just uploaded.
The best answer you can get is "A user that makes sense, preferably not the same one the web server runs as unless you have a good reason and have taken appropriate steps to ensure security."

Who should own /var/www?


email queue qmail

Question: Is there any way for me to check the mail queue on an ubuntu server using qmail without SSH access.
If not are there any free email stats programs that would do a similar job that you can recommend.
Thanks
Answer: No, you cannot check these stats without shell access.
If you want to make it available for example via WWW, you can use RRDtool to collect data and generate graphs.
Answer: Well if you have already installed it( From the sitehttp://www.webmin.com/rpm.html) then you can use Webmin. Just log in to Webmin then go to servers and click on Qmail server and you will see all the information including queue size. You can then login to see the queue. In general managing Qmail is best done via the command line. Hope this helps.

email queue qmail


Finding components of lines intersecting at a point.

Question: I'm just working on some summer problems so that I can be more prepared when I go into my class in the fall. I found a website full of problems of the content we will be learning but it doesn't have the answers. I need a little guidance on how to do this problem. Here is the problem:
Consider the lines $L1$ and $L2$ with equations:
$L_1 : r = (11, 8, 2) + s(4, 3, -1)$
$L_2 : r = (1, 1,-7) + t(2, 1, 11)$
The lines intersect at point $P$.
a. Find the coordinates of $P$.
Would we use a formula for this? For example: $\frac{x_1+x_2}{2}, \frac{y_1+y_2}{2}, \frac{z_1+z_2}{2}$.
b. Show that the lines are perpendicular.
Isn't there also a formula to find if lines are perpendicular?
Comment: Do you mean $(11,8,2)+s(4,3,-1)?$
Comment: @mfl The question I found says -1, not -2. But, perhaps there was an error on their part. I am not sure.
Comment: Sorry about the $-2$. I mean the way you write the line. It is written as [11, 8, 2] + s = [4, 3, -1]
Comment: @mfl Oh, yes! You're right. Thank you. Just fixed it.
Comment: I don't understand c. $R$ is the reflection of $Q$ with respect to what?
Comment: @Ella Check the latest edit to make sure it matches the way the problem was presented to you. The way mfl changed your equations is a way the formula for a line is often represented. What you had before did not make sense as the equations of lines: $r = (11, 8, 2) + s = (4, 3, -1)$ implies that $r = (4,3,-1),$ because equality is transitive, so you really just had written equations for two single points.
Comment: The results from parts a and b make c particularly easy to do.
Answer: Saying that
$L_1:r=(11,8,2)+s(4,3,−1)$
means that every point on the line is of the form
(x, y, z)= (11+ 4s, 8+ 3s, 2- s) for some number s.
In other words, x= 11+ 4s, y= 8+ 3s, z= 2- s.
$L_2:r=(1,1,−7)+t(2,1,11)$
means that every point on the line is of the form
(x, y, z)= (1+ 2t, 1+ t, -7+ 11t) for some number t.
In other words, x= 1+ 2t, y= 1+ t, z= -7+ 11t.
Where the two lines intercept the x, y, z coordinates must be the same: 11+ 4s= 1+ 2t, 8+ 3s= 1+ t, 2- s= -7+ 11t.
Notice that these are three equations in only two unknowns, s and t.  In general, two lines in three dimensions do NOT intersect- most often they are "skew".  What we can do is solve two of the equations for s and t then see if those s and t satisfy the third equation.
11+ 4s= 1+ 2t is the same as 10+ 4s= 2t or 5+ 2s= t.  Setting t= 5+ 2s in the second equation, 8+ 3s= 1+ t= 6+ 2s.  s= -2 and then t= 5- 4= 1.
Checking the third equation, 2- s= -7+ 11t, 2- (-2)= 4= -7+ 11.  Yes, those values are the same so the lines intersect at x= 11+ 4(-2)= 11- 8= 3, y= 8+ 3s= 8+ 3(-2)= 8- 6= 2, z= 2- s= 2- (-2)= 4.  The two lines intersect at P= (3, 2, 4).
Answer: Ideas to get the answer
Part a):
You need to solve the system
\begin{align}
11+4s&=1+2t\\
8+3s&=1+t\\
2-s&=-7+11t
\end{align}
Part b):
The lines are perpendicular if and only if its directions are perpendicular. That is, if and only if $$(4,3,-1)\cdot (2,1,11)=0.$$
Comment: For part a, would I combine like terms and solve for both s and t?
Comment: Yes. Note that if $(x,y,z)$ is the intersection point then it must be $x=11+4s$ (line 1) and $x=1+2t$ (line 2). The same for $y,z.$ Once you get a solution of the system ($s,t$ must be a solution of the $3$ equations) you substitute $s$ in the first line (or $t$ in the second line) and you'll get $P$.


Adding a link to a node in a Views export

Question: I'm using Views data export to export a view-based search as a CSV file for users. Basically it's working. However I'd like to customize how some of the fields come out in the CSV.
Specifically for this question I'm interested in learning how to export the link to the NODE that is returned. It doesn't have to be an active link per se (although that would be ideal), but just the URL to the node would be great too.
I've tried adding Content: Link to the Fields area but that just exports as 'View' for every single returned node. Not helpful.
I've tried returning my title which is currently set to link to the original content but the export doesn't return it as a link. It just returns the title.
I've tried returning the title and making it return as a link with Content: Link as the URL (absolute path selected). But that doesn't nothing.
Anyone have suggestions?
Answer: You need to add a new field "content:path" and check the option in the rewrite results section "Use absolute link (begins with "http://")". This should do what you want.
If you want to output it as a working link, you can check the option " Output this field as a link" and fill the replacement pattern [path] into "Link path".