Visualizing the folly of fitting random slopes for variables that don't vary within groups

Question: Sometime I encounter wrong mixed-models that run without warning. By wrong, I mean logically nearly impossible. Think of a cross-level interaction that is set by the software syntax to AGAIN vary across the levels of a grouping variable.
Is there a visual (i.e., plot) to demonstrate the folly of fitting random slopes for variables that don't vary within grouping variables?
# R code for 2 wrongly defined mixed-models that run fine:

library(lme4)

hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')

m1 <- lmer(math ~ ses+sector + (ses:sector | sch.id), data = hsb)

m2 <- lmer(math ~ ses +  (sector | sch.id), data = hsb)

Comment: Try plotting the raw data first for the non-varying variables by cluster. You will get a single line. That should be enough to prevent you from estimating a nonsensical model.
Comment: Try plotting the raw data first for the non-varying variables by cluster. You will get a single line. That should be enough to prevent you from estimating a nonsensical model.
Comment: @ErikRuzek, you mean like `hsb10 <- subset(hsb, sch.id %in% unique(sch.id)[1:10]);

ggplot(hsb10) + aes(x=size, y = math) + geom_path()+
  facet_wrap(~sch.id)`
Answer: I think it makes sense here to step back and simplify things. For the purpose of this answer we can think about this model:
Y ~ X + (X | G)

...in two scenarios: where X varies at the individual / unit level, and where X varies at the group level.
The motivation for fitting random slopes often arises out of the following. We have a study where we measures individuals, and we are interested in some fixed effect, ie slope of a variable. It could be the same variable measured over time, or it could be the response to different treatment levels of a variable, for example. If we had only one individual we would simply take measurements and think about a plot such as this:
set.seed(1)
X <- 1:20
Y <- 3 + X + rnorm(20, 0, 3)
ggplot(data.frame(Y, X), aes(y = Y, x = X)) + geom_point() + geom_smooth(method = 'lm', se = FALSE)

Our interest would then be in the slope of the fitted line, from the model:
> lm(Y ~ X) %>% coef()
(Intercept)           X
   3.062716    1.067789

Now, when we have multiple individuals, we don't want to fit seperate models for each individual, as discussed here: Difference between t-test on betas from individual regressions vs linear mixed modeling
So we want random intercepts, where each individual will have the same fixed effect (slope) for X, but a different intercept. Moreover, we naturally would expect each individual to have their own slope, so we want random slopes for X:
set.seed(1)
n.group <- 10
dt <- expand.grid(G = 1:n.group, X = 1:20)
dt$Y = 1

X <- model.matrix(~ X, dt)

myFormula <- "Y ~ X + (X | G)"

foo <- lFormula(eval(myFormula), dt)
Z <- t(as.matrix(foo$reTrms$Zt))

betas <- c(3, 1)
b1 <- rnorm(n.group, 0, 3)   # random intercepts
b2 <- rnorm(n.group, 0, 0.5)   # random slopes

b <- c(rbind(b1, b2))

dt$Y <- X %*% betas + Z %*% b + rnorm(nrow(dt), 1)

dt$G <- as.factor(dt$G)
ggplot(dt, aes(y = Y, x = X, colour = G)) + geom_point() + geom_smooth(method = 'lm', formula= y ~ x, se = FALSE)

All is good. This is a classical plot to illlustrate random slopes and intercepts. Each line represents one individual / group and has it's own intercept and slope. Note that this is not plotted from the output of a mixed model, but rather from the data itself. We fit a mixed model in order to estimate the parameters, in the case of the random effects, the variance and covariance of the random intercepts and slopes.
Now, if we let X be a group-level predictor:
dt$X <- as.numeric(dt$G) / 4
X <- model.matrix(~ X, dt)

dt$Y <- X %*% betas + Z %*% b + rnorm(nrow(dt), 1)
ggplot(dt, aes(y = Y, x = X, colour = G)) + geom_point() + geom_smooth(method = 'lm', formula= y ~ x, se = FALSE)

We can immediately see that each group is a vertical accumulation of points for each X value. So there is no slope for each group / individual.
This is why it does not make sense to fit random slopes for a variable that only varies at the group level. If we try to fit a model with random slopes to such data, it will almost certainly not converge, or converge to a singular fit. I say almost certainly, because as noted in the OP, we do sometimes see such model that do converge. This is why it is necessary for analysts to think about what they are doing. Plotting the data is a very good first step in many analysis tasks and can help in avoiding mistakes, and generally guide the analysis in the right direction.
Comment: Rob, I'll ask a question.
Comment: Thank you Rob! By the way, if `m <- lmer(math ~ ses*sector + (ses:sector | sch.id), data = hsb)` is a legitimate model? what is meaning of its random part? (Recall `ses` is a level-1 predictor and `sector` a level-2 predictor making their combinations a *cross-level interaction*)
Comment: Provided that the interaction varies by school, which it should since it includes a variable that varies by school, then I don't see a problem with that, other than, as I mentioned in another answer, allowing the interaction to vary by school, but not `ses` does not make much sense because they are linked (you can't change an interaction independenty of the main effects and vice versa), so if you insist on having random slopes for the interaction I think you should also include random slopes for `ses`.  Of course whether the data supports either model, is another matter entirely.
Comment: Thanks, Rob, my problem is conceptual. See, `ses:sector` is a cross-level interaction. Therefore, `ses` as a level-1 *effect* has to vary across schools but `sector` itself is a level-2 predictor and I can't understand how we can have `sector` vary as well?! In other words, a cross-level interaction cannot be taken to be random in a 2-level model.
Comment: ... You say provided that `ses:sector` varies by school (I think it can't). Because in each school `sector` is a constant. So, it is not until we get the `math ~ ses` relation across all schools that we can be talking about their cross-level interaction.
Comment: I know. But the interaction is literally the multiplication of the two variables, so it too will vary by school. Say you have `sch <- c(1,1,2,2) ; ses <- c(1,2,3,4) ; sec <- c(1,1,2,2)`, then the interaction `ses:sec` is literally `ses*sec` which will be `1 2 6 8`, which varies by school. This isn't really part of the question and answer above so we really shouldn't be discussing it in these comments. Feel free to ask another question if it's not clear.
Comment: Rob, [HERE](https://stats.stackexchange.com/questions/491042/how-a-cross-level-interaction-can-be-taken-to-be-random-in-a-2-level-model) is the question.


Jquery count total values in an each loop

Question: Trying to count each value from a checked input. Independently the code works and returns each value - I need to add them all together outside of the each loop so that I can interrogate the value.
Code is:
// Declare empty count
quiz_count = 0;
$('.questions li ul li').each(function(checking){
    quiz_count += $(this).find('input:checked').val();
});

I know I'm close - just can't seem to get there.
Comment: More clarity needed in this question, what do you mean I need to add them all together, create a variable to store the sum of all totals (this can be a global for instance).
Comment: Depending on what the value of the checkboxes is, you may need to use `parseInt()`. Other than that, `quiz_count` should contain the necessary total after the `each()` has completed. What exactly is the issue?
Comment: Can you provide a demo showing the issue?
Comment: Issue is that I can receive each value independently (4,3,1,3) - I want to add all the values together and query that count outside of the each loop.
Answer: if your value is integer use parseInt else use parseFloat
quiz_count = 0;
$('.questions li ul li').each(function(checking){
    quiz_count += ParseInt($(this).find('input:checked').val());
});


Non-singular derivative definition

Question: I have a basic definition question. I am studying inverse function theorem, and I am stuck with what it means to say that for a $f'$ is non-singular? I looked it up in the internet, but it did not help. And the book does not give a definition of what non-singularity means. Could someone please help me with it?
Thanks in advance!
Answer: In the multivariable setting, f' is a linear transformation, i.e. a matrix. They mean that this matrix is invertible, i.e. has nonzero determinant.
Comment: And if the matrix $f'$ is not a square matrix, are we talking about the left inverse or the right inverse?

Non-singular derivative definition


Running a Batch File from Task Scheduler With User credentials automatic fetch from directory

Question: I'm trying to run a batch file on Windows 7 from the Task Scheduler. I can run the batch file fine if I run it from the command prompt and by storing user credentials in Task schedular.
However, User's password changes per month so i need to find a way so that Task Scheduler can Automatically fetch user credentials from a directory to run Schedular.
Any help will be much appriciated.
Answer: If you change the user password, You will need to change the password on the task to get everything working again.
My suggestion: Create a service account to run the task and set the password to never expire.


Como acrescentar linhas em um data.frame e ou tabela no shinyserver?

Question: Olá, boa noite!
estou tentando resolver algumas coisas pelo shiny, porém me deparei com um problema, preciso criar um data.frame, onde eu seja capaz de acrescentar linhas de informação, sem ficar fazendo a logística de usar write.table() vs read.table.
library(shiny)

ui<-fluidPage(
sidebarPanel(
fluidRow(
selectInput("INPUT",  label="Entrada:"  ,choices=list("",1,2,3,4,5,6,7)),
selectInput("NOMEIPT", label="Nome:", choices=list("","Área","Comprimento","Largura")),
selectInput("COLOUR", label="Cor:",  choices=list("","black","white","red","green","blue","brown","yellow")),
actionButton("ADDIN",label="adicionar"))),
            mainPanel(fluidPage(
              fluidRow(tableOutput("dados")))))

server1 <- function(session,input, output) {

  counter <- reactiveValues(countervalue = 0) # tentei gerar um valor reativo, para criar vários data.frames
    observeEvent(input$ADDIN,{

counter$countervalue <- counter$countervalue + 1 })

  eventReactive(input$ADDIN,{
    # nesse caso deveria a cada vez que eu selecionace as três, opções, e clicasse no botão "Adicionar"
    # ele deveria gerar um data.frame: df1<-data.frame(iten=..cor=..nome=..) para cada click df2...df3...df4..
    eval(parse(text=paste("df",as.numeric(input$INPUT),"<-data.frame(iten=",as.numeric(input$INPUT),',cor="',input$COLOUR,'",nome=',input$NOMEIPT,")",sep="")))
      })

  # depois seria necessário apenas juntar esses data.frame usando o rbind, ou rbind.data.frame, não sei a diferença dos dois.
  # porém , eu não sei porque cargas d'água os data.frames não ficam armazenados... até pensei em colocar eles dentro da sessão, porém como eles usar entradas reativas
  # "input$.....", não iria funcionar.....

  DFrame<-eventReactive(input$ADDIN,{
    eval(parse(text=paste(c("rbind(",rep("",counter$countervalue-1)),"df",1:counter$countervalue,c(rep(",",counter$countervalue-1),")"),sep="")))

  })

  output$dados<-renderTable({DFrame()
  })

}

shinyApp(ui,server1)

#---------------------------------------------------------------------------------------

# Também tentei criar uum objeto reativo, e acrescentar a ele um data.frame vazio:

server2 <- function(session,input, output) {
  DT<-reactiveValues(DT=NULL)

  observeEvent(input$ADDIN,{

    DT$DT<-data.frame(iten=NULL,cor=NULL,nome=NULL)
  })

  DFrame<-eventReactive(input$ADDIN,{

  rbind.data.frame(DT$DT,data.frame(iten=as.numeric(input$INPUT),cor=input$COLOUR,nome=input$NOMEIPT))
 })

 output$dados<-renderTable({DFrame()})

}

shinyApp(ui,server2)
#---------------------------------------------------------------------------------------
# tentei dessa forma adicionando linhas ao data.frame vazio

  server3 <- function(session,input, output) {
    DT<-reactiveValues(DT=NULL)

    observeEvent(input$ADDIN,{

      DT$DT<-data.frame(iten="",cor="",nome="")
    })

eventReactive(input$ADDIN,{

  DT$DT[as.numeric(input$INPUT),]<-data.frame(iten=as.numeric(input$INPUT),cor=input$COLOUR,nome=input$NOMEIPT)

})

output$dados<-renderTable({DT$DT})

  }

  shinyApp(ui,server3)

O que eu preciso é que ele gere um data.frame(iten=..,cor=..,nome=..), e a medida que eu selecione as opções e click em adicionar, ele armazene e carregue a informação, e cada mudança de opções, ao clicar em adicionar, ele acrescente uma nova linha ao data.frame com as novas informações... eu preciso disso pois usarei como os itens do data.frame para gerenciar, os nomes e cores que irei usar nos kml files que irei carregar.... por isso não queria ficar regravando tabela pelo write.table(), e read.table()... pois cada arquivo novo geraria uma tabela nova!
Answer: INTRODUÇÃO
Vou apresentar a solução do problema utilizando o reactValues. Entretanto leia as considerações que vou fazer sobre essa solução logo em seguida.
SOLUÇÃO
A solução é essa:

crie um data.frame vazio no arquivo app.R, fora do ui e do server.
crie um reactValue para o data.frame criado.
atualize o data.frame a partir dos inputs sempre que o botão é clicado

Aqui vai o código completo do app.R
library(shiny)

## Cria data.frame vazio só para começar
df <- data.frame(Entrada=character(),
                 Nome=character(),
                 Cor=character(),
                 stringsAsFactors=FALSE)

## Interface que não foi alterada
ui <- fluidPage(
          sidebarPanel(
            fluidRow(
              selectInput("INPUT",  label="Entrada:"  ,choices=list("",1,2,3,4,5,6,7)),
              selectInput("NOMEIPT", label="Nome:", choices=list("","Área","Comprimento","Largura")),
              selectInput("COLOUR", label="Cor:",  choices=list("","black","white","red","green","blue","brown","yellow")),
              actionButton("ADDIN",label="adicionar"))),
          mainPanel(fluidPage(
            fluidRow(tableOutput("dados")))))

## Única alterada por mim
server <- function(session,input, output) {

  ## Uso do reactvalues para armazenar os dados
  values <- reactiveValues(df_data = df)

  ## Sempre que houver um toque no botão uma nova linha é adicionada
  observeEvent(input$ADDIN, {
    nova_linha <- data.frame(Entrada=input$INPUT, Nome=input$NOMEIPT, Cor=input$COLOUR)
    values$df_data <- rbind(values$df_data, nova_linha)
  })

  output$dados<-renderTable({ values$df_data
  })

}

shinyApp(ui,server)

o comportamento que você vai obter é como segue:

CONSIDERAÇÕES
Do ponto de vista de programação web o problema que você está enfrentando é o problema de gerenciar o estado da aplicação. Veja que uma boa aplicação deve estar desacoplada dos dados. O ideal seria você criar uma forma de armazenar os dados necessários para selecionar os futuros arquivos que você vai baixar na própria seleção dos inputs  e não armazenar em um data.frame. A forma ideal de armazenar os dados do app ao longo das sessões é por meio de um sistema de gerenciamento de banco de dados, que poderia ser até o SQLite3. Entretanto, nesse caso, os dados ficariam armazenados de forma permanente o que creio que não era seu objetivo. Não postei essa solução porque foge do escopo da pergunta e acredito que não seria a solução ideal para o seu problema.
Comment: Muitíssimo obrigado Flavio Barros, me quebrou foi uma árvore!!!


cyrus-imapd is not work with sasldb2, but postfix work

Question: centos6 64 bits:
when i use pop3 for access cyrus-imapd:
S: +OK li557-53 Cyrus POP3 v2.3.16-Fedora-RPM-2.3.16-6.el6_2.5 server ready <3176565056.1354071404@li557-53>
C: USER firstname.lastname@example.com
S: +OK Name is a valid mailbox
C: PASS abcabc
S: -ERR [AUTH] Invalid login
C: QUIT

and with USER "abc" failed too.
my imapd.conf:
configdirectory: /var/lib/imap
partition-default: /var/spool/imap
admins: cyrus
sievedir: /var/lib/imap/sieve
sendmail: /usr/sbin/sendmail
hashimapspool: true
sasl_pwcheck_method: auxprop
sasl_mech_list: PLAIN LOGIN
tls_cert_file: /etc/pki/cyrus-imapd/cyrus-imapd.pem
tls_key_file: /etc/pki/cyrus-imapd/cyrus-imapd.pem
tls_ca_file: /etc/pki/tls/certs/ca-bundle.crt

allowplaintext: true

#defaultdomain: myabc.com
loginrealms: myabc.com

sasldblistuser2:
email@example.com: userPassword

but my postfix is ok with same user.
/etc/sasl2/smtpd.conf
pwcheck_method: auxprop
mech_list: plain login
log_level:7
saslauthd_path:/var/run/saslauthd/mux

/etc/postfix/main.cf
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
mail_owner = postfix
myhostname = localhost
mydomain = myabc.com
myorigin = $mydomain
inet_interfaces = all
inet_protocols = all
mydestination = $myhostname, localhost.$mydomain, localhost,$mydomain
local_recipient_maps =
unknown_local_recipient_reject_code = 550
mynetworks_style = subnet
mynetworks = 192.168.0.0/24, 127.0.0.0/8
relay_domains = $mydestination
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
home_mailbox = Maildir/

mailbox_transport = lmtp:unix:/var/lib/imap/socket/lmtp

debug_peer_level = 2
debugger_command =
     PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
     ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.6.6/samples
readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES

smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_security_options = noanonymous
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_security_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
message_size_limit = 15728640
broken_sasl_auth_clients=yes

please help.
use imap:
username: "firstname.lastname@example.com" can login, but can't get mail
username: "abc" can't login

use pop:
username: "firstname.lastname@example.com" can login, but repoort: Unable to locate maildrop : Invalid mailbox name
username: "abc", can't login

it seems something wrong with cyrus-imapd mailbox.
the mail saved into user/abc
   but fetch mail from email@example.com
Answer: It doesn't look like sasl problem or authentication problem at all. I think you misconfigured cyrus mailboxes. In order to use mailboxes with domain part like email@example.com you should specify
unixhierarchysep: yes

in your imapd.conf.
And then you should create mailboxes like this:
cm email@example.com

I think this will be enough to make IMAP/POP3 work.
UPD: sorry, forgot one more option, you need this also in your imapd.conf:
virtdomains: userid

Comment: it works.that is great!  Thank you.  it is really hard to figure out from document.


H2 - Setting variable does not work as expected

Question: I am using h2 to generate some data for tests.
I have a select statement, that selects a random row in a table.
Within the select statement I set a variable called 'K' with the SET function (http://h2database.com/html/functions.html#set).
In a second statement within the same session I try to read / get the current value of the variable.
To get a reproducible result I use SYSTEM_RANGE(1,10) in the select statement below. I use the h2 web console to execute the statements.
If I set the variable like in the following statement
SET @K = SELECT X FROM SYSTEM_RANGE(1,10) ORDER BY RANDOM() LIMIT 1;

and I execute a subsequent VALUES statement
VALUES(@K)

it works as expected. The variable K has been set to a random value. Subsequent executions of both these statements show, that value of the variable changes randomly.
I would like to assign the variable within a select statement. Setting the variable as shown above does not help in reaching my goal.
This does not work as expected
SELECT SET(@K,X) FROM SYSTEM_RANGE(1,10) ORDER BY RANDOM() LIMIT 1;
VALUES(@K); -- value of K is different than result of above select
            -- subsequent executions show that the result of the select changes as expected
            — but the result of the values statement and thus the value of K does not change

I would expect the result of the select statement to be the same as the value of the variable, but they are not. Subsequent executions of both statements show, that the select statements delivers randomly selected results, but the values statement delivers the same / a constant integer.
Answer: (I tried a little....) and it is possible (not to call RAND, anytime you call VALUES):
SET @K = FLOOR(RAND() * 9) + 1;
VALUES(@K);

"Just omit" the select statement in SET
Comment: I am not interested in getting a reproducible result. I just want the assignment to the variable to be permanent, in order to use the randomly selected value in subsequent statements. My goal is to select the first row in the table at random and than I would like to do lookups in other tables with this randomly selected value. This approach garanties random data selection and consistency.


Webforms: Is it possible to set maximal value for Number in relation to another Number value?

Question: I am new in Drupal...
In webforms I use Number field to set age of person:
How old are you? [Number] /min 10, max 100/
When did you smoke for the first time? [Number] /min 10, max here should be the value of the previous number.
Is it possible to set it somehow in Webform GUI, or the only by the code?
Thanx
Answer: You might try making the age a drop-down with the given range and then webform conditional becomes an easy, ready to use option.
Many other ways to get this done but this is probably the most straightforward imho.
Comment: the most important part for me is, that there are more ways than none. I do not want to exploit the people here, I will try myself to find out. Thanx
Comment: In that case, the drop down is one. ;) Others involve additional modules and/or code depending on particulars. Happy to take the answer further if it helps.


Model broken stick model in R where one line has a constant gradient?

Question: I am current using the package (lme4) for a mixed effect model with random effects.
My model takes the form:
mod <- lmer(response ~ b1(predict1, bp) + b2(predict2, bp) + (1 | site), data = data)

The functions b1 and b2 come from the helpful advice in:
Estimating the break point in a broken stick / piecewise linear model with random effects in R [code and output included]
b1 <- function(x, bp) ifelse(x < bp, bp - x, 0)
b2 <- function(x, bp) ifelse(x < bp, 0, x - bp)

I am wondering, how would I set up my model so that the second part (line) of the broken stick model has a constant gradient?
So for example, I would like something like:
If X < breakpoint, Y = m1X + C1
If X > breakpoint, Y = C2
Hope I am making sense.
Matt.
Answer: I may have found a solution to my problem, but could someone please confirm what I've done?
I slightly modified the above functions b1 and b2. I have called them b3 and b4:
b3 <- function(x, bp) ifelse(x < bp, bp - x, 0)   #Y = mx + c
b4 <- function(x, bp) ifelse(x < bp, 0, 1)        #Y = C

The mixed model is similar, but b3 and b4 are used:
mod2 <- lmer(SIGNAL ~ b3(dci, bp) + b4(dci,bp) + (1 | gauge), data = cand_bug_data)

Answer: I see your post is pretty old, but I'm working on the same issue -- and I found a slightly different solution than yours.. figured I'd post for others out there.
b1 <- function(x, bp) ifelse(x < bp, x, bp)

#Wrapper for Mixed effects model with variable break point
foo <- function(bp)
 {
   mod <- lmer(y ~ b1(x, bp) + (1|Site), data = dat)
   REMLcrit(mod)
 }

mod <- lmer(y ~ b1(x, bp) + (1 | Site),  data = dat)

And everything else as appears on the original post


Find the value of $x^3-x^{-3}$ given that $x^2+x^{-2} = 83$

Question:
If $x>1$ and $x^2+\dfrac {1}{x^2}=83$, find the value of the expression$$x^3-\dfrac {1}{x^3}$$
a) $764$
b) $750$
c) $756$
d) $760$

In this question from given I tried to approximate the value of $x$ which should just above to 9 then I tried to calculate the value of cubic expression but all options are close enough to guess. Any idea to solve it?
Answer: First, notice that
$$\left(x-\frac{1}{x}\right)^2=x^2-2+\frac{1}{x^2}=83-2=81$$
Then, use the difference of two cubes formula:
$$x^3-\frac{1}{x^3}=\left(x-\frac{1}{x}\right)\left(x^2+1+\frac{1}{x^2}\right)=9\cdot(83+1)=756$$
We take the positive root of $81$ because $x>1$.


What is composition of convex and concave function?

Question:
Suppose that $f: \mathbb{R}\to \mathbb{R}$ is convex function and $g: \mathbb{R}\to \mathbb{R}$ is concave function. What can we say about their composition $g\circ f$ and $f\circ g$? Are they convex or concave functions?

Thank you in advace !
Comment: You cannot conclude anything without additional information; for instance, if $f$ is also nonincreasing, then the composition is concave.
Comment: See p. 84 of https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
Comment: Have you tried with some examples?
Comment: Yes, but I can't conclude with examples.
Comment: @LinAlg Many thanks for your useful reference!
Answer: Hint. Try $f(x)=e^x$ (convex) and $g(x)=-x^2$ (concave).
What about $f(g(x))=e^{-x^2}$?  Is it convex or concave? Check the plot at WA.
P. S. If we assume that $f,g$ are $C^2$ then
$$(f(g(x))'=f'(g(x))\cdot g'(x),\quad
(f(g(x))''=f''(g(x))\cdot (g'(x))^2+f'(g(x))\cdot g''(x)$$
So if $f''\geq 0$, $g''\leq 0$ and $f'\leq 0$ then $(f(g(x))''\geq 0$.
Comment: @Thomas Edison This means that you can't conclude nothing. You need additional hypothesis.  See my edited answer.
Comment: Or more generally if $\frac{f''(g(x))*(g'(x))^2}{-g''(x)} \ge f'(g(x))$ then it is convex, right?  (But just notice that this condition is much more specific because it depends on $g(x)$ rather than only on the derivatives).  $f'$ can be positive, but it just has to be small enough such that the hessian of $h$ is still positive semi definite right?
Comment: If the hessian of the composition is semidefinite positive, why do you conclude it is not concave nor convex?
Comment: it's convex, right?


How is Bayes Stats supposedly more "intuitive" when it requires us to think probabilistically which IS NOT intuitive for most folks?

Question: People don't naturally think in probabilistic ways, they often form priors through point estimates because it's less cognitively taxing to reduce everything down to single numbers. So if the fundamental premise of Bayesian Inference is a method formulated mathematically of updating our prior hypothesis from evidence presented to us as the practitioner, then why are we forced to think in a way that divorces from everyday convention? And yes, I get that "intuitive" is relative depending on who you ask but that's often one of the arguments I hear from Bayesians as to why it's superior to Frequentists.
Comment: Thinking in a Bayesian way is more intuitive because the same method can be used in many different problems. For example, hypothesis testing is very clear, you have your posterior distributions for the quantities you want to estimate, and then run a simulation to see how often one quantity exceeds another. The frequentist method requires you do know which test to use, and there are many, and each test requires you do to something different depending on the type of problem.
Answer: Because Bayesianism, unlike frequentism, has a concept of how likely a hypothesis is to be true, and that's what people intuitively (and rightly) care about.
If you try to use Bayesian methods to investigate the fairness of a coin, the output is a number which claims to represent the probability that the coin is fair. This is the thing you care about.
If you try to use frequentist methods to investigate the same thing, the output is a p-value, which is the probability that you would get results at least as "extreme" as the ones you actually got conditional on the coin actually being fair. This is not the thing you care about. (In fact, it's somewhat common for people to incorrectly believe that a p-value represents the probability that the null hypothesis is true. I imagine this is because it's intuitive that you would want to know the probability that the null hypothesis is true, so people just assume that's what p-values are.)


What is wrong with this limit $\lim_{x \rightarrow \infty} \frac{2x^4-1}{-4x^5+x^2}$?

Question: The arrow indicates an elimination due to numbers becoming negligible at high values of x.
The correct answer is 0, but I got infinity and I'm not sure where my reasoning went wrong.
$$\lim_{x \rightarrow \infty} \frac{2x^4-1}{-4x^5+x^2}=\lim_{x \rightarrow \infty} \frac{x^4(2-\frac{1}{x^4})}{x^5(-4+\frac{x^2}{x^5})}=\lim_{x \rightarrow \infty} \frac{x^4(2)}{x^5(\frac{1}{x^3})}=\lim_{x \rightarrow \infty} \frac{2x^4}{x^2}=\lim_{x \rightarrow \infty} 2x^2 = \infty$$
Thanks!
Comment: Why did you keep the $x^2/x^5$ term instead of the $-4$ on the bottom? You kept the $2$ instead of the $-1/x^4$ on the top.
Comment: This is quite difficult to read.
Comment: @Glacier Thanks for the edit
Comment: Sorry, I dunno how to write it in the other way.
Comment: Yeah, I did in the rewrite on the far right.
Answer: Here is a solution.
$$\lim_{x\to \infty}\frac{2x^4-1}{-4x^5+x^2} = \lim_{x \to \infty}\frac{\frac{2}{x}-\frac{1}{x^5}}{-4+\frac{1}{x^3}} = \frac{0-0}{-4+0}=0$$
I would say that the error is that you can't just take the result of the limit for some parts of the expression and some not, which is what I believe you did in the second equality.
Answer: Since I am sure you understood the answers to your problem, let us try to consider the general problem of finding $$\lim_{x \rightarrow \infty} \frac{P_m(x)}{Q_n(x)}$$ where $P_m(x)$ and $Q_n(x)$ are polynomials of degrees $m$ and $n$ that is to say $$P_m(x)=\sum _{i=0}^m p_i x^i=p_0+p_1x+p_2x^2+...+p_mx^m$$  $$Q_n(x)=\sum _{i=0}^n q_i x^i=q_0+q_1x+q_2x^2+...+q_nx^n$$in which coefficients $p_m$ and $q_n$ are not zero. You can factor $x^m$ in the numerator and $x^n$ in the denominator and then write $$P_m(x)=x^m  \sum _{i=0}^m p_i x^{i-m}$$ $$Q_n(x)=x^n  \sum _{i=0}^n q_i x^{i-m}$$ In the summations, except for the last terms which are $p_m$ and $q_n$ only negative powers of $x$ appear and, since $x$ goes to $\infty$, they are negligible. So, for large values of $x$, $$\frac{P_m(x)}{Q_n(x)} \simeq \frac {p_m x^m}{q_n x^n}=\frac {p_m }{q_n} x^{m-n}$$
As a consequence, if $m>n$ the limit is $\infty$, if $m=n$ the limit is $\frac {p_m }{q_n}$ and if $m<n$ the limit is $0$.
Comment: good generalization, but may be a bit hard for the OP
Comment: I really hope and wish that this is not too hard to follow after the specific problem has been solved.
Answer: First arrow is incorrect since $-4+x^{-3} \to -4$ as $x\to\infty$.
Comment: @Pallas: What logic did you apply on the top of the fraction? The same logic should apply on the bottom.
Comment: why doesn't 4 become negligible causing $x^5$ to be multiplied by $x^-3$?
Comment: Take $x=1$.  Then $-4+x^{-3}=-3$.  Now take $x=10$.  Then $-4+x^{-3}=-3.999$.  Now take $x=100$, etcetera.
Answer: Your mistake is not that you did not evaluate the numerator and denominator at the same time or in the same way.  Your mistake is strictly a computational one: $$\lim_{x \rightarrow \infty} \frac{x^4(2-\frac{1}{x^4})}{x^5(-4+\frac{x^2}{x^5})}=\lim_{x \rightarrow \infty} \frac{x^4(2)}{x^5(\frac{1}{x^3})}$$ is incorrect.  The RHS must instead read $$\lim_{x \rightarrow \infty} \frac{x^4(2)}{x^5(-4 + \frac{1}{x^3})},$$ and this is the source of the error.  This is because as $x \to \infty$, $x^5(-4 + x^{-3})$ asymptotically behaves as $-4x^5$, not $x^2$, and it is this faster growth of the denominator compared to the numerator that makes the limit zero.


Does Bayesian Statistics have no concept of statistical hypothesis testing?

Question: I was told that the framework of Bayesian Statistics has no concept of statistical hypothesis testing or confidence intervals.
How does this make sense? Bayesian statistics only says that we iteratively update our prior belief based on evidence. Consider the following example I got from my textbook where we use Bayesian statistics to model the behaviour of some variable C.

t e [0, 20]
C ~ Poi(lambda)
lambda = { lambda1, if t>10; lambda2, otherwise }
lambda1 ~ exp(alpha1)
lambda2 ~ exp(alpha2)
Run MCMC to compute posteriors of lambda1 and lambda 2

The parameter lambda takes on two different behaviours: one before 10 seconds and another after 10 seconds.
Now we'll do a t-test on to check whether the distributions of lambda1 are statistically different from lambda2 to check whether these two distributions are indeed different. I do not know whether doing this t-test makes sense, I was told we cannot do statistical testing in a Bayesian framework. We are supposed to use visualizations and reject them ourselves.
Can anyone confirm whether this is true? Is statistical testing invalid from a Bayesian perspective?
Comment: You can have things that are tests and intervals, but they have a somewhat different interpretation (e.g. a Bayesian interval isn't a confidence interval in the sense that it guarantees a coverage probability; it does something else).
Comment: A quick search for "bayesian hypothesis testing" in your search engine of choice should prove enlightening.
Comment: It may help you to more rigorously define what "statistically different" actually means in this context ( I do not know what it means here).  I also don't understand your model since you have some latent variable $t$ that is not conditioned on anything.  As for the more general question regarding statistical testing in a Bayesian setting; there is no concrete answer.  Since different people will still have different definitions as to what constitutes "statistical hypothesis testing" you would need to define , much more rigorously, exactly what type of testing methodology you have in mind.
Comment: What are the hypotheses that you are attempting to test via a t-test? Are you trying to test $H_0:\;\alpha_1 =\alpha_2$ vs $H_1:\;\alpha_1 \neq \alpha_2$.  If so, are these hyper-parameters estimated in the model or are they given a priori? To say "Bayesian Statistics has no concept of statistical hypothesis testing" requires a specific (frequentist) definition of hypothesis testing that not everyone will agree on.  To better understand this, it would be helpful to work your example in both a Bayesian and frequentist setting and compare the results.
Comment: Yeah, it seems to give a rather ad-hoc answer. Most results say "no" but I'm hoping for a clear answer by a human.
Comment: Sorry t are discrete values from 0 to 20. I just heard a famous Bayesian stats guy say that statistical testing is not valid in Bayesian stats.

C represents the amount of text messages in some duration. There are essentially two groups of messages. One when someone was in a relationship and one where someone wasn't in a relationship.
Comment: I think you have to put "statistical hypothesis testing" and "confidence intervals" in quotes. You can test hypotheses and you can create confidence intervals. That doesn't mean you use p-values and CI lookup tables necessarily.
Answer: I am surprised at the textbook statement as testing hypotheses and comparing models are a most fundamental feature of Bayesian analysis, with a wide variety of possible resolutions that exposes the multiple and sometimes incompatible facets of the problem.
(excerpt from our book, Bayesian essentials with R, Chapter 2, p.29:)

For the null and alternative hypotheses $$ H_0:\ \theta \in
> \Theta_0\text{ and }H_a:\ \theta \in \Theta_1 $$ and under the loss
  function $$ L_{a_0,a_1} (\theta ,d)  =
         \begin{cases} a_0 & \hbox{if}\quad \theta \in \Theta_0\quad\hbox{and}\quad d=0\,, \cr
                                 a_1 & \hbox{if}\quad \theta \in \Theta_1\quad\hbox{and}\quad d=1\,, \cr
                                 0   & \hbox{otherwise.} \cr \end{cases} $$ where $d=0$ denotes the rejection of $H_0$, the Bayes
  optimal decision associated with a prior $\pi$ is given by $$
 \delta^\pi(x)  =  \begin{cases} 1 & \hbox{if}\quad
 \mathbb{P}^\pi(\theta \in \Theta_0|x)>a_1\big/{a_0+a_1}, \cr
                                 0 & \hbox{otherwise.}\cr \end{cases} $$ For this class of losses, the null hypothesis $H_0$ is rejected
  when the posterior probability of $H_0$ is too small, the acceptance
  level $a_1/(a_0+a_1)$ being determined by the choice of $(a_0,a_1)$.

The Bayesian paradigm allows for testing and model comparison, to a larger extent than other statistical paradigms, I would say. What may sound at first like a drawback is that all aspects of this decision have to be spelled out, from the specification of the sampling models under the null and under the alternative hypotheses (which explains why I cannot spell out a strict distinction between hypothesis testing and model choice), to the construction of prior distributions on the parameters of both sampling models, to prior weights on the prior likelihood of both hypotheses, to the impact of selecting the "wrong "model".
Outside this Neyman-Pearson decision framework, there are further Bayesian resolutions of the testing issue, like

the substitute Bayes factor$$\dfrac{\mathbb{P}^\pi(\theta \in \Theta_0|x)}{\mathbb{P}^\pi(\theta \in \Theta_1|x)}\Big/\dfrac{\mathbb{P}^\pi(\theta \in \Theta_0)}{\mathbb{P}^\pi(\theta \in \Theta_1)}$$that avoids selecting the prior weights but which are not free from foundational drawbacks;
information criteria like BIC, DIC, WAIC and Aitkin's integrated likelihood;
score functions and related information approaches;
posterior predictive assessments like the posterior $p$-value of Gelman et al. and others;
Evans' relative belief;
divergence criteria like ABC$\mu$;
model averaging;
embedding models like our mixture representation.
Comment: I just ordered the book through Amazon.
Answer: No.
Bayesian statistics has a concept of hypothesis testing. From Wagenmakers and Grünweld:

A Bayesian hypothesis test (Jeffreys, 1961) proceeds by contrasting two quantities: the probability of the observed data $D$ given $H_{0}$ (i.e., $\theta = \frac{1}{2}$) and the probability of the observed data $D$ given $H_{1}$ (i.e., $\theta \ne \frac{1}{2}$). The ratio $B_{01} = p(D|H_{0})/p(D|H_{1})$ is the Bayes factor, and it quantifies the evidence that the data provide for $H_{0}$ vis-à-vis $H_{1}$.

Eric-Jan Wagenmaker and Peter Grünweld. 2006. A Bayesian Perspective on Hypothesis Testing A Comment on Killeen (2005). Psychological Science. 17(7):641–642.
Comment: Is it statistically invalid to apply a traditional t-test as I did in my example?


Sharing an IP pool for two openvpn instances (one TCP and one UDP)

Question: I'm currently running OpenVPN on my VPS, listening on port 1194 via TCP. I need to use TCP since I sometimes need to tunnel traffic over an HTTP proxy. However, I'd also like to be able to use UDP, which should be faster. However, I don't want to create two subnets, as I also have my machines connect to one another, and I'd like to have them all on one subnet.
Is there any way I have two instances share one IP pool?
Here's my server config, for reference:
dev tun
proto tcp
persist-key
persist-tun
log-append /var/log/openvpn
comp-lzo

port 1194
ca /etc/openvpn/easy-rsa/2.0/keys/ca.crt
cert /etc/openvpn/easy-rsa/2.0/keys/server.crt
key /etc/openvpn/easy-rsa/2.0/keys/server.key
dh /etc/openvpn/easy-rsa/2.0/keys/dh1024.pem
ifconfig-pool-persist ipp.txt
server 192.168.192.0 255.255.255.0
topology subnet
client-to-client
push "dhcp-option DNS 192.168.192.1"
push "dhcp-option DOMAIN my.example.com"

# Daemon settings
user nobody
group nogroup

Answer: Ok, I solved this.
First, I switched to a bridged network. I created one bridge device, and two tap devices which are attached (I don't have an ethernet device on the bridge). The UDP server listens on 192.168.192.1 [and on tap0], the TCP on 192.168.192.2 [and on tap1]. The bridge itself gets 192.168.192.1, but I don't think this is that important. Both have the same ifconfig-pool-persist file.
This worked, but I couldn't connect from clients connected via UDP to clients connected via TCP or vice versa (clients with the same method could talk to each other). I added a firewall rule:
iptables -A FORWARD -i br0 -o br0 -j ACCEPT

and now everything works.
Answer: The traffic you put into the VPN is independent from the protocol used for the tunnel. In an OpenVPN tunnel, you can put AFAIK any traffic (TCP, UDP, ICMP,...).
EDIT : I really really don't think you can have two OpenVPN instances with the same subnet as that would give you an impossible routing table. What you can do, is have to separate subnets or route between them. I have never done it but I think it's reasonnable to think that it will work.
Comment: ummm.. yeah. But the OpenVPN connection can be created over a TCP connection (good for tunneling via HTTP) or a UDP connection (better performance)
Comment: answered in edit.
Comment: It makes sense that it'd be a problem, but perhaps there's some trick out there. It seems like listening on both UDP and TCP is a fairly common requirement, and if the client's IP changed depending on where is would connect, it would be rather hard to find (DNS is a problem since if I use OpenVPN based DNS, I lose local network DNS).
Comment: For DNS, you could always use some bogus TLD such as .vpn and use that. You could then use both local and OpenVPN DNS...


Tem como configurar um pull automático usando agendador de tarefas do windows?

Question: Estou tentando encontrar uma maneira de atualizar um sistema local em um servidor utilizando versionamento git para ter melhor segurança e controle no meu projeto, mas ainda sou bem leigo no assunto. Acontece que eu queria encontrar uma maneira de sincronizar a máquina local, o github e o servidor de uma forma mais automática, considerando que o servidor não está na mesma rede local a solução que pensei foi criar um repositório remoto para o projeto e configurar um script no agendador de tarefas do servidor para fazer o pull em um dia e horário específico. Daí surgem algumas perguntas:
Como eu crio um script para rodar comandos no git?
Existe outra forma melhor de fazer isso? E se fossem vários outros servidores que eu tivesse que atualizar?
Answer: Sim, existe uma forma melhor de fazer isso, e é através de uma prática conhecida como Continuous Delivery!
A prática de entrega contínua, em português, ou simplesmente CD, é responsável por executar o deploy nos ambientes necessários realizando assim a entrega da aplicação. Normalmente existem ambientes de desenvolvimento (DEV), homologação (HMG) ou produção (PRD), ou apenas DEV e PRD, ou somente PRD mas com uso de slots, comum no Azure quando se utiliza WebApp,... Ou no caso de aplicação mobile o seu último ambiente pode ser a própria loja onde irá disponibilizar o app para os usuários. Qualquer que seja a quantidade e o propósito dos seus ambientes você precisa de uma orquestração entre eles para fazer esse deploy, ou instalação.
Quando se está desenvolvendo, você irá querer que qualquer commit no repositório seja instalado no ambiente de DEV. Já em homologação apenas quando tiver alguma feature pronta, funcional. E em produção somente quando o cliente aprovar ou estiver homologado. Para que esse processo funcione é preciso orquestrar o deploy entre esses ambientes. Várias ferramentas podem fazer isso, inclusive algumas também a etapa de integração de código, onde é feita compilação ou transpilação, os testes de unidade são executados, e o que mais for necessário para gerar um artefato instalável.
Sugestões:

Azure DevOps, funciona não só com Azure, mas aws e com infra local
Github Actions, mais recente, mas se o seu código já está no Github, pode ser uma boa alternativa
Relacionar o item, você deverá instalar ou rodar a partir de um container, pode até rodar ele em alguma nuvem


scanner.l:22: warning, rule cannot be matched

Question: I am currently attempting to write a program that counts the number of characters and lines in a .in file. The issue is that when I input the command:
<code> lex scanner.l
</code>
It produces an error that says:
<code>scanner.l:22:warning, rule cannot be matched
</code>
I would appreciate any help on this matter. Below is my code:
<code>%option noyywrap
%{
#include <stdio.h>
#include <math.h>
int charno=0;
int lineno=0;
%}

character [a-zA-Z]
line [\n]
digit [0-9]

%%

{digit}
        {
                charno++;
        }

{character}
        {
                charno++;
        }
{line}
        {
                lineno++;
        }
.
        {
                charno++;
        }

%%
int main(int argc, char **argv)
{
            ++argv, --argc; /*skip over program name */
            if (argc > 0)
                    yyin = fopen(argv[0], "r");
            else
                    yyin = stdin;
            yylex();

            printf("Number of characters: %d ", charno);
            printf("Number of lines:      %d ", lineno);
            return 0;
}
</code>
Answer: There should be no newline between the matched token and the action. So :
<code>{digit}
        {
                charno++;
        }
</code>
should be :
<code>{digit} {
                charno++;
        }
</code>
(and similarly for the others)


How can I ensure that a client received my message using UDP sockets in Python?

Question: I'm coding a school excercise using UDP sockets in python and I need to exchange some information (e.g., ints, strings, etc.)  between server and client.
I wrote this functions to asure a message sent from the server is received on the client side and vice versa:
import socket

BUFFER_SIZE = 1024

def send_udp_mgs(origin, destination, msg):
    msg = str(msg).encode('utf8')
    origin.sendto(msg, destination) # sending message
    # I never receive confirmation
    opt, _ = origin.recvfrom(BUFFER_SIZE) # Code stucks here
    opt = opt.decode('utf8')
    print(opt)

def receive_udp_msg(destination):
    msg, origin = destination.recvfrom(BUFFER_SIZE) # receiving message OK
    # This is the message sent as confirmation but is never received
    destination.sendto("CHECK".encode('utf8'), origin) # sent but not received
    msg = msg.decode()
    return msg

I would expect the code to work properly with the function receiving the confirmation after sending the message but it gets stuck waiting for the confirmation. The client sends the confirmation but the server never receives it. Other than that, the client receives the message well, it's only the confirmation back to the server that fails.
This is the server code:
def client_thread (s, c):
    print("Connection petition from", c)
    global n_cons
    cport = PORT + n_cons
    send_udp_mgs(s, c, cport)
    return

# UDP socket acting as server
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((IP, PORT))
while True:
    data, addr = s.recvfrom(BUFFER_SIZE)
    if data.decode() == CONNECT:
        n_cons += 1
        try:
            Thread(target=client_thread, args=(s,), kwargs={'c':addr}).start()
        except:
            print("Error creating thread")
            break

Client code
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s = (IP, PORT)
# Connecting to the server
c.sendto(CONNECT.encode('utf8'), s)
cport = receive_udp_msg(c)

Comment: How are you calling these functions? In particular, are they running as different processes? If so, how are you setting up the sockets.
Comment: I make a thread for each client on the server side, while the client is running on the "main" function. So the send_udp_mgs is on a thread on the server side, while receive_udp_msg is on the main the client
Comment: The code you posted works fine on its own, so my guess is that the problem is something going on in the server. Could you show us some of the code that runs the server? (My first suspicion is that it's some sort of threading problem.)
Comment: I added the server and client code.
Answer: I wasn't able to get your program to stop at the exact point you said it stops at, but I was able to find an issue I suspect has a similar cause:
With more than one client, the thread waiting for confirmation from one client can receive the CONNECT message from the next client, and the server's "main loop" can receive the confirmation message.
You can't avoid this problem: unless you can control when all clients send data, you can't spin off threads for different clients when you're using UDP. I recommend using select, selectors, or asyncio, or just asyncio's socket functions to perform actions on your sockets.
But here's something else to consider: why are you trying to confirm UDP messages? If you need to make sure the other end of the connection receives what you send, why aren't you using TCP or some other protocol that has mechanisms for ensuring delivery built-in?
If you really need to use UDP, you'll need to make at least one data structure to keep track of the clients who are trying to "connect," and other information about their "connections." But UDP is explicitly connectionless.

As an unrelated comment, does the cport in client_thread imply that you plan to create a new port, in sequential order, for each client? If so, consider that (a) you can only have so many ports open, (b) another process many be using one of those ports, (c) unless n_cons never goes down, this process will be using those ports, and (d) what do you need that many ports for? (See also this answer.)
Comment: Thanks so much for your answer. I know that the most logical thing to do would be to use TCP, but it's a school excersise with UDP. I will take into account everything you said, thanks again!


Can the Flag module be used to lock content while editing to prevent concurrent edits?

Question: We are trying to figure out a way to use the Flag module to prevent concurrent editing. In our research, we found the Content locking (anti-concurrent editing) module, but we thought since we are already using the flag module, that we could also use it for content locking.
The scenario would be if a user (person a) is already editing content A, and then another user (person b) tries to edit content A, then person b should not be allowed to edit content A until person a is done editing the content.
What is the best way to do this because we are having trouble trying to find the right combination to get this done? We were thinking once a content is being edited, a flag is set to lock the content and whenever another user tries to edit the content, they are prompted with a message "person a is already editing the content. please wait until they are done".
Is this possible with the Flag module? Would I need to use the Rules modules as well?
Answer: You can do it by using the node_validate function.
Your relevant part code is that :
if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  }

Answer: Below are 2 possible solutions (options) to address this question (which I assume is about D7) ...
Option 1: Use the Rules and Flag modules
Yes you can implement such edit-in-progress (EIP) feature using the Flag module, but you'll also need the Rules module to get it to work. Read on for more details ...
Step 1: Create an edit-in-progress flag
Create a global (not user specific) flag, and say you name (label) it edit-in-progress flag (='EIP' for short). The purpose of this flag is like so:

If this flag is turned on for a node, it means "somebody is editing this node, so do not allow any additional edit sessions for this node to be started".
If this flag is not turned on for a node, it means "the node is available for authorized users to start editing it".

Step 2: Create a rule to disallow edit if the EIP flag is set
Create a rule to disallow edit of a node if the EIP flag for a node is already set. To recognize a request to start an edit session for a node, use an URL like node/xyz/edit (with xyz = nid of the node).
Refer to my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains a rule that is pretty close to what's needed for this rule here:

Use the same Rules Event, i.e. "Drupal is initializing" (you want to catch this edit event via Rules BEFORE the edit session actually allowed to be started!).
Slightly adapt the regular expression, by adding /edit to it.
Add an extra condition to verify if the EIP-flag for this node is ALREADY turned on (which indicates some other edit session for this node was started already).
Adapt the Rules Action to (a) issue an appropriate message (that some other edit session is already started) and (b) redirect the user to whatever other path that fits your needs (e.g: just node/xzy).

Step 3: Create a rule to SET the EIP flag when an edit starts
Create a rule to SET the EIP flag for a node whenever an authorized user requests to start an edit session for a node. To recognize such request, use an URL like node/xyz/edit (with xyz = nid of the node).
Refer to my answer mentioned in Step 2, which contains a rule that is pretty close to what's needed for this rule here:

Use the same Rules Event, i.e. "Drupal is initializing" (you want to catch this edit event via Rules BEFORE the edit session actually allowed to be started!).
Slightly adapt the regular expression, by adding /edit to it.
Add an extra condition to verify if the EIP-flag for this node is NOT turned on (which indicates no other edit session for this node exists).
Adapt the Rules Action to SET the EIP flag.

Step 4: Create a rule to UNSET the EIP flag when an edit ends
Create a rule to UNSET the EIP flag for a node whenever an authorized user requests to end an edit session for a node.
Here is a summary of this rule:

Use Rules Event "after saving content".
Use Rules Action to UNSET the EIP flag.

Step 5: Merge Step 2 and Step 3 (optional)
Should you want to do/consider so, you should be able to merge the 2 Rules from Step 2 and Step 3 in a single Rule, using the Conditional Rules module. Refer to my answer to the question How to prevent a node being saved when using the Rules module? for a sample of how to use this module (for which not a lot of documentation seems to exist).
Option 2: Use other modules
For anybody who does not want (or is unable) to use the combination of the Flag and Rules modules as described above, there are some alternative modules that may be worth considering.
Here are some of them (quotes are from their project pages):

Content locking (anti-concurrent editing)

Features:

Block concurrent editing: When a user is editing a node, any other user that attempts to edit the same node will be blocked from doing so, and notified that the content is already being edited.
By node type: This module can be configured to only lock certain content types against concurrent editing.
By format: This module can be configured to only lock specific input formats against concurrent editing.
Avoid losing content by accident: If a user is editing content and attempts to leave the edit form without first saving it (e.g., closing the browser window/tab, clicking on a link, etc.), they will be notified. If the user confirms that they want to leave without saving the node, the edit lock gets automatically removed by an ajax call. This behavior can be disabled on the modules settings page.
Avoid forgotten locks: Users are notified if they forget to unlock a node. They will be prompted to click on a link to unlock the node.
Views integration: All open locks can be listed using Views.

Conflict.

This module allows parallel editing of nodes with field-level conflict detection and a trick to prevent accidental overwriting of fields when they are changed by another session while a node is being edited.
This behavior is useful for things like issue queues where multiple people might be following up to an issue simultaneously. The original problem that lead to this module is #1559578: D7 solution for when multiple users are updating an issue simultaneously.
It works by doing a 3-way comparison between the field data of the original node, the node as edited by us, and the node as edited by others.


http response shows Expires in 1981 when using mod_cache

Question: I'm setting up Apache caching on CentOS using mod_cache and mod_cache_disk with the configuration at the bottom of this post but the page is not cached. I included CacheDetailHeader on to get some debug info.
When I hit the page, the HTTP response shows X-Cache-Detail: "Expires header already expired; not cacheable" and the Expires header is set to some date in 1981, despite the date being correct.
Date: Mon, 19 Aug 2019 23:39:03 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT

The test is being done using Chrome Incognito browser on a public WordPress page.
The full configuration. CacheRoot exists and is writable for the Apache user.
# The following line could be required or not depending on your Apache installation
LoadModule cache_module modules/mod_cache.so

<IfModule mod_cache.c>
    CacheQuickHandler off
    CacheDetailHeader on

    CacheIgnoreNoLastMod On
    CacheDefaultExpire 7200

    CacheIgnoreCacheControl On
    CacheLastModifiedFactor 0.5
    CacheIgnoreHeaders Set-Cookie Cookie
    CacheHeader on
    CacheLock on
    CacheDisable /wp-admin
    CacheDisable /wp-login.php
    CacheDisable /wp-cron.php

    SetOutputFilter CACHE
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/rss+xml text/xml image/svg+xml

    # The following line could be required or not depending on your Apache installation
    LoadModule cache_disk_module modules/mod_cache_disk.so

    <IfModule mod_cache_disk.c>
        CacheRoot /var/cache/apache2/mod_cache_disk
        CacheEnable disk /
        CacheDirLevels 2
        CacheDirLength 1
        CacheMaxFileSize 2000000
    </IfModule>
</IfModule>

FYI - The reason I'm using mod_cache with WP is that this project is based on the Bedrock framework which doesn't seem to work well with WP Super Cache and other plugins. They recommend using Memcached, Nginx or Varnish, none of which I have access to install.
Update

WP_CACHE is set to true
Added CacheMaxExpire 86400 to config and the X-Cache-Detail error changed to s-maxage or max-age zero and no Last-Modified or Etag and the Cache-Control header is now Cache-Control: private, proxy-revalidate, s-maxage=0
Added mod_expires:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access 1 month"
...
</IfModule>

Comment: Good God, they recommended Batcache and to stay away from W3TC and Super Cache? That makes me think they're doing things they really shouldn't be doing, and makes me suspicious of the whole framework, at least with respect to caching.
Comment: It's a good framework in that it moves the site config out of the web application which improves security but to do that the folder hierarchy has to be changed and it's this that causes problems with the caching plugins. I haven't found one that works with Bedrock yet - I did try hacking the code of WP Super Cache but the pre-load still doesn't work.
Answer: PHP is configured to send cache disabling headers, including the Expires: header you show, on pages which start a session. This date corresponds to the birthday of the PHP developer who implemented this feature.
You can configure this behavior by setting session.cache_limiter in php.ini.
If you are running WordPress there should not be a need to change this from its default of nocache, as pages with this header correspond to pages being sent to users logging in or already logged in and thus shouldn't be cached by Apache anyway. You might change it to private or private_no_expire to allow logged in users' browsers to cache the pages, though.
To test your cache, use an incognito window and hit your WordPress site while logged out.
Comment: @Daniel Check your plugins. Some badly written WP plugins try to start a session on every page load, whether a user is logged in or not.
Comment: Huh, interesting, thanks! Yes this is PHP and WP, however this is not a page with a session - I've been running all tests using Chrome Incognito while logged out. Updated post.
Comment: Thanks, will investigate. I added `CacheMaxExpire 86400` and the error message changed to `s-maxage or max-age zero and no Last-Modified or Etag`
Comment: I've tried all the variants of session.cache_limiter in every php ini but the headers are always returned as `Expires header already expired; not cacheable `
Comment: @Daniel I still suspect your third party code, such as Bedrock. Try this with a plain WordPress installation.


Calculate 3D rotation of a point

Question: How do I calculate the pitch, yaw, and roll angles for a point in 3D space?
I'm working on a game where the player character must face towards an object that's flying around.
Answer: For yaw, use the atan2() of the X and Y coordinates. For the pitch, use the X-Y magnitude and the Z coordinate. Points don't have a roll.

Calculate 3D rotation of a point


optimizing query by removing distinct key word

Question: I am trying to tune the one query to increase the performance of the stored function by removing the distinct keyword.
in the process of query tuning, I came across the query in the stored function where the distinct keyword is using due to that performance is degrading, so I am trying to write the query with same functionality without using a distinct keyword.
Current code with distinct keyword:-
select distinct dm.strdatadest
            from PUBLIC.temp te1
            JOIN PUBLIC.applicationconfiguration AC on AC.intapplicationid = te1.applicationid
            JOIN columnmapping cm on cm.intapplicationid = AC.intapplicationid
            JOIN datamapping dm on lower(dm.strcolumnsource) = lower(cm.strcolumnsource)
            JOIN srctable s on s.applicationid=AC.intapplicationid
            where lower(cm.strtablesource) = lower(s.tablename) and
            lower(dm.strdatasource) = lower('||quote_literal(rec.status) ||') and lower( dm.strcolumndest ) LIKE ''strstatus'' and te1.applicationid='||quote_literal(rec.applicationid);

Trying code by removing distinct keyword:-
select  dm.strdatadest
from PUBLIC.temp te,
PUBLIC.applicationconfiguration AC,
            PUBLIC.columnmapping cm,
            PUBLIC.datamapping dm
            where AC.intapplicationid = te.applicationid and cm.intapplicationid = AC.intapplicationid and lower(dm.strcolumnsource) = lower(cm.strcolumnsource)
            and lower(cm.strtablesource) = lower(s.tablename) and
            lower(dm.strdatasource) = lower('||quote_literal(rec.priority) ||') and lower( dm.strcolumndest ) LIKE ''strpriority'' and te1.applicationid='||quote_literal(rec.applicationid)
            GROUP BY dm.strdatadest;

i required some sujjestion who to tune query by removing distinct keyword
Comment: BTW, you should keep the explicit `JOIN` syntax anyway.
Comment: GROUP BY instead of SELECT DISTINCT? What do the queries' execution plans say?
Comment: changing a distinct clause with an group by seems not a good idea ..  in the better case you have the same performance  . ..
Comment: I'm afraid both solutions will perform about the same.
Comment: if you need  better performance try improve your indexing
Comment: Your probably is probably not the `select distinct` but instead the `join` conditions that use functions.
Answer: There are two points about your query that should be mentioned

implicit join vs explicit join which approximately has the same performance.

people often ask if there is a performance difference between implicit and explicit joins. The answer is: "Usually not"

distinct vs group by which distinct is optimum for memory usage and group by is optimum for speed so the latter outperforms the former but requires a large amount of memory if needed.

The distinct approach is executed like:

Copy all business_key values to a temporary table

Sort the temporary table

Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

Scan the full table, storing each value of business key in a hashtable

Return the keys of the hashtable

An astute explanation on the links below.
implicit join vs explicit join
distinct vs group by


Angular Material - Date picker muda a data quando tiro o foco do input

Question: estou enfrentando problemas no Angular. Estou usando o angular material para alguns /componentes e eu estou usando o datepicker. O meu date locale já é 'pt', aparece até o nome dos meses em portugues e tal. Mas quando eu digito no input 11/08/1997 e clico fora do input, ele muda para 08/11/1997. Já tentei de tudo aqui mas não consegui.
Comment: Poderia colocar um trecho do código para facilitar a compreensão do problema? Você está utilizando o momentjs?
Answer: Conseguir resolver colocando isso no meu modulo:
import { MatNativeDateModule, MAT_DATE_FORMATS } from '@angular/material';
import { MomentDateModule } from '@angular/material-moment-adapter';

...
providers: [
  {
    provide: MAT_DATE_FORMATS,
    useValue: {
      parse: {
        dateInput: ['l', 'LL'],
      },
      display: {
        dateInput: 'L',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
      },
    },
  }
]

e no meu componente do input
import { DateAdapter } from '@angular/material';
    ngOnInit() {
    this.dateAdapter.setLocale('pt-br');
  }


Modified central binomial coefficients generating function

Question: Given $n \in \mathbb{N}$, I would like to find the ordinary generating function of the sequence $a_k = \binom{2n-2k}{n-k}$.
If
\begin{align}
A(x) = \sum_{k = 0}^\infty a_kx^k,
\end{align}
then I find that
\begin{align}
A(x) &= \sum_{k = 0}^n \binom{2n-2k}{n-k}x^k \\
&= \sum_{k = 0}^n \binom{2k}{k}x^{n-k} \\
&= x^n\sum_{k = 0}^n \binom{2k}{k} \left(\frac{1}{x}\right)^k
\end{align}
but I am stuck here. My understanding is that you cannot extend the last finite sum into an infinite series, so I cannot use the generating function of $\binom{2k}{k}$.
I have also tried rewriting $A(x)$ as
\begin{align*}
A(x) &= [y^n]\left(1 + xy + (xy)^2 + \cdots\right)\left(\sum_{i \ge 0} \binom{2i}{i}y^i\right)\\
&= [y^n] \frac{1}{1-xy}\frac{1}{\sqrt{1-4y}}
\end{align*}
but I have no idea how to proceed from here.
Any idea is greatly appreciated.
Comment: If the original problem, like I believe, is the computation of $\sum_{k=0}^{n}\binom{2k}{k}\binom{2n-2k}{n-k}$, by convolution you only need $\sum_{k\geq 0}\binom{2k}{k}x^k$, since $$\sum_{k=0}^{n}\binom{2k}{k}\binom{2n-2k}{n-k}=[x^n]\left(\sum_{k\geq 0}\binom{2k}{k}x^k\right)^2.$$
Comment: Hi Jack, sadly no, I am genuinely interested in the generating function of $\binom{2n-2k}{n-k}$.
Comment: I'm not hopeful for a nice answer. When I asked Mathematica for the generating function, it gave something involving the hypergeometric function ${}_2F_1$.
Answer: We consider $a_{n,k}=\binom{2n-2k}{n-k}$ with $n,k\geq 0$ non-negative integers.

Horizontal GF: First of all we note that
\begin{align*}
A_n(x)=\sum_{k=0}^na_{n,k}x^k=\sum_{k=0}^n\binom{2n-2k}{n-k}x^k\qquad\qquad n\geq 0
\end{align*}
is a polynomial in $x$ and as such a perfect ordinary generating function, a so-called horizontal generating function. Since it is a polynomial having a finite number of terms $a_{n,k}x^k$ not equal to zero, we do not expect a representation via $\frac{1}{\sqrt{1-4x}}$ which is an infinite series.

Vertical GF: On the other hand we can consider the vertical generating function for fixed $k\geq 0$:
\begin{align*}
B_k(y)&=\sum_{n=k}^\infty a_{n,k}y^n=\sum_{n=k}^\infty\binom{2n-2k}{n-k}y^n\\
&=\sum_{n=0}^\infty\binom{2n}{n}y^{n+k}\\
&=\frac{y^k}{\sqrt{1-4y}}
\end{align*}

Bivariate GF: We have the bivariate generating function $G(x,y)$ with $A_n(x)$  and $B_k(y)$ as horizontal resp. vertical section:
\begin{align*}
\color{blue}{G(x,y)}&=\sum_{k=0}^\infty\sum_{n=k}^\infty a_{n,k}x^ky^n\\
&=\sum_{k=0}^\infty\sum_{n=k}^\infty\binom{2n-2k}{n-k}x^ky^n\\
&=\sum_{k=0}^\infty\sum_{n=0}^\infty\binom{2n}{n}x^ky^{n+k}\\
&=\sum_{k=0}^\infty(xy)^k\sum_{n=0}^\infty \binom{2n}{n}y^n\\
&\,\,\color{blue}{=\frac{1}{1-xy}\,\frac{1}{\sqrt{1-4y}}}
\end{align*}
Answer: Here's the Mathematica result that I mentioned in the comments, in case it's helpful.  It uses Gauss's hypergeometric series ${}_2F_1$ (for background, see the beginning of Gasper & Rahman's Basic Hypergeometric Series, Cambridge, 2004).
$$\sum_{=0}^ {2n-2k \choose n-k} ^ = {2n \choose n} \, {}_2F_1\!\left(1,-n;\frac{1}{2}-n;\frac{x}{4}\right)$$


IIS: Redirect HTTP to HTTPS for all URLs

Question: For our website (Windows Server 2016 Datacenter, IIS 10) we use two different URLs - lets say url1.com and url2.com by using the same root directory and the same application pool.
In our web.config we define a redirection
<rules>
  <rule name="Redirect to HTTPS" stopProcessing="true" xdt:Transform="Insert" >
    <match url="^(.*)$" />
    <conditions>
      <add input="{HTTPS}" pattern="^OFF$" />
      <add input="{HTTP_HOST}" matchType="Pattern" pattern="^localhost(:\d+)?$" negate="true" />
      <add input="{HTTP_HOST}" matchType="Pattern" pattern="^127\.0\.0\.1(:\d+)?$" negate="true" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
  </rule>
</rules>

This works for all requests like url1.com, http://url1.com and http://www.url1.com but not for url2.com. Entering url2.com in our browser leads to http://url2.com and thus to error 403 .
What is wrong?
Answer: Some time of thinking solved our problem: The detailed (IIS) error number was 403.4 - SSL required. This means that my request was rejected already by IIS and did not reach our website. Thus, no redirect to https:// could be applied for url2.com.
In the IIS manager I found that for this URL "SSL required" had been selected. Unchecking this box solved my problem.


Euler graph having simple cycles

Question: One property of Euler graphs is that if a graph with $n \geq 3$ vertices and more than $n$ edges has an Euler circuit, then it has more than two simple cycles.
How can we prove it?
Comment: I am not sure I understand.  If you take the graph with 5 vertices A, B, C, D, and E, and 6 edges AB, BC, CA, AD, DE, EA then the edges in that order ABCADEA provide an Euler circuit and there are just two simple cycles ABCA and ADEA. Or does *simple* mean something else?
Comment: This looks like homework (and your past questions add more credence to that supposition). Why don't you show what you have tried? It is usually bad form to post homework questions without showing indications of having put in some effort...
Comment: @Henry: I guess it is at least two, rather than more than two...
Answer: Hint (for atleast two, see Henry's comment): Consider the vertex with the maximum degree.
Answer: Hints: Consider a Euler circuit as you know there is at least one.

Can you split the circuit into cycles?
Where?
Why?
Does that leave you with simple cycles?
If not, what can you do to create simple cycles?

Euler graph having simple cycles


Question about SQL function GETDATE()

Question: When I insert time with that sql function and get the time out with a select time to present it.. it gives me time in an American way: 6/28/2009 instead of the European way that i want 28/06/2009. Is there a quick way to convert between the times.
And another question will i have a problem when i convert the time to DateTime instead of converting to other Time objects such as ... DateTimeOffset
Answer: Use the DATE_FORMAT SQL function. Instead of SELECT date FROM mytable;, say SELECT DATE_FORMAT(date, ...) AS mydate FROM mytable;. You can configure the date formatting freely in analogy to date(1) on Linux.
The inverse function is STR_TO_DATE.
Comment: I dont use SQL to convert the date, but i use C# code when presenting the data.. can i use a  function to insert it as a European date...
Comment: Do you have an option to change your SQL query, though? Make the DB do the work so you don't have to.
Comment: lol..i thik i will use the DateTime class and extract the info and seperate it, I think it is they simplest option. Thanks for the help
Answer: Look at Convert function

Question about SQL function GETDATE()


Iniciar aplicação somente se uma url está em funcionamento (Online)

Question: Estou começando á tentar aprender um pouco na "marra", e queria saber se tem como fazer algum código que verifique se uma URL especifica está online, caso ela esteja a aplicação tem que iniciar normalmente, caso não, a aplicação deve ser fechada.
Alguém tem alguma ideia de como posso fazer isso em C#?
Answer: Tem sim Peeta !
<code>    //Aqui você cria a requisição
     WebRequest request = WebRequest.Create("http://www.sitepratestar.com.br");

    try{
         //Envia a requisição e recebe uma resposta ,  não recebendo é lançada uma exceção e o código segue pro catch
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();

         //Testa se o status code da resposta foi 200 ,  que é retornado quando a url está online .

         if(response.StatusCode == HttpStatusCode.OK)
         {
               // Execute seu código...
               Console.WriteLine("URL ONLINE !!");
         }
         else
         {
               //status code diferente de OK, manda pro catch
               throw new Exception();
         }
   }
   catch
   {
       // Feche seu app aqui
   }
</code>


Android : Cannot update RecyclerView

Question: I am developing an Android application in Kotlin and I implemented a RecyclerView.
The two parameters that are added to the parametersList are displayed, but when I press the TEST button, the RecyclerView is not updated! I don't understand my mistake, can you help me?
Here is my adapter:
class CustomAdapter(private val parameterList: List<Parameter>, private val onClick: ((selectedParameter: Parameter) -> Unit)? = null) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun showItem(parameter: Parameter, onClick: ((selectedParameter: Parameter) -> Unit)? = null) {
            itemView.findViewById<TextView>(R.id.parameterName).text = parameter.parameterName
            itemView.findViewById<TextView>(R.id.parameterValue).text = parameter.parameterValue as CharSequence?

            if(onClick != null) {
                itemView.setOnClickListener {
                    onClick(parameter)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.parameter_text, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.showItem(parameterList[position], onClick)
    }

    override fun getItemCount(): Int {
        return parameterList.size
    }

}

My activity:
class NFCActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_nfc)

        buttonTest.setOnClickListener() {

            parametersList = parametersList + ParameterText("Temperature", "24°C")
            rv_parameters2.adapter?.notifyDataSetChanged()
        }

        rv_parameters2.adapter = CustomAdapter(parametersList) { item ->
            println("------------------OnClick------------------")
        }
        rv_parameters2.layoutManager = LinearLayoutManager(this)

    }

    private var parametersList : List<Parameter> = listOf<Parameter> (
            ParameterText("Temperature", "24°C"),
            ParameterText("Temperature", "24°C")
    )

    companion object {
        fun getStartIntent(context: Context): Intent {
            return Intent(context, NFCActivity::class.java)
        }
    }
}

parameter_text.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="10dp">

    <TextView
        android:id="@+id/parameterName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="@string/parameter_name"
        android:textColor="@color/black"
        android:textSize="16sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/parameterValue"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/parameterValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="@string/parameter_value"
        android:textSize="16sp"
        app:layout_constraintStart_toEndOf="@id/parameterName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="@+id/parameterName"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_nfc.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.ble.NFCActivity">

    <Button
        android:id="@+id/buttonTest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TEST"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_parameters2"
        tools:listitem="@layout/parameter_text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/buttonTest"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

EDIT 1: (following SlothCoding's answer)
My new activity:
class NFCActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_nfc)

        buttonTest.setOnClickListener() {

            parametersList = parametersList + ParameterText("Temperature", "24°C")
            rv_parameters2.adapter?.notifyDataSetChanged()
        }

        rv_parameters2.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        rv_parameters2.adapter = CustomAdapter(parametersList) { item ->
            println("------------------OnClick------------------")
        }
    }

    private var parametersList : List<Parameter> = listOf<Parameter> (
            ParameterText("Temperature", "24°C"),
            ParameterText("Temperature", "24°C")
    )

    companion object {
        fun getStartIntent(context: Context): Intent {
            return Intent(context, NFCActivity::class.java)
        }
    }
}

EDIT 2: (following Sekiro's answer)
CustomAdapter
class CustomAdapter(private val parameterList: List<Parameter>, private val onClick: ((selectedParameter: Parameter) -> Unit)? = null) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    private var parameterListLocal: List<Parameter> = parameterList

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun showItem(parameter: Parameter, onClick: ((selectedParameter: Parameter) -> Unit)? = null) {
            itemView.findViewById<TextView>(R.id.parameterName).text = parameter.parameterName
            itemView.findViewById<TextView>(R.id.parameterValue).text = parameter.parameterValue as CharSequence?

            if(onClick != null) {
                itemView.setOnClickListener {
                    onClick(parameter)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.parameter_text, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.showItem(parameterListLocal[position], onClick)
    }

    override fun getItemCount(): Int {
        return parameterListLocal.size
    }

    fun addNewList(newList: List<Parameter>){
        parameterListLocal = newList;
        notifyDataSetChanged();
    }

}

NFCActivity
class NFCActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_nfc)

        buttonTest.setOnClickListener() {

            parametersList = parametersList + ParameterText("Temperature", "24°C")
            (rv_parameters2.adapter as CustomAdapter).addNewList(parametersList)
        }

        rv_parameters2.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        rv_parameters2.adapter = CustomAdapter(parametersList) { item ->
            println("------------------OnClick------------------")
        }
    }

    private var parametersList : List<Parameter> = listOf<Parameter> (
            ParameterText("Temperature", "24°C"),
            ParameterText("Temperature", "24°C")
    )

    companion object {
        fun getStartIntent(context: Context): Intent {
            return Intent(context, NFCActivity::class.java)
        }
    }
}

Comment: Check this answer I posted earlier: https://stackoverflow.com/a/65545398/14759470
Comment: I tried to do what you advise in the link you gave me but it doesn't work.
Comment: What exactly did you change in your codE?
Comment: I edited my first question with my new code
Answer: The issue is with your buttonTest.setOnClickListener() where you are updating the list but the adapter knows nothing about the updation of the arraylist, instead pass the new arraylist to the adapter and call notifyDataSetChanged()
Try the following
CustomAdapter
// add this new function

fun addNewList(newList: List<Parameter>){
   parameterList = newList;
   notifyDataSetChanged();
}

trigger addNewList through buttonTest.setOnClickListener
buttonTest.setOnClickListener() {
       parametersList = parametersList + ParameterText("Temperature", "24°C")
       (rv_parameters2.adapter as CustomAdapter).addNewList(parametersList)
}

Edit:
notifyDataSetChanged() is indeed a costly operation and should be replaced with either notifyItemInserted or a better choice would be to use ListAdapter
Comment: glad it worked, you dont have to add a new attribute, just update `parameterList` and call `notifyDataSetChanged()` , Happy coding :)
Comment: I followed your advice and it works! I had to add a `parameterListLocal` attribute in the **CustomAdapter** class but I don't know if it's the best thing to do.

Android : Cannot update RecyclerView


How to validate expiry date in php on local server (like xampp) project with no internet connection

Question: It works fine when system has correct date time.But when a user changed system date time by control panel(window system) then it bypass the security.I use this condition to validate.
if( (strtotime($this->system_date) <= strtotime($license_arr[4])) ){
     die('***********Licence Valid *****************');
}
else{
     die('***********Licence In-Valid *****************');
}

on [4] key of $license_arr expiry date used.
Answer: Fetch current datetime from your database also.
So user "system date" must be greater than "current datetime"
Check if your user "system date" between  database fetched datetime &   $license_arr expiry then it is valid
Comment: Hi Dipanwita ,thanks for your answer.I have checked it with mysql now() function it is giving me wrong date.It is giving same date as system date set.
Answer: It takes server date and time, restricts physical access to your server.


How to interpret regression coefficients when the dependent variable is square root transformed?

Question: I have problem with interpreting the OLS regression result with the dependent variable square root transformed when doing difference-in-differences analysis.
Our regression model is:
$$
Y = β_0 + β_1 {\rm policy} + β_2 {\rm treated} + β_3 {\rm policy} \times  {\rm treated} + \ldots + β_i X_i + \varepsilon
$$
Where ${\rm policy}$ is a dummy variable indicate the policy change (0=pre-policy vs. 1=post-policy). ${\rm treated}$ is also a dummy variable indicate treatment or control group (0=control, 1=treatment)
To deal with the skewed distribution, $Y$ was square root transformed. Just wondering how can we interpret the result? Say, after the policy change, $Y$ was increased / decreased by ____?
Answer: Let $X = \sqrt{Y}$. I am assuming that $$ X = \beta_0 + \beta_{1} \text{policy} + \beta_{2} \text{treated} + \beta_{3} \text{policy} \times \text{treated} + \dots + \beta_{i}X_{i} + \varepsilon$$
Suppose after a policy change, the expected value of $X$ increased by $c$ adjusted for the other variables.
Comment: If the square root was taken to normalize the residuals, it wouldn't be the average that increased by $c^2$ but the median. Also note that if the relationship were rectilinear in the original space, it would be curving in the transformed space & vice versa.
Comment: @XiaohuiWang, I'm not sure if I follow you. You should not transform Y to normalize its distribution, only the residuals (see [here](http://stats.stackexchange.com/a/33320/7290)). Re: how to interpret your situation, that is covered in the linked duplicate thread.
Comment: A thing to watch out for is *inference* in untransforming the outcome. Because $\sqrt{\sigma^{2}_{\beta}} \ne \sigma^{2}_{\sqrt{\beta}}$, you cannot assume that predictors found to be significant in a model of $Y^{2}$ would likewise be significant in a model of $Y$ (i.e. we would expect *different* values of the various *t* statistics for the $\beta$s in $Y^{2} \sim \mathbf{BX}$ as compared to $Y \sim \mathbf{B}\sqrt{\mathbf{X}}$).
Comment: This answer suddenly seems incomplete: it does not appear to say anything.
Comment: Thank  @gung  square root was used to deal with the skewed distribution of  Y. In this case, would you guy please give more deals about the interpretation?
Comment: @missingdataguy Thanks for your suggestion. But still do not know how to get c? would you please kindly explain more?