Extensive div child when parent grows/shrinks

Question: I have this HTML code:

What I want to do is have child2 take 200px and be on the bottom of parent, and have child1 grow/shrink as a parent grows/shrinks (zoom in/out of the page by the user for example)
example:
If parent's height is 1000px, then I want child1's height to be 800px & child2's height to be 200px.
If parent's height is 2000px, then I want child1's height to be 1800px & child2's height to be 200px
How do I do that?
Answer: You can use flexbox to get this done. But beware: Only supported in modern browsers, see caniuse.

#parent {
  display: flex;
  flex-direction: column;
  min-width: 100%;
  height: 1000px;
  background-color: gray;
}

#child1 {
  flex-grow: 1;
  min-width: 100%;
  background-color: orange;
}

#child2 {
  align-self: flex-end;
  min-width: 100%;
  height: 200px;
  background-color: red;
}

Answer: This trick works using margin and padding on first child according to the second child height:

#parent {
  height: 1000px;
  background-color: green;
}

#child1 {
  height: 100%;
  background-color: blue;
  margin-bottom: -200px;
  padding-bottom: 200px;
}

#child2 {
  height: 200px;
  background-color: red;
}

Answer: 1.
To do this is very simple. If you make the child2 200px then set the child1 to 100% in height minus the 200px, child1 will take up all the space apart from the 200px that child2 is taking.

alert($("#child1").height());
#parent {
  height: 1000px;
  background-color: green;
}

#child1 {
  height: calc(100% - 200px);
  background-color: blue;
}

#child2 {
  height: 200px;
  background-color: red;
}

2.
You could also do it using javascript
You take the height of the parent and then -200. Set child 1 to be the resulting height.
var height = $("#parent").height() -200;
$("#child1").height(height);

https://jsfiddle.net/g9xj0mjx/
if you then wanted to get rid of the 1000px parent height and make it a percentage so it changes when the user changes screen size (like you mentioned). You could put it inside a resize event
$( window ).resize(function() {
  var height = $("#parent").height() -200;
  $("#child1").height(height);
});

Comment: After Editing it works however calc is not well supported.
Answer: Solution1
You can do this with absolute position and padding like this:

html, body {height:100%;margin:0}

#parent {
  height:100%;
  position:relative;
}
#child1 {
  height:100%;
  background:yellow;
  padding-bottom:200px;
  box-sizing:border-box;
}
#child2 {
  height:200px;
  width:100%;
  position:absolute;
  bottom:0;
  left:0;
  background:black;
}

Solution2
You can also use calc(), check the support

html, body {height:100%;margin:0}

#parent {
  height:100%;
}
#child1 {
  height:calc(100% - 200px);
  background:yellow;
}
#child2 {
  height:200px;
  background:black;
}


How to test for simultaneous equality of choosen coefficients in logit or probit model?

Question: How to test for simultaneous equality of choosen coefficients in logit or probit model ? What is the standard approach and what is the state of art approach ?
Answer: Wald test
One standard approach is the Wald test. This is what the Stata command test does after a logit or probit regression. Let's see how this works in R by looking at an example:
mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv") # Load dataset from the web
mydata$rank <- factor(mydata$rank)
mylogit <- glm(admit ~ gre + gpa + rank, data = mydata, family = "binomial") # calculate the logistic regression

summary(mylogit)

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.989979   1.139951  -3.500 0.000465 ***
gre          0.002264   0.001094   2.070 0.038465 *
gpa          0.804038   0.331819   2.423 0.015388 *
rank2       -0.675443   0.316490  -2.134 0.032829 *
rank3       -1.340204   0.345306  -3.881 0.000104 ***
rank4       -1.551464   0.417832  -3.713 0.000205 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Say, you want to test the hypothesis $\beta_{gre}=\beta_{gpa}$ vs. $\beta_{gre}\neq \beta_{gpa}$. This is equivalent of testing $\beta_{gre} - \beta_{gpa} = 0$. The Wald test statistic is:
$$
W=\frac{(\hat{\beta}-\beta_{0})}{\widehat{\operatorname{se}}(\hat{\beta})}\sim \mathcal{N}(0,1)
$$
or
$$
W^2 = \frac{(\hat{\theta}-\theta_{0})^2}{\operatorname{Var}(\hat{\theta})}\sim \chi_{1}^2
$$
Our $\widehat{\theta}$ here is $\beta_{gre} - \beta_{gpa}$ and $\theta_{0}=0$. So all we need is the standard error of $\beta_{gre} - \beta_{gpa}$. We can calculate the standard error with the Delta method:
$$
\hat{se}(\beta_{gre} - \beta_{gpa})\approx \sqrt{\operatorname{Var}(\beta_{gre}) + \operatorname{Var}(\beta_{gpa}) - 2\cdot \operatorname{Cov}(\beta_{gre},\beta_{gpa})}
$$
So we also need the covariance of $\beta_{gre}$ and $\beta_{gpa}$. The variance-covariance matrix can be extracted with the vcov command after running the logistic regression:
var.mat <- vcov(mylogit)[c("gre", "gpa"),c("gre", "gpa")]

colnames(var.mat) <- rownames(var.mat) <- c("gre", "gpa")

              gre           gpa
gre  1.196831e-06 -0.0001241775
gpa -1.241775e-04  0.1101040465

Finally, we can calculate the standard error:
se <- sqrt(1.196831e-06 + 0.1101040465 -2*-0.0001241775)
se
[1] 0.3321951

So your Wald $z$-value is
wald.z <- (gre-gpa)/se
wald.z
[1] -2.413564

To get a $p$-value, just use the standard normal distribution:
2*pnorm(-2.413564)
[1] 0.01579735

In this case we have evidence that the coefficients are different from each other. This approach can be extended to more than two coefficients.
Using multcomp
This rather tedious calculations can be conveniently done in R using the multcomp package. Here is the same example as above but done with multcomp:
library(multcomp)

glht.mod <- glht(mylogit, linfct = c("gre - gpa = 0"))

summary(glht.mod)

Linear Hypotheses:
               Estimate Std. Error z value Pr(>|z|)
gre - gpa == 0  -0.8018     0.3322  -2.414   0.0158 *

confint(glht.mod)

A confidence interval for the difference of the coefficients can also be calculated:
Quantile = 1.96
95% family-wise confidence level

Linear Hypotheses:
               Estimate lwr     upr
gre - gpa == 0 -0.8018  -1.4529 -0.1507

For additional examples of multcomp, see here or here.

Likelihood ratio test (LRT)
The coefficients of a logistic regression are found by maximum likelihood. But because the likelihood function involves a lot of products, the log-likelihood is maximized which turns the products into sums. The model that fits better has a higher log-likelihood. The model involving more variables has at least the same likelihood as the null model. Denote the log-likelihood of the alternative model (model containing more variables) with $LL_{a}$ and the log-likelihood of the null model with $LL_{0}$, the likelihood ratio test statistic is:
$$
D=2\cdot (LL_{a} - LL_{0})\sim \chi_{df1-df2}^{2}
$$
The likelihood ratio test statistic follows a $\chi^{2}$-distribution with the degrees of freedom being the difference in number of variables. In our case, this is 2.
To perform the likelihood ratio test, we also need to fit the model with the constraint $\beta_{gre}=\beta_{gpa}$ to be able to compare the two likelihoods. The full model has the form $$\log\left(\frac{p_{i}}{1-p_{i}}\right)=\beta_{0}+\beta_{1}\cdot \mathrm{gre} + \beta_{2}\cdot \mathrm{gpa}+\beta_{3}\cdot \mathrm{rank_{2}} + \beta_{4}\cdot \mathrm{rank_{3}}+\beta_{5}\cdot \mathrm{rank_{4}}$$. Our constraint model has the form: $$\log\left(\frac{p_{i}}{1-p_{i}}\right)=\beta_{0}+\beta_{1}\cdot (\mathrm{gre} + \mathrm{gpa})+\beta_{2}\cdot \mathrm{rank_{2}} + \beta_{3}\cdot \mathrm{rank_{3}}+\beta_{4}\cdot \mathrm{rank_{4}}$$.
mylogit2 <- glm(admit ~ I(gre + gpa) + rank, data = mydata, family = "binomial")

In our case, we can use logLik to extract the log-likelihood of the two models after a logistic regression:
L1 <- logLik(mylogit)
L1
'log Lik.' -229.2587 (df=6)

L2 <- logLik(mylogit2)
L2
'log Lik.' -232.2416 (df=5)

The model containing the constraint on gre and gpa has a slightly higher log-likelihood (-232.24) compared to the full model (-229.26). Our likelihood ratio test statistic is:
D <- 2*(L1 - L2)
D
[1] 16.44923

We can now use the CDF of the $\chi^{2}_{2}$ to calculate the $p$-value:
1-pchisq(D, df=1)
[1] 0.01458625

The $p$-value is very small indicating that the coefficients are different.
R has the likelihood ratio test built in; we can use the anova function to calculate the likelhood ratio test:
anova(mylogit2, mylogit, test="LRT")

Analysis of Deviance Table

Model 1: admit ~ I(gre + gpa) + rank
Model 2: admit ~ gre + gpa + rank
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       395     464.48
2       394     458.52  1   5.9658  0.01459 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Again, we have strong evidence that the coefficients of gre and gpa are significantly different from each other.

Score test (aka Rao's Score test aka Lagrange multiplier test)
The Score function $U(\theta)$ is the derivative of the log-likelihood function ($\text{log} L(\theta|x)$) where $\theta$ are the parameters and $x$ the data (the univariate case is shown here for illustration purposes):
$$
U(\theta) = \frac{\partial \text{log} L(\theta|x)}{\partial \theta}
$$
This is basically the slope of the log-likelihood function. Further, let $I(\theta)$ be the Fisher information matrix which is the negative expectation of the second derivative of the log-likelihood function with respect to $\theta$. The score test statistics is:
$$
S(\theta_{0})=\frac{U(\theta_{0}^{2})}{I(\theta_{0})}\sim\chi^{2}_{1}
$$
The score test can also be calculated using anova (the score test statistics is called "Rao"):
anova(mylogit2, mylogit,  test="Rao")

Analysis of Deviance Table

Model 1: admit ~ I(gre + gpa) + rank
Model 2: admit ~ gre + gpa + rank
  Resid. Df Resid. Dev Df Deviance    Rao Pr(>Chi)
1       395     464.48
2       394     458.52  1   5.9658 5.9144  0.01502 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The conclusion is the same as before.

Note
An interesting relationship between the different test statistics when the model is linear is (Johnston and DiNardo (1997): Econometric Methods): Wald $\geq$ LR $\geq$ Score.
Comment: I wonder why the reduced model simply excludes `gre` and `gpa`? Isn't that testing $\beta_1=\beta_2=0$, not $\beta_1=\beta_2$? To me, to correctly test $\beta_1=\beta_2$, we need to keep `gre` and `gpa` and meanwhile impose $\beta_{\text{gre}}=\beta_{\text{gpa}}$.
Comment: @SibbsGambling Good catch! I updated my answer accordingly.
Comment: @Daniel Yes, this approach can also be used for levels of a categorical variable. The `multcomp` packages makes it particularly easy. For example, try this: `glht.mod <- glht(mylogit, linfct = c("rank3 - rank4= 0"))`. But a much easier way would be to make `rank3` the reference level (using `mydata$rank <- relevel(mydata$rank, ref="3")`) and then just use the normal regression output. Each level of the factor is compared to the reference level. The p-value for `rank4` would be the desired comparison.
Comment: @Daniel The p-values from the model output (changed reference level) and `glht` are the same for me (about $0.591$). Regarding your second question: `linfct = c("rank3 - rank4= 0")` tests only *one* linear hypothesis whereas `mcp(rank="Tukey")` tests *all* 6 pairwise comparisons of `rank`. So the p-values have to be adjusted for multiple comparisons. This means that the p-values using Tukey's test are generally higher than the single comparison.
Comment: Is this limited to continuous predictors only, or could I - for instance - also see whether two levels of a categorical variable are significantly different? Let's say, is the difference between rank3 and rank4 significant?
Comment: Thanks for clarification. Changing reference levels might be a solution, however, it's not that convenient. Furthermore, it seems that p-values of levels in the summary output differs from what `glht` returns. I just saw [your answer here](http://stats.stackexchange.com/questions/60352/comparing-levels-of-factors-after-a-glm-in-r/60361#60361), which already has answered my question. I tested both `linfct = c("rank3 - rank4= 0")` and `mcp(rank="Tukey")` (however, with my data, of course), and the latter returned a different p-value than the first approach (est. and t were same)  - I wonder why?
Comment: Thanks again! I think that is the reason why I got different p-levels (adjustment when using Tukey's test). When I relevel my factor, `summary(fit)` returns the same results (according p-levels) as `summary(glht(fit, linfct = c("t0vst11 - t0vst12 = 0")))` (with original reference level).
Answer: You did not specify your variables, if they are binary or something else. I think you talk about binary variables. There also exist multinomial versions of the probit and logit model.
In general, you can use the complete trinity of test approaches, i.e.
Likelihood-Ratio-test
LM-Test
Wald-Test
Each test uses different test-statistics. The standard approach would be to take one of the three tests. All three can be used to do joint tests.
The LR test uses the differnce of the log-likelihood of a restricted and the unrestricted model. So the restricted model is the model, in which the specified coefficients are set to zero. The unrestricted is the "normal" model. The Wald test has the advantage, that only the unrestriced model is estimated. It basically asks, if the restriction is nearly satisfied if it is evaluated at the unrestriced MLE. In case of the Lagrange-Multiplier test only the restricted model has to be estimated. The restricted ML estimator is used to calculate the score of the unrestricted model. This score will be usually not zero, so this discrepancy is the basis of the LR test. The LM-Test can in your context also be used to test for heteroscedasticity.
Answer: The standard approaches are the Wald test, the likelihood ratio test and the score test. Asymptotically they should be the same. In my experience the likelihood ratio tests tends to perform slightly better in simulations on finite samples, but the cases where this matters would be in very extreme (small sample) scenarios where I would take all of these tests as a rough approximation only. However, depending on your model (number of covariates, presence of interaction effects) and your data (multicolinearity, the marginal distribution of your dependent variable), the "wonderful kingdom of Asymptotia" can be well approximated by a surprisingly small number of observations.
Below is an example of such a simulation in Stata using the Wald, likelihood ratio and score test in a sample of only 150 observations. Even in such a small sample the three test produce fairly similar p-values and the sampling distribution of the p-values when the null hypothesis is true does seem to follow a uniform distribution as it should (or at least the deviations from the uniform distribution are no larger than one would expect due to the randomness inherrit in a Monte Carlo experiment).
clear all
set more off

// data preparation
sysuse nlsw88, clear

gen byte edcat = cond(grade <  12, 1,     ///
                 cond(grade == 12, 2, 3)) ///
                 if grade < .
label define edcat 1 "less than high school" ///
                   2 "high school"           ///
                   3 "more than high school"
label value edcat edcat
label variable edcat "education in categories"

// create cascading dummies, i.e.
// edcat2 compares high school with less than high school
// edcat3 compares more than high school with high school
gen byte edcat2 = (edcat >= 2) if edcat < .
gen byte edcat3 = (edcat >= 3) if edcat < .

keep union edcat2 edcat3 race south
bsample 150 if !missing(union, edcat2, edcat3, race, south)

// constraining edcat2 = edcat3 is equivalent to adding
// a linear effect (in the log odds) of edcat
constraint define 1 edcat2 = edcat3

// estimate the constrained model
logit union edcat2 edcat3 i.race i.south, constraint(1)

// predict the probabilities
predict pr
gen byte ysim = .
gen w = .

program define sim, rclass
    // create a dependent variable such that the null hypothesis is true
    replace ysim = runiform() < pr

    // estimate the constrained model
    logit ysim edcat2 edcat3 i.race i.south, constraint(1)
    est store constr

    // score test
    tempname b0
    matrix `b0' = e(b)
    logit ysim edcat2 edcat3 i.race i.south, from(`b0') iter(0)
    matrix chi = e(gradient)*e(V)*e(gradient)'
    return scalar p_score = chi2tail(1,chi[1,1])

    // estimate unconstrained model
    logit ysim edcat2 edcat3 i.race i.south
    est store full

    // Wald test
    test edcat2 = edcat3
    return scalar p_Wald = r(p)

    // likelihood ratio test
    lrtest full constr
    return scalar p_lr = r(p)
end

simulate p_score=r(p_score) p_Wald=r(p_Wald) p_lr=r(p_lr), reps(2000) : sim
simpplot p*, overall reps(20000) scheme(s2color) ylab(,angle(horizontal))

Comment: score test is a different name for what @jen-bohold called a Lagrange multiplier (LM) test.
Comment: Nice answer (+1). I especially like the effort of the simulation. I didn't know how to calculate the score test in Stata. Thanks.


Maven archetype: Modify artifactId

Question: While working on project, my requirement is to create a module.
The command will be like:
mvn archetype:generate \
  -DarchetypeCatalog=local \
  -DartifactId=test-module

And the target should have following file structure
test-module
|--pom.xml
`--src
   `--main
      |--install
      |  `--install.sh
      `--scripts
         `--test_module.sh

My whole goal is to create another variable derived from artifactId (say artifactIdWithUnderscore) replacing all hyphens - by underscope _. So that I can use the updated variable to create file(s).
Example:
+------------------+---------------------------------+
|INPUT - artifactId|OUTPUT - artifactIdWithUnderscore|
+------------------+---------------------------------+
|    test-module   |          test_module            |
|       temp       |             temp                |
| test-temp-module |       test_temp_module          |
+------------------+---------------------------------+

I tried to create a new variable as artifactIdWithUnderscore by adding following entries in archetype-metadata.xml
Option 1:
<requiredProperty key="artifactIdWithUnderscore" >
  <defaultValue>${StringUtils.replace(${artifactId}, "-", "_")}</defaultValue>
</requiredProperty>

Output:
${StringUtils.replace(${artifactId}, "-", "_")}

Option 2:
<requiredProperty key="artifactIdWithUnderscore" >
  <defaultValue>${artifactId.replaceAll("-", "_")}</defaultValue>
</requiredProperty>

Output:
maven_archetype_script

The above value of artifactId is coming from the POM of archetype project itself.
Option 3:
<requiredProperty key="artifactIdWithUnderscore" >
  <defaultValue>${artifactId}.replaceAll("-", "_")</defaultValue>
</requiredProperty>

Output:
test-module.replaceAll("-", "_")

Please let me know how I can achieve this.
EDIT:
Option 4:
<requiredProperty key="artifactIdWithUnderscore" >
    <defaultValue>${__artifactId__.replaceAll("-", "_")}</defaultValue>
</requiredProperty>

Output:
INFO: Null reference [template 'artifactIdWithUnderscore', line 1, column 1] : ${__artifactId__.replaceAll("-", "_")} cannot be resolved.
Define value for property 'artifactIdWithUnderscore': ${__artifactId__.replaceAll("-", "_")}: :

Comment: Can you show us your `archetype.properties` file?
Comment: @MattEckert, I don't have `archetype.properties` file. Using `archetype-metadata.xml`.
Answer: Option 2 work for me:
<requiredProperty key="artifactIdWithoutDash">
  <defaultValue>${artifactId.replaceAll("-", ".")}</defaultValue>
</requiredProperty>

I can use __artifactIdWithoutDash__.sh has a file name to create the file (in my case it was: some.letters.__artifactIdWithoutDash__.cfg)
Comment: this does not work for me. I got artifactId as the artifactId of architype itself.
Answer: In my case (which is somehow similar) a slightly modified option 2 did the trick:
<requiredProperty key="package-with-slash">
    <defaultValue>${package.replace(".", "/")}</defaultValue>
</requiredProperty>

Note, that the replacement is done by the apache velocity engine and the originally used replaceAll uses a regex expression.

Maven archetype: Modify artifactId


STR_TO_DATE from CONCAT

Question: I have one date-field ref_event_times.end_date and one time-field ref_event_times.end_time in my table "ref_event_times"...
I try to union that as a one datetime field "end_date_time"...
Use follow
STR_TO_DATE('CONCAT(`ref_event_times`.`end_date`,' ',`ref_event_times`.`end_time`)','%m/%d/%Y %H:%i') AS `end_date_time`

return null...
Where is the mistake?
Comment: try `STR_TO_DATE(CONCAT(ref_event_times.end_date,' ',ref_event_times.end_time),'%m/%d/%Y %H:%i')`  this one
Comment: TRY THIS I CHECKED ITS WORKING select STR_TO_DATE(CONCAT(current_date,' ',current_time),'%Y-%m-%d %H:%i:%s');
Comment: STR_TO_DATE(CONCAT(`ref_event_times`.`end_date`,' ',`ref_event_times`.`end_time`),'%Y-%m-%d %H:%i:%s')

Finaly need '%Y-%m-%d %H:%i:%s'
More thanks
Answer: MYSQL doesn't support your given datetime format '%m/%d/%Y %H:%i'
The mysql date format should be like this '%Y-%m-%d %H:%i:%s' Datetime format in mysql
    Data Type   "Zero" Value
    DATE        '0000-00-00'
    TIME        '00:00:00'
    DATETIME    '0000-00-00 00:00:00'
    TIMESTAMP   '0000-00-00 00:00:00'
    YEAR        0000

try this example
select STR_TO_DATE(CONCAT(current_date,' ',current_time),'%Y-%m-%d %H:%i:%s');

STR_TO_DATE from CONCAT


Distorted InfoBox in Google Maps API

Question: I'm using Google Maps' API and added a few markers in a map. Each marker has a infoBox with different content. Everything works fine but the appearance it's just horrible.
As you can see in the following image, it looks kinda distorted. Any clues?
image http://box.jisko.net/i/d8353364.png
Thank you!
Answer: OK. @geocodezip was right. Bootstrap does make a conflict with Google Maps and this was already solved here: Twitter Bootstrap CSS affecting Google Maps
Thank you :)

Distorted InfoBox in Google Maps API


FOSUserBundle fetch data from the form in the listener

Question: I'm trying to insert a data passed in the form (e-mail) in the response that I create in the listener to ensure that the response is a json object.
I can not take the form data from 'event in any way ..
There is a solution to what I want?
public static function getSubscribedEvents()
{
    return array(
        FOSUserEvents::PROFILE_EDIT_SUCCESS => 'onProfileEditSuccess',
    );
}

public function onProfileEditSuccess(FormEvent $event)
{

    $response = new Response();
    $output = array('success' => true, 'new_mail' => $event); //event return empty object
    $response->headers->set('Content-Type', 'application/json');
    $response->setContent(json_encode($output));
    $event->setResponse($response);
}

I tried to listen to the event COMPLETED, but does not make me change response!
Answer: You can grab form from $event object with $event->getForm() in PROFILE_EDIT_SUCCESS event.
in FOS\UserBundle\Controller\ProfileController:
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

To access email
$form = $event->getForm();
$email = $form['email']->getData();

Comment: Really thank you very much!
I was misled by the fact that if I passed a `$event->getForm()` or even `$event` I always returned an empty object!
And this even now I don't know give me an explanation ..
Comment: What exactly you do not understand? Event is just an simple object, which contains data from controller. You can modify this data, for example you can set response to it and controller will return this response.


Alterar ícone da barra de títulos e da janela

Question: Quero alterar o ícone da barra de títulos da janela do Java, conforme imagem abaixo:

Estou indo no método initComponents() e deixando como está no código abaixo, mas a linha setIconImage(iconeTitulo); fica como erro.
public FrmConfiguracoes() {
        initComponents();

    URL caminhoImagem = this.getClass().getClassLoader().getResource("smile.png");
    Image    iconeTitulo = Toolkit.getDefaultToolkit().getImage(caminhoImagem);
    setIconImage(iconeTitulo);

    }

Não reconhece o comando e não altera o ícone. O que posso fazer? E como alterar o logo que fica no ícone minimizado, conforma imagem abaixo?
Answer: Na hora de pegar a URL da imagem, remova a chamada getClassLoader() da forma que segue:
public FrmConfiguracoes() {

    initComponents();

    URL caminhoImagem = this.getClass().getResource("smile.png");
    Image    iconeTitulo = Toolkit.getDefaultToolkit().getImage(caminhoImagem);
    setIconImage(iconeTitulo);
}

Tenha em mente que mesmo assim só irá funcionar se a classe e a imagem estiverem no mesmo diretório(pacote) do projeto.

Outra forma é fazer a chamada utilizando a classe ImageIO:
public FrmConfiguracoes() {

    initComponents();

    try {

        Image iconeTitulo = ImageIO.read(getClass().getResource("smile.png"));

    } catch(IOException ex) {
      System.out.println("Erro ao importar icone: " ex.getMessage());
    }
    setIconImage(iconeTitulo);
}

Ambas as formas já alteram o ícone da janela e também o ícone que é exibido na barra de tarefas do windows, exibindo a imagem que você apontou no seu projeto, veja um exemplo na imagem abaixo:
Comment: Obrigado pela ajuda. Esta dando erro. Usei o código abaixo:  //alterando logotipo
        URL caminhoImagem = this.getClass().getResource("/logo.bmp");
        Image    iconeTitulo = Toolkit.getDefaultToolkit().getImage(caminhoImagem);
        setIconImage(iconeTitulo); Ao executar o programa é dado o erro: Uncaught error fetching image:
java.lang.NullPointerException
Comment: Se não me engano tem que ser png ou jpg o formato, e essa barra ai é desnecessária se a imagem está no mesmo pacote que a classe.
Comment: @RodrigoStortideOliveira o código acima resolveu o problema?
Comment: Obrigado pela ajuda. Testei com JPG sem a barra mas não deu certo
Comment: @RodrigoStortideOliveira então o problema é com o caminho. Se estiver usando netbeans, arraste a foto pro mesmo pacote da sua classe da tela,  e passe apenas o nome.extensao.


Handle multiple questions for Telegram bot in python

Question: I'm programming a telegram bot in Python using the Telegram bot API. I'm facing the problem of managing questions that need an answer of the user. The problem arises when the program is waiting for an answer of one user and another user request information or ask another question before the first user responds.
The Telegram API uses a code to handle the request. When you ask for updates you include a code. If the code you send is higher than a request code, it is mark as handled and telegram delete it and no longer appears in the updates. This code is sequential, so if you mark update 3 as handled, updates 1 and 2 are erased as well.
The question is why is the best phytonic/elegant way to handle multiple requests that needs an answer for the users?
Answer: There is not a most pythonic way of doing this. It is a problem you have to program to solve.
Basically, you have to maintain some state variables concerning each user. When a new message arrives, the bot checks what state that user is in, and responds accordingly.
Suppose you have a function, handle(msg), that gets called for each arriving message:
user_states = {}

def handle(msg):
    chat_id = msg['chat']['id']

    if chat_id not in user_states:
        user_states[chat_id] = some initial state ...

    state = user_states[chat_id]

    # respond according to `state`

This will do for a simple program.
For more complicated situations, I recommend using telepot, a Python framework I have created for Telegram Bot API. It has features that specifically solve this kind of problems.
For example, below is a bot that counts how many messages have been sent by an individual user. If no message is received after 10 seconds, it starts over (timeout). The counting is done per chat - that's the important point.
import sys
import telepot
from telepot.delegate import per_chat_id, create_open

class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, seed_tuple, timeout):
        super(MessageCounter, self).__init__(seed_tuple, timeout)
        self._count = 0

    def on_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)

TOKEN = sys.argv[1]  # get token from command-line

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(MessageCounter, timeout=10)),
])
bot.notifyOnMessage(run_forever=True)

Run the program by:
python messagecounter.py <token>

Go to the project page to learn more if you are interested. There are a lot of documentations and non-trivial examples.
Comment: The fourth way to help me is to make my answer your accepted answer, if you don't mind. Thank you.
Comment: Wow,  thank you so much! There is a chance to collaborate in your project? Things to do? Bugs and issues? Thank you in advance!
Comment: Thank you. The best way to help me is to let me know what you need that is not in the library, or any bugs. Another best way to help me is to spread the words about **telepot**. I truly believe it can ease the development of Telegram bots. The third best way is to use telepot in your own work. That is the whole point of publishing a library. Thank you, again.
Answer: In my bots I use webhooking. If you can to use web hooks - do it, it's more comfortable way to interactive with telegram bots.
If you can't webhooking (ssl problems, for example), there is workaround for you. Use ForceReply in order to get previous bot answer and write logic based on user replies.
Check if update contains reply (reply_to_message key), then make bot answer based on this reply. These actions must be asynchronous in order to get high bot performance.
If you are python programmer, I recommend Tornado for these purposes.
Comment: That's interesting. Although your method is suitable , I find a little messy when for example multiple user's must reply to a bot question. I think there is some work around to manage this problem without killing other user's question. But that's only my hope.


Every finitely generated flat module over a ring with a finite number of minimal primes is projective

Question: Over a commutative ring $R$, a finite type locally free (weak sense) module for which the rank function is locally constant is projective.
If we notice that for each minimal prime $p$ of the ring, the rank function is constant on the adherence of $p$ in the Zariski topology (because if $p\subset q$ the rank at $p$ is equals to the rank at $q$) on finite locally free (weak sense) modules, then if the ring has only a finite number of minimal primes, the rank function is always locally constant on finite flat modules. Am I right ?
Edit 2: Answering a request of Ben the detailed reasoning is the following:
 The image of the rank function is finite in $\mathbb{N}$. Every reciprocal image of an integer $n$ is a finite union of closed sets like the $V(p)$. So it is a closed set. The disjoint union of these closed sets is the whole spectrum. Each one of them is therefore open.
I am asking this simple question because I read this great answer here where an important paper of Raynaud-Gruson is mentioned. It gives amongst a lot of generalizations the simple criteria that if $R$ has a finite number of associated primes then without any other hypothesis on $R$ every f.g. flat modules is actually projective. My reasoning above seems quite simple and gets a slightly more general result, but perhaps I am wrong ?
Edit: since nobody answered my question I dug around but I did not find any reference to this simple criteria. I only found the criteria about the finiteness of the number of associated primes. Is it equivalent ? Is there a counterexample with an infinite number of embedded primes but a finite number of minimal (isolated) primes ?
Edit 3: the answer is here.
Comment: Aah, good point. If the subsets are not disjoint but the rank function is constant on both of them, then it agrees at the intersection and thus is constant on their union; that is what I missed. Seems fine to me now, nice observation!
Comment: Dear @brunoh, I think I have an example of a ring with unique minimal, but infinitely many associated primes. Would you like me to post it here or on MO? By the way, there, you asked for the etiquette of cross posting: when a question like yours isn't getting enough attention here, then there could be a point of posting it on MO too. But you should've waited for the bounty time here to elapse. Also, always tell people on both sites that and where you cross-posted, so users can check out the other site for useful comments or answers.
Comment: I may be missing a simple point, but how exactly do you attempt to cover the spectrum by open(!) subsets where the rank is constant?
Comment: @Ben Thank you very much for your time. My simple reasonning is the following : the image of the rank function is finite in $\mathbb{N}$. Every reciprocal image of an integer $n$ is a finite union of closed sets like the $V(p)$. So it is a closed set. The disjoint union of these closed sets is the whole spectrum. Each one of them is therefore open right ?
Comment: @Ben +1 for your comment. Thanks ! Unfortunately this question has not received enough attention. But if I am right it is a simple result I never saw anywhere (there is a close but less general one as I quoted in the question, and that is reached through a much more complicated approach ...)
Comment: Dear @Ben, quite useful comment +1. Firstly, I thank you very much for giving me the right guidelines for crossposting that I will follow in the future with diligence ! Secondly, I do prefer you post this comment and your example on MO if you do not mind. If you are right, I am happy because it shows that if I am right (which is actually my question) my criteria is slightly more general than the one obtained through more complicated ways !
Comment: This question got an excellent answer from @Ben on MO here
http://mathoverflow.net/a/219759/3333
Answer: Upon request, I repost my MathOverflow answer (c.f. MO/218737).
There are two questions here, namely, whether the argument given in the question is okay, and whether the criterion really is more general than the one by Raynaud-Gruson. The answer to both questions is yes. The following holds:

Let $A$ be a commutative with unity and $M$ a flat finitely generated $A$-module. Then the rank function $\mathrm{Spec}(A)\to\mathbb{N}_0$, $\mathfrak{p}\mapsto \mathrm{rk}_{A_\mathfrak{p}}(M_{\mathfrak{p}})$, is constant on all irreducible components of $\mathrm{Spec}(A)$. In particular, if $\mathrm{Spec}(A)$ has finitely many maximal irreducible components (i.e., if $A$ has finitely many minimal prime ideals), then the rank function is locally constant, hence $M$ is projective.

The (very nice and short) proof was given by the OP in the question text and in a comment. (With the same arguments, one can further generalise this to schemes; see loc. cit.)
The criterion by Raynaud-Gruson requires finitely many associated primes, so to be sure that the above criterion is more general, we need an example of a ring with finitely many minimal, but infinitely many associated prime ideals.
The following example has a single minimal prime ideal, but infinitely many associated prime ideals. Picture it as a line with infinitely many embedded points. (Just as $k[x,t]/(t^2,xt)$ has associated primes $(t)$, the unique minimal one, and $(x,t)$, the "embedded point".)
Let $H$ be the ring of holomorphic functions on the complex line $\mathbb{C}$ (with coordinate $z$) and $f\in H$ a non-trivial holomorphic function with infinitely many zeros (e.g., $f(z) = \sin(z)$). We consider the ring $A:=H[t]/(t^2,tf)$.
Since $A/(t)\cong H$ is an integral domain, the ideal $(t)$ is prime. On the other hand, this ideal happens to be the nilradical of $A$, which is the intersection of all prime ideals; thus, $(t)$ is the only minimal prime.
However, for each root $\alpha\in\mathbb{C}$ of $f$ we recognise the associated prime ideal $(t,z-\alpha)\subset A$, so there are infinitely many of them.
In fact, if $g\in H$ is the unique entire function with $(z-\alpha)g = f$, then it is easy to see that $(t,z-\alpha) = \mathrm{ann}_{A}(tg)$.
Comment: Dear @brunoh, I'm sorry for the late response. I wanted to construct a new example for this post, but what I had in mind didn't work out and then I got busy, so I forgot to repost the known one. I hope it's okay that I didn't copy-paste the proof.
Comment: better late than never. You got a well deserved IMO second bounty for your good work !


Which theorem is used to reduce a linear congruence here?

Question: $21x \equiv 49 \pmod{10}$?
21 % 10 = 1
and
49 % 10 = 9
So we can rewrite this as
$1x \equiv 9 \pmod{10}$
But which theorem shows that we can substitute the LHS & RHS with the remainder?
Comment: That's the definition of congruence. You can substitute an element by any element with the same remainder.
Comment: @AnuragA - where do I find this definition?
Comment: You used the Congruence Product Rule (see the dupe), and the the fact that [congruence is an equivalence relation.](https://math.stackexchange.com/q/655577/242)
Answer: If $a \equiv b \pmod{n}$, then $ax \equiv bx \pmod{n}$
Since $21 \equiv 1 \pmod{10}$, we have $21x \equiv x \pmod{10}$.
Also, note that it is an equivalence relation, we have symmetric and transitivity.
Since $21x \equiv x \pmod{10}$ and $21x \equiv 49 \pmod{10}$,
We have  $$ x \equiv 49\pmod{10}$$
Again, since $x \equiv 49 \pmod{10}$ and $49 \equiv 9 \pmod{10}$, we have $$x \equiv 9 \pmod{10}.$$


ANOVA when group differences aren't clear-cut

Question: I'm wondering if anyone can help me with a really tricky one-way independent ANOVA problem I'm having? Here's a bit of background:
There are 3 diagnostic groups (depression, anxiety, non-clinical). The groups are independent, but participants in the depression group might also have an anxiety diagnosis. The dependent variable is a continuous measures of self-esteem. A-priori power analysis indicated that I need around 50 participants per group to detect a medium effect, which I do. However, after doing an initial ANOVA to look at differences between these groups, I need to do a follow-up to see whether controlling for anxiety in the depression group affects the group differences (as they might just be similar on the DV due to shared high levels of anxiety).
I can't use the continuous measure of anxiety I've used to categorise participants into the diagnostic groups as a covariate, as this would remove the effect of anxiety in the anxiety group (which doesn't make much sense!) The only alternative option I've found is to split the depression group into 'depression with anxiety' and 'depression without anxiety' and then run another one-way ANOVA this way. However, the 'depression without anxiety' group is far smaller than 50, and so the test wouldn't be adequately powered.
Can anyone think of a way around this that results in a suitable, adequately powered test? Essentially, I need to control for a variable in one group but not the others!
Comment: Welcome to CV. Since you're new here, you may want to take our [tour], which has information for new users. Would you consider editing the title to make it more informative?
Comment: I took the liberty of replacing the title with one that is more informative.
Answer: As you seem to have a continuous measure of anxiety, you should take advantage of it.
Instead of continuing with an ANOVA-type analysis you could consider a linear model that specifically allows for both anxiety and depression scores for each individual. If you have anxiety and depression scores for each individual (including the non-clinical group) then you could use those scores plus an interaction between anxiety and depression scores to try to characterize your outcome. If we call the anxiety score "A", the depression score "D", and use ":" to represent the interaction then you could use a linear regression model:
outcome ~ A + D + A:D

That would also cover the non-clinical group, whose members presumably have low "A" and "D" scores. As your "A" score is continuous, this could work quite well even if "D" is binary. That would allow modeling of any combination of anxiety and depression score. This linear modeling of "A" and "D" and their interaction only uses up 3 degrees of freedom, versus the 2 in your ANOVA model, so your 150 cases should still be enough even if you, say, have to do some non-linear modeling of the "A" scores with a spline.
You will, however, have to be careful when interpreting the individual "A" and "D" coefficients with an interaction in the model. The coefficient for "A" will be the association of outcome with "A" when "D" is at its reference value (or 0 if continuous), and that for "D" will be the association of outcome with "D" when your continuous measure "A" is at a value of 0. If the interaction is significant then there won't be a single value representing either of anxiety or depression. That might be more complicated than you were hoping for, but if that's the reality then that is what your audience deserves to know.
That said, I am concerned about the issues raised by @BruceET with respect to re-design of the analysis after the data have been collected. I think this type of analysis will help get around those issues, but I haven't thought fully through whether the procedure for selecting the individuals for this study might lead to some problems if you proceed this way.
Answer: Re-designing an experiment after you see the data can be a direct path to false discovery.
If you can use pre-experiment information as criteria to split the Depression group for a post hoc analysis whether the two parts of it differ significantly. If so, then your report needs to admit the difficulty and unorthodox re-design along with findings.
Here are data for a design such as yours.
set.seed(2020)
NC = rnorm(50, 100, 20)
D  = rnorm(50, 115, 30)
A  = rnorm(50, 110, 20)
x = c(NC, D, A)
g = rep(1:3, each=50)
boxplot(x ~ g, col="skyblue2", pch=20)

oneway.test(x ~ g)

        One-way analysis of means (not assuming equal variances)

data:  x and gp
F = 3.5155, num df = 2.000, denom df = 95.537, p-value = 0.03364

A "re-design" based on illegitimate use of data, can produce bogus differences.
This is an extreme case, but it is why I mentioned that splitting the Depression
group needs to be based on pre-experiment information.
D1 = sort(D)[1:20]    # smallest into D1
D2 = sort(D)[21:50]   # largest into D2
y = c(NC, D1, D2, A)
gp = rep(1:4, c(50,20,30,50))
boxplot(y~gp, col="skyblue2", pch=20, varwidth=T)

oneway.test(y~gp)

        One-way analysis of means (not assuming equal variances)

data:  y and gp
F = 26.23, num df = 3.000, denom df = 65.733, p-value = 2.843e-11

t.test(D1,D2)$p.val
[1] 1.492356e-11


Gstreamer HLS pipeline creation error

Question: I am trying to stream a HLS Stream using gstreamer 1.0. I have a filter which works
gst-launch-1.0 -v souphttpsrc location="http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8" ! hlsdemux ! tsdemux ! h264parse ! avdec_h264 ! autovideosink

But when I try to convert this into c code, it fails.
int main(int argc, char* argv[])
{
    GMainLoop *loop;
    GstElement *pipeline, *source, *demuxer, *tsdemux, *h264parse, *vdecoder, *vsink;
    GstElement *aacparse, *adecoder, *aconvert, *asink;
    GstBus *bus;
    int bus_watch_id;

    gst_debug_set_default_threshold(3);
    gst_init(&argc, &argv);
    loop = g_main_loop_new(NULL, FALSE);

    if (argc != 2)
    {
       g_printerr("Usage: %s <http stream source>\n", argv[0]);
       return -1;
    }

    pipeline = gst_pipeline_new("myApp");
    source = gst_element_factory_make("souphttpsrc", "http-src");
    demuxer = gst_element_factory_make("hlsdemux", "hls-demuxer");
    tsdemux = gst_element_factory_make("tsdemux", "ts-demuxer");
    h264parse = gst_element_factory_make("h264parse", "h264parse");
    vdecoder = gst_element_factory_make("avdec_h264", "h264decoder");
    vsink = gst_element_factory_make("autovideosink", "videosink");

    /* set the input url to the source element */
    g_object_set(G_OBJECT(source), "location", argv[1], NULL);

    bus = gst_pipeline_get_bus(GST_PIPELINE (pipeline));
    bus_watch_id = gst_bus_add_watch(bus, bus_call, loop);
    gst_object_unref(bus);

    /* add elements into the pipeline */ //next aacparse
    gst_bin_add_many(GST_BIN (pipeline), source, demuxer, tsdemux, h264parse, vdecoder,vsink,  NULL);

    gst_element_link(source, demuxer);
    // this was wrong
    /*gst_element_link_many(tsdemux, h264parse, vdecoder, vsink, NULL);*/

    /* connect demuxer and decoder on pad added */
    /*g_signal_connect(demuxer, "pad-added", G_CALLBACK(on_pad_added), vdecoder);*/

    // Correct Implementation
    gst_element_link_many(h264parse, vdecoder, vsink, NULL);

    g_signal_connect(demuxer, "pad-added", G_CALLBACK(on_pad_added), tsdemux);
    g_signal_connect(tsdemux, "pad-added", G_CALLBACK(on_pad_added), h264parse);
    g_signal_connect(demuxer, "pad-added", G_CALLBACK(on_pad_added), vdecoder);
    // Correct Implementation

    g_print ("Starting play: %s\n", argv[1]);
    gst_element_set_state(pipeline, GST_STATE_PLAYING);

    g_print ("Running\n");
    g_main_loop_run(loop);

    /* Clean up after execution of main loop */
    g_print ("Stopping Playback: %s\n", argv[1]);
    gst_element_set_state(pipeline, GST_STATE_NULL);

    g_print ("Quitting\n");
    g_object_unref(G_OBJECT(pipeline));
    g_source_remove(bus_watch_id);

    g_main_loop_unref(loop);

    return 0;
}

I compile the code using:
cc my_app.c -o my_app $(pkg-config --cflags --libs gstreamer-1.0)

And launch the application using:
./my_app http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8

I always get the following error:
hlsdemux gsthlsdemux.c:792:gst_hls_demux_stream_loop:<hls-demuxer> error: stream stopped, reason not-negotiated

Do I have to do anything differently?
Comment: try specifying your video sink instead of relying on autovideosink. You should be able to see what sink your your terminal command chooses and use it in your C program
Answer: I was able to get it working. The problem was "tsdemux" and "demuxer" have to connect at run time in "on_pad_added" method.
Answer: // this was wrong
gst_element_link(source, demuxer);
// Correct Implementation
gst_element_link(source, demuxer,NULL);
where is your void
on_pad_added (GstElement *element,
              GstPad     *pad,
              gpointer    data); function?and take a look at here.

Gstreamer HLS pipeline creation error


Absolute value inequalities with integrals

Question: I don't understand why the following makes sense. Here, $1\leq t \leq 2$:

$$
\begin{align}
\int_1^2\Big|\int^t_1 f(x)x^2 \ dx \Big|\ dt &\leq \int_1^2 \int_1^t \Big|f(x)x^2\Big| \ dxdt\\
&\leq \int_1^2 \int_1^2 \Big| f(x)x^2\Big| \ dxdt\\
&\leq \int_1^2 \int_1^2 M \ dxdt, \quad \text{where } M = \max_{1\leq x\leq2}\Big|f(x)x^2\Big|
\end{align}
$$

I don't understand either of these three inequality steps, especially why the inequality holds when $t$ is replaced with two?
Answer: The first inequality follows from
$$\left|\int_a^bf(x)dx\right|\leq \int_a^b|f(x)|dx.$$
The second inequality follows from: if $f(x)\geq 0$ in $[a,b]$, then for any subinterval $[a,c]\subset[a,b]$, we have
$$\int_a^cf(x)dx\leq \int_a^bf(x)dx.$$
The third inequality follows from:
if $f(x)\leq g(x)$ in $[a,b]$, then
$$\int_a^bf(x)dx\leq \int_a^bg(x)dx.$$


How to find the key of a song without a pitch reference?

Question: For instance, if I play the middle C or any note before a song starts, I can instantly guess the key of the song(I think this is known as RP - relative pitch).
Another trick I've used is finding out the lowest note I can sing with my voice and use it as a "reference pitch" to guess the key of a song. However, sometimes I have soar throat etc. so this is not a reliable way to find the key.
So the question here is if I have no instrument around, how can I figure out the key of a song? Can you memorise a certain note(like the middle C) and go from there or how does one train to achieve such a thing?
Comment: I don't think this question is about developing perfect pitch (but the answers there are definitely useful).
Comment: Possible duplicate of: http://music.stackexchange.com/questions/1169/is-there-a-way-to-develop-perfect-pitch  - see the answers there.
Comment: One possible cheat is if you can hear an air conditioner or other similar device: Electric devices usually hum at a consistent pitch within your electric grid (Which usually includes but can be more than the country you live in.) I attended a concert where the performer claimed that pitch is roughly Bb in the USA.
Answer: Yes, you can absolutely memorize a pitch an use that as a reference.  I only have a passable sense of relative pitch but I've been able to memorize A440.
Like anything else, memorizing a pitch requires practising and testing.  When I started out I'd listen to a recording of an A440 sine wave, then grab my (out of tune) guitar and try to tune the A string to match, then check and adjust until it was in tune.  Once I was able to get it tuned quickly, I started doing the opposite — tuning first, trying to imagine the pitch in my head, and then verifying against the recording or with a tuner.  Once you're getting it perfect every time you can stop verifying all the time and make use of it!
Comment: Nice idea. I did it with the first note of a well known tune. If I don't keep doing it every few days, the skill tends to go off pitch, so keep checking!!
Comment: Matthew is right on here, just remember that just because he did it in 2 months, if it takes you longer don't stress on it, you will get it. If you play guitar try the low E or A first depending on whats easier to sing,
Comment: @lobi Good question.  I believe it was less than 2 months.
Comment: How long did this take you? weeks, months, years?
Comment: You can also relate it to your instrument instead of or in addition to a song: As a guitarist, there was a time when I knew E this way because of all the time spent tuning the guitar. I can attest that it does go away if you stop working on it.
Answer: The way I do this is by choosing a note at the bottom of my vocal range as my reference point.  It is a very recognizable place in my vocal range because if I try to go lower, the sound quality suffers dramatically.  So you're going for the feeling and the timbre, not just recognition of the note.
If there's a string instrument in your vicinity, that could give you a clue as well.  You can get it to resonate sympathetically with certain notes.  That resonance is audible in a subtle way, and sometimes visible, too.
Comment: Doesn't your vocal range change a bit during the day or depending on your state of health? When I try to use the lower end of my voice as a reference pitch, I notice that in the morning my lowest note might be about a whole tone lower than later in the day. When I have a cold it's even more ...
Comment: Me too.  And I just noticed that the OP noticed this too -- oops!  - - -  At any rate, the fact that there's a pattern, and the fact that most tunes aren't written in keys with tons of sharps or flats, can help.  - - -  I suppose one could carry around a little circular pitch pipe, if all else fails.
Answer: No, without a pitch reference you can't tell.  But there are many ways to find a pitch reference, including "perfect pitch".
And, once you have that reference, "guessing" doesn't come into it.  You know for sure!
Answer: My solution is to hum along to the song for a minute to get the feel (vibe), and then hum one a constant note which will most likely be the root or a perfect fifth above the root.
Then play each key on your instrument whilst humming until you find a match.  Once the root is found the key will most likely be minor if its modern music.
If this fails and your song is digital run it through detection software
Free software link


Jenkins declarative pipeline expression with boolean environment variable

Question: I'm using Jenkins declarative pipeline and I want to make a conditional step depending on an environment variable, which is set according the existence of a file.
So I just want to make something like that : if Dockerfile exist, perform next stage, else don't.
To perform this I tried  :
pipeline {
    // ...
    stage {
        stage('Docker') {
            environment {
                IS_DOCKERFILE = fileExists 'Dockerfile'
            }
            when {
                environment name: 'IS_DOCKERFILE', value: true
            }
            stage('Build') {
                // ...
            }
        }
    }
}

Or :
pipeline {
    // ...
    stage {
        stage('Docker') {
            environment {
                IS_DOCKERFILE = fileExists 'Dockerfile'
            }
            when {
                expression {
                    env.IS_DOCKERFILE == true
                }
            }
            stage('Build') {
                // ...
            }
        }
    }
}

In both cases, the Dockerfile exist and it is in the workspace. I also tried with strings ("true") but everytime, the pipeline continue without executing the stage 'Build'.
Any suggestions ?
Comment: You should use a different pipeline for each project. Having said that, you can have a stage which looks if there is a dockerfile using `fileExists`, and sets a global variable. Another stage may then look at the global variable using e.g. `when { expression { IS_DOCKERFILE == true }}` or `script { if (IS_DOCKERFILE) { ... } }`
Comment: It's unclear what you are trying to achieve. Most pipelines reside in Jenkinsfile which is kept together with the other code in a repository. Assuming this is your case too, the repository either has Dockerfile or it doesn't. I can't see the point of discovering this at runtime.
Comment: This is because I'm trying to use the same pipeline for two application types : web services (which have a Dockerfile) and libraries (which doesn't have a Dockerfile). The only difference is that the library don't need to be built as docker image, so I tried to perform the last step only if the is a Dockerfile. I use a jenkins shared library so the pipeline is common (maybe bad practice)
Answer: This is because the exprsssion:
IS_DOCKERFILE = fileExists 'Dockerfile'

Creates the environment variable with boolean value as string:
$ set
IS_DOCKERFILE='false'

So the solution would be to use .toBoolean() like this:
environment {
    IS_DOCKERFILE = fileExists 'Dockerfile'
}
stages {
    stage("build docker image") {
        when {
            expression {
                env.IS_DOCKERFILE.toBoolean()
            }
        }
        steps {
            echo 'fileExists'
        }
    }
    stage("build libraries") {
        when {
            expression {
                !env.IS_DOCKERFILE.toBoolean()
            }
        }
        steps {
            echo 'fileNotExists'
        }
    }
}

Answer: As @Sergey already posted, the problem is that you're comparing a string to a boolean. See fileExists: Verify if file exists in workspace.
Besides his answer, you can compare directly to a string:
environment {
    IS_DOCKERFILE = fileExists 'Dockerfile'
}
stages {
    stage("build docker image") {
        when {
            expression {IS_DOCKERFILE == 'true'}
        }
        steps {
            echo 'fileExists'
        }
    }
    stage("build libraries") {
        when {
            expression {IS_DOCKERFILE == 'false'}
        }
        steps {
            echo 'fileNotExists'
        }
    }
}


Disable whatever :hover css effects there is when on a different media

Question: I'm not sure if this is even possible, but I'd like to throw it out there: say I have something like
.this-thing:hover {
  /* something magical */
}

in CSS. During Print Preview and Print, I would like to "disable" whatever hover effect is on .this-thing, such that even if the user is hovering over a given element when they decide they want to print the page, the effects from /* something magical */ do not appear on Print Preview or the printed media.
Is there a pure CSS solution to this?
Note that I do not want to found out what the specifics of /* something magical */ is in order to disable it during @media print.
Comment: It seems so odd to me that the print styles would inherit the hover rules! I did a quick test and it definitely shows up in the print preview. Interesting Q!
Answer: You could use @media only screen to apply the hover effects only to the :hover rules.
So you would do:
@media only screen {
    .this-thing:hover {
      /* something magical */
    }
}

Organizationally, this may be a mess to pepper @media only screen around all of your hovers, but it's one option.
Answer: The same way as you use the only and and logical selector, you can use the not to specify that the style rule should not apply to some media type:
@media not print {
    .this-thing:hover {
        /* something magical */
    }
}


Java convert Windows-1252 to UTF-8, some letters are wrong

Question: I receive data from a external Microsoft SQL 2008 database (I make queries with MyBatis). The data is encoded as "Windows-1252".
I have tried to re-encode to UTF-8:
String textoFormado = ...value from MyBatis... ;
String s = new String(textoFormado.getBytes("Windows-1252"), "UTF-8");

Almost the whole string is correctly decoded, but some letters with accents  are not.
For example:

I received this: �vila
The code above makes: �?vila
I expected: Ávila
Comment: Your variable _textoFormado_ is already a string that you simply can use in your program. Why are thinking you must encode and decode it again?
Comment: How are you retrieving the String from MyBatis? That is where you need to deal with a charset conversion from Windows-1252 to UTF-16 (Java's native String encoding). Even if you have to use `getBytes()`, you should be specifying `Windows-1252` instead of `UTF-8` in the `String` constructor since you are not dealing with UTF-8 bytes at all.
Comment: Break your line into two statements, so you can get a look at the intermediate string.  That will help you see what the source of the problem might be.
Comment: Thank. But I tried String s = new String(mistring.getBytes("Windows-1252")); but the result is the same.
Comment: Because this String have the text "Ã�vila" (it is recived from database from MyBatis) and I need "Ávila".
Answer: Obviously, textoFormado is a variable of type String. This means that the bytes were already decoded. Java then internally uses a 16-bit Unicode representation. What you did, is to encode your string with Windows-1252 followed by reading the resulting bytes with an UTF-8 encoding. That does not work.
What you need is the correct encoding when reading the bytes:
byte[] sourceBytes = getRawBytes();
String data = new String(sourceBytes , "Windows-1252");

For using this string inside your program, you do not need to do anything. Simply use it. If - however - you want to write the data back to a file for example, you need to encode again:
byte[] destinationBytes = data.getBytes("UTF-8");
// write bytes to destination file here

Comment: Use `textoFormado.getBytes("Windows-1252")` instead.  Forget about UTF-8, it does not apply in this situation, and you are not using it correctly anyway.
Comment: Thanks for answering, it have sense and it give me some ideas.  But I use MyBatis for to launch queries to the database, this return me text in type String. I tried the next code for return back, but dont coded correctly:
byte[] textBytes = textoFormado.getBytes("UTF-8");
String value = new String(textBytes , "Windows-1252");
Answer: I solved it thanks to all.
I have the next project structure:

MyBatisQueries: I have a query with a "select" which gives me the String
Pojo to save the String (which gave me the String with conversion problems)
The class which uses the query and the Pojo object with data (that showed me bad decoded)

at first I had  (MyBatis and Spring inject dependencies and params):
public class Pojo {
    private String params;
    public void setParams(String params) {
        try {
            this.params = params;
        }
    }

}

The solution:
public class Pojo {
    private String params;
    public void setParams(byte[] params) {
        try {
            this.params = new String(params, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            this.params = null;
        }
    }

}

Answer: Why not tackling the issue at a lower level: reading the String in proper encoding from your database.
Most JDBC connection-string or URIs support the property characterEncoding.
So in you Microsoft SQL Server case you could have for example jdbc:sqlserver://localhost:52865;databaseName=myDb?characterEncoding=utf8.
Then each String column should be read in the specified encoding without the need to (re-)convert it manually to it.
See also:

JDBC character encoding
Problems reading/writing UTF-8 data in MySQL from Java using JDBC connector 5.1


Can't get SF Symbol erase layer imported from SF Symbols to Xcode?

Question: I created a custom SF Symbol. Pretty straightforward horse head with transparent eyes.
Trying to get the eyes to be transparent regardless of what rendering mode is used.
I used the "erase" color for the eye layer and a solid color for the head.
I export it as SF Symbol 4 and import it to Xcode.
The symbol looks right in SF Symbols, but is missing the "erase" layer in Xcode for all rendering modes; color, hierarchical and monochrome.
Here is how I am implementing the custom symbol. Where tab.iconName = "horse" in this case.

<code>        HStack {
            Image(tab.iconName).symbolRenderingMode(selectedTab == tab ? .monochrome : .multicolor)
                .font(.system(size: 20))
            if(selectedTab == tab) {
                Text(tab.title)
                    .font(.msTypographyButtonLarge())
                    .foregroundColor(selectedTab == tab ? Color.theme.accentPrimary: Color.theme.textDisabled)
            }
        }
        .foregroundColor(selectedTab == tab ? Color.theme.accentPrimary: Color.theme.textDisabled)
        .padding(.vertical, 8)
        .padding(.horizontal, selectedTab == tab ? 26 : 0)
        .background(selectedTab == tab ? Color.theme.buttonSecondary : Color.clear)
        .cornerRadius(40)
    }
</code>
Comment: Just curious, did you watch https://developer.apple.com/videos/play/wwdc2021/10250/? I haven't tried it
Answer: When you have multiple subpaths that are erased, only one gets processed and the others are ignored.


How do you automate an image carousel using HTML, JS, & CSS?

Question: I'm not very good at JS, so I had to suffer through a video explaining how to make an image carousel using HTML, CSS, and JS. I wanted to be able to automate it but could not figure out how to do so, due to my inexperience. If someone could explain how to modify this code to be able to take both manual inputs via the arrows and automatically cycle to the next image, I would greatly appreciate it.
This is the code for the manual button slider (HTML, JS, CSS)

            <button class = 'backButton' data-slider-button = 'previous'></button>
            <button class = 'nextButton' data-slider-button = 'next'></button>

const buttons = document.querySelectorAll('[data-slider-button]')

buttons.forEach(button => {
    button.addEventListener('click', () => {
        const offset = button.dataset.sliderButton === 'next' ? 1 : -1
        const slides = button
        .closest('[data-slider]')
        .querySelector('[data-slides]')

    const activeSlide = slides.querySelector('[data-active]')
    let newIndex = [...slides.children].indexOf(activeSlide) + offset
    if  (newIndex < 0) newIndex = slides.children.length - 1
    if (newIndex >= slides.children.length) newIndex = 0

    slides.children[newIndex].dataset.active = true
    delete activeSlide.dataset.active
    })
})

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.slides {
    width: 100%;
    height: 100vh;
    position: relative;
}

.slide {
    position: absolute;
    inset: 0;
    opacity: 0;
    transition: 0.8s opacity ease-in;
    transition-delay: 0.8s;

}

.slide[data-active] {
    opacity: 1;
    transition-delay: 0s;
    z-index: 1;
}

.slide > img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}

.backButton {
    position: absolute;
    width: 24px;
    height: 45px;
    top: 50%;
    left: 50px;
    transform: translate(0%, 50%);
    border: none;
    background: url('/Images/Left Arrow.png');
    z-index: 2;
}

.backButton:hover {
    cursor: pointer;
}

.nextButton {
    position: absolute;
    width: 24px;
    height: 45px;
    top: 50%;
    right: 50px;
    transform: translate(0%, 50%);
    border: none;
    background: url('/Images/Right Arrow.png');
    z-index: 2;
}

.nextButton:hover {
    cursor: pointer;
}

Comment: use setinterval in js
Answer: You can use the below code to make an automatic image slider. Or change your js code and set setTimeout() function.

let slideIndex = 0;
showSlides();

function showSlides() {
  let i;
  let slides = document.getElementsByClassName("mySlides");
  let dots = document.getElementsByClassName("dot");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}
* {box-sizing: border-box;}
.mySlides {display: none;}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active {
  background-color: #717171;
}

/* Fading animation */
.fade {
  animation-name: fade;
  animation-duration: 1.5s;
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .text {font-size: 11px}
}

Automatic Slideshow

Change image every 2 seconds:

1 / 3

Caption Text

2 / 3

Caption Two

3 / 3

Caption Three


Python package for SMOTEBoosting algorithm

Question: I am looking for a Python package that implements the SMOTEBoosting algorithm. But I only find SMOTE in imbalanced-learn.
Comment: `SMOTE-Boost` is an open issue on `imblearn` (see [issue #105](https://github.com/scikit-learn-contrib/imbalanced-learn/issues/105)). Contributions are welcome!
Answer: Find here an implementation of SMOTEBoost based on sklearn's AdaBoost API.
Note looking at the source, this library supports binary problem only
...
if minority_target is None:
            # Determine the minority class label.
            stats_c_ = Counter(y)
            maj_c_ = max(stats_c_, key=stats_c_.get)
            min_c_ = min(stats_c_, key=stats_c_.get)
            self.minority_target = min_c_
        else:
            self.minority_target = minority_target
....


Replacing Diacritics in an Array with Google Apps Script

Question: We're trying to replace all Diacritics in a sheet with their more database-friendly counterparts. I want to be able to apply the solution found here (Remove accents/diacritics in a string in JavaScript) to an Array.
We've already visited the topic on "Remove accents/diacritics in a string in Javascript" and the solution works great for one cell. However, when I try to do it with my current code, it only changes one value and pastes it to the whole array. What am I doing wrong?
(Rest of code is visible in link)
function removeDiacritics () {
  var range = "A2:B3";
  var array = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Cleaner").getRange(range).getValues();
  var base = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Cleaner").getRange(range);
  var newArray = [];

  for(var row=0;row<array.length;row++){
    for(var i=0;row<array[row].length;i++){

    var newText = array[row][i].replace(/[^\u0000-\u007E]/g, function(a){
      return diacriticsMap[a] || a;
    });
    newArray.push(newText);
  }
  }

      base.setValue(newArray);
}

Comment: I thought that your script might have been miscopied. Because `for(var i=0;row<array[row].length;i++){` should be `for(var i=0;i<array[row].length;i++){`. How about this? And Can you provide a sample values of `array` for replicating `when I try to do it with my current code, it only changes one value and pastes it to the whole array.`?
Answer: Answer:
You are iterating through the incorrect counter variable in your nested loop.
Fix:
In your nested loop, in order to change the element of the array which is being compared, you need to change:
for(var row=0;row<array.length;row++){
  for(var i=0;row<array[row].length;i++){
    // code
  }
}

to:
for(var row = 0; row < array.length; row++){
  for(var i = 0; i < array[row].length; i++){
    //code
  }
}


Como Enviar dados de localStorage via AJAX para PHP e salva-los em um arquivo HTML

Question: Quero enviar os dados salvos no LocalStorage com PHP para um arquivo ou para um banco de dados não necessariamente precisa ser código PHP preciso de alguma solução para isso

Likes

<button name="clique" class="btn btn-primary" id="like" type="button">
Likes  0
</button>

Data e horário do último like:

Answer: Opa, então, não sei se entendi muito bem a sua necessidade, mas para você enviar esses dados salvos no localStorage, ou qualquer outro dado, é bem simples utilizando AJAX.
$.ajax({
    method: 'POST', // seu método pro backend
    data: {
       dado: 'qualquer-dado',
       likes: localStorage.likes
    }, // seus dados a serem passados, que podem ser o que você quiser
    url: 'seu-backend.php',
    success: () => alert('Dados enviados com sucesso!'), // só entra aqui se a requisição tiver sucesso
    error: () => alert('Algum erro ocorreu') // entra aqui se tiver algum erro, url errada etc
})

Assim você consegue enviar os dados para o seu backend ai e fazer sua inserção no banco de dados, etc....
Também há outras formas se você não quiser utilizar ajax, pode botar os dados do localStorage dentro de um form e dar submit, as possibilidades são diversas.
Espero ter ajudado!!
Comment: Obrigado! Mas Como faço para colocar dentro do form e dar submit?
Comment: Digamos que você tem um form, e nele um input esperando receber esse valor, é simples: `$('seu-input').value( localStorage.likes )`, e pronto, ta no seu form. Se você quiser isso de forma automática sem a necessidade do user clicar em submit, pode dar um `$(seu-form).submit()`, mas ai não tem nem pq não usar ajax na minha opiniao
Comment: como faço para receber os dados lá do código acima?
Comment: Quais dados? Se forem os do `localstorage`, como mencionei acima, é só uma questão de relacionar chave e valor e ler eles no seu backend
Comment: Sim são os do localstorage queria saber como poderia pegar eles no backend
Comment: Mano se você fizer o que eu falei na resposta, você vai estar fazendo um `POST/GET` na url que passou como parametro, e na respectiva page no backend é do mesmo jeito: `$_POST['likes']` etc.. daí você consegue obter eles e fazer oq deseja


Cannot set menu link content field values in *links.menu.yml

Question: I added a field to the menu_link_content entity, but am unable to set the value of this field in my my_module.links.menu.yml.
Here is my hook_entity_base_field_info:
/**
 * Implements hook_entity_base_field_info_alter().
 */
function my_module_admin_menu_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() != 'menu_link_content') {
    return;
  }

  // Create the base field definition for the allowed roles. This field will
  // reference user entities.
  $fields['my_module_admin_menu__show_role'] = BaseFieldDefinition::create('entity_reference')
    ->setName('my_module_admin_menu__show_role')
    ->setTargetEntityTypeId('menu_link_content')
    ->setLabel(t('Roles able to see the menu link'))
    ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
    ->setSetting('target_type', 'user_role')
    ->setDisplayOptions('form', [
      'type' => 'options_buttons',
      'weight' => 0,
    ]);
}

In my my_module.links.menu.yml, I provide a menu link like so:
my_module_admin_menu.article:
  title: 'Article'
  menu_name: admin-per-user-role
  url: internal:/node/add/article
  parent: my_module_admin_menu.create
  bundle: menu_link_content
  my_module_admin_menu__show_role:
    settings:
      target_type: user_role
      handler: default
    target_id:
      - authenticated

The link shows up, but doesn't show the field:

When a link is added via the menu UI, the field is shown:
Answer: Menu links discovered in *.links.menu.yml are not menu link content entities and therefore don't contain the field you have added to the entity. If you want to fill this field with data programmatically, create an instance of the entity:
$link = MenuLinkContent::create([
  'title' => 'Article',
  'menu_name' => 'main',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'entity:node/1']],
  'custom_field' => 'custom content',
]);
$link->save();

The content of *.links.menu.yml seems a bit odd. The title field is the only required value and you can see that the link is discovered and the title is displayed in the screenshot. The other values are optional. Check the documentation about which values you can use in this file https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links

The field seems to be for some kind of access control. You shouldn't do this in the menu link. Instead control the permissions of the target. Menu items are only displayed for users who can access the target.


is it possible to have double nested input tag arrays in html?

Question: I'm wondering before I attempt to refactor my page if its possible to have a double nested input array in html. I have an 8X5 group of elements in a form and it would be nice for me to be able to parse it using an array of arrays...something like
    <input type="text" name="list[][]" /><input type="checkbox" name="list[][]" />

and so on
Comment: What is your server processing language?  I believe PHP can handle this.
Comment: Darrell: im using php. What im wondering is if $_POST['elem_name'] would be an array of arrays or if it would be garbage.
Answer: You are going to need to supply indexes into the first part of each field or else there is nothing to nest, and if it did work, it wouldn't look like a grid on the other end:
Row 1:
 name="list[0][]"

Row 2:
 name="list[1][]"

etc.
Finally, your server needs to support this as PHP and Rails do out of the box. I am not sure about other server technologies. For an example, the following HTML when posted to PHP:
<form action="post.php" method="POST" accept-charset="utf-8">
  <input type="text" name="list[0][]" value="1" />
  <input type="text" name="list[0][]" value="2" />
  <input type="text" name="list[0][]" value="3" />

  <input type="text" name="list[1][]" value="4" />
  <input type="text" name="list[1][]" value="5" />
  <input type="text" name="list[1][]" value="6" />

  <input type="text" name="list[3][]" value="7" />
  <input type="text" name="list[3][]" value="8" />
  <input type="text" name="list[3][]" value="9" />

  <input type="submit" name="Send" value="Send" id="Send" />
</form>

If in the PHP the following code exists:
<?php print_r($_POST['list']); ?>

The output is:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [3] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
        )

)

Comment: So you are just giving the fields names that have a number. You are faking the functionality, it's not really supported by HTML4.
Comment: I updated my answer to provide an example in PHP. @voyager, I am not really faking anything since the fields are valid HTML4 names and its up to the server technology to support it.
Comment: @Doug Neiner: What I tried to say was that HTML doesn't have a native way of sending a multidimensional array, you have to fake it by either pickleing it into one variable or using one variable per dimension.
Comment: so what if i am? I'm just trying to make it a little more elegant to do my php code on the other end of the form :)
Comment: Is there any possibility to do same in ASP.NET MVC? or is there any other alternatives?
Comment: Can you use strings instead of numbers inside the `[]`?
Answer: HTML allows you to have several inputs with the same name, which are sent to the server through POST or GET as a comma separated array, which most (all?) server side languages recognize as a native array.
There is no native way of making a multidimensional array with pure HTML without you rolling something yourself with javascript.
Comment: PHP does not recognize fields with the same name as an array. In fact, it will only return the last defined value. `d=1&d=2&d=3` when retrieved with `$_GET['d']` would return `"3"`
Comment: @Doug Neiner: I've never used PHP for anything bigger than a `hello, world`, so I assumed it worked like ASP, Python, Ruby and (I think) Perl.


How can I know the correct keys of the songs my band have to play?

Question: I used to look at tunebat.com, until my guitarist told me most of the keys there are wrong. And here are two examples of wrong keys, according to him:
https://tunebat.com/Info/Soul-Man-Live-Version-The-Blues-Brothers/5z2F9FkKdhd9HOSTI1GxRq
https://tunebat.com/Info/Sweet-Home-Chicago-The-Blues-Brothers/5DjnapHOsR30xp0MJaj4u9
Is the guitarist wrong? If not, where can I find the correct keys then?
Comment: Correct key? What is that? There is a key that a number may have been recorded in, but when there are several versions by different artists - or even re-recordings by the same artist years later, the key may well be different.Generally speaking, the correct key will be the one the vocalist is happy with, and if there are 3 or 4 harmonies too, their range needs to be considered.  f you are talking about a particular version of a particular song, do like a lot of us do. listen to it, and figure out the key for yourself. Soul Man says A, but it's played there in E. Don't believe any but yourself!
Comment: Sadly, so is SHC - says A, but in E With 3 chord wonders, it's very simple to work out key, and chords. Don't believe anyone needs telling what they are - especially erroneously!
Comment: The key of a piece of music isn't an entirely objective thing; sometimes people might disagree on what the key is. And yet those people could still all play the song well if they play the right notes (which you can do independently of knowinglanguages the key). Can you clarify why you need to know a key?
Answer: You're not going to like the answer.
You should be learning to play songs in different keys.
Maybe not every song in every key, but being able to play several songs in several keys, especially several of the common keys associated with that song, will make you that much more hirable.
Comment: Absolutely true! Over the years I've been really fed up with some guys who 'only play this song in this key'. And cannot change. +1.
Comment: That's why I practice Bach's prelude in Cis major in all 12 keys.
Answer: There is (at least in every band I have played in), only one rule. Play in a key that is comfortable for the singer. If this make the instrumental solos too awkward, transpose for the break and then back.
One must be able to play in different keys even for the same singer on different days.
The only time I played in a fixed key was when I had to sight-read some piece (and sort of hint to the rest of the players what the chord changes were.) After practicing a few days (by myself), I'd then adjust the keys to the rest of the band.
Answer: For starters, absolutely do not trust any websites blindly. They tend to put a lot of (popular) music in the "wrong key" either to make it easier to play (conunterintuitively, mostly when it's a harmonically simple song), or just because they messed up. This problem ravages guitar tablature sites in particular.
To solve this, I recommend listening to whatever recording your source material is (e.g. Bing Crosby's "White Christmas" recording from 1942) and determining the key directly from that audio. Other options include simply checking a bunch of websites for independent verification (which could still end up being wrong) or learning to play the song in all 12 keys. I find that checking piano sites tends to be more fruitful than guitar sites, for multiple reasons that I'll not explain here. (the worst kind of site has to be ukulele tab sites; they post songs in approximately three of the twelve keys, nearly everything else is transposed)
Note that for some songs, there really isn't any correct key. Take Happy Birthday, for example. What key is that in? (Bonus points if you say "all of them simultaneously") Or "The Star Spangled Banner"? Or the "shave and a haircut" bit?
And if your band or you wants to play in a certain key for the song, then do that, whatever the reason may be. Transposition time.
Comment: Agree all along. However, therre are certian numbers that seem to stay in the same original key. Usually guitar driven songs, using particular open chords/strings. Sweet Home Alabama - never played it in anything but 'start on D' (not saying what key!) with any band. Beethoven's 5th always starts in Cm (!), etc.
Comment: @Tim Very true. You'd think it would be that way for almost all popular music in D, since D is a pretty easy key for piano and guitar, but no, I've heard "Human Nature" in C on both instruments! I've no idea why, since D, A, C, and G is about as simple as it gets... And the converse, "Bohemian Rhapsody" in E major and also once in G major, both times with a capo! I mean, you're just going to play all the chords anyway... :) But yeah, some songs seem to be permanently in one key (though nothing is sacred to vocalists, apparently).
Answer: Ever since sheet music for popular songs has been available (which is WAY before sound recording was developed) performers have had to come to terms with the fact that what they heard in the concert hall on Saturday is very often NOT going to match up with what they buy at the music shop on Monday.   It might just be in a different key, it might be a substantially different arrangement.   If you want to copy a particular performance or recording, a published version will probably help, but you'll still have work to do!
As to online resources, let's just say that somre are more reliable than others, in all respects :-)


PIVOT with selected MONTH()

Question: How can I pivot for a column with dates which is MONTH as the parameter?
Example:
Data:
|-----------------------------------|
| def_kstnr | def_zeit | def_datum  |
|-----------------------------------|
| 100       | 3.2      | 2011-11-02 |
| 110       | 2.8      | 2011-02-03 |
| 120       | 5.4      | 2011-11-04 |
| 130       | 2.4      | 2011-08-05 |
| 140       | 4.9      | 2011-09-06 |
| 150       | 1.5      | 2011-10-07 |
| 160       | 2.6      | 2011-12-08 |
|-----------------------------------|

Query:
SELECT
    def_kstnr,
    [1] AS Jan,
    [2] AS Feb,
    [3] AS Mrz,
    [4] AS Apr,
    [5] AS Mai,
    [6] AS Jun,
    [7] AS Jul,
    [8] AS Aug,
    [9] AS Sep,
    [10] AS Okt,
    [11] AS Nov,
    [12] AS Dez
FROM
(Select
def_kstnr,
def_zeit,
 MONTH(def_datum) as TMonth
  from
    dbo.def) source
PIVOT
(
    SUM(def_zeit)
    FOR TMonth
    IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth

Result should look like this if the parameter month = 2 (February):
| def_kstnr  |  Feb |
   110          2.8

and if the parameter month = 11 (November)
| def_kstnr  |  Nov |
   100          3.2

I'm already googling, but I don't know what is the keyword for this my case. I haven't find it yet. Thank you..
Comment: You would have to use dynamic SQL - any particular query always produces a result set with a fixed "shape" - the number of columns, their *names* and types. On the other hand, changing a column heading within an *application* or a *report* is usually trivial - does this have to be done in *SQL*?
Comment: What is your RDBMS?
Answer: If you're using SQL Server, you can create a dynamic sql like this
DECLARE @Month Int = 11,
        @MonthName VARCHAR(20),
        @Sql NVARCHAR(MAX)

SET     @MonthName = CONVERT(VARCHAR(3), DATEADD(Month, @Month, -1), 107)
SET     @Sql = N'   SELECT  def_kstnr,
                            def_zeit AS ' + QUOTENAME(@MonthName) + '
                    FROM    DataTable
                    WHERE   MONTH([def_datum]) = @Month'

EXEC sp_executesql @Sql, N'@Month INT', @Month = @Month

You can add your SUM(def_zeit) and GROUP BY def_kstnr to the dynamic sql if that is the result you are after.. hard to tell by your expected result

PIVOT with selected MONTH()


ActionMailer randomly changing Message-ID

Question: I'm trying to track my message_id so that I can reply to track replies via the In-Reply-To field
However, it appears that the message_id that is set by ActionMailer randomly gets changed to a different ID?
I check the logs and they are not the same as the message_id that is set by action mailer.
<code>message_mail = MessageMailer.campaign(message, message_user)
message_mail.deliver_later
message_user.message_reply_to = message_mail.message_id
</code>
Any idea why ActionMailer would change the message_id?
Comment: Referring [this](http://www.rubydoc.info/github/mikel/mail/Mail%2FMessage%3Amessage_id%3D), which part of your `message_id` is getting changed ?
Comment: Instead of 'email@example.com' it might end up as 'email@example.com' (essentially just a different random UUID)

I believe this is a rails bug,btw.  It does not happen if I use `deliver_now` only `deliver_later`

I've [filed this bug on the rails project](https://github.com/rails/rails/issues/21220), once I get a response there I will update this SO post.
Comment: O i see. Thanks for giving the link here.
Answer: Turns out, this is a serialization / cloning bug in ActionMailer.
https://github.com/rails/rails/issues/21220


Is the Workflow module a Symfony component?

Question: In Drupal 8.5, is the Workflow module a component from Symfony?
I ask because I thought it might help me to learn the basics from the Symfony Workflow component, but looking at the core directory and the composer.json file I saw this.
"symfony/class-loader": "~3.4.0",
"symfony/console": "~3.4.0",
"symfony/dependency-injection": "~3.4.0",
"symfony/event-dispatcher": "~3.4.0",
"symfony/http-foundation": "~3.4.14",
"symfony/http-kernel": "~3.4.14",
"symfony/routing": "~3.4.0",
"symfony/serializer": "~3.4.0",
"symfony/translation": "~3.4.0",
"symfony/validator": "~3.4.0",
"symfony/process": "~3.4.0",
"symfony/polyfill-iconv": "^1.0",
"symfony/yaml": "~3.4.5",

In the replace section, I noticed the following line.
"drupal/workflows": "self.version",

Comment: No, I think they are different
Answer: No, the Workflow module is not a Symfony component.
As for what you found, the first list are the Drupal core dependencies, which include its dependencies from Symfony components.
Under the replace section, you just find a list of Drupal core modules. You can understand they are modules because they are listed as drupal/<module machine name>, while the Workflow component would be listed as symfony/workflow.


head of linked list fails to point to old element

Question: I have this code and I try to create a singly-linked list. However everytime I add a new element at the front, my code fails to point the element at the front of the list to the old element.
#include <stdio.h>
#include <stdlib.h>

struct list {
    struct node* head;
};

struct node {
    int data;
    struct node* next;
};

struct list* list_init(void) {
    struct list *l;
    l = malloc(sizeof(struct list));
    if (l == NULL) {
        return 1;
    }
    else {
        l -> head = NULL;
        return l;
    }

}

struct node* new_node(int num) {
    struct node *n;
    n = malloc(sizeof(struct node));
    if (n == NULL) {
        return NULL;
    }
    else {
        n -> data = num;
        n -> next = NULL;
        return n;
    }
}

int list_add_front(struct list* l, struct node* n) {
    if (l == NULL) {
        return 1;
    }
    else {
        if (l -> head == NULL) {
            // Make sure that the list head points to this node.
            l -> head = &n;
        }
        // Make list head point to new node;
        // Make new node point to old head node;
        else {
            struct node* old_head = l -> head;

            n->next = old_head;

            l -> head = &n;
        }
    }
}

int main()
{
    struct list* l = list_init();
    struct node* nn = new_node(2);

    printf("l address: %p \n", l);
    printf("n address: %p \n", nn);

    list_add_front(l, nn);
    int* datapoint = (l->head)->data;

    printf("List head data at first: %i, on address %p. \n\n", *datapoint, datapoint);

    struct node* nn2 = new_node(12);

    printf("l address: %p \n", l);
    printf("nn2 address: %p \n", nn2);

    list_add_front(l, nn2);
    int* datapoint3 = (l->head) -> data;
    printf("List head data is now: %i, on address %p. \n\n", *datapoint3, datapoint3);

    struct node* nextnode = (l->head) -> next;
    printf("it points to address %p, which is the list itself. why?? . \n\n", nextnode);

}

I do not know why. It goes wrong in list_add_front I believe.
I do not understand how it links to the address of the list struct itself, since printing the pointer seems to give that away.
Here is the executable code online, for convienence maybe: https://onlinegdb.com/rk7_meISN
Thanks in advance all.
Comment: You should have gotten a number of warnings from your compiler.  Fix those first.
Answer: As dbush pointed out, you have a number of warnings that need to be fixed. Be sure to compile with -Wall
In particular, in list_add_front, change all &n to n. This should fix the problem.  The compiler would/should flag this.
With &n this is a pointer to a pointer of struct node and not a pointer to struct node [which is what you want]. Using &n points to the address of n, which is on the program stack and not what n points to.
Here is an annotated and fixed version. It uses:
#if 0
// original code ..
#else
// fixed code ...
#endif

#include <stdio.h>
#include <stdlib.h>

struct list {
    struct node *head;
};

struct node {
    int data;
    struct node *next;
};

struct list *
list_init(void)
{
    struct list *l;

    l = malloc(sizeof(struct list));
    if (l == NULL) {
#if 0
        return 1;
#else
        return l;
#endif
    }
    else {
        l->head = NULL;
        return l;
    }

}

struct node *
new_node(int num)
{
    struct node *n;

    n = malloc(sizeof(struct node));
    if (n == NULL) {
        return NULL;
    }
    else {
        n->data = num;
        n->next = NULL;
        return n;
    }
}

int
list_add_front(struct list *l, struct node *n)
{
    if (l == NULL) {
        return 1;
    }
    else {
        if (l->head == NULL) {
            // Make sure that the list head points to this node.
#if 0
            l->head = &n;
#else
            l->head = n;
#endif
        }

        // Make list head point to new node;
        // Make new node point to old head node;
        else {
            struct node *old_head = l->head;
            n->next = old_head;
#if 0
            l->head = &n;
#else
            l->head = n;
#endif
        }
    }
}

int
main()
{
    struct list *l = list_init();
    struct node *nn = new_node(2);

    printf("l address: %p \n", l);
    printf("n address: %p \n", nn);

    list_add_front(l, nn);
#if 0
    int *datapoint = (l->head)->data;
#else
    int *datapoint = &l->head->data;
#endif

    printf("List head data at first: %i, on address %p. \n\n",
        *datapoint, datapoint);

    struct node *nn2 = new_node(12);

    printf("l address: %p \n", l);
    printf("nn2 address: %p \n", nn2);

    list_add_front(l, nn2);
#if 0
    int *datapoint3 = (l->head)->data;
#else
    int *datapoint3 = &l->head->data;
#endif

    printf("List head data is now: %i, on address %p. \n\n",
        *datapoint3, datapoint3);

#if 0
    struct node *nextnode = (l->head)->next;
#else
    struct node *nextnode = l->head->next;
#endif

    printf("it points to address %p, which is the list itself. why?? . \n\n",
        nextnode);

#if 1
    return 0;
#endif
}

Comment: Ah, woah! That really worked and it makes sense now. Thanks a lot, really clear explanation and feedback . Have a nice day.
Comment: @concurrencyboy Your link just goes to the site homepage. The best way for you to get help is to post a question on SO [as you've done before]. Many other people can respond with help. After you do that, if you still need more help, you can send me a message here with the link to your SO question page.


auto.arima Not Minimizing AIC

Question: I simulated a MA(3) process using:
set.seed(66)
w <- rnorm(100,0,3.6)
p1 <- 0.4; p2 <- -0.2; p3 <- 0.3;
ma3 <- w[1]
ma3[2] <- w[2] + p1*w[1]
ma3[3] <- w[3] + p1*w[2] + p2*w[1]
for (t in 4:100) ma3[t] <- w[t] + p1*w[t-1] + p2*w[t-2] + p3*w[t-3]

Running auto.arima on the time series gives:
> auto.arima(ma3)
Series: ma3
ARIMA(0,0,1) with zero mean

Coefficients:
         ma1
      0.3854
s.e.  0.1152

sigma^2 estimated as 14.41:  log likelihood=-275.39
AIC=554.77   AICc=554.89   BIC=559.98

However, fitting the series to a MA(3) model gives a lower AIC:
> arima(ma3, order=c(0,0,3))

Call:
arima(x = ma3, order = c(0, 0, 3))

Coefficients:
         ma1      ma2     ma3  intercept
      0.4039  -0.0836  0.5125     0.2752
s.e.  0.1158   0.0905  0.1039     0.6078

sigma^2 estimated as 11.2:  log likelihood = -264.67,  aic = 539.34

I'm not sure what's going on. I thought that auto.arima selected the best model based on the AIC.
Comment: Rob's answer shows that this is a statistical issue, specifically relating to the invertibility of the MA(3) model. I vote to keep open.
Answer: By default, auto.arima uses a stepwise search and there is no guarantee that it will find the best model. You can do a more complete search by setting stepwise=FALSE in the call. Like this:
> library(forecast)
> auto.arima(ma3,stepwise=FALSE)

Series: ma3
ARIMA(3,0,0) with zero mean

Coefficients:
         ar1      ar2     ar3
      0.3203  -0.0556  0.2816
s.e.  0.0976   0.1025  0.0984

sigma^2 estimated as 13.74:  log likelihood=-271.57
AIC=551.15   AICc=551.57   BIC=561.57

However, this still hasn't found an MA(3) model. That is because the fitted MA(3) model is almost non-invertible.
> fit <- Arima(ma3, order=c(0,0,3))
> plot(fit)

Note the root lies almost on the unit circle. auto.arima will not consider models that are close to the stationarity or invertibility boundary, as they are typically numerically unstable.
Comment: Thanks for the answer. That helps a lot. Also, thanks for the package and the book. I'm new to this area, and the resources you've created are very helpful.
Comment: Does setting `stepwise=FALSE` make `auto.arima` consider **all** submodels until the maximum orders? I.e. if we consider only ARMA($p,q$) (forget SAR, SMA for simplicity), setting `stepwise=FALSE` will mean a full search over the $2^{p+q}$ model space? The help file of `auto.arima` is not explicit on that.
Comment: Yes. Fully explained in the JSS article.
Comment: Article?  Book?  huh?
Comment: Article: https://www.jstatsoft.org/article/view/v027i03. Book: http://otexts.org/fpp

auto.arima Not Minimizing AIC