What are "fringeliers"?

Question: I recently received a reviewer comment from a journal submission that asked me to

report how I dealt with outliers and fringeliers.

I had not heard of the  term "fringeliers" and when I googled, there were some articles, but no concise definition. So I thought it would be good to have a question like this that could clarify what "fringeliers" are and provide a definition both for myself and future people asking the same question.
Comment: Here is a proposed reply when you submit your revision: "I deal with fringeliers by taking their comments on my manuscript into account and revising my paper accordingly." ;-)
Answer: Fringeliers appears to be defined as a less extreme kind of outlier. I.e., data on the fringes of the distribution.
For example, were you to define a cutoff for outliers, fringeliers might be operationalised to be those values that are close to either side of the cutoff (e.g., for a 3 SD cutoff, between 2.7 and 3.3 SD from the mean).
Osborne and Overbay (2008) write the following:

Although definitions vary, an outlier is generally considered to be a
  data point that is far outside the norm for a variable or population
  (e.g., Jarrell, 1994; Rasmussen, 1988; Stevens, 1984). Hawkins (1980)
  described an outlier as an observation that "deviates so much from
  other observations as to arouse suspicions that it was generated by a
  different mechanism" (p. 1). Outliers have also been defined as values
  that are "dubious in the eyes of the researcher" (Dixon, 1950, p. 488)
  and contaminants (Wainer, 1976).

And go on to introduce the term "fringelier" from Wainer (1976)

Wainer (1976) also introduced the concept of the "fringelier,"
  referring to "unusual events which occur more often than seldom" (p.
  286). These points lie near three standard deviations from the mean and hence may have a disproportionately strong influence on parameter estimates, yet are not as obvious or easily identified as ordinary outliers due to their relative proximity to the distribution center.

Some examples:
In some contexts, outliers suggest that the data is invalid. For example, if a man's  height is recorded as 8 foot tall (say 6.5 SD above the mean), this is probably an invalid measurement. In contrast, if someone's height is recorded as 6 foot 10 inches tall (3 SD above the mean - a fringelier), this might be a valid measurement, but equally, it might suggest a problem with measurement as this is pretty rare. The point is that determining whether a value is invalid gets harder, the less extreme the value becomes.
In other contexts, outliers are a concern because they have an excessive influence on parameter estimates, particularly when using standard statistical methods using least squares and so on. Thus, fringeliers may have greater impact than some most cases, but decisions about whether to retain the data or not for modelling purposes may be less clear.
References

Osborne, J. & Overbay, A. (2008). Best practices in data cleaning: how outliers and "fringeliers" can increase error rates and decrease the quality and precision of your results. In Osborne, J. Best practices in quantitative methods (pp. 205-213). Thousand Oaks, CA: SAGE Publications, Inc. doi: 10.4135/9781412995627
Wainer, H.Robust statistics: A survey and some prescriptions1(4)285-312(1976).
Comment: I suppose the difference can only manifest itself in how they are treated. Are the people noting the difference suggesting treating the "fringelier" with a soft penalty while treating the outlier with a hard penalty such as outright discarding?
Answer: I would think that you'd need to consider the frequency of the fringeliers w.r.t. the data points residing below the cutoff.   If the proportion of fringeliers to "valid" data is high (based on some factor(s)), perhaps the cutoff is unrealistically defined.  Imagine you're in a tent, and the only bears in the area are 3 miles away; but there are 500 of them! :)
Comment: This doesn't provide a definition.

What are "fringeliers"?


Tomcat/JIRA redirects to HTTP when accessed by HTTPS through a Pound proxy

Question: I'm trying to get a JIRA install to work behind a Pound proxy that is doing SSL termination/"acceleration". Unfortunately it seems that JIRA (Coyote) is redirecting to HTTPS when accessed:
C:\Users\Josh>openssl s_client -connect www:443
...
---
GET /support HTTP/1.1
Host: www

HTTP/1.1 302 Moved Temporarily
Server: Apache-Coyote/1.1
Location: http://www/support/
Transfer-Encoding: chunked
Date: Sat, 21 Jul 2012 16:05:03 GMT

0

I can't figure out how to stop this... This is my Pound config:
ignorecase 1

listenhttps
  address 10.3.0.12
  port 443
  cert "/usr/local/etc/bundle.pem"

  service
    headrequire "Host: www"
    url "/support.*"
    backend
      address 10.3.0.16
      port 8080
    end
    session
      type cookie
      ttl 1800
      id "X-SA"
    end
  end
end

Is there any setting in Tomcat or JIRA that would affect this?
Comment: Does it send the same redirect when you make the `GET` request for `/support/` instead of `/support`?
Answer: Glad you got it working. I'll try and add a bit of color to this in the event it's useful. When terminating SSL with an upstream device - a proxy, load balancer, etc., the downstream service won't know this. So your Tomcat was seeing normal HTTP traffic, specifically for a URI of just "/". At this point, Tomcat is doing an self referential redirect to /support/, where the application is configured.
When it does this, it builds the URI to use http://... instead of HTTPS://, as it's got literally no idea about the upstream proxy that is doing SSL. By adding the proxyPort and ProxyName directives, above, you've given Tomcat explicit awareness of an upstream device, so it'll now rebuild those redirects using https://, which will work.
--Matt
Answer: I figured it out, the proxy settings in Tomcat solved it (proxyPort and proxyName, IIRC).
Comment: Yep, I saw that. I added my answer for posterity; the explanation may help others who come across this post.


Hidden speech bubble toolltip for image

Question: I have this code where the hidden speech bubble appears when you hover over an image.
http://jsfiddle.net/e4q7K/19/
  #container {
background-color: #FF0;
margin: 100px;
float: left;
height: 200px;
width: 200px;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
 }

  div.hoverbubble {
  position: relative;
  text-decoration: none;
  width:50px;
  height:50px;
  }

 div.hoverbubble span {display: none;}
 div.hoverbubble:hover span {
display: block;
position: absolute;
padding: .5em;
content: attr(title);
min-width: px;
text-align: center;
width: auto;
height: auto;
white-space: nowrap;
top: -40px;
background: rgba(0,0,0,.8);
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
color: #fff;
font-size: 0.86em;
font-family: Arial, Helvetica, sans-serif;
   }
  div.hoverbubble:hover span:after {
position: absolute;
display: block;
content: "";
border-color: rgba(0,0,0,.8) transparent transparent transparent;
border-style: solid;
border-width: 10px;
height: 0;
width: 0;
position: absolute;
bottom: -20px;
left: 1em;
   }

Hidden message here.

And i was wondering if there is a way to style the image to this?
  width:100%; border:1px solid {color:border}; margin-bottom:6px;
 {block:ifroundedsidepic}
 -webkit-border-radius:100px; -moz-border-radius:100px; border-radius:100px;
 {/block:ifroundedsidepic}

I've tried doing this:

And I've also tried creating an image id, "#kuroko" in the CSS and changed the html to
Hidden message here.

But it did not work. Is there any possible way to style this image?
Answer: To style an element right after another one, you need to use the selector : +.
Your case will be :

with the css base :
img + span {
display:none;
}
img:hover + span {
display:block;
}

For the case of using the attribute title and a pseudo element from img , it will not be possible. img and input, for instance,  can not generate pseudo elements.

Hidden speech bubble toolltip for image


PHP not calling constructor on class?

Question: I have a project that I worked on around a year ago. I've coded various things in it and it was at a time where I was just starting out on the road to learning dependency injection.
Long story short, I've forgotten how to pass a parameter to a constructor. I've tried, although it doesn't seem to do anything. I've tried looking at the existing code for Dice but I can't work it out.
<?php declare(strict_types = 1);

$dice = new \Dice\Dice;

$configRule = [
    "constructParams" => ["config_directory_here"],
];

$dice->addRule("App\Providers\Configuration", $configRule);

The class in question
<?php declare(strict_types = 1);

namespace App\Providers;

class Configuration {
    private $config;

    public function __construct($configDirectory) {
        exit($configDirectory);
        $this->config = array();
        $this->loadConfig($configDirectory);
    }
}

As you can see, in the constructor I have this:
exit($configDirectory);

I don't get anything back, it just continues with the code and prints the Twig template, shouldn't it at least just print an empty string even if it didn't get passed?
I've not sure if this is a problem with my dice code or my PHP itself. I have PS4 autoloading so the Configuration class should be included.
"autoload": {
    "psr-4": {
        "App\\": "src"
    }
}

Can anyone help me here? Thanks! When adding the below code it works as expected, but I need to use a Dependency Injection Container to load the class.
$config = new \App\Providers\Config("test");
Comment: Why not `echo` then `exit` for making sure? PHP surely passes constructor parameters. Seems you are asking the specific way of doing DI that is preconfigured in a certain framework.
Comment: "PHP surely passes constructor parameters", if you read the question I'm relying on a DIC, not PHP. Echo and then exiting will do exactly the same, just in case I just tried it and it didn't change the outcome.
Comment: please include the code that initializes `Configuration` with DIC.
Comment: I already have, it's the first code block.
Answer: Full disclosure: I'm the author of Dice.
The reason this isn't working is because Dice never prematurely creates an object. The Configuration object won't be created until you request an instance from the container:
$configuration = $dice->create("App\Providers\Configuration");

Answer: The constructor is suppose to create an object and cannot return anything but the object it is attempting to create.
You should never create constructors that do any job other then assigning constructor parameters to the object properties.
Comment: This makes absolutely no sense. A constructor will exit perfectly fine if I initialize the class myself without DIC which proves the issue is with the DCI, and I'm only exiting for debugging purposes. This is not an answer.

PHP not calling constructor on class?


PowerShell parameters with special characters

Question: I am working on a PowerShell script to send an email, and some of the parameters may contains special characters, such as % and &.
powershell.exe .\sendmail.ps1 -to "firstname.lastname@example.com" -body "Special character & causing trouble." -subject 'PowerShell email'

This gives the following error:
Ampersand not allowed. The & operator is reserved for future use; use "&" to pass ampersand as a string.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : AmpersandNotAllowed

I have tried escaping the & with `. But the parameter will still not be correctly included in the script.
I am looking for a way to make sure the parameters will be correctly passed on to the script, including special characters. I am thinking about using encodedcommand, or perhaps placing the parameters in an xml file.
Any suggestions are most welcome.
Here is the script I am using:
param (
    [string]$body = "",
    [string]$subject = $(throw "-subject is required."),
    [string]$attachment = "",
    [string]$to = ""
)

Try
{
    $o = [Runtime.InteropServices.Marshal]::GetActiveObject("Outlook.Application")
}
Catch
{
    $o = New-Object -com Outlook.Application
}

$mail = $o.CreateItem(0)

$mail.subject = "Auto Build Test"

$mail.body = $body

#for multiple email, use semi-colon ; to separate
$mail.To = $to
$mail.Attachments.Add($attachment)
$mail.Display(0)

Answer: Try call the script in this way and let me know:
powershell.exe -command "& .\sendmail.ps1 -to email@example.com -body 'Special character & causing trouble.' -subject 'PowerShell email'"

Comment: Wow, that actually seems to work! Even with other special characters. Apparently, I have been missing the "Call operator"
Answer: simply use ' instead of " to disable expansion
powershell.exe .\sendmail.ps1 -to "email@example.com" -body 'Special character & causing trouble.' -subject 'PowerShell email'
Comment: Unfortunately, that does not work.
The string is missing the terminator: '.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Comment: this is working fine on PS V2 & PS V3 your probleme is elswere maybe in your sendmail.ps1. Show your script if you want more help. This is what i ran `PS>Send-MailMessage -to "email@example.com" -body 'Special character & causing trouble.' -subject 'PowerShell email' -from 'firstname.lastname@example.com'`
Comment: Thank you for your input. I have included the script in my question.
Comment: is there any good reason to use outlook via COM instead of using the powershell cmdlet [send-mailmessage](http://technet.microsoft.com/en-us/library/hh849925.aspx) ??
Comment: Unfortunately, there are reasons beyond my authority dictating the need to use Outlook via COM instead of send-mailmessage.
Comment: Many thanks for the hint. I had a problem passing = symbol to the PS script from a .BAT file and I resolved it by enclosing it with single quotes.


Vantagem e desavantagem entre onClick e setOnClickListener

Question: Tenho uma determinada situação onde vemos que é possível criar no arquivo XML uma propriedade chamada onClick:
onClick:
XML:
<Button
android:layout_height="@dimen/edittext_min_height"
android:layout_alignParentLeft="true"
android:minWidth="120sp"
android:onClick="btnSend"
android:clickable="true"/>

Classe:
public void btnSend(View view){
    //faça algo
}

Por outro lado também podemos instanciar dentro da classe o setOnClickListener():
setOnClickListener:
XML
<Button
    android:id="@+id/btnSend"
    android:layout_height="@dimen/edittext_min_height"
    android:layout_alignParentLeft="true"
    android:minWidth="120sp"/>

Classe:
Button btnSend = (Button) findViewById(R.id.btnSend);
btnSend .setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      //faça algo
   }
});

Quais seriam as vantagens e desavantagens entre usar onClick e setOnClickListener?
Comment: Não tive ainda um problema real que impedisse de usar o onClick no xml. Só algumas vezes tive de usar uma mesma tela mais de uma vez no programa para situações diferentes. Talvez seja isso.
Comment: Particularmente não gosto de usar o `onClick` no XML, pois se você, por algum motivo, excluir o método `btnSend` da sua classe, não vai dar erro de **compilação**, e sim erro de **execução**.
Comment: Acredito que seja "ruim" o onClick no XML porque seria necessário criar um método para cada botão no layout, deixando o código java imenso.
Comment: Na verdade eu acho que o "android:onClick" foi implementado no android 5 essa é a única diferença.
Comment: @GabrielLocalhost julgo que o atributo `android:onClick` sempre existiu.
Answer: Só encontro uma vantagem em cada uma delas que, por sua sua vez, representam uma desvantagem em relação à outra.
setOnClickListener().

Vantagem.
Permite a reutilização de código existente.
Se implementar a interface em uma classe em separado ela pode ser reutilizada em outras situações iguais.
Desvantagem.
A implementação, sendo feita numa classe anónima, torna o código mais difícil de ler e de manter. Claro que é discutível e há quem diga o contrário. No meu entender é código que "aparece do nada", no meio daquele em que estou interessado a ler/analisar.

onClickno XML

Vantagem.
Código mais fácil de ler. O código está num método declarado para esse propósito.
Pode evitar a necessidade de ter um campo e usar o findViewById()
Desvantagem.
O código não pode ser reutilizado.
Só funciona quando a view é usada numa Activity.

Para implementações simples e sem necessidade do código ser reutilizado, use o onClick no XML com o respectivo método no java.
Para implementações mais complexas e/ou reutilização do código, crie uma classe à parte e use o setOnClickListener().
Comment: Se eu usar o onClick, teria como mudar dinamicamente o texto deste botão ?
Comment: Texto ou o código associado?
Comment: A duvida relacionada é: Eu só consigo alterar o texto do botão caso eu instancie usando o `findViewById()`? Se não houver alguma forma, penso talvez então ser uma desvantagem usar o `onClick` quando quero alterar o texto dos botões dinamicamente.
Comment: Não vejo qual a relação entre usar o `onClick` e alterar o texto do botão. Note que eu digo que "**Pode evitar** a necessidade de ter um atributo e usar o `findViewById()`" e não que **evita**. Penso que as (principais)razões a ter em conta para escolher uma das formas são aquelas que indico no final da resposta
Answer: Acredito que exista apenas uma diferença ou um modo diferente de aplicação.
Os métodos são semelhantes, tanto faz você indicar a sua ação ao clicar no botão no XML como manusear esta ação pelo Listener.
Acontece que, ao utilizar o android:onClick o método setOnClickListener é implementando do mesmo jeito, só que você não o vê. Eles fazem a mesma coisa. E sim, você pode manusear várias ações diferentes utilizando o atributo no XML.
Veja um exemplo:

XML

<Button android:id="@+id/b_1"
    android:onClick="actionHandle"/>

<Button android:id="@+id/b_2"
    android:onClick="actionHandle"/>

Java

public void actionHandle(View v){
    switch(v.getId()){
        case R.id.b_1:
            // act!
            break;

        case R.id.b_2:
            // act!
            break;
    }
}

Veja que você pode utilizar o método actionHandle ou qualquer método que você definir, para manusear o click que ocorrer em seus botões. Se você for utilizar o setOnClickListener, ficaria algo assim:

setOnClickListener

public class A extends Activity {

    @Override
    protected void onCreate(Bundle b){
        super.onCreate(b);
        // setContent

        (findViewById(R.id.b_1)).setOnClickListener(actionHandle);
        (findViewById(R.id.b_2)).setOnClickListener(actionHandle);
    }

    View.OnClickListener actionHandle= new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.b_1:

                    break;

                case R.id.b_2:

                    break;
            }
        }
    };
}

Na minha opinião, utilizar o atributo no XML é mais maleável e organizado e, claro, se você souber utilizar o atributo sem ficar criando vários métodos para diferentes botões, utilizar o android:OnClick é a melhor opção não importa o tamanho da aplicação.
Answer: Não existe um forma mais correta.
Mas a segunda opção setOnClickListener na activity é a recomendada como boas práticas.
Por possuir uma visualização mais rápida da função que o método tem.
Para realizar uma manutenção, ou mesmo durante o desenvolvimento, o uso do onClick no XML, pode acabar gerando um código mais confuso.
Comment: Pode explicar porque é *"a recomendada como boas práticas"*?
Comment: @ramaral Editei a resposta, mas já tinha na resposta que é para facilitar a manutenção do código, por ser mais fácil de visualizar. De qq forma, obrigado pela ajuda.
Comment: Relendo a sua resposta fico com a ideia contrária, ou seja, parece que, quando diz *"Pois, para uma manutenção, ou mesmo durante o desenvolvimento isto acaba gerando um código mais confuso."*, se está a referir ao uso do `setOnClickListener()`.
Comment: Feito! Fiz a correção deixando claro que a segunda opção é a melhor a ser implementada. Mais uma vez, obrigado!
Comment: Sobre a afirmação "...a segunda opção é a melhor a ser implementada.". Bom, e exatamente esse o propósito da minha pergunta, saber qual vantagem e desvantagem, porém você não não indicou nenhuma referência. Você disse também "a segunda opção setOnClickListener na activity é a recomendada..." mas recomendada por quem?
Comment: @seamusd Em um aplicativo muito grande, se torna improdutivo dar manutenção nesses métodos, pois fica difícil localizar quais views que este método faz referência e vice versa.
Se o nome do método não estiver bem explícito que é um evento onClick e está sendo referenciado em um layout xml, ou não houver um comentário especificando isso, o programador poderá não saber disso até que ocorra um erro.
Comment: retirado de (http://www.brunonardini.com.br/mobile/android-boas-praticas-para-o-evento-onclick)
Comment: desculpe o link não funcionou [link](http://www.brunonardini.com.br/mobile/android-boas-praticas-para-o-evento-onclick)
Comment: *"Se o nome do método não estiver bem explícito ... "*, não é razão para não usar, porque o que está errado é o nome do método e não o uso do onClick. Tomara que todos os métodos fossem tão fáceis de dar nome como esse.
Answer: Eu tive a mesma dúvida e dei uma aprofundada no assunto e depois dessa resposta acabei me convencendo a não usar o onClick.
Basicamente: as implementações de botões Android indicam que o botão será clicavel, porém, se algum fabricante seta-lo para false, você só sentirá o problema através do mercado. Você pode forçar para que o botão seja clicável, porém, se esquecer, um abraço!
EDIT: Pelo que identifiquei na resposta, o problema está em setar o evento Click em um objeto não botão.
Comment: Se, como diz, "algum fabricante seta-lo para false" esse problema não terá o mesmos efeito se usar `setOnClickListener()`?
Comment: Acabei de fazer um teste bobo em um app, setei o meu  imagebutton com o clickable = false e adicionei o OnClick, ao clica-lo, tenho um erro em tempo de execução. Ao manter o clickable como false e utilizar o setonClickListener() o image funcionou normalmente.
Comment: Não consigo reproduzir qualquer erro. Tanto o `onClick` como `setOnClickListener()` funcionam. Verifique se não é o código que colocou no `onClick` que provoca o erro. O que tem de especial no uso de `android:clickable="false"` simultaneamente com `android:onClick="buttonClick"` ou `setOnClickListener()` é que o `clickable="false"` não terá efeito. Ele é colocado em `true` no método [setOnClickListener()](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.0_r1/android/view/View.java#View.setOnClickListener%28android.view.View.OnClickListener%29).


Does anyone actually compose using Lilypond? And do people usually compose by line or bar/beat?

Question: It is really annoying and tedious and slow. Are people using it to compose from scratch? Is it meant for composing from scratch, or as a music engraver ie. COPYING or TRANSPOSING etc. and NOT write directly onto a notepad.
I tried it and the notation for multivoices is really annoying and complex sometimes that all attention is spent on the code part and making sure it will compile
Additionally, I am wondering what is the best practice for composing in the sense of by line or beat for example, if you had a melody with accompany planned out, would you write the melody all out then accomp all out, or would you do it at the SAME time but bar by bar? How did the great composers do it?
Comment: "How did the great composers do it" is a separate question and should be asked as such, and of course they didn't all do it the same way, but mostly they either worked it out at the keyboard and then wrote it down or they sketched it out, melody and bass line first, probably not measure by measure, and then filled in the inner voices.  It's much faster to do this on paper than with any notation software I've ever used.
Comment: (Also, spoiler alert, the answer to that one is probably "no two composers do everything the same." Personally, not that I do much composing, but I do a combo of both: First I sketch out ideas very minimally—maybe just a melody line, maybe just a bass line, some chord names. When I'm later in the process, putting down the "for real" version, I might get a bar fully realized before moving on to the next bar. If the genre is very contrapuntal I might work more with one line at a time.)
Comment: When you ask about "best practice for composing" I'm not sure if you mean the mechanical task of notating it, or how to creatively make up musical ideas.
Comment: Welcome! Please take a second to read about [the topics covered here](https://music.stackexchange.com/help/on-topic) and [how to avoid subjective answers](https://music.stackexchange.com/help/dont-ask). You might want to edit this question to make it a bit more "narrow"; right now the "do you compose bar by bar or one voice at a time" question is really its own, not really integral to the Lilypond question; you can split that off and ask it separately. I'm voting to close as too broad, but will happily retract my vote if it's edited.
Comment: There are a few users active on the r/composer subreddit who claim to compose in Lilypond, and some even go as far as to recommend it to other people for composition. It's rare.
Comment: MuseScore has been mentioned in the answers. I can tell you that you **can** compose entirely in MuseScore if you want to. Your last question doesn't make sense though; if you have both melody and accompaniment completely planned out, then how you enter them doesn't affect the result so obviously do whatever is easiest for you.
Answer: Lilypond is really meant to be a tool that engraves nice scores and that's it -- it conforms to the "Unix Philosophy" in the sense that it tries to do one thing (albeit very complex), do it well, and interoperate easily with other programs (its text-based input is well-suited for that).
I can't speak for the Lilypond developers, but I'd say it's pretty obvious they had these things in mind, as opposed to any kind of "WYSIWYG" or "on-the-fly" writing. I guess it's partly because of the fact that there already are several other tools that do notation in this way (MuseScore seems to be a good free one, but I don't use it) and there wouldn't be need for another.
So I must agree that trying to compose with Lilypond is mostly annoying (I tried it and I came to the same conclusion as you, although in some corner cases it can be useful, e. g. writing canons and having the parts automatically shifted is easy in Lilypond).
When it comes to my personal composing experience: I managed to evolve an old-fashioned style of composing where I just scribble the scores in pen into paper music notebooks, and only after the score is scribbled, I transcribe it using Lilypond to get a nice PDF. It's probably not the most efficient workflow under the sun, and probably not the method you wanted to hear about. If you want to compose "on the fly" on your computer, it will be better to use a tool that is better suited for that.
Comment: @ToddWilcox: Indeed, that is the fundamental design philosophy behind Unix. A lot of it has been lost in modern Linux Desktop distributions, but *fundamentally*, the idea is to have small utilities that "[Do One Thing And Do It Well](https://wikipedia.org/wiki/Unix_philosophy)" and consume and produce plain text (this is sometimes expressed as "[The Power Of Plain Text](https://wiki.c2.com/?PowerOfPlainText)"). The Unix OS then has tools like pipelines and shell substitutions that allow the user to easily plug multiple utilities together and use one utility's output as the input of the next.
Comment: @ToddWilcox: An example would be the DAW [Rosegarden](https://www.rosegardenmusic.com/), which can be set up to export directly to LilyPond.
Comment: @ToddWilcox: Another example would be TuxGuitar. As for MIDI and MusicXML, it cannot ingest them directly, but there are scripts `midi2ly` and `musicxml2ly` that come bundled with Lilypond and convert these things into Lilypond sources. By "interoperability", I just meant that anyone who writes an app that needs to show scores can just generate a simple text file and turn it into a score with Lilypond.
Comment: Checkout [Frescobaldi](https://www.frescobaldi.org/). I've been using it to compose short pieces for piano. It has a MIDI extension for listening. As others have mentioned, having a sketch first helps with the creative process.
Comment: What other programs does Lilypond interoperate with? Can it ingest MIDI or MusicXML?
Comment: I concur, and will add that what you describe as "corner cases" come up often IME: e.g. when a theme comes up many times (not necessarily at the same pitch). Some developers have written Lilypond "snippets" (like software packages) which extend the functionality. Some of these simplify the description of repetitive parts of the musical score.
Comment: Ah I get it now. Instead of having to use a complicated API, anyone can just write a text processing script to generate Lilypond from any source data. Interesting…
Comment: @JörgWMittag Yeah I've been a UNIX user for over 30 years now. I just didn't see how the "interoperability" part of this answer applied to modern music production workflows. The IT and music parts of my brain don't normally talk to each other
Comment: @ToddWilcox: Hah, yeah, I can understand. I wrote some tools long ago to generate nicely-formatted set lists in LaTeX. However, in my current usage, that has been replaced by the setlist feature in OnSong. I also used to keep Cubase projects in version control and crazy stuff like that. (I still use the feature in OnSong that allows you to export your entire library into text files and keep those in Git.) But the "mainstream" tools are just not set up for that. For example, there is nothing technically stopping Cubase, Logic, ProTools, etc. to use plain text files for pretty much everything …
Comment: … in a project except the actual audio files, but they just choose not to and use an opaque, undocumented, proprietary, binary format instead.
Comment: @ToddWilcox Unless your music is more complicated algorithmically than I can imagine, the task of Lilyponding it won't necessarily entail you writing an external app to generate Lilypond code. Lilypond's language is powerful enough to express the notion of generating Lilypond code itself. At a basic level, you can assign a music expression to a variable and reuse that variable multiple times, possibly transposed.
Comment: The biggest issue with LilyPond is that it uses LaTeX syntax. This is why I prefer Unison (unisonofficial.com), where you can type in plain English commonly accepted music terms.
Comment: To be clear: that is why you *created* Unison. (The way your message is worded, I first thought you were a mere user who discovered Unison and preferred it over LilyPond.)
Answer: Does anyone actually write mathematics using LaTeX?  LaTeX is not a tool for doing mathematics but for expressing it.  Similarly, LilyPond is a tool not for composing music but for expressing it.  How closely someone's creative workflow will align with an expressive tool is individual and will very much depend on personal habits and with how much attention working with the tool will consume over working with and on the material.
Musical notation, like mathematical notation, has been developed and evolved for a reason.  It tends to make a better mapping through the visual pathways to the mind.  So to some degree it also depends on how directly the transcription will appear in a visual form.
Check out https://lilypond.org/easier-editing.html for an overview of tools known to the LilyPond project.  The most popular at the moment may be Frescobaldi.
Comment: "writ[ing] mathematics" is exactly what LaTeX is for. Maybe "solve mathematical questions"...?
Comment: I write math using LaTeX, and I know I'm not the only one. So the answer to your question is **yes**. That said, I would never compose directly into Lilypond. @Aaron When I started using LaTeX I was way beyond "solving" things, but I did formulate my proofs entirely in LaTeX. I suppose I sometimes jotted notes down on an iPad, but between 80% and 95% of my work was right into LaTeX. I think the markup is much more readable for math than Lilypond is for music.
Comment: thank you, this was exactly what i was looking for. Nice analogy. I was doing it wrong then...
Comment: @ToddWilcox "...there's way too much information to decode the Matrix. You get used to it, though. Your brain does the translating. I don't even see the code. All I see is blonde, brunette, redhead. Hey uh, you want a drink?" - Todd Wilcox, probably
Answer:
all attention is spent on the code part and making sure it will compile

That is precisely the opposite of the goal of a non-WYSiWYG system like LaTeX or Lilypond. The advantage is (at least supposedly!) that you can just write content without having to worry how it compiles / renders at first. Then in the end when all the content is there, you polish it up for actually obtaining a document.
Does that really play out in practice? Well, it depends. For LaTeX it definitely can work, once you've gathered a bit of experience. Yet many people use it very similar to how one would use a WYSiWYG editor like MS Word, particularly with tools like Overleaf: they mostly look at the rendered output, and only when making a concrete change switch to the code view. This is in some ways counterproductive (in particular when it comes to premature bikeshedding like exact placement of floating figures), however there is a point to be made that particularly for maths formulas, it's just way easier to navigate the neat rendered form and decide what still needs to be done.
With music that's perhaps even more extreme: many composers nowadays rely not only on having a sheet with rendered notes in front of them rather than weird symbols, but also on the various playback functionalities offered by software like MuseScore or Sibelius. If you're approaching it from the perspective that editing a score is performing incremental modifications to a piece of sound, then Lilypond can't work well. But while these sorts of modifications are certainly helpful at some level, I would argue that it is not good to use them as the primary creative tool. It tends to lead to quite superficial music, where every individual snippet sounds good but there is little cohesion, overarching themes etc..
Most composers before the digital age worked very differently: when your medium is just paper and pencil, plus an instrument you can play yourself, you're forced to start out from ideas, motifs, and you also need to plan out the larger structure before actually writing a symphonic score, else it'll take forever moving the parts around. I won't say this sort of constraint is necessary to create great works, but I do think it helps. And that, I'd say, could also be a great advantage of a system like Lilypond: separating the meaning of the different components of a compositions from the actual appeareance/sound of the final result.
So that would mean you should neither compose-by-line or compose-by-beat or whatever, but instead by logical unit.
But again: so goes the theory. Yet, unlike for LaTeX, which is the de-factor standard in scientific publishing at least in some discipline, Lilypond is very much a niche tool (though also not so niche that not many composers aren't aware of it). But they evidently do not find it to be better than e.g. Sibelius in practice. And even I, although I'm very much an advocate of command-line terminals, coding in lightweight text editors, do not consider Lilypond a pleasant tool for creating musical scores, whether newly-composed ones or transscriptions of existing material. Music is actually the only thing I prefer writing on paper rather than any digital form.
Not sure whether it is a fundamental property of music that makes it worse suited for writing-from-code (perhaps the inherent, and desired ambiguity and multitude of possible interpretations), or just that Lilypond hasn't found the best way to go about it.
Of course, a lot of it also has simply to do with what you're acquainted to: Lilypond is complex and you should expect to need at least several months of regular use before you can unlock its full potential. The syntax is in a kind of weird no man's land between Lisp syntax (which was probably natural to the developers, but hardly to most other people) and ad-hoc shorthands to make it concise, but neither is carried out consequently. Leaving aside how good or bad that is in principle, it definitely doesn't help the learning curve.
Answer: You may want to check out arranger.ly. It's originally intended at arranging, though probably suitable for composing as well. It implements a workflow that is totally different than the usual LilyPond workflow and more like the workflow in a graphical editor: you cut&paste fragments of music, replace measure 5 beat 3 with note X, etc. As opposed to editing a linear representation of the score, you add conceptual editing operations like this that are easier to do. I know several people who are using it for arranging and happy about it.
Answer: I've had a similar experience over the past few months.
Musecore is fantastic for prototyping and generating parts.  It really can't be beat for those purposes.  If your goals are to create scores and generate parts, then use Musecore.
As others said: musecore is a WYSIWYG (what you see is what you get) piece of software.  It is an all-in-one suite that makes it easy to manipulate and see instant results.
However, lilypond is just two things:

A file format: *.ly files abide by a well-defined set of rules to describe music.
A program which converts *.ly files to something useful like *.pdf

Because Lilypond is a file format and not a GUI, it is much more difficult to learn and use.  (it is possible for someone to develop a GUI for lilypond to mitigate that drawback).
Musecore and lilypond both produce beautiful engravings so why would someone ever choose lilypond?
Here are several reasons:

VCS: Because *.ly files are ascii encoded, they can easily be managed by "version control systems" like git (e.g. github), svn, or hg.  That lets you merge changes from contributers and inspect the history of your scores to figure out when, why, and by whom each line was touched.  This is how software source code is managed and is essential for big projects with lots of contributers.

Intrgration: if you are only producing full-page, stand-alone PDFs, then musecore is still a better option, but if you want to produce SVGs or miniature PDFs that can be integrated into web pages, or other documents, especially if you would prefer to rely on scripts to do the conversion instead of opening the GUI each time, the  lilypond is better.

Here's a workflow that demonstrates the power of lilypond:

A user looks at my Web page/document and sees a deficiency.
They checkout the repository using "git clone", retrieving my *.ly files.
They edit the lilypond file and "git push" to send the improvements back to me.
I get a merge request containing only changes (I don't need to look at the whole file).
I look at the difference (it is a text file showing which lines were added/changed/deleted).  If I like the suggestion, I choose "accept".
I have a build machine that detects the change and automatically runs a script to re-compile the *.ly file.  This generates new SVG or PDF files which are immediately uploaded to my living document or website.

Here is a simpler example:
I'm writing a PhD dissertation that contains many orchestral excerpts.  The books will have several chapters of text, chapter headers, page numbers, bibliography, and the music.
Musecore can handle the music, but it won't easily make a good bibliography, add figures, hyperlinks, table of contents, cross references, or even paragraphs.  Fortunately, lilypond integrates nicely with LaTeX which does all of that nicely.
To write the dissertation, I write it in a .lytex file using latex, then use <code>\lilypondfile{}</code> to include the excerpts (.ly files).  It doesn't matter if my document is Letter with 1in margins, A4 with 1cm margins, or something else. Latex passes the geometry to lilypond so the lines are always the appropriate length and still readable.  Latex also forwards things like font and fontsize so text in the music matches the rest of the document.  If I want to change to a sans-serif font, I just change my lytex file in one place and recompile the full project.  If my music was in musecore, I'd have to open each file, manually change settings and re-export every excerpt by hand.
While musecore is easier for most users, lilypond saves a lot of manual labour in some cases despite the learning curve.
As to whether I write bar-by-bar or beat-by-beat in lilypond.  I tend to do 20-30 measures at a time, then compile and look for errors.


Is there a notion of an "Lie (algebraic) skew field" and can it be shown that $\mathbb R^3$ isn't one?

Question: I was wondering what makes the skew-field structures on $\mathbb C$ (complex numbers) and $\mathbb C^2$ (cuaternions) special. A natural answer seems to be that they are manifolds such that with respect to addition $\mathbb C$ and $\mathbb C^2$ are Lie groups and also $\mathbb C \setminus \{ 0 \}$ and $\mathbb C^2 \setminus \{ 0 \}$ are Lie groups with respect to multiplication. My first question is, is this generalised to some well known-notion of "(skew-)Lie field" or something like that?
What I'm more interested in is, does there exist a (skew-)field structure on $\mathbb R^3$ such that with respect to the standard manifold structure $\mathbb R^3$ is a Lie group with respect to addition and $\mathbb R^3 \setminus \{ 0 \}$ is a Lie group with respect to multiplication? Does the answer change if instead of Lie groups we only ask them to be topological groups? I wasn't able to find anything on this anywhere.
Comment: $\mathbb{C}^2 \neq \mathbb{H}$ and what do you mean by skew field? Unitary division ring (i.e. noncommutative field)?
Comment: There is work done on such rings, everything has not been shown yet but I think you must have $\dim_\mathbb{R} K = 2^n$ and for $n=3$ (octonions) you don't have associativity.
Comment: And if you impose associativity, you have https://en.wikipedia.org/wiki/Frobenius_theorem_(real_division_algebras)
Comment: @JulesBesson What do you mean $\mathbb C^2 \neq \mathbb H$? They are isomorphic as additive groups and as smooth manifolds. By skew field I mean unitary division ring, can be commutative but not necessarily. Frobenius' theorem partially answers my question, but what if we don't ask about an associative division algebra structure on $\mathbb R^3$ but we ask of a skew field structure where the additive operation is the vector space one (that is, we don't ask compatibility with scalars from $\mathbb R$ of the field multiplication)?
Comment: I have an interesting remark about this problem made in my homotopy course, I can write it down in an answer if you want. What I meant for $\mathbb{H} \neq \mathbb{C}^2$, is that when you take the highest structure possible, which here is finite dimensional $\mathbb{R}$-algebra, they are not isomorphic.
Comment: @JulesBesson Ah yes, now I understand what you mean. Please write your remark, I'd be very interested to see it.
Comment: Also I forgot to tell you but for $\mathbb{R}^3$ it was shown to be impossible and maybe for any number that is not a power of $2$.
Comment: The only spheres that are H-groups are $S^n$ for $n=0,1,3,7$ corresponding to the reals, complex numbers, quaternions, and octonions.  So even putting a group structure on $\mathbb{R}^n\backslash\{0\}$ is limited.
Answer: This is not an answer, I just needed space for the remark I was talking about in the comments
First of all, only $\mathbb{R}^{2^m}$ can hope to be endowed with a structure of (non associative) unitary division ring. So for $\mathbb{R}^3$ it can't work.
Let me first introduce a proposition:

Proposition: Let $G$ be a Hausdorff topological group and $H$ a closed subgroup of $H$. Let $G/H$ be the space of orbits for the left action of $H$ on $G$.
Suppose the quotient map $q: G \to G/H$ has a local section at $[e](=H)$, then if $K \leqslant H$ is closed, the quotient map $p: G/K \to G/H$ is a fibre bundle with fibre $H/K$.

With this theorem and the definition of $l$-frames given by:
$$V_{k,l}^\mathbb{F} = \left\{ (v_1,\dots,v_l) \in (\mathbb{F}^n)^l \mid \langle v_i,v_j\rangle = \delta_i^j\right\}$$
So the $l$-orthonormal families, and its sort of dual; the grassmanian:
$$Gr_{n,l}^\mathbb{F} = \left\{ V \subset \mathbb{F}^n \mid V \text{ is a sub-vector-space of dimension } l\right\}$$
You have one first fibre bundle that links Stiefel manifolds:
$$V_{n-k,l-k}^\mathbb{F} \to V_{n,l}^\mathbb{F} \to V_{n,k}^\mathbb{F}$$
And a second that defines the Grassmanian manifold:
$$V_{l,l}^\mathbb{F} \to V_{n,l}^\mathbb{F} \to Gr_{n,l}^\mathbb{F}$$
Unfortunately I can't give to much detail.
This is used to solve the problem: can $\mathbb{R}^{2^m}$ be endowed with a structure of unitary division ring? Of course all the topological properties follow here.
For that we define the Hopf fiber bundles given by:
$$V_{1,1}^\mathbb{F} \to V_{n+1,1}^\mathbb{F} \to Gr_{n+1,1}^\mathbb{F} \simeq \mathbb{F}P^n$$
So for $\mathbb{F}= \mathbb{R}, \mathbb{C}, \mathbb{H}$, we get
$$\mathbb{S}^0 \to \mathbb{S}^1 \to \mathbb{R}P^n$$
$$\mathbb{S}^1 \to \mathbb{S}^{2n+1} \to \mathbb{C}P^n$$
$$\mathbb{S}^3 \to \mathbb{S}^{4n+3} \to \mathbb{H}P^n$$
Unfortunately for $m \geq 3$ the projective space is not defined since we lose associativity (but it can exist for $n=1$ and $(n=2, m=3)$... This leads us to one more definition: Hopf fibrations (just set $n=1$ in the previous fibre bundles):
$$\mathbb{S}^0 \to \mathbb{S}^1 \to^{\cdot 2} \mathbb{S}^1 $$
$$\mathbb{S}^1 \to \mathbb{S}^{2n+1} \to^{\eta} \mathbb{S}^2$$
$$\mathbb{S}^3 \to \mathbb{S}^{4n+3} \to^{\nu} \mathbb{S}^4$$
Check on YouTube, this is cool!
And from what I know Hopf fibrations can be defined for $m = 3$ (octonions) and we get a Bundle:
$$\mathbb{S}^7 \to \mathbb{S}^{15} \to^{\sigma} \mathbb{S}^8$$
I don't know exactly why, but this is one of the key to study this (I believe) open problem:
can $\mathbb{R}^{2^m}$ be endowed with a structure of unitary division ring?.
A construction already exists for $m=4$ it is called sedenions.
Comment: Can I ask why I got a downvote? All I did is give some result following a discussion in the comments, not the actual answer...
Comment: Hi! I didn't down-vote, but I don't think the site is (yet) rotten with negative energy. However, I will say that users are a lot less tolerant of "extended comments" than they used to be. I got a couple of down-votes for an extended comment myself a few days ago. That annoyance was tempered by that same extended comment being accepted by the OP as an answer though! ¶ Anyway, have an upvote. But do you mean **sedenions**?
Comment: Also you can transpose the theorem in "smooth mode" to get Lie groups, it works
Comment: Next time I won't bother answering with all this negative energy, originating from the frustration that rottens this site.
Comment: Yes thanks for correcting, maybe I was a little bit too annoyed that in 5s I got a downvote (I had not even time to correct my first mistakes) maybe its a miss click but I thought this person did not even took time to read the comments.
Answer: I may be misinterpreting your question, but it sounds to me like you're asking the following:

Is there a continuous operation $\cdot$ on $\mathbb{R}^3$ which a) distributes over the usual addition and b) has a unit, and c) all non-zero elements have inverses?

The answer to this is yes.  In fact, there is commutative example on any $\mathbb{R}^n$.
Consider the elements $\{e, x_1, x_2,..., x_n\}$ as a basis of $\mathbb{R}^{n+1}$. We define $e$ to be the multiplicative identity, $x_i^2 = -1$ and $x_i x_j = x_j x_i = 0$ for $i\neq j$.   We extend this definition to all of $\mathbb{R}^{n+1}$ bilinearly.
This resulting operation obviously distributes over addition and has a unit.  What about inverses?
Well, given a non-zero $\alpha e + \sum \beta_i x_i$, it is easy to verify that the inverse is $\displaystyle\frac{\alpha e - \sum \beta_i x_i}{\alpha^2 + \sum \beta_i^2}.$
Of course, in the above example, for any $n\geq 3$ there are zero-divisors.  We will show that this is necessary, at least if $n$ is odd.
Let's prove this.
Proposition 1:  If $\cdot$ is continuous and distributes over addition, then for any $\alpha\in \mathbb{R}$, $x,y\in \mathbb{R}^n$, we have $$(\alpha x)\cdot y = x\cdot(\alpha y) = \alpha(x\cdot y).$$
Proof:  We will only prove that $(\alpha x)\cdot y = \alpha (x\cdot y)$, the other case being similar.
We first prove it for $\alpha = 0$.  Here, note that $0\cdot x = (0+0)\cdot x = 0\cdot x + 0\cdot x$.  Subtracting $0\cdot x$ from both sides, we find $0\cdot x = 0$.
Next, we prove it for $\alpha \in \mathbb{N}$.   We have $$(\alpha x)\cdot y = (x + x + ... + x) \cdot y = x\cdot y + x\cdot y + ... + x\cdot y = \alpha (x\dot y).$$
Next, we prove it for $\alpha \in \mathbb{Z}$.  We have $$0 = 0\cdot y = (\alpha x - \alpha x)\cdot y = (\alpha x)\cdot y + (-\alpha x)\cdot y,$$ so $(-\alpha x)\cdot y = -(\alpha x\cdot y).$  Since we know the result for $\mathbb{N}$, it now follows for $\mathbb{Z}$.
Next, we prove it for $\alpha \in \mathbb{Q}$.  Write such an $\alpha$ as $\alpha = \frac{\beta}{\gamma}$.  Then $$\gamma \alpha (x\cdot y) = (\gamma \alpha x)\cdot y = ( \underbrace{\alpha \cdot x + ... + \alpha \cdot x}_{\gamma \text{ copies}}\cdot y = (\alpha x)\cdot y + (\alpha x)\cdot y + ... + (\alpha x)\cdot y = \gamma((\alpha x)\cdot y).$$  So $\gamma\alpha(x\cdot y) = \gamma((\alpha x)\cdot y).$  Now divide both sides by $\gamma$.
Lastly, we prove it for $\alpha\in \mathbb{R}$.  Let $\alpha_n$ be a sequence of rationals which converge to $\alpha$.  Then $\alpha_n(x\cdot y) = (\alpha_n x)\cdot y$ for all $n$.  Taking $\lim_{n\rightarrow\infty}$ of both sides and using the fact that $\cdot$ is continuous, we find $\alpha (x\dot y) = (\alpha x)\cdot y.$ $\square$
Let $L_x:\mathbb{R}^n\rightarrow \mathbb{R}^n$ be given by $L_x(y) = x\cdot y$.
Proposition 2:  The map $L_x$ is a linear transformation.
Proof:  We have $$L_x(\alpha y + \beta z) = L_x(\alpha y) + L_x(\beta z) = \alpha L_x(y) + \beta L_x(z),$$ where the first equality is because $\cdot$ distributes over $+$ and the second is from Proposition 1.  $\square$
Let $e\in \mathbb{R}^n$ denote the unit.
Proposition 3:  Suppose $n\geq 3$ is odd and suppose that we have a multiplication $\cdot$ satisfying  a) multiplication is continuous, b) multiplication distributes over $+$, and c)  all non-zero elements have multiplicative inverses.  Then there are zero divisors.
Proof: From Proposition 2, for each $x\in \mathbb{R}^n$, $L_x$ is a linear transformation.
Now, select $x \in \mathbb{R}^n$ with $\{x,e\}$ linearly independent, which is possible because $n>1$.
Because $n$ is odd, the linear transformation $L_x$ has an eigenvector $0\neq y\in \mathbb{R}^n$, so $xy = \alpha y$ for some $\alpha \in \mathbb{R}$.
Now, consider the element $z:=x-\alpha e$.  Because $\{x,e\}$ is linearly independent, $z\neq 0$.  But then $z\cdot y = x\cdot y - \alpha e\cdot y = \alpha y - \alpha y= 0$.  Thus, there are zero-divisors.  $\square$
Comment: Unital multiplications without zero-divisors are actually quite special.  For example, given such a multiplication, one gets an $H$-space structure on the unit sphere $S^{n-1}\subseteq \mathbb{R}^n$ by defining $\mu(x,y) = (x\cdot y)/|x\cdot y|$.  As yoyo indicates in the comments, this implies that $n = \{1,2,4,8\}$, though the proof is significantly harder than my proof above which only rules out $n\geq 3$ odd.  There is a proof using characteristic classes which rules out any $n$ which is not a power of $2$, but ruling out $16,32, ...$ is much harder and was first accomplished by Adams.


rsElementTypeMismatch error When I Edit Subscription

Question: I updated the scheduling options in Step 7 of a data-driven subscription. The subscription did not execute at the specified time - no error message was  displayed. When I clicked "Edit", the following message appears:
"The value provided for the StartDateTime field is not valid for its type. It cannot be converted from a string value to the type that is required. (rsElementTypeMismatch)"
I have since run the subscription directly from its SQL Agent job. The dates and times in the job are valid.
Searching on "rsElementTypeMismatch" has not proven useful - I have reviewed most MSDN pages, MSSQLTIPS, etc. related to this error but they do not allow me to edit the actual subscription.
StartDateTime does not exist within the report, datasets or underlying SQL code. Nor can I find it as a column within the ReportServer tables.
Any suggestions on some useful info related to "rsElementTypeMismatch" or the error in general would be greatly appreciated.
Using SSRS 2008 R2.
Thank you
Answer: I have had a similar problem myself, and from the research I have done it appears to be a mismatch between the locality settings of the PC (Internet Explorer), from which the report is run from, the server on which SSRS is installed or the Database server that the data is pulled from.
In my instance a server upgrade had been carried out and one server had a locality set as English (Which is American English), and the remainder where British English.
This error is to do with the way each locality deals with dates. America language shows dates as MM/DD/YYYY, while British Language shows dates as DD/MM/YYYY.
Applications wont allow for example the 30th day to be a month, so it throws it out.
I was unable to edit the subscription and had to recreate it from scratch.
The StartDateTime Field you are receiving the error on, may be on the actual report or within a parameter on the report.


Como verificar se um item está contido em um array?

Question: O que estou fazendo errado nesse if?
if (angular.uppercase(nome[id]) in ['A', 'E','I', 'O', 'U']) {
    ....
}

Se eu fizer somente assim funciona. Mas vou ter que repetir para os outros.
if (angular.uppercase(nome[id]) == 'A'){
    .....
}

Estou usando esse código dentro do meu controller.
$scope.verificaVogal = function(nome) {
  var dados = {};
  for (id = 0; id < nome.length; id++) {
    if (angular.uppercase(nome[id]) in ['A', 'E', 'I', 'O', 'U']) {
      dados[id] = 'é vogal';
    } else {
      dados[id] = 'não é vogal';
    }
  }
  return dados;
}

Agradeço pela ajuda!!
Answer: Você está utilizando o operador in incorretamente, a função dele é retornar true se a propriedade especificada estiver no objeto especificado. No seu caso você está trabalhando com um array e não um objeto.

The in operator returns true if the specified property is in the specified object.

Fonte: in operator (MDN)
Para verificar se um item está contido num array, que parece ter sido a sua intenção, será necessário utilizar o método indexOf da seguinte forma:
if (['A', 'E', 'I', 'O', 'U'].indexOf(angular.uppercase(nome[id])) != -1) {
    dados[id] = 'é vogal';
} else {
    dados[id] = 'não é vogal';
}

Comment: Obrigado pela ajuda Zignd!!!
Answer: Tente fazer assim:
$scope.verificaVogal = function(nome) {
  var dados = {};
  for (id = 0; id < nome.length; id++) {
    if (angular.uppercase(nome[id]) in {'A':'', 'E':'', 'I':'', 'O':'', 'U':''}) {
      dados[id] = 'é vogal';
    } else {
      dados[id] = 'não é vogal';
    }
  }
  return dados;
}

Fica um pouco "feio" desse modo, mas é funcional. Teste no seu código.
O operador in do javascript é utilizado para a verificação de chaves em objetos e no seu caso você possui um array.
Uma verificação em arrays é realmente feita da maneira que o @Zignd falou. Mas você também pode transformar as matrizes (arrays) em objetos com a seguinte função:
function toObject(array){
  var object = {};
  for(var i = 0; i < array.length; i++){
    object[array[i]]='';
  }
  return object;
}

Com isso, basta fazer assim:
if (angular.uppercase(nome[id]) in toObject(['A', 'E', 'I', 'O', 'U'])) {
  dados[id] = 'é vogal';
} else {
  dados[id] = 'não é vogal';
}

Comment: Obrigado pela ajuda Samir Braga!!!
Answer: Já foi dito a maior parte nas outras respostas. Deixo uma outra resposta com algumas coisas ainda não ditas.
Nota que quando usas for (id = 0; id estás a declarar essa variável globalmente e podes estar a sobrescrever valores nas outras variáveis que possam ter o mesmo nome. Junta sempre var em for (var i = ....
No teu código estás a criar um objeto com index numerário. Nesse caso vais ter algo como
{
    0: 'string',
    1: 'outra string',
    etc...

e sendo assim parece-me mais semântico (ie mais correto) mapear a string inicial.  Deixo também uma sugestão com regex, que dispensa o .indexOf e uppercase.
Nesse caso o código que queres poderia ser assim:
$scope.verificaVogal = function(nome) {
    var vogais = ['A', 'E', 'I', 'O', 'U'];
    return nome.split('').map(function(letra) {
        return vogais.indexOf(angular.uppercase(letra) != -1);
    });
}

ou assim:
$scope.verificaVogal = function(nome) {
    return nome.match(/[aeiou]/i);
}

Nota: se usares a primeira variante, eu prefiro assim:
(function(){
    var vogais = ['a', 'e', 'i', 'o', 'u'];
    $scope.verificaVogal = function(nome) {
        return nome.split('').map(function(letra) {
                return vogais.indexOf(letra.toLowerCase()) != -1);
        });
    }
})();

para diminuir sempre que possível código não nativo e para não declarar constantes dentro da função.
Comment: Obrigado pela ajuda Sergio!!!


Get Icy metadata from audio stream with Exoplayer2 without using duplicate streams

Question: I thought I found a way to do this, but it seems like this is for exoplayer1 (the first answer to this question):  Extracting metadata from Icecast stream using Exoplayer
I already have a way to read Icy metadata, but it uses a stream of it's own, so it creates extra data costs for the user.
How can this be done just using one instance of the stream?
Answer: This can be done easily by registering a listener for your ExoPlayer instance:
<code>exoPlayer.addListener(new Player.Listener() {
    @Override
    public void onMediaMetadataChanged(MediaMetadata mediaMetadata) {
        String title = (String)mediaMetadata.title; // This is the artist / song
    }
}
</code>


numpy.subtract performs subtraction wrong on 1-dimensional arrays

Question:
I read the post is-floating-point-math-broken and get Why it
happens, but I couldn't find a solution that could help me..
How can I do the correct subtraction?

Python version 2.6.6, Numpy version 1.4.1.
I have two numpy.ndarray each one contain float32 values, origin and new. I'm trying to use numpy.subtract to subtract them but I get the following (odd) result:
>>> import numpy as
>>> with open('base_R.l_BSREM_S.9.1_001.bin', 'r+') as fid:
        origin = np.fromfile(fid, np.float32)
>>> with open('new_R.l_BSREM_S.9.1_001.bin', 'r+') as fid:
        new = np.fromfile(fid, np.float32)
>>> diff = np.subtract(origin, new)
>>> origin[5184939]
0.10000000149011611938
>>> new[5184939]
0.00000000023283064365
>>> diff[5184939]
0.10000000149011611938

Also when I try to subtract the arrays at 5184939 I get the same result as diff[5184939]
>>> origin[5184939] - new[5184939]
0.10000000149011611938

But when I do the following I get this results:
>>> 0.10000000149011611938 - 0.00000000023283064365
0.10000000125728548

and that's not equal to diff[5184939]
How the right subtraction can be done? (0.10000000125728548 is the one that I need)
Please help, and Thanks in advance
Comment: The proposed duplicate http://stackoverflow.com/questions/588004/is-floating-point-math-broken may explain why you can differing floating representations, but does not explain the difference in this case.  Unduplicated.
Answer: You might add your Python and numpy versions to the question.
Differences can arise from np.float32 v np.float64 dtype, the default Python float type, as well as display standards.  numpy uses different display rounding than the underlying Python.
The subtraction itself does not differ.
I can reproduce the 0.10000000125728548 value, which may also display as 0.1 (out 8 decimals).
I'm not sure where the 0.10000000149011611938 comes from.  That looks as though new[5184939] was identically 0, not just something small like 0.00000000023283064365.


Are repeated octaves permissable in four-part SATB?

Question: I am writing a four-part SATB (soprano, alto, tenor, bass) and wanted to know if repeated (that is, successive) octaves are permissible?
I know that parallel fifths/octaves are not allowed, but what about successive fifths and octaves?
Comment: Great question -- my students got confused by this every year until I started putting it in bold type on the assignments. Use the term "oblique octaves" instead of successive, since that's a term others use to mean parallel.
Comment: @MichaelScottCuthbert I've started saying in class that we're only concerned with parallel *motion*. If there's no motion then there can't be any errors. The only problem with the term "oblique octaves" is that, on its face, it isn't possible. Oblique motion involves one voice holding or repeating while the other voice moves, so it always involves a change of interval. Maybe "repeated octaves" would underline the difference? I don't know, no matter how I try to cover it, this is a perennial source of confusion for students.
Comment: Do you mean repeating the same octave?  Yes that's fine.
Comment: "repeated octaves on the same pitch"? a mouthful, but I'm afraid that repeated octaves alone might mean "C-C to D-D" ("I repeated the use of octaves! Prof. Muchmore said it was okay!")  you're totally right that oblique isn't the right work either.  In my computer programming of music theory I use SIMILAR, CONTRARY, OBLIQUE, and NO_MOTION to distinguish the four kinds (with parallel a subset of similar).
Answer: Yes, they are, and many authorities seem to consider this so utterly obvious that they never even mention it. (Tripped me up big time when doing a music test right after changing schools, once.)
Comment: Yeah, things that people consider too obvious to mention often lead to the biggest blunders by students (so let's mention them!) -- I remember in my first year of playing clarinet getting screamed at for changing from F# to F-natural for the second note of a tie that went over the barline.  I was told accidentals only carried through one bar -- how was I to know that it was "too obvious to mention" the exception for tied notes?
Comment: @MichaelScottCuthbert: Unfortunately, a lot of people are told that the difference between a tie and a slur is that the former connects two notes that the same pitch, while the latter connects notes at different pitches, but in quality printed music ties should be horizontally confined to the spaces between notes, while slurs should generally extend into the space above or below the notes being connected, and people hand-writing music should typically follow that convention as well.


Solve the differential equation: $-x^2 y'' = \lambda y$

Question: I need to solve the differential equation  $-x^2 y'' = \lambda y$ by transforming the differential equation to a equation with constant coefficients. I need to do this by using $f(x) = y(e^x)$. If I do this, I become the equation:
$y''(e^x) + \frac{y'(e^x)}{e^x}+ \frac{\lambda y(e^x)}{(e^x)^2} = 0$
The I find a general solation of: $$y(e^x) = C \exp\left(\frac{-1+\sqrt{1- \frac{4\lambda}{x^2}}}{2(e^x)^2}\right) + C \exp\left(\frac{-1-\sqrt{1- \frac{4\lambda}{x^2}}}{2(e^x)^2}\right) $$
But Wolfram alpha gives the solution:
$$y(x) = c x^{\frac{1}{2} + \frac{1}{2}*\sqrt{1-4\lambda}} + c x^{\frac{1}{2} - \frac{1}{2}*\sqrt{1-4\lambda}}  $$
Can someone help me figure this out?
Comment: https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
Answer: It is true that the given ODE can be transformed into an equation with constant coefficients by substituting $x:=e^t$. But the necessary computations are  and not at all straightforward, hence error prone.
Consider your equation as a Eulerian ODE instead, and use the "Ansatz" $y(x):=x^\alpha$, with $\alpha\in{\mathbb C}$ to be determined. This leads to
$$-x^2\cdot \alpha(\alpha-1)x^{\alpha-2}=\lambda x^{\alpha}\ ,$$
hence to the "characteristic equation"
$$\alpha^2-\alpha+\lambda=0\ .$$
This equation has the two solutions ${1\over2}\bigl(1\pm\sqrt{1-4\lambda}\bigr)$ and leads to the following general solution of the given ODE:
$$y(x)=C_1 x^{(1+\sqrt{1-4\lambda})/2}+C_2x^{(1-\sqrt{1-4\lambda})/2}\ .$$
If these are real, fine. Otherwise addditional measures (via complex exponentials) are necessary.
For the desired transformation define
$$z(t):=y(e^t)$$ and compute, using the chain rule,
$$\dot z(t)=y'(e^t)\>e^t,\qquad \ddot z(t)=y''(e^t)\>e^{2t}+y'(e^t)\>e^t=-\lambda z(t)+\dot z(t)\ .$$
It folows that $t\mapsto z(t)$ satisfies the constant coefficient equation
$$\ddot z-\dot z+\lambda z=0\ .$$
Comment: This certainly is a good solution but the exercise really said it was preferable to use the transformation $f(x):= (e^x)$. How would it look like if you use this transformation or is it impossible? But this method seems to be easier by the way.
Answer: It is true that using $f(X)=y(e^X)$ allows to transform the ODE into an ODE with constant coefficients, but with a little trick at first beginning :
$f(X)=y(e^X)$ is valid any symbol of variable, for example  $f(t)=y(e^t)$
Let $e^t=x \quad\to\quad f(t)=y(x)$
$dx=e^tdt=xdt \quad\to\quad \frac{dt}{dx}=\frac{1}{x}$
$\frac{dy}{dx}=\frac{df}{dt}\frac{dt}{dx}=\frac{1}{x}\frac{df}{dt}$
$\frac{d^2y}{dx^2}=\frac{d\left(\frac{1}{x}\frac{df}{dt}\right)}{dx} =
-\frac{1}{x^2}\frac{df}{dt}+\frac{1}{x}\frac{d^2f}{dt^2}\frac{dt}{dx}=
-\frac{1}{x^2}\frac{df}{dt}+\frac{1}{x^2}\frac{d^2f}{dt^2}$
$-x^2\frac{d^2y}{dx^2}=\lambda y=x^2\left(-\frac{1}{x^2}\frac{df}{dt}+\frac{1}{x^2}\frac{d^2f}{dt^2}\right)= -\frac{df}{dt}+\frac{d^2f}{dt^2}$
$$\frac{d^2f}{dt^2}-\frac{df}{dt}-\lambda f(t)=0$$
This is a linear ODE with constant coefficients easy to solve.
$$f(t)= c_1e^{\frac{1+\sqrt{4\lambda+1}}{2}t}+c_2e^{\frac{1-\sqrt{4\lambda+1}}{2}t}=c_1(e^t)^{\frac{1+\sqrt{4\lambda+1}}{2}}+c_2(e^t)^{\frac{1-\sqrt{4\lambda+1}}{2}} $$
$$y(x)=c_1 x^{\frac{1+\sqrt{4\lambda+1}}{2}}+c_2x^{\frac{1-\sqrt{4\lambda+1}}{2}}$$


Multiple instances of systemd unit not writing to log files

Question: I'm trying to create a systemd unit file that will take an argument for a php script.
The small php script:
<?php
$val = $argv[1];

while(true) {
        echo "Argument = $val\n";
        sleep(1);
}
?>

Devs are working on the real script. All I need to do to test is take an argument, which is passed in the systemd unit file. Here it is:
test-systemd-params@.service
[Unit]
Description=Systemd Params Test
Wants=network-online.target
After=network-online.target

[Service]
Environment=ARGS=%I
ExecStart=/usr/bin/php /home/myself/test_systemd.php $ARGS
StandardOutput=file:/var/log/test-multiple-systemd-$ARGS.log

[Install]
#Start after boot
WantedBy=multi-user.target

I start the multiple instances with systemctl start firstname.lastname@example.com and systemctl start email@example.com. When checking the services, I see:
root@servername:/lib/systemd/system# systemctl --type=service | grep test
firstname.lastname@example.com      loaded active running Systemd Params Test
email@example.com      loaded active running Systemd Params Test

It is not creating the different log files. It's only creating a single one, strangely with quotes around it:
-rw-r--r--  1 root      root     285 Dec  8 08:15 'test-multiple-systemd-$ARGS.log'
And the content of the log file is mostly "Argument = bar". Only a few instances of "Argument = foo" for some reason:
cat /var/log/test-multiple-systemd-\$ARGS.log
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = bar
Argument = foo <--- WHY???
Argument = foo
Argument = foo
Argument = foo
Argument = foo
Argument = foo

Is it possible to write to different log files for each instance of the systemd unit? I would like to see test-multiple-systemd-foo.log and test-multiple-systemd-bar.log if those are the arguments I pass. I've tried escaping the $ in the log path to no avail. I've tried removing and adding quotes to the Environment="$ARGS=%I" also to no avail. The log always shows with quotes with the literal "$ARGS" in the name.
UPDATE
It appears I cannot create the multiple log files dynamically, per this answer.
So, I created the log writing in the php script with:
echo file_put_contents("/var/log/test-multiple-systemd-$val.log", "Argument=$val", FILE_APPEND);
Will this suffice? I'm getting the multiple log files now and they are writing the argument correctly to the log file.
Comment: While starting a file from your script works, I would say that using the systemwide /var/log directory for a bash script could be unsafe, and you still have to contend with unexpected stderr/stdout coming from the script. Did you consider just using the journal and `systemd-cat` or `logger` in your script?
Comment: This is not a permanent log path. I'm just testing on a dev server. :) The logs are in a subdirectory of /var/log/. They've existed for quite some time, but now they're wanting multiple instances of the same script.
Comment: It probably doesn't make sense to put the ARGS into the environment, if you already include this info on the ExecStart line. Just use '%i" in the ExecStart line and be done with it.  Prefer %i here, because otherwise you could have an escape of the quotes and unwanted globbing and word splitting by the shell. Not an issue if you only use numbers, but higly recommended for more general usage of these methods of passing the instance variable.
Comment: Also look here for an idea how to package your instances into a target that can run a defined set of them: https://www.stevenrombauts.be/2019/01/run-multiple-instances-of-the-same-systemd-unit/
Answer: You should fix your .service file for several log files. Variables should be with braces {}. Like this:
ExecStart=/usr/bin/php /home/myself/test_systemd.php ${ARGS}
StandardOutput=file:/var/log/test-multiple-systemd-${ARGS}.log


SEO for possible duplicate content

Question: Website is about bands and musicians.
Musician can create the profile and add his bio.
Band can create profile and add band members and their bio.
Many musicians are members of several bands, so i will have bio of XY repeated on several pages of my website.
Any idea how to control this since site will be made and controlled more or less by users ?
Comment: How would you solve it for a non-Drupal site?
Comment: I have no idea. I am only using Drupal, and i learned a lot about SEO and am paying a lot of attention to it, my other sites are doing fine on Google. This is first time i have to deal with this as i am not the one who will create content and therefore i can not stop this from happening i guess.
Comment: For the band profile section on a musician's profile page, I'd probably just show a summary of the full profile, then link to the separate band profile page for each - especially if there may be multiple bands for each member profile.
Answer: I think the answer relies on the way you organize your content. I imagine bands could be a content type, with fields like bio, discography, pictures, videos and whatever, and a field with multiple values to add users, beeing the band musicians.
The users get their own fields from which bio. Then you can display a list of teasers of musicians in the band node, with a link to complete profile and bio.
EDIT : (for lazy or busy musicians :) I guess NY Big Band staff i.e knows all members's emails, names...

Create a role "band manager" with the rights to create user accounts
When an account is created by this role, set up a rule to send an automatic email to notify the musician,  that an account has been created for him and he's welcome to check if his information is correct.

This way you 'll have a unique "musician content", without SEO duplicate problems, and you 'll also improve the involvement of musicians in your website.
Comment: You are about right except the part where band can link to complete musician profile and bio. There will be many cases where bands will create profiles before musician from that band does it and vice versa. Example: New York Big Band has 25 members. Lets say half of band members will create their own profiles, while half don't care and will never do it, or they have it on some other website and won't bother doing it again on
Comment: I edited the answer for that point also.

SEO for possible duplicate content


Is there a Swing implementation of a "rearrangable accordian" component? Or what is it called?

Question: Basically there can be one or more of these controls with panels in them, and the panels can be dragged between them, or slide within the control to change positions, minimized, or closed.

Blue area can have scroll bars if shrunk too small.
Is there a name for this? And is there a Java swing implementation of it I can try?
EDIT: some examples of what I'm talking about.
EDIT: found the term "accordion", updated title to better reflect question and still looking for correct name for what I'm describing, if there is one.
Comment: [How to Use Internal Frames](https://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html)
Comment: Looks kind of like JInternalFrames held by a JDesktopPane.
Comment: @MadProgrammer I mean for them to be locked to the width of the vertical control they live in, unable to move left to right or hang off into nothingness, and can only slide and displace each other. Also these have "windowshading" collapse and are unable to overlap, as well as being compacted to the top of their column. Going to update the original post with some examples soon.
Comment: They are still `JInternalFrame`s in the concept of Swing.  You could utilise different layout managers or maybe a custom `DesktopManager` to implement your required functionality.  Otherwise, from Swing's perspective, nothing like that exists
Comment: @MadProgrammer Yeah, I figured it wasn't a standard control, but I've seen it often enough to hope it had a name. I'm looking for a library that implements it using swing, or the name of it so I can find one on my own. Failing that, I'll at least know what to call mine when I make it. I've enjoyed using it in the past and it seems to fit my application.  Also I have added those examples now.
Comment: As I said, you could fake it using `JInternalFrame`s and a custom Layout Manager and/or `DesktopManager`.  You could also have a look at the `JXCollapsiblePane` from [SwingLabs SwingX project](https://java.net/projects/swingx/downloads/directory/releases)
Comment: @MadProgrammer The stacked collapsible panes are called [accordions](https://en.wikipedia.org/wiki/Accordion_%28GUI%29). A typical accordion isn't rearrangeable though, so I'm still looking around.
Answer: The collapsible sub-panels, particularly in the blender example, fit the description of an accordion control. But most accordions can't have their panels re-arranged by dragging.


Integration with square root involved

Question: How to compute the integral of $\sqrt{1-r^2}$ with respect to $r$? Is there a substitution? What are the steps? Thanks
Answer: The standard substitution is
$$ r = \sin t \implies dr = \cos t dt$$
Hence
$$ \int \sqrt{1-r^2}  = \int \sqrt{1 - \sin^2 t } \cos t dt = \int \cos^2 t dt$$
and this is an easier integral since you can use the fact that
$$ \cos^2 t = \frac{1 - \cos 2t}{2} $$
Comment: Almost the same as mine...deleting it, upvoting this one. +1
Comment: Don!! Soy DonAnselmo... Como estas? a los siglos. :)
Comment: Ah, cambiaste de nombre...¿por qué? Yo bien, y espero que tú también. Un abrazo.

Integration with square root involved


Getting error '_http_outgoing.js:335' while sending API response from backend to frontend

Question: In my Angular/Node application, I am calling a 3rd party API in the Node.js backend and I am facing an error while sending data to the Angular.js frontend.
Here's the relevant part of my Node.js code:
app.use('/callApi', function(req, res, next) {

    var result;

    var url = 'http://someApi.com/someData';

    http.get(url, function(resp) {
        var body = '';

        resp.on('data', function(chunk) {
            body += chunk;
            console.log("Got body: " + body);
        });

        resp.on('end', function() {
            console.log("Got response: " + body);   // WORKS!

            // res.setHeader("Content-Type", "text/html");
            // res.send(body);                      // DOES NOT WORK!

            sendResult(body);                       // DOES NOT WORK!
        });
    }).on('error', function(e) {
        console.log("Got error: ", e);
    });

    function sendResult(result){
        res.send(result);
    };

    res.send('about done');                         // WORKS!

    next();
});

In the Node.js terminal, I see the response followed by an error:
_http_outgoing.js:335

... and the Node.js process gets terminated.
I dont see this _http_outgoing.js file anywhere in my project.
Can anyone please point me in the right direction?
Comment: There should be more to the error than just the built-in filename and line number, such as the actual exception message and more stack trace lines. Did you try adding an error handling middleware?
Comment: Also, what version of node are you using?
Comment: @mscdex I wish there was more to that error. How do I add a error handling middleware?  I am using `node v0.12.4`.
Comment: You add one by adding a middleware with 4 parameters: `app.use(function(err, req, res, next) { console.error(err.stack) })`
Answer: FWIW the actual error is Can't set headers after they are sent.
The problem is that you're calling next() at the end of your route handler. So some other middleware or route handler is also handling the request and already sending a response before your http.get() finishes.
Remove that next() and responding to the request from inside the http.get() should work fine.


Get an Activity's Title in Android

Question: I'm looking for a way to retrieve an activity's title in Android Lollipop.
What I mean is not the process name or even the app's name, but the title that is given to the activity when it is open. For example, when you navigate to http://www.google.com/ in Chrome, the title changes from "Chrome" to "Google", which can be seen when you hit the recent apps button, and I need something that returns the word "Google".
Below is my awful attempt at looping through the currently running apps and trying to find that information.
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();

    for (int i = 0; i < runningAppProcessInfo.size(); i++) {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo info = null;
        try {
            info = pm.getApplicationInfo(runningAppProcessInfo.get(i).processName, 0);
            Log.i("DEBUG_LABEL", "Process Name: " + runningAppProcessInfo.get(i).processName);
            Log.i("DEBUG_LABEL", "App Label: " + pm.getApplicationLabel(info).toString());
            if (info.className != null) {
                Log.i("DEBUG_LABEL", "Info's package and class name: " + info.packageName + ", " + info.className);
                ComponentName cName = new ComponentName(info.packageName, info.className);
                ActivityInfo activityInfo = pm.getActivityInfo(cName, PackageManager.GET_META_DATA);
                Log.i("DEBUG_LABEL", "Activity Label: " + activityInfo.loadLabel(pm));
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

Comment: Is this your app or ALL apps?
Comment: This is supposed to work for all apps(ideally)
Comment: http://stackoverflow.com/questions/11391451/list-out-installed-running-applications-in-android-programmatically
Comment: That's not overly helpful. The second method in the link is similar to what I was doing, so I just tried the first method with `queryIntentActivities()` and while I got the Activity, calling `loadLabel()` just gave me "Chrome". I'd like sure-fire way to get the *same* title that's being shown in the recent apps screen
Answer: Apparently what I was looking for was the description of the Task.
List<ActivityManager.RunningTaskInfo> rTaskInfoList = am.getRunningTasks(100);

...

return rTaskInfoList.get(i).description.toString() // Returns "Google", instead of "Chrome"

Get an Activity's Title in Android


Accessing a parent's component from inside a nested child's component without rendering child's HTML in parent

Question: I am trying to access the my parents component variables and methods by doing the following but getting an error message saying:
error_handler.js:57 ORIGINAL EXCEPTION: Cannot read property 'getSelectedRow' of undefined

I am trying to accomplish this by doing the following:
Parent Component:
get self(): SearchComponent{
        return this;
    }

Method trying to be accessed from child:
getSelectedRow():string {

        if(this.ssn != null){
            return this.ssn;
        }

        return "";

    }

Parent's HTML:
<user-form [setUserSsn]="self"></user-form>

Childs component:
@Component({
    selector: 'user-form',
    templateUrl: 'userForm.html',
    styleUrls: ['./userForm.css']

})
export class UserFormComponent {

    private _parentComponent: SearchComponent;

    @Input()
    setUserSsn(parent: SearchComponent){
        this._parentComponent = parent;
    }

    ssn = this._parentComponent.getSelectedRow();
}

-----------Update 1--------------------
I have tried a new approach but now I am getting the error:
Cannot read property 'getSsnFromSelectedRow' of undefined

methods in parent component:
setClickedRow(user:User) {

        let ssn = user.ssn;

        this.setSsnForUsersForm(ssn);

        console.log("SSN: "+user.ssn);
    }

    setSsnForUsersForm(ssn:string){
        this.ssnForUsersForm = ssn;
    }

    getSsnFromSelectedRow():string{
        return this.ssnForUsersForm;
    }

call in child component
ssn = this._parentComponent.getSsnFromSelectedRow();

------------------Update 2--------------------------
I guess I need a @Directive but I do not think I am using it correctly.
child component
@Component({
    selector: 'user-form',
    templateUrl: 'userForm.html',
    styleUrls: ['./userForm.css']

})
@Directive({selector: '[userSsn]'})
export class UserFormComponent {

}

parent.html

                    {{data.ssn}}
                    {{data.userId}}
                    {{data.lastName}}
                    {{data.office}}
                    {{data.role}}

Now when the user selects a row the child component with know the ssn of the row selected. However it is not working still.
--------------------Update 3---------------
Error:
Can't bind to 'parent' since it isn't a known property of 'div'. ("

][parent]="self">

</div

Child Component
@Component({
    selector: 'user-form',
    templateUrl: 'userForm.html',
    styleUrls: ['./userForm.css']

})
@Directive({selector: '[userForm]'})
export class UserFormComponent implements OnInit  {

    @Input('parent') _parentComponent: SearchComponent;

    private ssn: string;

    ngOnInit() {
        this.ssn = this._parentComponent.getSsnFromSelectedRow();
    }

}

parent html

Comment: Your parent component is undefined bc u set it before it is passed through to your child. Wrap the setter in the ngOnInit function.. though this whole passing the parent thing is generally bad
Comment: If you want the parent do something triggered by the child, then define an event (using @Output()) in the child and then catch the event in the template of the parent
Answer: @tam5 is right. The problem is that you are trying to read an object before is assigned.
ssn = this._parentComponent.getSelectedRow(); // at this point your setUserSsn hasn't being called yet.
One possible approach is to implement ngOnInit like this, although there are better approaches https://angular.io/docs/ts/latest/cookbook/component-communication.html :
import { OnInit } from '@angular/core';
// other imports here

export class UserFormComponent implements OnInit {

    private _parentComponent: SearchComponent;
    private ssn: string;

    @Input()
    setUserSsn(parent: SearchComponent){
        this._parentComponent = parent;
    }

    ngOnInit() {
       this.ssn = this._parentComponent.getSelectedRow();
    }
}

If you don't want to render the user form HTML in the parent then the most suitable approach will be a directive:
import { Directive, OnInit } from '@angular/core';
// other imports here

@Directive({
  selector: '[userForm]'
})
export class UserFormDirective implements OnInit {

  @Input('parent') _parentComponent: SearchComponent;

  private ssn: string;

  ngOnInit() {
    this.ssn = this._parentComponent.getSelectedRow();
  }
}

Then you can use it like this:

Comment: This does get rid of the error but I do NOT want the HTML to render in the parent at all.
Comment: I don't understand what your original question has to do with what you are saying now. If you define a component in your Parent's HTML:  then userForm.html will render in Parent's HTML. I'm really confused now.
Comment: There is a variable in parent that I want to pass to my child without rendering HTML that is the end goal.
Comment: You need a directive then not a component
Comment: You need to add the directive to the module declarations https://angular.io/docs/ts/latest/guide/attribute-directives.html
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/136577/discussion-between-drew1208-and-artemisian).
Answer: You could pass just the selectedRow via @input(), I think sending the hole component isn't good for performace.
Something like that:
Parent's HTML:
<user-form [ssn]="ssn"></user-form>

Childs component:
@Component({
    selector: 'user-form',
    templateUrl: 'userForm.html',
    styleUrls: ['./userForm.css']

})
export class UserFormComponent {
    // starts as an empty string to avoid missing parameters issues
    @Input() ssn: string = '';

}

Comment: I do not was the HTML from the child's component to render in the parents. Your above method does exactly that. Thank you for your efforts. Once a row is clicked in a `*ngFor` there is a `routerLink=` and the child needs to know the `ssn`


How does Outlook identify "Extra Line Breaks"

Question: I am writing a script that emails the output to me, and I read it in Outlook.  For some reason Outlook removes all the line breaks in the message, and gives me a little notice that it has removed the extra line breaks from the message
How can I fix my message so that Outlook doesn't remove  the line breaks?

Outlook displays other messages fine (with correct line breaks)
I have tried all these things with sed - s/$/\r/  s/$/\n/  s/\r\n/\n/  s/\n\r/\n/  s/$/^M/  - with no luck

What does Outlook expect at the end of a line?
Comment: I'm thinking.. shouldn't programming questions be posted in stackoverflow instead?
Comment: I put it here because I thought it would be more applicable to sysadmins than programmers.
Answer: Not sure about what it's looking for, but how about configuring Outlook to not remove them?
Tools -> Options -> Preferences Tab -> click E-mail Options button -> uncheck the box
Another option (albeit not ideal and maybe not even the case for your msgs):

Open Outlook.
Open the item.
Click Format.
Click to clear the Unwrap Text check mark.

And here's a post that says that a hack you can use would be to add 2 empty characters to the beginning of each line of text in order to make Outlook not remove the breaks.
Additionally see here for a better layout, add at least 3 spaces at the end of every line (incl. empty lines).
Comment: He's asking how Outlook parses the mails, not how he can shut off the behaviour in Outlook.
Comment: Yeah, I know.  But frequently other suggestions end up working better than the requested functionality.  I also posted a hack more toward what he was asking.
Comment: Dude.  The problem is "Outlook is misbehaving", not "the message is broken".  Fix the Outlook problem.
Comment: See also http://serverfault.com/questions/26004/getting-correct-linefeeds-in-emails-generated-from-linux
Comment: Ok - you edited and it looks a bit more helpful now, I'm taking my -1 back
Comment: That hack of adding 2 spaces to the beginning of each line works great!  I just did sed "s/^/  /" before the mail command.
Comment: I think that's right, I had a similar problem with Pegasus mail.  Make sure still generate line breaks because there is a maximum line length at which your line will just be truncated.
Comment: @pauska: BTW - Thanks for explaining the downvote earlier!  Kinda bugs me when people don't do that...
Comment: see https://stackoverflow.com/a/1638608/1498669 and add at least 3 spaces at the end - better for layout :)


What user account should we use for scheduled tasks on a server with sensitive material?

Question: I'm working in a team with 10 developers. We have servers set up which performs backup, automated build of software, automated deployment and more. Some of these servers contains sensentive material, such as login details to production systems (which is required for automated deployment).
We want to limit who has access to these machines to reduce the risk of passwords leaking out accidentally. To do this, we created a group in Active Directory containing 4 persons who are allowed to access the servers containing the sensitive material and made sure that only these 4 users could log on.
Some of these servers run scheduled tasks and Windows services to perform backup/deployment. These tasks/services run under a specific "shared" user account, let's call it "buildacc". The reason for this is that the tasks require access to shared resources in the network to be able to perform build/deployment. So we gave this user access to the servers as well.
To be able to modify the scheduled tasks in Windows, all 4 developers needs to have access to this "buildacc" account, which means that they all have to know the shared password and inform eachother when it's changed which we don't like the idea of.
We've considered using personal accounts to run scheduled tasks such as the script for building. The downside we see is that any member in the team can change the build script and make it do new things under the user account who configured the actual scheduled task.
Is there any best practices on how to handle this situation?
Comment: What version of Windows Server are you using ?
Comment: 2008 R2 SP1 at the moment, but if a Windows Server 2012 solves this in a better way we can probably upgrade.
Comment: 2008R2 will do, as long as your DCs are also R2 and so is your domain functionality level.
Answer: Overall what you've done up front is fine.  A dedicated "service" style account that is setup with the permissions it needs and is used to run the scheduled tasks.
At this point, all you really need to do is:

Change the password to buildacc
Don't let the 4 developers know the password
Assign someone the task of changing the scripts/tasks going forward (ie. Change Control policies) after the developers change their code.

It's really just an internal policy issue at this point.  You should setup the scheduled tasks so that they don't really change.  Meaning if it is running "test.exe" then have the developers modify that exe file but not the scheduled task itself.  If all 4 of the developers truly need access to change the scheduled tasks then you are simply stuck where you are...
EDIT:  I'd also caution you on being too liberal with your buildacc account across services and servers.  Better to keep it strictly for "builds" and have backups and other services run under their own dedicated accounts.
Comment: Dedicated "service" accounts typically don't get "logged into" and scheduled tasks typically don't change frequently.  If the 4 devs are using this account for their daily work then you can't really prevent "they all have to know the shared password and inform each other when it's changed which we don't like the idea of."  What type of solution were you hoping to achieve?
Comment: Considering people need vacation, get sick and so on, at least 2 persons needs the login details for the buildacc account. If we have three such "shared" accounts, that means that every person will need to remember 2-3 shared passwords and to coordinate with eachother when it changes. I don't feel this is really a great solution.
Comment: Something better. Please see Stephane's answer which seems to be better.
Comment: An MSA doesn't prevent "The downside we see is that any member in the team can change the build script and make it do new things under the user account who configured the actual scheduled task.".  You also stated that the `buildacc` account is used on multiple computers.  MSA's exist only on a single computer.
Comment: @TheCleaner That is correct, but a different problem alltogether. Basically, if the users need to change the script you run, there are only two ways around it: don't run the script in a context that has more access than the user himself or force an audit good enough to trace. In this situation, the typical solution is to place the build script under source control and have the build server automatically pull the latest version from SVN before running it: you have a proper audit trail.
Answer: Assuming you are using a Windows 2008R2 system and a 2008R2 AD, you can use a managed service account for this.
This technet blog entry has a pretty good summary of how to use managed service accounts but, here are the basic principles:
A managed service account is an AD account that is strongly tied to a computer and that has an automatically managed password. You don't create the password and nobody needs to know about it but since it's an AD account, you can use it for network ACLs which makes it perfect for your scenario.
Using a MSA for a scheduled task will, however, require you to use the command-line to create your tasks (see this and this thread for more details).
Answer: I see several answers mentioning MSA as a solution for the account used to run a scheduled task but as mentioned by the author of this post, they use Windows Server 2008 R2 and according to my research, MSA on this OS can't be used to run scheduled tasks.
However, with Windows Server 2012, a gMSA (Group Managed Service Account) can be used to run scheduled tasks as explained in this article.
Comment: Welcome to ServerFault. While the content of the article you linked may well be helpful, it's generally recommended on this site to include the relevant content from linked articles in your answer such that your answer doesn't explicitly rely on the links to be useful. Could you update your answer with the relevant info from the article please?
Comment: This is most likely the article being referenced:  https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/windows-server-2012-group-managed-service-accounts/ba-p/255910
Comment: Here in 2020 - article does no longer exist under the given URL.