$\int_{0}^{a}\left(\sum_{j=0}^{n-1}(-x)^j\right)^{b-1}\cdot\sum_{j=0}^{n-1}(jb+1)(-x)^j\mathrm dx=I$

Question: Consider

$$\int_{0}^{a}\left(\sum_{j=0}^{n-1}(-x)^j\right)^{b-1}\cdot\sum_{j=0}^{n-1}(jb+1)(-x)^j\mathrm dx=I\tag1$$
  How does one show that
  $$I=a(1-a+a^2-a^3+\cdots+a^{n-1})^{b}$$
  $(a,b)>0$

expanded
$$\int_{0}^{a}(1-x+x^2-\cdots-x^{n-1})^{b-1}(1-(b+1)x+(2b+1)x^2-\cdots[(n-1)b+1]x^{n-1})\mathrm dx=I$$

Assume $a<1$, then
$$\int_{0}^{a}(1+x)^{1-b}\cdot\sum_{j=0}^{\infty}(jb+1)(-x)^j\mathrm dx\tag2$$
But doesn't really help to prove $(1)$
Comment: Where the crap do you keep coming up with these problems 0_0 I mean, they are fun to solve, but you seem to have had an infinite supply recently
Comment: Go to work daily and ideas just happened to pop up while travelllling on the bus and train, so I wrote it down and start to work on it. Putting these ideas and formulas into my book and keep in the cupboard is quite dull and useless so might as well write it here.
Comment: Don't you get maths ideas come to you while travelling around @Brevan Ellefsen?
Comment: evidently not as much as yourself XD I'm bad at doing mental math, and I'm unable to keep track of symbols in my head very well. As such, I tend to invent most of my problems when I'm sitting down. When commuting somewhere I tend to think about problems I've already formulated.
Comment: Also, first step I would take on this problem is to take $-x \to x$. I fail to see why you chose to use $-x$ instead...
Comment: The first series is equal to $\frac{x^n - 1}{x-1}$ after the transformation
Comment: I have look through Wikipedia or wolfram to find the closed form for theses sums, but couldn't find any.
Comment: first one is a geometric series, second one is a modified geometric series (multiply the terms out and you find that it's a geometric series plus the derivative of a geometric series)
Comment: because we have closed forms for the geometric-like series in your post I'm fairly certain we can get a closed form... Biggest problem is definitely just the integral. How hard the function is to integrate will depend on what we get when we multiply the closed forms of the sums
Comment: my biggest fear is that we might get a quartic polynomial in the denominator, which are a beast to integrate (though always possible, at least when the numerator is a polynomial)
Answer: Define $f(x) = \sum_{j=0}^{n-1}(-x)^j$ then the integral can be written
$$I(a) = \int_{0}^{a}f(x)^{b} + x\frac{d}{dx}f(x)^{b}{\rm d}x = \int_0^a\frac{d}{dx}\left[xf(x)^b\right]{\rm d}x = af(a)^b$$
Answer: Winther's answer is definitely the shortest way. Here I will detail out how we get there, and show what a solution would be like if were to actually try differentiation. We first run the substitution $-x \to x$ (not necessary at all, but it makes the geometric sum more obvious for beginners in my opinion)
$$\int_{0}^{a}\left(\sum_{j=0}^{n-1}x^j\right)^{b-1}\left(\sum_{j=0}^{n-1}(jb+1)x^j\right)\mathrm dx$$
We first note that, by the geometric series formula,
$$\sum_{j=0}^{n-1}x^j = \frac{x^n -1}{x-1}\tag{1}$$
We can also split the second sum into the form
$$b\sum_{j=0}^{n-1}jx^j+\sum_{j=0}^{n-1}x^j $$
The second sum is clearly the geometric series we had before; the first can be written as
$$b\sum_{j=0}^{n-1}jx^j=bx\sum_{j=0}^{n-1}\frac{d}{dx}\left(x^j\right)=bx\frac{d}{dx}\sum_{j=0}^{n-1}x^j \tag{2}$$
We can use $(1)$ and $(2)$ we can write the original problem as
$$\int_{0}^{a}\left(\frac{x^n -1}{x-1}\right)^{b-1}\left(bx\frac{d}{dx}\left(\frac{x^n -1}{x-1}\right)+\frac{x^n -1}{x-1}\right)\mathrm dx \tag{3}$$
If we try to actually differentiate we get
$$\int_{0}^{a}\frac{\left(\frac{x^n-1}{x-1}\right)^{b-1} \left(x^n ((bn-b+1) x-b n-1)+(b-1)
   x+1\right)}{(x-1)^2}\mathrm dx$$
This could be simplified, if you had the patience of a god. I will leave that up to you though, and just point out that we can write $(3)$ in the form
$$\int_{0}^{a}f(x)^{b-1}\left(bx\frac{d}{dx}f(x)+f(x)\right)\mathrm dx$$
$$=\int_{0}^{a} \left(bx\frac{d}{dx}f(x)f(x)^{b-1}+f(x)^b\right)\mathrm dx$$
$$=\int_{0}^{a} \bigg(bxf'(x)f(x)^{b-1}+f(x)^b\bigg)\mathrm dx$$
Applying the chain rule in reverse we find that $x\frac{d}{dx}f(x)^b = f(x)^{b-1}\cdot bxf'(x)$, and we apply this to gett
$$=\int_{0}^{a} \bigg(x\frac{d}{dx}f(x)^b+f(x)^b \bigg)\mathrm dx$$
Which leads us into Winther's answer


Dependência circular em API Rest com Spring Boot

Question: Estou me aventurando no desenvolvimento de uma API Rest usando Spring Boot, JPA com Hibernate e Maven para gerenciar os repositórios.
Na minha modelagem eu tenho uma classe Club:

@Entity
@Table( name = "CLUB")
public class Club {

   /**
    * Id da entidade
    */
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

    /**
    * Atual técnico do clube.
    */
   @OneToOne(mappedBy = "actualClub")
   private Coach coach;

   //Outros atributos, getters e setters
  }

que tem um relacionamento @OneToOne com a classe Coach:

@Entity
@Table(name = "COACH")
public class Coach extends Person {

   /**
    * Clube atual do técnico.
    */
   @OneToOne
   @JoinColumn(name = "CLUB_ID")
   private Club actualClub;

   //Outros atributos, getters e setters

}

A Classe Person tem alguns atributos adicionais, entre eles o id, que segue a mesma lógica implementada em Club.
Por fim, tenho também a classe ClubController para lidar com algumas requisições:

@RestController
public class ClubController {

   /**
    * Instância da classe de serviços da entidade Club
    */
   @Autowired
   private ClubService clubService;

   /**
    * Retorna JSON que representa o clube com o 'id' especificado.
    *
    * @param id Identificador do clube a ser buscado.
    * @return ResponseEntity Objeto com detalhes da requisição HTTP, como o Status.
    */
   @RequestMapping(value = "/clubs/{id}", produces = MediaType.APPLICATION_JSON_VALUE,
           method = RequestMethod.GET)
   public ResponseEntity<?> getClubById(@PathVariable Long id) {

      final Club club = this.clubService.findById(id);
      if (club != null) {
         return new ResponseEntity<>(club, HttpStatus.FOUND);
      } else {
         return new ResponseEntity<>("Não encontrado", HttpStatus.NOT_FOUND);
      }
   }

   /*Entre outros métodos...*/

}

O problema que estou tendo é que o JSON retornado possui uma relação circular entre Club e Coach. Ou seja, eu recebo os dados do clube, entre eles os dados do técnico. Dentro dos atributos do técnico há novamente os dados do clube e assim continua... x(
E isso certamente vai acontecer também quando eu for relacionar Clubcom Player mais adiante.
Uma solução que encontrei foi esta: Link. Que usa @JsonIdentityInfo na declaração das classes. Um problema que percebi nessa solução é o overhead de informações que nem sempre são necessárias. Por exemplo, quando for @OneToMany com Player, eu traria necessariamente todas as informações dos jogadores ao buscar por um clube.
Pesquisando mais um pouco, eu encontrei uma outra posível solução (ainda não testei) do próprio Sring: Spring HATEOAS. Dessa forma eu conseguiria adicionar links (href) para certos atributos, e só faria a requisição para obter mais informações se realmente fosse necessário. Mas vi também que o HATEOAS ainda possui algumas limitações.
Então minha dúvida é: qual seria a melhor abordagem para esses casos? Tem alguma outra opção?
Minha ideia mais pra frente é consumir essa API em um aplicativo iOS. (Isso pode ser importante para ajudar na resposta)
Comment: Detalhe 1: se a opção com `@JsonIdentityInfo` for a escolhida, eu teria que usar UUID para os campos @Id do JPA, conforme o Link detalha.

Detalhe 2: A API do Spotify usa uma abordagem parecida com o HATEOAS [link](https://api.spotify.com/v1/tracks/3f9zqUnrnIq0LANhmnaF0V), ao buscar uma **track**, há um campo `href` para o **artist**.
Answer: Eu trato essa referência da seguinte maneira.
No lado da associação que eu quero que seja gerado o json eu anoto o atributo com
@JsonManagedReference, e do outro lado eu anoto com @JsonBackReference.
Se na serialização do objeto for encontrado o @JsonBackReference, neste objeto esse atributo não será serializado pois o outro lado carregar essa responsabilidade,


Reset class attributes for testing

Question: I have a python class like this one:
class MyClass():
    class_att = 0

@classmethod
def increase_value(cls):
    att = att + 1

I want to prepare two tests for the class: in one of them it checks the initial value and in another one that it is increased with the method.
test_initial_value(self):
    self.assertEqual(MyClass.class_att, 0)

test_increase_value(self):
     MyClass.increase_value()
     self.assertEqual(MyClass.class_att, 1)

But there is a dependence between both tests, since first one will only pass if it is run before the second. So I would need to "reset" the class attributes. Is this possible? How could I do it?
Answer: It is good that you try to keep your tests independent.  In your particular case, you have several options.
Option 1: You can provide an explicit static init method to your class MyClass.  Such a method can then be used in your tests.
test_increase_value(self):
    MyClass.init()
    MyClass.increase_value()
    self.assertEqual(MyClass.class_att, 1)

This makes it unnecessary for your unit-tests to directly access the class's internals to bring back the class into is original state.  It may also be a good choice in case you find other reasons in your code to have such a possibility, not only for unit-testing reasons.
Option 2: Reset the class's state from your unit-tests, as was shown by Mebin Joe.  This makes your tests slightly less stable, because you are somehow duplicating the class's internals and thus have to change your tests is the class changes.  You can do it with setUp and teardown (which in this case would be preferrable), or directly from within each test (just for demonstration):
test_increase_value(self):
    MyClass.class_att = 0
    MyClass.increase_value()
    self.assertEqual(MyClass.class_att, class_att_before + 1)
    MyClass.class_att = 0 # bring back to initial state

Option 3: Write your tests such they also work reliably independent of the class's state:
test_increase_value(self):
    class_att_before = MyClass.class_att
    MyClass.increase_value()
    self.assertEqual(MyClass.class_att, class_att_before + 1)

This has a couple of disadvantages: The test code becomes harder to read, and it may not be easy to implement all desired test cases this way.
Summary: I would recommend to choose option 1, unless you really don't want such an init method.  Then, option 2 is preferrable over 3, for which I do not see many uses.
Answer: Reset variables to None, the total memory is cleared after every unittest.
Sample:
class TestEx(unittest.TestCase):

    def setUp(self):
        self.class_att = "value"

    def teardown(self):
        self.class_att = None

Comment: But class_att is an attribute of the class MyClass, not from the TestEx class. How could it work?
Comment: TestEx is just an example class for demonstration. Please feel free to refactor.

Reset class attributes for testing


Give non-administrator users acces to node-class

Question: I have installed "node-class" on my drupal webiste. As an administrator, i can assign a class now to a node, but other verified users can't...?
Comment: So, have you checked permission list? You know, the huge wall of checkboxes?
Answer: Here is a framework for a module to add that permission:
In your contrib module folder, add the folder node_class_perms and add these files within that folder:
node_class_perms.info
node_class_perms.module

in node_class_perms.info add this:
name = Node Class Perms
description = Alters permissions for Node Class.
core = 7.x
dependencies[] = node_class

in node_class_perms.module add this:
<?php

function node_class_perms_permission(){
  return array(
    'administer node classes' => array(
      'title' => t('Administer Node Classes'),
      'description' => t('Allows node classes to be added to nodes.'),
    ),
  );
}

function node_class_perms_form_alter(&$form, &$form_state, $form_id) {
  // Check form type && if user_access is ok
  if (isset($form['#node']) && ($form_id == $form['#node']->type . '_node_form') &&
    user_access('administer node classes')) {
    // Add form elements in vertical tab to node settings.
    if (!isset($form['node_class'])) {
      $form['node_class'] = array(
        '#type' => 'fieldset',
        '#title' => t('Node Class settings'),
        '#description' => t('Assign CSS classes to the node.'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#access' => user_access('administer node classes'),
        '#weight' => 80,
        '#tree' => TRUE,
        '#group' => 'additional_settings',
        '#tree' => TRUE,
        '#attributes' => array('class' => array('node-class-form'))
      );
    }

    // Get css attribute information
    $attributes = node_class_attributes($form['#node']);

    // Check CSS exists in DB to prepare SQL update
    if ($attributes) {
      $form['node_class']['existing_css'] = array(
        '#type' => 'hidden',
        '#value' => '1');
    }

    $form['node_class']['css_class'] = array(
      '#type' => 'textfield',
      '#title' => t('CSS class(es)'),
      '#default_value' => $attributes,
      '#description' => t('Separate classes with a space.'));
  }
}

Now install the module, then add the permission 'Administer Node Classes' to the role you want.
You can tighten the permissions if you want, but as the node edit form has already gone through a basic node-edit permission it really is not necessary.


How to create page like general->about->legal in iphone setting preferences

Question: i just want to create a page in setting preferences like the page which comes after pressing clicking on general -> about -> legal
help will be appreciated
Answer: There is some vagueness in your question: are you looking to have a page in the Settings app to set up preferences or are you looking to have a legal disclaimer (or the likes of it) in the Settings app?
If it is the latter, I would suggest that you investigate a little further on whether if it is appropriate based on the iOS Human Interface Guideline.
If it is the earlier, you can read more about it here. It would require you to use a Settings bundle and NSUserDefaults class to access it.


Melhor maneira de lidar com Exceptions

Question: Durante meus trabalhos eu aprendi uma forma de lidar com Exceptions, mas não sei se é muito boa. Aqui vai um exemplo do código:
class Program
{
    private static void Main(string[] args)
    {
        try
        {
            Foo();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message + Environment.NewLine + (ex.InnerException != null ? ex.InnerException.ToString() : String.Empty));
        }
        Console.ReadKey();
    }

    public static void Foo()
    {
        try
        {
            Bar();
        }
        catch (Exception ex)
        {
            throw new Exception("Erro no método Foo: " + Environment.NewLine + ex.Message + (ex.InnerException != null ? ex.InnerException.ToString() : String.Empty));
        }
    }

    public static void Bar()
    {
        try
        {
            DateTime? data = null;
            int x = data.Value.Day;//forçar uma exception de proposito
        }
        catch (Exception ex)
        {
            throw new Exception("Erro no método Bar:" + Environment.NewLine + ex.Message + (ex.InnerException != null ? ex.InnerException.ToString() : String.Empty));
        }
    }

}

A minha ideia é mapear os erros e jogar a responsabilidade de seu tratamento para o método principal.
Para ser mais objetivo vou direto as perguntas:

Gostaria de saber a opnião de vocês. Existe uma forma [melhor | correta] de propagar e exibir as exceções de forma simples? Essa é uma boa forma de lidar com Exceptions?
Qual a importância de capturar Exceptions mais especificas, por exemplo: DivideByZeroException?
Comment: Achei um tutorial MUITO interessante!!! Aqui: http://www.codeproject.com/Articles/125470/Exception-Handling-for-C-Beginners
Answer: A pergunta é ótima, mas vou tentar uma resposta que não seja baseada em opiniões, porque o foco do Stack Overflow não é a discussão.
Existe uma forma [melhor | correta] de propagar e exibir as exceções de forma simples?
Depende da interface da sua aplicação. Por exemplo, em uma aplicação Web, a melhor maneira de lidar com uma exceção é escalando-a, exibindo avisos em tela com a mensagem informativa da exceção ou usando uma lógica que lide com o erro internamente, disparando alguma lógica adicional ou reportando o problema em log.
O que é errado é abafar a exceção, impedindo ela do seu comportamento normal, que é interromper a execução do fluxo normal do código para evitar problemas maiores no sistema.
No caso do seu código, se a intenção é registrar as exceções em Console, o código está certo e adota boas práticas. No caso, você está acumulando as mensagens das exceções, o que é correto, e exibindo em uma saída que não aparece para o usuário. Neste caso, apenas é importante devolver ao usuário uma mensagem legível e compreensível do problema ocorrido.
Qual a importância de capturar Exceptions mais especificas, por exemplo: DivideByZeroException?
Uma determinada situação pode gerar erros diferentes, o que exige tratamentos diferentes. Para cada tratamento, a tipificação da exceção é uma boa prática para prover a cada situação de erro o tratamento adequado.
Answer: Atenção, vou fazer algumas simplificações abaixo, o espaço não permite discorrer sobre tudo o que o tema pede. E principalmente vou usar muito as palavras "geralmente" e "provavelmente". Não existem verdades absolutas em desenvolvimento de software. Portanto cuidado com "boas práticas", principalmente se você é como a maioria das pessoas que se esquecem o que isso significa e começam tratar recomendações para grande parte dos casos como verdades absolutas para todos os casos. Boas práticas costumam fazer as pessoas pararem de pensar sobre os problemas, elas viram receita de bolo. Especialmente ocorre no tutorial do comentário na pergunta. Ele parece bom mas não é tanto assim. Na tentativa de simplificar a explicação ele prega coisas normalmente erradas. Talvez a pessoa que escreveu saiba disso, mas quem está lendo provavelmente não.

Gostaria de saber a opinião de vocês. Existe uma forma [melhor | correta] de propagar e exibir as exceções de forma simples? Essa é uma boa forma de lidar com Exceptions?

Indo direto ao ponto, essa NÃO é uma forma boa de lidar com exceções.
Talvez o exemplo não seja o melhor para indicar sua intenção, mas só posso julgar pelo que você postou. Eu jamais faria um código desse em produção, ele tem alguns problemas:

Ele intercepta uma exceção muito genérica. A "boa prática" é só interceptar exceções mais específicas. O quanto elas devem ser específicas depende muito do caso. Mas provavelmente pegar a Exception é erro. Pegar a Exception pode ser útil em um nível alto do call stack (no Main() por exemplo).
Ele lança uma Exception. A classe Exception deveria ser abstrata (ok, eu sei que isso criaria alguma limitação não desejável em certos casos) para evitar alguém instanciar e lançar algo que efetivamente foi feito para ser uma abstração.
Ele destrói o stack trace e fica mais difícil achar informação útil, quando o objetivo parece ser oposto.
Ele não provê nenhuma melhoria semântica à exceção original, só coloca um vestidinho e um batom nela (e fica parecendo um travesti :) ). Particularmente não está especializando mais.
Ele manipula uma exceção sem saber o que fazer com ela.
Ele está deixando uma exceção ocorrer quando ela pode ser prevenida. Eu sei que é só um exemplo, mas estou fazendo a análise do que existe. Exemplos ruins fazem as pessoas entenderem as coisas erroneamente.

Se você está usando um throw sem estar imediatamente seguido de um ;, provavelmente está fazendo alguma coisa errada. Preservar o stack trace é tão importante que o C# 6 agora tem filtered exception sem a qual o novo compilador, parte do compilador Roslyn, não poderia ter sido criado adequadamente.
try { … }
catch (MinhaException e) if (meufiltro(e)) {
    …
}

Coloquei no GitHub para referência futura.
Capturar Exception, ApplictionException, SystemException, etc. são genéricas demais para conseguir fazer qualquer coisa útil. São exceções que geralmente só devem ser capturadas como última ação antes da aplicação/thread quebrar. Quase sempre a ação executada será logar o estado antes do término. Note que tratamento de exceções em aplicações multi-thread são ainda mais complicadas. Existem diversas outras preocupações para manipular corretamente em uma ambiente de paralelismo que não vêm ao caso aqui.
Sem saber com clareza o que fazer com uma exceção, portanto sem ter uma solução real para o problema, uma exceção não deve ser capturada. Tenha em mente que 80% dos programadores erram no tratamento de exceções em 80% das vezes. Ok, os números são chutados, mas até programadores experientes erram porque não entendem profundamente do tópico que gerou a exceção (não só a exceção em si). Algumas pessoas diriam até que exceções são vazamento de abstração.
Centralizar a captura das exceções, especialmente em um nível alto da call stack que você tem conhecimento ou capacidade de manipular adequadamente é uma "boa prática". A escrita em log e eventualmente o aviso ao desenvolvedor/suporte da aplicação é a ação mais comum nestes casos. Quando se usa threads, existe um ponto central para cada thread.
Quando você está criando exceções, pense duas vezes. Elas são lentas quando lançadas e dificultam o trabalho de depuração de código. E muitas vezes os programadores não sabem bem quando realmente a situação é excepcional ou quando é apenas um fluxo alternativo ao programa. A situação piora quando se tenta escolher a especificidade e a semântica correta para a falha. Por isso, capturar e tentar melhorar exceções bem arquitetadas provavelmente resultará em derrota. Use a exceções existentes a não ser que você agregue algo realmente útil na sua própria exceção. Leia o código fonte do .NET para entender onde e quando lançar as exceções existentes.
Prefira sempre que possível tratar a falha antes da exceção ocorrer. Ter uma método TryAlgumaCoisa() evita o uso da exceção. Mas claro que nem sempre isso é possível. Não dá para usar esta técnica quando você precisa de mais do que "falhou/funcionou", quando há risco de race condition, etc.
Se realmente precisar interceptar uma exceção, tente lança-la de novo integralmente com throw; e se ainda tiver que lançar a mesma exceção melhorada ou outra mais específica, use a versão do overload que permite preservar o stack trace (Ex.: Exception(String, Exception)). Se a exceção que você vai lançar não tem esse overload, fuja dela então, foi feita muito porcamente e não vale seu uso.
Se precisar "enfeitar" as mensagens da exceção antes de apresentar ao usuário, faça só quando estiver realmente manipulando a exceção. Varra o stack trace e outros membros da exceção e transforme as mensagens imediatamente antes da apresentação. Não faça o enfeite da mensagem antes, ao contrário do que mostra o exemplo.
Cuidado com o que coloca nas mensagens das exceções. Eu quase morro de dar risada com algumas aplicações web que só faltam incluir a senha do root para todo mundo ver.
Logue ex.ToString() e não ex.Message.
Alguns erros comuns seu exemplo não comete:

O código não está engolindo a exceção por completo.

Não coloca uma lógica muito complicada no catch, caso contrário você começa correr risco de ter uma exceção enquanto está manipulando outra exceção. Simplifique! Faça só o necessário.

Nem tudo deve estar em um catch, o finally pode ser mais adequado em algumas situações.
A maioria das exceções no tratamento de exceções (desculpe o trocadilho) vão ocorrer em situações onde você está criando um framework ou uma atividade com um nível de menor abstração. Nestes casos ou você sabe bem o que está fazendo, tem que saber, ou merecerá todo sofrimento que terá :)
Existe o evento Application.ThreadException que é uma rede de segurança para o caso de todas as tentativas de capturar um erro falharem. É um recurso bem limitado onde basicamente você só vai conseguir logar o estado atual. Não tente usar sem ter um profundo entendimento dos seus compromissos.
Compile seu exemplo e compile outro retirando toda manipulação de erros. Depois você me conta qual forneceu informação mais útil. Provavelmente você vai se surpreender. Compile com debug.

Qual a importância de capturar Exceptions mais especificas, por exemplo: DivideByZeroException?

Já foi dito antes que quase sempre é melhor capturar exceções mais específicas. Você provavelmente terá melhores condições de manipular a exceção adequadamente.
Especialmente a DivideByZeroException não deve ser manipulada, pelo menos não em condições normais. Vou explicar melhor abaixo mas a razão básica que ela não deve ser capturada, salvo algum motivo que determine o contrário, é que ou não há como se recuperar desta falha ou ela pode ser prevenida antes da exceção ocorrer.
Se você pode fazer alguma coisa para salvar um cálculo depois de receber um DivideByZeroException então você sabe que o divisor será zero e não deve executar esse cálculo.
Exceções não devem ser usadas para controle de fluxo da aplicação ou determinar regras de negócios.

Eu gosto muito do artigo do Eric Lippert sobre o assunto e vou fazer um resumo aqui.

Tipo
O que fazer
Exemplo

Fatal
Nada, a CLR saberá o que fazer melhor que você
OutOfMemoryException

Trapalhada
Conserte o bug que está causando isso
ArgumentNullException

Ruido
a) Conserte o software/framework mal arquitetado b) Troque de fornecedor de biblioteca mal arquitetada c) Aceite o prejuízo e trate como se fosse Estrangeira
Por sorte conheço nenhum exemplo

Estrangeira
Manipule da forma mais adequada possivel
FileNotFoundException

Existem 2 grupos de exceções: as recuperáveis e as irrecuperáveis.
As recuperáveis se dividem em dois tipos. Uma claramente deve ser manipulada sempre que possível e a outra também, porém só se você não puder escapar dela.
O primeiro tipo é representado pelas exceções estrangeiras (exogenous). Elas ocorrem por falhas de recursos não gerenciados. São fruto de falhas em tentativa de acesso a recursos externos controlados pelo sistema operacional ou processos que servem sua aplicação. Erros produzidos pela filesystem, rede, banco de dados, servidor de aplicação, etc. Em geral você não só pode manipular adequadamente, como provavelmente deve. Provavelmente irá definir se vai retentar, se vai encerrar o recurso em uso, se vai avisar e perguntar o que fazer para o usuário, se vai tentar uma alternativa, enfim, a criatividade pode ser grande aqui. Capturar o mais próximo possível do ponto gerador da exceção costuma ser uma boa ideia, embora em alguns casos dá para generalizar ações.
O segundo tipo é a exceção que existe por ruído (vexing). É a exceção que não deveria existir. Existe porque foi mal arquitetada. Se ela foi criada por você ou sua equipe, dê um jeito de fornecer uma forma alternativa de tratar um acontecimento que não é excepcional. Se isso ocorre em uma biblioteca de terceiros, tente que o fornecedor lhe dê uma alternativa; ou pense em abandoná-lo. Além de não entender como exceções devem ser criadas, ele ainda é teimoso? Fuja dele. Não consegue? Bom, então faça o que a documentação manda ou descubra por conta própria o que fazer (ainda falta documentação? fuja mesmo). O próprio .NET já teve alguns exemplos de exceções criadas equivocadamente, mas hoje existem alternativas para evitar o seu uso.
O outro grupo, como o próprio nome diz, são irrecuperáveis. Já de cara entenda: não tente recuperar essas exceções! Erro comum de principiante, até dos principiantes com 10 anos de experiência.
O primeiro tipo são as falhas fatais ou de ambiente. Não há nada que você possa fazer nestes casos. Sinta-se com sorte se conseguir logar o erro, além de deixar a mensagem um pouco mais bonitinha ou palatável para o usuário.
O segundo tipo é onde as pessoas mais erram na manipulação, e deveria ser o mais fácil. São as trapalhadas (boneheaded). São erros de programação. É culpa de quem desenvolveu. Mas por alguma razão (talvez Freud explique) os programadores acham que podem e devem resolver o problema na execução (trocar o pneu com o carro andando). Muito raramente podem, mas mesmo quando podem, não devem tentar recuperar-se disso. A única forma de lidar com em erro de programação, é corrigi-lo. Claro que durante o programa você pode fazer alguma coisa e essa coisa é, no máximo, deixar a mensagem mais bonitinha, logar e alertar o desenvolvedor. A maneira de tratar essas exceções podem variar se está desenvolvendo ou em produção. Esse tipo de erro nunca deveria chegar em produção, mas chega. Fazer de conta que o erro não ocorreu ou tentar fazer algo para que o programa continue funcionando só pode trazer mais problemas. E o local para fazer isso é no Main() ou próximo dele. Dificilmente uma exceção deste tipo deve ser interceptada antes.
DivideByZeroException é um exemplo de erro de programação! E é incrível a quantidade de programadores que acham que não é. Há casos que você tentar verificar o divisor antes e depois fazer o cálculo pode causar uma race condition. Nestes casos, comece tudo de novo, você tem algum problema sério na arquitetura da sua aplicação.

Algumas linguagens mais modernas estão até usando mecanismos diferentes para tratar falhas. Elas provêm um mecanismo para dar uma saída personalizada e centralizada nos casos irrecuperáveis e outro mecanismo para tratar os casos recuperáveis de uma forma mais simples que um try catch. Curiosamente eu conheço uma linguagem bem antiga que já percebia que deveriam ter 2 mecanismos simples ao invés de exceptions :)
Veja também Por que devemos evitar retornar códigos de erro?.
Eu percebi que algumas pessoas não concordam com tudo aqui, talvez essas pessoas entendam de C# mais que o Eric Lippert.
Answer: A respeito de Exceptions em .Net você precisa entender o seguinte:
Try/Catch
Try/Catch significa: Tente, e Trate. Se seu código não tem um tratamento específico para a exceção, não trate-o. Mas isso não significa que sua exceção não deva ser tratada por ninguém, apenas que o método atual (que pode estar numa pilha de chamadas de 10 níveis) só deve ter um try/catch se houver algum sentido para catch.
Try/Finally
Try/Finally
Try/Finally significa: Tente, e a final... Se você tem uma operação que precisa ser realizada mesmo que dê erro, use-o.
IDisposable, Using e Try/Finally
Quando você implementa IDisposable, você pode usar o using para a criação de seu objeto. O que as pessoas não sabem é que o Using é uma implementação de try/finally onde no Finally o método Dispose() é chamado.
Criando suas próprias exceptions
Caso você crie exceptions próprias, é recomendado que você segmente suas exceptions usando herança, criando um ramo de herança específico para exceções de negócio. Essa segmentação facilita na hora de tomar a decisão sobre o que deve ser feito com a exception. Por exemplo:

Exceções de negócio são enviadas para o usuário em forma de um popup,
ou simplesmente são logadas como Warning e não Error. Em
contrapartida, as demais exceptions são tratadas como erro, e talvez
mereça uma mensagem genérica para o usuário.

Crie no mínimo uma exception, que represente a exception de negócio. Use ao máximo as exceptions já contidas no .Net.

Atenção Quando você começa a construir suas exceptions, você naturalmente e inconscientemente começa a olhar para toda reposta
validação (negativa) como uma potencial exception específica. Na
prática, não é necessário! Crie tantas exceptions forem necessárias
para que facilitem o tratamento. Se uma exception específica não tem
tratamento específico, ou você espera que alguém trate-a
especificamente um dia (um consumidor qualquer de sua classe) ou você
está criando exceções demais.
É comum que tendam a criar exceptions duplicas com as exceptions do
.Net, como ArgumentException, ArgumentNullException etc. Não
cometa esse erro. Uma coisa é um programador chamar um método,
passando um parâmetro inválido, outra coisa é você não poder "salvar
um objeto" pois ele está em um estado (na visão de negócio) que não
permita esse tipo de operação.

Throw e Re-throw

Se você precisa lançar uma exception, o faça!
Se você precisa lançar uma exception a partir de um catch de um try/catch, então coloque a exception original como innerException.
Se você precisa tratar uma exception e relança-la, use throw;

A diferença entre no rethow:
ERRADO
try
{
    ...
}
catch(Exception ex)
{
    ...
    throw ex;
}

CORRETO
try
{
    ...
}
catch(Exception ex)
{
    ...
    throw;
}

A diferença é significativa e não está sujeita a interpretações. O primeiro exemplo, errado, gera uma mudança no StackTrace da exception, fazendo com que você perca a rastreabilidade da exception. No segundo exemplo o comportamento é relançar a mesma exception, da mesma forma que ela chegou até você.
Tratamentos Globais
Somente os pontos mais externos de sua API, serviço, etc, devem efetivamente tratar exceções talvez omitindo-as para o usuário/consumidor e sempre logando-as.
Soluções para tratamentos globais:
Já foi dito aqui em outra reposta, o tratamento para a thread atual, mas você pode tratar também no AppDomain. Usar aspectos (AOP) também é uma excelente alternativa. O tratamento para WCF precisa ser diferenciado, pois exceptions no WCF são causadoras de quebra de canal, portanto nesse cenário, suas exceptions precisam virar faltas.
Answer: Complementando boas respostas, mas algo mais avançado abaixo.
O .Net fornece duas subclasses de Exception, pouco conhecidas: ApplicationException e SystemException.
O SystemException já é usado pelo framework para as exceções nativas, os programadores deveriam, principalmente quando usando o DDD, criar suas exceções e derivar do ApplicationException.
O porque é simples, você ganha mais granularidade, pode facilmente discernir se foi uma exceção gerado por usuário programador ou do sistema, escalonar o erro de uma camada de baixo nível para cima de forma controlada.
Capturar apenas Exception é uma técnica ruim, deve-se usá-la como failsafe, o ideal é capturar as exceções específicas e dar o tratamento correto. Um bom programador sabe quais exceções são atiradas do trecho de código protegido, senão nem saberá como tratar.
try
{
    // exception code
}
catch (FileNotFoundException ex) { // tratamento para arquivo não encontrado }
catch (ArgumentOutOfRangeException ex) { // tratamento para acesso incorreto de indice }
catch (CustomException ex) { // tratamento para exceção que eu criei }
catch (Exception ex) { // Algo inesperado ocorreu !!!!, log e analise }

Melhor maneira de lidar com Exceptions


How to play accents on short notes on the violin

Question: The technique I generally use to play an accent on my violin is to press down the bow before executing the note. So that creates the necessary impact. This video demonstrates it well:

This technique works really well with minims or crotchets. but the main problem is with semiquavers or quavers especially when I'm playing short notes consecutively. If I put my mind to pressing down the bow before playing the note I lose track of the rhythm and the impact of the action makes my note longer than it should be.
Is there a better alternative in such cases? Or do I have to be content with just applying a slight pressure on the note as I play it?
Answer: You can accentuate fast notes in flow by using, well, fast bow speed, making the bow travel a larger distance than other notes.  A bit like a stroked rather than thrown spiccato.
Answer: If you want to play faster accents like in semiquavers you need to practice your way there.
Starting with this videos technique you need to practice the shown attack there dividing gradually into smaller and faster accents.
In the video you have 1 accent per bow. Practice that first. Then make 2 accents per bow. In this phase you are not trying to be ritmic correct, you should just focus on starting the bow with the right pressure so it "bites" the string, and start the bow from a stopped position.
So the things to keep in mind is: the accents come out of a stopped bow with pressure.
When you are comfortable with 2 accents per bow (stopping the bow between them as long as it needs so you are sure you will get the right attack/accent after), then you are ready to play 3 accents. And then 4 and so on.
Mastering this might actually take you some months of focused training. The more slow and detailed you are in the beginning probably the better you will play later.
After a while you will have a reflex, a bit like vibrato can be a reflex, and the short elegant accents will come out.
On your way there remember:

at one point you will be able to play fast. Don't destroy it when its "green", keep practicing always slower than what you can control so you don't loose the technique.
the more accents, the shorter bow. If you want to go many accents it will be very little bow.


RAID1 to store ~10 million files <3MB?

Question: I have many small files in all of my websites, which are backed up every day to local computer. Today I use external 2TB HDD, but due to lack of free space wanna buy additional HDD. So my goal is not just to increase capacity, but also provide additional protection. What about getting 8TB (2x4TB) RAID1 array? Is it worth it? I think 2 are better than 1.
Comment: Yes, RAID is a good thing and in general it is worth it. However there is a lot more to good backups then redundant hard drives. If you are serious, you should learn more about it.
Comment: What about it?  Yes, 2 copies of data is better than 1.
Comment: Just a thought, if you are running on Linux, but you might want to consider using ZFS with mirroring.  Using snapshots and zfs send/recv will backup those small files much faster then any filesystem backup tools.
Answer: RAID1 is good. RAID10 is better, but RAID10 might not be needed in your use case, if you don't need speed as well as redundancy.
Don't forget the 3, 2, 1 rule in backups.
3 copies minimum
2 of those copies on separate devices
1 copy off-site
Comment: Thank you very much! I don't know 3-2-1 rule as a theory, but practically also have 3 copies on separate devices. :)

RAID1 to store ~10 million files <3MB?


Why do I keep getting Microsoft-Kernel-Power error and my 2012 R2 DataCenter is randomly restarting with this error

Question: Microsoft-Kernel-Power error ID=41 on Windows Server 2012 R2 Data Center.
My server went down twice yesterday due to this error happening, causing the server to restart on its own. This is an Azure VM.
I checked the Device Manager and found nothing to be out of place or needing an update. Also found print drivers for random printers that I did not install. Any insight to this would be greatly appreciated.
I don't currently have any more info than that.
Answer: This indicates an ungraceful shutdown. i.e. the node was shot in the head using a software power switch. Something to contact MS about.
<code>Log Name:  System
Source:       Microsoft-Windows-Kernel-Power
Event ID:    41
Level:         Critical
Description:
The system has rebooted without cleanly shutting down first. This error could be caused if the system stopped responding, crashed, or lost power unexpectedly.
An event 41 can occur in the following scenarios.

Scenario 1: The computer restarts, and there is a Stop error BugcheckCode in the event data

When a Stop error occurs, the Stop error data is written in Event ID 41 as part of the additional event data. There may be the instances in which the Stop error code information cannot be written before the computer restarts or shuts down. Such instances are covered in scenario 3.

Scenario 2: The computer is shut down By Azure (there was no outage listed in Azure Service Dashboard)
http://azure.microsoft.com/en-us/support/service-dashboard/

Scenario 3: The system randomly restarts and no Stop error BugcheckCode is listed, or the computer is completely unresponsive (hard hang)
</code>
Comment: ...or something running on the server caused it to crash and/or BSOD.  Impossible to say exactly, without more information.
Comment: No BSOD screen. Our sites go down and I RDP into the VM. When I log on, the restart screen has completed screen is open asking for a reason for restarting.
Comment: Some power issue with the hardware was the culprit. The hardware was replaced and no  more error.
Answer: You're saying that you saw print drivers for random printers - those drivers are usually installed by the server itself if you are connecting with RDP and have print redirection enabled (and Remote Desktop Easy Print fails to map the printer).
If you are the only one who use RDP to this server and you don't recognize any of the print drivers then I'm pretty sure that someone you don't know has logged on, probably through a brute-force attack using well known username/password combinations.
Comment: Our whole team has access. You are correct in the drivers, they were just my local ones to share my devices with server if needed. Thanks for your input, gives me insight on things to look for in the future.
Answer: I was informed that Azure had to replace some hardware and the error went away. One of the cons of the cloud...
Comment: How is this an answer? And how is this a con of the cloud, where your VM or app is migrated to properly functioning hardware if there's an issue (vs you having to physically replace a server)? Sounds like a pro, not a con.
Comment: I cannot monitor Microsoft's equipment. What planet do you live on David? When you use a Azure VM, the hardware is handed out like a raffle. It was my question, how can anyone but me say what the answer is? After  submitting a ticket with Azure, they swapped out hardware and we did not get the error anymore. Now, what more can be said about that?


Scrollspy não está funcionando

Question: Bom dia, estou desenvolvendo um site, e a principio está tudo funcionando, porém o Scrollspy(Bootstrap 3.3) não está funcionando, segui diversos tutoriais na internet de como aplica-lo em um Website mas não obtive sucesso mesmo seguindo-os corretamente. Eis um trecho de meu código.

html, body {
 font-family: 'Montserrat', sans-serif;
 width:100%;
 height:100%;
 padding:0px;
 margin:0px;
 text-shadow:none;
 background:#FFF !important;
 position: relative;
}

.links-navbar{
 text-align: center;
 margin: 10px;
}
.links-navbar a {
 padding: 25px 36px;
    font-size: 18px;
    font-weight: 600;
    color: #FFFFFF;
    text-transform: uppercase;
}
.navbar .links-navbar a:hover,
.navbar .links-navbar>.active>a,
.navbar .links-navbar a:focus {
 text-decoration: none;
 z-index: 20;
 color: var(--hoverLink);
 background-color: var(--hoverFundo);
}

            Voltar para o site

          o emprendimento
          áreas comuns
          garagens
          apartamentos
          localizacao
          contato

Answer: Cara para o ScrollSpy funciona vc precisa seguir as regras estabelecidas pela documentação oficial que vc pode consultar aqui! https://getbootstrap.com/docs/3.3/javascript/#scrollspy
Ponto 1: Não sei se vc está usando position:relative no , mas isso é necessário para o ScrollSpy funcionar!
Ponto 2:

Requires Bootstrap nav
  Scrollspy currently requires the use of a
  Bootstrap nav component for proper highlighting of active links.

Resumindo: "Vc precisa usar o componente Bootstrap nav para ativar a marcação dos links" ou seja vc tem que usar a NavBar oficial do Bootstrap e a sua que vc colocou na pergunta está totalmente diferente da NavBar original do BS3 como vc pode ver aqui: https://getbootstrap.com/docs/3.3/components/#nav

Aqui deixo um exemplo simples funcionando do ScrollSpy para vc usar como referência, repare no position:relative no Body, no link entre os href do menu e nos id das sections e principalmente na construção da NavBar

<!DOCTYPE html>

    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                </button>
                WebSiteName

                            Section 1

                            Section 2

                            Section 3

Section 1

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at
            the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at
            the navigation bar while scrolling!

Section 2

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at
            the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at
            the navigation bar while scrolling!

Section 3

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at
            the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at
            the navigation bar while scrolling!

OBS: Deixei no CSS os estilos que vc precisa customizar para quando o item da Navbar estiver .active
Comment: @aleque_b tranquilo jovem esses componentes são chatos de mexer mesmo, tem que seguir a documentação a risca para funcionar direito, qualquer ordem diferente nas tags html, ou uma classe css a menos o componente já para de funcionar, mas que bom que deu certo, boa sorte ai com o projeto e... "leia a documentação" rss. []´s
Comment: Ele está com position relative no body, segui todas as instruções pelas quais você mencionou como o Nav do bootstrap porém não obtive sucesso . Faltou alguma coisa?
Assim como tentei trocar aquela div do .links-navbar por uma , com cada link sendo uma .
Comment: @aleque_b cara edita novamente a sua pergunta e coloca o código completo da sua página, da mesma forma que eu fiz na minha resposta, coloca tudo que tiver entre as tags HTML e o seu CSS também. Pois se vc analisar o exemplo vc vai ver que ele funciona, então provavelmente é alguma coisa que vc fez, ou deixou de fazer na estrutura que está bugando o Spy
Comment: Sim eu editei e o HTML está conforme postado agora, nao postei o código inteiro porque ele está mesclando HTML, CSS e PHP. Mas assim, todas as âncoras estão configuradas, assim como as Divs com Id. Não tem o que pode estar de errado.
Mas mesmo assim não está funcionando.
Comment: @aleque_b Cara a sua Navbar ainda continua completamente diferente do modelo do Bootstrap padrão.... Olha na minha resposta  como está a minha `` vc está construindo sua Navbar dentro dessa div `` isso está totalmente diferente do que diz a documentação.... Cara pega o modelo que eu postei e "reconstroi" a sua página dentro dele, acho que é uma opção pra vc já que não está rolando com o seu código.
Comment: Refiz o cabeçalho do 0 e parece que agora funcionou. Desculpe a demora pela resposta, tive que reformar tudo o CSS para estar estilizado de acordo como tava no cabeçalho anterior. Muito obrigado!

Scrollspy não está funcionando


With no accent mark available to soften a note or 2, can Dynamics notes be used instead?

Question: I realize a form of this question has been addressed in the past, but ... I am very new to music theory and need a clarification.  I was shocked to discover today that in music notation, there is no Articulation mark to tell the player to play one or a few notes more softly than the rest of the score ... nothing to serve as a opposite to the > sign.  Soft isolated notes are played in music all the time, and I cannot believe there is no such mark invented by the folks who invented music notation.  However, I have read posts about it on this and other forums, and encountered one knowledgeable person stating that if I want someone to play even one note softer than usual, I can simply use a dynamics mark above it, then use another dynamics mark on the next note(s).  His suggestion would look like this (in measure 35, corrected in measure 37):

Is this acceptable?  If not, what can possibly be used to tell the player to soften the note in measure 35?
Comment: You can use ghost note notation (putting regular brackets around a notehead) to signify it's played quieter than the others.
Comment: Personally I would put in hairpins instead. They're more readable to me. Plus they are more relative, like an accent. With accents, you can change the dynamic mark at the beginning of a passage and the whole passage changes and the accents are still accented. Same with hairpins. With explicit dynamic marks you have to update all of them if you want to make a whole passage louder or softer.
Comment: Dynamic specifications addressing only one system are rare. Fortunately nothing is missed here, since the right hand is clearly only accompaniment and every decent player will soften it anyway. Given that there is a full chord in bar 33/34, its also somewhat self-explaining, that bar 35 is softer.
Comment: @Pyromonk Ghost notation is almost inexistent on "standard" piano scoring, and, unless a specific introduction is put for the piece, that would be just confusing for common players who might not be used to modern notation. Being a drummer as well, I *do* know ghost notes, and I'd still be really skeptic about its usage and how to play it (or if?!). While I see your point, there's no need for "extra" notation like that, and I also believe that a ghost note is a quite different thing, more close to an ornament, which is not this case): using a dynamic notes at the right position is clear enough.
Comment: Wow!  I am a bit as confused as ever.  We seem to have opinions to just hope the player softens the note, use ghost notes, dynamics marks, parentheses, or hairpins.  One other guy suggested even making the note smaller if you want it to play softer.  Another suggested to use a backward **<** symbol to soften the note.  I don't want to violate good music conduct here, but in a piano score, is there an actual STRONG preference for a particular approach, if I want to mark a few notes to play softer?  If so, could someone please post a short sketch so I can see what to do?  Really appreciate it.
Comment: I believe my answer is sufficient, the excerpt from Debussy uses standard, well established and clear indications. Any decent pianist would have no problem with it (while they would with almost any other alternative).
Comment: The Debussy example is valid, but @ToddWilcox  comment about using decrescendo/crescendo hairpins (>●<) seems like a cleaner solution for softening a single note.
Comment: I suggest getting a copy of *Behind Bars* by Elaine Gould. As the subtitle asserts, it **is** the definitive guide to music notation. If you want to know what will be most easily read and understood by pianists, it's either in that book or it doesn't exist. I would say that beyond using individual dynamic marks or hairpins, you'd have to put a key or a note at the first appearance explaining. Nothing other than some form of traditional dynamic mark will be instantly understood by a wide range of musicians. One advantage to traditional marks is they enable cold sight reading.
Answer: While it's common knowledge[citation needed] that until classic-age there were rare cases of dynamics differences between parts, that doesn't mean that they were not considered: they were just more simple and generic, usually based on the selection of the [orchestra] instrumentation for the specific section of the composition.
In fact, those differences are actually less uncommon (and less modern) than we might think of: consider that clavichords and organs had many keyboards and registrations in order to provide different dynamics also. While the preference of registration/keyboard was up to the player, the difference was still important, not only for the timbre.
Since [post] romantic music onwards, also due to the technical and composition evolution of what had become the most common keyboard instrument, differences in dynamics of voices became much more common.
Consider this excerpt from Debussy's Golliwogg's Cake-walk (circa 1908):

So, no, there's nothing wrong in specifying dynamics for a specific system (or voice), as long as it's clear what it's referred to.
In your case I would avoid putting those indications too above, otherwise they might be a bit confusing about their reference: try to put them as close (but not too much) as possible to their part.
For instance, the mp of the second system should better be a bit below and on the left than it is now; while it's probably clear that it is referred to bar 37, notation should always be as clear as possible, without allowing any possibility of doubt: the player shouldn't lose even a fraction of a second thinking about "is it above or below?".
Comment: Sorry.  Confused.  I assume the MF dynamic addresses all of the notes in that measure, but what does the pp and decrescendo address?  It looks like it asks the player to soften all of the 8 notes in measure 3.  What if I wanted to just soften the first E/B notes in the measure?  What would I put there?
Comment: In a single instrument system, dynamics that are common for all parts are normally put between the two staffs, so the *pp* and decrescendo address everything (both hands, all voices). When dynamics are above the top staff, they refer to that staff *or* the top voice if more voices are on the same staff, as much as having dynamics on bottom of the lower staff are only referred to the left hand (or bottom voice). In any case, it all depends on the relative position to staff *and* voice. To soften e/b notes at the bottom of the 2nd bar, and *not* the f/a, they must be in different voices.


How do you go from paper to code?

Question: My background is in Computational Biology, although I am a Biologist by training. I just recently started my PhD, and while I have a strong interest/curiosity in Computational Biostatistics/Epidemiology and method development, I am fairly sure I won't have to develop and implement new methods. But as I said, I am curious about it.
More precisely, I still do not understand how someone goes from a research paper to e.g., an R package. I find it very difficult, not only because maybe I do not have the proper theoretical understanding of it, but also because I find programming statistical methods particularly difficult. I know how to code, I code quite a bit, but I never had to implement a method starting from the paper presenting it.
Just to give an example, I recently came upon this paper and apparently somebody implemented it in R here (file named focus_1.0.0.tar.gz). I genuinely would not know even where to start. What kind of mental model do you need to have in order to be able to translate such a framework into code?
Comment: As a graduate student, I took courses in numerical analysis (Conte & deBoor, etc.) and used that material to perform and publish scientific computations.  Nevertheless, when [Numerical Recipes](http://numerical.recipes/) appeared it was a revelation.  You can read it a chapter, or even a section, at a time; learn the underlying principles; see working code; and adapt the code for your own purposes for further research or production (the code's not perfect--which is a good thing!).  A little practice with such exercises will go a very long way.
Comment: It is actually an implementation to produce results for [a different paper](https://arxiv.org/abs/2106.02521)  using the methods in the paper you quote.  Once you have done that, making it available for others helps the world and helps the PhD student who did it promote herself.
Comment: Only somewhat in jest: read through the [Epigrams on Programming](http://pu.inf.uni-tuebingen.de/users/klaeren/epigrams.html).  Penned in the early '80s, they are applicable today.  Computers have changed, put programming has not.  In particular, I find great utility in #15: "Everything should be built top-down, except the first time."  I find it plays into many of the answers here.
Answer: For me, I go through the maths until I understand it (and can identify methods to make the linear algebra efficient and stable).  Quite often this involves writing out the maths again in the smallest possible steps (as a LaTeX document).  This is often useful as a maintenance document - if you come back to the software in a year's time, you probably won't remember exactly how it works, and a step by step mathematical derivation (with annotations that explain your problems with it) is a fast way to remember it again. Usually with programming the main difficulty is not coding (e.g. working out how to tell the computer to do something) but problem solving/understanding (working out exactly what it is you want the computer to do).
The next step is to identify components of the algorithm/method that you can test individually.  Don't try to implement the whole thing in one go.  I quite like Heinlein's quote "when faced with a problem you do not understand, do any part of it you do understand, then look at it again".
It is also a good idea to read other people's code and work out why they have implemented it in the way that they have, and to look at how the code has been structured in the case of packages that are used by other people.  Documentation is also very important, if you want people to use your code, you need to make it as easy as possible, so minimise dependencies (e.g. on third party packages) make the user interface or API simple and consistent with expectations, and provide good documentation.  This takes a lot of time/effort that most of us (including me) don't seem to be able to spare ;o)
Answer: To supplement Dikran Marsupial's answer, the following is an articulation of a process I use personally. This is from the perspective of coding machine learning algorithms for research, rather than from a full-blown production level software engineering perspective.
Primarily, I've often found it useful to see the process of coding a machine learning algorithm from scratch as instantiating a mathematical idea:
Mathematical, pre-algorithmic stage.
Usually in machine learning, you use some kind of mathematical or formal principle to guide the development of your algorithm. It may be statistical e.g. maximum likelihood estimation, and most likely, involve a degree of optimisation. Usually, you will need to do a fair amount of mathematical derivation work, until you have what you need.
Personally, I've found that one needs both a solid under-the-hood grasp of the mathematical principles operating here, as well as absolute security in the correctness of one's derivations. Any haziness or uncertainty at this stage will compound during implementation, when one additionally has to worry about debugging. Before proceeding to the next stage, I will often use a symbolic computing package or computer algebra system, such as Mathematica, to check all my derivations, because even a single error at this stage can lead to the extremely undesirable situation of having to search for derivation and/or debugging errors.
Algorithmic.
After I've checked that my mathematical derivations are watertight, with no errors, and I'm at a level where I can specify and sketch out my algorithm on paper, I proceed to drafting formal pseudocode. Similar to the above poster, I find that forcing oneself to type this up using algorithm2e in LaTeX helps in that it commits you in a way working solely with pen and paper doesn't.
During this pseudo-code drafting stage, I start thinking about more implementational concerns, such as adapting my derivations to be as vectorised as possible, i.e. using as few loops as possible, or making use of linear algebra techniques as far as possible. However, the implementational concerns extend only as far as complying with basic advice and standard principles of algorithm design, but not as far as optimising the code.
Implementation.
Implement the pseudocode in code. The clearer your pseudocode, and the more consistent your notation, the easier this will be. Something you will probably pick for up for yourself is that it pays enormous dividends, as the above poster has stated, to ensure you are writing modular code. Split the code writing into little chunks, which you can individually test.
In most cases, there will almost always be very basic sanity checks you can do. For example, if your code uses gradients, then you can use finite differencing to assess this has correctly been computed. If you are implementing an EM algorithm, your log-likelihood will monotonically increase, so any decreases are most likely coding errors, provided your derivations are correct.
Optimisation.
I don't want to say much about this, except that it can get deep very quickly. At this stage, you time your code, or use a whole host of numerical linear algebra, matrix computation and convex optimisation tricks to squeeze as many performance speed-ups as possible.

Concerning the use of tools for debugging, I don't know much about the debugging tools in R as it's something I'm only getting to grips with. However, it looks like the RStudio debugger is similar to that of pdb in Python.
In the case of Python, the PyCharm IDE is one example where I've found that tools can vastly improve the debugging process. You can walk through each line of your code as it runs, and step in, step out, do side by side evaluations, as well as keep track of all variable states at once. I personally find that the visual means of accessing all variable states at once is far superior to using doing manual command line queries using pdb. Whilst I wish I knew this earlier, I emphasise this is for consideration only, and I have no affiliation with JetBrains whatsoever.
Some final things. Like most things in life, you get better through practice. There are lots of papers accompanied with code at paperswithcode.com; and there is also an ML paper reproducibility challenge also.
Lastly, if you ever find that debugging is starting to grind on your soul somewhat, I've found it helps to think of the days when people used to use punch cards to implement algorithms...
Comment: Nice answer (especially "absolute security in the correctness of one's derivations" - you have to be able to have confidence on the foundations on which you are building).  For optimisation, profiler tools are essential.  The one in MATLAB is excellent and shows the proportion of time spent on each line of code, so you can see where to focus and whether your improvements are working (put in the code for both, one after the other, and you can see directly which method is fastest).
Answer:
More precisely, I still do not understand how someone goes from a research paper to e.g., an R package.

Like a lot of things in life, sometimes the hardest part is just getting started. A lot of people set themselves up for failure by just, well, thinking they aren't prepared enough and are going to fail, so they effectively give up before they even try.
With that said, you do have to know at least a little to get started. In the context of writing R packages based on a paper, you don't necessarily need to be comfortable with the math or theory behind the topic to get started. You might find the process of writing the package actually helps with developing that deeper understanding you eventually do want to have, and that over time you'll make changes to the package that reflect that. I actually have a very robust, user-friendly R package where I started in this situation. I have a lot of programming experience, and someone I know had this non-trivial theory he'd been developing but didn't have the ability to properly implement in a package, so he asked me to help. The details of the math and theory were mostly unfamiliar to me since my expertise is somewhere else. I didn't even know the details of creating an R package at that point. But now, after having gone through the process of creating the package, I'm at a point where I'm even able to make my own contributions and advancements to the theory and its applications.
To start, what you need to do is think about what users might want in a package. What does the paper present that potential users will find useful? This does require at least a high-level understanding of what the paper is accomplishing; presumably, you wouldn't be trying to write a package for a paper if you had no idea what the paper is about. So make a list of the things that users will want. Now assign these items to function names without worrying about the details of how these functions work internally. For example, you might have one function that does a core statistical analysis, one that calculates confidence intervals, one that calculates variances, and maybe one that does a basic visualization.
Next, what are the most fundamental inputs you need for these functions? There might be a lot of little things that are useful for convenience, tuning, or flexibility in the function, but these aren't important yet. What's important is just getting the basic functionality running; you can go back and deal with the finer details later so that they don't overwhelm you now.
Now, what are these functions returning for values? In other words, what would a user expect or find most useful in terms of results? Part of this may end up shaping or being shaped by the previous point about inputs. If you have one function that builds on the result of another, then the input of one is going to be the output of another. So depending on the situation, you might have one function that returns simple things like a numeric or a vector, and you might have another function that returns complex things like a list or class object.
Once you have a list of the functions you want, what they need for inputs, and what they produce, you now have what you need for a basic skeleton package. So start coding by creating a bunch of empty functions. Or maybe just have them print something. If you've never written a package before, this a good time to try  building and installing it (locally on your computer) to make sure it works. As you work, periodically build, install, load, and test your package to make sure everything is doing what you think it is.
Finally, with a skeleton package setup, you can now start digging into the mathematical/theoretical details. Your functions act as guide to help you break down this task so that you don't try to overwhelm yourself by focusing on everything at once. Just focus on one thing and work on getting the basics of the function running. You absolutely should not be worrying about performance at this point. Same goes for other things like weird corner cases with input data. You should be focused on getting things implemented in the simplest manner possible. Once everything is running and you have a better feel for everything, then you can revisit.
Eventually, you will pick up a deeper understanding of what it is you're trying to accomplish with your package. You might find yourself realizing that there are functions you need that you didn't think of before, or maybe a couple of your functions need to be combined. You may even look back and realize there is a completely different way of doing things that is better. For my package, v0.1.0 (essentially a beta) and v1.0.0 (first production release) are night and day different. I completely rewrote the package from scratch for v1.0.0. v0.1.0 was great for learning, not only the math and the theory, but how my framework decisions felt both as a user and as a package maintainer. Turns out, it was clunky and unpleasant for both, and a complete overhaul was worth investing in. So don't worry about getting it perfect right away; take your time in the pre-release stage to try things, and preferably give some potential users a chance to try it and give feedback as well. I can't tell you how often other people's real-world data will expose weird corner-cases you never considered...
Some additional tips:

Technical debt: sometimes there are situations where there are multiple ways to do a task. Before publishing your package, you need to think ahead what these choices mean, because if you just take the easy way, you may find it costs you a ton of time later to work around. It's best to take care of this before publishing because you want to avoid breaking things for users once they start using the package. There are tons of articles on "technical debt". Spend some time reading a few of them.
Maintenance burden: If you intend to create an R package, please be committed to maintaining it. A huge problem I've seen with scientific software is that many people publish software/packages as a one-off task for a publication and then let it rot, which ultimately costs others a lot of time and energy when things go wrong with the software for them. Hopefully you aren't one of them. To that end, you have to be aware of how your choices in designing the package are going to affect your time commitments later. Every little thing you add is one more thing that can break, needs to be tested, requires support for users, etc., leading to more time spent maintaining your package instead of other things you want to do. So be judicious with what you add and what you cut from the feature list; if you try to add every little convenience thing that people want, you will regret it later. The same goes for thinking about what external packages you need for your package; every dependency you add is another chance for a change someone makes in their package to break your package.
For publishing an R package, please put it on CRAN. I can't tell you how many times I've looked at the GitHub repo for non-CRAN packages (with peer-reviewed publications) only to find fundamental flaws that CRAN's "annoying" policies would have prevented. Seriously, one package I looked at changed multiple default R behaviors that many other common packages implicitly depend on. Simply by loading the package, it could completely alter the behavior of other packages in a way that was completely silent with non-obvious changes in results, and could only be fixed easily by restarting R (and never loading the package again). The commands this package was using to do this are explicitly prohibited in CRAN packages. If the author had tried to publish to CRAN, they would have caught it (or maybe they did try and decided it wasn't worth the hassle to fix just to get on CRAN...)
Use automated testing (for R, see the 'testthat' package). This really should be a requirement for any package. Unfortunately, just because a package has unit testing doesn't mean it's being done well. It can be a bit of an art form figuring out how to do it well.
Good documentation is necessary. And I don't just mean the typical R function references. I expect most people benefit from having a variety of tutorials/vignettes explaining concepts and giving examples. Trying to write these will actually contribute to your own understanding of the math and theory, or at the very least give you confidence in what you have learned. For R, I recommend looking at the 'pkgdown' package for this; it helps you build a website for your package that's hosted as part of your package's GitHub repo.

Some parting words: If you're going to write software for scientists, please keep in mind how important of a responsibility it is. If you really dedicate yourself and do it right, you could make a huge difference in the ability of many people to do their research more efficiently and effectively. But if you half-ass it or are lazy about maintaining it, you could screw a lot of people and cost them a lot of time, energy, and potentially money. Either way, you have the potential to make an out-sized impact on science that you might not normally have by just staying in your own little research bubble.

How do you go from paper to code?


WPF DataGrid - CellEditEnding event update data

Question: I am struggling with the DataGrid in WPF. I have a ObservableCollection bound to it. When the user enters the first cell, the other cells will update accordingly. To achieve that, I subscribed to the CellEditEnding event to force the update after the first cell has been changed.
In this event, I also update other properties of MyClass like this:
<code>    private void DataGridTeilnehmer_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        if (!commiting)
        {
          commiting = true;
            DataGridTeilnehmer.CommitEdit(DataGridEditingUnit.Row, false);
            commiting = false;

            if (e.Column.DisplayIndex == 0)
            {
                MyClass data = (e.Column.GetCellContent(e.Row) as ContentPresenter).Content as MyClass;
                data.pass = "nothing";
            }
        }
</code>
The problem is, that the Grid doesn't update itself so "nothing" is not be showed, until I enter edit-mode of the cell that is bound to the property "pass" which contains "nothing". But I would like to show it immediately.
Thanks in advance,
Frank
PS: I have worked with many (Data)Grids in my life, but the WPF Grid is the worst I encountered so far.
Comment: have you mentioned UpdateSourceTirgger while binding the field Pass. IF yes then you might not have defined propertychanged event in your MyClass for Pass property.
Comment: Can you show the dataGrid code where you are binding?
Comment: Are you using Mvvm for working with the DataGrid? If yes, then you may update the ViewModel for the DataGrid row, if it is a property changed class, then all bindings will be updated, and also the Datagrid rows.
Answer: The correct way is as follows, currently use this way in my software
<code>private void MyWPFFrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        if (e.Column.SortMemberPath.Equals("EndDate"))
        {
            if (((MyObject)e.Row.Item).EndDate.Equals(DateTime.MinValue))
            {
                ((MyObject)e.Row.Item).Completed = 1;
                ((MyObject)e.Row.Item).CompletedDescription = "YES";
            }
            else
            {
                ((MyObject)e.Row.Item).Completed = 0;
                ((MyObject)e.Row.Item).CompletedDescription = "NO";
            }

            this.MyWPFFrid.CurrentItem = ((MyObject)e.Row.Item);

            if (!e.Row.IsEditing)
            {
                this.MyWPFFrid.Items.Refresh();
            }

        }
    }
</code>


Prove that $ \sqrt{5} $ is irrational geometrically Hardy and Wright

Question: I am reading Hardy and Wright's Intro to Number Theory chapter about irrational number and there is a section proving that $ \sqrt{5} $ is irrational geometrically, but the proof is confusing me for some parts. The proof, extracted verbatim from the book, is presented below for convenience.
$ \textbf{Proof} $: We argue in term of $ \displaystyle x = \frac{\sqrt{5} - 1}{2} $. Then $ x^2 = 1 - x $. Geometrically, if $ AB = 1, AC = x $, then $ AC^2 = AB.BC $ and $ AB $ is divided in golden section by $ C $. (For the geometric figure, see Fig 4 here.)
If we divide $ 1 $ by $ x $, taking the largest integral quotient, viz. $ 1 $, the remainder is $ 1 - x = x^2 $. If we divide $ x $ by $ x^2 $, the quotient is again $ 1 $ and the remainder is $ x - x^2 = x^3 $. We next divide $ x^2 $ by $ x^3 $, and continue the process indefinitely; $ \textbf{at each stage the ratios of the number divided,} $
$ \textbf{the divisor, and the remainder are the same.} $ I am confused about this bold sentence. I work out a few examples and I got:
$ 1 = 1.x + (1 - x) = 1.x + x^2 $
$ x = 1.x^2 + (x - x^2) = 1.x^2 + x^3 $
$ x^2 = 1.x^3 + (x^2 - x^3) = 1.x^3 + x^4 $
and so on, so the ratios of the number divided, the divisor, and the remainder are all $ \displaystyle \frac{1}{x} $, is that what they are implying here?
Continue the proof:

Geometrically, if we take $ CC_{1} $ equal and opposite to $ BC $, $ AC $ is divided at $ C_{1} $ in the same ratio as $ AB $ at $ C $, i.e. in golden section; if we take $ C_{1}C_{2} $ equal and opposite to $ C_{1}A $, then $ C_{1}C $ is divided in golden section at $ C_{2} $; and so on. Since we are dealing at each stage with a segment divided in the same ratio, the process can never end.

I currently stuck on this paragraph, what do they mean by "$ AC $ is divided at $ C_{1} $ in the same ratio as $ AB $ at $ C $?" At first I thought this means $ \displaystyle \frac{AB}{AC} = \frac{AC}{AC_{1}} $, but this is not true since $ \displaystyle \frac{AB}{AC} = \frac{1}{x} $ while $ \displaystyle \frac{AC}{AC_{1}} = \frac{x}{2x - 1} $.
Continue the proof:

If $ x $ is rational, then $ AB $ and $ AC $ are integral multiples of the same length $ \delta $, and the same is true for $ C_{1}C, C_{1}C_{2}, \dots $, i.e. all the segments in the figure. Hence, we can construct an infinite sequence of descending integral multiples of $ \delta $, and this is plainly impossible.

If $ x = AC $ is rational, then $ \displaystyle AC = \frac{a}{b} $ and $ AB = 1 $, then how can "$ AB $ and $ AC $ are integral multiples of the same length $ \delta $?"
Any insight is appreciated.
Answer:
$ \textbf{at each stage the ratios of the number divided,} $
  $ \textbf{the divisor, and the remainder are the same.} $ I am confused about this bold sentence.

They mean that
$$\color{red}{\text{red}}:\color{blue}{\text{blue}}:\color{green}{\text{green}}=1:x:x^2$$
always holds in
$$\color{red}{1}=1\times \color{blue}{x}+\color{green}{x^2}$$
$$\color{red}{x}=1\times \color{blue}{x^2}+\color{green}{x^3}$$
$$\color{red}{x^2}=1\times \color{blue}{x^3}+\color{green}{x^4}$$
$$\vdots$$

I currently stuck on this paragraph, what do they mean by "$ AC $ is divided at $ C_{1} $ in the same ratio as $ AB $ at $ C $?"

$\qquad\qquad$
In the paragraph, they mean that
$$BC:CA=AC_1:C_1C=CC_2:C_2C_1=C_1C_3:C_3C_2=\cdots$$
where $BC=C_1C=x^2,AC_1=C_2C_1=x^3,CC_2=C_3C_2=x^4,\cdots$.

If $ x = AC $ is rational, then $ \displaystyle AC = \frac{a}{b} $ and $ AB = 1 $, then how can "$ AB $ and $ AC $ are integral multiples of the same length $ \delta $?"

$AB=b\times\frac 1b$ and $AC=a\times\frac 1b$ are integral multiples of $\delta=\frac 1b$.


Polynomials with natural coefficients arising from exponentiation and sums

Question: Is there any nice characterization of the class of polynomials can be written with the following formula for some $c_i , d_i \in \mathbb{N}$? Alternatively, where can I read more about these? do they have a name?
$$c_1 + \left( c_2 + \left( \dots (c_k + x^{d_k}) \dots \right)^{d_2}  \right)^{d_1}$$
For instance, it is not possible to write $1 + x + x^2$ in this way, but it is possible to write $1 + 2x + x^2$ or $0 + x^3$.
For some context: two actions on the set of polynomials $A \times \mathbb{N}[x] \to \mathbb{N}[x]$, and $B \times \mathbb{N}[x] \to \mathbb{N}[x]$ can be combined into a single one $\left<A,B\right> \times \mathbb{N}[x] \to \mathbb{N}[x]$ that takes a word of elements on $A$ and $B$ and applies the multiple actions in order. In the case of multiplication and exponential, we can see that the class of polynomials
$$c_1  \left( c_2  \left( \dots (c_k  x^{d_k}) \dots \right)^{d_2} \right)^{d_1}$$
can be just described as the polynomials of the form $cx^d$. I do not expect such a simple characterization in the case of sums and exponentials, but I would like to know if this class of polynomials has been described or studied somewhere.
Comment: Interesting question. It might help to know where it comes from ([edit] to tell us.) The leading coefficient must bte $1$ (except for the constants).
Comment: compound interest ?
Answer: Some partial elementary observations that might lead to necessary conditions, probably not to a characterization.
If the nonconstant polynomial $p(x)$ has this form then the leading coefficient must be $1$ and you can make the constant term anything you like.
The quadratics are precisely the ones where the coefficient of $x$ is even.
The cubics are the ones of the form
$$
c + 3t^2x + 3tx^2 + x^3 .
$$
That is, those where the coefficient of $x^2$ is a multiple $t$ of $3$ and the coefficient of $x$ is $t$ times the coefficient of $x^2$.
For degree $n$, must the coefficient of $x^{n-1}$ be a multiple of $n$? How will it restrict some lower order coefficients?
Answer: You can figure out if a given polynomial is of that form by "going backwards". Let:
 $$(a_n x^n  + a_{n-1} x^{n-1} + ...a_1 x^1 + a_0) =   c_1 + \left( c_2 + \left( \dots (c_k + x^{d_k}) \dots \right)^{d_2}  \right)^{d_1}$$
A valid polynomial will always be of the form:
$$ c_1 + \left( c_2 + \left( \dots (c_k + x^{d_k}) \dots \right)^{d_2}  \right)^{d_1} = x^n + (\frac{n c_{k}}{d_{k}}) x^{n-d_{k}} + ... = P(x)$$
where there are no non-zero intermediate powers between $x^n$ and $x^{n-d_k}$, and $c_{k} \neq 0$ except in the cases where the polynomial is $x^{d_1}$. We solve it by substituting $x = (y-c_k)^{\frac{1}{d_k}}$ in our polynomial from the computed values, checking if $P((y-c_k)^{\frac{1}{d_k}})$ is still an integer polynomial and $c_k$ is an integer, then solving recursively for :
 $$c_1 + \left( c_2 + \left( \dots (c_{k-1} + x^{d_{k-1}}) \dots \right)^{d_2}  \right)^{d_1} = P((y-c_k)^{\frac{1}{d_k}})$$ until all pairs $(c_k,d_k)$ are computed.
Eg: $x^2 + x + 1$ gives $d_k = 1$ and $\frac{2c_k}{1} = 1$ which is non-integer $c_k$ so there are no solutions.
Eg: $P(x) = x^3 + 6x^{1} $ gives $d_k = 3-1 = 2$ and $\frac{3c_k}{2} = 6$ so $c_k = 4$. We then calculate $P((y-4)^{\frac{1}{2}}) = (y-4)^{\frac{3}{2}} + 3 (y-4)^{\frac{1}{2}} $. We see that the exponents are not natural so this cannot be further expanded. There are no solutions.
Eg: $P(x) = x^{20} + 12 x^{15} + 54 x^{10} + 108 x^5 + 83$. We see $d_k = 20-15 = 5 $.  Also $\frac{20c_k}{5} = 12$ so $c_k = 3$. We compute $ P((y-3)^{\frac{1}{5}}) = y^4 + 2 = P_{2}(y)$. Applying the same procedure to $P_{2}$ we get  $d_{k-1} = 4-0 = 4 $. and $\frac{4c_{k-1}}{4}=2$ so $c_{k-1} = 2$. Substituting again we see that $P_{2}((z-2)^{\frac{1}{4}}) = z$ . So our final result is: $((x^{5}+3)^4 + 2)$ .


$P (x)$ have a local minimum at $x = \sqrt 2$. Prove that $P (x)$ has also a local minimum or maximum at $x = -\sqrt 2$

Question:
Let the polynomial $P (x)$ with integer coefficients have a local minimum at the point $x = \sqrt 2$. Prove that $P (x)$ has also a local minimum or maximum at the point $x = -\sqrt 2$  (not an inflection point).

Let $P(x)=a_nx^n+a_{n-1}x^{n-1}+...+a_1x+a_0$, where $a_i \in \mathbb Z, i=0,..n$. Then $$P'(x)=na_nx^{n-1}+(n-1)a_{n-1}x^{n-2}+...+a_1$$
$$P'(\sqrt2)=0$$
Answer: For a polynomial $Q$ with integer coefficients, $Q(\sqrt 2)=0$ iff $X^2-2$ divides $Q(X)$ iff $Q(-\sqrt 2)=0$.
That $P$ has an extremum at $\sqrt 2$ is equivalent to  $P'(\sqrt 2)=P''(\sqrt 2)=\ldots=P^{(m)}(\sqrt 2)=0$ and $P^{(m+1)}(\sqrt 2)\ne 0$ for some odd number $m$, and by the above remark, thius again is equivalent to $P'(-\sqrt 2)=P''(-\sqrt 2)=\ldots=P^{(m)}(-\sqrt 2)=0$ and $P^{(m+1)}(-\sqrt 2)\ne 0$, i.e., that $P$ has an extremum at $-\sqrt 2$.


Example of a non-measurable maximum likelihood estimator

Question: If you have a measurable parameter space $(\Theta, \mathcal{F})$ and a parametric family of probability measures $(P_\theta)_{\theta \in \Theta}$ on a measurable space $(\mathcal{X}, \mathcal{B})$ that have densities $(f_\theta)_{\theta \in \Theta}$ with respect to some dominating measure $\mu$, then you might define the maximum likelihood estimator $\hat{\theta} : \mathcal{X} \to \Theta$ as
$$
\tag{1}\label{1}
\hat{\theta}(x)
= \operatorname*{arg\,max}_{\theta \in \Theta} f_\theta(x)
$$
for all $x \in \mathcal{X}$.
This is an abstract version of how MLEs are introduced in some statistics texts and classes, but there are a few issues.
For one thing, a global maximum might not be attained, or there might be multiple global maxima, so \eqref{1} isn't necessarily well-defined.
Moreover, if it happens to be well-defined, then is it measurable?
Certainly all examples of maximum likelihood estimators one sees in applied statistics courses (at least that I've seen) are measurable.
Of course you can get around these issues by defining MLEs in a different way: for example, you might call a function $\hat{\theta} : \mathcal{X} \to \Theta$ a maximum likelihood estimator if it is a priori measurable and there exists a set $N \in \mathcal{B}$ such that $\mu(N) = 0$ and
$$
\tag{2}\label{2}
f_{\hat{\theta}(x)}(x) = \sup_{\theta \in \Theta} f_\theta(x)
$$
for all $x \in \mathcal{X} \setminus N$.
However, oftentimes \eqref{2} isn't how maximum likelihood estimation is introduced, and I'm more interested in the question of measurability of functions $\hat{\theta}$ satisfying \eqref{1} or \eqref{2}.

Questions.
Are there any explicit examples in which some reasonable interpretation of \eqref{1} is well-defined (at least off a $\mu$-null set) but not measurable?
Alternatively, can a function $\hat{\theta}$ satisfying \eqref{2} (again, at least off a $\mu$-null set) exist when no such measurable function exists?
What about if $(\Theta, \mathcal{F})$ and $(\mathcal{X}, \mathcal{B})$ are standard Borel spaces?
If there isn't a constructive example, then is there a proof of the existence of an example?

There are various results that give criteria under which there cannot be examples of the kind I'm looking for, thereby restricting the class of spaces and densities that might possess such examples.
Example 1.
Lemma 2 in Jennrich (1969) implies that if

$\Theta$ is a compact subset of a Euclidean space and $\mathcal{F}$ is its Borel $\sigma$-algebra, and
the function $\theta \mapsto f_\theta(x)$ from $\Theta$ into $\mathbb{R}$ is continuous for every $x \in \mathcal{X}$,

then there exists a measurable function $\hat{\theta} : \mathcal{X} \to \Theta$ such that \eqref{2} holds for all $x \in \mathcal{X}$.
Example 2.
Theorem 3.1 in Wagner (1980) (the Kuratowski and Ryll-Nardzewski selection theorem) implies that if

$(\Theta, \mathcal{F})$ is a Polish space with its Borel $\sigma$-algebra,
$(\mathcal{X}, \mathcal{B})$ is any measurable space,
for each $x \in \mathcal{X}$, the set
$$
  F(x)
= \big\{\theta \in \Theta : \text{$f_\theta(x) \geq f_\psi(x)$ for all $\psi\in\Theta$}\big\}
  $$
is nonempty and closed, and
for every open $U \subseteq \Theta$, the set
$$
  \big\{x \in \mathcal{X} : F(x) \cap U \neq \emptyset\big\}
  $$
belongs to $\mathcal{B}$,

then there exists a measurable function $\hat{\theta} : \mathcal{X} \to \Theta$ such that $\hat{\theta}(x) \in F(x)$ for all $x \in \mathcal{X}$ (i.e., \eqref{2} holds for all $x \in \mathcal{X}$).
Thus, under the additional assumptions of Example 1 or Example 2 there always exists a measurable maximum likelihood estimator.
Example 3.
Theorem 7.50(b) in Bertsekas and Shreve (1996) implies that if

$(\Theta, \mathcal{F})$ and $(\mathcal{X}, \mathcal{B})$ are standard Borel spaces, and
for every $c \in \mathbb{R}$, the set
$$
\big\{ (x, \theta) \in \mathcal{X} \times \Theta : f_\theta(x) > c \big\}
$$
is an analytic subset of $\mathcal{X} \times \Theta$,

then the set
$$
I = \left\{ x \in \mathcal{X} : \text{$f_\theta(x) = \sup_{\psi\in\Theta} f_\psi(x)$ for some $\theta \in \Theta$}\right\}
$$
is universally measurable. Moreover, for each $\varepsilon > 0$ there exists a universally measurable function $\hat{\theta} : \mathcal{X} \to \Theta$ such that \eqref{2} holds for all $x \in I$, and for all $x \in \mathcal{X} \setminus I$,
$$
f_{\hat{\theta}(x)}(x)
\geq \begin{cases}
\sup_{\psi \in \Theta} f_\psi(x) - \varepsilon, & \text{if $\sup_{\psi \in \Theta} f_\psi(x) < \infty$,} \\
\varepsilon^{-1}, & \text{if $\sup_{\psi \in \Theta} f_\psi(x) = \infty$.}
\end{cases}
$$
Example 3 doesn't necessarily guarantee the existence of a measurable maximum likelihood estimator (for instance, since there are universally measurable sets which are not Borel), but it is arguably in the same spirit as Example 2.
Comment: Since a measurable function is defined between two measurable spaces, the parameter space $\Theta$ would need to be endowed with a natural measure for the question to be well-defined.
Comment: Any text that proposes $\Theta$ is a measure space is going to present a Bayesian theory rather than MLEs.  (Classical texts do not make any such assumption because they do not always need to model the parameter as a random variable.)  In this sense your characterization of the situation appears not to reflect anything one would find in any account of MLE.
Comment: @whuber I'm not assuming $\Theta$ is a measure space, merely that it's endowed with a $\sigma$-algebra. In most situations in practice $\Theta$ is a Borel subset of a Euclidean space, so it comes with a natural $\sigma$-algebra that doesn't need to be mentioned. If the parameter space isn't endowed with a $\sigma$-algebra then we can't talk about parameter-valued estimators
Comment: My sense is it's possible, but imposing "regularity conditions" on the parameterization might help ensure measurability.  That means the parameterization has to be continuous relative to some reasonable topology on the space of probability distributions.
Comment: @Xi'an there is no measure involved in the definition of a measurable map (or a measurable space for that matter). In the measure-theoretic development of statistics, estimators need to be measurable functions. Otherwise we couldn't talk about distributions of estimators.
Comment: Those are good points.  But I think you don't need that extra structure.  It occurs to me you could explicitly state $\Theta$ has no given sigma algebra and then proceed to develop estimators anyway.  However, in order to view the estimators as random variables one needs *some* sigma-algebra on $\Theta,$ but why can't it be imposed for this purpose--perhaps depending on the estimators and what one wants to prove about them--rather than given as part of the problem?
Comment: @whuber I'm ok with that proposal. The question then becomes, once all $\sigma$-algebras are chosen so that one can talk about the measurability of parameter-valued estimators, is it possible for equation (1) to be well-defined but not measurable?
Answer: Here is a contrived example.
Let $(\mathcal{X}, \mathcal{B})$ be the interval $[0, 2]$ with its Borel $\sigma$-algebra, let $(\Theta, \mathcal{F})$ be the interval $[1, 2]$ with its Borel $\sigma$-algebra, and let $P_\theta$ be the uniform distribution on $[0, \theta]$ for each $\theta \in \Theta$.
The family $(P_\theta)_{\theta \in \Theta}$ is dominated by the restriction of Lebesgue measure to $\mathcal{X}$ (call it $\mu$ as in the question), and a sensible choice of density for $P_\theta$ with respect to $\mu$ is
$$
f_\theta = \theta^{-1} \mathbf{1}_{[0, \theta]}.
$$
The maximum likelihood estimator $\hat{\theta} : \mathcal{X} \to \Theta$ is then given by
$$
\hat{\theta}(x) = \max\{1, x\},
$$
which is certainly measurable.
However, suppose I'm not sensible, and that I have a favorite Vitali set $V \subseteq [0, 1]$, and I define a family $(g_\theta)_{\theta \in \Theta}$ of functions $\mathcal{X} \to \mathbb{R}$ as follows:

if $\theta - 1\in V$, then $g_\theta = 3 \mathbf{1}_{\{\theta - 1\}} + \theta^{-1} \mathbf{1}_{[0, \theta] \setminus \{\theta - 1\}}$;
if $\theta - 1\notin V$, then $g_\theta = f_\theta$.

In other words,
$$
g_\theta(x)
= \begin{cases}
3, & \text{if $x \in V$ and $x = \theta - 1$,} \\
f_\theta(x), & \text{otherwise}
\end{cases}
$$
for all $x \in \mathcal{X}$ and $\theta \in \Theta$.
Since each $g_\theta$ is a modification of $f_\theta$ on at most a singleton, the family $(g_\theta)_{\theta \in \Theta}$ is another family of densities for $(P_\theta)_{\theta \in \Theta}$ with respect to $\mu$.
Now one can check that there is a unique function $\hat{\vartheta} : \mathcal{X} \to \Theta$ such that
$$
g_{\hat{\vartheta}(x)}(x) = \sup_{\theta \in \Theta} g_\theta(x)
$$
for each $x \in \mathcal{X}$; this function is given by
$$
\hat{\vartheta}(x) = \begin{cases}
\max\{1, x\}, & \text{if $x \notin V$,} \\
x + 1, & \text{if $x \in V$,}
\end{cases}
$$
and it is not measurable (for example, since $\{x \in \mathcal{X} : \hat{\vartheta}(x) = x + 1\} = \{0\} \cup V$).
Thus, in the setup with the family of densities $(g_\theta)_{\theta \in \Theta}$, there exists a function $\hat{\vartheta} : \mathcal{X} \to \Theta$ such that
$$
g_{\hat{\vartheta}(x)}(x) = \sup_{\theta \in \Theta} g_\theta(x)
$$
for all $x \in \mathcal{X}$, but no such measurable function exists.
This example merely shows that the the question of whether a measurable maximum likelihood estimator exists is sensitive to the choice of version of the Radon-Nikodym derivative $dP_\theta / d\mu$. When we used the much more reasonable family of densities $(f_\theta)_{\theta \in \Theta}$ we had no trouble obtaining a measurable maximum likelihood estimator, but when we artificially perturbed each of these densities on a null set to obtain $(g_\theta)_{\theta \in \Theta}$, we ran into problems.
This example is inspired by Example 2.2 in Pfanzagl (1969), wherein a similar but much more subtle modification of densities yields a scenario in which no maximum likelihood estimator exists at all, measurable or not.


Does the -o-animation vendor prefix exist?

Question: I'm trying to find out if I need to include the -o-animation vendor prefix in my CSS, but I can't seem to find any resources which indicates it exists, and if it does, what versions of Opera it applies to.
Can anyone offer some suggestions?
Comment: According to Can I Use (http://caniuse.com/#feat=css-animation), the prefix was used in the Opera 12.00 series. See also https://developer.mozilla.org/en-US/docs/Web/CSS/animation#Browser_compatibility
Comment: According to [can I use](http://caniuse.com/#search=animation), they use `-webkit-` straight away. This probably has to do with [Opera moving to webkit recently](http://my.opera.com/ODIN/blog/300-million-users-and-move-to-webkit).
Answer: The -o-animation vendor prefix is no longer required for Opera, unless you need to support old Opera v12.** versions.
Instead, use the -webkit-animation vendor prefix to support newer Opera.
Answer: According to Opera 12.10 release notes, you didn't need the -o- vendor prefix from that version on. Adding -o- was therefore just needed to support Opera 12.0x versions.


PHP preg_replace replace between slash

Question: I have a PHP function which is supposed to remove a value with its starting / and ending / from a given URL.
for example: remove /page_###/ from http://my-domain.com/search/page_2/order_asc.
the result will be: http://my-domain.com/search/order_asc.
but also the URL may be like this: http://my-domain.com/search/order_asc/page_2. there is no ending / in the end;
function stripDir($url, $mask){
    return preg_replace('/' . $mask . '[\s\S]+?/', '', $url);
}

the above function should be able to remove page_5 from following URLS...
stripDir('http://my-domain.com/search/page_5/order_asc', 'page') and stripDir('http://my-domain.com/search/order_asc/page_5', 'page')
Answer: The /s in your current regular expression are delimiters, not the starting and ending characters you are looking for. Try changing the delimiter and it should work. Also if the trailing / is optional you should modify the regex I think:
~/page_[\s\S]+?(/|\z)~

or per your function:
~/' . $mask . '[\s\S]+?(/|\z)~

would work for you.
Demo: https://regex101.com/r/sH7bE2/3
Demo of just modified delimiters: https://regex101.com/r/sH7bE2/2
Demo of original regex: https://regex101.com/r/sH7bE2/1
Also since you are checking for the starting and ending / you're going to want to re-place one of those /s.
With substitution demo: https://regex101.com/r/sH7bE2/4
Answer: function stripDir($url, $mask) {
    return preg_replace('/\/' . preg_quote($mask, '/') . '[^\/]+/', '', $url);
}

Comment: Answers should have a write up with them.

PHP preg_replace replace between slash


passing functions as arguments in clojure

Question: I have a function which takes a function and a number and returns the application of the function on the number, and a cube function:
(defn something [fn x]
  (fn x))

(defn cube [x]
  (* x x x))

When I call the function as follows it works:
(something cube 4)

but this returns an error:
(something Math/sin 3.14)

However, this works:
(something #(Math/sin %) 3.14)

What is the explanation?
Answer: Math.sin is not a function! It is a method straight from Java, and doesn't understand the various rules that Clojure functions have to follow. If you wrap it in a function, then that function can act as a proxy, passing arguments to the "dumb" method and returning the results to your "smart" function-oriented context.
Comment: Can you ask this as a real SO question rather than in the comments? The formatting in here is pretty lackluster, and I don't really want to add "another answer" to a completely unrelated question.
Comment: Thanks, now I understand. Actually I was trying to understand macros when this confusion arose. Can you explain this line to me?       - 'Since macros don't evaluate their arguments, unquoted function names can be passed to them and calls to the functions with arguments can be constructed. Function definitions cannot do this and instead must be passed anonymous functions that wrap calls to functions.'
Comment: My confusion is that I have clearly passed an unquoted function 'cube' to 'something' and that works.
Comment: Posted a new question here - http://stackoverflow.com/questions/5727923/macros-and-functions-in-clojure


Is it feasable to translate a Chinese HP Driver to english?

Question: I apologize for the naivety of this question, I've some programming experience, but none writing drivers.
We have an older HP DesignJet 5000ps plotter. The only Windows 7 driver we were able to find for it is in Chinese... which works ok until we need to change the settings (there was an employee who spoke Mandarin, but he/she left).
I'm assuming, for the driver to work with windows properly, the source code is in English and simply the user interface is in Mandarin, so if I could access it, it would be a matter of changing the output for the various display options.
Thank you for your time.
Comment: According to this [other forum post elsewhere](http://www.experts-exchange.com/questions/27244983/HP-Designjet-5000-64-Bit-Drivers-Can-5500-drivers-work.html), you should get away with the HP DesignJet 5500 drivers - or maybe [this link here](http://www.driverscape.com/download/hp-designjet-5000ps-42-by-hp) will help? Seems to be Win7 drivers - not sure about the language
Answer: It looks like the following link has the English driver you are looking for:
http://h20564.www2.hp.com/hpsc/swd/public/readIndex?sp4ts.oid=58144
You can choose the language and the operating system version from the dropdown menus. If you have a newer Windows, you can run the software with XP compatibility settings if there are any problems.