Layout programaticamente ou no XML

Question: Fiz um layout em XML, com o tempo comecei a perceber que o layout programaticamente tem mais facilidade de modelar a tela conforme a interação do usuário. Programaticamente é melhor que em XML? E se for, existe algum "tutorial" de criação?
Comment: Antes de qualquer coisa, comece fazendo o [tour](https://pt.stackoverflow.com/tour) para entender como a comunidade funciona; depois leia o guia de [Como perguntar](https://pt.stackoverflow.com/help/dont-ask) para verificar como pode melhorar sua pergunta e, por fim, acesse a [central de ajuda](https://pt.stackoverflow.com/help) para verificar vários artigos que te lhe ajudarão a entender melhor o site.
Comment: Desculpe, foi a pressa e frustação em enviar a pergunta. Vou ter mais cuidado nas futuras dúvidas....
Answer: De forma geral é gosto, mas dá para afirmar que o código imperativo (o que está chamando de programaticamente) sempre será mais flexível ou poderoso, a não ser que a tecnologia tenha muita "mágica", e mesmo assim só será melhor em alguns pontos específicos onde a mágica foi criada. A forma declarativa (que o AP chama de XML) pode ser mais prática em certos pontos porque elimina certo boilerplate e adiciona alguns, e permite uma forma que designers estão mais acostumados, principalmente se já usou HTML. A forma declarativa, apesar de ser usada para dar informações para a aplicação programar o dispositivo computacional, não é exatamente programação. Uma forma declarativa nunca consegue ter o poder da programação.
Se quer fazer layouts dinâmicos então a solução quase sempre é fazer programaticamente. Tem algumas formas para dar certo dinamismo de forma declarativa, mas é bem limitado.
Não conheço o stack de tecnologia do Android em profundidade, mas a forma declarativa tende a ser mais lenta, principalmente se isto é interpretado em tempo de execução. Mesmo que um código seja gerado em tempo de compilação partindo da declaração feita no XML, ainda deve ficar mais lento. É como comparar uma linguagem de alto nível com Assembly (bem feito), é muito difícil a linguagem de alto nível produzir um Assembly tão otimizado quanto dá para fazer na mão. A questão é fazer bem feito, fazer o código na mão pode até ser pior se for mal feito, mas é mais raro acontecer este tipo de erro, a pessoa tem que ser muito sem noção, ao contrário do que acontece com Assembly que tem outro nível de abstração.
Esse custo de performance pode até ser intermediário, ou seja, gerar um código da linguagem de programação no processo de JITting.
Também não sei se tem alguma desvantagem fazer em código, tem tecnologia que usa uma forma de XML que tem um código para distribuir muito menor.
De forma geral as pessoas usam a forma declarativa também porque tem mais documentação e mais suporte da comunidade, afinal se todo mundo faz assim pode obter mais ajuda.
Eu gosto mais de fazer com código, mas não descarto fazer algo declarativo se me mostrar vantagens ou for necessário por algum motivo que foge do meu controle. Não tem melhor, tem gosto e necessidade. Se a pessoa não souber programar com código imperativo pode ser pior. Então se está com alguma dificuldade precisa saná-las, não existe forma automática de resolver isso. Desenvolver software é difícil e precisa dominar tudo para alcançar bons resultados.
Comment: Entendi, muito obrigado, no que estou fazendo, mesmo não entendendo direto, o código imperativo fica mais interessante. Vou estudar mais sobre, me ajudou muito sua informação... Obrigado
Answer: O que é melhor em programação depende do contexto. A mesma abordagem pode ser melhor numa situação e não o ser noutra.
A utilização do xml é na maioria das situações, por ser declarativa, mais eficiente na perspectiva do programador. Você diz o que quer e o Android fica encarregue do "como o fazer".
No Java é possível fazer tudo o que é feito por xml mas é mais "trabalhoso" e necessita de um bom conhecimento de como as "coisas" funcionam, já que tem de ser você a dizer como se faz. No entanto, é mais versátil.
Uma das razões para utilizá-lo será aquela que refere: layouts dinâmicos, em função de inputs do utilizador.
Neste momento está em desenvolvimento uma api(Jetpack Compose) que permite construir de forma declarativa layouts directamente no código, no caso usando Kotlin.
Comment: Obrigado, quero fazer muitas interações dinâmicas, e achei de fato mais interessante em código imperativo. Vou estudar mais sobre...

Layout programaticamente ou no XML


Programmatically alter user permissions

Question: The current state of the site, is configured such that authenticated members, can post specific content types and comment on everything.
What was asked of me, was the restriction of users having tagged (taxonomy) themselves as "private" (their profiles aren't accessible), not being able to perform the above operations.
Apart from assigning a new role, on user update and having one more role to manage, is there another way to do that?
Ideally I'd like to assign to a "private" user the same rights as an anonymous user but without actually making him one, since I am already filtering for authenticated users in views and such.
Comment: I don't see any comment button, so I just have to post my 'answer'. How about adding a hidden field in the user-profile? But that will give you more work to-do than just simply adding a new role :)
Answer: Well, there is a way to do this, without the need to create an extra role. The code below should give you at least a hint on how to do it. You will need to create a custom module if you don't already have one and modify the function names and code where appropriate accordingly. Be warned though: the code is not tested :)
<code>/**
 * Implements hook_user_load().
 */
function my_module_user_load($users) {
  foreach ($users as &$account) {
    // Check if the user's profile is private
    if (_my_module_user_profile_is_private($account)) {
      static $drupal_static_fast;
      if (!isset($drupal_static_fast)) {
        $drupal_static_fast['perm'] = &drupal_static('user_access');
      }
      $perm = &$drupal_static_fast['perm'];

      if (!isset($perm[$account->uid])) {
        // If you want, you can add here a new "virtual role"
        // $account->roles[ROLE_ID] = 'custom role';

        // Make a copy of the roles array,
        // because we don't want to make changes on the user object
        $account_roles = $account->roles;

        // Remove the authenticated role, before querying all permissions
        if (isset($account_roles[DRUPAL_AUTHENTICATED_RID])) {
          unset($account_roles[DRUPAL_AUTHENTICATED_RID]);
        }

        // Get all permissions for user's roles
        $role_permissions = user_role_permissions($account_roles);

        $perms = array();
        foreach ($role_permissions as $one_role) {
          $perms += $one_role;
        }

        $perm[$account->uid] = $perms;
      }
    }
  }
}

/**
 * Helper function.
 *
 * Checks if a user's profile is private.
 */
function _my_module_user_profile_is_private($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }
  // Check if the user's profile is private
  // ...
  return TRUE; // just for testing
}
</code>
Comment: Seems legit, I'll try it out and return with a checkmark later.
Comment: Code has some logical errors but the gist is valid. Sadly, it does not meet my needs from the business logic point of view after all but it answers the original question so here you go.
Comment: Hmm after some further testing this does not seem to throw 403's wherever needed even with permissions manipulated accordingly :/
Comment: If it's not a caching issue, then it must be the code. I'm afraid I can't be of more help without seeing the final code you came up with.

Programmatically alter user permissions


Give a new class by ng-class with variable value

Question: Hi I've got follow code:

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.fieldSize = "cInputLarge"; //Change for the effect to -> cInputMedium, cInputLarge
});
.cDefault {
  width: 50px;
}
.cInputMedium {
  width: 100px;
}
.cInputLarge {
  width: 200px;
}

  <input class="cDefault" ng-class="{{fieldSize}}">

{{fieldSize}}

My goal is, to give to the input a class name, which changes the width of it. I know how ng-class works with conditions, but is something like this also possible (to give a class name in the ng-class and it takes it's properties)?
Thanks and cheers.
Answer: Just use the name of the variable, it should be sufficient:

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.fieldSize = "cInputLarge"; //Change for the effect to -> cInputMedium, cInputLarge
});
.cDefault {
  width: 50px;
}
.cInputMedium {
  width: 100px;
}
.cInputLarge {
  width: 200px;
}

  <input class="cDefault" ng-class="fieldSize">

{{fieldSize}}

Comment: Hi and thanks for you answer, it works! I will mark it as correct answer as soon as possible. Cheers!
Answer: Yes its  correct .
You can bind to a scope variable
Comment: Hi, but look at my snippet... it's still 50px and not 200px from the binded class...?
Comment: I checked it is width: 200px;
Answer: Or try this
   <input class="cDefault"  ng-class="{{'fieldSize'}}">


What is a white noise process?

Question: What is the best way of defining white noise process so it is intuitive and easy to understand?
Comment: Noises (stationary random series) are classified by a [PSD](https://en.wikipedia.org/wiki/Spectral_density) color indicating how energy is distributed over frequency . *White* has the meaning of *uniform distribution* (flat), like in white light or white acoustic noise. White noise is made of all frequencies in equal proportions (not found in nature). *Red*: Energy decreases with frequency. *Pink*, Between white and red: Energy decreases, but is equal per octave, common in nature.  *Blue*: Energy increases (radioactivity). See [Colors of noise](https://en.wikipedia.org/wiki/Colors_of_noise)
Answer: A white noise process is one with a mean zero and no correlation between its values at different times. See the 'white random process' section of Wikipedia's article on white noise.
Comment: @mpiktas, i usually explain the white noise to students through the spectral density concept, at least it gives light to (through the analogy with white color) why the noise is "white", and why the $AR(1)$ process could be could called "red" and there is no "black noise" :)
Comment: you forgot the constant variation. If variation varies, then the process is not white noise.
Comment: When you say correlation between values at different times... do you think all possible lag combinations or only t vs t-1?
Comment: @user333 *All* nonzero lags: that's the first equation in the Wikipedia link @onestop gave.
Comment: @mpiktas: you're right, good point.
Comment: @mpiktas do you mean variance when you say variation?
Comment: @user32423, yes, I meant variance.
Comment: What about the "white" part? If there is no correlation at very small time lags, won't the power be too concentrated toward the high frequency end of the spectrum?
Answer: A white noise process is a random process of random variables that are uncorrelated, have mean zero, and a finite variance.
Formally, $X(t)$ is a white noise process if $$E(X(t)) = 0, E(X(t)^2) = S^2\text{, and } E(X(t)X(h)) = 0 \text{ for } t\neq h\text{.}$$
A slightly stronger condition is that they are independent from one another; this is an "independent white noise process."
Answer: I myself usually think of white noise as an iid sequence with zero mean. At different times values of the process are then independent of each other, which is much stronger requirement than correlation zero. What is the best with this definition that it works in any context.
Side note. I only explained my intuition, the correct definition of white noise is given by @onestop. The definition I gave is mathematically defined as white noise in strict sense.

What is a white noise process?


Group by with multiple properties on single array using JavaScript

Question: I have array of objects on which I want to apply groupBy() with two fields. I can achieve group by with single field but not able to achieve with 2 fields.
I want output in following format:
{
   data: [
     {
        "name":"que1",
         "image":"img1",
        "data":[
            {
               "name":"que1",
               "title":"title1",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
            {
               "name":"que1",
               "title":"title2",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
            {
               "name":"que1",
               "title":"title3",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
           {
               "name":"que1",
               "title":"title4",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            }
           ]
     },
    {
       "name":"que1",
         "image":"img1",
        "data":[
            {
               "name":"que1",
               "title":"title1",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            },
            {
               "name":"que1",
               "title":"title2",
               "description":"desc1",
               "instruction":"inst1",
               "image":"img1",
            }
          ]
    }
  ]
}

_.chain(quesList)
        .groupBy("category","image")
        .map((value, key) => ({ name: key, data: value }))
        .value()

Is it possible to achieve this kind of output?
Comment: You can use a function for the groupBy iteratee in which you can do whatever you want e.g. item => item.category + "#" + item.image;
Comment: What's your input (`quesList`)? Have you tried `.groupBy(["category","image"])`? (Note `[` and `]`)
Comment: Yes, @barbsan.. I tried ```.groupBy(["category","image"])``` but not giving me as I want..
Comment: Yes, @GruffBunny, by concatenating I am getting what I want. Thank you..
Answer: Try concatenating them to use as a virtual key for grouping, as you can use a callback as the grouping algo, so just concatenate and return that.
Don't concatenate straight forward, it can have ambiguity problem. (eg: "AB" + "C" and "A" + "BC" is resulting the same) Use any separator and concatenate.
Just modifying your ans:
_.chain(quesList)
        .groupBy(({category,image}) => category + '|' + image)
        .map((value) => ({ name: value[0].name, image: value[0].image, data: value }))
        .value()

Each group mast have some value (in a result of group by, otherwise it will not form a group), so you can take the properties from the first object blindly.
Note: Correct properties name which you want to map outside, as I just guessed and placed name and image


How to sort a Alphanumeric string with special characters in C# using Linq?

Question: How to sort a Alphanumeric string with special characters in C# using Linq?
Order should be first special characters, then numbers and then alphabets.
Example :
Input - { Hello, #Test, @Red, &While, 123@Test, @123Test, %54Sun, Dom, Left }
Expected - { @123Test, %54Sun, @Red, #Test, &While, 123@Test, Dom, Hello, Left }
enter image description here
Comment: Then `input.OrderBy(x => x)` is perfectly fine.
Comment: Sort method returns the desired result... not the _Expected_ one that seems to be wrong; could you please add real code, or at least real data?
Comment: Any specific requirements on how to order within the special characters? The standard order function gives: "@123Test", "@Red", "&While", "#Test", "%54Sun", "123@Test", "Dom", "Hello", "Left".
Comment: @KlausGütter No specific requirement within special characters. the order should be first special characters, then numbers and then alphabets. Thanks.
Comment: @KlausGütter I tried input.OrderBy(x => x) the result I have attached above when I click on column for sort in descending
Comment: Better add this as text, not as image. Your result seems to use different input that the example in your question, right?
Comment: Yes its different example
Answer: As the standard string comparison does exactly that, you can just use OrderBy:
var input = new[] { "Hello", "#Test", "@Red", "&While", "123@Test", "@123Test", "%54Sun", "Dom", "Left" };
foreach (var s in input.OrderBy(x => x)) Console.WriteLine(s);

Gives:
@123Test
@Red
&While
#Test
%54Sun
123@Test
Dom
Hello
Left

Since the string comparison is culture-dependent, this might be different depending on your current culture. If you want it culture-independent, use e.g. OrderBy(x => x, StringComparer.InvariantCulture).
Comment: This is not working when I want to sort the column manually. It working only for once while loading the UI
Comment: You mean in a DataGridView or similar? What exactly are you doing to sort it and what is the result?
Comment: Yes it is a DataGridView and I am trying to sort by clicking on column
Comment: But this is really something different now. Mabe ask a new question for this.
Answer: You may use custom implementation of IComparer, then pass it to OrderBy call. E.g.:
public class SpecialCharactersNumbersLettersComparer : IComparer<string>
{
    private readonly IComparer<string> defaultComparer = StringComparer.InvariantCulture;

    private static int OrderOfChar(char ch)
    {
        if(Char.IsLetter(ch))
            return 2;
        if(Char.IsDigit(ch))
            return 1;
        return 0;
    }

    public int Compare(string left, string right)
    {
        if(string.IsNullOrEmpty(left)
          || string.IsNullOrEmpty(right)) {
            return defaultComparer.Compare(left, right);
        }

        var leftChar = left[0];
        var rightChar = right[0];
        var leftOrder = OrderOfChar(leftChar);
        var rightOrder = OrderOfChar(rightChar);

        if(leftOrder == rightOrder)
            return defaultComparer.Compare(left, right);

        if(leftOrder > rightOrder)
            return 1;
        return -1;
    }
}

public static List<string> SortSpecialCharactersNumbersAlphabet(IEnumerable<string> input)
{
    return input.OrderBy(_ => _, new SpecialCharactersNumbersLettersComparer())
        .ToList();
}

Used as:
Console.WriteLine(string.Join(", ",
    SortSpecialCharactersNumbersAlphabet(new [] {
    "Hello", "#Test", "@Red", "&While", "123@Test", "@123Test", "%54Sun", "Dom", "Left"})));

produces output:
@123Test, @Red, &While, #Test, %54Sun, 123@Test, Dom, Hello, Left


Polymer: Observar uma variável global

Question: Eu quero criar um elemento que vai abrir um popup e exibir uma mensagem para o usuário. Quero que ele possa ser acessado por qualquer visão do meu sistema. Portanto criei uma variável global que vai ficar responsável em guardar as mensagens de erro. Quero saber como o elemento do popup pode descobrir quando esse variável teve alterações. Estou importando o popup no my-app.html.
app-data.html
<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="app-data">

</dom-module>

menu-perfil.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/app-route/app-location.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/iron-localstorage/iron-localstorage.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="app-data.html">

<dom-module id="menu-perfil">
  <template>

    <app-data id="idpopuphandler" key="popuphandler"></app-data>
    <iron-localstorage name="user-storage" value="{{storedUser}}"></iron-localstorage>

    <iron-ajax
       id="registerLoginAjax"
       method="post"
       content-type="application/json"
       handle-as="json"
       on-response="handleUserResponse"
       on-error="handleUserError"></iron-ajax>

Log in

        <paper-input-container>
          Usuário
          <input is="iron-input" id="username" type="text" bind-value="{{formData.nome}}">
        </paper-input-container>
        <paper-input-container>
          Senha
          <input is="iron-input" id="password" type="password" bind-value="{{formData.senha}}">
        </paper-input-container>

          <paper-button raised class="primary" on-tap="postLogin">Log In</paper-button>

  </template>

</dom-module>

popup-message.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-dialog/paper-dialog.html" />
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="app-data.html">

<dom-module id="popup-message">
  <template>

    <app-data key="idpopuphandler" key="popuphandler"></app-data>

    <paper-dialog id="idpopup">
      <template is="dom-repeat" items="[[error]]">

[[item.message]]

      </template>

      <paper-button dialog-dismiss>Ok</paper-button>
    </paper-dialog>
  </template>

</dom-module>

Answer: Eu mudei o tipo da variável global para booleano.
popup-message.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-dialog/paper-dialog.html" />
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="app-data.html">

<dom-module id="popup-message">
  <template>

    <app-data id="idpopuphandler" key="popuphandler" data="{{popuphandler}}"></app-data>
    <app-data id="idpopupdata" key="popupdata"></app-data>

    <paper-dialog id="idpopup">
      <template is="dom-repeat" items="[[messages]]">
-
[[item.message]]

-      </template>

      <paper-button dialog-dismiss>Ok</paper-button>
    </paper-dialog>
  </template>

</dom-module>

menu-perfil.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/app-route/app-location.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/iron-localstorage/iron-localstorage.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="app-data.html">

<dom-module id="menu-perfil">
  <template>

    <app-data id="idpopuphandler" key="popuphandler"></app-data>
    <app-data id="idpopupdata" key="popupdata"></app-data>
    <iron-localstorage name="user-storage" value="{{storedUser}}"></iron-localstorage>

    <iron-ajax
       id="registerLoginAjax"
       method="post"
       content-type="application/json"
       handle-as="json"
       on-response="handleUserResponse"
       on-error="handleUserError"></iron-ajax>

Log in

        <paper-input-container>
          Usuário
          <input is="iron-input" id="username" type="text" bind-value="{{formData.nome}}">
        </paper-input-container>
        <paper-input-container>
          Senha
          <input is="iron-input" id="password" type="password" bind-value="{{formData.senha}}">
        </paper-input-container>

          <paper-button raised class="primary" on-tap="postLogin">Log In</paper-button>

  </template>

</dom-module>

Polymer: Observar uma variável global


Is there a way to export List of objects to .CSV in Java using OpenCSV?

Question: I try to generate a .csv file in Java using OpenCSV. I want to generate results without hardcoding.
I have an entity  with has fields like: Id, Title, Overview, etc.
In List movies I store all data from database.
I want to write this list in .csv without tell headers or other things.
Example.
...writeToCSV(Movie.class) not writeToCSV("ID", "Title', etc)
In first step, I used Apache POI, but he don't work properly.
<code>@Slf4j
@Setter
@NoArgsConstructor
public class CSVHelper {
    private CSVFormat csvFormat;
    private PrintWriter printWriter;
    private CSVPrinter csvPrinter;

    public void writeHeader(Class<?> c) {
        List<String> headers = getHeaders(c);
        try {
            setCsvPrinter(new CSVPrinter(printWriter, csvFormat));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        headers.forEach(header -> {
            try {
                csvPrinter.print(header);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void writeToCsv(List<?> list, Class<?> c) {
        writeHeader(c);
        List<String> headers = getHeaders(c);
        try {
            setCsvPrinter(new CSVPrinter(printWriter, csvFormat));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        list.forEach(o -> {
            try {
                csvPrinter.println();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            headers.forEach(header -> {
                try {
                    Method method = c.getMethod("get" + header.substring(0, 1).toUpperCase() + header.substring(1));
                    String value = String.valueOf(method.invoke(o));
                    csvPrinter.print(value);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        });
    }

    private static List<String> getHeaders(Class<?> c) {
        List<Field> fields = List.of(c.getDeclaredFields());
        return fields.stream().map(Field::getName).collect(Collectors.toList());
    }
}
</code>
I like to use direct object to method, without any code from me. This code is working but on any change to the entity it does't work.
Comment: How is this related to `apache-poi`?
Comment: I did not find anything specific in Apache POI to automatically select the fields from a certain class. I resorted to writing the code and just sending the fields. It was a headache until I selected all the fields, the methods for the getters. After I got all the names I wrote them with apache poi
Comment: I didn't want to have hradcoded headers, the fields will differ over time, I can't rely on that
Comment: This question is not about `apache-poi`. So it also should not tagged as such. Please remove that tag.
Comment: Related: [StatefulBeanToCsv with Column headers](https://stackoverflow.com/q/46072947/12567365)
Answer: From the documentation:

The easiest way to write CSV files will in most cases be
StatefulBeanToCsv, which is simplest to create with
StatefulBeanToCsvBuilder, and which is thus named because there used
to be a BeanToCsv.Thankfully, no more.

<code> // List<MyBean> beans comes from somewhere earlier in your code.
 Writer writer = new FileWriter("yourfile.csv");
 StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
 beanToCsv.write(beans);
 writer.close();
</code>
Source: http://opencsv.sourceforge.net/#writing_from_a_list_of_beans


Will all Drupal 7 Ubercart 3 orders be deleted if I disable & uninstall all Ubercart related modules?

Question: I'm working on migrating a Ubercart site to Commerce and wanted to know if all Ubercart orders and tables will be deleted if I disable & uninstall all related modules. Since I don't need the old data, I don't mind it having it completely deleted.
Answer: If you uninstall them, then yes.
EDIT:
No, they will not. Good call, duckx (I shouldn't have assumed that the D7 version implemented hook_uninstall_schema()).
Comment: actually they do not.. i just did an uninstall and see my database alot of the uc_ table are still there: ---->

uc_order_statuses
uc_orders
uc_packaged_products
uc_packages
uc_payment_check
uc_payment_cod
uc_payment_cybersource_hop_post
uc_payment_other
uc_payment_paypal_ipn
uc_payment_receipts
....
Comment: Good call @duckx -- I can only assume their reasoning for this is in case you want the data preserved...? #wtf
Comment: seems like i have to delete all this stuff myself. I hope it doesnt break anything even though all the modules are uninstalled. --- http://prntscr.com/19ej2b
Comment: correction ubercart did delete the tables. I must have somehow missed typing  drush pm-uninstall in my bash script


Repeating the result of a user input

Question: I'm currently using the following VBA code to prompt the user to enter how many people will be needed for processing a spreadsheet.
Dim N As Long
    N = Application.InputBox(Prompt:="Enter value", Type:=1)
        If N > Rows.Count Then
            N = Rows.Count
        End If

        For i = 1 To N
            Cells(i + 1, 19) = i
        Next i

It accomplishes what I initially need as shown in the image but I want to repeat the count until the end of the document based on what data is left in column A. So the count should start at 1 in cell S20.
Any thoughts?
Screenshot of initial Result
Comment: Are you just wanting to fill in the next `N` rows each time, or do you want to repeat the numbers `1,2,3,...,N` as many times as necessary to get to the end of column A?
Comment: Hi, I want repeating numbers based on the users entry to run down Column S until there is no data in Column A.  i know a loop is involved but i can't figure it out.
Comment: If you're asking the users to enter a number then it seems that your code is working as designed.  If you want your code to update column S with numbers 1,2,3,...N until column A is null, then that's different and why ask the users how many people are needed.
Comment: Overall i can have about 50 to 500 rows of information that will need to be divided up among employees to review. The amount of employees may differ which is why I wanted the prompt. Based on the user's answer, I wanted to enter 1-N in a column. But i need this to repeat the sequence for every N rows. We can then filter the sheet to show only 1's, 2's or 3's so that the each employee who is assigned a number only reviews what is given to them.
Comment: LOL - I have to laugh at the test for `N` being greater than `Rows.Count` - there's not many companies with more than 1,048,576 employees! (But it is always good to build safe code! :D)
Answer: The easiest thing to do is just loop across all the rows, but write out the (slightly adjusted) row number modulo N
Dim N As Long
Dim lastRow As Long

lastRow = Cells(Rows.Count, "A").End(xlUp).Row

N = Application.InputBox(Prompt:="Enter value", Type:=1)

For i = 2 To lastRow
    Cells(i, 19).Value = ((i - 2) Mod N) + 1
Next i

Repeating the result of a user input


Benefits of SDP over other methods

Question: I have general question regarding the benefits of semi-definite programming.
Assuming I have a non-convex program which can by relaxed to an SDP. Why should I use the SDP formulation (and the corresponding SDP solvers) over a standard convex programming formulation (and its corresponding solvers) when I adopt the same relaxation?
To the best of my knowledge, many SDP solvers and many standard solvers for convex programs use interior point methods. Where are the advantages of the one over the other?
Edit (sorry for being so imprecise):
What I meant is the (corner ?) case in which I can relax a non-convex problem to an SDP (e.g. having actually a non-affine equality constraint and using Schur's complement to make it a SDP-conform inequality constraint) and then using an SDP solver like Sedumi. Compared to the case when applying the same/equivalent relaxation to the non-convex problem but then using standard interior points methods directly (e.g. using MATLABs fmincon).
Meaning in the example above, I assume that the objective is convex but there is non-convex constraint.
Edit 2
Assuming e.g. that I have a convex objective and and some convex constraint, and also one non-convex constraint of the form $\delta = d^2$ where $\delta$ is some slack variable. Then I can obtain a SDP-conform relaxation using Schur complement via
$$
S = \begin{bmatrix} 1 & d \\ d & \delta \end{bmatrix} \succeq 0
$$
Consequently, I am forcing all eigenvalues of $S$ to be non-negative. If I now obtain the corresponding constrains on $\delta$ and $d$ such that $S$ is PSD and use them e.g. in fmincon:
What are the benefits of using an SDP solver in the example above, compared to the case where I incorporate the non-negative eigenvalue constraints in to e.g. into fmincon?
Comment: Or, are you referring to situations where the convex relaxation can be formulated as an LP, CQP, or SOCP (all of which can be solved as SDP's)?
Comment: Similar question to Brian here. Do you have a specific example in mind of a non-convex problem with two different nonlinear convex relaxations---one SDP and one otherwise?
Comment: By "standard convex programming formulation" are you referring to a convex optimization problem with arbitrary (perhaps smooth) convex functions in the objectives and constraints?  Or something else?
Comment: @BrianBorchers  I made an edit that hopefully clarifies the questions.
Comment: @MichaelGrant I made an edit that hopefully clarifies the questions.
Comment: fmincon isn't an interior point solver.
Comment: @BrianBorchers I guess it has this option, please see https://de.mathworks.com/help/optim/ug/fmincon.html?requestedDomain=www.mathworks.com#busp5fq-6
Comment: I stand corrected- I had thought fmincon was using SQP.  In any case, you can't formulate an SDP in the form solved by fmincon, and fmincon only obtained locally optimal solutions to nonconvex problems.
Comment: One you have chosen a particular nonlinear relaxation, everything beyond that is just a method of solving that relaxation. Even if you had a choice between fmincon and an SDP solver, you're still solving the same problem, and you can make the choice based on practical concerns like performance.
Comment: There's certainly no need (or benefit) to using an SDP solver to deal with the simple quadratic constraint $d^{2}-\delta \leq 0$.  You can solve this as a convex quadratically constrained quadratic programming problem, use an SOCP solver, etc.
Answer: it certainly is possible to solve semidefinite programming problems by general purpose convex optimization solvers such as the analytic center cutting plane method (ACCPM).  You might consider ACCPM to be an interior point method although it is far more general than the primal-dual interior point method for SDP.  In practice, using a specialized primal-dual interior point method to solve an SDP is faster than using the more general ACCPM.
There are also first-order methods for convex optimization that have been specialized to solving SDP and other conic optimization problems.  These are not considered interior point methods.  See for example the Splitting Conic Solver package.  Compared with interior point methods, the first order methods can often solve larger instances, but the accuracy of solutions produced by the first order methods is often poor in comparison with the accuracy of solutions produced by primal-dual interior point methods.
Interior point methods for smooth nonlinear programming problems (see for example the IPOPT software package) exist, but they aren't properly applicable to SDP because the semidefiniteness constraint isn't expressible in terms of a finite number of inequality constraints involving smooth functions.  For the same reason, other commonly used nonlinear programming methods like sequential quadratic programming aren't useful for solving SDP.
Finally, you might consider applying a general purpose nonlinear programming solver to your original nonconvex formulation of the problem.  However, most nonlinear programming solvers only ensure convergence to a local (not global) minimum of a nonconvex optimization problem, so there's no way to be sure that you've actually solved the problem correctly.  There are specialized methods that do obtain globally optimal solutions to some nonconvex optimization problems, but these are typically limited to very small instances and aren't of much use in practice.
P.S. Added after the original poster explained their problem in more detail.  For a single convex quadratic constraint, SDP is overkill- any solver that can handle a quadratically constrained quadratic program will handle this constraint.
Comment: Thank for your answer, please see also my second edit to the question where I try to formulate an example where the PSD constraint could be formulated by means of further constraints into a form that could be e.g. understood by fmincon.

Benefits of SDP over other methods


Conditionally remove / blank out field values in View using Views PHP

Question: I am trying to build a map (IPVGM) of locations which will be used as a block appended to all entities of type Person. Locations are stored in a taxonomy, with an extra field to hold the coordinates. There are multiple fields in a Person that reference the Locations taxonomy (Field:birthplace and Field:other_locs), and I am trying to plot all of them on the same map. IPVGM can handle multiple locations per row, but the view I've been able to construct so far duplicates the birthplace in every row. This means that IPVGM constructs a map with (in this case) 4 birthplaces.

I'd like to use Views PHP to remove values for birthplace and birthplace coordinates in every row but the first one. I've had some luck trying to do this in the Output Code of Views PHP, but I think it needs to be handled in the Value Code area in order for IPVGM to pick up on the field values (or hopefully lack thereof). Any help? I looked at Views Distinct, and using a Global:PHP filter, but both of these would remove the entire row, when I only want to remove the birthplace & birthplace coordinates components.
Answer: Try to use Views Conditional.
Views Conditional is a simple module that allows you to define conditionals with fields in views.
Conditions include:

Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

Views conditional allows you to output text based on the result of the condition.
Comment: Thanks - I've had success playing with this in terms of getting the view right by adding a view result counter field and then checking against that, but IPGV&M isn't picking up the coordinates generated by Views Conditional. I'm going to open an issue with the IPGV&M module, and I'm going to leave this post open for the moment in hopes of finding a different solution.


Tag  não quebra linha conforme a DIV

Question:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    <form>

            <button type="submit" class="btn btn-danger">Remover</button>

    </form>

Tenho o seguinte acima minha duvida é porque o P dentro da div conforme na imagem não esta se ajustando (quebrando linhas) conforme o normal, obs tenho esse css:
https://gist.github.com/nicollasfeitosa/2d4de32b36fdf3089ba786972c8130ad
Answer: Não esta quebrando linha porque seu texto aaaa... é visto como uma unica palavra (ela não tem espaçamento). Então via CSS você pode indicar que o navegador deve inserir quebra de linha nesses casos, para isso você pode usar a propriedade word-break veja os exemplos abaixo:

.tweetContainer {
  width: 200px;
  border: 1px solid red;
}

.break-all {
  word-break: break-all;
}

.break-word {
  word-break: break-word;
}

    word-break: normal; 11111111111111111 222222222222222222222222222222222222222222 333333333333333333333333333333333333333333

    word-break: break-all; 11111111111111111 222222222222222222222222222222222222222222 333333333333333333333333333333333333333333

    word-break: break-word; 11111111111111111 222222222222222222222222222222222222222222 333333333333333333333333333333333333333333

Tag  não quebra linha conforme a DIV


How do I remove unwanted scrollbar that appears when using "sap.f.ShellBar" for custom launchpads?

Question: A scrollbar appears always if sap.ui.core.ComponentContainer height is 100%, on screens of Notebook-size or smaller if 95%. Page endings look out of position if set below 95%. Auto-size won't work.
How to get rid of the scrollbar?
In index.html:
// On core init:
new sap.ui.core.ComponentContainer({
    height: "95%",
    name: "MyApp",
}).placeAt("content");

In App.view.xml
<mvc:View xmlns:mvc="sap.ui.core.mvc"
    xmlns="sap.m"
    xmlns:f="sap.f"
    height="100%"
    displayBlock="true">
    <f:ShellBar title="MyApp">
    </f:ShellBar>
    <Shell>
        <App id="app">
        </App>
    </Shell>
</mvc:View>

My intention is to create my own version of a launchpad container to host other apps.
UI5 version: latest stable SAPUI5 release
Answer: You might want to try the approachs in samples Shell Bar with Flexible Column Layout or Shell Bar with Split App
sap.m.Shell does not appear to play well when there are sibling controls in the page. It is usually used as the top container in the page.


Plotar função em PYTHON ou MATLAB

Question: Galera preciso plotar uma função e não consigo achar ferramentas legais para isso, pois a função tem por definição constantes, e achei por bem usar uma linguagem de programação pra isso, porém não sei python , nem matlab, as únicas que pensei pra esse caso; se alguém puder me ajudar ai e mandar o código e a imagem gráfica, ou qualquer um dos dois ajudaria bastante, pois é pra um relatório de faculdade.
Segue a função:
f(X0) = 76
f(X1) = 121
f(Xn+2) = (2 * f(Xn+1) - f(Xn)) + 18

Comment: matlab custa alguns milhares de reais pela licença de uso, enquanto Python é grátis, aberto e livre - queria entender melhor como  "tanto faz"
Answer: "Funções" são um dos conceitos fundamentais de linguagens de programação modernas - e derivam justamente do conceito de funções em matemática.
Python é uma linguagem de programação robusta, que pode atender o que você precisa - Matlab é uma ferramenta de domínio específico da matemática, desenvolvida e publicada por um único vendedor (empresa), e é algo meio hibrido entre matemática e linguagens de programação - com os avanços das bibliotecas abertas de matemática nos últimos anos, talvez tenha se tornado obsoleto. Então continuo a resposta usando Python.
O primeiro passo é traduzir sua função da notação matemática para uma função em Python - ela fica assim:
def f(x):
   if x == 0:
       return 76
   elif x == 1:
       return 121
   return  (2 * f(x - 1) - f(x - 2)) + 18

Esse tipo de função, que faz uma chamada a ela mesma, é chamada de "função recursiva". Uma chamada a mesma vai retornar um único número para quem a chamou de "fora", apesar de internamente ela ser percorrida várias vezes.
Aqui alguns exemplos da função sendo chamada -
In [30]: f(0), f(1), f(2), f(3), f(4)
Out[30]: (76, 121, 184, 265, 364)

Na verdade, no "maravilhoso mundo da programação", sua função não precisa ser fixa - se você desejar experimentar com outros parâmetros, ela pode ser escrita assim -
e você pode passar qualquer um deles opcionalmente se ela for escrita dessa forma.
def f(x, x0=76, x1=121, x2=18):
   if x == 0:
       return x0
   elif x == 1:
       return x1
   return  (2 * f(x - 1 1, x0, x1, x2) - f(x - 2, x0, x1, x2)) + x2

Para poder usar a função você vai precisar ter um ambiente para usar isso - como você é iniciante, e quer explorar matemática, eu recomendo o uso do ipython notebook - aqui tem um artigo detalhado: https://medium.com/horadecodar/como-instalar-o-jupyter-notebook-windows-e-linux-20701fc583c
Depois de a função estar no lugar, você pode passar ao ato de plotar a função - para isso em Python usamos a biblioteca "matplotlib" -
se você instalou o jupyter notebook com o anaconda, como no artigo que passei,, a matplotlib já está instalada. Senão, com  seu ambiente Python ativo digite "pip install matplotlib" no shell do sistema operacional.
Agora, finalmente, antes de plotar, há um outro aspecto da sua função - para cada valor com o qual ela é chamada, exceto 0 e 1, são geradas outras 2 chamadas de função, com valores menores. Algumas centenas de chamadas de função não são problema algum para o Python ou computadores modernos, no entanto, essa função gera expnencialmente mais chamadas - uma chamada com o valor "34" geraria mais que 2 ** 32 = 4 bilhões de chamadas de função - cada uma tendo que criar internamente um objeto de "frame" e ser processada- talvez o tempo restante de vida do Universo não fosse o suficiente para isso, mesmo com uma CPU i9 rodando a 5GHz.
No entanto isso aconece computacionalmente por que para cada chamada, o computador vai calcular novamente os falores de f(x-1) e f(x - 2) a partir do "zero". Quando fazemos as contas em papel, e estamos preenchendo uma tabela com os valores de "f(x)", os valores para f(x - 1) e f(x - 2) estão prontamente disponíveis nas linahs de cima da tabela.
Então, para poder computar valores dessa função, temos que criar o equivalente computacional dessa tabela com os valores anteriores. Em Python, isso é feito com o decorador de funções "lru_cache". Internamente ele faz exatamente o que fazemos em papel: anota os valores com os quais f(x) já foi chamada, e, se x for repetido, usa o valor já retornado da primeira vez.
Isso efetivamente acaba com o aspecto exponencial da sua função f - já que, ao cálculaur "f(4) ", por exemplo, ele internametne os valores de f(3) e f(2) - mas quando for cálcular f(2), o valor já está na tabela - uma vez que foi preciso durante o cálcul de f(3).
A declaração da função fica assim:
from functools import lru_cache

@lru_cache()
def f(x):
   if x == 0:
       return 76
   elif x == 1:
       return 121
   return  (2 * f(x - 1) - f(x - 2)) + 18

E agora, está tudo pronto para plotar um gráfico de x X f(x), que pode ser feito com:
from matplotlib import pyplot as plt

plt.plot(range(1, 20), list(map(f, range(1, 20))))
plt.show()

Plotar função em PYTHON ou MATLAB


Question about extending a function whose counter-image is a quotient space

Question: Let $H$ be a Hilbert space, $W$ a closed subspace of $H$ and $\mathcal{T}: H\rightarrow H/W$ a well defined linear bounded operator. My question is under what conditions can I find a bounded $T:H \rightarrow H$ such that $q\circ T = \mathcal{T}$, where $q:H \rightarrow H/W$ is the canonical map.
I am currently completely lost and out of ideas, any tip will be appreciated.
Comment: It should be  $q\circ T$ instead $T\circ q.$ The quotient space $H/W$ is isometrically isomorphic to $W^\perp.$
Comment: I see.... Thanks! I also edited the question with your remark.
Answer: Let $P$ denote the orthogonal projection onto $W^\perp.$ Then $I-P$ is the orthogonal projection onto $W.$
Moreover there holds $$\|[v]\|=\|Pv\|\qquad (*)$$ Indeed, we have $v=(I-P)v+Pv,$ hence $[v]=[Pv],$ which implies $\|[v]\|=\|[Pv]\|\le \|Pv\|.$ On the other hand for any $w\in W$ we get
$$\|v+w\|^2=\|Pv+(I-P)v+w\|^2\ge \|Pv\|^2$$
Thus $\|[v]\|\ge \|Pv\|.$
Consider the operator $U:H/W\to H$ given by
$U([v])=Pv.$ The operator is well defined due to $(*).$ The same formula implies that $U$ is a linear isometry.
Observe that $q\circ U=I_{H/W}.$ Indeed
$$(q\circ U)([v])=q(Pv)=[Pv]=[v]$$
Let $T=U\circ\cal{T}.$ Then $$q\circ T=q\circ U\circ \cal{T}=\cal{T}$$


After Drupal 7.32 should sql injection attempts create PDOExceptions?

Question: I have the Logging and Alerts module installed on a few of my sites. Yesterday I noticed a series of notification emails with the following data. These produced PDOException exceptions and so far as I can tell were unsuccessful at doing anything malicious.
This site was patched hours after SA-CORE-2014-005 was announced on 2014-Oct-15.
I simply want verification that these types of SQL injection attacks create PDOExceptions in Drupal, vs stripping the offending key/values from the injection attempt. Prior to the patch I wasn't receiving any such errors.

Email Title from LoggingAlerts module:
[] Error: PDOException: SQLSTATE[42000]: Syntax error or access...

Email Message Body:
email@example.com  Mon, Nov 17, 2014 at 11:04 AM
To: firstname.lastname@example.com
Site: https://site.com
Severity: Error (3)
Timestamp: 20141117 11:04:35
Type: php
IP Address: 128.xxx.xxx.xxx
Request URI: https://site.com/?q=user/login
Referrer URI:
User: Anonymous (0)
Link:
Message:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ' 'test' AND status =
1' at line 1: SELECT * FROM {users} WHERE name = :name_0, :name_1 AND status
= 1; Array
(
[:name_0] => test3
[:name_1] => test
)
in user_login_authenticate_validate() (line 2149 of
/var/www/mysite/htdocs/modules/user/user.module).
$_SERVER => Array
(
[HTTP_HOST] => site.com
[HTTP_X_REAL_IP] => 198.101.235.xxx
[HTTP_X_FORWARDED_FOR] =>

... lots of more lines of email output ...
Answer: It is my understanding that in theory, yes, a compromised site from the particular vulnerability could lead to such behaviour. As Drupal.org recommends, in such cases you should treat your site as compromised and all next actions should be the appropriate for this case.
The fact that you patched the site shortly after the announcement, as you mentioned, is very important. As far as I have seen, most attacks are coming from scripts and it has not come to my attention any automated attack that would cause such behaviour (to my experience of course). This again is not reassuring, just a thought on the possibility for the nasty thing to have happened.
Apart from the obvious actions (see links below), I would definititely take a good look of the code that doesn't behave nicely. Also a good tool is always diff comparing to clean code. I would as well take a good look in the db. Last, there might also be a possibility that some contributed module has got issues with 7.32 or maybe anything else that might have been updated.
Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?
https://www.drupal.org/drupalsa05FAQ
Comment: I believe you're wrong, see my answer below after much much searching.
Comment: Can you please let me know which part of my answer is wrong and why? It seems to me that your answer agrees with it, with more detail why.
Comment: I dont believe my site is compromised. Drupal 7.32 and highe produces a pdoexception on all sql injection attempts
Comment: I never said it is.
Answer: As per this answer -- Drupal throws a PDOException on sql injection attempts as of Drupal 7.32:
https://drupal.stackexchange.com/a/133820/3279
From the testing module:
/**
+   * Test SQL injection via database query array arguments.
+   */
+  public function testArrayArgumentsSQLInjection() {
+    // Attempt SQL injection and verify that it does not work.
+    $condition = array(
+      "1 ;INSERT INTO {test} SET name = 'test12345678'; -- " => '',
+      '1' => '',
+    );
+    try {
+      db_query("SELECT * FROM {test} WHERE name = :name", array(':name' => $condition))->fetchObject();
+      $this->fail('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+    catch (PDOException $e) {
+      $this->pass('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+
+    // Test that the insert query that was used in the SQL injection attempt did
+    // not result in a row being inserted in the database.
+    $result = db_select('test')
+      ->condition('name', 'test12345678')
+      ->countQuery()
+      ->execute()
+      ->fetchField();
+    $this->assertFalse($result, 'SQL injection attempt did not result in a row being inserted in the database table.');
+  }
+

Comment: Thank you. I've been worrying about this same issue since updating. I also see two errors accompanying the PDO exception "Warning: addcslashes() expects parameter 1 to be string, array given in" and "Warning: mb_strlen() expects parameter 1 to be string, array given"... Hope that future versions of Drupal fix this; user input, especially anonymous, should be diligently cleaned and not even reach the database for checks before the cleanups.


Is zookeeper reconfig expected to update the zoo.cfg.dynamic file?

Question: I'm setting up a distributed cluster for ZooKeeper based on version 3.5.2. In specific, I'm utilizing the reconfig command to dynamically update the configuration when there is any rebalance in the cluster (e.g. one of the nodes comes down).
The observation I have is that the zoo.cfg.dynamic file is not getting updated even when the reconfig (add/remove) command is correctly executed. Is this the expected behavior ? Basically I'm looking for guidance whether we should manage the zoo.cfg.dynamic file also through a separate script (update it lock-step with the reconfig command) or can we rely on the reconfig command to do this for us. My preference/expectation is the latter.
Following is the sample command:
reconfig -remove 6 -add server.5=18.104.22.168:1234:1235;1236
Answer: From the reconfig documentation:

Dynamic configuration parameters are stored in a separate file on the server (which we call the dynamic configuration file). This file is linked from the static config file using the new dynamicConfigFile keyword.

So I could practically start with any file name to host the ensemble list and ensure the 'dynamicConfigFile' config keyword just point to this file.
Now when the reconfig command is run, basically a new dynamic-config file (e.g. zoo.cfg.dynamic.00000112) is generated which contains the transformed list of servers, in the form as below (as an example):

server.1=22.214.171.124:2780:2783:participant;2791
  server.2=126.96.36.199:2781:2784:participant;2792
  server.3=184.108.40.206:2782:2785:participant;2793

The zoo.cfg file is hence auto-updated to point the 'dynamicConfigFile' config keyword to the new config file (zoo.cfg.dynamic.00000112). The previous dynamic-config file continues to be available in the runtime (config directory) but it is not being referred by the main config anymore.
So overall, there is no overhead to update any file lock-step to the reconfig command i.e. reconfig command takes care of it all. The only potential overhead to upfront resolve is to write a periodic purge of the old dynamic-config files.


How do you know if a likelihood function is increasing or decreasing?

Question: I have the following function $f(x|\alpha,\beta)=\frac{\alpha}{\beta^\alpha} x^{\alpha-1}, 0\le x \le \beta$ and taking its likelihood I have the following result,
$$lik(\alpha,\beta|x)=\prod_{i=1}^n \frac{\alpha}{\beta^\alpha} x_i^{\alpha-1}*I_{[0,\beta]}(X_i) \\
=\frac{\alpha^n}{\beta^{n\alpha}} \prod_{i=1}^n x_i^{\alpha-1}*I_{[0,\beta]}(X_{(n)})*I_{[0,\infty]}(X_{(1)})$$
Where $X_{(n)}$ and $X_{(1)}$ are order statistics.
Now as I'm trying to find the mle of $\beta$ I'm not understanding the solutions answer of "For any fixed $\alpha,lik(\alpha,\beta|x)=0$ if $\beta<X_{(n)}$ and $lik(\alpha,\beta|x)$ a decreasing function of $\beta$ if $\beta \ge X_{(n)}$. Thus, $X_{(n)}$ is the mle of $\beta$." If you're able to provide a simple graph, that would help me a lot as I'm a visual person.
So my question is, how is $lik(\alpha,\beta|x)$ a decreasing function of $\beta$ if $\beta \ge X_{(n)}$ as I'm having a hard visualizing how this is a decreasing function.
Comment: As $\beta$ gets larger, the value of the likelihood function gets smaller, because $\beta$ is both positive and only in the denominator.
Comment: Yes, the value of the indicator function doesn't change with changes in $\beta$ as long as $\beta \geq x_{[n]}$, it's just a way of writing a constraint on $\beta$, and therefore can be ignored unless the solution winds up at the boundary $\beta = x_{[n]}$.
Comment: @jbowman, wow thank you. I knew it was something easy that I was missing and now with this understanding that we are only interested in the function that variable is associated with makes me understand this problem and others a lot more when it comes to indicator functions. i.e. the function of interest is $1/\beta$. Thank you for the explination.
Answer: You can visualize it as a function of $\beta$
$$lik(\alpha,\beta|x)=\begin{cases}0& \quad \text{if $\beta < X_{(n)}$}\\
\vphantom{\frac{1}{\beta^{n\alpha}}} \smash{\underbrace{{\frac{1}{\beta^{n\alpha}} }}_{\llap{\text{decreasing f}}\rlap{\text{unction of $\beta$}}} }\,\cdot \,\overbrace{ \alpha^n\prod_{i=1}^n x_i^{\alpha-1}}^{\text{constant term}} & \quad \text{if $\beta \geq X_{(n)}$}
\end{cases}
\vphantom{\begin{cases}0& \quad \text{if $\beta < X_{(n)}$}\\
{\frac{1}{\beta^{n\alpha}}} {\overbrace{{\frac{1}{\beta^{n\alpha}} }}^{\llap{\text{decreasing f}}\rlap{\text{unction of $\beta$}}}} \cdot \alpha^n\prod_{i=1}^n x_i^{\alpha-1} & \quad \text{if $\beta \geq X_{(n)}$}  \cdot \overbrace{ \alpha^n\prod_{i=1}^n x_i^{\alpha-1}}^{\text{constant term}}
\\t\\t\\t
\end{cases}}
$$
If this is still too abstract then choose some example data and make a plot of the likelihood for that data.


Zend Framework attach custom event to shared event manager

Question: Using Zend Framework, I want to attach an event on my Application/Module so that on every dispach event this function will be called, for every module. This is my code:
class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }

    public function onBootstrap(MvcEvent $event)
    {
        $application = $event->getApplication();
        $serviceManager = $application->getServiceManager();
        $sessionManager = $serviceManager->get(SessionManager::class);

        // Get event manager.
        $eventManager = $event->getApplication()->getEventManager();
        $sharedEventManager = $eventManager->getSharedManager();

        // Register the event listener method onDispatch
        $sharedEventManager->attach(AbstractActionController::class,
                MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);
    }

    public function onDispatch(MvcEvent $event)
    {
        // Will perform application wide ACL control based on controller,
        // action and user data.
    }
}

For some reason my onDispatch is never called, even though the application screens are loaded.
Don't know what am I missing. As far as I know, I need to use the shared event manager to be valid for the whole application.
Answer: For this (listening to MVC events) to work you don't need the shared event manager, but the MVC event manager. Change your code like this and it will work as expected:.
$application    = $event->getApplication();
$eventManager   = $application->getEventManager();

// Register the event listener method onDispatch
$eventManager->attach(MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);

Read also in this great blog post for more details on when to use the shared event manager. This particular case is also explained in this blog post:

The special case of MVC events
  I said earlier that we should use the shared event manager. But there is one specific case: the event manager we retrieve from the onBootstrap method is the MVC event manager. This means that this event manager knows the events triggered by the framework. This means that if you want to add listeners to the events of the Zend\Mvc\MvcEvent class, you can do it without using the shared event manager:


Python for loop accessing GPIO pins

Question: I'm new to Python and the Raspberry Pi. I'm trying to shorten my code and use for loops for repetitive parts in my code, like changing all pins to high and low.
I'm trying to use a for loop to access pins. Is this even possible?
import RPi.GPIO as GPIO
from time import sleep

R1=22
R2=10
R3=9
R4=11

GPIO.setup(R1, GPIO.OUT)
GPIO.setup(R2, GPIO.OUT)
GPIO.setup(R3, GPIO.OUT)
GPIO.setup(R4, GPIO.OUT)

for x in range(1, 5):
    print "We're on time %d" % (x)
    GPIO.output(R + %d % (x), GPIO.HIGH)
    sleep(1)
    GPIO.output(R + %d % (x), GPIO.LOW)
    sleep(1)

GPIO.cleanup()

Answer: That sort of thing is possible, but often nicer to use a list or dict:
pins = [22, 10, 9, 11]

for pin in pins:
    GPIO.setup(pin, GPIO.OUT)

for x in range(1, 5):
    GPIO.output(pins[x], GPIO.HIGH)
    sleep(1)
    GPIO.output(pins[x], GPIO.LOW)
    sleep(1)

Comment: That sort of thing *isn't* possible. They're trying to create a variable name dynamically: `R + '1'`, etc.
Comment: @PeterWood They're just trying to access variables that already exist, which can be done using `eval`, `exec`, etc (but isn't very nice).
Comment: I see what you mean now.
Answer: You can't create variable names like that. You have to have the same variable name and change what it is pointing to:
pins = [R1, R2, R3, R4]

for pin in pins:
    GPIO.setup(pin, GPIO.OUT)

for pin in pins:
    GPIO.output(pin, GPIO.HIGH)
    sleep(1)
    GPIO.output(pin, GPIO.LOW)
    sleep(1)

Python for loop accessing GPIO pins


Apigility content validator - enable to fetch service validator

Question: I was following the tutorials on https://apigility.org/documentation/content-validation/basic-usage. But, when I tried to inject the input filter service AddressBook\V1\Rest\Contact\Validator in the ContactResource, I get the following error:
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
/Users/.../src/apigility-tutorials/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:529
Message:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for AddressBook\V1\Rest\Contact\Validator
I am not sure if it's an issue with apigility itself, this is why i'm asking if the example shown in the link above actually works when using dependency injection. Thanks
Comment: Did you actually register an `InputFilter` with that name in your `InputFilterManager` or did you create `input_filter_specs` for a input filter with that name as a key?
Comment: @Wilt I used the apigility-admin interface to create this Contact REST service. I can confirm that it did create an input_filter_specs for Contact.
Comment: I read your question once more. What do you actually want to achieve? Why inject the `InputFilter` in the `ContactResource`?
Comment: @Wilt I was just following the tutorial on apigility documentation to set an example for my problem. My problem is that I cannot get the inputFilter service to work by calling `$service->get('AddressBook\V1\Rest\Contact\Validator')` in ContactResource or elsewhere.
Answer: Got it. According to the zf-content-validation doc, the input filter is registered through Zend\InputFilter\InputFilterPluginManager which means I have to get the InputFilterManager service first then get the Contact input filter service as follows:
$inputFilter =
$serviceLocator->get('InputFilterManager')
               ->get('AddressBook\V1\Rest\Contact\Validator');
Thanks for looking into it.


XServe Raid with Ubuntu 10.04 problems

Question: I have an Apple XServe RAID connected via fibre channel to a Dell Poweredge R610.  This server is mainly for hosting subversion repositories, and storing disk images.  In the past 6 months or so we have encountered some issues with this setup where the raid ends up being remounted read only after some errors.  It seems fine when the load is minimal, but a few days ago when copying some large disk images to it it had a bunch of errors and remounted read only.
The actual error messages begin with a bunch of task aborts
May 17 15:20:09 sub0 kernel: [4661904.506886] mptscsih: ioc1: attempting task abort! (sc=ffff88011d2aea00)
May 17 15:20:09 sub0 kernel: [4661904.506890] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 17 2c ea 00 04 00 00
May 17 15:20:09 sub0 kernel: [4661904.507219] mptscsih: ioc1: task abort: SUCCESS (sc=ffff88011d2aea00)
...
May 17 15:21:42 sub0 kernel: [4661997.476282] mptscsih: ioc1: attempting target reset! (sc=ffff88011e632c00)
May 17 15:21:42 sub0 kernel: [4661997.476284] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 18 14 52 00 04 00 00
May 17 15:21:42 sub0 kernel: [4661997.494532] mptscsih: ioc1: target reset: SUCCESS (sc=ffff88011e632c00)
May 17 15:21:42 sub0 kernel: [4661997.494589] mptscsih: ioc1: attempting bus reset! (sc=ffff88011e632c00)
May 17 15:21:42 sub0 kernel: [4661997.494592] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 18 14 52 00 04 00 00
May 17 15:21:42 sub0 kernel: [4661997.495403] mptscsih: ioc1: bus reset: SUCCESS (sc=ffff88011e632c00)
May 17 15:21:52 sub0 kernel: [4662007.498403] mptscsih: ioc1: attempting host reset! (sc=ffff88011e632c00)
May 17 15:21:52 sub0 kernel: [4662007.498411] mptbase: ioc1: Initiating recovery
May 17 15:22:02 sub0 kernel: [4662016.680666] mptscsih: ioc1: host reset: SUCCESS (sc=ffff88011e632c00)
May 17 15:22:12 sub0 kernel: [4662026.686900] sd 2:0:0:0: Device offlined - not ready after error recovery
...
May 17 15:22:12 sub0 kernel: [4662026.687032] sd 2:0:0:0: [sdb] Unhandled error code
May 17 15:22:12 sub0 kernel: [4662026.687034] sd 2:0:0:0: [sdb] Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
May 17 15:22:12 sub0 kernel: [4662026.687037] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 18 14 52 00 04 00 00
May 17 15:22:12 sub0 kernel: [4662026.720494] lost page write due to I/O error on sdb1
...
May 17 15:22:12 sub0 kernel: [4662027.117326] sd 2:0:0:0: [sdb] Unhandled error code
May 17 15:22:12 sub0 kernel: [4662027.117328] sd 2:0:0:0: [sdb] Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
May 17 15:22:12 sub0 kernel: [4662027.117331] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 17 2c ea
May 17 15:22:12 sub0 kernel: [4662027.117339] 00 04 00 00
May 17 15:22:12 sub0 kernel: [4662027.122264] sd 2:0:0:0: [sdb] Unhandled error code
May 17 15:22:12 sub0 kernel: [4662027.122266] sd 2:0:0:0: [sdb] Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
May 17 15:22:12 sub0 kernel: [4662027.122268] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 17 30 ea 00 04 00 00
May 17 15:22:12 sub0 kernel: [4662027.125053] sd 2:0:0:0: [sdb] Unhandled error code
May 17 15:22:12 sub0 kernel: [4662027.125055] sd 2:0:0:0: [sdb] Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
May 17 15:22:12 sub0 kernel: [4662027.125058] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 18 18 52 00 04 00 00
May 17 15:22:12 sub0 kernel: [4662027.127869] sd 2:0:0:0: [sdb] Unhandled error code
May 17 15:22:12 sub0 kernel: [4662027.127871] sd 2:0:0:0: [sdb] Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
May 17 15:22:12 sub0 kernel: [4662027.127874] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 18 10 62 00 03 e8 00
...
May 17 15:22:12 sub0 kernel: [4662027.130737] sd 2:0:0:0: [sdb] Unhandled error code
May 17 15:22:12 sub0 kernel: [4662027.405150] sd 2:0:0:0: [sdb] Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
May 17 15:22:12 sub0 kernel: [4662027.405152] sd 2:0:0:0: [sdb] CDB: Write(10): 2a 00 a8 17 34 ea 00 04 00 00
May 17 15:22:12 sub0 kernel: [4662027.410575] JBD: Detected IO errors while flushing file data on sdb1
May 17 15:22:13 sub0 kernel: [4662028.182860] JBD: Detected IO errors while flushing file data on sdb1

At this point the array is remounted read only.  I am at a loss as to what the problem could be(I'm relatively new to dealing with Fibre Channel/RAID arrays of this type)
System Information(let me know if I can provide anything else that may be helpful)
sysadmin@sub0:~$ lspci(snipped to the relevant stuff I presume)
03:00.0 SCSI storage controller: LSI Logic / Symbios Logic SAS1068E PCI-Express Fusion-MPT SAS (rev 08)
05:00.0 Fibre Channel: LSI Logic / Symbios Logic FC949ES Fibre Channel Adapter (rev 02)
05:00.1 Fibre Channel: LSI Logic / Symbios Logic FC949ES Fibre Channel Adapter (rev 02)

sysadmin@sub0:~$ cat /proc/mpt/summary
ioc0: LSIFC949E, FwRev=01031700h, Ports=1, MaxQ=1023, LanAddr=00:06:2B:1B:89:14, IRQ=40
ioc1: LSISAS1068E B3, FwRev=00192f00h, Ports=1, MaxQ=266, IRQ=16
ioc2: LSIFC949E, FwRev=01031700h, Ports=1, MaxQ=1023, LanAddr=00:06:2B:1B:89:15, IRQ=50

sysadmin@sub0:~$ cat /proc/mpt/version
mptlinux-3.04.12
  Fusion MPT base driver
  Fusion MPT FC host driver
  Fusion MPT SAS host driver

sysadmin@sub0:~$ cat /etc/issue
Ubuntu 10.04.2 LTS \n \l

Full /var/log/messages: https://gist.github.com/96df4b5b9ac7ec46f74c#file_messages
Full /var/log/kern.log: https://gist.github.com/96df4b5b9ac7ec46f74c#file_kern.log
Thanks for taking the time to read and for any help you can provide.
Answer: I'd would be helpful to know more about how the RAID is actually configured e.g. volume, size, RAID level, stripe and chunk sizes etc, and whether you're using multipath.
You're getting an error handling escalation because the aborted command isn't being handled to the satisfaction of the low level driver and the SCSI mid-layer, that's why the recovery severity keeps climbing. How it got there to begin with is going to require lots of analysis like recording blktrace. All I can recommend with this very limited information is to try and upgrade your driver using one the LTS backport kernels (Oneiric for example) and attempt to recreate the problem; The mptsas driver you're using is very old. If you look hard enough, you might be able to update just that driver using a DKMS package.
If you still have the problem then you'll have to consider your capacity for digging in and running down this problem down vs seeking additional support from your OS vendor. These are the sort of problems support contracts are made to resolve. No matter which way you go, be prepared to commit weeks, not days to determine the root cause. Good luck.

XServe Raid with Ubuntu 10.04 problems


Automatic OAuth login using Spring Social

Question: I have a Spring MVC web application that I am trying to authorize to post to our company Yammer feed under a generic account, but I am having trouble figuring out how to automatically authenticate this generic user and create a session with the Yammer API.  As far as I can tell from reading-up on OAuth2 and Spring Social's mechanism for establishing connections to service providers, manual user authentication through the service provider's login page is always required to get an access token.  Is it possible to automatically acquire a token, given a user's credentials?
Answer: This is how OAuth works for the Yammer OAuth flow. 3rd parties should always present the user with the authorization dialog and have the user allow access. When the user allows access then the OAuth flow can be completed and you'll have an OAuth token.
If you are a Yammer customer you might be able to make use of the impersonation feature to acquire an OAuth token on behalf of a user. Users will still get an email notifying them that an app has been activated for their account. This requires verified administrator access to Yammer which a 3rd party app will typically not have. Impersonation will also prevent challenges for a 3rd party who is looking to get into the Yammer App Directory.
Comment: This sounds like it might be the answer to my problem. This is a private app on an internal network, so this should hopefully be easy to pull off.
Comment: @woemler - did you get a working solution to this impersonation issue in the end?


Customizing custom modules

Question: We are planning to implement custom features (in the form of newly developed modules) on top of a standard Drupal7 installation. This "standard" Drupal installation may include some contribution modules such as organic groups.
This extended Drupal installation will be provided to different clients each of which may require custom theming and some (minor) customisation of the custom features mentioned above.
What I am wondering about is the deployment and code maintenance architecture.
Coming from an object oriented background my initial reaction was to propose a layered architecture along these lines:
<code>------------------------
Client Customization Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
Generic Self-created Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
  Contribution Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
      Drupal Core
------------------------
</code>
Meaning the custom main extension modules ("Self-created Modules") would be overwritten/overloaded wherever the respective client requires individual changes using a second custom layer of "Client Customization Modules".
From my point of view this is benefitial as it allows for the generic "Self-created Modules" to remain identical for all clients so bugfixes can easily be performed on a single, central svn location.
Now a colleague argued heavly against such an approach, saying having a 4th module layer which basically overwrites hooks of the 3rd layer would be extremely bad practice in Drupal development as it raises the application complexity and makes debugging virtually impossible.
The alternative would be to create redundant copies of the "Generic Self-created Modules" layer for each client and directly customize these instances. While this is surely possible, a bugfix or change to the generic functionality would then not be possible anymore in a central location, so this approach seems quite dirty to me.
Is it really considered bad practice, or heavily advised against, to customize ones own custom modules by "hooking custom hooks" in a way proposed above?
Answer: In Drupal, most of the customization is not done by overriding existing code but rather by extension or alteration.  Most contribution modules and Drupal core provides extension points (hooks) and configuration variables. Your custom modules (self-created and client customization) should re-use these hooks and configurations.
For your self-created modules, you can use the Features module to easily export configurations into code. To customize your features at the client customization level, you can choice to either use alteration hooks or to re-write part of the Features-generated code to make it customizable via in-DB configuration. See http://developmentseed.org/blog/2009/jul/09/development-staging-production-workflow-problem-drupal and http://www.archive.org/details/CodeDrivenDevelopmentUsingFeaturesEffectivelyInDrupal6And7 for more information on the Features module. Also, the Kit Specification provides information on how to build re-usable features modules (with Features)., see also http://funnymonkey.com/building-features-for-install-profiles and http://nodeone.se/blogg/an-alternative-way-of-structuring-features-for-distributions.
Comment: Thank you - your approach to make the 3rd layer simply more configurable - will certainly make things way easier and reduce the 5-10% i mentioned above.
I will discuss with our developers and post what the result was.
Answer: It should be fine, but do your performance tests, of course.
How extensive are those customizations? Can you use Drupal variables or database tables to control your layer 3 behaviours?
If you can get away with mostly the same module codebase for the different sites, you can use a multisite setup to simplify maintaining the codebase for those sites while allowing site-specific modules for sites that need more extensive customizations.
Comment: Thank you for your answer - the modifications will (compared to the lines of code of what i labeled layer 3) minor - such as 5-10%.
I fear a multisite setup isnt viable as some clients may require to have their installation instances hosted on servers they control.

Customizing custom modules


False discovery rate of multiple regressions models

Question: I have 10 models analysing pupal developmental rates (DR) and developmental times (DT) depending on a number of factors:
m1 <- lm(DR ~ population+sex+temperature+weight+population*temperature)
m2 <- lm(DR ~ population+sex+population*sex)
m3 <- lm(DR ~ population+sex+temperature+population*temperature)
m4 <- gls(DR ~ population+sex, ...)
m5 <- lm(DR ~ population+sex+temperature+weight+population*temperature)
m6 <- glm(DT ~ sex+temperature+weight, gamma)

... and so on
The models refer to datasets of two different species, two different years and different phases of pupal development.
One of the reviewers asked for control of the experiment-wide false discovery rate, which is not so common in the field of ecology. In many of the examples from genetics and medical studies one testing results in only one p-value, which is then adjusted using the FDR procedures. How does it work in my case? Extracting p-values of only, say, the population variable and use them? And then the same separately for sex and so on? Or use all the p-values from each of the models as one vector?
If so, what shall I do in cases when the factor has already been excluded from the final model – skip them and use only the ones left? Add them back to the model?
Answer: @Dian breathe easy, it's pretty much not too difficult. So let's work from familiar territory to false discovery rate (FDR).
First, I see that you have a bunch of outcomes, with a varying number of predictors. Someone who is more familiar with multivariate regression (i.e. multiple dependent variables, assuming possible correlations between errors of different models) will have to speak to whether your modeling approach is the best one. Let's take it as given.
Each of your models will produce some number of $p$-values (incidentally I am an epidemiologist, and have absolutely no idea what you mean about "only one $p$-value." If that were true, it would change the nature of my work and that of my colleagues considerably. :). You could go ahead and test your hypotheses about individual effects separately using these $p$-values.
Unfortunately, hypothesis testing is like the lottery (the more you play, the more your chance to "win"), so if you want to go into each hypothesis test assuming that the null hypothesis is true, then you are in trouble, because $\alpha$ (your willingness to make/probability of making a false rejection of a true null hypothesis) only applies to a single test.
You may have heard of "the Bonferroni correction/adjustment", where you try to solve this conundrum by multiplying your $p$-values by the total number of null hypotheses you are testing (let's call that number of tests $m$). You are effectively trying to redefine $\alpha$ as a family-wise error rate (FWER), or the probability of making at least one false rejection out of a family of tests, assuming all null hypotheses are true. Alternatively, and equivalently, you can think about the Bonferroni adjustment as dividing $\alpha$ by $m$ (or $\alpha/2$ by $m$ if you are performing two-tailed tests, which in all likelihood you are in a regression context). We get these two alternatives because basing a rejection decision on $p \le \frac{\alpha/2}{m}$ is equivalent to $mp \le \frac{\alpha}{2}$.
Of course, the Bonferroni technique is a blunt hammer. It positively hemorrhages statistical power. $\overset{_{\vee}}{\mathrm{S}}\mathrm{idák}$ got a smidge more statistical power, by altering the adjustment of the $p$-value to $1-(1-p)^{m}$. Holm improved upon both Bonferroni and $\overset{_{\vee}}{\mathrm{S}}\mathrm{idák}$ adjustments by creating a stepwise adjustment. The step-up procedure for the Bonferroni adjustemnt:

Compute the exact $p$-value for each test.
Order the $p$-values from smallest to largest.
For the first test, adjust the $p$-value to be $pm$; and generally:
For the i$^{\text{th}}$ test, adjust the $p$-value to be $p(m–(i–1))$.
Using Holm's method, for all tests following the first test for which we fail to reject H$_{0}$ we will also fail to reject the null hypothesis.

The Holm-$\overset{_{\vee}}{\mathrm{S}}\mathrm{idák}$ adjustment is similar, but you would adjust each $p$-value using $1-(1-p)^{m-(i-1)}$.
Some folks, most notably Benjamini and Hochberg (1995), were not comfortable with the world view implied by the assumption that all null hypotheses are true within a stepwise procedure. Surely, they reasoned, if you make an adjustment and reject a single hypothesis, that must imply that a better assumption would be that the remaining $m-1$ hypotheses have a lower probability of all null hypotheses being true? Also, science in general does not assume that there are no relationships in the world: quite the opposite, in fact. Enter the FDR which progressively assumes that rejection probabilities must increase if previous hypotheses were rejected after adjustment. Here's the step-down procedure they proposed:

Compute the exact $p$-value for each test.
Order the $p$-values from largest to smallest (step-down!).
For the first test ($i=1$), adjust the $p$-value to be $\frac{pm}{m-(1-1)} = p$.
For the i$^{\text{th}}$ test, adjust the $p$-value to be $\frac{pm}{m-(i–1)}$.
Using Benjamini & Hochberg's method, we reject all tests including and following the first test for which we reject the null hypothesis.

We often term $p$-values that have been adjusted this way $q$-values.
The advantages of this FDR adjustment include (1) more statistical power, especially for large $m$, and (2) easy integration of additional tests/$p$-values (say, adding $p$-values from an additional regression model) in a manner which leaves the inferences from the first FDR adjustment unchanged.
Update: All these FWER procedures, and the FDR procedure I just described can produce adjusted $p$-values that are greater than one. When reporting adjusted $p$-values, these are typically reported as $p=1$, $p>.999$, $p=$not reject or something along those lines.

References
Benjamini, Y. and Hochberg, Y. (1995). Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing. Journal of the Royal Statistical Society. Series B (Methodological), 57(1):289–300.
Comment: The Bonferroni correction doesn't get the maths wrong: it's a conservative correction for tests that aren't independent. Sidak's is exact, but only for independent tests.
Comment: @Dian... not at all. Some comments: (1) I don't have a dog in this race, *but* if a reviewer explicitly asked for FDR, I would go ahead and do FDR :); (2) these methods are implemented in most statistical software, so if you ain't doing by hand, consider that (e.g. `p.adjust()` in R, `qqvalue` in Stata, etc.), (3) you have a $p$-value for each variable and interaction term in *each* model (I counted 20-something in your examples above), you can also add each whole model $p$-value if reporting; (4) if my answer is useful, I hope you will consider clicking the check-mark at the top left of it.
Comment: Clarifying that my (3) in the above comment means you pile together the $p$-values from *all* the tests you are conducting.
Comment: @Alexis : when you write "5. (...) we reject all tests including and following the first test for which we reject the null hypothesis." does this mean we reject also those that passed previously the test, or when you write "all" you mean "all those after the first failed one"?
Comment: Neither. "all those after the first failed one" is close, but it ignores the fact that you reject the first rejected test under the procedure, not merely the subsequent ones. But you can also just read the literature. :)
Comment: Fair enough, got confused for a moment. Edited.
Comment: @Alexis: thank you so much for your detailed answer. Bonferroni correction is really more commonly used by us, while with the FDR I first encountered only now. I think I'd use BH adjustment, but in the step "Order the $p$-values from largest to smallest" I wonder in my case which $p$-values I should order? In the model output I've got a p-value for population variable, one for sex variable and so on. In the reference paper they consider the example where the treatment groups were compared with chisq and t tests, thus got one test - one pvalue.
Comment: In the hypothesis if population affects the DR - do I order the pvalues from all the models only for the population variable? Sorry, if my question sounds stupid to you, I'm not the smartest person in statistics
Comment: Great, that was exactly the answer I could not find anywhere else. Thank you very much, Alexis!
Comment: @Alexis: Sorry, but there's one more point that is not quite clear for me. If I'm piling together the **p**-values from all the final models, does it mean that they are already kind of preselected, since there are mostly significant that are left? Than the adjusted values will be biased too, won't they?
Comment: Well I really can't speak to the cherry-picking approach that many researchers take in including only "significant" variables in their models. Many such model-building approaches, such as step-wise inclusion or step-wise exclusion, are a good way to guarantee biased results.
Comment: Great answer! Did I misread or is the OP running several different regression models on the same data and then calculating FDRs on all of the coefficient p-values? That could lead to misleading results.
Comment: @RobertF Disagree about lead to misleading results (because of FDR scalability), but feel free to change my mind!
Comment: What if I fit a model with 100 variables and want to drop the non-significant coefficients and refit the model to keep just the most significant ones and get more accurate values for the coefficients? How do I apply the p-value adjustment then?
Comment: @skan Do not do that?
Answer: What you're doing is a type of step-wise regression, so FDR in this context serves to guide the model selection: the p-value would be that of the goodness-of-fit (coefficient of determination), not of any individual explanatory variable.
Comment: This is a very important question because most analysis are performed with a multivariate model and backwards stepwise selection.

And do we need to apply FDR corrections if we are using regularization (lasso)?


Core search, when only one result, open result

Question: Is there a simple way to accomplish the feature in the title ?
When a search results in one result, don't show the result but go directly to the node.
Answer: As I see the only way is use hook menu alter for this item
<code>/**
 * Implements hook_menu().
 */
function search_menu() {
  $items['search'] = array(
    'title' => 'Search',
    'page callback' => 'search_view',
    'access callback' => 'search_is_active',
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'search.pages.inc',
  );
</code>
I propose to replace page callback "search_view" to your own and put there your logic.


Complex line integral along a null homotopic curve and the Cauchy Representation Formula

Question: In my complex analysis book, they ask to show that: if $C$ be the circle $|z| = 1$, then $\int_C \frac{z}{z^2+9} dz= 0$ right after the theorem that says that a complex line integral along a piece wise null-homotopic $C^1$ loop is zero.
My guess is that this is the case because $C$ is parametrized by $[-\pi,\pi] \rightarrow \mathbb{C}: t \mapsto e^{it}$, and since we can continuously deform a circle to a point, this map is null-homotopic.
So then, why is the Cauchy representation formula, i.e. $\frac{1}{2\pi i}\oint_{\partial B} \frac{f(w)}{w-z}dw$, where $B$ is an open ball, not always equal to zero? Because then, following the same reason as before, the border of an open ball can be continuously deformed to a point.
Could anyone point out the flaw in my intuition?
Comment: Do you have poles inside the contour?
Comment: If the integrand does not have poles inside the contour, what do you expect the answer is? Check Cauchy theorem?
Comment: @MhenniBenghorbal, so far the course has not said anything about poles :). Is my assumption about the first integral wrong then?
Answer: The theorem about "complex line integral along a piece wise null-homotopic C1 loop is zero" requires that the function you are integrating is holomorphic on the set your homotopy is passing through. In practice, this means that the function should be holomorphic on (a neighbourhood of the closure of) the domain bounded by your loop.
In your particular case, the function $f(z) = \dfrac{z}{z^2+9}$ is holomorphic on the whole complex plane except the points $z = \pm 3i$, so there is no problem. If you try to integrate over a curve containing one or both of $\pm 3i$, $f$ is no longer holomorphic inside the loop and your theorem doesn't apply. In that case, Cauchy's integral formula, or more generally  the Residue theorem, comes into play.
Comment: But, then why isn't the integral in the Cauchy representation formula 0?
Comment: Because $\dfrac{f(w)}{w-z}$ is (generally) not holomorphic at $w=z$.
Comment: But the function $\frac{z}{z^2+9}$ is not holomorphic at $3i$, but since the loop is not passing through this point this is no problem?


Dimension of kernels of powers of operators

Question: Let $A$ be a closed operator on a Banach space $E$ and $\lambda$ some eigenvalue of $A$ such that $n = \dim \ker(\lambda - A) < \infty$. Is it than necessarily true that $\dim \ker(\lambda - A)^k \leq nk$ for all $k \in \mathbb N$?
Answer: WLOG $\lambda=0$. The exact sequence $0\to\ker A\to\ker A^{k+1}\xrightarrow{A}\ker A^k$ gives $\dim\ker A^{k+1}\leq\dim\ker A+\dim\ker A^{k}$ from which the result is immediate by induction.
Answer: The statement is true. It can be shown by induction on $k$.
The statement is true for $k=1$ by $n = \dim (\ker (\lambda I-A))$. Now let $k\in\mathbb{N}$. By the induction hypothesis, $\ker (\lambda I - A)^{k}$ has a basis $F$ of cardinality less than or equal to $nk$. As $\ker (\lambda I-A)^{k}$ is a vector subspace of $\ker (\lambda I-A)^{k+1}$, $F$ can be extended to a basis $F_{0}$ of $\ker (\lambda I - A)^{k+1}$. If $x\in F_{0}\setminus F$, then $(\lambda I-A)^{k}(x)\in \ker (\lambda I - A)$. In addition, as $F_{0}\setminus F$ is a subset of the linearly independent set $F_{0}$, $F_{0}\setminus F$ is linearly independent.
I claim that
$$G := \{(\lambda I - A)^{k}(x) : x\in F_{0}\setminus F\}$$
is a linearly independent subset of $\ker (\lambda I-A)$ with the same cardinatlity as $F_{0}\setminus F$. For if this has been shown, then the cardinality of $G$ is less than or equal to $n$ because $\dim (\ker (\lambda I-A))$, and then as $F_{0}$ is equal to $F\cup (F_{0}\setminus F)$, the cardinality of $F_{0}$ is less than or equal to $nk + n = n(k+1)$, proving the statement for $k+1$ and completing the proof by induction.
To show that $G$ has the same cardinality as $F_{0}\setminus F$, it is sufficient to show that distinct elements of $F_{0}\setminus F$ correspond to distinct elements of $G$. Suppose for a contradiction that this fails, so that there are $x,y\in F_{0}\setminus F$ with $x\neq y$ such that $(\lambda I-A)^{k}(x) = (\lambda I-A)^{k}(y)$. Then $x-y\in \ker (\lambda I-A)^{k}$, but as $\ker (\lambda I - A)^{k} = \text{span}(F)$ and $x-y\not\in \text{span}(F)$, this leads to a contradiction. Therefore, each $x\in F_{0}\setminus F$ corresponds to a unique element of $G$, which shows that $F_{0}\setminus F$ and $G$ have the same cardinality.
To show that $G$ is a linearly independent subset of $\ker (\lambda I-A)$, suppose for a contradiction that it is linearly dependent. Then using that distinct elements of $F_{0}\setminus F$ correspond to distinct elements of $G$, there is a finite index set $\mathcal{F}$ such that $\{x_{i}:i\in\mathcal{F}\} \subseteq F_{0}\setminus F$ with $x_{i} \neq x_{j}$ for $i\neq j$ and a collection of scalars (not necessarily distinct) $\{\alpha_{i}:i\in\mathcal{F}\}$ which are not all zero, such that
$$\sum_{i\in \mathcal{F}}\alpha_{i}(\lambda I-A)^{k}(x_{i}) = 0.$$
But by the linearity of $(\lambda I-A)^{k}$, it follows that
$$(\lambda I-A)^{k}\left( \sum_{i\in\mathcal{F}}\alpha_{i}x_{i} \right) = 0.$$
This implies that $\sum_{i\in\mathcal{F}}\alpha_{i}x_{i} \in \ker (\lambda I-A)^{k}$. But $\ker (\lambda I - A)^{k} = \text{span}(F)$ and $\sum_{i\in\mathcal{F}}\alpha_{i}x_{i}\not\in \text{span}(F)$, which is a contradiction. Therefore, $G$ is linearly independent. This completes the proof.
Note that this proof only used linear algebra. It didn't use $A$ being a closed operator or $E$ being a Banach space anywhere.