CakePHP working with two controllers / models

Question: First of all i'm sorry about the name of this question i had a hard time figure out what to call it:
Here is my problem i have the following two data tables:
Users

Employees.

These two data-tables are connected in a 1 to 1 relationship
Now both of these has a Model a view and a controller. Now my question is kinda split into two parts first the hard part:
Whenever an employee wants to create a new user (new employee) he has to insert the data into two tables first in the users table and then after getting the user_id add a record in the employee table
the employee table looks like this:
users_idUsers client_id

Where users_idUsers is the userid from the user table
How will i go around this? is it possible to add the functions of another model into my employee model?
The second question is kinda an extension of this and is relatively simple.. i want to display all the employees however the view should be joined with the users so that you can see the username of the person in the view.
It should be said that i am quite new to Cake so i hope that some of you will be able to help me out.
Answer: What you're after is linking two models together. CakePHP has a solid relationship mapper that does all this for you without needing to "take the id from the last insert and do something else with it".
If I'm not mistaken, your problem put into simple terms is:
An Employee hasMany users

A User belongs to one Employee

For a 1-to-many model relationships CakePHP has something called "hasMany": http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
It's in the same way a user for instance can make many comments; An employee can create many users.
On the flipside of that relationship between a user and a employee, you'd want a "belongsTo" mapping, so you know that the user was added by some employee: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
This way you can find what employee that added "user X" by searching "through the user", so to speak.
When you have mapped up the models together, things like retrieving data (like findBy: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#findby) and managing model relationships becomes much easier as you don't have to think much about how relations are chained together (that's what the model mapping is for as outlined above), but rather on what you want to retrieve.
In turn it allows you to do things like this intuitively
$this->Employee->find('all', array(
            'recursive' => 1,
            'fields' => array('employee.name, employee.age')
            ));

or if you wanted to find say what employee that added the user "Sarah".
$this->Employee->User->find('all', array(
'conditions' => array('User.name' => 'Sarah'),
'fields' => 'Employee.*',
'recursive' => 0))

which would give back an associative array with employees.
As a sidenote: The use of recursive = 1 is abit old fashioned. There is something much better called "Containable" that allows you to kind of inject models based on what you need. It's outside the scope of this problem, but I though I'd mention it.
Comment: So do i have to put this relation in both models or only in one of them?
Comment: When ive added the code has one i get the following error:

SQL Query: SELECT `Employee`.`users_idUsers`, `Employee`.`client_id`, `User`.`id`, `User`.`username`, `User`.`password`, `User`.`role`, `User`.`created`, `User`.`modified` FROM `system_bloglic_com_test`.`employees` AS `Employee` LEFT JOIN `system_bloglic_com_test`.`users` AS `User` ON (`User`.`employee_id` = `Employee`.`users_idUsers`) WHERE 1 = 1 LIMIT 20
Comment: But my sql statement is suppose to join on User.User.id = employees.users_idUsers
Comment: Put a relationship in each model. And also, you'll want to name your database fields according to cakePHP conventions. So, rather than users_idUsers, you'd just name the column user_id.
Comment: I've revised the answer. Please have a new look on it.
Comment: Marc, read the entire page of conventions at http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html, particularly the database conventions.


Using Pivot in SQL t

Question: I rarely have had to use pivot in SQL and am having trouble wrapping my head around it. I have query that produces a table of patients and insurance for a medical facility. I want to return a single row that shows all of the insurances that the patient has.
Sample data:
ID  Insurance
1840    Medicaid Of New York
1841    Affinity Health Plan
1841    Medicaid Of New York
1842    Fidelis Care
1842    Medicaid Of New York

The goal is to show the data like this:

I'm understand the basic functionality of pivot, but don't have a lot of time to figure out how to achieve the results above. I haven't achieved anything close to working results, which could be either lack of experience or fatigue at this point. Any help would be appreciated.
Comment: Tag your question with the database you are using.
Comment: Ok done. It must be the mental fatigue I'm experiencing ;)
Answer: something like this
with data as (
select id,insurance ,row_number() over ( partition by id order by insurance) rowid
)

select d.id , [1] as ins1,[2] ins2,[3]ins3,[4] ins4
from data d
pivot
(max(insurance)
for rowid in ([1],[2],[3],[4])
)pv

Answer: I prefer conditional aggregation where possible:
SELECT  ID,
        MAX(CASE WHEN RN = 1 THEN INSURANCE ELSE '' END) AS INSURANCE1,
        MAX(CASE WHEN RN = 2 THEN INSURANCE ELSE '' END) AS INSURANCE2,
        MAX(CASE WHEN RN = 3 THEN INSURANCE ELSE '' END) AS INSURANCE3,
        MAX(CASE WHEN RN = 4 THEN INSURANCE ELSE '' END) AS INSURANCE4
FROM (
      SELECT  ID,
              INSURANCE,
              ROW_NUMBER() OVER (PARTITION BY ID ORDER BY INSURANCE) RN
      FROM YourTable
     ) A
GROUP BY ID

This is a good read on conditional aggregration, or Cross Tabs, versus PIVOT
Answer: If you have at most two values (as suggested by your sample data and results), you can use min() and max():
select id,
       min(insurance) as insurance1,
       (case when min(insurance) <> max(insurance) then max(insurance)
        end) as insurance2
from t
group by id;

Comment: There can be up to 4, but I tried to keep the sample data simple to understand how pivot would work.
Answer: Here is what you are looking for. This will flatten your records as desired.
SELECT
    ID, Insurance1, Insurance2, Insurance3, Insurance4
FROM (  SELECT
            ID,
            Insurance,
            RN = 'Insurance' +
            CAST(ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Insurance) AS CHAR(1))
        FROM MyDB.MySchema.MyTable
) AS d
PIVOT(
    MAX(Insurance)
        for RN
            in (Insurance1, Insurance2, Insurance3, Insurance4)
) AS p;

Using Pivot in SQL t


How do you use a binary heap to implement a priority queue?

Question: Despite the fact that I've got a BS in Computer Science (and this was covered in the university), I've never been able to understand the relationship between binary heaps and priority queues. It just... doesn't click. I completely understand what a binary heap is and I know how to implement one in an array. I also know what a priority queue is. But how do the two of them fit together?
A quick google query shows a lot of articles like this one. Which kind of explains it, yet I'm left more questions:

A priority queue needs to ensure that if two items with the same priority are added, then they will be removed in the same order that they were added. How does a binary heap ensure this? (In fact, if I'm not mistaken, then the border case where ALL the items have the same priority would produce a heap which would violate this rule).
What happens when you remove the root from the heap, then put in the last element in place of the root, and then need to swap it with one of the children - but both children have the same value. How do you pick which one to swap with? (Holding in mind the FIFO rule of same-priority items)

What am I missing here?
Answer: A priority queue is an abstract data type like "stack" or "associative array." There can are many different ways to implement a priority queue - you can use binary heaps, binomial heaps, Fibonacci heaps, pairing heaps, etc.
I don't believe that there is any intrinsic requirement that a priority queue be "stable" and require that elements with equal priorities be dequeued in the same relative order in which they were added, much in the same way that there's no instrinsic requirement that a sorting algorithm be stable (though many are). It's a nice property to have, but usually it's not guaranteed. This is why, for example, a standard heapsort isn't a stable sort.
Fortunately, it's not too hard to adjust binary heaps to be stable. Keep a counter associated with the binary heap. Whenever you add an element to the heap, tag it with the current value of the counter and increment the counter. When doing heap operations, use the counter as a tiebreaker to determine which value is smaller if two values compare equal. Essentially, this changes the comparison to a lexicographical comparison first on the real value and then on the insertion order.
Hope this helps!
Comment: Hmm, I guess the "queue" part and the frequently cited comparison with printer queues made it somehow intuitive. In a simple queue there is a FIFO rule (that's what makes it a queue). And a printer queue also is stable. Wikipedia also says: `If two elements have the same priority, they are served according to their order in the queue`. Plus it somehow seems... natural, that a higher priority might allow an element to "cut in front of the queue", but it shouldn't change the order of the other items.
Comment: @Vilx- While I don't do academic research into data structures, I do have experience teaching data structures at an advanced undergraduate level and have read the original research papers for many types of priority queues. I've never encountered this requirement in any of the priority queue data structures that I've seen before and none of the papers I've seen mention anything about it. I'd also be very surprised if most standard library implementations of a priority queue actually were stable, though I could be wrong.
Comment: No, you're probably right. It was just my intuitive understanding that was wrong. It's not a "queue + priority", it's something... else.
Comment: Still, if you ever teach this to someone again, please emphasize, that a "priority queue" is NOT like a printer queue! :D
Answer: Simple java code to illustrate priority queues
<code>package heap;

import java.util.Comparator;

/**
 * Generic implementation of priority queue based on heap with add and pop
 * Reverse is min heap
 *  Average Worst case
 Space  O(n)    O(n)
 Search O(n)    O(n)
 Insert O(1)    O(log n)
 Delete O(log n)    O(log n)
 * Created by  on 9/7/14.
 */
public class BinaryHeap<T extends Comparable> {
    private final Comparable[] pq;
    private int size = 0;

    private final Comparator<Comparable> comparator;

    private final static Comparator<Comparable> comparatorMax = new Comparator<Comparable>() {
        @Override
        public int compare(Comparable o1, Comparable o2) {
            return o1.compareTo(o2);
        }
    };

    public BinaryHeap(int size) {
        this(size,false);
    }

    public BinaryHeap(int size, boolean reverse) {
        pq = new Comparable[size];

        if(reverse)
            comparator = comparatorMax.reversed();
        else
            comparator = comparatorMax;
    }

    public void add(T entry) throws Exception {
        if(size == pq.length)
            throw new Exception("Heap Overflow Exception: "+ entry);
        pq[size] = entry;
        size++;
        maxHeapify(pq, getNewPos(size - 1), true);
        print();
    }

    public Comparable pop() throws Exception {
        if(size == 0)
            return null;
        size--;
        swap(pq,0,size);
        Comparable entry = pq[size];
        pq[size] = null;
        maxHeapify(pq, 0, false);
        System.out.println("Popped: "+ entry);
        print();
        return entry;
    }

    public Comparable find(T entry) {
        for(int i=0; i < size; i++)
            if(comparator.compare(entry,pq[i]) == 0)
                return entry;

        return null;
    }

    private void maxHeapify(Comparable[] entries, int pos, boolean swimUp) throws Exception {
        int leftPos = 2 * pos + 1;
        int rightPos = 2 * pos + 2;

        Comparable parent = entries[pos];
        Comparable left = null;
        if(leftPos < size)
            left = entries[leftPos];

        Comparable right = null;

        if(rightPos < size)
            right = entries[rightPos];

        if(left == null && right == null)
            return; //For swim Down case

        if (parent == null)
            throw new Exception("Entry not found Exception: " + pos);

        //Find the largest of left and right for swaps
        int largest = pos;
        if (left != null && comparator.compare(parent,left) < 0) {
            largest = leftPos;
        }

        if (right != null && comparator.compare(parent,right) < 0) {
            if(largest == pos)
                largest = rightPos;
            else if(comparator.compare(right,entries[largest]) > 0) {
                largest = rightPos;
            }

        }

        if (largest != pos) {
            swap(entries, largest, pos);
            if (swimUp && pos == 0)
                return;

            maxHeapify(entries, swimUp ? getNewPos(pos) : largest, swimUp);
        }
    }

    private void swap(Comparable[] entries, int pos1, int pos2) {
        Comparable temp = entries[pos2];
        entries[pos2] = entries[pos1];
        entries[pos1] = temp;
    }

    private int getNewPos(int pos) {
        int newPos = pos / 2;//Takes the floor automatically because of int
        if (pos > 0 && pos % 2 == 0)
            newPos = (pos / 2) - 1;

        return newPos;
    }

    public void print() {
        System.out.print("[");
        int i=0;
        for(;i < size-1; i++)
            System.out.print(pq[i] + ",");

        System.out.print(pq[i]+"]");
        System.out.println();
    }

    public static void main(String[] args) {
        BinaryHeap<Integer> pq = new BinaryHeap<Integer>(100);
        try {
            pq.add(5);

            pq.add(3);

            pq.add(9);

            pq.add(16);
            pq.add(2);
            pq.add(3);
            pq.add(19);
            pq.add(500);
            pq.add(90);
            pq.add(1);
            pq.add(91);
            pq.add(600);
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();
            pq.pop();

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>


Denying user object access to a computer setting GPO

Question: Let's say I have a GPO called gpo1 which sets some computer settings.
I want these computer settings to apply only to certain user. Is it possible in the delegation tab to add a user group and then deny them the read / apply this gpo rights?
I'm not sure if it would work because the gpo1 is setting some computer settings and not user settings.
Thanks !
Comment: Computer settings apply to computers, user settings to users.
Comment: Yeah, this I know, but there is a specific GPO that I want activated for some user which is only in the computer settings.

I want to prevent users printer redirection on a RDS server, and that GPO is not available trough the user settings, it is only available in the computer section.

I would like for a given terminal server to apply this only for certain users
Comment: @JohDoh it isn't possible. You might need some kind of loopback processing, but as it stands this question isn't answerable.
Comment: Ok, I tried with loopback processing but this only applies to  users settings applied to a computer.

It merges the user's settings GPO applied on a computer with the remote user's settings
Answer: As has been stated in the comments, you can't do this with Group Policy. If this is for a small number of users you can disable printer redirection on the properties of the user account. Simply uncheck the box in the screenshot below.


Loss functions in statistical decision theory vs. machine learning?

Question: I'm quite familiar with loss functions in machine learning, but am struggling to connect them to loss functions in statistical decision theory [1].
In machine learning, a loss function is usually only considered at training time. It's a differentiable function of two variables, loss(true value, predicted value), that you iteratively minimize over the training set to converge to (locally) optimal model weights.
In statistical decision theory, a loss function seems to be relevant at prediction time (?). You want to rationally choose a value for an unknown quantity, based on your assessment of its probable values, and your loss of making a wrong prediction.
What is the intuition of how these two concepts relate to each other?
[1] For example, in Ch 6.3 of "Machine Learning: A Probabilistic Approach" or Ch 2.4 of "Elements of Statistical Learning".
Answer: The loss that is of ultimate interest is the prediction loss (or decision loss). It represents real (financial/material/...) consequences of any given decision for the decision maker. It is this and only this loss that we want to minimize for its own sake rather than as an intermediate goal.
The training loss is an intermediate tool for building prediction models. It does not affect the welfare of the decision maker directly; its effects manifest themselves only via the prediction loss.
It may or may not be a good idea to match the training loss to the prediction loss.

For example, suppose you have a sample generated by a Normal random variable. You have to predict a new observation from the same population, and your prediction loss is quadratic. Absent additional information, your best guess is the mean of the random variable. The best* estimate of it is the sample mean. It so happens that the type of training loss that is minimized by the sample mean is quadratic. Thus, here the training loss coincides with the prediction loss.
Now suppose the situation is the same but your prediction loss is the absolute value of the prediction error. Absent additional information, your best guess is the median of the random variable. The best* estimate of it is the sample mean, not the sample median (because our sample is generated by a Normal random variable). As we already know, the training loss that yields the sample mean when minimized is quadratic. Thus, here the training loss does not coincide with the prediction loss.

*Best in the sense of minimizing the expected prediction loss.
Comment: @FransRodenburg, try a simulation if you do not trust my point. You will discover that sample mean is a more efficient estimator of $\mu$ than the sample median, for any sample size (small or large). This is a well known example, I did not come up with it myself.
Comment: @FransRodenburg, there are many ways of estimating the same parameter. E.g. you could take the first element of the sample as an estimate of the mean. Obviously (?), this is inefficient compared to taking the sample mean. Less obvious but no less true is the fact that the sample median is a less efficient estimator than the sample mean when the data is normal. I would encourage to try a simulation just to see for yourself (I have tried it myself) even though I believed in the result upfront.
Comment: @RichardHardy How do you write down that loss function to begin with? The only related formulation I know is mean == minimizing the L2 _norm_ of a vector of deviations ([source](http://www.johnmyleswhite.com/notebook/2013/03/22/modes-medians-and-means-an-unifying-perspective/)). But this is not a loss function in the supervised learning sense, where you measure the difference between a true and predicted value (?).
Comment: @kennysong, for the variable of interest $y$ and its prediction $\hat y$, $\text{Training loss}(y,\hat y)=\sum_{i=1}^n (y_i-\hat y_i)^2$  over a sample indexed by $1,\dots,n$.
Comment: I'm not sure I follow your second bullet. If a variable is truly normal, the mean coincides with the median. Why then would the sample median be a worse estimator? Except for very small samples, the sample estimates of the mean and median of a normally distributed variable should be very close to each other, right?
Comment: It sounds perfectly logical, I just don't see why this would be the case when the median should coincide with the mean.
Comment: Thank you for taking the time to clarify, but perhaps I'll turn this into another question. Namely, I have no reason to assume the first element would coincide with the mean, but I do have reason to assume the median would coincide with the mean. I suppose the question would then be: If the mean and median coincide, and the sample mean is a more efficient estimator of the mean, is the sample mean also a more efficient estimator of the median?
Comment: @RichardHardy Thanks! Can you explain a bit more about what "training loss" means in the context of computing a sample mean?
Comment: @kennysong, you seek a function of the sample data that minimizes the training loss, namely, the sum of squared errors. This function is the sample mean. The training loss is square loss.
Comment: @FransRodenburg, when dealing with a sample from a Normal random variable, there is actually pretty low chance that the sample median will (exactly, not approximately) coincide with the sample mean. (Even though the population median and the population mean do coincide; they are the same $\mu$.) To answer your question, yes, the sample mean is a more efficient estimator of the population median. The sample median is a less efficient estimator. This follows immediately from the discussion about estimating the population mean, because the population mean and the population median coincide.
Comment: @RichardHardy Right, but how do you formulate computing a simple average as minimizing some `loss(true value, predicted value)`?
Comment: @kennysong, take the first derivative of the loss function and set it to zero, and you will obtain mean (=average) as the solution.
Answer: Let me give a slightly more ML-focused perspective on the accepted answer.
Don't conflate training loss and decision loss – they're separate concepts even though the functions can be the same. It's easier to see this distinction in classification than regression.
So, let's say we're doing binary classification using logistic regression. The training loss is cross entropy / log loss (maybe with regularization). After the model is trained, we don't care about the training loss anymore.
At prediction time, our logistic regression model tells us $P(y|x)$. We need to translate this distribution into a single class. Do we just pick the class with the highest probability? Do we want to be extra careful about false positives? We formally encode these preferences into a decision loss, which allows us to optimally choose a single class from $P(y|x)$.

For a more academic exposition, I found "Pattern Recognition and Machine Learning" to have a great disambiguation of these two.

Determination of $p(x, t)$ from a set of training data is an example of
inference and is typically a very difficult problem whose solution
forms the subject of much of this book. In a practical application,
however, we must often make a specific prediction for the value of $t$,
and this aspect is the subject of decision theory.... We shall see that the decision stage is generally very simple, even trivial, once we have solved the inference problem.

It is worth distinguishing between the squared loss function arising
from decision theory and the sum-of-squares error function that arose
in the maximum likelihood estimation of model parameters. We might
use more sophisticated techniques than least squares, for example
regularization or a fully Bayesian approach, to determine the
conditional distribution $p(t|x)$. These can all be combined with the
squared loss function for the purpose of making predictions.
Answer: Actually this is not really a big difference between Statistics and Machine Learning. Machine Learning theory is concerned with how well predictions work outside the training sample in terms of the loss function as well. I think this is usually referred to as generalization risk or generalization error there, see for example
Bousquet & Elisseef: Stability and Generalization.
Obviously if you only have the training sample, you can only evaluate the loss function on the training data. But many methods are based on some kind of training loss minimization, which implies that the training error (because it is optimized on the training data) will not generalize well and loss on new observations can be expected to be higher. This depends on the specific method and situation, but considering at least theoretically (or on separate test data) applying the loss function to new to be predicted data is a key tool for investigating this, and both Statistics and Machine Learning are concerned with this. (And you can sometimes choose methods or parameters based on expected generalization loss rather than plain training loss, at least where theory exists.)
Answer:
Theoretical approach: In first layer, define prediction error $\epsilon=y-E(y|x)$. Then, to estimate parameter, we define a loss or criterion function as $l(\epsilon)=\|\epsilon\|_p^p$.
Empricial approach: We define residual error $r=y-\hat{y}$, where $\hat{y}$ approximate the prediction function $E(y|x)$ from the given data under a suitable model structure with a suitable loss or criterion function $l(r)=\|r\|_p^p$.


Lidando com colisões em dictionary C#

Question: Preciso mapear um array de strings em um dictionary para que eu possa testar posteriormente se uma string informada é valida, verificando se ela faz parte do dict, além disso gostaria de recuperar algumas outras informações armazenadas no dict.
Para isso estou utilizando a seguinte estrutura:
struct reservedWord
    {
        public String command;
        public type token;      //token é um enumerador
    };

Ao tentar armazenar a sequência de strings por meio do código (modificações tentando seguir as recomendações do @mgibsonbr):
Dictionary<string, string> palavras = new Dictionary<string, string>();
for (int i = 0; i < reservedWords.Length; i++)
        (...)
        palavras.Add(reservedWords[i], word);

em tempo de execução é gerada uma exceção pela inserção de chave duplicada. Mesmo quando substituo este código de inserção por
palavras.Add(reservedWords[i].getHashCode(), word);

recebo a mesma mensagem de erro.
Comment: Eu entendi o erro que você está tendo, mas não entendi exatamente o que você deseja fazer? Você tem um conjunto de palavras-chaves e também outro conjunto de palavras a serem testadas?
Comment: Exatamente isso
Answer: Técnicas para lidar com colisões
A classe Dictionary<TKey, TValue> do .Net não permitem chaves nulas nem duplicadas. Você terá que lidar com estas ocorrências da forma mais apropriada para o seu uso. Existem várias técnicas que dependem do comportamento que você desejar. No caso de uso de chaves duplicadas, destaco as seguintes:

Substituição: se quiser adicionar um item ao dicionário, substituindo a chave caso ela já exista:

dict[chave] = valor;

Adicionar se não existir:
if (!dict.ContainsKey(chave))
     dict.Add(chave, valor);

Recuperar se existir ou adicionar: se quiser adicionar uma chave/valor, somente se a chave ainda não estiver ocupada, e se estiver ocupada então recuperar o valor já existente:

TValor original;
if (!dict.TryGet(chave, out original))
    dict.Add(chave, valor);

Adicionando múltiplos itens na mesma chave: se quiser adicionar vários elementos na mesma chave, na verdade teria que usar um dicionário de listas, juntamente com a técnica de adicionar ou recuperar:
List lista;
if (!dict.TryGet(chave, out lista))
    dict[chave] = lista = new List();
lista.Add(valor);

Alguns problemas em potencial que notei no seu código

Não use o método GetHashCode() como chave do dicionário. Este método já será usado internamente pela classe Dictionary<TChave, TValor> em todas as chaves, e serve para agilizar o processo de localização de elementos dentro do dicionário.
A sua struct não implementa IEquatable<T>, e tampouco é passado um IEqualityComparer<T> para o dicionário. Por causa disso, o hash será extraído do primeiro campo na sua struct, que é o campo command... será que é isso mesmo que você quer? Me parece bem razoável, mas mesmo assim é bom notar isso.
Sua struct possui campos que podem ser alterados depois de inseridos no dicionário. Um tipo que seja usado como chave de um dicionário, não pode ter seu hash alterado, e o recomendável é que a struct fosse imutável.
Comment: Miguel, quero quer a hash seja gerada apenas pelo primeiro campo da struct, pois estou usando essa hash para validação de comandos. Gostaria de saber como faço para tornar o primeiro campo da struct imutável. Faz muito tempo que não programo em C#
Answer: Bom, um meio de verificar colisões antes de incluir no dicionário, é utilizar o método ContainsKey de Dictionary. Este método permite que você verifique se existe tal chave para cada item do dicionário. Exemplo com um método de extensão:
public static bool AddSafe<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
    if (!dictionary.ContainsKey(key))
    {
        dictionary.Add(key, value);
        return true;
    }
    return false;
}

Answer: Há algumas misconcepções aqui, precisamos resolvê-las antes de pensar na solução mais apropriada:

Há mesmo uma "colisão", ou seu problema são "chaves duplicadas"?
Se sua massa de dados tem por exemplo a chave "a" mapeando tanto a 1 quanto a 2, então o problema não é colisão de hash. Colisão seria se tivéssemos "a" mapeando pra 1 e "b" mapeando pra 2, mas hash(a) == hash(b).
3 colisões em 59 entradas não me parece "pouquíssima", mas um número excessivo, principalmente se a função de hash for bem feita (como acredito ser o caso com getHashCode). Por isso suspeito que seu caso é de chaves duplicadas, mas isso só você pode confirmar. Caso seja isso - e for normal na sua aplicação uma chave apontar pro mesmo valor - então de fato uma solução como a sua proposta (mapear chave a uma lista) seria a correta.
Se há uma colisão, de quem é a responsabilidade de tratá-la?
Colisões podem ocorrer em qualquer função de hash, e as bibliotecas que fazem uso delas estão (ou deveriam estar) preparadas para tratar delas. No exemplo acima, se você inserir "a" e "b" num Dictionary e houver colisão entre seus hashes, é obrigação do Dictionary fazer algo a respeito, não sua. A menos que essa biblioteca esteja muito quebrada (não tenho experiência prática com C#, mas duvido que seja o caso) isso será tratado de forma transparente para o programador-usuário [da biblioteca, i.e. você].
Seu exemplo acima me leva a pensar se era mesmo um Dictionary<int, int> que você queria. Se suas chaves são strings, não seria o caso de usar Dictionary<string, int>? Pois se você chama o método getHashCode da string manualmente, e usa seu resultado como chave (e não a string original) então você está transferindo pra você uma responsabilidade que seria da biblioteca (tratar colisões). Que eu saiba, não há razão para se fazer isso...

Se após ler o exposto acima você ainda precise tratar manualmente de colisões, atualize sua pergunta com mais detalhes e eu procurarei te orientar melhor quanto às suas opções (encadeamento, rehashing...).
Comment: Conforme você comentou, editei o post adicionando mais detalhes sobre o problema. No caso, o hashCode é gerado de acordo com o conteúdo das strings, como não tenho strings duplicadas na minha massa de dados, tenho problemas de colisão e não duplicação. Realmente achei bizarro o dictionary lançar um exception toda vez que tento inserir uma chave duplicada (colisão) e não tratar isso pra mim, mas também não encontrei nenhuma solução melhor. Inclusive, os colegas acima apontaram que a minha abordagem é satisfatória.
Comment: @lfelix Não entendo. O código que você postou não deveria nem compilar! O tipo genérico de `palavras` é `string`, portanto ele deveria aceitar somente strings. Você não quis dizer `Dictionary`? (ou talvez `palavras.Add(reservedWords[i].command, word)`). Além disso, seria bom ter uma lista de strings que estão dando colisão pra gente testar - caso contrário fica difícil reproduzir o problema (você tem poucas strings, mas elas são muito grandes?). Você poderia criar um exemplo no [ideone](http://ideone.com) que mostre o erro acontecendo?
Answer: Outra suggestao era construir o Dictionary a volta do proprio reservedWord struct, depois de decorra-lo com IEquatable<reservedWord>
public struct reservedWord : IEquatable<reservedWord>
{
  public string command;
  public MyType token;

  public override int GetHashCode(){ return command.GetHashCode() ^ (int)token; }
  public bool Equals(reservedWord other)
  {
    // seja qual for o teu criteria de egualdade...'case-sensitive'?
    return String.Equals(command, other.command) && token == other.token;
  }
}

e depois
var palavras = new Dictionary<reservedWord, string>();
var reservedWords = new reservedWord[] { .... }; // lista de struct 'reservedWord'
for (int i = 0; i < reservedWords.Length; i++)
{
    (...)
    if(!palavras.ContainsKey(reservedWords[i])
      palavras.Add(reservedWords[i], word);
}

Lidando com colisões em dictionary C#


A good reference to the fact that unitary transforms map normal vectors to normal vectors?

Question: More precisely: given a vector of independent, standard normally distributed random variables, if we apply a unitary transform we obtain again a vector of independent, standard normally distributed random variables.
A good reference?
Answer: If $X$ is multivariate normal and $A$ is any real matrix, we can let $Y=AX$ and obtain a multivariate normal $Y$ with
$E[Y]=AE[X]$
and
$\mbox{Cov}(Y)=A \; \mbox{Cov}(X) A^{T}$.
If $X$ is a standard normal ($N(0,I)$), and $A$ is an orthogonal matrix matrix, then $E[X]=0$, so $E[Y]=A0=0$, and $\mbox{Cov}(Y)=AIA^{T}=I$.  Thus $Y$ is $N(0,I)$.
This is discussed in many textbooks and references on mathematical statistics.  A reasonable starting point is the Wikipedia article on the multivariate normal distribution:
https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Affine_transformation
Comment: Thank you. I see now it is a very special case of a much more general result, which is why I was not able to find it simply by keyword search.
Comment: I've assumed that you're interested in real multivariate normal random variables and a real unitary (that is orthogonal) matrix A.  This becomes a bit more complicated if you want to deal with complex multivariate normal random vectors.
Comment: You assumed correctly.
Comment: For the complex case, see: http://www.rle.mit.edu/rgallager/documents/CircSymGauss.pdf


Boolean.parseBoolean not working

Question: I am trying to save this boolean array. When I read the array the string array (parts) says that
     parts[0]=true;

,but when I use Boolean.parseBoolean array[0] is still false. Can someone help me and tell me what I am doing wrong. Please and Thank You.
public void writeArraytofile() {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(Arrays.toString(array));
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.v("MyActivity", e.toString());
    }
}
public boolean[] read(){

String result = "";
boolean[] array = new boolean[2];
try {

    InputStream inputStream = openFileInput("array.txt");

    if (inputStream != null) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String tempString = "";
        StringBuilder stringBuilder = new StringBuilder();

        while ((tempString = bufferedReader.readLine()) != null) {
            stringBuilder.append(tempString);
        }

        inputStream.close();

        result = stringBuilder.toString();

        String[] parts = result.split(" ");
        for (int i = 0; i < array.length; i++){
            array[i]=Boolean.parseBoolean(parts[i]);

        }

    }

} catch (FileNotFoundException e) {
    Log.v("MyActivity", "File not found" + e.toString());
} catch (IOException e) {
    e.printStackTrace();
} catch (NumberFormatException e) {
    //here you catch and watch the problem
    Log.e("MyActivity", "cant parse string: " + result);
}
return array;
}

Comment: 'parts[0] = true' wouldn't compile
Comment: The very first thing I do when I provide input that doesn't get handled as I expected is to inspect the input to make sure it's what I thought it was. Did you think to check `parts[i]` to see what it contains when you pass it on to `Boolean.parseBoolean`? I'll bet it's not what you think.
Comment: because it's a string array...
Comment: @anomeric why not?
Comment: Could you please show us the value inside variable `result`
Answer: Arrays.toString() will print brackets and commas, so when you read the string back in and call .split(" "), the first piece will be "[true,". Since that is not just "true", Boolean.parseBoolean() will return false.

Boolean.parseBoolean not working


What should be the rDNS PTR records for a self-hosted email server with a website domain hosted elsewhere?

Question: We have a self-hosted mail server at our business's single, static IP address (mail.companyA.com). Our website is hosted by another company at a different IP address (companyA.com). Our emails use the @companyA.com domain.
Sometimes we send emails to certain clients that get through fine, and sometimes we get bouncebacks from the same client indicating we are blocked. Short-story: I am concerned that a reverse DNS lookup done by some companies with stricter requirements on emails is getting us in trouble depending on the rDNS lookup result that appears first.
MXToolbox reports that a rDNS lookup on our static IP address (from which we sent our emails) has two PTR records:  One to mail.companyA.com and the other to companyA.com
Should I request our ISP to remove the PTR record to companyA.com, leaving only mail.companyA.com - or will this create problems?
Answer: The issue here is usually related to Forward Confirmed reverse DNS (FCrDNS) checks, which are used as proof-of-work tests by some mail servers.
A receiving server may perform a check using the sending server IP address PTR record and confirm that an A record exists that matches the PTR record. Some mail servers even go further and verify a 200 response.
If your mail server is located at mail.example.com, then the PTR for the IP address of the server should be mail.example.com.
Note that an IP address can have only one PTR record.
A more technical explanation that includes other reasons to configure FCrDNS are included in RFC 1912.
Comment: Thank you all - I think the problem is well illustrated, then, by the PTR discussion. In fact, our static IP has 2 PTR records, one which is correct (mail.example.com) and the other which points to our website hosted at a different location and should be removed (example.com).
I have started a conversation with our ISP to request this change (and that has its own communication difficulties where they think everything is fine).
I am confident this will lead to the resolution of our intermittent problem, once it is updated.
Comment: The host name provided by PTR should also match the MTA's HELO name. IP->PTR->A->IP *MUST* match.
Comment: The fourth paragraph is wrong. An IP address *can* have more than one PTR record. It is not recommended, but it is not forbidden either. In other words, it will technically work, although the result will probably not be useful.
Comment: @TilmanSchmidt I wasn't intending to suggest it to be programmatically impossible.
Comment: Well, you wrote "can have only" which in English typically indicates (im-)possibility.
Comment: To pass an FCrDNS check, there can be only one PTR record. I think you are abstracting the sentence from the rest of the post.


No memory window in Visual Studio 2010

Question: I have VS2010 Premium RTM version on Windows 7 Ultimate x64.
In the documentation they refer to the Memory 1-4 windows, supposedly under Debug->Windows->Memory.
I have "Enable address-level debugging" enabled in VS (Options->Debugging).
The problem is that I have no Memory menu item under Debug->Windows during debug of a c++ program.
Under Debug->Windows I have only:
Breakpoints
Parallel Tasks
Parallel Stacks
Watch ->
Locals
Call Stack
Threads
Have anyone else experienced this (and hopefully solved it)?
Comment: Also running Visual Studio 2010 Premium RTM on Win7 (Pro) x64, and the windows are there. Just to confirm that the memory windows are supposed to be there in this configuration.
Comment: They're even there when running managed (C#) code, not that you need them then.
Comment: When I'm debugging assembly language programs, the memory window only shows up for me (in Visual C++ 2010 Express) when I use "Step into.", with "Expert Settings" enabled.
Answer: During the first run of VS after installation it asks you which "mode" it should run in, depending on your selection it shows or hides various menu items etc. Maybe you selected an option that hid those windows? This is described at this page.
I think you can use the information on this page to change those settings.
You might also be able to just run Devenv /ResetSettings to reset them, but not sure exactly what you'd end up with then...
Comment: That solved it for me, imported the Visual C++ settings.

Thank you, you have saved my day!
Comment: Also, which settings would I need to select in order to enable the memory window options?
Comment: Also, where should I run `Devenv /ResetSettings`?
Comment: @AndersonGreen DevEnv is the executable, so just open a visual studio command prompt. Not 100% sure which setting you should use, but since C++ is the one that sounds most likely to use the Memory window I'd guess at that.
Comment: @FredrikJansson How did you import the Visual C++ settings? I'm still trying to figure out how to do this. :/
Comment: Also, is it possible to show all of the menu items at the same time in Visual Studio (instead of just showing some of them)?
Comment: That didn't work for me. Don't see Debug | Windows | [Memory | Disassembly | Registers] option. Added them manually but they appear disabled :(
Answer: Go to command Window and type in memory. It will show the Memory 1 watch window. I had to do that because I still can't find the debug command for it under customize even.
Answer: You can switch to expert mode by checking :
Tools > Settings > Expert Settings

Now you can show up Registers Window and much more other windows
Answer: The Memory window is available only if address-level debugging is enabled in the Options dialog box, Debugging node. The Memory window is not available for Script or SQL, which are languages that do not recognize the concept of memory.
or go here for other details:
http://msdn.microsoft.com/en-us/library/s3aw423e.aspx

No memory window in Visual Studio 2010


Sumir com um componente usando jQuery ao carregar a página. E depois aparecer ele após um determinado evento em um laço while

Question: Criei um jogo de jokenpo e quero colocar um while para pedir um valor para o usuário. Preciso que quando o document seja carregado o texbox suma.
   $(document).ready(function(){

    var choice = null;
    var vitoriaPlayer = 0;
    var vitoriaComputer = 0;

    $("#nameJogador-index").ready(function(){
        this.hide();
    });

    //Altera o nome do jogador no inicio do index_game
    $("#nameUser").text(localStorage.jogador);

    //Gera a opção do computador
    var computerChoice = Math.random();

    if (computerChoice < 0.34) {
        computerChoice = "Pedra";

    }else if(computerChoice <= 0.67) {
        computerChoice = "Papel";

    }else {
        computerChoice = "Tesoura";

    }

    //Evento e função responsáveis por comparar as jogadas e mostrar para o usuário
    $('#pedra, #papel, #tesoura').on('click', function(ev){

        //Atribui o valor clicado pelo usuário para variavel choice
        var choice = $(this).prop("id").toLowerCase();
        computerChoice = computerChoice.toLowerCase();

        if((computerChoice == choice) || (computerChoice == choice)||(computerChoice == choice)){
                $("#vencedor").text("Empate");
                $("#jogada-jogador").text("Jogada do jogador(a) "+localStorage.jogador+" foi "+choice);
                $("#jogada-oponente").text("Jogada do oponente foi "+computerChoice);

        }else if (choice === "pedra"){

                if (computerChoice === "tesoura"){
                    $("#vencedor").text("Jogador "+localStorage.jogador+" venceu");

                    vitoriaPlayer += 1;

                    $("#scoreUser").text(vitoriaPlayer);

                    $("#jogada-jogador").text("Jogada do jogador(a) "+localStorage.jogador+" foi "+choice);
                    $("#jogada-oponente").text("Jogada do oponente foi "+computerChoice);

        }else{
                    $("#vencedor").text("Oponente venceu");

                    vitoriaComputer += 1;

                    $("#scoreOponent").text(vitoriaComputer);

                    $("#jogada-jogador").text("Jogada do jogador(a) "+localStorage.jogador+" foi "+choice);
                    $("#jogada-oponente").text("Jogada do oponente foi "+computerChoice);
            }

        }else if (choice === "papel"){
                if (computerChoice === "pedra"){

                     $("#vencedor").text("Jogador "+localStorage.jogador+" venceu");

                     vitoriaPlayer += 1;
                     $("#scoreUser").text(vitoriaPlayer);

                     $("#jogada-jogador").text("Jogada do jogador(a) "+localStorage.jogador+" foi "+choice);
                     $("#jogada-oponente").text("Jogada do oponente foi "+computerChoice);

        }else{
                     $("#vencedor").text("Oponente venceu");

                     vitoriaComputer += 1;

                     $("#scoreOponent").text(vitoriaComputer);

                     $("#jogada-jogador").text("Jogada do jogador(a) "+localStorage.jogador+" foi "+choice);
                     $("#jogada-oponente").text("Jogada do oponente foi "+computerChoice);

            }

        }else if (choice === "tesoura") {

                if (computerChoice === "pedra"){
                     $("#vencedor").text("Oponente venceu");

                     vitoriaComputer += 1;

                     $("#scoreOponent").text(vitoriaComputer);

                     $("#jogada-jogador").text("Jogada do jogador(a) "+localStorage.jogador+" foi "+choice);
                     $("#jogada-oponente").text("Jogada do oponente foi "+computerChoice);

        }else{

                     $("#vencedor").text("Jogador "+localStorage.jogador+" venceu");

                     vitoriaPlayer += 1;

                     $("#scoreUser").text(vitoriaPlayer);

                     $("#jogada-jogador").text("Jogada do jogador(a) "+localStorage.jogador+" foi "+choice);
                     $("#jogada-oponente").text("Jogada do oponente foi "+computerChoice);
            }

            if(vitoriaPlayer >= 3){
                alert("Jogador "+localStorage.jogador+" venceu");
            }else if(vitoriaComputer >=3){
                alert("Computador ganhou");
            }
        }

        //Janela modal
        ev.preventDefault();

        var id = $("a[rel=modal]").attr("href");

        var alturaTela = $(document).height();
        var larguraTela = $(window).width();

        //Colocando o fundo preto
        $('#mascara').css({'width':larguraTela,'height':alturaTela});
        $('#mascara').fadeIn(1000);
        $('#mascara').fadeTo("slow",0.8);

        var left = ($(window).width() /2) - ( $(id).width() / 2 );
        var top = $(window).scrollTop()+10

        $(id).css({'top':top,'left':left});
        $(id).show();

        });

        $("#mascara").click( function(){
            $(this).hide();
            $(".window").hide();
        });

        $('.fechar').click(function(ev){
            ev.preventDefault();
            $("#mascara").hide();
            $(".window").hide();
            });
        });

Código HTML

        <input type="text" id="nameJogador-index" placeholder="Nome do Jogador">
        <input type="submit" value="Jogar" id="jogar">

Comment: Mas ainda tah faltando algum código ali depois do while.
Comment: Com o código cortado não tem como reproduzir para entender como isso funciona.
Comment: Opa, e agora, ficou melhor?
Comment: Agora melhorou. =]
Comment: Me desculpa, tinha colocado o while mas para ter uma noção do que eu queria e não coloquei a variável para pegar o click
Comment: Se entendi, você quer que suma o formulário onde coloca o nome do jogador?
Comment: Sim isso mesmo, se a jogada do usuário for igual a do computador vai gerar um empate e dai para o while rodar certo vai ter que pedir um outro valor para o usuário. Só que eu quero que esse evento seja disparado quando ocorrer o empate, caso contrário que permaneça escondido.
Comment: Eu não consegui reproduzir seu código aqui... dá erro.
Comment: Ficou faltando a outra parte do programa, desculpa. Sou novo aqui, ainda não me acostumei.
Answer: Você pode usar o .hide() e o .show() do JQuery.
Exemplo:
$('#id_do_componente').hide(); //Some

$('#id_do_componente').show(); //Aparece

Fonte:
https://www.w3schools.com/jquery/jquery_hide_show.asp


Vista / 7 Base Filtering Engine Prevents All Incoming Connections

Question: After last months batch of Windows updates, no one can RDP into their machines.
Doing a bunch of testing turns up that you can't connect to ANY of the ports on the machine.  Stopping the 'Base Filtering Engine' immediately makes the box perform like a 'normal' Windows workstation.
It also doesn't appear to be any of the services dependent on BFE either--I tried stopping those one-by-one and it didn't fix the issue.
I tried stopping the Windows Firewall Service, and that didn't fix it.  I stopped their eTrust antivirus too.
Whenever the BFE service is running, you can't connect to anything on the machine.  Any pointers?  Google returns a ton of problems with BFE failing to start, but nothing that I can find about it denying all inbound traffic.  This happens on both Windows 7 and Windows Vista boxes.
Comment: Started a case w/ MS.
Answer: Sorry--forgot to post my answer after MS got back to me.
Microsoft said to run:
Secedit /configure /cfg c:\Windows\inf\defltbase.inf /db defltbase.sdb /verbose
I'm not familiar with the secedit tool, so run it at your own risk, but apparently this clears out the firewall rules and then re-applies them from group policy on the next reboot.


ValueError: math domain error

Question: Alguém pode me ajudar com o erro abaixo:
As vezes ele aparece as vezes não , sou noob e não entendo o porque disso.
Código:
import math

a = float(input("digite o valor de a: "))
b = float(input("digite o valor de b: "))
c = float(input("digite o valor de c: "))

delta = b**2 - 4 *a*c
raiz_delta = math.sqrt(delta)

x1 = (-b + raiz_delta)/2*a
x2 = (-b - raiz_delta)/2*a

print("x1 e igual a ", x1)
print("x1 e igual a ", x2)

Erro:
digite o valor de a: >? 2
digite o valor de b: >? 5
digite o valor de c: >? 6
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/DACIO/PycharmProjects/Introducao_ao_Python_Diego_Mariano/Respostas_Curso_V2.py", line 34, in <module>
    raiz_delta = math.sqrt(delta)
ValueError: math domain error

Comment: Este erro está acontecento pois o valor de `delta` é negativo e não é possivel tirar a raiz quadrada de um numero negativo.
Answer: Bom, como comentado por outro usuário, a função math.sqrtestá definida apenas para números positivos e, portanto, retorna um erro toda vez que delta for negativo. Existem duas soluções para seu problema. A primeira é aproveitar o seu código e incluir uma condicional. Veja:
import math

a = float(input("digite o valor de a: "))
b = float(input("digite o valor de b: "))
c = float(input("digite o valor de c: "))

delta = b**2 - 4 *a*c

if delta>0:
    raiz_delta = math.sqrt(delta)

    x1 = (-b + raiz_delta)/2*a
    x2 = (-b - raiz_delta)/2*a

    print("x1 e igual a ", x1)
    print("x1 e igual a ", x2)
else:
    print('Delta tem valor negativo e, portanto, as raízes da equação são números complexos')

A segunda opção consiste em usar a função built-in pow cujo domínio incluí números negativos.
a = float(input("digite o valor de a: "))
b = float(input("digite o valor de b: "))
c = float(input("digite o valor de c: "))

delta = b**2 - 4 *a*c

print(delta)
raiz_delta = pow(delta,0.5)

x1 = (-b + raiz_delta)/2*a
x2 = (-b - raiz_delta)/2*a

print("x1 e igual a ", x1)
print("x1 e igual a ", x2)

ValueError: math domain error


Stabilizer of probability measure on projective space

Question: I'm reading notes on Lattices on Lie groups (in French:
Réseaux des groupes de Lie) by Yves Benoist and I have some
troubles to understand some aspects on the setting & proof of the
Lemma 7.3 (due to Furstenberg) on page 60.

Let $k= \mathbb{R}, \mathbb{C}$ or a finite
extension of $p$-adic field $\mathbb{Q}_p$, $p$ prime. Let $E:=k^d$ be
a vector space and $\mathbb{P}(E)$ the associated projective space,
$\operatorname{PGL}(E)$ the group of projective transformations
on $\mathbb{P}(E)$ and $\nu$ a probability measure on
$\mathbb{P}(E)$.

Let $S:= \{ g \in \operatorname{PGL}(E) \ \vert \ g_* \nu = \nu \} $.
(recall $ g_* \nu $ is the push-forward or image measure with respect
automorphism $g: \mathbb{P}(E) \to \mathbb{P}(E)$)
Questions:
1) In the notes there is not a word said about the $\sigma$-algebra
with which the projective space $\mathbb{P}(E)$ is endowed which allows
to consider a (probability) $\nu$.
In most cases when dealing with measures on affine space $k^d$
without making any comment on the underlying $\sigma$-algebra,
one uses in silence the Borel-$\sigma$-algebra, a kind of canonical
$\sigma$-algebra on affine spaces.
Is there any type of "canonical" $\sigma$-algebra for
projective spaces which is in most cases used when one is
discussing measures on projective spaces without mentioning
by name the underlying $\sigma$-algebra? So is there a kind of
standard $\sigma$-algebra for projective spaces known as a sort of
pendant to the Borel-$\sigma$-algebra for affine spaces?
2) At the beginning of the proof of the Lemma there is remarked that it's rather
obvious that the stabilizer $S:= \{ g \in \operatorname{PGL}(E) \ \vert \ g_* \nu = \nu \} $
of probability measure $\nu$
is a closed subspace in $\operatorname{PGL}(E)$.
Why that's the case? I assume that the topology on
$\operatorname{PGL}(E)$ is the quotient topology induced
from $\operatorname{GL}(E) \subset \operatorname{End}(E) \cong k^{d^2}$.
It is known that if in general a topological group $G$ acts continuously
on a topological space $S$ by continuous map
$a: G \times S \to S$, then any stabilizer is closed.
But here we consider the "stabilization" of a measure und
there is no standard way I know to endow the "space of meausures"
on $\mathbb{P}(E)$ with continuous $\operatorname{PGL}(E)$-action.
How the closedness of
$S= \{ g \in \operatorname{PGL}(E) \ \vert \ g_* \nu = \nu \} $
can be deduced? I not see the exact reason why that's really clair at all.
Answer: 1) The canonical projection $\pi:E\setminus0\to \mathbb{P}(E)$ is a (topological) quotient map; the $\sigma$-algebra of $\mathbb{P}(E)$ is the associated Borel $\sigma$-algebra (in your situation, and in general if $\sigma$-algebras are not mentioned). By an argument similar to that discussed at https://math.stackexchange.com/a/4348985/169085 this is the same thing as saying $B\subseteq \mathbb{P}(E)$ is measurable iff $\pi^{-1}(B)\subseteq E\setminus0$ is Borel measurable.
2) Note that $\mathbb{P}(E)$ is a compact metric space. Consequently the space $\mathcal{M}(\mathbb{P}(E))$ of Borel probability measures on $\mathbb{P}(E)$ is compact w/r/t the weakstar topology. Further, the action $\mathbb{P}\text{GL}(E)\curvearrowright \mathbb{P}(E)$ is by homeomorphisms, so the action $\mathbb{P}\text{GL}(E)\curvearrowright \mathcal{M}(\mathbb{P}(E)), g\curvearrowright \mu=g_\ast(\mu)$ is by affine homeomorphisms. (You are correct to assume $\mathbb{P}\text{GL}(E)$ to be endowed with the quotient topology). Now you can use the general statement about stabilizers of topological actions, or alternatively you can take $g_n\to g$ and argue that if $(g_n)_\ast(\nu)=\nu$, then $g_\ast(\nu)=\nu$ also. Of course, the stabilizer is not only a closed subspace; it's a closed subgroup.
Comment: thank you, that was exactly what I was looking for! one remark: you use the statement that if $S$ is a *compact metric space*, then the space $\mathcal{M}(S)$ of Borel probability measures on $S$ is *compact* wrt weak^* topology. could you give a reference for the proof of this statement. I should admit that I have never saw it before
Comment: @user7391733 I'm glad it was useful. Regarding the compactness of $\mathcal{M}(S)$, Parthasarathy's book Probability Measures on Metric Spaces is the standard reference (see Thm.6.4 on p.45 for the particular statement). Introductory books on ergodic theory (Walters, Einsiedler-Ward, Brin-Stuck, Katok-Hasselblatt ...)  would contain a proof as well.


Cargowise eAdaptor API manual + integration with QlikSense

Question: just wanted to ask, if somebody has a manual for eAdaptor API for Cargowise?
We are trying to get the data from the system to QlikSense via REST API and we are not entirely sure how to do it. We do have an URL that will get us probably to some "middle man", however we still need to create a query for a specific (for example) shipment.
If somebody was working with this API and would have some insight, any help would be much appreciated.
Answer: There is an "eAdaptor Developers Guide.pdf" download which contains all the info about the CargoWise side of things.
You'll need someone with a CargoWise instance to download it for you from the following location in the CargoWise portal:


Prevent line break in doc test

Question: I am trying to write a doc test for a struct member function created by a macro. Apparently it is only possible to use a capture in a standalone doc attribute. However, this forces a line break in the doc test so that the capture fills an entire line in the rendered result. Is this a way to prevent line breaks or to use the capture directly without using procedural macros?
#[macro_export]
macro_rules! gen_functions {
    ($name:tt) => {
        /// # Usage
        ///
        /// ```
        /// let h =
        #[doc = $name]
        ///  {};
        /// h.test_a();
        /// ```
        pub fn test_a(&self) {
            println!("test a")
        }
    };
}

pub struct CustomStruct {}
impl CustomStruct {
    gen_functions!("CustomStruct");
}

fn main() {
    let h = CustomStruct {};
    h.test_a();
}

And the resulting doc test. It does compile but it is difficult to read (compared to the version in the main function):
let h =
CustomStruct
{};
h.test_a();

Comment: @Stargateur I wrote a post [here](https://internals.rust-lang.org/t/idea-concatenate-strings-in-doc/12042) to pitch your idea (although I proposed a slightly different syntax)
Comment: There's a macro crate for this: https://lib.rs/crates/doc-comment
Comment: `#[doc(" let h = ", $name, " {};")]` should work I advice you to create issue in https://github.com/rust-lang/rust/issues
Comment: @Stargateur `#[doc(...)]` doesn't work, the right syntax is `#[doc = ...]` for documentation
Comment: @Aloso As I said "should" work, it doesn't..., https://doc.rust-lang.org/rust-by-example/attribute.html.
Comment: @Stargateur the syntax with parentheses is used for _configuration_. For instance, `#[doc(hidden)]` means that the item is not displayed in the documentation, and `#[doc(inline)]` will inline items in the docs, when they are re-exported. [More infos](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html)
Comment: @Aloso I don't care, rustdoc could implement it that what I want to say. for example `#[doc(doc = " let h = ", doc = $name, doc = " {};")]` or something.
Answer: Someone showed me a nice solution on this internals thread, which uses a macro. I adjusted the macro to make it nicer to use.
Usage:
macro_rules! gen_functions {
    ($name:tt) => {
        doc! {
            /// # Usage
            ///
            /// ```
            [concat!(" let h = ", $name, " {};")]
            /// h.test_a();
            /// ```
            @ pub fn test_a(&self) {
                println!("test a")
            }
        }
    };
}

And this is the macro:
macro_rules! doc {
    {
        $(#[$m:meta])*
        $(
            [$doc:expr]
            $(#[$n:meta])*
        )*
        @ $thing:item
    } => {
        $(#[$m])*
        $(
            #[doc = $doc]
            $(#[$n])*
        )*
        $thing
    }
}

The macro converts strings in [square brackets] into #[doc = _] attributes. What makes it special is that it can contain concat! and stringify! macro calls. They can also be combined, e.g.
doc! {
    /// # Usage
    ///
    /// ```
    [concat!(" let ", stringify!(h), " = ", stringify!(CustomStruct), " {};")]
    /// h.test_a();
    /// ```
    @ pub fn test_a(&self) {
        println!("test a")
    }
}

Comment: This works good for module level functions. If I try it inside of a `impl` block I get  a strange error message `expected one of 'async', 'const', 'crate', 'default', 'extern', 'fn', 'pub', 'type', or 'unsafe', found 'pub fn test_a(self: (/*ERROR*/)) { println!("test a") }'` (removing the self parameter does not solve this error, origin is the `doc` macro). It seems it does not parse the the `$thing:item` capture properly. Any idea how to solve this?
Comment: You have to put an `@` before the item (this was necessary so the syntax of the macro is unambiguous).
Comment: I did that. The code I used for testing: [github gist](https://gist.github.com/pixix4/33658477f67a3a46c2069acff9c49270)

Prevent line break in doc test


injective dimension and Ext

Question: Let $(R,m)$ be a Noetherian local commutative ring with a unit. $M$ is a finitely generated module. In the article "Minimal Injective Resolutions" by Robert Fossum, he mentioned it is standard that
$$\operatorname{id}_R(M)=\sup\{i\mid \operatorname{Ext}^i_R(R/m,M)\neq 0 \}$$
why is it the case? I mean $\operatorname{id}_R(M)$ is definitely $\sup\{i\mid\operatorname{Ext}^i(N,M)\}$ in which $N$ ranges through all modules. How can we reduce it to the case $R/m$?
Does it mean $M$ is injective if and only if $\operatorname{Ext}^1(R/m,M)=0\,$? I mean if this is true, the original problem is trivial.
Thank you
Comment: I do not think the statement that $M$ is injective if $Ext^1_R(R/m,M) = 0$ is true. For instance, take a regular local ring $R$ of dimension at least $2$ and $M = R$. Then $Ext^1_R (R/m, R) = 0$ as the depth of R is at least $2$. But $R$ is not injective an $R$-injective module.
Answer: (R,m) is Noetherian local ring.
I am very sorry for the wrong argument.thanks for the comment above.it shows that $M$ may not injective if $Ext^1(k,M)=0$.We only can reduce to the case $M$ is injective iff $Ext^i(k,M)=0.\forall i>0$.
Definition:If $M$ is an $R$ module,$p\in Spec(R)$ is called associate prime if $\exists x\in M$ such that $ann(x)=p$.
Denote $ass(M)$ is the set of associated prime ideals.
lemma1:for any nonzero module M,$ass(M)$ is not empty.
corollary1:for any finite generated module $M$,there is a filtration:$M_0=0\subset M_1\subset M_2\subset …\subset M_n=M$ such that $\forall i=0,1,2,…,n-1.\exists p_i\in Spec R$ such that $M_{i+1}/M_i\cong R/p_i$.(In fact,$p_i\in Supp(M)$)
Lemma2:if $N$ is finite generated and $Ext^1(R/p,M)=0 ,\forall p\in Supp(N)$,then $Ext^1(N,M)=0$.
Lemma3:Let $M$ be a finite generated $R$ module.if $p$ is a prime ideal different from $m$,and $Ext^{n+1}(R/q,M)=0,\forall q\in V(p)-p$,then $Ext^n(R/p,M)=0$.
(Hint:select $x\in m-p$,then there is a short exact sequence $0\rightarrow R/p \xrightarrow x R/p \rightarrow R/(x,p)\rightarrow 0$.
Remark $Supp(R/(x,p)\subset V(p)-p$.
Then you can prove $id M=sup\{i\mid Ext^i(k,M)\ncong 0\}$ by using Lemma 3 repeatedly.
Comment: If all the prime ideals has this property,then use lemma2.
Comment: Of course Baer's criterion.
Comment: @LongLêThiên such as:Relative homological algebra.(Enoch and Jenda)
Comment: @LongLêThiên yesterday I have a wrong hinit.I say consider prime ideals $V(p)=m$,in this case $p=m$.I am so sorry!I feel so ashamed!
Comment: @LongLêThiên thanks,

injective dimension and Ext


Nagios 3 how to install RabbitMQ plugin Ubuntu 12.04

Question: I am trying to incorporate a RabbitMQ Server into our Nagios Core 3 running on Ubuntu 12.04.
My searching led me to http://www.thegeekstuff.com/2013/12/nagios-plugins-rabbitmq/ which seemed quite informative.
When I run the ./check_rabbitmq_server I encounter an error message Can't locate Monitoring/Plugin.pm in @INC ... which led me to the discussion at https://github.com/monitoring-plugins/monitoring-plugin-perl/issues/6
Where can I find the package libmonitoring-plugin-perl for Ubuntu 12.04?
Edit: When attempting to run apt-get install libmonitoring-plugin-perl the package is not found in Ubuntu 12.04. Only libmonitoring-availability-perl and libmonitoring-livestatus-perl are found in the repository.
Edit #2
I have attempted to install the perl plugin. The command and result are here:
cpan[2]> install libmonitoring-plugin-perl
Warning: Cannot install libmonitoring-plugin-perl, don't know what it is.
Try the command

i /libmonitoring-plugin-perl/

to find objects with matching identifiers.

cpan[3]> i /libmonitoring-plugin-perl/
No objects found of any type for argument /libmonitoring-plugin-perl/

Thank you.
Steven
Comment: Have you think to install this module via CPAM?
Comment: This may be trivial but the package does exist in Ubuntu's repositories. See http://packages.ubuntu.com/yakkety/libmonitoring-plugin-perl -- have you considered using apt-get instead of wget to download/install the package?
Comment: when attempting to run apt-get install libmonitoring-plugin-perl the package is not found in Ubuntu 12.04. Only libmonitoring-availability-perl and libmonitoring-livestatus-perl are found in the repository.
Comment: @RomeoNinov please see my edit #2 above
Comment: @Steven, try to search for libmonitoring or just monitoring and select appropriate
Answer: After careful review of the results from the make test and additional Google'ing around I found via CPAN console adding numerous Perl libraries resolved the issue. Sorry, I do not recall the 3 or 4 Libraries I had to add. Please refer to the error messages when you run your make test command.


How does music theory explain I-VII7-I?

Question: In the tune called Whispering we find C-B7-C (I-VII7-I). The melody descends from C to B in bars 2 and 3. The chords also do this. B7 sounds a bit like a dominant chord to me but it uses non-scale tones. B7 is not even a part of the scale. I have been thinking if it is a bit modal but I hear the tune as tonal music. A lot of modal music never use non-scales tones anyway.

How does music theory explain I-VII7-I?
Comment: @PiedPiper That other question doesn't have an accepted answer, so how could it answer this one. :) Actually, I have yet to really understand any of these "how does theory explain" questions. What is it that the posters want? Do they ever confirm that now something has been "explained"? What does it even mean to explain a chord sequence. How does one know that an explanation was sufficient. They get a feeling "ahh... theory... words... ", go away and forget the whole thing? Or does the explanation allow them to _do_ something? What?
Comment: @piiperiReinstateMonica - I believe that "how does theory explain this chord progression" questions mainly ask for how these chord progressions can be interpreted, preferably with common practice period harmony. That way, the question asker can learn whether they can use that chord progression in a piece of classical music in the style of the 19th century or earlier without breaking genre or feeling like the chord progression doesn't fit. (For example, if all the answers explain the chords as a tritone substitution, the progression probably breaks 19th-century-or-earlier classical genre.)
Comment: Mr. Sandman has the same first change, but then it goes into the circle of 4ths. We really have a whole bunch of questions which are asked on the premise that there's something wrong with using non-diatonic notes. Those notes B and A are both from B7. Nothing wrong there?
Comment: I would say those answers do not sufficiently answer the question.
Comment: OP: you could ask, how is the usage or function or harmonic effect of the VII7 chord in Whispering different than the VII7 in Jobim's Meditation. If the answers to the Meditation question don't explain the issue to you, then I don't know what you could do about it.
Comment: @Tim wrong? not at all. Everything is in order. I just wanted to know the formal explanation of this harmony.
Comment: @Dekkadeci common practice period harmony? I am not sure that would be the best language to explain this kind of harmony. We also have jazz harmony
Answer: With common practice period harmony, a C-B7-C chord progression interpreted as I-"VII7"-I can be interpreted as I-V7/iii-VI/iii instead, with the VI/iii simultaneously having a pivot chord interpretation of I.
Comment: @Tim note 1. vi (or bVI) quite frequently substitutes I (or i) in deceptive resolution 2. another example (unrelated in this question): it's often very useful to consider pair of chords as ii-V, even if not followed by I
Comment: This seems to be the theory, but what does one do with it? To me, V/x is trying to explain that the V part leads to the x, but it appears that it doesn't actually have to. So where does it go? Wherever the composer wants! So calling it V/x becomes pretty well meaningless.
Comment: @Tim - The "wherever the composer wants" is covered by the VI/iii chord being interpreted as a I chord at the same time. The purpose of this answer is to provide an interpretation consistent with common practice period harmony instead of one that throws it out.
Comment: I'm not knocking your answer, far from it. I'm questioning the point in theory calling something V/x, when not actually leading to x. But then again, in key C, we call G V, but it ofrten doesn't get followed by I (C).
Comment: One thing that I think strengthens this interpretation is that it's supported by voice leading, the double leading tone B-D# up to C-E is pretty clearly dominant-tonic motion.
Answer: It is one of the standard passing-6/4-chord-progressions. Along with the cadential-6/4-chords and pedal 6/4-chords-progressions form the basis in standard harmony for how second inversion chords are used.
These passing chords would actually be either, I6 - vii 6/4 - I 5/3 or I 5/3 - vii 6/4 - I6 (If I remember correctly.). I did these chords extensively in my ABRSM grade 6 exam. They seemed to be a recurring theme in question 2 of that exam.
The basics of the passing 6/4 progressions can be seen in the following pictures. The I-IV-I and V - I -V are quite common. The one you mentioned is the slightly more advanced one. You learn in the first advanced grade of music-theory. For me that was ABRSM grade 6.
Comment: Isn't your image showing pedal (or "neighbor") six-fours, not passing?
Comment: Could it be a tritone sub for the IV?  But why IV7?  There is such a thing as a vii-->I cadence (leading tone cadence).  But that would be a -7(b5) which is just an extension of the V7.  Considering how the altered notes in the VII7 relate to the V7 may reveal that this is a type of altered V7 extension.  Or so I speculate.
Comment: This seems to have little to do with the OP's question. Where's VII?

How does music theory explain I-VII7-I?


"Connection refused" when using host network in Docker in GitHub Actions

Question: I am starting a Docker container with Chrome inside, as follows:
docker run --rm --cap-add=SYS_ADMIN --network=host selenoid/vnc:chrome_117.0

In my local machine, this container listens to incoming requests in the following URL: http://localhost:4444/
Nevertheless, I have a "connection refused" error when trying to connect that URL (http://localhost:4444/) after starting that image (using the host network) in GitHub Actions. The error I get in Java is the following:
Caused by: java.net.ConnectException: Connection refused (Connection refused)

Can I use the host network in GitHub Actions?
Comment: Please include your GHA workflow in your question. Looks like you can make use of [service containers](https://docs.github.com/en/actions/using-containerized-services/about-service-containers) for your use case.
Comment: Using service containers is not an option for me, since the container is started programmatically using a Docker Java client. In any case, my GHA workflow is the following: https://github.com/bonigarcia/webdrivermanager/blob/master/.github/workflows/build.yml
Comment: Right. Have you tried to run that command directly? Are there any error logs?
Answer: Please have a look on this link How to access host port from docker containe  and Can't curl to localhost
Instead of localhost you can try http://host.docker.internal:4444/
Answer: I confirmed this can be done in GH Actions. The problem I experienced was the use of Xvfb. For some reason, using Xvfb does not allow us to use port 4444 in the same session.
It is solved as follows:

Test: https://github.com/bonigarcia/selenium-examples/blob/main/src/test/java/io/github/bonigarcia/selenium/remote/DockerWdmChromeCdpTest.java
Workflow: https://github.com/bonigarcia/selenium-examples/blob/main/.github/workflows/docker-java.yml
Execution: https://github.com/bonigarcia/selenium-examples/actions/runs/6706576135


QueryWorkspaces returning empty array but workspaces exist

Question: Quite simply, I'm trying to get a list of workspaces by calling the QueryWorkspaces method of the VersionControlServer class in powershell.  I'm passing null across to the parameters and according to the documentation it should give me a list of workspaces.
If I name the workspace it works fine and returns a single workspace but the documentation says a null name should give all the workspaces.
function Get-Workspace
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$TeamProjectCollection,
        [string]$Owner,
        [string]$Computer,
        [parameter(ValueFromPipeline=$true)]
        [string]$Name
    )

    begin
    {
        [Microsoft.TeamFoundation.Client.TfsTeamProjectCollection]$tfsTeamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($TeamProjectCollection)
        [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
    }

    process
    {
        Write-Output $versionControlServer.QueryWorkspaces($Name, $Owner, $Computer)
    }
}

I am running with Project Collection Administrator rights.
Answer: The problem appears to be PowerShell does not pass null as null when the .net class is expecting string.  Somewhere in the PowerShell layer the null was translated to an empty string.  This prevented the code path which returns all the workspaces from executing.  Instead it was trying to match a workspace called "".
The details of the issue are on a Microsoft Connect article which reports the issue to be fixed in PowerShell 3.0.
Knowing what the problem and with hints on how to fix it I started down the Reflection route.  However this got more complicated because the QueryWorkspaces method is overloaded so a simple call to GetType threw an exception.  Attempts to pass the array of types into the GetType call failed because PowerShell passed it as an array of Object instead of an array of Type.  Thus it had to be done long hand ...
function Get-Workspace
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$TeamProjectCollection,
        [string]$Owner,
        [string]$Computer,
        [parameter(ValueFromPipeline=$true)]
        [string]$Name
    )

    begin
    {
        [Microsoft.TeamFoundation.Client.TfsTeamProjectCollection]$tfsTeamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($TeamProjectCollection)
        [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
        [array]$methods = $versionControlServer.GetType().GetMethods()
        [System.Reflection.MethodInfo]$methodToInvoke = $null
        foreach($method in $methods)
        {
            if ($method.Name -eq "QueryWorkspaces")
            {
                if ($method.GetParameters().Length -eq 3)
                {
                    $methodToInvoke = $method
                }
            }
        }
    }

    process
    {
        if ([string]::IsNullOrEmpty($Name))
        {
            $params = @($null, $Owner, $Computer)
            Write-Output $methodToInvoke.Invoke($versionControlServer, $params)
        }
        else
        {
            Write-Output $versionControlServer.QueryWorkspaces($Name, $userName, $computerName)
        }
    }
}

Comment: Thank you. "To pass null, you need to use [System.Management.Automation.Language.NullString]::Value" - not exactly fixed but oh well.
Answer: Is ever using $null pass in
[System.Management.Automation.Language.NullString]::Value
Instead of $null
(PowerShell doesn't handle this properly and $null gets interpreted as "")


To use or not to use a variable that contains information w.r.t. uncertainty

Question: The data I'm looking at is concerned with percentages of people who would recommend a hospital.
<code>E.g.
               NOT         PROBABLY    DEFINITELY          FREQ
hospital_1     10.0        80.0        10.0                100
hospital_2     20.0        50.0        30.0                200
</code>
We'd like to do the analysis on the hospital level, so basically I converted the percentages in some kind of weighted score (for example the arbitrarily chosen NOT * 0 + PROBABLY * 1 + DEFINITELY * 2, does not matter), which will yield some kind of single variable called "average_recommendation_score".
I'm expecting that this score is unbiased regardless of the number of people who filled in the survey (FREQ), well... in the limit. However, in doing this kind of analysis, where this might actually be a dependent variable, should we also use the FREQ variable for the estimation of parameters (it feels like this given uncertainty about the average_recommendation_score contains extra information; you can imagine how a maximum score is probably not the "real" score if only based on 1 participant's vote)?
Is it OK to disregard the FREQ variable or should it / could it be incorporated somehow yielding a single variable? If it should be, how?
Note: The goal is inference using some variables that are assumed to be predictors.
Answer: From what I understand, you want to postulate a relationship (linear for exposition's shake)
$$q_i^* = \mathbf x_i'\beta + u_i,\;\; E(u_i\mid \mathbf X)=0,\;\; i=1,...,n$$
wher $q_i^*$ is a "quality score" of hospital $i$, and $\mathbf x_i'$ contains a series of regressors that in some way explain "objectively" this score (say, number of qualified staff, age of equipment, rate of in-hospital infections etc).
But, what you have available regarding the dependent variable, is an imperfect measurement of it, through the subjective evaluation of a sample from people that have used the services of each hospital. So instead of $q^*_i$ you have the series $q_i$. Now you need to make some assumptions.
First we assume that people perceive unbiasedly what the results of the "objective determinants of quality" are, and so "on average" they will provide a reliable measurement. This implies the relationship
$$q^*_i = q_i + \epsilon_i,  \;\;E(\epsilon_i) =0,$$
where $\epsilon_i$ is an i.i.d. error term, uncorrelated with the measurement.
Now each $q_i$ is calculated as
$$q_i = \sum_{k=0}^{h}\frac {m_{ik}}{m_i}k$$
where the set $\{0,...,h\}$ is the set of values to which you map the evaluation of each person for hospital $i$, $m_i$ is the total number of persons that expressed an opinion for hospital $i$, and $m_{ik}$ is the number among them that evaluated it with a score $k$. Given our assumption we have
$$q_i = \sum_{k=0}^{h}\hat p_{ik}k =\hat E(q^*_i),\;\; E(q_i) = E[\hat E(q^*_i)]=E(q^*_i)$$
So $q_i$ is an estimator of the expected value of $q^*_i$, and as such, it has a variance. And its variance will depend inversely on the size of the sample on which it is based. We have
$$\operatorname{Var}[q_i] = \operatorname{Var}\left(\sum_{k=0}^{h}\frac {m_{ik}}{m_i}k\right) = \frac 1{m_i^2}\operatorname{Var}\left(\sum_{k=0}^{h} m_{ik}k\right)$$
If we are willing to assume that $\operatorname{Var}\left(\sum_{k=0}^{h} m_{ik}k\right)$ is constant across $i$, then we can write
$$\operatorname{Var}[q_i] = \frac {\alpha^2}{m_i^2}$$
meaning that the variance will be different for each $i$,
because of the different sample sizes. This in turns imply that in the feasible specification that we can estimate,
$$q_i = \mathbf x_i'\beta + u_i,\;\; E(u_i\mid \mathbf X)=0,\;\;i=1,...,n$$
we have
$$\operatorname{Var}[q_i \mid X] = \operatorname{Var}[u_i \mid X] = \sigma^2_i=\frac {\alpha^2}{m_i^2}$$
and you have a model with conditional heteroskedasticity, of known functional form, a functional form that arises consistently from the characteristics of the model.
Then, the road forward is not to include the "sample size" as a regressor, but use it to estimate the conditional variances.
If you are willing to make a distributional assumption for $u_i$ you can estimate this in one take by using maximum likelihood (the $\alpha$ will be estimated alongside the $\beta$'s). Or by Two-stage least-squares.
For exposition's shake, if we assume that the distribution of $u_i$ conditional on the regressors is normal, then the log-likelihood of the sample will be
$$\ln L (\beta, \alpha \mid \mathbf X, \mathbf m) = \ln \left[\left(\frac 1{\sqrt {2\pi}}\right)^n\cdot \prod \frac {m_i}{\alpha}\cdot \exp{\left\{-\frac 12 \sum\frac {m_i^2}{\alpha^2}(q_i-\mathbf x_i'\beta)^2\right\}}\right]$$
$$= C -n\ln \alpha  -\frac 1{2\alpha^2} \sum m_i^2(q_i-\mathbf x_i'\beta)^2$$
which would give us the estimate
$$\hat \alpha^2 = \frac 1n\sum m_i^2(q_i-\mathbf x_i'\hat \beta)^2$$
alongside the estimates for the $\beta$ vector, which of course would be affected by the presence and the need to estimate also $\alpha$, thus taking into account the different sample sizes from which the $q_i$'s were calculated.
Finally, note that if the set of people expressing opinions on each hospital, overlap, then the $q_i$'s are auto-correlated, and you have additional issues.


Number of onto functions, why does my solution not work?

Question: I have a set $A$ with $4$ elements and a set $B$ with $3$ elements.
We need to find all onto functions from $A$ to $B$.
My line of thought:

Map each element in $A$ to $B$, where only one element in $A$ must be mapped to the same element in $B$.
So for the first element in $A$, we have $3$ choices.
For the second element in $A$, we have $2$ choices.
For the third element in $A$, we have $1$ choice.
Now map the fourth element in $A$ to any of the elements in $B$, hence $3$ choices. Total would be $3 * 2 * 1 * 3 = 18$.

This is wrong however, the solution is $36$.
The solution also uses a different approach. They say a pair of elements needs to map to the same element. Choose this pair in ${4\choose 2}=6$ ways. Then select any of the $3$ elements from $B$ as a mapping target. Then there are $2$ choices left, hence total is $6 * 3 * 2 = 36$
I find my approach more intuitive, however I wonder what I counted wrong. Seems I'm missing half of the possible solutions.
Comment: maybe the fourth element in $A$ is not the one that gets mapped to an element of $B$ that has two pre-images
Comment: Arranging the elements of $A$ in order of $a_1, a_2, a_3, a_4$ and declaring that the pair of elements mapped to the same element *must* be $a_4$.  We could also have that pair be ($a_1$ and $a_3$) or ($a_1$ and $a_2$) or ($a_2$ and $a_3$).
Answer: There is no reason why only one element of $A$ must be mapped to a given element of $B$. Let $A=\{a_1,a_2,a_3,a_4\}$ and $B=\{b_1,b_2,b_3\}$. Suppose $f(a_1)=f(a_2)=b_1, f(a_3)=b_2$ and $f(a_4)=b_3$. This is an onto function but you are not counting this function.
Answer: By your counting, the first two elements of $A$ cannot map to the same element of $B$.
Arguing along the lines you are using:  The first element of $B$ comes from any of the four elements of $A$, the second from any of the remaining three, the third from any of the remaining two.  The remaining element of $A$ can be mapped to any element of $B$, say $a_1 \mapsto b$ and $a_2 \mapsto b$, but we have overcounted.  Both choosing $a_1 \mapsto b$ during the first three steps and $a_2 \mapsto b$ during the last step and choosing $a_2 \mapsto b$ during the first three steps and $a_1 \mapsto b$ during the last step produce the same map, so we have only
$$  4 \cdot 3 \cdot 2 \cdot 3 \cdot \frac{1}{2} = 36  $$
distinct maps.


Taking screenshot of videoview and other multiple view in one layout

Question: I have created an application that creates random number of layouts at run time. I need to capture a screenshot of the screen/my application after some time (not fixed). I am successfully creating a bitmap of the screen using following code:
private Bitmap getBitmapOfRootView(View v){
    v = v.getRootView();
    v.setDrawingCacheEnabled(true);

    bitmap = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);
    return bitmap;
}

But whenever VideoView(s) is involved I am getting a black screen for the area of VideoView(s).
Here is one of the screenshot with VideoView.

I have found the solution. But it would work if there is only one layout being used. For this purpose I used the following code from VideoView getDrawingCache is returning black
public Bitmap videoFrame(String uri, long msec) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(uri);
        return retriever.getFrameAtTime(msec);
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        ex.printStackTrace();
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
        }
    }
    return null;
}

I know it is possible to take screenshot of VideoView using above code if only video is being displayed on the screen. But, in my application multiple views are visible (ImageView, WebView) at the same time. I am looking for a solution a generic which works with any time of view.
Answer: Try this
Bitmap bitmap = getBitmapFromView(rootView, rootView.getChildAt(0).getHeight(), rootView.getChildAt(0).getWidth());

private Bitmap getBitmapFromView(View view, int height, int width) {
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return bitmap;
}


How are very long tuplets in Romantic music played in practice?

Question: In Romantic music, especially for piano, one can often find oversized tuplets like this one: (the excerpt comes from the very beginning of the 3rd movement of Grieg's piano concerto)

Are you really supposed to play them "precisely" (i. e., in the first bar, each note and rest for only 8/13 of the notated length)? That looks like a nearly impossible task (or at least countless hours spent with the metronome). Or is it "acceptable" to break them down into smaller parts (triplets, quintuplets, heptuplets), for instance like this?

Or is there any other way? On the recordings, the whole run is performed so fast that I can't even discern how exactly it is played...
P.S.: I don't play the piano at all. I'm just wondering since those tuplets seem to pop up quite a lot. Meanwhile the biggest (prime) tuplet I can play is a heptuplet, and I never found any larger tuplet in any rhythm practice book either.
Comment: They are not at ALL to be interpretted in the way the West African tradition of rhythm would interpret those tuplets.  It basically means "squidge these notes into this space", and there's nothing wrong with that ;D
Comment: Sorry, that wasn't too clear, by west African I mean in the sense that music with a "groove", interprets tuplets: as polyrhythms to be rendered precisely.  In common practice music, meter is much more flexible: tempo is one of the musical elements available to you as a tool of expression.  In modern performance practice, classical musicians are VERY free with their interpretations of Tuplets (although they might not admit it). That's generally truer and truer of earlier recordings too, for straight rhythms AND tuplets see this for an example: https://youtu.be/qFPW9ENtNKA?t=370
Comment: http://youtu.be/tVV3SIvncD4?t=177 for an example of how a run of fast tuplets might be rendered (depends on context)
Comment: Examples from Chopin's nocturnes (and various other slower pieces) would probably be better, because they are often slow enough that one *can* discern whether or not the performer is performing them precisely metronomically.
Comment: @KyleStrand: Yes. However, these tend to contain the tuplets of notes printed in smaller size. I understood the small-sized (not grace) notes to generally mean "just somehow fit these notes into the given space" before asking the question, so hearing that these are rubato-ed wouldn't strike me as anything weird. I chose the Grieg concerto because it was the first thing to come up to my mind when I was thinking about long tuplets that looked like being meant seriously.
Comment: @Some_Guy, thanks for all the examples. I like to see other people and even famous composers to vary the tempi etc.... and generally just make music like people, not machines :—).
Comment: @Ramillies Hmm, that might depend on the edition--and if nothing else, the "tuple-marker" is still there, providing the number of noteheads in Arabic numerals.
Answer: They aren't necessarily supposed to be played with metronomical precision of the 13:8 ratio, but they are supposed to make up a homogeneous run with no unequal subdivision. In particular, there should be no note in the run that clearly hits the 2 beat, as the B and A do in your proposed subdivision, so that approach is no good. I would at least not train to play that subdivision, especially not in a rigid fashion with those sub-tuplets counted out.
Really, much the idea behind such tuplets is usually to lose the track of a steady rhythm, in favour of a more dreamy or disoriented impression. Instead of counting them out in any rigid way, one should focus on the run as a whole, where it leads, and that it goes over smoothly with no kind of interruption. The entire thing should then ideally also last about one bar, but that's not as crucial really – a bit of rubato is almost always ok in romantic music.
Comment: Great answer: The idea is a smooth flurry of notes to be played fluidly
Comment: Good general answer, but not relevant to this particular example.  This flourish from the Grieg concerto is anything but "dreamy or disoriented".
Comment: I'm not sure if that was your intention, but the phrase "no unequal subdivision" suggests they should be somehow equal. While they may be if that expresses the intended emotion, such passages should be played with phrasing (using timing, dynamics, etc.).
Answer: In a slower tempo, this type of gesture might well be played with a degree of rubato.  In this context, as you say, the intention is just a brilliant flourish, filling one bar of a brisk 2/4.


How to use Library Methods from another cookbook in chef?

Question: I have a case where I have to use a library function from another cookbook, but I am always getting had an error: NoMethodError: undefined method 'func'.
What did I try:
cookbook_1/libraries/lib1.rb:
module namespace_1
  module namespace_2
    def func(var)
       something
    end
  end
end

Chef::Recipe.include(namespace_1::namespace_2)

cookbook_2/metadata.rb:
.
.
depends 'cookbook_1'

cookbook_2/resource/some_resource.rb:
# Try 1
action :setup do
  a = func('abc')
end

#Try 2
extend namespace_1::namespace_2
action :setup do
  a = func('abc')
end

#Try 3
::Chef::Recipe.send(:include, namespace_1::namespace_2)
action :setup do
  a = func('abc')
end

#Try 4
action :setup do
  a = namespace_1::namespace_2::func('abc')
end

#Try 5
Chef::Recipe.include(namespace_1::namespace_2)
action :setup do
  a = namespace_1::namespace_2::func('abc')
end

I am getting the same error, i.e. NoMethodError: undefined method 'func'
How do I solve this?
Comment: corrected it, it was resource @seshadri_c
Comment: The custom action `:setup` should not be in `metadata.rb`. Or is it in a custom resource?
Answer: For Ruby methods written in libraries or custom resources to be available in custom resource actions, we should use action_class block.
Quoting from documentation:

Use the action_class block to make methods available to the actions in the custom resource.

So in your cookbook1, apart from having the library, you should have a custom resource with action_class. I am giving my own example based on yours.
cookbook1: libraries/lib1.rb:
# a custom function to just return the received argument

module Namespace1
  module Namespace2
    def custom_func(arg1)
      arg1
    end
  end
end

cookbook1: resources/some_resource.rb:
property :msg, String, name_property: true

# this is required to make sure functions are available to custom actions
action_class do
  include Namespace1::Namespace2
end

action :setup do
  a = custom_func(new_resource.msg)

  log a do
    level :info
  end
end

Note that I created the custom resource in the same cookbook as the library. Now this custom resource can be used in cookbook2:
cookbook2: metadata.rb
depends 'cookbook1'

cookbook2: recipes/default.rb:
cookbook1_some_resource 'Test custom function'


Check if Postgres json array intersects with another array

Question: Is there a postgres jsonb operator that checks whether any one element of a set of elements is in another set of elements?
for example:
if ['a', 'b', 'c'] in ['c', 'd', 'e'] = True because c in 2nd set
if ['f', 'g', 'h'] in ['g', 'h', 'i'] = True because of g and h in 2nd set

Comment: Prolly answered by https://stackoverflow.com/questions/32812526/postgresql-json-array-intersection-query and https://stackoverflow.com/questions/39480816/postgres-jsonb-array-query-for-non-empty-intersection
Comment: If you are specifying the other side as an array, then this is indeed a duplicate of the question linked to by @IljaEverilä. (Unclear why it being part of a join condition would make a difference, or why MongoDB would be better here, up to you.)
Comment: This would be very easy with a native Postgres array.
Comment: @IljaEverilä I guess the other questions you point to expect one of the sides to be a PostgreSQL array already. It's not clear from the pseudo-code in this question if both arrays come in `jsonb` type, or if one of them already is provided as `text[]`. (I was assuming the former.)
Comment: I've defined the column as type JSON
Comment: @el_pup_le, just to clarify, both column**s**?
Comment: @Bruno You guessed correctly. On the other hand this question is so vague that should've voted "unclear" instead of dupe.
Comment: just one column, I'm specifying the array of strings. I couldn't get it working with where table_a.post_types::json <@ array['foo']
Comment: I should of included in the question that it is for a join condition
Comment: i think its better to use mongodb for this anyway
Answer: You can expand the JSON array using jsonb_array_elements (when using jsonb) or json_array_elements (when using json), or directly to text using jsonb_array_elements_text (when using jsonb) or json_array_elements_text (when using json), and then turn them into a PostgreSQL array using array_agg.
WITH json_data(x, y) AS (
    VALUES ('["a", "b", "c"]'::jsonb, '["c", "d", "e"]'::jsonb),
           ('["a", "b", "c"]'::jsonb, '["g", "h", "i"]'::jsonb)
)
, array_data AS (
    SELECT x, (SELECT array_agg(e) AS arr FROM jsonb_array_elements_text(x) e) AS xarr,
           y, (SELECT array_agg(e) AS arr FROM jsonb_array_elements_text(y) e) AS yarr
    FROM json_data
)
SELECT x, y, xarr, yarr, xarr && yarr AS with_intersection FROM array_data

This produced these results:
        x        |        y        |  xarr   |  yarr   | with_intersection
-----------------+-----------------+---------+---------+-------------------
 ["a", "b", "c"] | ["c", "d", "e"] | {a,b,c} | {c,d,e} | t
 ["a", "b", "c"] | ["g", "h", "i"] | {a,b,c} | {g,h,i} | f
(2 rows)