Random forest with small number of samples (10)

Question: I have a computer science background but I am trying to learn how to apply ML by solving small problems.
I have been working on this problem for the last couple of days and I cannot find a solution. I have a dataset with just 10 samples (5 belong to class A and 5 to classB) and 30000 features. I can reduce the number of features (~100) and I would like to use random forest algorithm to identify the most important features among those 100.
I split the dataset into train and test set (test_size=0.20, so it is even smaller than the initial one). Unfortunately (and as expected) I have the overfitting problem. I tried to tune the model using different parameters (max_depth, n_estimators, min_samples_leaf, criterion) + GridSearchCV. However, I still get 100% accuracy. Is there anything else I can try?
Thank you in advance for you help
Comment: Since you are working on this as a learning exercise, another comment: a small dataset for model development is a big problem for data-driven methods. So actually you didn't choose a small problem. There are lots & lots of tutorials and examples online; I suggest you start with some of those.
Comment: Your feature to observation ratio is hopeless even if the data were generated from a linear model with no noise when P is 30,000. It's still pretty tough when P is 100.
Answer: Unfortunately, this problem is all but hopeless for a random forest approach. You do not have enough data to do much of anything, let alone a complicated model like you have selected.
If you just want to learn the mechanics of implementing a random forest in software without having to concern yourself with excessive training time due to a large data set, then this is fine, but you should not expect good predictions from your data or an ability to identify important features with any kind of confidence in your identification.
How to know that your machine learning problem is hopeless
The first paragraph and image posted by Gung apply here (unless you just want to work on the software mechanics), even if that was posted in a rather different context.


A question about vector representation in polar coordinates.

Question: Suppose we want to write the vector:
$$\vec{A}=4\hat{x} +3\hat{y}$$
in polar coordinates $(\rho, \phi)$, by making use of the identities:
$$
\hat{x}=\cos\phi\,\hat{\rho} -\sin{\phi}\,\hat{\phi}, \quad \hat{y}=\sin\phi\,\hat{\rho} +\cos{\phi}\,\hat{\phi}
$$
which simply yield:
$$
\vec{A}= \left(4\cos{\phi}+3\sin{\phi}\right)\hat{\rho} + \left(-4\sin{\phi}+3\cos{\phi}\right)\hat{\phi}
$$
Now expressing $\vec{A}$ as above does not make much sense to me because $\vec{A}$'s orientation is fixed so there should appear no free parameter such as the angle $\phi$. If $\phi$ indeed represents the orientation of the given vector then:
$$
\cos\phi=\frac{A_x}{||A||}=\frac{4}{5}, \quad \sin\phi=\frac{A_y}{||A||}=\frac{3}{5}
$$
If I plug these in $\vec{A}$, I end up with:
$$A=5\hat{\rho}$$
By using the same reasoning above, a generic vector's, $\vec{A}=A_x \hat{x} + A_y\hat{y}$, representation in polar coordinates appears to be
$$\vec{A}=||A|| \hat{\rho}, \quad ||A||=\sqrt{A_x^2+A_y^2}$$
But on the other hand, a generic vector in polar coordinates is given in the form:
$$
\vec{A}=A_{\rho}\hat{\rho} + A_{\phi}\hat{\phi}
$$
If my steps of converting $\vec{A}$ from cartesian to polar coordinates is correct, then why does the $\hat{\phi}$ component seems to disappear ?
EDIT
Thank you all for your answers. I need to clear up few more things. In one of the answers below it is stated the representation (although I have seen such notation on the web):
$$
\vec{A}=A_{\rho}\hat{\rho} + A_{\phi}\hat{\phi}
$$
with constant coefficients is wrong. Is this also true for the representation of
say:
$$
\vec{A}=4\hat{x} +3\hat{y} + 2\hat{z}
$$
in cylindrical and spherical coordinates ? If so, then the proper conversion of $\vec{A}$ must read
$$
\vec{A}=5\hat{\rho} + 2\hat{z}, \quad \rho=\sqrt{x^2 + y^2}
$$
in cylindrical coordinates and
$$
\vec{A}=\sqrt{29}\hat{r}, \quad r=\sqrt{x^2+y^2+z^2}
$$
in spherical coordinates. Therefore the representation of a generic vector with arbitrary but constant coefficients:
$$
\vec{A}= A_{\rho} \hat{\rho} + A_{\phi}\hat{\phi} + A_{z}\hat{z}\\
\vec{A}= A_{r} \hat{r} + A_{\phi}\hat{\phi} + A_{\theta}\hat{\theta}
$$
is wrong. Is this conclusion correct ?
Comment: No question is ever dumb!
Comment: You've aligned your polar coordinate frame so that $\hat{\rho}$ is pointing in the same direction as $A$, so that's why there is no $\hat{\phi}$ component.
Comment: Your last conclusion is correct. Given a curvilinear coordinate system $\xi_1,...,\xi_n$ with unit vectors $\boldsymbol{\epsilon}_1,...,\boldsymbol{\epsilon}_n$ a vector will be in general some linear combination of these basis vectors: $$\mathbf{v}=\sum_{i=1}^n f_i(\xi_1,...,\xi_n) \boldsymbol{\epsilon}_i$$ In a lot of coordinate systems, many of these coefficients will be zero - this is precisely what makes them so useful.
Answer: Probably I'm not understanding your notation or your question properly, but if what you want is to express the point $(4,3)$ in the Cartesian plane in polar coordinates, I'll use the identities
$r=\sqrt{x^2+y^2}$ and $\tan(\theta)=\frac{y}{x}$
Substituting your values, the answer will be $\left(5, \arctan\left(\frac{3}{4}\right)\right)$
Answer:
But on the other hand, a generic vector in polar coordinates is given in the form:
$$
\vec{A}=A_{\rho}\hat{\rho} + A_{\phi}\hat{\phi}
$$

The formula
$$\underline{v}=v_r \hat{\underline{r}}+v_\theta \hat{\underline{\theta}}$$
Is wrong. The radius unit vector is defined such that the position vector $\underline{\mathrm{r}}$ can be written as
$$\underline{\mathrm{r}}=r~\hat{\underline{r}}$$
That's what makes polar coordinates so useful. Sometimes we only care about things that point in the direction of the position vector, making the theta component ignorable.
Comment: I have edited the question a bit. Could you take a look at it ?
Answer: Cartesian coordinates have some very convenient properties.
The vector that expresses the distance and direction from point
$P = (p_x,p_y)$ to point $Q = (q_x,q_y)$
is simply $(q_x - p_x)\hat x + (q_y - p_y)\hat y$;
that is, the vector's $x$ coordinate is simply the difference of the two points'
$x$ coordinates, and similarly with $y$ coordinates.
This works exactly the same no matter where you are in the plane.
We don't have this convenience with polar coordinates.
You cannot just take the polar coordinates of $P$ and $Q$,
find the difference in $\rho$ coordinates, and use this as the $\rho$ coordinate of the vector between the points.
It doesn't work for the $\phi$ coordinate either.
Usually when someone uses $\hat\rho$ and $\hat\phi$ as unit vectors like $\hat x$ and $\hat y$, what they are actually doing is (in at least some sense) looking at the grid of the polar coordinate system at some point in the plane and building a Cartesian coordinate system with an origin at that point and axes aligned with the radial and tangential directions.
That's why you can construct a vector with components like
$A_{\rho}\hat{\rho} + A_{\phi}\hat{\phi}$;
it is actually a vector in a locally defined Cartesian coordinate system where $\hat\rho$ is the unit vector pointing along one axis and $\hat\rho$ is the unit vector pointing along the other axis.
It turns out we can define the same locally defined coordinates for any point along the same radial line out from the origin--that is, for all points with a given $\phi.$ But if you take a point whose $\phi$-coordinate is different you have a different local coordinate system.
That's where the "free" $\phi$ in your vector expression comes from.
That "free" $\phi$ is not really free; it is a function of the point on which you decided to construct the locally-defined coordinate system.
It expresses the angle between the $\hat x$-$\hat y$ coordinate axes
and the $\hat\rho$-$\hat\phi$ coordinate axes for those two local Cartesian coordinate systems at that point, which you must know in order to correctly convert the coordinates of a given vector between those two coordinate systems.


Finding the rule of a quadratic graph

Question:
I am trying to find the rule. Insofar:
$y = a(x-b)^2 + c$
Turning point is $ (1,9) $
So $ b = 1 $ and $ c = 9 $
$y = a(-4-1)^2 + 9$
$-16 = a(-4-1)^2 + 9 $
$-25 = a (-4-1)^2 $
$-25 = a (-5)^2 $
$-25 = 25a$
$a = -1$
So;
$ y = -1(x-1)^2 + 9$
$ -x^2 + 8$
However this is wrong the answer is $y = 8 + 2x - x^2 $
Could I please have some help/advice?
Comment: Carefully multiply out the binomial square in $ \ -1 \cdot (x-1)^2 \ + \ 9 \ $ , collect the terms, and you will see that you have a different form of the correct answer... It _does not_ equal $ \ -x^2 \ + \ 8 \ . $
Comment: Yes, it's all right until the last step where you simplify $y=-1(x-1)^2+9$ to $-x^2+8$ -- looks like you dropped the term $2ab$ in $(a+b)^2=a^2+2ab+b^2.$
Comment: I get it now thank you both. It becomes $-(x^2-2x+1)+9 -> -x^2 + 2x + 8$
Answer: Assume the rule is $f(x)=ax^2+bx+c$ for some constant $a,b$ and $c$. Since its graph is passing through points $$(1,9),~~(-4,-16),~~(4,0)$$ so we have $$f(1)=9,~~f(-4)=-16,~~f(4)=0$$ so we get $$a(1)^2+b(1)+c=9\to a+b+c=9\\a(-4)^2+b(-4)+c=-16\to 16a-4b+c=-16\\ a(4)^2+b(4)+c=0\to 16a+4b+c=0$$ Now solve the latter three equations simultaneously to find  $a,b$ and $c$.

Finding the rule of a quadratic graph


Qt QSpinbox: accept only values of stepsize (16)

Question: I want to have a spinbox that allows only value in steps such as 0, 16, 32, ...
The problem is, that with each entered number the valueChanged signal emits and if I check the values for example by rounding to the next number
if (value % incrX != 0)
{
    value = round(value / incrX) * incrX;
    ui->spinBoxX->setValue(value);
    return;
}

This does not work, since I can not enter "12". The first "1" round to 0 and every futher value will result in 0 as well.
Any ideas? I could deaktivate the edit and leave only the up-down buttons. Or I could mark the text red if not valid and mark it normal if the value is valid.
Comment: please provide a [mcve]
Answer: Use QSpinBox::editingFinished, like this:
QSpinBox sb;
sb.setSingleStep(12);
QObject::connect(&sb, &QSpinBox::editingFinished, [&](){
   sb.setValue( sb.value() / sb.singleStep() * sb.singleStep() ) ; });
sb.show();

Or use delegate/validator to show and edit you specific behavior.


c# text to int64 representation

Question: I'm trying to convert the string "Eureka" into its UTF-8 Int64 representation.
I'm trying the following code :
  string message = "Eureka"; // if I use "Eureka\0\0" it works...
  byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);

  // this fails because I have 6 bytes, not 8 (as required for Int64)
  Int64 m = BitConverter.ToInt64(bytes, 0);

  byte[] decodeBites = BitConverter.GetBytes(m);

  string decodeMessage = System.Text.Encoding.UTF8.GetString(decodeBites);

  if (!decodeMessage.Equals(message)) {
    Console.WriteLine("Message mis-match!!!");
  }

Now, because my string is too short, I don't have the right number of bytes and it fails. If I add 2 chars, it works, but then I don't have the desired string in decodeMessage... Pretty sure I need some conversion trick to remove the trailing "0" bytes after the conversion, but none of my attempts work. Any help would be much appreciated!!
UPDATE
The goal is REALLY to have the integer representation of "Euraka", not "Eureka\0\0" then trim at the end.... The goals is to use the RSA-method on the obtained Int64, so at the other end, people won't know they have to trim anything...!
Comment: That isn't ASCII, consider removing that from your question.
Comment: Changed to UTF-8 already...
Comment: If you are going to use `BitConverter.ToInt64` then you have to pad with `0` the bytes array.
Answer: Let's pad the array with 0 (to ensure the array contain of 8 bytes) and trim the string from \0:
string message = "Eureka"; // if I use "Eureka\0\0" it works...

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);

byte[] pad = new byte[bytes.Length < sizeof(Int64) ? sizeof(Int64) - bytes.Length : 0];

// Concat(new byte[...]) - ensure m contains 8 bytes
Int64 m = BitConverter.ToInt64(
  bytes.Concat(pad).ToArray(),
  0);

byte[] decodeBites = BitConverter.GetBytes(m);

// Since we have 8 bytes always, we have to get rid of tail '\0'
string decodeMessage = System.Text.Encoding.UTF8.GetString(decodeBites).TrimEnd('\0');

if (!decodeMessage.Equals(message)) {
  Console.WriteLine("Message mis-match!!!");
}

Edit: Since Int64 has 8 and "Eureka" is encoded in 6 only, will-nilly you have to get rid of 2 zero bytes. If you don't want Trim you can Skip them e.g.
byte[] decodeBites = BitConverter
  .GetBytes(m)
  .TakeWhile(b => b != 0)
  .ToArray();

string decodeMessage = System.Text.Encoding.UTF8.GetString(decodeBites);

Comment: Again, what I am interested in is "what is the int value of bytes" ?? In other words, what is the formulae to convert a `byte[]` to an int value... I'd think something like `sum(256^i*byte[i]`, no??
Comment: Ok, I now got your solution, took me some time - you remove the empty "zero" bytes in the array. Works great, cheers!!

c# text to int64 representation


Unable to store string in a struct

Question: This code is a part of a bigger program. I want to create an array of structs. The struct contains two data types: char and char*, each of which gets an input from the user. I'm a rookie and not able to find my way through this. Please help.
Error generated:  Segmentation Fault 11.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
    char ch;
    char str[20];
}typ;

typ* add(char* str, char ch);

int main(int argc, char const *argv[]){
    typ* arr;
    arr = (typ*)malloc(sizeof(typ));

    char* name;

    name = (char*)malloc(10);
    *(name + 0)= 'c';
    *(name + 1)= 'a';
    *(name + 2)= 'p';
    *(name + 3)= '\0';
    char c = 'k';

    arr = add(name, c);

    printf("%c\n", arr->ch );
    printf("%s\n", arr->str );

    return 0;
}

typ* add(char* str, char ch){
    typ tempo;
    strcpy(str, tempo.str);
    printf("%s\n", str);
    tempo.ch = ch;
    typ* temp;
    *temp = tempo;
    return temp;
}

Comment: Naming a struct type 'typ' is not helpful:(
Comment: OK, rookie.  1st step - indent you code to make it readable, else devs. will just move on to the next question.
Comment: 2nd step - run your program under a debugger.
Comment: This: 'typ* temp; *temp = tempo;' is undefined behaviour because temp is not initialized to point anywhere legal.
Comment: In any case, even if you fixed that issue in add(), you must not return a pointer to a local var.
Comment: [Don't cast the result of `malloc` in C](http://stackoverflow.com/q/605845/995714)
Comment: @LưuVĩnhPhú Why shouldn't I typecast malloc. It always seems to work fine.
Comment: Did you click on the link?
Answer:
You used arr for the allocated memory, but then you assign it to add's return value, the memory got lost at this point, you have a memory leak.
In the add function, you return a pointer to a variable with automatic storage, which does not exists after the function returns. That's why you are getting a segfault.

So I would allocate the struct in the add function, and returns it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
    char ch;
    char str[20];
} Item;

Item* add(char* str, char ch);

int main(int argc, char const *argv[]){
    int i;
    int n = 3; // number of elements in the array
    Item** arr = malloc(n * sizeof(Item*));

    arr[0] = add("cap", 'k');
    arr[1] = add("foo", 'i');
    arr[2] = add("bar", 'j');

    printf("%c\n", arr[0]->ch );
    printf("%s\n", arr[0]->str );

    for (i = 0; i < n; i++)
         free(arr[i]);
    free(arr);
    return 0;
}

Item* add(char* str, char ch) {
    Item *i = malloc(sizeof *i);
    strcpy(i->str, str);
    i->ch = ch;
    return i;
}

Comment: Thanks @fluter. But it works fine even when I allocate memory to `arr`. The only change that i have to do then is `arr[0] = add(name, c);`.
Comment: @DivyanshuSharma that leads to memory leak, as I said.
Comment: @fluter then how can I create the array of structs I originally wanted to? If I consider memory leakage, your code will only help me store one `Item` in  `arr`.
Comment: @hotessy see the change above, now you have an array of pointers to structs, and each element point to a struct that returned by add. Is this what you meant to do?

Unable to store string in a struct


Problema com cores hexadecimais de 8 dígitos - Android

Question: Estou trabalhando em um aplicativo onde estou tentando seguir o guia de design Material do Google. Nessa página, recomenda-se usar a cor preta (#000000) com 87% de opacidade como a cor dos textos principais.
Utilizando um conversor de decimal para hexadecimal, cheguei ao valor de 57 na base hex. Unindo a opacidade desejada com a cor, cheguei que a cor final deveria ser #57000000, porém o resultado foi esse:

Enquanto deveria se parecer com isso:

Minha pergunta é: houve erro de cálculo por minha parte? Não é assim que deve ser calculada a opacidade? O valor da opacidade varia de 0-100 ou de 0-255?
O meu arquivo xml de cores é esse:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="texto">#57000000</color>
    <color name="texto_secundario">#36000000</color>
    <color name="dica">#1A000000</color>
    <color name="divisores">#0C000000</color>

    <color name="laranja">#ffab40</color>
    <color name="laranja_escuro">#ff9100</color>
    <color name="laranja_claro">#ffd180</color>

    <color name="roxo">#673ab7</color>
    <color name="roxo_escuro">#512da8</color>
    <color name="roxo_claro">#d1c4e9</color>
</resources>

Answer:
Tanto as cores quanto as opacidades no "formato web" costumam ser interpretadas de 00 a ff, ou seja, de 0 a 255 em decimal.
Multiplicando 0xFF (255) por 0,87 dá um valor próximo a 0xDD (221), portanto o preto na transparência desejada seria:
   #dd000000

Segue uma tabela básica como referência:
     0% 0x00          0
     5% 0x0D         13
    10% 0x1A         26
    15% 0x26         38
    20% 0x33         51
    25% 0x40         64
    30% 0x4D         77
    35% 0x59         89
    40% 0x66        102
    45% 0x73        115
    50% 0x80        128
    55% 0x8C        140
    60% 0x99        153
    65% 0xA6        166
    70% 0xB3        179
    75% 0xBF        191
    80% 0xCC        204
    85% 0xD9        217
    90% 0xE6        230
    95% 0xF2        242
   100% 0xFF        255

E aqui, os valores desejados no enunciado:
    12% 0x1e         30
    26% 0x42         66
    54% 0x89        137
    87% 0xDD        221

Comment: @RenanLazarotto acrescentei a tabela dos valores de transparência que você mencionou no enunciado.
Comment: Obrigado pela resposta rápida! Pelo visto foi apenas um erro de cálculo meu. Não pensei na possibilidade de o intervalo ser de 255 valores, ao invés de 100 como havia considerado.
Comment: Novamente, obrigado! Vou salvar essa lista para referência futura.


CSS Media Queries (várias declarações seguidas)

Question: Olá, quero saber se é possível obter um solução mais limpa e mais compacta do seguinte CSS.
    @media screen and (min-width: 630px) {
        .tab ul.login{
            right: 29%;
        }
    }

    @media screen and (min-width: 760px) {
        .tab ul.login{
            right: 27%;
        }
    }

    @media screen and (min-width: 830px) {
        .tab ul.login{
            right: 30%;
        }
    }

    @media screen and (min-width: 990px) {
        .tab ul.login{
            right: 21%;
        }
    }

    @media screen and (min-width: 1030px) {
        .tab ul.login{
            right: 24%;
        }
    }

    @media screen and (min-width: 1160px) {
        .tab ul.login{
            right: 25%;
        }
    }

    @media screen and (min-width: 1200px) {
        .tab ul.login{
            right: 19%;
        }
    }

    @media screen and (min-width: 1300px) {
        .tab ul.login{
            right: 21%;
        }
    }

    @media screen and (min-width: 1400px) {
        .tab ul.login{
            right: 24.5%;
        }
    }

    @media screen and (min-width: 1560px) {
        .tab ul.login{
            right: 1%;
        }
    }

@media screen and (min-width: 1760px) {
    .tab ul.login{
        right: 7%;
    }
}

Answer: Não existe uma regra padrão, e essa resposta pode até ser baseada em opinião.
Mas você pode separar em arquivos diferentes e utilizar a regra da media no atributo media da tag link:
<link href="style-min-default.css" type="text/css" rel="stylesheet" />
<link href="style-min-630.css" media="screen and (min-width: 630px)" type="text/css" rel="stylesheet" />
<link href="style-min-760.css" media="screen and (min-width: 760px)" type="text/css" rel="stylesheet" />
<link href="style-min-830.css" media="screen and (min-width: 830px)" type="text/css" rel="stylesheet" />
<link href="style-min-990.css" media="screen and (min-width: 990px)" type="text/css" rel="stylesheet" />
<link href="style-min-1030.css" media="screen and (min-width: 1030px)" type="text/css" rel="stylesheet" />
<link href="style-min-1160.css" media="screen and (min-width: 1160px)" type="text/css" rel="stylesheet" />
<link href="style-min-1200.css" media="screen and (min-width: 1200px)" type="text/css" rel="stylesheet" />
<link href="style-min-1300.css" media="screen and (min-width: 1300px)" type="text/css" rel="stylesheet" />
<link href="style-min-1400.css" media="screen and (min-width: 1400px)" type="text/css" rel="stylesheet" />
<link href="style-min-1560.css" media="screen and (min-width: 1560px)" type="text/css" rel="stylesheet" />
<link href="style-min-1760.css" media="screen and (min-width: 1760px)" type="text/css" rel="stylesheet" />

Arquivos:
// style-min-630.css
.tab ul.login{
  right: 29%;
}

// style-min-760.css
.tab ul.login{
  right: 27%;
}

// style-min-830.css
.tab ul.login{
  right: 30%;
}

// style-min-990.css
.tab ul.login{
  right: 21%;
}

// style-min-1030.css
.tab ul.login{
  right: 24%;
}

// style-min-1160.css
.tab ul.login{
  right: 25%;
}

// style-min-1200.css
.tab ul.login{
  right: 19%;
}

// style-min-1300.css
.tab ul.login{
  right: 21%;
}

// style-min-1400.css
.tab ul.login{
  right: 24.5%;
}

// style-min-1560.css
.tab ul.login{
  right: 1%;
}

// style-min-1760.css
.tab ul.login{
  right: 7%;
}

Lembrando que esse código não está visando performance, para esse propósito o melhor é compactar tudo em um único arquivo minificado.
Com essa estrutura, você tem um ambiente de desenvolvimento organizado, mas pro usuário final fica um pouco pesado, então uma boa solução pra isso seria utilizar um pre-processador como LESS utilizando o plugin clean-css que possibilita mesclar vários arquivos e compacta-los ao mesmo tempo, tendo assim apenas um arquivo CSS:
// style.min.less
@import url("style-min-630.less");
@import url("style-min-760.less");
@import url("style-min-830.less");
@import url("style-min-990.less");
@import url("style-min-1030.less");
@import url("style-min-1160.less");
@import url("style-min-1200.less");
@import url("style-min-1300.less");
@import url("style-min-1400.less");
@import url("style-min-1560.less");
@import url("style-min-1760.less");

Processe o arquivo: (via linha de comando)
lessc style.min.less > style.min.css --clean-css="--s1 --advanced --compatibility=ie8"

E use-o em produção
<link href="style.min.css" type="text/css" rel="stylesheet" />

Comment: Acho que a melhor solução será "minificar" o código mesmo
Comment: @lazyFox a melhor solução mesmo é usar um preprocessador como less e importar todos os arquivos e processa-lo minificando. ;)
Comment: @lazyFox complementei a resposta, assim você pode usar das duas maneiras, separado para o desenvolvimento e compactado para usuário final.


Can I return buffer created in functions?

Question: char * return_buffer()
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "%s", "test");
    return buffer;
}

buffer is created in the function, can I return the buffer directly? after the function returns, the buffer would disappear?
Comment: [You're correct](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). You need to allocate some memory dynamically, or get the user to do that and pass in the buffer to use.
Answer: You are creating a statically allocated buffer, which means that it is being created on the stack. When the function returns, it will give you an address on the stack that is no longer in use. So if you make more function calls, the data it stores will likely corrupt.
It is much better to allocate it to the heap by calling malloc.
Comment: Just note that "statically allocated" in this case means: allocated with a static array size known at compile time. Not to be confused with the keyword `static` and static storage duration.
Answer: You will need to allocate the buffer on heap using malloc.
buffer is a local/automatic variable and is not guaranteed to exist after the function returns.Using any such buffer beyond the function scope will result in Undefined Behavior.
Answer: Yes. This buffer is a local variable using stack and will be released once you exit the function. Use malloc to allocate a dynamic memory buffer.
Answer: In this case, no you cannot. More like you can but you should not do this.
Here the buffer is created on stack which will be reused.
You can return when you allocate with malloc or similar functions.
Answer: This is not possible and may lead to crash. Here the memory is allocated on the stack and once the function returns memory will be freed. If you want to return buffer from a function then you have to allocate memory on the heap. You can use malloc/calloc for this. Read more
Answer: No, you can't return pointers to local variables.
The best way to write such functions is to leave allocation to the caller. The advantages are: 1) the code is independent of the memory allocation method and can be used both with statically and dynamically allocated memory, and 2) keep algorithms and memory allocation separated, so that the algorithms only concern themselves with the main task at hand and don't concern themselves with side-tasks irrelevant to the algorithm itself, such as memory allocation.
This kind of program design is very common (for example it is used by the Windows API).
Example:
void print_buffer (char* buffer, size_t size)
{
  snprintf(buffer, size, "%s", "test");
}


Check if command is executed

Question: I have a problem with my restriction system for commands.
The message 'you don't have permission' will only run once (when you don't have the role). I'm aware that if you don't set a var (in this case checkrole) the code will be executed once however, I don't know how to check when a command is executed.
So I could do something like this:
if  (command === ' ') {
    checkrole = false
}

Code of interest:
if (!message.member.roles.some(r => ["someone"].includes(r.name.toLowerCase())) && checkrole === false) {
    checkrole = true;
    return message.channel.send('Sorry, but you do not have the **permissions** to do that.');
  }

(var checkrole is defined - it begins as false (var checkrole = false;))
Kind regards,
Ruben
Comment: I guess you need to have the checkrole variable for all of your users! unless you only have one. and if you are using this code in the server and want to send a message to the user only once if they are restricted, you can keep the checkrole variable in database for each user!
Answer: Usually if you want to use commands you need a prefix. Once you chose that, you know that the content of the message (Message.content) will start with prefix + command. So you could write it like this:
// Assuming that:
// var prefix = '-'; for example
if (message.content.startsWith(prefix + "mycommand")) {
  checkrole = false;
}

Although this works, there are more efficient ways to use commands, especially if you'll need to use arguments and so on...
Reading this guide might help you: it covers the basics but also more advanced stuff ;)

Check if command is executed


VSS backups cause custom windows service to fail

Question: I've built custom windows services in vb.net that run on a timer and look for files in a remote directory to process.  On a few servers, they fail without any error at the same exact time, around 10:04PM when the VSS service fails.  The service errors look like:
'The process cannot access the file filename.txt because it is being used by another process.'
Sometimes there are no errors but the service hangs.  I am assuming this is the VSS service.  Regardless, there is a huge spike in CPU up to 100% and back down.
 I have logs (ie the file above that cannot be written to) that relay all activity to me, and each process is wrapped in a try..catch which will also report exceptions to logs for me.  Nothing comes of this.  The processes fail in random parts of code, usually in the poll timer and sometimes in the middle of processing without warning.  The service hangs but says it's still running in services.msc.
Has anyone experienced this issue or know of a fix?  I was thinking to make the services multi-threaded so one can check on another in case one thread hangs but am not sure if this would fix the problem.  We have tried giving more resources to the servers and this seems to have helped a bit but did not completely fix the problem.  Some days it overloads, others it doesnt.  Using windows server 2008 x64.
Thanks in advance for you help!
<code>    Public Shared aTimer As New Timers.Timer

    Public Shared Sub SetTimer()
        aTimer.Interval = 60000
        ' Hook up the Elapsed event for the timer.
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
        aTimer.Enabled = True

    End Sub

    ' The event handler for the Timer.Elapsed event.
    Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
        Dim gen = New Service1
        aTimer.Enabled = False
        gen.ProcessEvents() 'This is the main function of the service
        aTimer.Enabled = True
    End Sub
</code>
Answer: Update:
Had never thought of a simple solution like this, but in the Task Manager, I right clicked on the service and set the priority to "Realtime" in hopes that the high CPU load during backups would not affect the service.  So far so good.
This can be done programatically so each time the service restarts it is in higher priority.  This is in my OnStart():
VB.NET:
<code>System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.RealTime
</code>


File Access Error using OleDB to read CSV data

Question: I am trying to use OleDB 4 to read some data in CSV files.  I am using the following code, which I have copied from various sources that indicate it should work....
    protected virtual string ConnectionString
    {
        get
        {
            return string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='text;HDR=Yes;FMT=Delimited'", _path);
        }
    }

    public void ReadData()
    {
                using (OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT [Name] FROM SomeTable", ConnectionString))
                {
                    using (DataTable table = new DataTable())
                    {
                        adapter.Fill(table);
                        foreach (DataRow row in table.Rows)
                        {
                              //Do something with the data
                        }
                    }
                }
     }

I am trying to test the code with a unit test, but I keep getting the following exception on the "adapter.Fill" line:
"The Microsoft Jet database engine cannot open the file ''.  It is already opened exclusively by another user, or you need permission to view its data."
Please can anyone give me some clues to find out what the problem might be?  The file is not opened by another application already.  I have tried using a path under "AppDomain.CurrentDomain.BaseDirectory" as well as just a hard-coded path to a temporary folder, but whatever I try it gives me the same error.
Comment: Have you solved the issue yet?
Answer: In the connection string you must set Data Source to the folder that contains the CSV file, then you have to SELECT * FROM your-file-name.csv.
Here working (and tested) sample with a file located in F:\Temp\dummy.csv:
var dir = @"F:\Temp";
var fn = "dummy.csv";
var cn = new OleDbConnection(
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + dir + "\";Extended Properties='text;HDR=Yes;FMT=Delimited(,)';");
cn.Open();
var cmd = new OleDbCommand("select * from [" + fn + "]", cn);
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    Console.WriteLine(rdr[0] + " " + rdr[1]);
}
cn.Close();


How to set NSLayoutConstraint in Swift?

Question: I want to change some constraints aromatically in different cases.
Declaration of my Constraints coming from the storyboard:
    @IBOutlet weak var topConstraintPostImageView: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

This is my code, where I want to change the constraints:
func updateCellView(post: PostModel) {

    // Wenn Bild mit Text gepostet wird
    if post.imageURL != nil && post.postText != nil {

        topConstraintPostImageView.constant = 10

        // Wenn Text ohne bild gepostet wird
    } else if post.imageURL == nil && post.postText != nil  {

        heightConstraint.constant = 1

        // Wenn Bild ohne Text gepostet wird
    } else if post.imageURL != nil && post.postText == nil {

        topConstraintPostImageView.constant = 0

    }
}

But the constraints still doesn't change.
Here my cellForRowAt func:
    extension DiscoveryViewController: UITableViewDataSource {
    // wie viele Zellen
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return postArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DiscoveryCollectionViewCell", for: indexPath) as! DiscoveryCollectionViewCell

        cell.updateCellView(post: postArray[indexPath.row].post!)
        cell.layoutIfNeeded()
        cell.user = postArray[indexPath.row]
        cell.post = postArray[indexPath.row]
        cell.delegate = self

        return cell
    }
}

Thanks in advance for your help!
Comment: Are you sure that at least one condition is `true`?
Comment: Yes the code is more complex, but I simplified for this question. All datas will be loaded but not the constraints. Do I have to make special settings for the constraints in storyboard?
Answer: Insert in cellForRowAt in the vc
 cell.updateCellView(arr[indexPath.row])////  change arr to your datasource arr inside here set constants
 cell.layoutIfNeeded()
 return cell

at the end of the if statements
Comment: Thanks for your answer. Im inside a tableViewCell, Value of type 'DiscoveryTableViewCell' has no member 'view'´´
Comment: still the same problem but in the `VC``cellRowAt`
`Value of type 'DiscoveryTableViewCell' has no member 'configure'`
Comment: see https://stackoverflow.com/questions/36574052/swift-dynamic-table-cell-height ,
Comment: screenshot the layout of the cell with constraints shown
Comment: every if need a separate else to give the reverse value of constant when the condition doesn't fit , ex if image url exists then constant height say = 20 and if no then zero , do this for all constraints , as cells are dequeued
Answer: Consider calling setNeedsUpdateConstraints() on your view from updateCellView() and then implement:
class MyView: UIView {
  // ...
  override func updateConstraints() {
    super.updateConstraints()
    // This is where you update your constraints including the logic above.
  }
  // ...
}

✳ Better still, consider using UIStackViews to arrange and individually hide or show views you want to show conditionally.

How to set NSLayoutConstraint in Swift?


how to compare int value with GUID value?

Question: I'm writing a website in my project I have used identity and as you know identity used "GUID" type for "id" but I have a problem when I want to fetch information of users in "modal popup" I need to compare "int" value with "GUID" but I can't do it. for example:

if (Model != null && Model.Id > 0) // I got the error (
  Operator '>' cannot be applied to operands of type 'string'
  )

    @model  DataLayer.User

@using (Html.BeginForm("Edit", "users", FormMethod.Post, new { id = "popupForm" }))
{
    if (Model != null && Model.Id > 0)
    {
        @Html.HiddenFor(a => a.Id)
    }

        User Name
        @Html.TextBoxFor(a => a.UserName, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.UserName)

        First Name
        @Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.FirstName)

        Last Name
        @Html.TextBoxFor(a => a.LastName, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.LastName)

        Gender
        @Html.TextBoxFor(a => a.Gender, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Gender)

        Condition
        @Html.TextBoxFor(a => a.IsActive, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.IsActive)

        Email
        @Html.TextBoxFor(a => a.Email, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Email)

        Address
        @Html.TextBoxFor(a => a.Address, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Address)

        PhoneNumber
        @Html.TextBoxFor(a => a.PhoneNumber, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.PhoneNumber)

        <input type="submit" value="Edite" />

}

=======================================
    @*@using DataLayer
    @model IEnumerable<DataLayer.User>*@
@model  IEnumerable<Dentistry.Areas.ViewModels.UserViewModel>

@{
    ViewBag.Title = "مدیریت کاربران";
}

@*
مدیریت کاربران
*@

    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />

        @*  افزودن کاربر جدید *@
          افزودن کاربر جدید

کاربران

                        <input type="text" name="table_search" class="form-control pull-right" placeholder="Search">

                            <button type="submit" class="btn btn-default"></button>

                            UserName
                            FirstName
                            LastName
                            Gender
                            Email
                            Condition
                            Address
                            phonenumber

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

ویرایش کاربران

                 ویرایش کاربر

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

Modal title

                ...

                <button type="button" class="btn btn-success"> Yes</button>
                <button type="button" class="btn btn-default" data-dismiss="modal"> No</button>

Comment: convert string type to int or float and compare.
Comment: If your guid is just plane numbers then try `parseInt(yourguid)`
Comment: why not to compare it with string.empty?
Answer: instead of
Model.Id > 0

use this - as it a Guid Type column.
Model.Id != Guid.Empty


What are the most common ways to "decorate" a melody?

Question: Yes, I know, there are way too many possibilities and it depends on the style of the music... I would be happy with an incomplete list for beginners (like me). Here is what I have so far:

Accompanying triads, very common in fake books, see also How do I make piano chords sound interesting when playing along with popular songs?
Melody played on two notes, with exactly one octave distance
Dyads
Ornaments

What other ways are there to "decorate" a melody?
I expect a list of the most common techniques + links to explanations (if needed), just as above.Do not go into details about the myriad of variations of a particular technique.
Comment: Per http://music.stackexchange.com/faq#dontask I think the whole intent of the question is a bad fit for Stack Exchange, both for the "imagine a whole book" reason, and for the "chatty, open ended" potential. Dozens of us could chip in with potential additions to your list (although the site doesn't appear popular enough now). I do encourage you to create more focussed questions  about the topics you deleted.
Answer: The art of Counterpoint, as studied by composers for centuries, gives exact details on how to correctly ornament any melody. The lists of ornaments cited as point 4 in the question is only a subset of the possibilities given to us by counterpoint.
There are five main species of counterpoint. The treatise by Johann Joseph Fux is today the most common source for an in depth description of counterpoint. In a nutshell, species counterpoint categorizes intervals into consonant (octaves, perfect fifths and fourths, and major and minor thirds and sixths) and dissonant (seconds, sevenths, and tritones). Then, it gives guidelines for the placement of intervals based on the pattern of strong and weak beats.
Note that in all the examples of counterpoint given here (images are from wikipedia), the added melody is the top voice. These same counterpoint rules can apply to any melody that also has an accompanying harmony (as described in point 1 in the question above).

First Species: Also note against note counterpoint. Since all pitches fall on downbeats, all intervals must be consonant.

Second Species: Two notes in the counterpoint voice are set against each note in the given voice. The intervals on the downbeats should be consonant intervals, whereas the second note can be consonant or dissonant. When dissonant, the best choice is either a passing or neighbor note.

Third Species: Four notes against one. This species extends the use of dissonances in second species. The first and third notes of every four-note group should be consonant while the second and fourth may be dissonant.

Fourth Species: Here, notes in the upper voice are suspended over the bar line, often creating a dissonance on the downbeat of the bar. When dissonant, the upper voice must resolve downward to a consonant interval.

Fifth Species: This species combines the methods described in the previous four. The example shows how this species can be used to create well ornamented melodies in a free style.

Species counterpoint can at first seem very limiting, but through its practice, it can be used to create very exciting melodies and counter-melodies. Knowing how and when to use consonance vs. dissonance allows complete control over the design of a melody.
Answer: Ornamentation is the process of adding little "points of interest" to accentuate the drama of the melody.

Passing Tones add a moment of slower "pace" to a melody. Instead of flying, jumping, or teleporting to the destination, this poor schmo has to take each step one at a time.
Grace Notes add a bit of "trajectory" to melody. There's an older style slow grace note which happens on the beat and pushes the real note forward. The newer cut grace notes (sometimes notated with a slash through the stems) happen just before the beat (perhaps with a little push on the real note for a slight "syncopation" effect).
Trills add a bit of "pizazz" (for want of a better term). Think "jazz hands" from IIRC Bring It On 2 (You know you've seen it; ain't foolin' nobody!). Unless explicitly notated funny (like in some Chopin works), the "correct" way to play these is to start on the Upper Note, then down, up-down, up-down.
Mordents add a little "twirl". Like a pirouette. Or a dog turning a few circles before lying down. It emphasizes the arrival at this point.
Slurs are the opposite of passing tones: one note just glides into the next.

Phrasing and Articulation effects can also enhance a melody.

Legato each note "touches" the next for a continuous, unbroken sound.
Staccato each note "pops" out of nowhere and dissolves away to silence before the next.
Tenuto soft of halfway between Legato and Staccato; each note "sings" but with just a little bit of punctuating silence to keep them distinct.
Sforzando is a Forte Staccato out of left field!
Subito or Subito Piano is a sudden quiescence. It can be really spooky.
Answer: Yes, typical ways that cocktail pianists use to decorate the melody include:

using 6ths
using 3rds on top
chromatic connecting tones between key chord tones
adding dominant chord approaches to tonic chords (eg. E7b13 > Am) or pieces of such chords
adding diminished passing chords, or pieces of such chords
"mild" forms of improvisation on basic chord tones and allowed tensions for that chord
using the "allowed" improvisational tones for a chord to target the melody tone
stripping out superfluous melody tones (ie those that do not fall on the downbeat) and replacing them with other tones from the key scale
Comment: You tell a lot true about using chords, but the question is about decoration **melodies**, maybe your answer could be improved be re-ordering the list? Ok, +1, I see, the question text seems a little confused.
Answer: One of the other answers gives a mixture of traditional ornaments like trill and mordent along with "passing tones." It's a nice list, but "passing tones" are only one type of "non-chord tone" (NCT) and I think a fuller list of NCT's should be given:

Passing Tones
Neighbor Note
Suspension
Anticipation
Appoggiatura
Escape tone
Cambiata (or changing tones)

All of these and some others are defined with notated examples at Wikipedia
https://en.wikipedia.org/wiki/Nonchord_tone
Keep in mind that while the terms are from formal music theory, the actual "melodic moves" they describe are used in virtual every musical style including pop and rock.


Is it possible to create a delta VM?

Question: I have a VM of approx. 18GB. Sometimes I need temporally clones of it, so I clone it. The problems are:

It takes a while until it's done.
Sometimes I happen to need dozen of clones and I'm running out of storage.

I wonder if there's a way to create a VM that saves only the delta (difference) since the delployment out of the source machine. That way each new VM's filesize should be 100MB at most, and creating it will be much faster.
I've heard that VMWare View is using this concept. Is such a thing possible for ESXi as well?
I'm using ESXi 4.1 with VSphere 4.1.
Thanks!
Answer: You might want to check this out:
http://communities.vmware.com/docs/DOC-9202
It's a script that allows you to create as many linked clones as you need in ESXi.
Answer: VMware's VDI can do this I believe.  It just takes a base VM, and creates clones of it for every new VM that you need.  Disk space used is minimal.
Comment: Yes is does, but I'm using ESXi and not VDI.

Is it possible to create a delta VM?


How to remove delete link from admin manage fields ui

Question: I have created a new entity type and progamatically added the fields it requires. My issues is that on the Manage Fields UI (the same interfaced used for managing fields for basic pages/articles), in the operations column there is an option to delete the field. How do I remove prevent the delete link from appearing?
I have googled and looked at the FAPI documentation but don't see an option for this. Anyone know how to do this?
Comment: With out of the box drupal you cannot control access specifically to that action. Possibly something exists in a contrib module that would allow you to, otherwise you would need custom code.
Comment: I'm going to go out on a limb here and say you might consider exporting your created Entity to a feature. This way, if anything ever gets "deleted" by accident you can easily revert it with one command using drush.
Answer: this function will do one of two things - remove the link from the screen, or limit it's effect to doing nothing, depending on what you want to accomplish.
This will work on the Body of an Article - you will need to adjust names appropriately for the content type and field names.
Keep in mind however this will not prevent them from accessing the delete functionality using the url: example.com/admin/structure/types/manage/article/fields/body/delete - you would need to either override the menu, use an access restriction module or something like Rules to prevent users from manually deleting the field.
<code>function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'field_ui_field_overview_form' && $form['#bundle'] == 'article')
  {
    unset($form['fields']['body']['delete']);  // remove the link

    $form['fields']['body']['delete']['#href'] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '#';  // make the link have no effect
  }
}
</code>


Animation doesnot work on Display: block to none

Question: I am trying to show or hide the title of sidepanel while collapsing it to width:50%
I am using display: block to display:none;
Somehow I am not able to use the animation on it
Here is the code I am using
.fade-in {
  animation: fade-in 0.5s ease-in-out both;
}
.fade-out {
  animation: fade-out 0.6s ease-in-out both;
}
@keyframes fade-in {
  0% {
    opacity: 1;
    display: block;
  }
  100% {
    opacity: 0;
    display: none;
  }
}
@keyframes fade-out {
  0% {
    opacity: 0;
    display: none;
  }
  100% {
    opacity: 1;
    display: block;
  }
}

Any idea why display is not working
Comment: I'm afraid an animation between `display` conditions is impossible. The only way to implement it is to make another animation that visually hides an element and than really hide an element at finish. In this case `js` is required. If you need such solution, tell me.
Comment: Thanks @voloshin. I did it with typescript.
Answer:

.fade-in {
  animation: fade-in 0.5s ease-in-out both;
  background:black;
  height:200px;
  width:200px;
  margin-bottom:10px;
}
.fade-out {
  animation: fade-out 0.6s ease-in-out both;
  background:red;
  height:200px;
  width:200px;
}
@keyframes fade-in {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
@keyframes fade-out {
  0% {
    opacity: 1;
    display: none;
  }
  100% {
    opacity: 0;
  }
}

Comment: You Can See : https://stackoverflow.com/questions/26607330/css-display-none-and-opacity-animation-with-keyframes-not-working
Comment: This does not help at all. when opacity:0 display:none is not getting applied
Comment: The display property isn't animatable. You can remove it from the keyframes animation with the same result.
Comment: I am using this animation in angular template where I already have collapse animation. when the sidepanel is collapsed, display: none is not working with opacity.   If I don't use opacity and try to make it working with display, I am getting the issue when I am opening my sidepanel back. The content is jumping as display is changed to block from none. I want display:block to be delayed
Comment: Its purely angular
Comment: It seems its in Angular 1. Do u have any reference for Angular 4


File directories question

Question: I've started learning Drupal 8 and I have question about file directories.
Previously on D7 I've set directories like this:
files - /sites/all/files
modules - /sites/all/modules
themes - /sites/all/themes
Usually I don't make multisites, so can I set directories like this for D8?
files - /files
modules - /modules
themes - /themes
Answer: In Drupal 8, /modules and /themes are already in the root for you. Within them, you can also do /contrib and /custom for further organization.
I have never put files in the root, but I suppose you could as long as you ignore it with git.
See this answer for more detail: https://drupal.stackexchange.com/a/84851/57

File directories question


How to find the number of elements between three different sets when there is not a total sum of their elements?

Question: The problem is as follows:

In an institution they offer three language courses one being German,
  the other French and the last one Polish. Four students enrolled in
  the three courses, six students in Polish and German and seven in
  French and Polish. If all students enrolled in Polish also enrolled in
  German or French. How many of the students were in the Polish course?

The existing alternatives in my book are:

9
7
6
5
8

What I tried to do is to build up a Venn diagram as shown below:
$\hspace{3cm}$
But from this point I am stuck as I do not know how to relate the number of students in Polish language since there is not known the total number of elements from all sets together.
Can this problem be solved without needing this information?.
There is one thing regarding how I understood the problem as it mentions seven students enrolled in French or Polish so by interpreting this information I assumed that $P=7$ and $F=7$ therefore the diagram would become into this:
$\hspace{3cm}$
Edit:
By reviewing what it was mentioned in the problem I noticed that earlier assumptions did considered only elements belonging to $P$, $G$ or $F$ but it was not the case, therefore I changed this approach and "calculated" the elements for $G$ and $P$ and $G$ and $F$ alone being them $2$ and $3$ respectively.
This can be seen in the figure below:
$\hspace{3cm}$
But this is how far I went in the problem. How can I take it from here to reach the solution?.
Therefore I'm stuck at this, can somebody help me to go in the right track or what conclusion I have to take to solve this problem?
Comment: Your final attempt is correct.  There is an implicit assumption here that a student who is enrolled in German and Polish may also be enrolled in French and that a student who is enrolled in French and Polish may also be enrolled in German.
Comment: @N.F.Taussig I totally missed the clue regarding the number of students in Polish alone being none as it is mentioned in the problem they also took other courses from this on the problem can be solved. :)
Answer: You know that there is no student who solely studies polish.  So the answer is $6+4+7$.
Edit: as you know that there are $6$ students in G and F altogether.  Now $4$ of them are in all three courses, so there are $2$ left which solely study German and Polish.  Similar, only three student are studying French and Polish solely.  Hence the numbers are $2$, $4$ and $3$ instead of $6$, $4$ and $7$ so the final answer is $2+4+3=9$.
Comment: I've added the existing alternatives which are available on my book and none seems to match with what you say as the answer. So is my book wrong?.
Comment: This solution seems to assume that the problem said "... and seven in French and Polish" -- but what it actually said, according to the OP's quote, was "... and seven in French **or** Polish".
Comment: @Michael Hoppe Maybe can you explain a little bit better?. Which part of my drawing is not correct?. I thought that the intersection between $G$ and $P$ is $6$. How do I know that there are $6$ between $G$ and $F$. To come to that conclution I may had to establish what it is solely on $P$ which it is what it is being asked in the first place. Maybe can you include a Venn diagram?
Answer: Your first Venn diagram is wrong, the second one is correct.  We are told that there are "Four students enrolled in the three courses" so the middle portion where all 3 sets overlap has the number 4. But the "six students in Polish and German" includes those who are enrolled in all 3 courses.  The overlap between Polish and German should have the number 6- 4= 2, not the full 6.  Similarly, the "seven in French and Polish" Includes the 4 who are taking all three.  The overlap of French and Polish only should have the number 7- 4= 3.  We are told that "all students enrolled in Polish also enrolled in German or French" so the number in the Polish only set is 0.  There are a total of 4+ 2+ 3= 9 students taking Polish.
Comment: Is it just me or my computer is not displaying your paragraph correctly. It looks as if you tried to make bold one word but it is not showing it that way. As you mentioned yes it took me a while to notice that error because they did not used the word "only" hence I had to understand that the numbers given included the $4$ so had to subtract from them. The last clue was not very obvious to me but as they said all Polish enrolled also in other courses there was no people who took Polish alone. The rest is as you mentioned. Thanks!
Comment: Yes, I should have used ** rather than [b].  Unfortunately that varies from one board to another.
Answer:
"Four students enrolled in the three courses,"

This is unambiguous.  The students who enrolled in all three classes is $4$.
Venn diagram is so far:

"six students in Polish and German"

This IS ambiguous.
It can be interpretted in 3 ways:
(Most likely):  $6$ students are taking both polish and german.  Some of them might be taking French as well.  The Venn Diagram for that is:

(Less likely but possible): There are $6$ students who are taking both polish and german but are not taking French.  The Venn Diagram for that is:

(Very unlikely):  If you consider all the students who are taking Polish or are taking  German there are $6$ such students.  (This is very bad language usage).  The Venn diagram is:

and seven in French and Polish.

Ditto.
More Diagrams:

If all students enrolled in Polish also enrolled in German or French.

THe means there were no students in polish alone.
In the most likely event we have this final diagram:

In this case we can see the students taking polish is $0+3+4+2 = 9$.  (I am absolutely certain this was the intended answer).
In the less likely event we have this final diagram:

There we can see the students taking polish are $0+7+4+6 = 17$. (I am fairly certain this was not the intended answer).
And in the least likely even we have:

From that we really can't determine anything.  We have $4$ students taking all three so there are there are $2$ other students taking either German or Polish and $3$ other students taking either French or Polish.  If the $2$ students are both taking German and not polish then there are $3$ taking french only and there are only $4$ taking polish.  If one of the other $2$ students is taken polish and the other taken german but not polish, then there are $2$ students taking french but not polish and there are $5$ students taken polish. If both the $2$ other students are both taking polish, then there is $1$ taking french but not polish and there are $6$ taking polish.
(I am absolutely certain this is not the intended answer)
Comment: I also noticed during a closer examination of this problem that there were more interpretations. But as you indicated the intended answer was $9$. The two diagrams were a nice addition.


Como fazer para que o Combo Box faça uma sugestão do que está na lista quando o usuário começa a digitar

Question: Estou trazendo uma lista de cadastro do banco de dados para o combo box e gostaria que quando o usuário começa a escrever, o combo box fassa uma sugestão
Answer: para que o combobox te forneça uma sugestão é bem simples, altere as seguintes propriedades do seu combobox:
<code>  this.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
  this.AutoCompleteSource = AutoCompleteSource.ListItems;
  this.DropDownStyle = ComboBoxStyle.DropDownList;
  this.FlatStyle = FlatStyle.Standard;
</code>
pronto seu combobox irá se comportar da forma que espera.
Comment: Obrigado Samuel pela dica. Deu certo aqui.


Access notes app data

Question: i'm developing a notes app and I want to import all the notes stored in the default ios app into mine.
How should I do this?
Answer: There's no API to do this. 3rd party apps have no access to such data.
Comment: A user can setup their notes to sync through an email account. Perhaps the other app accesses the notes through the email account. Either way, there is no API to even do that and there's no guarantee a user has setup their notes to sync via email.

Access notes app data


When should I create a service or a utility function?

Question: I had this question in mind along all the last week: When I should create a service or an utility function?
In the Drupal Core we have both Services and Utility functions, but I can't find the distinction between them (when I need to create a service or when I need to create an utility function).
I will take as example the Modules Weight module where I have the InternalFunctions class.
<?php

namespace Drupal\modules_weight\Utility;

class InternalFunctions {

  public static function prepareDelta($weight) {
    $delta = 100;

    $weight = (int) $weight;

    if ($weight > $delta) {
      return $weight;
    }

    if ($weight < -100) {
      return $weight * -1;
    }

    return $delta;
  }

  public static function modulesList($force = FALSE) {
    $modules = [];
    $installed_modules = system_get_info('module');

    $config_factory = \Drupal::service('config.factory');

    if ($force) {
      $show_system_modules = TRUE;
    }
    else {
modules.
      $show_system_modules = $config_factory->get('modules_weight.settings')->get('show_system_modules');
    }

    $modules_weight = $config_factory->get('core.extension')->get('module');

    foreach ($installed_modules as $filename => $module_info) {
      if (!isset($module_info['hidden']) && ($show_system_modules || $module_info['package'] != 'Core')) {
        $modules[$filename]['name'] = $module_info['name'];
        $modules[$filename]['description'] = $module_info['description'];
        $modules[$filename]['weight'] = $modules_weight[$filename];
        $modules[$filename]['package'] = $module_info['package'];
      }
    }
    uasort($modules, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);

    return $modules;
  }

}

In this class I have two static functions but they are both utility functions or prepareDelta() is an utility function and modulesList() should be in another class and have a service?
The only difference that I found at this time is that inside the namespace Drupal\Component\Utility (where you will see a lot of utility fucntions) none of them use inside a service and usually a service use another services inside (I don't have review all the services to validate this).
So, when I should create a service or an utility function?
Comment: @NoSssweat But `Unicode` _is_ a Drupal class that contains only static methods! The fact that the core devs chose to implement it as a static class, rather than a service, probably means something don't you think? A utility class doesn't really need to be overwritten, by its nature - it does some things, if those things aren't what you want, you write your own class instead. Remember the sort of things that traditionally live in utility classes are one-shot, "I do this and nothing else" types of methods, that don't need input except a set of parameters
Comment: @Clive `it doesn't really need to be.` One could argue it's the "Drupal way". Also, making it a service makes it easier for other devs to find what you can overwrite.
Comment: Ken Rickard from Slack Drupal #contribute channel says: "I would create a service if you expect other modules (or other developers) to interact with that code. Utility methods are just private shortcuts for yourself."
Comment: That's what I was thinking about Utility methods, but for services sometimes I think that is more a consideration.
Comment: I think a lot of it comes down to what the class does, and what it needs to have made available to it in order to operate. Take the `Unicode` class in core - that's a static utility class, not a service, because it doesn't have any dependencies, and doesn't need to maintain any state. If it required a service dependency, the DI pattern would require it to be converted to a service, and you'd use the singleton (or factory-generated) instance from the container when you needed it. Otherwise you can just `use` the static class it when it makes sense.
Comment: As such, _I would create a service if you expect other modules (or other developers) to interact with that code_ doesn't ring true to me. If that were the case, `Unicode` would be a service by design, and it doesn't really need to be. Don't forget utility classes can just as easily, more easily in some respects, be used by other modules and other code in your own module. But that all depends on your own perspective/experience as a developer, it'll mostly come down to common sense learnt the hard way
Answer:
Ken Rickard from Slack Drupal #contribute channel says: "I would
  create a service if you expect other modules (or other developers) to
  interact with that code. Utility methods are just private shortcuts
  for yourself."

Yes, a cool thing about services is that anyone can overwrite them. So if you want to give other people the ability to customise a particular piece of code.
See Altering existing services, providing dynamic services.
In addition, you should make it a service if you need to do Mock test for PHP Unit testing. See Services and dependency injection in Drupal 8, see Unit testing more complicated Drupal classes.
Q & A:
Service unit test
Writing unit tests for a method that calls static methods from another class
Comment: Yeah it's an interesting one @NoSssweat. IMO it's guided by higher-level principles than Drupal or Symfony. I think you apply good, standard, class design to your code, and then slot the results into whatever framework you're using at the time by whatever method makes sense for that class
Comment: _you should create a service if it's something you see yourself using again in different files of your module_ Why would a service be more useful (or better practice) than having a utility class which is used several times in the same module? (to clarify: I'm not arguing, but there doesn't seem to be any difference in that context specifically. I'd love to hear why you think a service makes more sense)
Comment: @Clive you got me there on that context alone.
Comment: @Clive can you post an answer with your opinions and some references?
Comment: @AdrianCidAlmaguer I did start writing an answer, then about six paragraphs in, I realised to get down what I actually want to say about it would end up being rather a long essay. It's a very big topic :) If I think of a way to write it down succinctly I will do
Comment: @Clive I will appreciate it, this is something that I want to know how should be done in Drupal 8.
Comment: @Clive one think that I notice is that the Utility functions don't have calls to services, is always like this (maybe this is a reason)?
Comment: @AdrianCidAlmaguer Yes, I mentioned that in the comments on the question - if a class doesn't have state (which dependencies arguably are), then it doesn't need to be, some might argue shouldn't, be instantiated. A service is always instantiated, so if you agree with that thinking, the decision can be made just on what the class actually does. Does it need state? No? It's not a service. But it won't always be that black and white, those are general guidelines (and, importantly, my opinion; others may see it differently)
Answer: In general use services. See the following blog post when it is OK to use static utility functions:

So never use static?
Well no, there are valid use cases. One is that if you have a list of
  pre defined items static can help reduce memory since it will be on
  class level and not in any instances.
Other cases are utility methods which do not require outside
  dependencies, for instance a slugify method.
<?php
class Util
{
    public static function slug($string)
    {
        return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $string)));
    }
}

The slug method only does a very well defined behavior. It is easy to
  take the behavior into account in unit tests and I would not be too
  worried when I see this call.
These methods can even be unit tested since they do not require
  initialization.

Source: https://stovepipe.systems/post/avoiding-static-in-your-code
(The amount of static code now in Drupal is because of the transition from procedural D7 code, so don't use Drupal in the current state as example.)

About the example from the question, the rest of the utility class (not shown in the question)
<?php

namespace Drupal\modules_weight\Utility;

/**
 * Provides module internal helper methods.
 *
 * @ingroup utility
 */
class InternalFunctions {

...

  /**
   * Return the modules list ordered by the modules weight.
   *
   * @param bool $force
   *   Force to show the core modules.
   *
   * @return array
   *   The modules list.
   */
  public static function modulesList($force = FALSE) {
    // If we don't force we need to check the configuration variable.
    if (!$force) {
      // Getting the config to know if we should show or not the core modules.
      $force = \Drupal::service('config.factory')->get('modules_weight.settings')->get('show_system_modules');
    }
    // Getting the modules list.
    $modules = \Drupal::service('modules_weight')->getModulesList($force);

    return $modules;
  }

}

calls the module own service in a static wrapper:
\Drupal::service('modules_weight')

This is probably because the utility class is used in legacy procedural code. In OOP code this is not necessary, here you should inject the service directly.
Comment: Thanks for the answer, yesterday I changed a little the module code (because I made some commits) and I create the modules_weight service. I have the service because this can be used by others modules and is now general, you can get all the modules or only the core modules list. But in the module this list can be affected by the value inside the show_system_modules config variable, so I made another function that takes this var and then call the services, but reading your answer it seems that the modulesList function should not be static.
Comment: In this case do you thing that the modulesList function should be inside the service or on another class with a constructor with the dependency injection?
Comment: I think you you can put it in the same service and declare getModulesList() as a protected method.
Comment: but the point is that if somebody wants to use getModuleList() will not be possible and modulesList() have access to a variable that only is important for the module. Maybe adding modulesList() as another method and adding in the description that use a module config variable?
Comment: I would only make one of the two methods public. Perhaps you can set a default value `$force = NULL`, so that you know if someone wants to override the config value with a FALSE.
Comment: Can you take a look to the last modification in the module and give me your opinion? https://www.drupal.org/project/modules_weight/issues/2927548#comment-12365198 if you provide me your drupal.org username I can give you credit solving the issue :-)
Comment: I've made a comment in the issue queue about $force.


Is it a foul for the defender to preemptively slide tackle a potential shot?

Question: Let's say that the striker is closing in to the goal post on the right side.  As a defender, I am running towards the middle of the right post and the striker.  I perform a slide tackle towards the line in anticipation of a shot from the striker.
3 possible scenarios could happen with the slide tackle:

The striker hits the ball and I might take it out of play with my slide tackle
The striker side steps me and continues to the goal
The slide tackle in front of the striker caught him by surprise and he crashes into me with the ball.

Is the above move legitimate in football?  What happens if situation 3 happens, is it a foul?  Is it risky for the striker to get injured?
I'm playing recreational football, so I'm not sure if I should be doing any slide tackle at all even if the striker is far from me.
Comment: If you have to do a slide tackle it means you've messed up somehow (or maybe a teammate has and you're trying to cover).
Answer: Firstly, it would be rare for such a tackle to be performed; it's bad for a defender to commit themselves like that. Especially at a higher level, oppenents will be able to read your actions and trivially side-step your tackle; they're then through on goal, and you won't be able to support your defence in time.
Providing I'm reading your scenario right, then it shouldn't be judged as a foul. You'll get the ball first, it isn't a tackle from behind; so, providing it was otherwise a legitimate slide (feet weren't high, studs weren't showing, it wasn't a lunge, you don't go through the player), I can't see the referee giving a foul for it.
As for the striker getting injured; I doubt it. It won't catch the striker by suprise per-sec, but just late enough so they can't navigate themselves out of the situation with the ball. They'll still see the tackle arriving, and will be able to catch themselves with their arms, roll off the tackle, or even step/ jump over you.
Comment: "it isn't a tackle from behind" - it doesn't matter which direction the player comes from in determining whether it's a foul.
"You'll get the ball first" - this doesn't prevent it from being a foul. If you get the ball then clean up the player, in all likelihood, it's still a foul.
Comment: But as far as I understand it, it is indeed considered more reckless when blindsiding a player. And it's not expressly a foul when one gets the ball and the player gets upended subsequently. So long as it isn't vicious (the reasons Matt gave). Getting the ball first doesn't prevent it being a foul, but Matt never said it did. But inversely, getting the ball then player is not a set foul either. It's about recklessness.
Comment: Yes, the striker might indeed actually be surprised (he may be planning a different move, distracted elsewhere, etc). He may even get injured. But that doesn't make it a foul. You can go ball-player if needed and done properly. I have done some officiating training (college intramurals), but certainly someone may be more expertised and overturn me. But from my training and experiences at least, that's how I know it.
Comment: I'd say you actually do often see defenders throwing themselves, in the path at least, to slow an attacker and possibly block near the box. But as a Bournemouth fan (whose teams seems to do it a lot) it can definitely be taken apart by a controlled striker as Matt suggests!
Answer: I presume you mean that you are sliding in and taking the ball from him cleanly, and then the player falls over you? If so, then this is not a foul.
Should you make contact with the player though, either before getting the ball, or in a manner that the referee deems to be careless or reckless, he would award a penalty to the attacking team.


Identity function is a homeomorphism iff topologies are equal

Question: Let  $\tau_1$  and $\tau_2$ are two topologies on $X$
Then the function $f: (X,\tau_1) \to (X,\tau_2)$ defined by $f(x)=x$ is a homeomorphism if and only if $\tau_1=\tau_2$
I have tried many many unnecessary properties and I am in a jam now. I need exact and clear two directioned proof. Can someone illuminate me or direct me to exact proof? (Without using f is a homeomorphism iff f is open and continuous)
Comment: $f$ is always a bijection so the only concern is continuity of $f$ and $f^{-1}$. If $\tau_1=\tau_2$ then take any open set $O\in \tau_1=\tau_2$ then its preimage by $f=f^{-1}$ is $O$ which is open. so $f$ is continuous hence $f $ is a homeomorphism.
Comment: @palio Thanks but as I said below I can not use f is continuous and open
Answer: Assume the identity map, $f:(X,\tau_1)\to(X,\tau_2)$ is a homeomorphism. Let $U\in\tau_1$, then by the continuity of $f^{-1}$, $(f^{-1})^{-1}(U)$ is open in $\tau_2$, but $(f^{-1})^{-1}(U) = f(U) = U$, so $U\in\tau_2$, hence $\tau_1\supseteq \tau_2$. Now let $U\in\tau_2$, then by the continuity of $f$, $f^{-1}(U)$ is open in $\tau_1$, but since the inverse of the identity map is itself (see https://proofwiki.org/wiki/Inverse_of_Identity_Mapping), $f^{-1}(U) = f(U) = U$, so $U\in\tau_1$, hence $\tau_2\supseteq \tau_1$. Therefore $\tau_1 = \tau_2$.
Now assume $\tau_1 = \tau_2$, and let $f:(X,\tau_1)\to(X,\tau_2)$ be the identity map. Then for every $U\in\tau_2$, $f^{-1}(U) = U$ and $U\in\tau_1$, hence $f$ is continuous. For every $U\in\tau_1$, $(f^{-1})^{-1}(U) = f(U) = U$ and $U\in\tau_2$, hence $f^{-1}$ is continuous. Additionally due to the definition of the identity map, it is a bijection (see https://proofwiki.org/wiki/Identity_Mapping_is_Bijection). As a result $f$ is a homeomorphism.
Answer:
If $\tau_1 = \tau_2$, then $f$ is definitely a homeomorphism, because it is bijective, because it is open (the image of every open set is itself an open set), and because it is continuous (the inverse image of every open set is itself open.)
If the identity function $f$ is a homeomorphism, then it is continuous and open.
Because $f$ is open: if $A$ is an open set in $\tau_1$, then $f(A)$ is an open set in $\tau_2$. But $f(A) = A$ because $f$ is the identity, so this shows that $A$ is open in $\tau_2$ if $A$ is open in $\tau_1$.
Because $f$ is continuous: if $B$ is an open set in $\tau_2$, then $f^{-1}(B)$ is an open set in $\tau_1$. But $f^{-1}(B) = B$ because $f^{-1}$ is the identity, so this shows that $B$ is open in $\tau_1$ if $B$ is open in $\tau_2$.
This shows that $U$ is open in $\tau_1$ if and only if $U$ is open in $\tau_2$; hence $\tau_1 = \tau_2$.
Comment: Thank you so much but I can not use f is a homeomorphism if and only if f is continuous and open because we have seen this property as a theorem which is later than this theorem. I must use definitions only. (f is bijective, continuous on X, continuous on Y)
Comment: I think these are the same things. Open map means open mapped to open, so inverse is continuous


How to return Xml Data from a Web API Method?

Question: I have a Web Api method which should return an xml data but it returns string:
 public class HealthCheckController : ApiController
    {
        [HttpGet]
        public string Index()
        {
            var healthCheckReport = new HealthCheckReport();

            return healthCheckReport.ToXml();
        }
    }

It returns:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<myroot><mynode></mynode></myroot>
</string>

and I have added this mapping:
 config.Routes.MapHttpRoute(
              name: "HealthCheck",
              routeTemplate: "healthcheck",
              defaults: new
              {
                  controller = "HealthCheck",
                  action = "Index"
              });

How to make it return just the xml bits:
<myroot><mynode></mynode></myroot>

If I was using just MVC, I could be using the below but Web API doesn't support "Content":
 [HttpGet]
        public ActionResult Index()
        {
            var healthCheckReport = new HealthCheckReport();

            return Content(healthCheckReport.ToXml(), "text/xml");
        }

I have also added the below codes to the WebApiConfig class:
 config.Formatters.Remove(config.Formatters.JsonFormatter);
 config.Formatters.XmlFormatter.UseXmlSerializer = true;

Comment: Can you just return the HealthCheckReport instance, and let the XML formatter do the serialization? Right now, you are serializing to XML in your controller and then passing that string to the XML formatter. Then the XML formatter serializes the string to XML.
Answer: The quickest way is this,
 public class HealthCheckController : ApiController
 {
     [HttpGet]
     public HttpResponseMessage Index()
     {
         var healthCheckReport = new HealthCheckReport();

         return new HttpResponseMessage() {Content = new StringContent( healthCheckReport.ToXml(), Encoding.UTF8, "application/xml" )};
     }
 }

but it is also very easy to build a new XmlContent class that derives from HttpContent to support XmlDocument or XDocument directly. e.g.
public class XmlContent : HttpContent
{
    private readonly MemoryStream _Stream = new MemoryStream();

    public XmlContent(XmlDocument document) {
        document.Save(_Stream);
            _Stream.Position = 0;
        Headers.ContentType = new MediaTypeHeaderValue("application/xml");
    }

    protected override Task SerializeToStreamAsync(Stream stream, System.Net.TransportContext context) {

        _Stream.CopyTo(stream);

        var tcs = new TaskCompletionSource<object>();
        tcs.SetResult(null);
        return tcs.Task;
    }

    protected override bool TryComputeLength(out long length) {
        length = _Stream.Length;
        return true;
    }
}

and you can use it just like you would use StreamContent or StringContent, except that it accepts a XmlDocument,
public class HealthCheckController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Index()
    {
       var healthCheckReport = new HealthCheckReport();

       return new HttpResponseMessage() {
           RequestMessage = Request,
           Content = new XmlContent(healthCheckReport.ToXmlDocument()) };
    }
}

Comment: How is the XmlContent class used?  Does it have to registered somewhere?


GKE k8s cluster storage.googleapis.com sporadic Temporary failure in name resolution

Question: I am trying to run a snakemake pipeline on a kubernetes cluster (GKE). The job is being initiated from a GCE VM. Sometimes it works, mostly it doesn't.
Steps I took were
gcloud container clusters get-credentials snakemake-k8s-demo
kubectl delete pod $(kubectl get pods | grep snakejob|colprint 1)
snakemake --kubernetes --container-image eu.gcr.io/scailyte-is/snakemake-gsdk --use-conda --default-remote-provider GS --default-remote-prefix xxxxxx-snakemake-test-1 --jobs 2

This first try worked very well.
I then deleted the files created by the snakemake pipeline and ran the identical job again without changing anything.
The job failed with the following error message:
HTTPSConnectionPool(host='storage.googleapis.com', port=443): Max retries exceeded with url: /storage/v1/b/xxxxxxx-snakemake-test-1/o?projection=noAcl (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f3ee35159d0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))

According to the Google Cloud Status Dashboard, there are no problems with the Google Cloud Storage.
Subsequent attempts failed in the same way.
Any tips for a resolution gratefully accepted.
Comment: Does [this](https://stackoverflow.com/questions/48274552/how-can-i-resolve-httpsconnectionpoolhost-www-googleapis-com-port-443-max-r) answer your question ?
Answer: The problem was caused by lack of appropriate firewall rules allowing intra-cluster communication. Once the appropriate ALLOW rules had been created the immediate problem went away, as the pod was able to reach its DNS server.
Our policy is to forbid all communication (including VPC-internal) between endpoints unless explicitly allowed. So the new cluster in a new address space needed additions to enable it to work properly.
I figured this out by enabling logging on the final DENY rule that fires when no previous ALLOW rule was applicable.
I haven't worked out why it worked the first time but I suspect there were some differences that I didn't make a note of.


phpMyAdmin server description instead of hostname

Question: I installed phpMyAdmin 4.4.8 (latest version) and I configured some MySQL host I can connect to.
Servers are listed with the $cfg['Servers'][$i]['host'] value in the server list and I cannot find out a way to configure a "description string" in the phpMyAdmin configuration file.
I know I could configure a DNS or a /etc/hosts entry to assign a custom name to the servers, but I wish to use a more understandable description (like "Testing server" or "Production server").
Do you know a way to configure this in phpMyAdmin?
Thank you very much!
Bye
Answer: Try set $cfg['Servers'][$i]['verbose']

$cfg['Servers'][$i]['verbose']
Type:   string
    Default value:  ''
Only useful when using phpMyAdmin with multiple server entries. If set, this string will be displayed instead of the hostname in the
  pull-down menu on the main page. This can be useful if you want to
  show only certain databases on your system, for example. For HTTP
  auth, all non-US-ASCII characters will be stripped.

Ref: http://docs.phpmyadmin.net/en/latest/config.html#server-connection-settings
Comment: Thank you very much Federico! I didn't see that configuration variable!


Esconder um botão em HTML5 e CSS quando estiver em Smartphone

Question: Fiz uma aplicação Web responsiva, que quando chega no Checkout tem dois botões: Imprimir e Salvar.
Só que o usuário (cliente) no smartphone clica em imprimir, mesmo não tendo impressora.
Já tentei estender com o @media, mas não estou conseguindo.
Como posso esconder o botão "Imprimir" e deixar somente o botão "Salvar" quando o usuário estiver no Smatphone ou Tablet?
Comment: Possível duplicata de [Exibir Div Apenas em Versão Mobile](https://pt.stackoverflow.com/questions/117414/exibir-div-apenas-em-vers%c3%a3o-mobile)
Comment: Vou ver esta se resolve.
Answer: Se você está usando bootstrap4, você pode usar a classe d-none (significa display none)
Como esse conjunto de classes aceitam prefixos, você pode adicionar a classe d-sm-block para mudar para display block quando a tela for small ou superior.
No fim, ficaria assim:
<button class='d-none d-sm-block'>Imprimir</button>

Quando a tela for small, medium, large Ou extra large, voce vai ter um display block, normal.
Quando a tela for inferior a small, tipo extra small (Ou smartphone) o display vai ser none.
Espero ter ajudado.
Comment: Obrigado pessoal pela ajuda. A solução do @Andrew Ribeiro funcionou perfeitamente no Bootstrap 4. Obrigado Andrew.


A question on Bayesian updating (Han Solo and the Bayesian priors)

Question: http://www.statslife.org.uk/the-statistics-dictionary/2148-han-solo-and-bayesian-priors
in the preceding article, there is a bit of Bayesian updating that does not make sense to me. We have a prior probability (of Han Solo escaping the asteroid field) and the C3PO estimate of a probability that someone survives the field.
they are somehow combined to yield a posterior probability (of Han surviving the field)
now ... the way I understood the process of calculating a posterior, you'd need a prior $P(A)$, observe an event $E$, and use two conditionals $P(E|A)$ and $P(E|\not A)$ to calculate the posterior (or, perhaps, the ratio between these two conditionals)

the question is: why is C3P0's estimate of the probability of a random person being used in this place? It seems you would need two conditionals, or a likelihood ratio, and C3P0's estimate is neither.
Comment: I think you are justifiably confused by this example. One issue is that this example is not about probability of Han's survival per se, but rather our _belief_ in his chances of survival. But, even so, in order for us to rationally update our belief in Han's chances based on other pilots we have to establish a link between their performance and his. The update performed in the article was done as if the other pilots were an acceptable proxy for Han. Yet, the article is trying to make the point that Han is not like other pilots.
Comment: trying to clarify the question
Answer: It is wrong to say that the Posterior = Prior*Likelihood as there is no guarantee that multiplying two distributions will result in a valid distribution (i.e, integrates to 1). However, it is perfectly legitimate to write Posterior $\propto$ Likelihood * Prior as there always some normalizing constant that will make the posterior a valid distribution.
You may be used to seeing the posterior as the following,
$$p(\theta|x) = \frac{p(x|\theta)p(\theta)}{p(x)}.$$
the denominator, $p(x)$, is the "normalizing constant". It is easy to see that this normalizing constant makes the posterior integrate to one if we notice $p(x)=\int^\infty_{-\infty} p(x|\theta)p(\theta)dx$. That is, $$\int^\infty_{-\infty}\frac{p(x|\theta)p(\theta)}{p(x)} dx = \frac{1}{p(x)}\int^\infty_{-\infty} p(x|\theta)p(\theta) dx =1$$
Since $p(x)$ is just some constant that make the posterior a valid distribution, it is not interesting and that's why one sees Posterior $\propto$ Likelihood * Prior or sometimes, incorrectly, Posterior = Likelihood*Prior.
Comment: thanks.
but the thing that bothers me is not the normalization
Comment: my problem is with using C3PO's estimate in a place that seems to demand conditional probabilities (or a ratio of them)
Comment: @josinalvo Perhaps another prior would've been better but using the probability that a person survives as a prior for the probability that Han Solo makes sense to me. Many priors make sense here and the estimate will change if you use a different prior.
Answer: I think in the article you are linking the authors avoid to consider the denominator and simply multiplicate the likelihood (C3PO) estimate by the prior (our guess that Han Solo will succeed).
Indeed, just after
Posterior = Likelihood $\times$ Prior
you read

The only thing not explicitly stated in this formula is that we
  usually want to normalize everything so it sums up to 1. It also turns
  out that combining our two beta distributions in this way, including
  the normalization, is remarkably easy.
Answer: I think your question is
\begin{align}
&H:= \text{Han survives} \\
&D:= \text{random pilots die} \\
\\
&P(H|D) \propto P(D|H) P(H) \\
&P(D|H) = ?!
\end{align}
The article is guilty of some hand waving because in order for us to rationally update our belief in Han's chances based on other pilots' experience we have to establish a link between their performance and his. The update performed in the article was done as if the other pilots were an acceptable proxy for Han. However, the article wants to say at the same time that Han is somehow more awesome than the other pilots, which would break the applicability of their data.
One key thing to keep in mind is that this example is not about the probability of Han surviving per se but of our belief that he will survive. As first time viewers approaching the asteroid field, we don't know what the probability of survival for an attempted crossing by Han would be. We believe that chances are more likely high for Han than not, but we are uncertain. So, not only is the outcome uncertain for a given chance, we aren't even certain what the chances are.
Han is a pilot of extraordinary skill, so our belief in his chances of survival of a danger is a distribution $h$, heavily weighted toward 1. In this example, the model used is
\begin{equation}
h(p) \sim Beta(20000,1) \propto p^{20000-1}(1-p)^{1-1}
\end{equation}
so that our mean prior survival odds for Han are $E[h(p)] = 20000:1$.
Now,  if C3PO provides data, $D$, that 2 pilots have survived and 7440 have perished, then for a given chance of survival $p$, the likelihood of that data is
\begin{equation}
L(D|p) \propto p^2 (1-p)^{7440}
\end{equation}
Even though he's really awesome, Han's chances of success do depend on the level of danger, which we now have reasons to believe are higher than before C3PO provided information. However, the following update only works to the extent the additional data is applicable as proxies for Han, that is to the extent we can treat their experiences as belonging to Han's sampling distribution.
\begin{align}
h(p|D) &\propto L(D|p) h(p) \\
       &\propto [p^2 (1-p)^{7440}][p^{20000-1}(1-p)^{1-1}] \\
       &= p^{(20000+2)-1}(1-p)^{(7440+1)-1}
\end{align}
Note that what's changed is our belief in Han's chances, not his actual chances per se. Though, if Han's beliefs were constructed in the same way as ours, C3PO may have just eroded his confidence. To the extent confidence is good in dangerous situations and our heroes are always overconfident, never let robots report the odds.