Hibernate/JPA version concurrency control and DTO/change command patterns

Question: I would like to use @Version for optimistic concurrency control with JPA & Hibernate.
I know how it works in the typical scenario of two parallel transactions. I also know that if I have a CRUD with 1:1 mapping between the form and entity, I can just pass version along as a hidden field and use this to prevent concurrent modifications by users.
What about more interesting cases, which use DTOs or change command patterns? Is it possible to use @Version in this scenario as well, and how?
Let me give you an example.
@Entity
public class MyEntity {
    @Id private int id;
    @Version private int version;
    private String someField;
    private String someOtherField;
    // ...
}

Now let's say two users open the GUI for this, make some modifications and save changes (not at the same time, so the transactions don't overlap).
If I pass the entire entity around, the second transaction will fail:
@Transactional
public void updateMyEntity(MyEntity newState) {
    entityManager.merge(newState);
}

That's good, but I don't like the idea of passing entities everywhere and sometimes would use DTOs, change commands etc.
For simplicity change command is a map, eventually used in a call like this on some service:
@Transactional
public void updateMyEntity(int entityId, int version, Map<String, Object> changes) {
    MyEntity instance = loadEntity(entityId);
    for(String field : changes.keySey()) {
        setWithReflection(instance, field, changes.get(field));
    }
    // version is unused - can I use it somehow?
}

Obviously, if two users open my GUI, both make a change, and execute it one after another, in this case both changes will be applied, and the last one will "win". I would like this scenario to detect concurrent modification as well (the second user should get an exception).
How can I achieve it?
Answer: If I understand your question correctly, all you need is a setter for your private int version field and when you update the entity, you set it in your entity. Of course your DTO must always transport version data. Eventually, you would do also something like:
MyEntity instance = loadEntity(entityId);
entityManager.detach(instance);
for(String field : changes.keySey()) {
    setWithReflection(instance, field, changes.get(field));
}
//set also the version field, if the loop above does not set it
entityManager.merge(instance);


Finding MLE of the common $\mu$ from normal samples with two unknown variances

Question: My problem is as follows,

Find the maximum likelihood estimator, $\mu^{MLE}$ from $(m+n)$ samples, where $X_1, \cdots, X_m \sim N(\mu, \sigma_1^2), Y_1, \cdots, Y_n \sim N(\mu, \sigma_2^2),$

where $\sigma_1^2, \sigma_2^2$ : both unknown.
My attempt
$$
\begin{aligned}
\log L(\mu) = l(\mu) &= \mathrm{constant}-\frac{1}{2} \left[\sum_{i=1}^m\frac{(x_i - \mu)^2}{\sigma_1^2} + \sum_{j=1}^n\frac{(y_j - \mu)^2}{\sigma_2^2}  \right] \\
\frac{\partial l(\mu)}{\partial \mu} &= - \frac{\mu}{\sigma_1^2} \sum_{i=1}^m x_i^2 - \frac{\mu}{\sigma_2^2} \sum_{j=1}^n y_j^2 + \frac{m \bar{x}}{\sigma_1^2} + \frac{n \bar{y}}{\sigma_2^2}
\end{aligned}
$$
This yields $\hat{\mu^{MLE}} =\frac{ m \bar{x}/\sigma_1^2 +n\bar{y}/\sigma_2^2 }{m /\sigma_1^2 +n/\sigma_2^2}$, but the main problem is, I basically don't know the variances. Any help will be appreciated.
Comment: Hi: get rid of the variances right at the beginning by using their respective MLE's.  this way, you just have one unknown parameter to solve for. This is called the profiled ( the term concentrated is sometimes used )  likelihood and is often helpful when maximizing a likelihood when there is more than one parameter. I don' know the specific answer but that should help.
Comment: One other thing: Your answer should come out to some weighted function of the two sets of observations  where the observations are weighted by the inverse of their variance. This way, larger variance observations get less weight.
Comment: I may not be able to derive it regardless, but, to calculate the confidence interval, one needs the expression for the estimate of $\mu$ and it's standard deviation.   So, the MLE expression is needed to obtain it's standard deviation. Soiunds like you derived it so send the exact expression.
Comment: @mlofton Even though I adopt such technique, how can I estimate confidence interval for $\mu$?
Comment: Actually, there are *two* (independent) samples - $(X_1,X_2,\ldots,X_n)$ and $(Y_1,Y_2,\ldots,Y_m)$. The sample *size* is $m+n$.
Answer: Your attempt at the problem is correct so far, but you have only derived the conditional MLE when the variance parameters are known.  To derive the unconditional MLE for the mean parameter, you will need to derive the corresponding equations for the MLEs of the variance parameters and then solve the resulting set of simultaneous equations.  This should give you a unique MLE estimating each of the three parameters in the model.  Let me show you how to do this.

Derivation of the full MLE: For greater clarity, I will denote the variance parameters as $\sigma_x^2$ and $\sigma_y^2$ rather than denoting them with number subscripts.  From your specified model, the log-likelihood for your observed data (ignoring an additive constant) can be written as:
$$\begin{equation} \begin{aligned}
\ell(\mu,\sigma_x,\sigma_y)
&= - m \ln \sigma_x - n \ln \sigma_y -\frac{1}{2} \Bigg[ \sum_{i=1}^m \frac{(x_i - \mu)^2}{\sigma_x^2} + \sum_{i=1}^n \frac{(y_i - \mu)^2}{\sigma_y^2} \Bigg] \\[6pt]
&= - m \ln \sigma_x - n \ln \sigma_y -\frac{1}{2} \Bigg[ \frac{1}{\sigma_x^2} \sum_{i=1}^m (x_i^2 - 2 \mu x_i + \mu^2) + \frac{1}{\sigma_y^2} \sum_{i=1}^n (y_i^2 - 2 \mu y_i + \mu^2) \Bigg] \\[6pt]
&= - m \ln \sigma_x - n \ln \sigma_y -\frac{1}{2} \Bigg( \frac{1}{\sigma_x^2} \sum_{i=1}^m x_i^2 + \frac{1}{\sigma_y^2} \sum_{i=1}^n y_i^2 \Bigg) \\[6pt]
&\quad \quad \quad \quad \quad \quad \quad \text{ } \text{ } + \Bigg( \frac{m\bar{x}}{\sigma_x^2} + \frac{n\bar{y}}{\sigma_y^2} \Bigg) \mu -\frac{1}{2} \Bigg( \frac{m}{\sigma_x^2} + \frac{n}{\sigma_y^2} \Bigg) \mu^2. \\[6pt]
\end{aligned} \end{equation}$$
where $\bar{x} = \sum_{i=1}^m x_i / m$ and $\bar{y} = \sum_{i=1}^n y_i / n$
are the sample means of the parts.  Hence, your score function consists of the following partial derivatives:
$$\begin{equation} \begin{aligned}
\frac{\partial \ell}{\partial \mu}(\mu,\sigma_x,\sigma_y)
&= \Bigg( \frac{m\bar{x}}{\sigma_x^2} + \frac{n\bar{y}}{\sigma_y^2} \Bigg) - \Bigg( \frac{m}{\sigma_x^2} + \frac{n}{\sigma_y^2} \Bigg) \mu, \\[10pt]
\frac{\partial \ell}{\partial \sigma_x}(\mu,\sigma_x,\sigma_y)
&= - \frac{1}{\sigma_x^3} \Bigg( m \sigma_x^2 - \sum_{i=1}^m (x_i - \mu)^2 \Bigg) , \\[10pt]
\frac{\partial \ell}{\partial \sigma_y}(\mu,\sigma_x,\sigma_y)
&= - \frac{1}{\sigma_y^3} \Bigg( n \sigma_y^2 - \sum_{i=1}^n (y_i - \mu)^2 \Bigg) . \\[10pt]
\end{aligned} \end{equation}$$
Setting the partial derivatives to zero yields the following simultaneous equations for the MLE:
$$\hat{\mu} = \frac{m \bar{x} \hat{\sigma}_y^2 + n \bar{y} \hat{\sigma}_x^2}{m \hat{\sigma}_y^2 + n \hat{\sigma}_x^2} \quad \quad \quad \hat{\sigma}_x^2 = \frac{1}{m} \sum_{i=1}^m (x_i - \hat{\mu})^2 \quad \quad \quad \hat{\sigma}_y^2 = \frac{1}{n} \sum_{i=1}^n (y_i - \hat{\mu})^2.$$
These equations give us the conditional MLEs for each of the parameters, when the other parameters are known.  To find the unconditional MLEs for each of our parameters we need to solve these simultaneous equations.  This is a large algebraic exercise, which I will leave to you.

Solving via profile log-likelihood: Rather than solving these simultaneous equations directly, we can go back and substitute the form of the MLEs for the variance parameters back into the original log-likelihood function to obtain the profile log-likelihood:
$$\begin{equation} \begin{aligned}
\ell_*(\mu) \equiv \ell(\mu,\hat{\sigma}_x,\hat{\sigma}_y)
&= - m \ln \hat{\sigma}_x - n \ln \hat{\sigma}_y -\frac{1}{2} \Bigg[ \sum_{i=1}^m \frac{(x_i - \mu)^2}{\hat{\sigma}_x^2} + \sum_{i=1}^n \frac{(y_i - \mu)^2}{\hat{\sigma}_y^2} \Bigg] \\[6pt]
&= - \frac{m}{2} \cdot \ln \Big( \sum_{i=1}^m (x_i - \mu)^2 \Big) - \frac{n}{2} \cdot \ln \Big( \sum_{i=1}^n (y_i - \mu)^2 \Big) + \text{const}. \\[6pt]
\end{aligned} \end{equation}$$
The corresponding score function is:
$$\frac{d\ell_*}{d\mu}(\mu)
= \frac{m^2(\bar{x} - \mu)}{\sum_{i=1}^m (x_i - \mu)^2} + \frac{n^2 (\bar{y} - \mu)}{\sum_{i=1}^n (y_i - \mu)^2}.$$
Setting this function to zero yields the following cubic equation for the critical points:
$$0 = m^2 (\bar{x}-\hat{\mu}) \sum_{i=1}^n (y_i - \hat{\mu})^2 + n^2 (\bar{y}-\hat{\mu}) \sum_{i=1}^m (x_i - \hat{\mu})^2.$$
It should be possible to find a unique maximising critical point that gives the MLE.  (Substitute into the above conditional MLE equations as a check on your working.)  Again, this is a large algebraic exercise that I will leave to you.


Proof for coloring combinations problem. (color vertices of pentagon)

Question: While studying, I found a problem in my book that read: "Each vertex of convex pentagon ABCDE is to be colored with one of seven colors. Each end of every diagonal must have different colors. Find the number of different colorings possible."
The answer key showed the answer as 7770. The answer key also explained that you needed to find the number of ways to color the pentagon with 3, 4, and 5 colors, then add the numbers up. But other than this, no explanation was given. Could someone please give me an explanation to reaching this answer of 7770?
Answer: Jack D'Aurizio's answer works very well, but I see another way to solve it using chromatic polynomials. I understand that this is not the way your book wants you to solve it, but I'm posting it here for future reference:
Draw a graph with five vertices with edges connecting the vertices that cannot receive the same color. (The edges are AC, AD, BD, BE, and CE.) This graph is isomorphic to $C_5$. Then your problem is equivalent to finding the value of the chromatic polynomial of $C_5$ at $x=7$.
We know that the chromatic polynomial of $C_n$ is $(-1)^n(x-1)+(x-1)^n$. Plug in $n=5$ and $x=7$ and you get $(-1)^5(7-1)+(7-1)^5=7770$.
Comment: yay, someone mentioned $C_5$ is isomorphic to its complement.
Answer:
There are $7$ ways to color vertex $A$, split in two cases:
Case $1$: $D$ and $C$ have the same color, there are $6$ ways to pick that color, after this, vertices $E$ and $B$ must be distinct and must not have the color of $D$ and $C$, there are $6\cdot 5$ ways to do this, $7\cdot6\cdot6\cdot5=1260$ total.
Case $2$: $D$ and $C$ have different colors, there are $6\cdot 5$ ways to pick these colors, if $E$ and $D$ have the same color there are $6$ options for $B$ , if $E$ and $D$ have distinct colors there $5$ options for $E$ and then $5$ options for $B$ (so $6+25=31$ total). Hence there are $7\cdot6\cdot5\cdot31=6510$
Hence there are $1260+6510=7770$ total.
Comment: i wish I could ask 2015 me why he drew a pentagram instead of a convex pentagon as stated, perhaps I was possesed
Answer: If a single colour appears more than once, it must appear at two consecutive vertices and nowhere else, hence the possible colourings fulfilling the constraints are:

$T_0$: $ABCDE$;
$T_1$: $AABCD$ and cyclic shifts;
$T_2$: $AABBC$ and cyclic shifts.

There are $7\cdot 6\cdot 5\cdot 4\cdot 3 = 2520$ colourings in $T_0$, $5\cdot(7\cdot 6\cdot 5\cdot 4)=4200$ colourings in $T_1$, $5\cdot(7\cdot 6\cdot 5)=1050$ colourings in $T_3$, hence the answer is given by:
$$ 2520+4200+1050 = \color{red}{7770}.$$


Como é feito o cálculo de matemática do módulo (%) em JavaScript?

Question: Estou a tentar utilizar "engenharia reversa" para entender qual é o cálculo feito pelo módulo (%), mas não estou a conseguir perceber e queria entender e esclarecer-me, para deixar claro esta parte, antes de avançar e começar a fazer exercícios com ele.
Então eu vi este exemplo:

If we do 23 % 10, we divide 23 by 10 which equals 2 with 3 left over. So 23 % 10 evaluates to 3.

More examples:
17 % 5 evaluates to 2
13 % 7 evaluates to 6

Neste primeiro exemplo ele diz que dividimos 23 / 10 que é igual a 2 mas na verdade se fizéssemos esse calculo daria 2,3. Então eu pensei, talvez o que isto quer dizer é:

23 % 10 igual a 2 com 3 de fora, deve significar 23 / 3 igual a 2,3, então esta seria a razão do igual a 2 e 3 de fora?!

Mas depois quando apliquei esta teoria nos exemplos seguintes, esta teoria não se aplicou... Também pensei que pudesse ser a divisão do número 23 por 2 que arredondado seria 10 10 deixando os 3 de fora, mas essa teoria também não teria lógica porque senão seria 23 % 2 em vez de 23 % 10.
Answer: A conta é feita em cima de valores inteiros, exatamente como é na matemática. O algoritmo seria mais ou menos isto:

let x = 23;
let y = 10;
let temp = Math.trunc(x / y); //pega a parte inteira, então o 2,3 vira 2
let modulo = x - temp * y; //pega o dividendo menos o maior valor inteiro divisível
console.log(modulo);
console.log((17 - Math.trunc(17 / 5) * 5));
console.log((13 - Math.trunc(13 / 7) * 7));

Coloquei no GitHub para referência futura.
Comment: Aviso: essa função de truncamento faz parte do ES6 e não está disponível em `Math` em qualquer browser.
Comment: É, bom aviso. nesse caso foi mais para demonstrar o funcionamento, ninguém vai fazer essa fórmula se tem o operador pronto.
Answer: O conceito de "módulo" é semelhante ao de "resto da divisão [inteira]":
Dividendo ou numerador: 23
Divisor ou denominador: 10
Quociente: 2
Resto: 3

Não é exatamente o mesmo conceito (segundo a Wikipedia, as linguagens de programação mais comuns - inclusive JavaScript - implementam o resto da divisão no seu operador %, e não o módulo), mas é próximo o bastante, principalmente quando todos os números envolvidos são inteiros e positivos (como nos seus exemplos). Entretanto, não é sempre o caso:

// Em JavaScript, o dividendo determina o sinal do resto
log(23 % 10);   // 3
log(-23 % 10);  // -3
log(23 % -10);  // 3
log(-23 % -10); // -3

// Se o dividendo não for inteiro, o resto também não é inteiro
log(23.5 % 10); // 3.5

// Se o divisor não for inteiro, não importa, o quociente é que sempre tem de ser inteiro
log(23 % 10.5);   // 2
log(23.5 % 10.5); // 2.5

function log(x) { document.body.innerHTML += "
" + x + "
"; }

Outras linguagens podem seguir convenções diferentes ou possuir restrições diferentes quanto ao tipo dos operandos (não sei dizer se isso é padronizado ou não). Sobre como o cálculo é feito, creio que a resposta do Maniero já explica muito bem (sendo consistente com o operador % em todos os casos citados acima).
Sobre o módulo em si, caso tenha curiosidade, trata-se de uma relação de equivalência entre vários valores segundo um critério bem definido. Não faz sentido perguntar "qual o valor de X módulo Y?", na verdade X é equivalente a infinitos números módulo Y:
23 ≡ 3 ≡ 13 ≡ -7 ≡ -17 ≡ ... (mod 10)

Apenas um deles - o 3 - satisfaz à relação 0 <= 3 < 10, de modo que é comumente considerado o valor "canônico", mas isso só faz sentido (e é útil) quando o módulo (10) é positivo e inteiro.
Answer: Só para complementar
Ambas as respostas do Maniero e do mgibsonbr são bastantes boas e completas, obrigado pelo esclarecimento e informações adicionais que me instruíram mais =) . Enquanto pesquisava mais sobre este assunto, encontrei aqui um exemplo no SO em inglês sobre este mesmo assunto, que achei que seria de valor adicionar aqui à 'documentação'.
Calculando o seguinte exemplo: 16 % 6 = 4
16 / 6 = 2

Depois multiplica-se o quociente (resultado da divisão) por 6 (que é o divisor):
2 * 6 = 12

E por fim subtrai-se o dividendo:
16 - 12 = 4

O resultado dá 4. O número 4 é o resto, que é o mesmo resultado da divisão do modulo que iremos obter, ao fazer 16 % 6 = 4.


How to use Drupal Commerce to extract all the people who purchased a specific product?

Question: I want to create a report (a list) of all the people who purchased a specific product.
I want to use this list for a report to verify purchase when people pickup registration packs etc., so that I can confirm those people when they arrive.
How do I get this in a report format that I can extract from Drupal Commerce?
Answer: Not 100% sure what you mean with "reports on line items" or "a line item report" (consider refining what actually this means). But since the question is tagged with the reporting tag, maybe you may want to consider the Forena module.
It would probably take a bit of time to achieve perfection, but you'd have all of Forena's xHTML-power available to finetune the ultimate result (report), for things such as:

look-and-feel (styling/theming).
maybe add some charts to it also (using selected data about commerce).
saving the ultimate output (report) in formats such as PDF, DOC, etc.
creating eMail campaigns about selected records.
pulling in information stored in other databases related to this report.

For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

Forena documentation - use the link 'Reporting documentation' or visit relative link /reports/help.
Forena samples - use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).
Here is some more info about the other databases in mentioned above:

Using a SQLite instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
Forena comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.
Be aware: I'm a co-maintainer of Forena.
Comment: I'm basically trying to extract current orders with who bought them so I can get a list of names for these orders
Comment: So you are using "Drupal Commerce" with Drupal version 7, right? Are you also using Commerce Reports (cfr https://www.drupal.org/project/commerce_reports)? Consider rephrasing your original question details, by including links to the modules you're using.
Comment: updated question, I want to extract all the people who purchased a specific product.
Answer: Because of the comments in my previous reply (which I believe is still an option to consider), I'd assume that using Commerce Reports should help a lot for creating that list.
Let's hope Matt (maintainer of it) will step in soon to find the (maybe out-of-the-box?) answer ... It'd be interesting to hear from him also to what extend my forena-alternative might make sense also (even if it was only to enhance Commeerce reporting with all sorts of Forena-features ...).


Sum the columnar values accumulated by numerous form submissions

Question: After submitting a form, I receive an indexed array as a SQL-query result and the goal is to sum the column-specific  values with previously collected results.
Example:
// 1st query result
$product_amount = [0.36, 0.14, 0.42]

// 2nd query result
$product_amount = [0.28, 0.12, 0.40]

// n-th query result
$product_amount = [0.16, 0.14, 0.42]

// the desired sum
$total = [0.80, 0.40, 1.24]

How to do it?
The code that creates an array:
function doseCount($num){
    return ($num/100) * intval($_POST['portion']); //getting multiplier for productAmount() function
}

function productAmount(){
    global $link; //connection to the MySQL server
    if(isset($_POST['product'])){
        $product_amount_query = 'SELECT va.vitamin_a, va.vitamin_b1, va.vitamin_b2, va.vitamin_b3, va.vitamin_b5,
                va.vitamin_b6, va.vitamin_bc_b9, va.vitamin_b12, va.vitamin_c, va.vitamin_d, va.vitamin_e, va.biotin, va.vitamin_k,
                va.flavonoids, va.lipoic_acid FROM products_list p, vitamins_amount va WHERE p.id = va.product_id AND p.name = ?';

        $product_amount_stmt = mysqli_prepare($link, $product_amount_query);
        mysqli_stmt_bind_param($product_amount_stmt, "s", $_POST['product']);
        mysqli_stmt_execute($product_amount_stmt);

        $result = mysqli_stmt_get_result($product_amount_stmt);

        $product = mysqli_fetch_array($result, MYSQLI_NUM);

        return $product_final_result = array_map('doseCount', $product);
        mysqli_stmt_close($product_amount_stmt);
        mysqli_close($link);
   }
}

$product_amount = productAmount();

After submit, the $product_amount array gets new data and this new data must be added to the previously accumulated data.
Comment: If I'm correct; you should check this out. This might help you out. http://php.net/manual/en/class.multipleiterator.php
Answer: You could accomplish this by combining array_map and array_sum. If you're using PHP 5.6 or greater, which you should, you could write something like this:
$total = array_map(function (...$vals) {
    return array_sum($vals);
}, ...$results);

Assuming that $results contains all of your $product_amount arrays.
If you want to build $total incrementally instead of passing all query results at once, you can do this:
// Initialize $total array
$total = [0, 0, 0];

// Update $total for each query
$total = array_map(function (...$vals) {
    return array_sum($vals);
}, $total, $product_amount);

Answer: This problem can be solved with proper use of sessions:
if (empty($_SESSION['product_amount'])){
    $_SESSION['product_amount'] = $product_amount;
}else{
    foreach ($_SESSION['product_amount'] as $key => $value) {
        $_SESSION['product_amount'][$key] += $product_amount[$key];
    }
}

Special thanks to Mawia HL for his help.
Answer: I have a number of concerns and suggestions:

Don't use global to gain access to required values.  Pass required data to your function explicitly.
Functions/Methods should not access $_POST directly -- these values should be passed in explicitly so that your code can be more easily unit tested.
Since the calculation with $portion is small and unconditional, I'd probably just build that step directly into the productAmount().
When you have the rows collected, you can make mapped calls of array_sum() on each column of data and even truncate the float values to a certain number of decimals if you wish.
To avoid needing to rely on  session variables, are you able to adjust the user experience so that they only submit one time after they have selected all desired products and portions?
Ideally, it makes sense to fetch ALL rows in a single trip to the database. I'd say that your task could be completely achieved with SQL, but I'm not going to the extent of refactoring your code completely.

Code: (PHPize Demo)
function productAmount($mysqli, $productName, $portion): array
{
    $sql = '
        SELECT va.vitamin_a,
               va.vitamin_b1,
               va.vitamin_b2,
               va.vitamin_b3,
               va.vitamin_b5,
               va.vitamin_b6,
               va.vitamin_bc_b9,
               va.vitamin_b12,
               va.vitamin_c,
               va.vitamin_d,
               va.vitamin_e,
               va.biotin,
               va.vitamin_k,
               va.flavonoids,
               va.lipoic_acid
        FROM products_list   p
        JOIN vitamins_amount va ON p.id = va.product_id
        WHERE p.name = ?
    ';
    $stmt = $mysqli->prepare($sql);
    $stmt->execute([$productName]);
    return array_map(
        fn(int $amount) => ($amount / 100) * $portion,
        $stmt->get_result()->fetch_array(MYSQLI_NUM)
    );
}

$POSTs = [
    ['product' => 'goodinya', 'portion' => 3],
    ['product' => 'healthy1', 'portion' => 2],
    ['product' => 'vitastic', 'portion' => 4],
];

$result = [];
foreach ($POSTs as ['product' => $product, 'portion' => $portion]) {
    $result[] = productAmount($mysqli, $product, $portion);
}

var_export(
    array_map(
        fn(...$rows) => sprintf('%0.2f', array_sum($rows)),
        ...$result
    )
);


Configuring *all* JSHint settings in WebStorm IDE

Question: After a somewhat comprehensive evaluation of IDEs for use in front end development, WebStorm leads the pack I think.
The one missing piece is that we can't configure JSHint the way we need to. The WebStorm preferences GUI provides some options, but not the full set. The GUI only lets you configure 15 of the 30 or so actual available options.
This is a problem because we don't want to change our coding practices just because an IDE doesn't let us configure linting the way we want.
Is there a hacky way to go in and adjust the JSHint library behind the scenes for WebStorm?
Answer: You can configure all the options you'd like in a .jshintrc file located in the root directory of your project. This will be a project-wide setting.
From https://www.jetbrains.com/webstorm/webhelp/jshint.html:

Use config files
Select this check box to have the code verified according to the settings from a configuration file. A configuration file is a JSON file with the extension .jshintrc that specifies which JSHint options should be enabled or disabled. WebStorm will look for a .jshintrc file in the working directory. If the search fails, WebStorm will search in the parent folder, then again in the parent folder. The process is repeated until WebStorm finds a .jshintrc or reaches the project root. To have WebStorm still run verification in this case, specify the default configuration file to use.

I've been using this for a while and it works great. Plus you can commit it to your repo and ensure the entire team follows the same code style. Also a great place to add globals.
Comment: My mistake. I thought that you would be able to edit the .jshintrc files using the IDE's JsHint configuration UI, but it seems you can't. Once you choose "Use Config File" the UI is no longer available and you have to edit the files by hand.
Comment: Doesn't seem to work in WebStorm 11. The .jshintrc file is ignored by JsHint and it isn't updated when changing the JsHint settings in the IDE
Answer: I'm not aware of any hacky way to do it, but you can vote for the existing feature request.
Comment: There's a simple way to do it - use [`.jshintrc`](http://stackoverflow.com/a/21990463/1269037)
Answer: There's a per-file solution that works, but is not ideal. Would prefer an IDE or project-wide fix/hack.
Set JSHint options at the top of your file:
/*jshint laxcomma:true, asi:true */

Comment: This seems to not actually affect the IDE. I am sure JSHint actually does not complain; however, /*jshint expr:true*/ for instance will not prevent complaints from webstorm itself when trying to access a getter.
Comment: It's finicky about spaces, but it does work for me in the lastest, "non-stable" IDE version. Try putting a space before the last "*/"
Comment: @simpleascouldbe thank you! I couldn't get it to work until I made sure there was *no* space before jshint.   Seems like I need a linter for my linter directives!


Dúvida no método de usar o Distinct e Count juntos!

Question: Tenho uma tabela pedidos como a do exemplo abaixo:
 Id | Cliente | Status
 1  | XPTO    | Proposta
 2  | ABCD    | Proposta
 3  | XPTO    | Venceu
 4  | XPTO    | Perdeu

E quero apresentar um resultado assim:
Cliente | Status    | Qtd
XPTO    | Proposta  | 02
XPTO    | Venceu    | 01
ABCD    | Proposta  | 01

Já fiz algumas tentativas e não consegui nada!
O máximo que consegui foi o resultado abaixo no MySQL Workbrench, porém não consegui reproduzir o mesmo no meu código:
Status    | Qtd
Proposta  | 03
Venceu    | 01

Código executado no MySQL Workbrench:
SELECT distinct (status), count(cliente) as qtd_cliente
FROM portal.pedidos
group by status;

E como fazer isso no Laravel? Abaixo estou colocando o código do controller:
class RelatorioController extends Controller
{
    public function index ()
    {
        $relatorio = \App\Pedido::join('clientes', 'cliente', '=', 'nome')
        ->get();

        $cliente = \App\Cliente::lists('nome');

        return view ('relatorio.index',compact('relatorio','cliente'));
    }

    public function status()
    {

//o código abaixo é exatamente onde tenho dúvida, por isto o mesmo não está correto!!! Estas foram tentativas mal sucedidas dos meus testes.

        $status = \App\Pedido::distinct('status')
            ->groupby('cliente')
            ->get();

        return view ('relatorio.status', compact ('status'));
    }
}

Comment: Para dar a pergunta como resolvida é só pressionar o V do lado da resposta certa.
Comment: Por que a pergunta tem a tag Laravel?
Comment: Se tiverem vários clientes que tiverem feito propostas, qual você quer exibir na coluna `Cliente` da resposta?
Comment: Se o problema é do lado do PHP poste o enxerto de código com problema.
Comment: Não vejo a necessidade de usar o distinct  uma vez que você já esta agrupando no seu group by status;
Comment: por acaso, em `4  | XPTO    | Perdeu` não seria `4  | XPTO    | Proposta`?
Answer: Você não precisa do distinct, o group by faz o serviço todo nesse caso:
SELECT cliente, status, count(cliente) as qtd_cliente
FROM portal.pedidos
group by cliente, status;

Se você usar distinct(status) como no seu exemplo, ele vai pegar os status sem repetir, omitindo os clientes.
Comment: @DanielAnselmodeAlmeida Infelizmente não sei mas deve ser bem fácil. Dá uma olhada no documentação do Eloquent Query Builder: https://laravel.com/docs/5.1/queries#ordering-grouping-limit-and-offset
Comment: consegui resolver o meu problema!!!
Segue abaixo o código que funcionou...

`$status = \App\Pedido::select('cliente', 'status', DB::raw('count(cliente) as qtd_cliente'))
        ->groupby('cliente','status')
        ->get();`
Comment: Perfeito!!! Muito obrigado pela ajuda!!!
Você sabe como fazer isso no laravel???
Comment: Estou vendo que você é novo no Stack Overflow. Se você acha que a minha resposta resolveu o seu problema, por favor marque ela como 'Aceita' clicando no check verde dessa forma: http://i.stack.imgur.com/QpogP.png  Valeu! Abraço!


Calculate the sum on the 24 hours time frame in spark dataframe

Question: I want to calculate the sum on date and date+1(24 hours) by filtering the rows based on hours.
1, 2018-05-01 02:12:00,1
1, 2018-05-01 03:16:10,2
1, 2018-05-01 09:12:00,4
1, 2018-05-01 14:18:00,3
1, 2018-05-01 18:32:00,1
1, 2018-05-01 20:12:00,1
1, 2018-05-02 01:22:00,1
1, 2018-05-02 02:12:00,1
1, 2018-05-02 08:30:00,1
1, 2018-05-02 10:12:00,1
1, 2018-05-02 11:32:00,1
1, 2018-05-02 18:12:00,1
1, 2018-05-03 03:12:00,1
1, 2018-05-03 08:22:00,1

Here, example I have filtered the rows from 9AM to 9AM(next date)
Output
1, 2018-05-01,12
1, 2018-05-02,5

Comment: What should result look like?
Comment: @ipj Here the sum should calculate for 24 hours period. sum should be between 09:00:00 to next data 09:00:00 (next date). Example for 2018-05-01, sum is 12
Comment: @swati,  If the answer helped you to resolve issue.. Could you **`upvote and accept`** the answer to close this thread! :-) https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: First define df for reproducibility:
import pandas as pd
import io
data=\
"""
1, 2018-05-01 02:12:00,1
1, 2018-05-01 03:16:10,2
1, 2018-05-01 09:12:00,4
1, 2018-05-01 14:18:00,3
1, 2018-05-01 18:32:00,1
1, 2018-05-01 20:12:00,1
1, 2018-05-02 01:22:00,1
1, 2018-05-02 02:12:00,1
1, 2018-05-02 08:30:00,1
1, 2018-05-02 10:12:00,1
1, 2018-05-02 11:32:00,1
1, 2018-05-02 18:12:00,1
1, 2018-05-03 03:12:00,1
1, 2018-05-03 08:22:00,1
"""

df = pd.read_csv(io.StringIO(data), sep = ',', names = ['id','t', 'n'], parse_dates =['t'])

Then use pd.Grouper with frequency set to 24h and base parameter set to 9, which indicates period is beggining at 9 a.m.:
df.groupby(pd.Grouper(key='t', freq='24h', base=9)).n.sum()

result:
t
2018-04-30 09:00:00     3
2018-05-01 09:00:00    12
2018-05-02 09:00:00     5
Freq: 24H, Name: n, dtype: int64

Comment: Thanks @ipj, do you know how to implement in pyspark or spark-scala
Answer: Use date_format(), date_add(),to_date() and then groupBy,aggregate spark built in functions.
Example:
Spark-Scala:
df.show()
//+---+-------------------+---+
//| id|               date|cnt|
//+---+-------------------+---+
//|  1|2018-05-01 02:12:00|  1|
//|  1|2018-05-01 03:16:10|  2|
//|  1|2018-05-01 09:12:00|  4|
//|  1|2018-05-01 14:18:00|  3|
//|  1|2018-05-01 18:32:00|  1|
//|  1|2018-05-01 20:12:00|  1|
//|  1|2018-05-02 01:22:00|  1|
//|  1|2018-05-02 02:12:00|  1|
//|  1|2018-05-02 08:30:00|  1|
//|  1|2018-05-02 10:12:00|  1|
//|  1|2018-05-02 11:32:00|  1|
//|  1|2018-05-02 18:12:00|  1|
//|  1|2018-05-03 03:12:00|  1|
//|  1|2018-05-03 08:22:00|  1|
//+---+-------------------+---+

df.withColumn("hour",when(date_format(col("date"),"HH").cast("int") >= 9,to_date(col("date"))).otherwise(date_add(to_date(col("date")),-1))).
groupBy("id","hour").
agg(sum("cnt").cast("int").alias("sum")).
show()
//+---+----------+---+
//| id|      hour|sum|
//+---+----------+---+
//|  1|2018-05-01| 12|
//|  1|2018-05-02|  5|
//|  1|2018-04-30|  3|
//+---+----------+---+

Pyspark:
from pyspark.sql.functions import *
from pyspark.sql.types import *
df.withColumn("hour",when(date_format(col("date"),"HH").cast("int") >= 9,to_date(col("date"))).otherwise(date_add(to_date(col("date")),-1))).\
groupBy("id","hour").\
agg(sum("cnt").cast("int").alias("sum")).\
show()
#+---+----------+---+
#| id|      hour|sum|
#+---+----------+---+
#|  1|2018-05-01| 12|
#|  1|2018-05-02|  5|
#|  1|2018-04-30|  3|
#+---+----------+---+

Comment: @swati,  If the answer helped you to resolve issue.. Could you **`upvote and accept`** the answer to close this thread! :-) https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: Just shift the time of your timestamp column by 9 hours and then groupby the date of the adjusted column:
from pyspark.sql.functions import expr, sum as fsum

df
# DataFrame[id: int, dtime: timestamp, cnt: int]

df.groupby("id", expr("date(dtime - interval 9 hours) as ddate")) \
  .agg(fsum("cnt").alias("cnt")) \
  .show()
+---+----------+---+
| id|     ddate|cnt|
+---+----------+---+
|  1|2018-05-01| 12|
|  1|2018-05-02|  5|
|  1|2018-04-30|  3|
+---+----------+---+


Build android apk with apache buildr

Question: Trying to build my android project with Buildr (Apache), but can't find any info on how to do it, and my attempts all fail.
A example buildfile or a "no it dosent work" answer would be good :)
Answer: It is best to ask the Buildr community using the users mailing list, since we don't all check Stack Overflow.
I know Pepijn worked on a plugin some time ago (see this thread) and apparently novoda had developed something as well, but it's not on github anymore.
So the answer is likely no, it doesn't work out of the box. It looks like there are ways to make it work and people to partner with to make it happen if you want.
Thanks for using Buildr!
Answer: We have generated android packages with buildr.

You have to call the aapt code generator before compiling. There is an example in the buildr wiki how to hook up a source generator.
system( @aapt, "package", "-m", "-J", to, "-M", _("AndroidManifest.xml"), "-S", _("res"), "-I", @androidjar, from )
For the apk we have a custom package task, which calls dx, aapt and apkbuildr
system( @aapt, "package", "-f", "-M", ("AndroidManifest.xml"), "-F", apkdir + "/resources.ap", "-S", _("res"), "-I", @androidjar )
system( @apkbuilder, apkdir + "/" + projectname + "signed.apk", "-z", apkdir + "/resources.ap", "-f", apkdir + "/classes.dex", "-d", "-rj", _(:target, "libs"))
system( @apkbuilder, apkdir + "/" + projectname + "unsigned.apk", "-z", apkdir + "/resources.ap", "-f", apkdir + "/classes.dex", "-u", "-rj", _(:target, "libs"))
Comment: Instead of concatenating paths, you want to use File.join to avoid Windows file path issues.

Build android apk with apache buildr


Função em javascript executar em cada elemento

Question: Amigos bom dia.
Tenho o seguinte problema.
Estou desenvolvendo um variável que contem uma lista de produtos.
var produtos = new Array()

produtos[produtos.length]="OUTROS|Catchup|1 sache|10"
produtos[produtos.length]="OUTROS|Mostarda|1 sache|15"
produtos[produtos.length]="OUTROS|Maionese|1 sache|40"
produtos[produtos.length]="OUTROS|Molho branco|1 colh sopa|30"
produtos[produtos.length]="OUTROS|Molho bolonhesa|1 colh sopa|30"
produtos[produtos.length]="OUTROS|Molho madeira|1 colh sopa|10"
produtos[produtos.length]="OUTROS|Molho agridoce|1 colh sopa|30"
produtos[produtos.length]="OUTROS|Molho rose|1 colh sopa|50"
produtos[produtos.length]="OUTROS|Catchup|1 sache|10"
produtos[produtos.length]="OUTROS|Pizza calabresa/frango catupiry e quatro queijos|1 fatia|400"
produtos[produtos.length]="OUTROS|Lasanha|2 colh sopa|160"
produtos[produtos.length]="OUTROS|Cachorro quente|1 unid|420"
produtos[produtos.length]="OUTROS|Misto quente|1 unid|235"
produtos[produtos.length]="OUTROS|Cheese burguer|1 unid|300"

produtos.sort();

function lstprodutos(){
  var nomeprd="";
  var recallprd="";
  for (x=0;x<produtos.length;x++){
    subprod=produtos[x].split('|');
    if (recallprd!=subprod[0]){
      nomeprd+='
'+subprod[0]+'
';
      recallprd=subprod[0];
    }
  }
  document.getElementById('produtos').innerHTML=nomeprd;
  document.getElementById('totalcal').innerHTML=0;
}

function escolha(item){
  var escolhido='';
  for (x=0;x<produtos.length;x++){
    subprod=produtos[x].split('|');
    if (item==subprod[0]){
      escolhido+='

'+subprod[1]+'

'+subprod[2]+'

'+subprod[3]+'

';
    }
  }
  this.document.getElementById('select').innerHTML=escolhido;
}

var item=new Array;

function prato(num,retira){
  var pratofeito="";
  var valocal=0;
  if (!isNaN(num)){
    elem = produtos[num];
    item.push(elem);
  }
  if (!isNaN(retira)){
    item.splice(retira,1)
  }
  for (i=0;i<item.length;i++){
    substring=String(item[i]);
    sub=substring.split('|');
    pratofeito+='
'+sub[1]+', '+sub[2]+'
';
    valocal=valocal+parseInt(sub[3]);
  }
  document.getElementById('escolha').innerHTML=pratofeito;
  document.getElementById('totalcal').innerHTML=valocal;
}

Neste js, ele pega a categoria de produtos, quando clico ele abre a a lista de produtos, ao clicar ele carrega o valor de cada produto em cima, como se eu estivesse selecionando os produtos de uma refeição.
Que funciona conforme o código abaixo:

    Lanche

ESCOLHA UM GRUPO DE ALIMENTOS

        CEREAIS

        HORTALIÇAS

        LEGUMINOSAS

        FRUTAS

        LEITE E DERIVADOS

        CARNE E OVOS

        OLEOS E GORDURAS

        DOCES

        BEBIDAS

        OUTROS

Escolha um alimento

Alimento

Quantidade

Calorias

            <button class="btn_concluido" id="concluido">CONCLUIDO</button>

Porém eu preciso fazer isso para 10 refeições para que o usuário possa escolher os alimentos de cada refeição.
Eu já fiz funcionar o select para selecionar a lista de categoria de produtos, para que ele funcione o click só no elemento que estiver manipulando, porém quando clico na div de baixo que posso escolher a categoria de produto ele carrega só na primeira div. nunca carregar o produto no div do select que estou manipulando.
Sei que o Jquery tem o this que faz essa função.
Comment: amigo, por exemplo café da manhã, vai o codigo, lanche vai o código para ele escolher o alimento, porém se clico no select do grupo de alimentos abre cada um em sua devia refeição, mas se clico para escolher o produto ele só carregar na primeira div, na segunda eu consigo fazer o select, mais ele so carrega a lista na primeira div.
Aqui está um link de como está para você entender melhor.
http://www.beltnutrition.com.br/blog/dieta/index.html
Comment: @jeannsebold não entendo o que este site faz.
Comment: @devgaspa ele faz o calculo do gasto calórico, na parte de Cálculo de ingestão de calorias, eu faço os lançamentos do alimentos, ai temos 7 refeições.

Nela devemos lançar os alimentos consumidos clica-se no "Escolha um Grupo de Alimentos" ao clicar ele seleciona o grupo de alimentos que deseja, bom selecionou os alimentos do café da manhã, vamos para o alimentos do lanche, quando clico no select  "Escolha um Grupo de Alimentos" do lanche, ele abre e se seleciono o grupo de alimento ele carrega o grupo no café manhã, eu quero cada alimentos sejam carregados em cada grupo da refeição.
Comment: Consegui identificar seu problema.
Answer: Antes de tudo, isto está acontecendo porque você declarou vários atributos id com o mesmo valor, isso é altamente não recomendável, é uma má prática e irá causar muitos problemas futuros.
Para resolver isto, uma das alternativas existentes é:
Em cada chamada, exemplo, javascript:escolha('CEREAIS') você irá passar um parâmetro a mais indicando um identificar do grupo atual, por exemplo: javascript:escolha('CEREAIS', 1).
Também irá alterar os elementos
 com id="escolha" para id="escolha1", lembrando que 1 é um identificador referente ao seu grupo.
Na função escolha(); você fará a seguinte alteração:
function escolha(item, idGrupo){
  {...}
  escolhido+='

'+subprod[1]+'

'+subprod[2]+'

'+subprod[3]+'

';
  {...}
  this.document.getElementById('select').innerHTML=escolhido;
}

Assim você irá declarar para a função prato o identificador do grupo ao qual ela pertence.
Na função prato é quase a mesma coisa, você irá fazer estas alterações:
function prato(num,retira,idGrupo){
  {...}
  document.getElementById('escolha'+idGrupo).innerHTML=pratofeito;
  document.getElementById('totalcal').innerHTML=valocal;
}

Quando a função prato for chamada, no momento em que for fazer o innerHTML, o elemento que irá receber o pratofeito será o com id="escolha1"
Uma observação final é de que está forma não é a mais recomendada, existem formas melhores de se fazer isso, bem mais performáticas, consistentes e modulares. Acredito que muitas coisas em seu código possam ser melhoradas, sendo assim, se precisar de qualquer ajuda estaremos aqui.
Comment: Vlw Desvaga.

Funcionou tudo blz, só que ao selecionar os alimentos de cada refeição ele da um bug.
Quando eu adiciono o elementos no café da manhã, ele adiciona tranquilo, mais quando vou para o lanche e adiciono outro alimento ele adiciona os alimentos do café da manhã mais o alimento selecionado no lanche.
Comment: @jeannsebold Estou analisando...
Comment: @jeannsebold vamos para um chat para que eu possa te ajudar melhor, http://chat.stackexchange.com/rooms/32118/devgaspa-ajuda-voce
Comment: blz cara.. estou indo para la, mais eu ano consigo digitar nada
Comment: cara nao consigo conversar contigo nao da pra digitar mensagem
Comment: cara se tiver skype podemos falar por lá que acho que mais facil
Comment: @jeannsebold você precisava de 20 ou mais de reputação para poder digitar no chat, agora dá, caso ainda não consiga, vou informar meu skype para você no chat.


Substitute for exception causes in Java ME

Question: In Java SE it is possible set the cause of an exception using initCause to avoid losing information about the error when catching and rethrowing an exception. Is it possible to do the same in Java ME?
Answer: It is easy to extend the Exception class to achieve this:
public class OperationFailedException extends Exception{
    public Exception cause;
    public OperationFailedException(String string, Exception ex) {
        super(string);
        cause=ex;
    }

    public void printStackTrace(){
        super.printStackTrace();
        System.err.println("\nCaused by:\n");
        cause.printStackTrace();
    }
}

This exception is useful for hiding the underlying exceptions, such as when we want to avoid dependancies or when we want to avoid forcing the caller to deal with too many types of exceptions. I generally also create a version of this class extending RuntimeException for wrapping exception that I want to be unchecked


Every banach manifold is locally arcwise conneted

Question: I found this inside a proof of another fact. I've been trying to find any result to prove it, but I couldn't find any. Does someone know this result or how to prove it? I'm working with a manifold inside $W^{1,p}(\Omega)$, if it can help by any way.
Comment: A Banach manifold is locally arcwise connected since a Banach space is : in a Banach space open balls are arcwise connected.
Answer: Every Banach space has the property that all its open balls are locally convex, hence arcwise-connected. So all Banach manifolds are locally arcwise-connected too.
Comment: I think my confusion was caused by the fact that I was trying to use just the definition (chart, atlas, e.g.). Do u know where I could find some results to help me prove that $M=f^{-1}({1})$ where $f\in C^{1}$ is a Banach Manifold? Inside Sobolev Spaces


$\mathbb{R}^2$ homeomorphic to its quotient by $D^2$ (closed disc).

Question: I have to show what is written in the title. I've used the map $f:\mathbb{R}^2\to\mathbb{R}^2$ defined as $f(x)=\frac{||x||-1}{||x||}x$ for $x\in\mathbb{R}^2\setminus D^2$ and $f(x)=0$ otherwise, which I've proved to be continuous and surjective. I only need to show that this map is closed, but I've got problems to do it.
I tried to do it considering a closed set $C\subset \mathbb{R}^2$ and a sequence $\{y_n\}\subset f(C)$ converging to some $y\in\mathbb{R}^2$. Therefore, I've got a sequence $\{x_n\}\subset C$ such that $f(x_n)=y_n$, but I don't know whether this sequence converges or not, I only know that $f(x_n)\to y=f(x)$.
Comment: Hint: Are the $x_n$ necessarily bounded?
Comment: I don't know. Are they? If they were I could find a convergent subsequence necessarily converging to $x$, and that would solve the problem.
Comment: Well, I guess they have to be bounded because $\frac{||x_n||-1}{||x||}x_n$ converges to $y$.
Comment: The closed unit disk is not homeomorphic to the plane, since one is compact and the other is not.
Comment: You mean you identify $D^2$ to a point?
Comment: @HennoBrandsma yes, that's what I mean.
Answer: You could use the fact that if $y=f(x)$ and $\|x\|>1$,
then $x=\frac{\|y\|+1}{\|y||}y$,
which shows that the restriction of $f$ to $\mathbb{R}\setminus D^2$ has a continuous inverse $\mathbb{R}\setminus\{0\}\to\mathbb{R}\setminus D^2$.
That should take care of the case $y\ne0$.
If $y=0$, your sequence $(x_n)$ will satisfy $\limsup_{n\to\infty} \|x_n\|\le1$,
so you can find a convergent subsequence whose limit $x$ satisfies $\|x\|\le1$, and you're done!


Resize an Image Inside a UIImage before saving in directory

Question: I have this code which gets the image inside my UIImage (connected with IB called 'c1_1') and should save in my directory folder:
IBOutlet UIImageView *c1_1;

if (c1_1.image != nil)
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/ImagensApp/ImagensClientes/%@_%@_Cliente.jpg",list[0],abc]];
            NSData* data = UIImageJPEGRepresentation(c1_1.image, 70);
            [data writeToFile:path atomically:YES];
        }

This code works, but I want to resize the image to scale 200x200, how I can do this before saving?
Answer: Scaling an image is just a few lines of code that

creates a memory bitmap
draws the image into that bitmap
and then gets the new image from the bitmap

like this
- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake( 0, 0, newSize.width, newSize.height )];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return( result );
}

Comment: Works! and to call I want to put this inside my code  NSData* data = UIImageJPEGRepresentation([self scaleImage:c1_1.image toSize:CGSizeMake(150, 150)], 70);


Can I pop up a dialog box on the IOS Home interface, like AirPods?

Question: I have a BLE device. When the device sends data to the mobile phone, I want to pop up an information box on the iPhone to display the data. It requires that I can still pop up the window in the background like Airpods. Is there any way to achieve this function?
Answer: You could't pop a dialog like AirPods, because It's system private framework! You should use the local notification, then the user can choose to see it or not. Force user to see the dialog on home screen of device isn't recommended by apple. If apple provide the technique, I suppose that it is very likely to be abused!


Properties of Battacharyya distance vs Kullback-Leibler divergence

Question: What properties do these measures have and how can I determine which one is better for a given purpose? What are extreme cases where they differ a lot?
Comment: What is this "given purpose"?
Comment: @mbq: This here, for example: http://www.lscp.net/persons/peperkamp/Peperkamp_Le_Calvez_Nadal_Dupoux_%282006%29_The_acquisition_of_allophonic_rules.pdf (i.e. probability distributions for speech sounds in context of other adjacent sounds) ... but my question aims for a general answer of what I have to take into account when I rate each measure's applicability for any use case.
Answer: First properties are explained competently here  and
there.
Which one is better suited to a given purpose will depend on said given purpose so you might think about rephrasing this part of your question.
Comment: Dumbfounded by this comment. This is priceless and should be kept for posterity: "Actually, the first and foremost reason [for me to ask this  question] was to get some reputation to be able to answer a question on meta".--Felix Dombek, January 31st, 2011.
Comment: I understand that if more points were needed, you would have asked several other fake questions. Is this what you mean?
Comment: @Didier, I feel rephrasing this part of the question will be the hardes part of the job, maybe the question is asking for pairs of (purposes,best distance). But you are right, maybe @Felix could tell us more about why he is asking his question.
Comment: Actually, the first and foremost reason was to get some reputation to be able to answer a question on meta: http://meta.stats.stackexchange.com/questions/707/could-r-tag-be-displayed-as-a-capital-r . Also, I don't understand much of the wikipedia pages and I have of course read them first. I'm extremely lousy in statistics and maths.
Comment: Good that only five are needed ... I don't understand why they don't use the total rep on all SE sites for some actions =)
Comment: This is not a fake question. I do indeed not understand what the different formulas have as implications, and from my comment for the question, it should be evident that I encountered them in real life. If more points were needed, I would either have just dropped it, or possibly just told someone who answered on a previous question of mine what I wanted to answer on meta and asked him to do it for me. Also, I intended to get the points only from accepting an answer (I already had 3 previously) and not from upvotes, but I guess my question isn't bad after all with 3 upvotes so far.
Comment: Also, you must admit that my answer on meta is pretty useful.
Comment: Felix: I simply read what you wrote, nothing else. Now if you'll excuse me, I will take my leave from here.


RadioButton with Listview.builder

Question: I have radiobutton in my listview builder, listview builder building Cards, when calling the first radio button it changes from all subsequent Cards.
How can I isolate the radio button option for just the chosen card?
<code> Center(
                        child: ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            scrollDirection: Axis.vertical,
                            shrinkWrap: true,
                            itemCount: data != null ? data.length : 0,
                            itemBuilder: (BuildContext context, index) {
                              Map data = snapshot.data[index];
                              //alts.length = 0;
                              if (data['alts'] != null) {
                                alts = json.decode(data['alts']);
                                alts.forEach((element) {});
                              } else
                                return snapshot.data[index]['alts'] =
                                    Column(children: <Widget>[
                                  Container(
                                    padding:
                                        EdgeInsets.fromLTRB(10, 20, 10, 0),
                                    child: Card(
                                                child: Container(
                                                    padding:
                                                        EdgeInsets.only(
                                                            left: 0,
                                                            right: 25,
                                                            bottom: 15),
                                                    child: Row(
                                                      //  crossAxisAlignment:
                                                      //CrossAxisAlignment
                                                      //   .start,
                                                      mainAxisSize:
                                                          MainAxisSize.max,
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceEvenly,
                                                      children: [
                                                        Row(children: [
                                                          Radio(
                                                              value: null,
                                                              groupValue:
                                                                  null,
                                                              onChanged:
                                                                  null),
                                                          Text(
                                                            'Certo',
                                                            style:
                                                                TextStyle(
                                                              color: Colors
                                                                  .black,
                                                              fontSize: 16,
                                                            ),
                                                          )
                                                        ]),
</code>
Comment: Why don't you provide some information about your data? Also, why are giving a null value to all properties of Radio widget? Please read the documentation carefully: https://api.flutter.dev/flutter/material/Radio-class.html
Comment: Radio is null because i haven't created yet anything to setstate...
Comment: "...when calling the first radio button it changes from all subsequent cards" -- That means the "value" property of every radio button is the same, in your case they are  all null. So Radio widget will compare null(value) == null(groupValue) which is true, hence the resulting behavior.
Answer: Try this small addition to your code:
<code>Row(children: [
    Radio(
        key: UniqueKey(),  // add this line
        value: null,
        groupValue: null,
        onChanged: null
    ),
</code>
It provides a unique key for each radio button.

RadioButton with Listview.builder


Check Variable for Blank Spaces

Question: I have a variable called location that users put a URL in. I was able to take that URL and convert it to an HTML link. I found out though if the user puts a link in with a space, where there should be a %20, the HTML link breaks. Here is my code to try and fix any blank spaces but it doesn't seem to be working.
var medias = []
var type = FilePlanForm.Items[i].Fields["Media Location"].Value;
var location = FilePlanForm.Items[i]["Media Location"].Value;
if ((location != null) && (location.indexOf(/\s/g) > -1)) {
  location.replace(/\s/g, "%20");
}

if ((type == null) && (location != null) && (location.length >0)) { medias.push("Medias Type not selected" + " - " + location); }
else if((location != null) && (location.length > 0)) {medias.push(type + " - " + location); }

var type = FilePlanForm.Items[i].Fields["Media Location 2"].Value;
var location = FilePlanForm.Items[i]["Media Location 2"].Value;
if ((location != null) && (location.indexOf(/\s/g) > -1)) {
  location.replace(/\s/g, "%20");
}

if ((type == null) && (location != null) && (location.length >0)) { medias.push("Medias Type not selected" + " - " + location); }
else if((location != null) && (location.length > 0)) {medias.push(type + " - " + location); }

I have also tried using the encodeURI function, but if the user enters the URL correctly and without any spaces, it breaks the URL.
Thanks
Comment: the above duplicate also covers the [URL interface](https://developer.mozilla.org/en-US/docs/Web/API/URL) in this anser: https://stackoverflow.com/a/68210862/13762301
Answer: This is a good use-case for window.URL.
Do:

const url = new URL('https://example.com/correct%20part/incorrect part');
console.log(url.href);
Comment: Hey, thank you! This seems like it will work. It appears to fail though if one of the values is left blank. Might need to add some kind of if statement in there
Comment: @Schmit when what is blank? in my example you explicitly can see that it *does* handle blank parts correctly.

Check Variable for Blank Spaces


Get item name in PayPal payments

Question: I forward users from my website to the PayPal payment page via a simple POST request that contains payment information:
<code><FORM action="https://www.paypal.com/cgi-bin/webscr" method="post">
</code>
This form contains everything that is needed including an hidden element "item" that describes the product to be paid. Amazingly in my PayPal backend I never see the value of this "item" field but only the name of the person who paid.
So: what has to be changed to see the item/product name together with the received payments?
Thanks!
Answer: You should take a look: Paypal variables

item_name
Description of item. If this variable is omitted, buyers enter their
  own name during checkout.

Optional for Buy Now, Donate, Subscribe, Automatic Billing, Installment Plan, and Add to Cart buttons
Not used with Buy Gift Certificate buttons

Hope it helps!
Comment: This is a comment, not an answer
Answer: Elmi, the name of the variable for the name of the object is "item_name".
Hope that helps.
Answer: You should use field name "item_name" instead of "item"

Get item name in PayPal payments


Como recuperar conteúdo de um cookie

Question: Como faço para recuperar o conteúdo de um cookie, esse cookie tem o ID do material que será solicitado e a quantidade, preciso recuperar para inserir no banco. Já procurei muito na internet e ainda não achei como fazer isso.
Segue o codigo de como eu crio o cookie e insiro os valores nele.
<code>    [Authorize]
    public void AddCarrinho(String Qtd, String Id)
    {
        HttpCookie cookie;
        if(Request.Cookies["pedido"] == null)
        {
            cookie = new HttpCookie("pedido");
        }
        else
        {
            cookie = (HttpCookie)Request.Cookies["pedido"];
        }
        cookie.Expires = DateTime.Now.AddHours(1); //cookie expira depois de 1 hora
        cookie.Values.Add(Id, Qtd);
        Response.Cookies.Add(cookie);
    }
</code>
Editado
Segue o codigo de como eu fiz  após a resposta do Cigano Morison e não deu certo.
<code>    public void AddCarrinho(String Id, String Qtd)
    {
        HttpCookie cookie;
        if (Request.Cookies["teste"] == null)
        {
            cookie = new HttpCookie("teste");
        }
        else
        {
            cookie = (HttpCookie)Request.Cookies["teste"];
        }
        cookie.Expires = DateTime.Now.AddHours(1); //cookie expira depois de 1 hora
        cookie.Values.Add(Id, Qtd);
        Response.Cookies.Add(cookie);
    }

    public ActionResult Recuperar()
    {
        Teste t = new Teste();

        List<Teste> lst = new List<Teste>();

        if(Request.Cookies["teste"]["Id"] != null && Request.Cookies["teste"]["Qtd"] != null)
        {
            for(int i = 0; i < Request.Cookies.Count; i++)
            {
                t.ID = Request.Cookies["teste"]["Id"];
                t.Quantidade = Request.Cookies["teste"]["Qtd"];
                lst.Add(t);
            }
        }

        return View(lst);
    }
</code>
Editado
Answer: Um Cookie é um dicionário, logo:
<code>if (Request.Cookies["pedido"][Id] != null)
{
    minhaInformacao = Request.Cookies["pedido"][Id];
}
</code>
Comment: Cigano, eu editei a pergunta e postei o código de como eu fiz, não deu certo, veja se tem alguma coisa errado por favor. Obrigado.
Comment: @AlanAlmeida No momento que você executa `Recuperar`, quando você inspeciona `Request.Cookies`, o que tem dentro dela?
Comment: Quer que eu poste um print da tela pra você ver?
Comment: @AlanAlmeida Pode ser. Eu preciso saber o que tem dentro da variável.
Comment: Esta adicionado, editei a pergunta.
Comment: @AlanAlmeida `AllKeys` não diz nada. Você precisa expandir o enumerável através da propriedade `Result` pra ver o que tem preenchido.
Comment: você se refere a ultima opção que tem o nome de Result View? se for, tem o mesmo resultado [0] "teste"

Como recuperar conteúdo de um cookie


Scraping number of retweets using Beautifulsoup

Question: Hi I am using Beautifulsoup for scraping twitter data and i want to scrape number of retweets for each tweet and my below is my code
import urllib2
from bs4 import BeautifulSoup

url = "https://twitter.com/nokia"
response = urllib2.urlopen(url)
soup = BeautifulSoup(response,"html.parser")
tweets = soup.findAll('li',{"class":'js-stream-item'})
for tweet in tweets:
    if tweet.find('p',{"class":'tweet-text'}):
        tweet_user = tweet.find('span',{"class":'username'}).text
        tweet_text = tweet.find('p',{"class":'tweet-text'}).text.encode('utf8')
        retweets = tweet.find('span',{"class":"ProfileTweet-actionCount"}).text
        print(tweet_user)
        print(tweet_text)
        print(retweets)
    else:
        continue

I am able to get tweet_user and tweet_text but some how not able to get number of retweets can someone explain me how to get number of retweets
Comment: Not an answer, but this could be much easier achieved using the Twitter API!
Comment: yes i know that but api has a rate limit and moreover you can get tweets for not more than 7 days before
Comment: As far as I know you can get the 3 200 last tweets, no matter how old. At least a few weeks ago, last time I tried!
Comment: thanks for your advice
Answer: Although using tweepy is encouraged
Your code with little modifications:
import requests
from bs4 import BeautifulSoup

url = "https://twitter.com/nokia"
response = requests.get(url)
soup = BeautifulSoup(response.text,"lxml")
tweets = soup.findAll('li',{"class":'js-stream-item'})
for tweet in tweets:
    if tweet.find('p',{"class":'tweet-text'}):
        tweet_user = tweet.find('span',{"class":'username'}).text.strip()
        tweet_text = tweet.find('p',{"class":'tweet-text'}).text.encode('utf8').strip()
        replies = tweet.find('span',{"class":"ProfileTweet-actionCount"}).text.strip()
        retweets = tweet.find('span', {"class" : "ProfileTweet-action--retweet"}).text.strip()
        print(tweet_user)
        print(tweet_text)
        print(replies)
        print(retweets)
    else:
        continue


Is extending a list of dictionaries higher performing than iterating over the keys?

Question: When helping my co-worker troubleshoot a problem I saw something I was unaware python did. When compared to other ways of doing this I am curious where the performance and time complexity stacks up and the best approach is for sake of performance.
what my co-worker did that prompted this question:
list_of_keys = []
test_dict = {'foo': 1, 'bar': [1, 2, 3, 4, 5]}
list_of_keys.extend(test_dict)

print(list_of keys)

['foo', 'bar']

vs other examples I have seen:
list_of_keys = []
test_dict = {'foo': 1, 'bar': [1, 2, 3, 4, 5]}
for i in test_dict.keys():
    list_of_keys.append(i)

and
keys = list(test_dict)

which one of these is shown to be the most beneficial and the most pythonic for the sake of simply appending keys. which one yields the best performance?
Comment: Use the `timeit` module to find out..
Comment: @thebjorn another thing i was unaware existed, thanks my dude!
Comment: using on only one iteration, last one seems the fastest, but you should timeit over 1m iterations to get accurate results
Comment: It's worth noting that under the covers, anything you do to make a list out of the dict's keys has to be iterating those keys. The only question is whether you do it explicitly, or wrapped up inside some function or method (which might be implemented in C, and might have some special optimizations you can't easily reproduce).
Comment: "performant" is a noun that means "a performer".
Comment: its worth noting this was discovered as a mistake. this is by no means practically in use. i was simply curious. also now that i know about timeit i dont think i will see myself asking this kind of question in the future. thanks a bunch @thebjorn
Comment: Also, you're asking for a bunch of different—and potentially conflicting—things here. Do you want to know which is fastest, which has the lowest algorithmic complexity, or which is most pythonic? And if it's the first, do you want to know which is fastest for this particular input, or how they stack up across a wide range of inputs?
Answer: As the docs explain, s.extend(t):

extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)

OK, so that isn't very clear as to whether it should be faster or slower than calling append in a loop. But it is a little faster—the looping is happening in C rather than in Python, and it can use some special optimized code for adding onto the list because it knows you're not touching the list at the same time.
More importantly, it's a lot simpler, more readable, and harder to get wrong.

As for starting with an empty list and then extending it (or appending to it), there's no good reason to do that. If you already have a list with some values in it, and want to add the dict keys, then use extend. But if you just want to create a list of the keys, just do list(d).

As for d.keys() vs. d, there's really no difference at all. Whether you iterate over a dict or its dict_keys view, you get the exact same values iterated, even using the exact same dict_keyiterator. The extra call to keys() does make things a tiny bit slower, but that's a fixed cost, not once per element, so unless your dicts are tiny, you won't see any noticeable difference.
So, do whichever one seems more readable in the circumstances. Generally speaking, the only reason you want to loop over d.keys() is when you want to make it clear that you're iterating over a dict's keys, but it isn't obvious from the surrounding code that d is a dict.

Among other things, you also asked about complexity.
All of these solutions have the same (linear) complexity, because they all do the same thing under the covers: for every keys in the dictionary, append it to the end of a list. That's one step per key, and the complexity of each step is amortized constant (because Python lists expand exponentially), so the title time is O(N) where N is the length of the dict.
Comment: as mentioned above this was discovered out of a mistake. he was intending to append the dict but mistakenly used extend. i personally would be iterating over the keys, not making them a new list.
Answer: After @thebjorn mentioned the module. seems that calling extend is fastest
It seems that list() is the most pythonic for sake of readability and cleanliness.
the most beneficial seems dependent on use-case. but more or less doing this is redundant as mentioned in a comment. This was discovered from a mistake and i got curious.
timeit.timeit("for i in {'foo': 1, 'bar': [1, 2, 3, 4, 5]}.keys():[].append(i)", number=1000000)
0.6147394659928977

timeit.timeit("[].extend({'foo': 1, 'bar': [1, 2, 3, 4, 5]})", number=1000000)
0.36140396299015265

timeit.timeit("list({'foo': 1, 'bar': [1, 2, 3, 4, 5]})", number=1000000)
0.4726199270080542

Comment: Which version of Python did you use?
Comment: @sophros Python3


Background fetch request and notifications doesn't work in every situations

Question: In my AppDelegate, I've added a method to do a fetch request on my Core Data, and in some case I'm showing a notification... But I see that there are some deprecated methods. I Tried to do some changes, but:

When I kill my app the background mode does not work
When my app is on foreground, the background mode works, but the notifications don't show up
When I run my app in background, everything is working fine

Here is my code:
The method that I want to run every time (every minute):
func notification(){

    let appDel: AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext
    var messageNotif:String? = nil

    do {

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Leads")
        let predicate = NSPredicate(format: "statutSendLead=%@ OR statutSendSimulation=%@", "0", "0")
        request.predicate = predicate
        let results = try context.fetch(request)

        if results.count > 0 {
            if Reachability.isConnectedToNetwork() == false {

                messageNotif = "Votre demande n'a pas été envoyée, merci de vous connecter à internet."
            } else {

                Reachability.checkUrl(urlString:Configuration.MyVariables.url, finished: { isSuccess in

                    if isSuccess == false {
                        messageNotif = "Notre service d'enregistrement des demandes est temporairement indisponible, un renvoi sera effectué ultérieurement."
                    }
                })
            }
            */

            if (messageNotif != nil) {

                let identifier = self.stringWithUUID()

                if #available(iOS 10.0, *) {
                    let center = UNUserNotificationCenter.current()
                    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in

                        let content = UNMutableNotificationContent()

                        content.body = messageNotif!
                        content.sound = UNNotificationSound.default()
                        // Deliver the notification in five seconds.
                        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
                        let request = UNNotificationRequest.init(identifier: "test", content: content, trigger: trigger)

                        // Schedule the notification.
                        let center = UNUserNotificationCenter.current()

                        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
                        UNUserNotificationCenter.current().add(request) {(error) in
                            if let error = error {
                                print(error)
                            }
                        }
                    }
                } else {
                    let notification = UILocalNotification()
                    notification.alertBody = messageNotif
                    notification.fireDate = NSDate() as Date
                    notification.soundName = UILocalNotificationDefaultSoundName
                    UIApplication.shared.scheduleLocalNotification(notification)
                }
            }
        }

        /* else {
         timerNotification.invalidate()
         } */

    } catch {
        print(error)
    }
}

The other methods:
var window: UIWindow?
var timerUploadData:Timer!
var timerNotification:Timer!
var test:Timer!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UIApplication.shared.setMinimumBackgroundFetchInterval(
        UIApplicationBackgroundFetchIntervalMinimum)

    let userDefaults = UserDefaults.standard

    if userDefaults.object(forKey: "ApplicationUniqueIdentifier") == nil {
        let UUID = Foundation.UUID().uuidString
        userDefaults.set(UUID, forKey: "ApplicationUniqueIdentifier")
        userDefaults.synchronize()
    }

    Thread.sleep(forTimeInterval: 3.0)
    window = UIWindow(frame: UIScreen.main.bounds)
    let containerViewController = ContainerViewController()
    window!.rootViewController = containerViewController
    window!.makeKeyAndVisible()

    if #available(iOS 10.0, *){

        application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        timerNotification = Timer.scheduledTimer(timeInterval: 60 * 1, target: self, selector: #selector(AppDelegate.notification), userInfo: nil, repeats: true)

    }
    else { //If user is not on iOS 10 use the old methods we've been using
        let notificationSettings = UIUserNotificationSettings(
            types: [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound], categories: nil)
        timerNotification = Timer.scheduledTimer(timeInterval: 60 * 1, target: self, selector: "notification", userInfo: nil, repeats: true)
        application.registerUserNotificationSettings(notificationSettings)
    }

    registerPushNotifications()

    return true
}

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    notification()
}

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != UIUserNotificationType() {
        application.registerForRemoteNotifications()
    }
}

func registerPushNotifications() {
    DispatchQueue.main.async {
        let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)
    }
}

func stringWithUUID() -> String {
    let uuidObj = CFUUIDCreate(nil)
    let uuidString = CFUUIDCreateString(nil, uuidObj)!
    return uuidString as String
}

Comment: see this https://stackoverflow.com/questions/17044373/local-notification-in-foreground for your question why notifications are not shown when your app is in foreground (because the app have to show the notification itself)
Comment: Any response for the app terminated situation ?
Comment: Have you read this: https://blog.newrelic.com/2016/01/13/ios9-background-execution/ ?
Comment: Did you ever figure this out? Scheduling notifications from within a background fetch doesn't work. Scheduling notifications work in every other situation. Is Apple trying to say use push notifications or is this a bug?
Comment: Btw, killing the app will also tell the OS not to wake up your app again. You have to let it naturally suspend and push out of memory by itself. You can use the Background Kill test app to try to force it.
Comment: @TruMan1 look here : http://stackoverflow.com/questions/41674040/a-solution-to-retrieve-information-when-theyre-no-internet-connection
Answer: although this is an old question I now got a good answer on a similar problem, see the answer from Rob
This is a possible answer why your background mode does not work when you kill your app and even a hint on how to test this.
The other question is already answered in the comments:

see this stackoverflow.com/questions/17044373/… for your question why notifications are not shown when your app is in foreground (because the app have to show the notification itself) – data cosmos Jan 13 at 10:49


Where is list of theme features in Drupal 8 that can be exposed on the "Settings" page?

Question: In my theme.info.yml file, I can expose features to show up in the settings of my theme. It's documented here: drupal.org theming
<code>features:
  - comment_user_verification
  - comment_user_picture
  - favicon
  - logo
  - node_user_picture
</code>
I tried to google a list of these, but can't find it. Is there some way I can figure out all the options available here, if there's not an explicit list anywhere?
Answer: Here is the answer:
http://cgit.drupalcode.org/drupal/tree/core/config/schema/core.data_types.schema.yml#n172
There needs to be documentation for this. Maybe I'll write it.....


Find the distribution of (X, X+Y) when X and Y have a given joint Normal distribution

Question: Let random variables $X$ and $Y$ be independent Normal with distributions $N(\mu_{1},\sigma_{1}^2)$ and $N(\mu_{2},\sigma_{2}^{2})$. Show that the distribution of $(X,X+Y)$ is bivariate Normal with mean vector $(\mu_{1},\mu_{1}+\mu_{2})$ and covariance matrix
$$ \left( \begin{array}{ccc}
\sigma_{1}^2 & \sigma_{1}^2  \\
\sigma_{1}^2 &\sigma_{1}^2+\sigma_{2}^2  \\
 \end{array} \right).$$
Thanks .
Comment: This question has several aspects: (1) show that $(X,X+Y)$ is Normal, (2) compute the means, and (3) compute the variance-covariance matrix.  For which of these do you need guidance?
Answer:
Is $(X, X+Y)$ normal? Yes! It is a linear combination of independent univariate normal distributions.
Means: the mean of $X$ is $\mu_1$, and the mean of $X+Y$ is the sum of the means because they are independent, so $\mu_1+\mu_2$.
Variance-covariance. The variance of the sum of two independent random variables is the sum of their variance. So, the variance of $(X,X+Y)$ is $(\sigma_1^2, \sigma_1^2+\sigma_2^2)$. Now calculate the covariance:

$$ Cov(X,X+Y) = Cov(X,X)+Cov(X,Y) = \sigma_1^2+0$$
A multidimension normal distribution is defined by its mean and variance-covariance matrix. Therefore,
$$ (X,X+Y)\sim N \left(\left( \begin{array}{c} \mu_1 \\ \mu_1+\mu_2 \end{array}\right),
\left( \begin{array}{ccc}
\sigma_{1}^2 & \sigma_{1}^2  \\
\sigma_{1}^2 &\sigma_{1}^2+\sigma_{2}^2  \\
 \end{array} \right) \right)
$$


Modify django's username policy?

Question: Django default admin authentication module disallows use of the \ char in usernames. How can I make it accept it?
It looks like it's possible to edit contrib/auth/models.py's username field's validator, but that won't do because it requires a change to django's base code.
Answer: You can use custom regex validators and a custom user model in order to achieve this. Be sure to set USERNAME_FIELD and REQUIRED_FIELDS in your model definition and AUTH_USER_MODEL in your settings.
custom_userprofile_app.models.py
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(_('username'), max_length=30, unique=True,
                                help_text=_('Required. 30 characters or fewer.'),
                                validators=[
                                    validators.RegexValidator(r'^(.*)$',
                                                              _('Enter a valid username. '
                                                                'This value may contain any characters', 'invalid'),
                                    validators.MinLengthValidator(5, 'Username must be at least 5 characters'),
                                ],
                                error_messages={
                                    'unique': _("A user with that username already exists."),
                                })
    # The rest of your fields, etc
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email','first_name','last_name']

settings.py
AUTH_USER_MODEL = 'custom_userprofile_app.User'

Answer: You can override django's default User model and then edit the regex validator.
You are just required to create a child class of base user model and then define a setting for that.
Read how to specify custom user model @ django docs

Modify django's username policy?


In the NBA, if your shot gets blocked, does it still reset the shot clock?

Question: I'm just wondering about when specifically the shot clock gets reset, especially in cases where the shooter gets blocked (or packed, as known informally). Is all that matters that a shot was attempted? Or does the ball have to hit the rim/backboard?
Answer: NBA Rule 7 governs the shot clock.  2d describes a legal shot that must occur within the clock period:

2d After gaining possession of the ball, a team must attempt a field
goal before the shot clock expires. To constitute a legal field goal
attempt, the following conditions must be complied with:

The ball must
leave the player's hand prior to the expiration of the shot clock.

After leaving the player's hand(s), the ball must make contact with
the basket ring.

A shot that is blocked or redirected by the defense such that it does not reach the basket rim does not reset the shot clock.


Como aparecer o que eu digitei no input em uma imagem

Question: Olá, gostaria de saber como eu posso fazer o seguinte, eu tenho várias imagens com nomes, e criei um script em js para eu digitar no input e o que eu digitei aparecer embaixo, e dessa vez gostaria que formasse uma imagem.
Exemplo:
Eu escrevo o nome "andre".
Queria que o comando "img" (html), ficasse com o "src" para o link dessa imagem, por exemplo, eu já escreveria o diretório, e só viesse no nome "andre" no meio.
Ex:

Meu script com input:

HTML:
<input id="campo" type="text" onkeyup="mostrarTexto(this.value)"/>

Comment: Não deu para entender muito a pergunta. Você quer renomear a imagem com o que é digitado? Ou chamar a imagem que for igual ao que é digitado?
Comment: Tipo, eu digito no input o nome "andre" e aparece no diretório da imagem como se o nome da imagem fosse andre. Se eu escrever "roberto" vai aparecer a imagem desse roberto. Deu pra entender?
Answer: Seguindo mais ou menos a minha resposta na sua outra pergunta
Você pode utilizar o elemento canvas do HTML5 para criar a imagem ao digitar.

window.escreveNoCanvas = function(mensagem){
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  //função criar a base branca do canvas
  context.fillStyle = "white";
  context.beginPath();
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.fill();

  //aqui eu crio a mensagem
  context.font = '9pt Arial';
  context.fillStyle = 'black';
  context.fillText(mensagem, 0, canvas.height/2);

  //desenha tudo que foi escrito anteriormente no canvas
  context.stroke();
}
<input type="text" onkeyup="escreveNoCanvas(this.value)">
<canvas id="myCanvas"></canvas>

EDIT*
Se for somente alterar o path da imagem você pode fazer simplesmente assim:

window.mudaImagem = function(mensagem){
  var imagem = document.getElementById('imagem');
  imagem.src = "https://www."+mensagem+".com.br/images/srpr/logo11w.png";
}
Digite "google": <input type="text" onkeyup="mudaImagem(this.value)">

Comment: Ah sim, muito obrigado. Resolvido.
Comment: Eu entendi o que você fez, mas não é bem isso. Tipo, eu tenho uma imagem qualquer que o nome dela (em arquivo) é andre.png, e queria que após eu escrever o nome "andre" no input o img src funcionasse. E que tivesse um local para eu colocar o diretório, onde lá teriam o nome de todas os nomes que eu iria colocar no input.
Comment: Caso precise de um exemplo prático, posso editar minha pergunta.
Comment: @fkda editei a resposta, agora, o que você quer dizer com "um local para eu colocar o diretório, onde lá teriam o nome de todas os nomes que eu iria colocar"?
Comment: Eu consegui editar da forma que eu queria, a sua edição. Deu certinho, mas só falta uma coisinha, eu queria que quando a pessoa entrasse já aparecesse uma imagem, aí só se a pessoa mexer no input que mudaria, pra você entender mais, olha aí o que eu queria:
Comment: window.escreveNoCanvas = function(mensagem){
  var imagem = document.getElementById('imagem');
  imagem.src = "http://localhost:8090/howper/media/img/"+mensagem+".png";
}
Comment: no html: `` é só você definir o `src="caminhoDaImagemPadrão.jpg"`


cardview not showing cornerRadius and elevation

Question: I created a card view in a recycler view and my codes work well but the problem now is that the cardview does not show the rounded edges and elevation at runtime but it shows in the design codes. my codes are shown blow
activity_main
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Controller.MainActivity">

    <uk.co.markormesher.android_fab.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:buttonIcon="@drawable/ic_add_group"
        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/groupListView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

my card_view.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
    android:id="@+id/groupCardView"
    android:layout_width="match_parent"
    android:layout_height="128dp"
    android:layout_marginEnd="16dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="24dp"
    app:cardCornerRadius="10dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent">

        <TextView
            android:id="@+id/groupTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:text="Trips"
            android:textAlignment="center"
            android:textSize="30sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>

I do not know what I have done wrong
Comment: set background color to cardview. You set set same color which you are using for the page.
Comment: i found my error. I was setting background color instead of cardbackgroundcolor
Answer: Anyone could encounter this issue and the solution is very simple and caused by a mistake.there's a difference between backgroundColor and cardbackgroundColor. use setcardbackgroundColor and it should work.
Answer: You need to set
android:background="@android:color/transparent"

for main constraint, and set
app:cardBackgroundColor="@color/white"

to cardview, np


Can I query DHCP server for getting mapping of MAC to IP address (I have admin rights)?

Question: I need to know the MAC to IP address mapping stored on DHCP server.
I don't want to use arp cache as that would require me to either broadcast ping (which is not allowed on windows) or ping the all possible ip address of subnet( which takes lot of time).
I am sure that DHCP server stores the mapping of MAC to IP, how can i use that information, to map MAC to IP address?
Answer: In Windows Server 2008 (possibly for 2003 as well, but don't have access to a 2003 DHCP server right now)
Start the DHCP mmc.
The IP leases & mac addresses should be under Scope->Address Leases.
If you want to export them to a file & then  you can right-click on addresses leases and select Export List...

Getting this programatically?
DHCPOBJS.DLL from the Windows 2000 Resource Kit looks promising.
Comment: thanks , that looks promising, let me get check the  dll
Answer: Last time I looked, Advanced IP Scanner was able to provide this info.  It doesn't query DHCP for it (goes out to the network instead), but it is pretty damn fast and will cost you nothing.
Comment: i need to use it in a prgoram advanced ip scanner wont do that
Answer: Are you sure scanning takes a long time? I just scanned a /24 using nmap in just under 4 seconds. Along with scanning and querying the DHCP server, you might also look at querying your switch CAM table(s) or router ARP table(s) via SNMP.
Answer: You can also use the Windows API if you can use a native language like C++.
DHCP Server Management API Functions


Can't establish wss connection [React + ASP.NET Core, SignalR + nginx]

Question: I have React app that talks to Asp.Net core API. Both of them are deployed on Docker on my VM. Nginx is installed and configured to resolve domain names for app (thesis.uno - for react app, api.thesis.uno - for asp.net core api)
I added chat support to my app using SignalR, but when react tries to establish wss connection through api.thesis.uno it fails

When I replace api domain name with VM ip and port, everything seems to function properly, which means that the trouble is in the Nginx configuration.

I tried to google this trouble, but no solution seemed to help me (https://stackoverflow.com/questions/48300288/signalr-in-asp-net-core-behind-nginx, https://stackoverflow.com/questions/12102110/nginx-to-reverse-proxy-websockets-and-enable-ssl-wss)
My nginx config:
<code>client_max_body_size 64M;

upstream backend {
    # enable sticky session based on IP
    ip_hash;

    server localhost:5000;
  }

server {
    root /var/www/thesis.uno/html; # Directly serves anything in the Rails public folder
    index index.html index.htm index.nginx-debian.html;
    server_name thesis.uno www.thesis.uno; # managed by Certbot

    location / {
        proxy_pass http://localhost:5001;
        proxy_set_header Host $host;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/thesis.uno/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/thesis.uno/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.thesis.uno) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = thesis.uno) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80 ;
    server_name thesis.uno www.thesis.uno;
    return 404; # managed by Certbot
}

server {
    server_name api.thesis.uno www.api.thesis.uno;

    # all other requests
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }

    # web socket chat requests
    location /api/chat {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.thesis.uno/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.thesis.uno/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.api.thesis.uno) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = api.thesis.uno) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name api.thesis.uno www.api.thesis.uno;
    return 404; # managed by Certbot
}
</code>
UPDATE:
Turned out nginx has a logs file, seems like nginx can't redirect request properly, gives 404 on request
Answer: Is it possible this is related to needing sticky sessions and what this comment mentions as "random 404s" https://github.com/dotnet/AspNetCore.Docs/issues/10827#issuecomment-631088853


Help with exporting in FL Studio?

Question: In FL Studio, I exported a project on these settings:
<code>Mode: Full song
Tail: Leave Remainder
Type: WAV
WAV bit depth: 32Bit float
Resampling: 512-point sinc
HQ for all plugins: ON
Disable Maximum polyphony: ON
Alias-free TS404: ON
Save slice markers: OFF
Split mixer tracks: ON
Save ACIDized: ON
Trim PDC delay: ON
</code>
After exporting the 1st time, I opened up the mixer WAV files a new FL Studio project to cut out some flaws in the export. (Just using the slice tool, no edits to the actual wave forms were made)
I exported again using the same exact settings as before -without splitting the mixer tracks. This time, the export sounded noticeably more saturated than listening to the song through the DAW.
I did a small comparison. I pulled up the 1st export and the 2nd export into an FL Studio project to compare waveforms, and sure enough, the 2nd export was slightly larger and more... saturated. It seems that exporting the files multiple times destroyed the quality.
So I decided to do a little test. I exported a WAV file on these settings (without splitting mixer tracks). I re-exported it 6 times. Every time I exported the WAV file, the quality got worse.
I have roamed the internet in hope of finding a fix, but I can't find anything other than the settings I am using. I even read FL Studio's documentation on exporting and... nothing. I have also tried using different interpolations (like 24-point as in the F10 Audio settings of FL Studio).
How do I fix this quality issue with the 2nd export?
Comment: Does the master track have any plugin? Is the master track set to unity gain (no increase in volume at all)?
Comment: THANK YOU SO MUCH! I totally forgot about the Fruity Limiter that FL Studio automatically adds to the master of any new project. It was boosting the gain as it does by default! Put your comment in answer form so I can mark it correct? This problem was causing me a lot of stress -thank you! @Archundia
Answer: I totally forgot about the Fruity Limiter that FL Studio automatically adds to the master of any new project. It was boosting the gain as it does by default!
Comment: FL studio only adds the limiter if you open new projects from a template with a limiter.  If you don't want that, open new projects from the "empty" template.

Help with exporting in FL Studio?


cyclic group - automorphism - $f_a(x) = x^a$

Question: Question:
Let G be a cyclic group of order n. For each $a\in\Bbb{Z}$ define $f:G\to G ,f_a(x) = x^a$.
Prove that $f_a$ is an automorphism of G if and only if $a$ is prime to $n$.
I managed to show that if $a$ is prime to $n$ then $f_a$ is automorphism. When I try to prove the reverse, I need to proof that when $f_a$ is an automorphism, (i.e. the kernel is $e$), $a$ is prime to $n$. I managed to show that only when $m=kn$  will $g^{ma}=e=g^{pn}$ (m,p,k are integers). I felt the two $a$ and $n$ must be relatively prime. But I cannot prove it. Can anyone help?
Answer: Consider $kerf$ Let $x\in kerf$ then $x^a=e$.Thus order of $x$ divides $a$.Also order of an element divides order of the group .order of $x$ divides $a$ and  $n$ both .But $gcd(a,n)=1$.Thus order of $x =1$ thus $x=e$.And in a finite group injectivity implies surjectivity and showing homomorphism is easy.Conversely let $G=<g>$ let $d=gcd(a,n)>1$.Then $a/d,n/d$ are integers.$f_a(g^{n/d})=g^{na/d}=e.g^{n/d}\in kerf_a$ since $n>n/d>1 g^{n/d}\neq e$ thus contradiction that $d>1$
Comment: To go the other direction, let $p$ divide $gcd(|G|,a)$, and show that $g^{|G|/p}$ is a nontrivial element of the kernel, where $g$ is a generator.
Comment: Cool. Glad it helped. Learnmore's answer includes the other direction now as well ( although note that $n/d$ could be $1$ if $n$ divides $a$ ). You can just accept this answer.
Comment: That's the direction OP already knows.
Comment: @Callus Your comment really helped me solved this problem. I found setting $p=gcd(|G|,a)$ and prove $g^{|G|/p}$ is a nontrivial element of kernel if $p\neq1$ would be suffice to prove this. Can u answer it desperately so I may select yours as the answer?