AJAX or more specific MooTools Request.JSON error types?

Question: I'm trying to get myself an overview about all the errors that can occur on Request.JSON().
I've googled for a while but there seems not to be any overview about them all.
What I've figured out was that the 404 error occures if no such file is available to request on.
Does anyone have an idea where to find them? I think it has not to be specific mootools errors, what I'm looking for are the AJAX errors itself.
Kind regards
Answer: Well, Ajax itself has no 'error codes'. Ajax is simply an asynchronous request you are making to a server without refreshing a page.
Things that can go wrong are the same things that can go wrong on a normal request. These are for instance the http status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Some frameworks implement some extra error codes or change some of them. Most frameworks/libs (like Mootools) have a usefull onFailure() function that passes in the xhr object used dor the request.
The 'error' code is thus noet an 'ajax' code but a http code.


auto.arima with an input of another series

Question: Two time series, which are related to each other.
I want to see if "order" helps in predicting sales, by running auto.arima with and without the input of order.
sales<- c(15,25,37,45,53,72,77,88,97,83,92,85,113,133,124,137,131,147)
order<- c(35,35,36,39,40,40,42,46,45,45,50,51,49,53,53,56,56,58)

sales_ts <- ts(sales, frequency = 1, start=c(1950))
order_ts <- ts(order, frequency = 1, start=c(1950))

auto.arima without the input.
auto.arima(sales_ts)

Series: sales_ts

ARIMA(0,1,0) with drift

Coefficients:
       drift
      7.7647
s.e.  2.6222

sigma^2 estimated as 124.2:  log likelihood=-64.59

AIC=133.18   AICc=134.04   BIC=134.85

auto.arima with the input of a series.
auto.arima(sales_ts, xreg = order_ts)

Series: sales_ts

Regression with ARIMA(0,0,0) errors

Coefficients:
      intercept    xreg
      -146.8293  5.0626
s.e.    16.4214  0.3521

sigma^2 estimated as 135.7:  log likelihood=-68.67

AIC=143.35   AICc=145.06   BIC=146.02

Judged from the AIC values (133.18 vs 143.35). Am I right that the input of the order series is not helpful in fitting the auto.arima for sales?
The ultimate goal is to predict sales. ARIMAX only provides model fitting but no forecast, so I want to see how auto.arima can help in forecasting when combined the 2 series.
Answer: Judging only by the AIC, you would be correct: smaller AICs are better, and a difference of 10 is quite strong. It appears as if the model without the external regressor is a better fit to the data, and will therefore probably perform better in forecasting.
However.
It's always a good idea to plot data.
plot(sales_ts)
lines(order_ts,col="red")
legend("topleft",lwd=1,col=1:2,legend=c("Sales","Orders"))

The correlation is not perfect, but there seems to be an obvious relationship between sales and orders. Enough that I suspect there may be more here than meets the eye.
I see two possibilities:

The AIC reported by auto.arima() may only account for the ARIMA model part, not the regression on orders that precedes the ARIMA modeling. I can't tell, and the documentation is not telling, either. You may want to dig through the source code.

Both sales and orders show an increasing trend. The question really is whether there is an "inherent" trend in sales (which can be captured by the drift term in your first model), or whether sales are mainly driven by the (trending) orders.
Unfortunately, there is no way to disentangle this with just the data you have. You would need to wait for a time with increasing orders and decreasing sales to have an indication that the two are independent...

To be honest, sales being driven by orders (possibly with a lag) seems to be obvious enough to me that I would try to use orders in forecasting sales. I would suggest that you find out how far ahead orders happen with respect to sales, to see how much you need to lag them. (And if you need to forecast further out, you will need to forecast the orders themselves.)
Then you can compare models using a holdout sample. This may be helpful.
Comment: sir, thanks for the fantastic breakdown of the problem, and explanation. Wish you a good day!


"Set of observations" is an identity map - why such a framework?

Question: First of all, I do not ask this on CrossValidated since I'm speaking here of mathematical statistics, which explicitly belongs to mathematics.
I am currently working on rank tests in order to write an introduction on this theory. My main reference work is Theory of Rank Tests (Hájek, Šidák and Sen, 1999, 2nd edition)
They begin, naturally, by defining the terms and the general framework they will use, as follows:

2.1.1 Probability space and observations From a probabilistic point of view, a random experiment is represented by a probability space $(\Omega,\mathcal{A},P)$, where $\Omega$ is the space of all possible outcomes of the experiment, $\mathcal{A}$ is a $\sigma$-field determining how finely the outcomes are distinguished, and $P(\cdot)$ is a probability measure. In this setup, observations are defined as $\mathcal{A}$-measurable functions.

Until here, I understand perfectly. It is the classical framework.

From a statistical point of view, an experiment is described by an indexed set of observations $X=(X_{1},X_{2},\dots,X_{N})$, each observation $X_{i}$ taking its values $x_{i}$ on the real line or on a proper subset of the real line. The set of observations is determined by its (joint) distribution function
  $$\begin{align}F(x_{1},\dots,x_{N})&=P(X_{1}\le x_{1},\dots,X_{N}\le x_{N}) \tag{1}\\
&-\infty<x_{1},\dots,x_{N}<+\infty
\end{align}$$

Here, I understand that $P$ in $(1)$ is the induced probability measure on $(E^N,\mathcal{E}_{N})$ by $\hat{P}$ where $X_{i}:(\Omega,\mathcal{A},\hat{P})\to(E,\mathcal{E})$ is a $(\mathcal{A},\mathcal{E})$-measurable function for all $i=1,\dots,N$ ($\mathcal{E}$ and $\mathcal{E}_{N}$ are appropriate $\sigma$-fields).
Is that correct?
The book continues with:

2.1.2 Statistics, $\sigma$-fields and $\lambda$-fields A set of observations $X$ together with a distribution function $F(x)$ generates a probability space $(\mathcal{X},\mathcal{A},P)$ as follows: $\mathcal{X}$ is the space of all possible values $x=(x_{1},\dots,x_{N})$ of $X$, i.e. it is an N-dimensional Euclidean space; $\mathcal{A}$ is the $\sigma$-field of Borel subsets of $\mathcal{X}$, i.e. the smallest $\sigma$-field containing all events appearing on the right side of $(1)$; finally, $P(\cdot)$ is the probability measure uniquely determined by $(1)$. The set of observations may be considered as an identity map $X(x)=x,\,x\in\mathcal{X}$.
[...] As a rule, the probability distribution $P(\cdot)$ will be determined by a density $p$,
  $$P(A)=\int_{A}p(x)\text{d}x\tag{$A\in\mathcal{A}$}$$

This is where I do not fully understand what they mean. They consider $X$ as being defined as follows:
$$X:(\mathcal{X},\mathcal{A},P)\to(\mathcal{X},\mathcal{A},P):x\mapsto X(x)=x$$
And then, while usually $P(X\in A)$ was a notation for $P(X^{-1}(A))$, we have now $P(X^{-1}(A))=P(A)$ since $X$ is the identity. But what motivates such a framework? I mean, why would someone consider $X$ as an identity map. I must admit that I am more used to statistics viewed from a probabilistic point of view (actually, it does not make sense to me to speak about "probalistic point of view" and "statistical point of view"). What does motivate someone to consider the "observation set" (whose components are usually considered as a random variables, as far as I know) as an identity map? Why would we need to consider it that way? Why can't we stay in a general "probabilistic point of view" with $X_{i}$ being general random variables?
I understand it can be a very basic question, but I am quite confused with such a choice in the framework.
Answer: That's about representation of probability spaces. The original definition is: for random experiment we need to have some sample probability space, and observations are measurable maps from that space to the range space. These maps induce the joint probability measure. Now, usually you know what is the range space, and what is the joint distribution, so 2.1.2 says how to build sample probability space out of it: just take this space itself (of course, there are some other ways to do that, but this one always works). Since random experiment also requires observation maps, you need to define them as well: such that they push joint distribution to joint distribution. The identity map for sure would work in this case. This construction often appears in other areas of probability, such as theory of stochastic processes, and is often called canonical probability space for process etc.
Comment: Thank you. To be sure I understand correctly, the $X_{i}$'s are classical random variables, and the sample space is built by considering the joint probability of these $X_{i}$'s and the probability space they generate (the so-called "sample space"). Then, we consider $X$ as the identity map between this sample space and itself in order to consider it as a random vector?
Comment: @MoebiusCorzer: not sure I got you. To clarify, the random experiment on the range space $(E,\mathcal E)$ is the tuple $(\Omega, \mathcal F, \mathsf P, f)$ where $f$ is $\mathcal F|\mathcal E$-measurable. Then $\mathsf Q := \mathsf P\circ f^{-1}$ is the joint probability distribution. If you are given $(E,\mathcal E, \mathsf Q)$ you can construct a random experiment by taking $\Omega = E$, $\mathcal F = \mathcal E$, $\mathsf P = \mathsf Q$ - only $f$ is missing. It needs to satisfy $\mathsf P\circ f^{-1} = \mathsf P$, so $f = \mathrm{id}$ works.
Comment: Thank you very much. I had never heard of that explictly before.
Comment: @MoebiusCorzer: I've found it interesting some time ago, and I have a couple of pages with rumblings on this topic, with examples if you are interested.
Comment: I am, definitely. You have a link or do you need an email address?
Comment: @MoebiusCorzer: section 2.1 [here](https://web.comlab.ox.ac.uk/people/alessandro.abate/publications/cTA14.pdf)
Comment: Thank you. I'll read it. Does your work have any link with Stein's method?
Comment: @MoebiusCorzer: never heard of it before, and there is no explicit link - at least based on what I just read about Stein's method. An interesting one, though - I also look into different kind of metrics, but on bigger spaces, so there may be some connections.


Como posso obter o input do html para o js

Question: Como é que eu posso pegar no input de alguem no html e dar log (console.log) na consola.
Basicamente eu quero poder pegar no input do utilizador e dar log dele na consola (console.log)
Porfavor caso ache que a pergunta esta mal estruturada explique no que posso melhorar e não dê logo -1!
FORM HTML
<form id="OrderForm">
            <input id="ON" class="OrderName" type="text" name="OrderName" placeholder="Buyer Name" value="" required>
            <input id="OD" class="OrderDate" type="text" name="OrderDate" placeholder="Date of Order" required>
            <input id="sku" class="SKU" type="text" name="ProductSKU" placeholder="Product SKU" required>
            <input class="SUBMIT" type="submit" name="Submit" value="SUBMIT">
          </form>

WEBSITE

function appendOrders(orders) {
  var ElementOrders = document.getElementById("Orders")
  ElementOrders.innerHTML = orders
}

function appendEarnings(earnings) {
  var ElementEarnings = document.getElementById("Earnings");
  ElementEarnings.innerHTML = earnings
}

function JSONLOAD() {
  "use strict";

  fetch("Static/Data/DATA.json")
    .then(function(resp) {
      return resp.json();
    })
    .then(function(data){
      var Earnings = data.DataInfo[0].Earnings;
      appendEarnings(Earnings);
      var Orders = data.DataInfo[0].Orders;
      appendOrders(Orders)
    })
}

JSONLOAD()
body {
  margin-left: 0px;
  margin-right: 0px;
  margin-top: 0px;
  margin-bottom: 0px;
  background: #252C35;
  color: white;
}

#UpperBar {
  height: 45px;
}

.MASlime {
  position: absolute;
  font-size: 30px;
  top: 1px;
  left: 40px;
}

#Totals {
  position: absolute;
  font-size: 30px;
}

.Total {
  position: absolute;
  top: 70px;
  left: 130px;
}

.TotalEarnings {
  position: absolute;
  top: 70px;
  left: 200px;
}

.TotalO {
  position: absolute;
  top: 140px;
  left: 130px;
}

.TotalOrders {
  position: absolute;
  top: 140px;
  left: 200px;
}

#Earnings {
  position: absolute;
  top: 70px;
  left: 350px;
}

#Orders {
  position: absolute;
  top: 140px;
  left: 350px;
}

.NewOrder {
  position: absolute;
  top: 250px;
  left: 200px;
  font-size: 30px;
}

.OrderName {
  position: absolute;
  top: 350px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.OrderDate {
  position: absolute;
  top: 400px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.SKU {
  position: absolute;
  top: 450px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.SUBMIT {
  position: absolute;
  top: 500px;
  left: 220px;
  width: 100px;
  height: 40px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
  cursor: pointer;
}

.Menu {
  position: absolute;
  top: 25px;
  left: 480px;
  font-size: 30px;
  cursor: pointer;
}

.menu {
  text-align: center;
  width: 100%;
}

.menu a {
  display: block;
  border-bottom: 1px solid #EAEAED;
  border-top: 1px solid #EAEAED;
  text-decoration: none;
  color: white;
  margin-top: 120px;
  padding-bottom: 10px;
  padding-top: 10px;
  font-size: 30px;
  background: #252C35;
}

.All {
  display: block;
}

#toggle {
  display: none;
}

.fadeIn {
  animation: fadein 1.3s ease-in;
}

@keyframes fadein {
  0% { opacity: 0; }
  25% { opacity: 0.3; }
  50% { opacity: 0.5; }
  75% { opacity: 0.8; }
  100% { opacity: 1; }
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>EComerce App Slime</title>
    <link rel="stylesheet" href="Static/css/index.css">
    <link rel="icon" href="Static/Images/favicon.png">

      ☰
      <input type="checkbox" id="toggle" onclick="meuMenuToggle()"/>

          Slime Recipe

MASlime

Total

Earnings

Total

Orders

100€

1

New Order

          <form id="OrderForm">
            <input id="ON" class="OrderName" type="text" name="OrderName" placeholder="Buyer Name" value="" required>
            <input class="OrderDate" type="text" name="OrderDate" placeholder="Date of Order" required>
            <input class="SKU" type="text" name="ProductSKU" placeholder="Product SKU" required>
            <input class="SUBMIT" type="submit" name="Submit" value="SUBMIT">
          </form>

Answer: Se você quer dar um console.log() no que o user escreveu no input, você pode pegar a tag pelo id e assim, conseguir o valor dela.
input = document.getElementById("ON")
console.log(input.value)

Se você quiser que ele seja printado no console quando o user clicar no botão de submit, você pode adicionar um eventListener no Form.
<form onsubmit="printInput()">
  <input type="text" id="ON">
  <button type="submit" value="submit">
</form>

Comment: Isto é a unica coisa que ele está a dizer na consola `?OrderName=Antonio&OrderDate=1%2F11%2F1&ProductSKU=198&Submit=SUBMIT:39` e neste caso o que eu queria apenas o Antonio do nome!
Comment: Sim, isso acontece quando você clica no submit, os valores do input são passados na URL. Se você quiser o valor do input quando o usuário clicar, você colocar um eventListener na sua form pra quando o user clicar, ele printar no console de javascript o valor.
Comment: Poderia porfavor explicar como eu posso fazer isso !
Comment: Editei minha resposta!


Como desativar a main form quando outra foi aberta

Question: Desativar a main form quando outra foi aberta sem fechar a mesma para poder utilizar a segunda form que foi aberta mas não poder clicar na main form
Answer: Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Openlistaclientes.Click
    Form_ShowDialog()

End Sub

Comment: Isso é chamado [**Multiple-Document Interface (MDI)**](https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/multiple-document-interface-mdi-applications) é uma tecnologia que o **.net** legou do **Delphi** e serve para criar janelas "modais" que comumente são chamadas de "dialog"
Answer: Experimenta isto.
NomeDoForm.ShowDialog()

Comment: user111359, quando postar uma resposta, mesmo que esteja correta, explique detalhadamente o motivo. Assim, a dúvida é sanada corretamente, além evita comentários "Mas porque dessa forma ?"
Comment: Tinha-me enganado no lugar que metia isso mas já sabia como era obrigado


Bash one-liner way to preserve original pipe output file in presence of a pipe error?

Question: There are many ways to do this using intermediate files and functions or append/truncate, but I was curious if anyone knows how a one-liner way to express a conditionally non-destructive overwrite like either of:
# outfile not touched if script1 fails
script1  > outfile
# outfile not touched if script1 or script2 fails
script1 | script2 > outfile
# or maybe a "lazy >" command, but I'd rather see how bash itself can do this
script1 | script2 | magicproxy outfile

where outfile's prior contents remain untouched if its pipeline failed to output any valid stream content.
It is okay to mess up outfile if some output flows, but not if no output flows.
I don't know of anything bash-wise to account for this, as I am fairly certain it does not pend basic file setup related to a pipeline stdout file until it sees output flow. Unless there is a magic set -o lazy option lurking.
So I am looking for a one-liner way to make a pipeline more lazy than eager wrt basic stdout file setup, triggered "on first actual output", using bash conventions.
Comment: You're correct in that the FIFOs are all -- necessarily -- set up *before* the subprocesses are started. Can't be any other way -- after the `execve` calls are done, there's no way for the parent process to synchronously change where the FDs point.
Comment: The conventional thing is `script1 | script2 > tempfile && mv tempfile outfile`, albeit with a generated (guaranteed unique) as opposed to constant tempfile name.
Comment: ...that said, something like the `sponge` command from moreutils might be possible to extend into your use case, by adding an option to abort if no contents exist.
Answer: A Quick Note For Future Readers
The original question here asked only about waiting for at least one line of output to make it through the pipeline before modifying the output file. This is not the same as ensuring that the pipeline exits with a nonzero status before overwriting the destination file, but the section "depending on pipeline success" has been added with details on just that approach.

Depending on pipeline success
Unfortunately, this one's not so easy to write as a one-liner.
shopt -s pipefail # fail if any component of a pipeline doesn't succeed

tempfile=$(mktemp "$1".XXXXXX)
if script1 | script2 >"$tempfile"; then
  mv -- "$tempfile" "$1"
else
  rm -f -- "$tempfile"
fi

An obvious approach is to use eval, but this requires great care to avoid security bugs:
# DANGER: command_source *must* be a constant string; MUST NOT substitute argument values
#         directly into source -- instead, refer to variables from that string.
eval_to_output_file() {
  local command_source destfile tempfile retval
  command_source=$1
  destfile=$2
  tempfile=$(mktemp -- "$destfile.XXXXXX")
  if eval "$command_source" >"$tempfile"; then
    mv -- "$tempfile" "$destfile"
  else
    retval=$?
    rm -f -- "$tempfile"
    return "$retval"
  fi
}

...usage as:
# CRITICAL that script argument is single-quoted, and all arguments expanded by eval
# ...otherwise, expansions can perform code injection.
eval_to_output_file 'script1 "$arg1" | script2 "$arg2"' outfile

More safely, the pipeline could be encapsulated in a function:
# Safer alternative to eval_to_output_file
# Requires that a pipeline be encapsulated into a function
run_to_output_file() {
  local destfile retval
  destfile=$1; shift
  tempfile=$(mktemp -- "$destfile.XXXXXX")
  if "$@" >"$tempfile"; then
    mv -- "$tempfile" "$destfile"
  else
    retval=$?
    rm -f -- "$tempfile"
    return "$retval"
  fi
}

# example of a function running your pipeline
# note that arguments are passed through by the above
myfunc() (          # myfunc() ( ) instead of myfunc() { } means execute in a subshell
  shopt -s pipefail # because we're in a subshell, this won't propagate out
  script1 "$1" | script2 "$2"
)

run_to_output_file outfile myfunc arg1 arg2

Waiting only for the first line
magicproxy() {
  [[ $1 ]] || { echo "Usage: magicproxy filename" >&2; return 1; }

  if IFS= read -r first_line; then
    cat <(printf '%s\n' "$first_line") - >"$1"
  fi
}

Note that this means that your output file will exist with partial contents at some point.

Renaming after the entire stream is complete
magicproxy() {
  [[ $1 ]] || { echo "Usage: magicproxy filename" >&2; return 1; }

  local tempfile
  tempfile=$(mktemp -- "$1.XXXXXX") || return
  if cat >"$tempfile" && [[ -s "$tempfile" ]]; then
    mv -- "$tempfile" "$1"
  else
    rm -f -- "$tempfile"
  fi
}

...will work with your proposed pipeline:
script1 | script2 | magicproxy outfile

That said, if you're on a GNU system and the restrictive permissions used by mktemp don't work for you, you might also want to add:
# give your temporary file the same permissions as your destination
chmod --reference="$1" -- "$tempfile"

...before the mv.
Comment: Yes perfect! This is better done explicitly anyway due to the importance of clearly showing update avoidance cases.
Comment: Nice!  Detail question: if I'm reading correctly, both `magicproxy` versions will overwrite the named file if something earlier in the pipe produces output, but then fails after that (as opposed to failing before producing any output).  Am I right, or am I missing something?  Would `magicproxy` need to be called when `pipefail` is set to prevent writing `$1` in that case?
Comment: @cxw, ...so, the OP originally asked only about the no-output error case; covering anything else was a later extension. The tricky thing, here, is that there's no mechanism for the last entry in a pipeline to know how things earlier in that pipeline exited (after all, they're all running concurrently -- and moreover, in `A|B`, if `A` closes its stdout and waits for a while before exiting, then `B` can actually exit *before* `A` does, thus, while A doesn't *have* an exit status at all!)
Comment: @cxw, ...hence the first "depending on pipeline success" section not using magicproxy at all, and only permitting one-liner use with ugliness such as `eval`.
Comment: @cxw, ...well -- ugliness such as `eval`, or a function encapsulating the pipeline. You've actually encouraged me to extend with an answer demonstrating the latter.
Comment: Nice (again)!  I don't think I've seen `if "$@"` before.  Thanks for the edit!


Is it possible to run a Drupal 7 on 2 domains?

Question: I'm not sure is it about the server or Drupal. Anyway, my Drupal was installed inside the directory "/public_html" folder. We are pointing "mysiteA.com" and "mysiteB.com" into this directory.
Both urls look the same but only "mysiteB.com" is able to login. And "mysiteA.com" is showing "access denied" after submit the login form. The question is, Drupal is showing "mysiteB.com" domain inside the "configuration > Site information". Is there a way to change it to be "mysiteA.com" or both(not sure is it possible)?
Answer: Let's back up and debug this from the top:
Confirm that both sites actually point to the same Drupal installation.

Open up a terminal or command prompt. Ping mysitea.com and mysiteb.com. Confirm that the IP address is the same for both domains.
Create a dummy file test.html in the Drupal root. Confirm that you can access it from both mysitea.com and mysiteb.com.

Confirm both sites actually use the same database

Look in the sites directory. The only two directories should be "default" and "all". If you see mysitea.com or mysiteb.com, it's possible you are using different DBs.

Figure out what Drupal config is causing the error

Confirm that you don't have any domain-related modules installed (domain access).
See if clearing all cookies after switching to the second domain let's you log in. i.e., is the problem that you can't ever log in to one of the domains, or that you just can't log in to them one after another? This could be due to the cookie domain.

Try setting $cookie_domain in settings.php for each site.
EDIT: Now I see that you tagged your post "domain-access", so I'm assuming you are using that module. Why didn't you say that in your post? That's kind of a critical thing to know if your problem is related to accessing a site on two domains ;) I'm pretty sure it's just a misconfiguration or bad permissions related to Domain Access. Try disabling it and see if you can access both sites.
Comment: Thanks @danepowell.
1) yes, confirmed that both sites are pointed tot he same Drupal installation.
2) yes, confirmed both sites actually using the same database
3) yes, i didn't install any domain-access
Answer: It seem like something to do with Cookie domain like what @danepowell said above. So I added the following code. Now, it's working!
on file "sites/default/settings.php", I added
<code>$cookie_domain = '.mysiteA.com';
</code>
then I copy the file "sites/default/settings.php" to "sites/mysiteB.com/settings.php", and change the cookie_domain to
<code>$cookie_domain = '.mysiteB.com';
</code>


Accessing the AST when using Frama-C

Question: I want to access the Abstract Syntax Tree (AST) created by the Frama-C tool. Is there a plug-in or any other support to access the AST in Frama-C?
Answer: I think you can follow the development gui of Frama-C
http://frama-c.com/download/plugin-development-guide-Fluorine-20130601.pdf

Accessing the AST when using Frama-C


Problemas ao consumir REST pelo meu App

Question: Em realidade fiz no lado do serviço(que está funcionando) eu estou serializando uma lista, mas na verdade é apenas um único valor retornado. Para esse serviço eu tenho apenas uma informação, um valor decimal, mas tentei colocar uma Task simples e um retorno FirstOrDefault e dá erro. Bem, então mantive a List mesmo sabendo que não é a forma correta, mas vou alterar isso. O que preciso nesse momento é fazer meu App Android(Xamarin.Forms) consumir esse serviço. Ele está se perdendo. Pelo Postman ok, está funcionando meu REST, mas pelo App é que não funfa. Veja os códigos no meu App.
Fiz uma model exatamente com é no lado do serviço. Essa Model é exatamente idêntica à Model que está no REST, tudo.
public class DesvioFaturamento
    {
        public int IdUsuario { get; set; }
        public int IdGaragem { get; set; }
        public decimal Desvio { get; set; }
    }

Aí fiz uma classe para Desserializar o que o serviço que fornece
public class DataService
    {
        HttpClient client = new HttpClient();
        public async Task<List<DesvioFaturamento>> getDesvioFaturamento(int user, int garagem)
        {
            string url = $"http://localhost:2710/api/faturamento/{user}/{garagem}";
            var response = await client.GetStringAsync(url);
            var desvio = JsonConvert.DeserializeObject<List<DesvioFaturamento>>(response);
            return desvio;
        }
    }

E na minha MainPage.xaml.cs fiz o métod(click) que pega o que o serviço me disponibiliza assim:
try
            {
                if (!string.IsNullOrEmpty(txtUser.Text) && !string.IsNullOrEmpty(txtGaragem.Text))
                {
                    int user = Int32.Parse(txtUser.Text);
                    int garagem = Int32.Parse(txtGaragem.Text);
                    var data = await dataService.getDesvioFaturamento(user, garagem);
                    DesvioFatNotifications.Text = data.ToString();
                }
            }
            catch (Exception ex)
            {
                string erro = ex.Message;
            }

O var data... está quebrando. Quando chega nesse ponto não faz nada e preciso fechar o debug, senão fica sem nenhuma resposta. Claro não esperei mais do que 2 min, enfim, não funciona. Como consumir esse serviço?
EDIT1
Tentando resolver isso, eu coloquei essas linhas em meu projeto.
response.Wait(); // use assim ou com o while ....

                while (response.Status != System.Threading.Tasks.TaskStatus.RanToCompletion)
                {

                }

Está dando erro que:

"string" não contem uma definição para Wait e não foi encontrar nenhum
  método de extensão "Wait"...

Tenho uma outra App que não tenho erro nessas linhas e tenho as mesmas referências e etc...
EDIT2
Meu serviço está assim(Model):
[Route("faturamento/{iduser}/{idgaragem}")]
        public List<decimal> GetDesvioFaturamento(int iduser, int idgaragem)
        {
            var desvio = lista.Where(l => l.IdUsuario == iduser && l.IdGaragem == idgaragem)
                        .Select(s => s.Desvio).ToList();

            return desvio;
        }

Minha controller(ApiController)
[EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/Faturamento")]
    public class FaturamentoController : ApiController
    {
        DesvioFaturamentoModel desvio = new DesvioFaturamentoModel();

        [Route("{iduser}/{idgaragem}")]
        [AcceptVerbs("Get")]
        public IEnumerable<decimal> GetDesvioFaturamento(int iduser, int idgaragem)
        {
            return desvio.GetDesvioFaturamento(iduser, idgaragem);
        }
    }

Minha classe POCO
public class DesvioFaturamento
    {
        public int IdUsuario { get; set; }
        public int IdGaragem { get; set; }
        public decimal Desvio { get; set; }
    }

EDIT3

EDIT4
Fiz esse novo código
try
            {
                HttpClient client = new HttpClient();
                //client.BaseAddress = new Uri("http://localhost:2710/api/");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.Timeout = TimeSpan.FromSeconds(60);

                //string url = $"faturamento/{user}/{garagem}";
                string url = $"http://localhost:2710/api/faturamento/{user}/{garagem}";
                var uri = new Uri(string.Format(url));

                try
                {
                    HttpResponseMessage response = await client.GetAsync(uri);

                    if (response.IsSuccessStatusCode)
                    {
                        var json = response.Content.ReadAsStringAsync();

                        return JsonConvert.DeserializeObject<List<DesvioFaturamento>>(json.Result);
                    }
                }
                catch (HttpRequestException ex)
                {
                    string erro = ex.Message;
                }

                return null;
            }
            catch (TaskCanceledException ex)
            {
                string erro = ex.Message;
                return null;
            }

e na linha do HttpResponseMessage response = await client.GetAsync(uri);está dando esse erro:

An error occurred while sending the request

praticamente não diz nada
EDIT5
Tenho esse código em meu dataservice
try
            {
                client = new HttpClient();
                string url = $"http://localhost:2710/api/faturamento/{IdUsuario}/{IdGaragem}";
                try
                {
                    var response = await client.GetStringAsync(url);
                    var desvio = JsonConvert.DeserializeObject<List<DesvioFaturamento>>(response);
                    return desvio.ToList();
                }
                catch(Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

Quando chega nessa linha var response = await client.GetStringAsync(url); o app para e não sei mais o que acontece. Não cai no catch interno que coloquei.
Comment: hehehe seu erro esta no seu  var desvio = lista.Where(l => l.IdUsuario == iduser && l.IdGaragem == idgaragem)
                        .Select(s => s.Desvio).ToList();
Comment: bem aqui  .Select(s => s.Desvio)
Comment: ai vocÊ faz um  var desvio = JsonConvert.DeserializeObject>(response);
Comment: é o que retorna é uma lista de Desvio e não o tipo esperado ou seja List
Comment: veja seu proprio print que só tem um 99 e não sua classe
Comment: Então, estou com essa dúvida desde ontem. O que preciso seria retornar apenas o valor esperado e não estava conseguindo. No lugar de retornar um IEnumerable deveria retornar a minha classe, certo, @MarconcilioSouza
Comment: Não sei, vai da sua regra de negocio, o que você tem que saber é que tem que DeserializeObject para o mesmo tipo que você esta mandando. se você vai manda uma lista de DesvioFaturamento tem que  DeserializeObject  para uma lista do mesmo tipo ...
Comment: O que esta retornando no seu var response = await client.GetStringAsync(url); ??? você vai precisar so do Desvio
Comment: @MarconcilioSouza, então fiz isso e está vindo nula minha lista. Fiz uma alteração e quando chega nessa linha o sistema para: `HttpResponseMessage response = await client.GetAsync(uri);`
Answer: Tem alguns detalhes faltando no método que busca os dados da API. Vou modificar seu método para a forma que utilizo aqui e funciona perfeitamente.
public async Task<List<DesvioFaturamento>> GetDesvioFaturamento(int user, int garagem)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:2710/api/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string url = $"faturamento/{user}/{garagem}";

    HttpResponseMessage response = await client.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        var json = response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<List<DesvioFaturamento>>(json.Result);
    }

    return null;
}

Observações

Note que eu uso a propriedade BaseAddress para definir a URL base da sua API. Do jeito que estava fazendo também funciona, mas essa é a forma recomendada (boas práticas) para esse tipo de operação.
Adicionei um header à sua requisição: client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Timeout
Caso queira, é possível definir um timeout para a sua requisição. Para isso, basta adicionar a seguinte linha abaixo de client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));:
client.Timeout = TimeSpan.FromSeconds(60);

Feito isso, após 60 segundos sem resultado, o método irá retornar uma exceção do tipo TaskCanceledException.
public async Task<List<DesvioFaturamento>> GetDesvioFaturamento(int user, int garagem)
{
    try
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:2710/api/");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.Timeout = TimeSpan.FromSeconds(60);

        string url = $"faturamento/{user}/{garagem}";

        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            var json = response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<List<DesvioFaturamento>>(json.Result);
        }

        return null;
     }
     catch(TaskCanceledException ex)
     {
        /// TODO
     }
}

Comment: Quando chega nessa linha `HttpResponseMessage response = await client.GetAsync(url);` para. Tive esse problema antes e resolvi com o `Wait()` que coloquei em minha edição e que agora não está aceitando e não sei porque.
Comment: Coloca o timeout conforme falei ali em cima e adicione um try catch no método e verifique se é gerada uma exceção por timeout. Atualizei a resposta.
Comment: Cara, quando chega na linha acima para tudo. Não trava, mas nada acontece, como se ele estivesse se perdido. Vou editar e postar o código do serviço, mas adianto que testando pelo Postman eu obtenho o resultado esperado.
Comment: Coloca um breakpoint na linha if (response.IsSuccessStatusCode) e outro breakpoint no catch(TaskCanceledException ex) e veja se o código chega ali pelo menos. E outra, o endereço usado no postman está igual ao código? A sua API está online no endereço localhost informado?
Comment: O postman está exatamente como eu estou. O problema é que não chega nessas linhas. Já fiz isso e não chega. Quando chega na linha citada, para e não faz mais nada. Preciso dar um Kill. URL do Postman copiado e colado: http://localhost:2710/api/faturamento/1/1
Comment: Teria como colocar uma imagem do postman? Com o resultado e a URL?
Comment: Coloquei um screenshot do Postman.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/71404/discussion-between-perozzo-and-pnet).
Comment: Dá uma olhada no chat

Problemas ao consumir REST pelo meu App


Button in variable didn't work when i clicked. Angular Typescript

Question: When i use this function:
@Pipe({name: "safeHtml"})
export class Save implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }

  transform(value: any) {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
}
//-----------------------------------------------------------

FindTheResult(Group: string, Name: string) {

this.GetData().then(() => {
  this.ListOfName.forEach(name => {
    let Link = "Results/" + Group + "/" + name + "/" + Name
    this.FirebaseData.database.ref(Link).get().then(res => {
      if (res.val() == null) {

        this.tagName = `<h1>` + name + '

не приступал
' + `<button (click)="Back()">dasds</button>` + this.tagName

      } else {
        this.tagName = this.tagName + `<h1>` + name + '

' + String(res.val()) + '%
'
      }
    })
  })
})}
Back() {
this.IsTest = !this.IsTest}

I use this function to collect all data from a firebase. then i take all this stuff to variable 'tagName' and a button. But the button didn't work when i clicked.
P. s didn't work if i write this.Back() in (click)
Html:

My homework

nothing happens. Seems it just does not see this function
Answer: IMO the bypassSecurityTrustHtml() + [innerHTML] binding must only used in Angular if it couldn't be avoided. It doesn't support event handling such as (click)="Back()".
I'd define an array and use it to contain the value. Then use *ngFor and *ngIf directives to render it in the template.
public tags = [];

FindTheResult(Group: string, Name: string) {
  this.GetData().then(() => {
    this.ListOfName.forEach(name => {
      let Link = "Results/" + Group + "/" + name + "/" + Name
      this.FirebaseData.database.ref(Link).get().then(res => {
        this.tags.push({
          name: name,
          value: res.val()
        });
      })
    })
  })
}

Back() {
  this.IsTest = !this.IsTest
}

My homework

        <ng-container *ngFor="let tag of tags">

tag.name

            {{ tag.value }}

          <ng-container #noBack>

не приступал

            <button (click)="Back()">dasds</button>
          </ng-container>
        </ng-container>

Sidenote: I'm not sure how you'd click the button if the wrapping
 has a "pointer-events:none".
Comment: HOOOOOLY, Thanks. wooooow


Account for spatial autocorrelation with a binomial regression model

Question: I am using a binomial regression model for presence/absence, with 20 independent variables to test. The data has x and y coordinates and I would like to understand how can I take into account the spatial autocorrelation.
I already studied the correlation between the variables and run the same model for 1000 different samples (I have a big dataset that allows me to do this) to understand the distribution of each parameter and check for variables that might be introducing problems in my model.
glm_model <- glm(PA ~ Var1 + Var2 + Var3 + Var4 + Var5,family=binomial(link=logit))
However I believe I also need to account for spatial autocorrelation. I saw that there is a package that might help me (spdep), however I am not sure I completely understand if I can use my model or not. My question is what are my options ?
Answer: If you are happy to assume your binomial responses are coming from a spatially correlated gaussian random field via a logit link, and your non-spatial covariates have the usual log-linear form, then stuff it all into geoRglm:
http://cran.r-project.org/web/packages/geoRglm/vignettes/geoRglmintro.pdf
and once you've got your MCMC all tuned, out pops the parameter estimates.
Comment: +1 This package also has non-Bayesian solutions if you want to do some classical variography yourself without specifying priors.
Answer: It sounds to me like x, y are potential independent variables in your model. The issue is that the binomial regression model you mention assumes that the independent variables are not correlated. Some people add interaction terms to their model to deal with this, but a lot of model interpretability is lost when you do this.
You have several options for your classification problem. You could use for example k-means clustering. You can find a nice cheat sheet for classification methods in R here.
Answer: I found this tutorial for the spdep package to be quite useful.
In the end, you would want to create spatial weights like this:
us.nb4 <- knearneigh(coordinates(data[,1:2]), k=4)
us.nb4 <- knn2nb(us.nb4)
us.nb4 <- make.sym.nb(us.nb4)
us.wt4 <- nb2listw(us.nb4, style="W")

... which you could use into a Moran eigenvector filtering function to remove spatial autocorrelation from the residuals of (generalised) linear models (if you see the tutorial it will make sense).


In react hooks, how can i pass the filtered values to the chart?

Question: I am using React with hooks to pass filtered values to a chart.
The problem is that i was no able to pass the "filterData" values to the chart:
const filterData = data.datasets[0].data.filter(value => value > Number(filterdatanumber))

Any suggestion on how can i solve this?
I have tried different solutions existing in these videos https://www.youtube.com/watch?v=cz2rG-OVXXU, or create a new variable, among others, however nothing worked.
The complete code:
import React, { useState } from 'react';
import { Bar } from 'react-chartjs-2';

export default function VerticalBar() {
  const [firstNumber, setFirstNumber] = useState("");
    const textChangeHandler = (i) => {
    setFirstNumber(i.target.value);
    console.log("target.value", i.target.value);
    filterChart(Number(i.target.value));
  };

    const data = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [{
        label: 'Weekly Sales',
        data: [18, 12, 6, 9, 11, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };

    const filterChart = (filterdatanumber = Number.MIN_SAFE_INTEGER) => {
      const filterData = data.datasets[0].data.filter(value => value > Number(filterdatanumber))
      // const filterData = data.datasets[0].data.filter(value => value > 9)

      const filterLabels = [];
      const filterColors = [];
      let i = 0;
      for (i; i < filterData.length; i++) {
        const result = data.datasets[0].data.indexOf(filterData[i]);
        const labelsResult = data.labels[result];
        const colorssResult = data.datasets[0].backgroundColor[result];
        filterLabels.push(labelsResult );
        filterColors.push(colorssResult);
    }

    console.log("filterData", filterData)
    console.log("filterLabels", filterLabels)
    console.log("filterColors",filterColors)

    data.datasets[0].data = filterData;
    data.labels = filterLabels;
    data.datasets[0].backgroundColor = filterColors;
  }
  filterChart();

    return (

       <Bar  data={data} />
       <input value={firstNumber} type="number" name="firstNumber" onChange={textChangeHandler} />

    )
}

Comment: actually your code is applying the filtered data already. how do you see it is not?
Comment: The new approach to solve this problem below is much better, however the bars in the chart lost the correct indexing therefore some of them display randomly. Do you have any suggestion to fix this?
Answer: your code has many problems regarding how you handle state date inside the component.
If data is constant then you can move it outside the component.
The function filterData can be replaced with a state holding the filtered data and a useEffect that will be triggered when another filterdatanumber state changes.
Here is an example code with these changes.
import React, { useState, useEffect } from "react";
import { Bar } from "react-chartjs-2";

const data = {
  labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  datasets: [
    {
      label: "Weekly Sales",
      data: [18, 12, 6, 9, 11, 3, 9],
      backgroundColor: [
        "rgba(255, 26, 104, 0.2)",
        "rgba(54, 162, 235, 0.2)",
        "rgba(255, 206, 86, 0.2)",
        "rgba(75, 192, 192, 0.2)",
        "rgba(153, 102, 255, 0.2)",
        "rgba(255, 159, 64, 0.2)",
        "rgba(0, 0, 0, 0.2)",
      ],
      borderColor: [
        "rgba(255, 26, 104, 1)",
        "rgba(54, 162, 235, 1)",
        "rgba(255, 206, 86, 1)",
        "rgba(75, 192, 192, 1)",
        "rgba(153, 102, 255, 1)",
        "rgba(255, 159, 64, 1)",
        "rgba(0, 0, 0, 1)",
      ],
      borderWidth: 1,
    },
  ],
};

export default function VerticalBar() {
  const [firstNumber, setFirstNumber] = useState("");
  const [filterdatanumber, setFilterdatanumber] = useState(
    Number.MIN_SAFE_INTEGER
  );
  const [filteredData, setFilteredData] = useState(data);
  const textChangeHandler = (i) => {
    setFirstNumber(i.target.value);
    console.log("target.value", i.target.value);
    filterChart(Number(i.target.value));
  };

  useEffect(() => {
    const newData = { ...data };
    const filteredData = [];
    const filterLabels = [];
    const filterColors = [];
    for (let i = 0; i < newData.datasets[0].data.length; i++) {
      const value = newData.datasets[0].data[i]
      if (value > Number(filterdatanumber)) {
        const labelsResult = newData.labels[i];
        const colorssResult = newData.datasets[0].backgroundColor[i];
        filterLabels.push(labelsResult);
        filterColors.push(colorssResult);
        filteredData.push(value)
      }
    }
    console.log("filteredData", filteredData);
    console.log("filterLabels", filterLabels);
    console.log("filterColors", filterColors);
    newData.datasets[0].data = filteredData;
    newData.labels = filterLabels;
    newData.datasets[0].backgroundColor = filterColors;
    setFilteredData(newData);
  }, [filterdatanumber]);

  return (

      <Bar data={filteredData} />
      <input
        value={firstNumber}
        type="number"
        name="firstNumber"
        onChange={textChangeHandler}
      />

  );
}

Please remember that this code is just an example, maybe it will need some edits in order to match your needs.
Comment: this is a much better approach however the correct indexing is not working anymore, and that has been my main problem during the last weeks. Can you please help?
Comment: What do you mean with "correct indexing"?
Comment: The bars in the chart lost the correct indexing therefore some of them display randomly.
Comment: The console.logs print them correctly, however the chart displays the bar values incorrectly.
Comment: Please provide a working example on codesandbox or similar.
Comment: Yes, here it is https://codesandbox.io/s/fervent-shape-hxmsc?file=/src/App.js
Comment: I updated the answer. There was a bug in how you calculate the labels and colors inside the for loop. If now the answer is correct please consider to mark it as accepted in order to help others to find the right solution quickly.
Comment: I have tried this updated answer with the number 9 for example and it shows also bars with values below 9 in the chart therefore there still may be something to be adjusted in the code. Any ideas?
Comment: @David I updated the answer, I think that any further bug fixing is out of scope of the question so please try to go ahead on you our own and I also invite you, if the answer is correct, to mark it as accepted.
Answer: Here is my final solution fully working and with a refactored 3rd approach. The values are matching the keys consistently when filtered and displayed correctly in the chart.
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Bar } from "react-chartjs-2";

export default function VerticalBar() {
  const [data, setData] = useState ([
    {val: 18, label: "Mon"},
    {val: 1, label: "Tue"},
    {val: 5, label: "Wed"},
    {val: 8, label: "Thu"},
    {val: 19, label: "Fri"},
    {val: 5, label: "Sat"},
    {val: 7, label: "Sun"}
  ])

  const chartConfig = useMemo(() => {
    return  {
        labels: data.map(el => el.label),
        datasets: [
          {
            label: "Weekly Sales",
            data: data.map(el => el.val),
            backgroundColor: [
              "rgba(255, 26, 104, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)",
              "rgba(75, 192, 192, 0.2)",
              "rgba(153, 102, 255, 0.2)",
              "rgba(255, 159, 64, 0.2)",
              "rgba(0, 0, 0, 0.2)",
            ],
            borderColor: [
              "rgba(255, 26, 104, 1)",
              "rgba(54, 162, 235, 1)",
              "rgba(255, 206, 86, 1)",
              "rgba(75, 192, 192, 1)",
              "rgba(153, 102, 255, 1)",
              "rgba(255, 159, 64, 1)",
              "rgba(0, 0, 0, 1)",
            ],
            borderWidth: 1,
          },
        ],
      };

  }, [data])

  const textChangeHandler = useCallback(
    (event) => {
    setData(prevData => {
      return prevData.filter((el) => parseInt(event.target.value, 10) < el.val)
    })
  }, [setData]);

  return (

      <Bar data={chartConfig} />
      <input
        type="number"
        name="firstNumber"
        onChange={textChangeHandler}
      />

  );
}


Same address space on C

Question: I have an issue that some of you can help me out
I currently have this code (these are both global variables)
<code>    int * x;
    int * y;
</code>
Now, on the main method I want to get the address space of those two, as follows
<code>    int main ( int argc, char *argv[ ] ){
     printf("%p\n",x);
     printf("%p\n",y);
     system("pause");
     return 0;
     }
</code>
In both cases I get 00000000 as the address space (as if they "shared" the same address space)
My questions are
1) Why does it gets the address space of 0? It is supposed to take another address since we are talking about global variables
2) Why does both of the variables are sharing the same space in memory when they should take 000000 and 000004 (assuming that the assignment is correct)
Thanks in advance for your answers
Comment: Global variables are zero-initialised by default.
Comment: `%p` expects a void pointer.
Comment: You say *address space*, but everything else indicates you mean simply *address*. "Address space" is the technical term for a separate thing (though strongly related), so I advise you stop using it like this.
Answer: You're printing the values of the pointers, the address they are pointing to. This is 0 in both cases as global variables get initialized to 0.
If you want to know the addresses of the pointer variables, use
<code>int main ( int argc, char *argv[ ] ){
 printf("%p\n",&x);
 printf("%p\n",&y);
 system("pause");
 return 0;
}
</code>
Comment: That is it, that is the correct way to do it, now my code is returning the values I needed, thank you very much everyone!
Answer: Because uninitialized global variables/pointers are automatically initialized to zero/NULL.
Answer: 1.) They are both uninitialized pointers. The compiler automatically initializes global pointers to NULL (address is 0)
2.) They are not sharing the same address. They are both pointing to NULL (address is 0)
Hope this helps.

Same address space on C


Calling Opencv's Video Capture on a Video-URL does not work on Heroku

Question: I'm trying to open a videoURL using cv2.VideoCapture on Heroku, and it consistently fails to open. I've called the same code on my local machine (Windows 10) and it ran with no problems. Does anyone have recommendations/buildpacks/alternatives to resolve this?
OpenCV Version: 18.104.22.168
Python: 3.7
Current Buildpacks:

https://github.com/cstavish/heroku-buildpack-vips.git
https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git
https://github.com/heroku/heroku-buildpack-apt
heroku/python
https://github.com/timanovsky/subdir-heroku-buildpack

Open Cv Build info (Video) from the Heroku Dyno
Video I/O:
DC1394:                      NO
FFMPEG:                      YES
  avcodec:                   YES (ver 58.21.104)
  avformat:                  YES (ver 58.17.101)
  avutil:                    YES (ver 56.18.102)
  swscale:                   YES (ver 5.2.100)
  avresample:                NO
GStreamer:                   NO
libv4l/libv4l2:              NO
v4l/v4l2:                    linux/videodev.h linux/videodev2.h
gPhoto2:                     NO

Edit: we're trying to use the code below to open the video
cap = cv.VideoCapture(video_url) #get video
print(cap.isOpened())

With this code, we've noticed that the print statement consistently says 'False' when using a URL similar to one provided by youtubeDL.
Comment: Please define "fail to open".  What is the error message you are getting on Heroku?  Please also provide your source code that illustrates the problem.  Your question is at the risk of being closed as none of us can reproduce your problem.  To improve this, please take the [tour] and please visit [ask].
Comment: @rayryeng Please see the edited changes.
Answer: My apologies for the delay.  I am assuming you are using pip to install OpenCV.
The answer to your question is that for OpenCV 3.x, Mac OS and Linux (and ultimately the environment that Heroku is run under) do not link with FFMPEG which means that video support is not enabled for those platforms.  However, it is enabled with Windows.  This is the reason why there is an inconsistency between the platforms: What is the deal with `pip install opencv-python` is it a full opencv?
The solution is you will either need to build OpenCV 3.x from source, or use OpenCV 4 which now bundles FFMPEG with it.  I would highly recommend you use OpenCV 4 unless there is something blocking you from using it.  However to install OpenCV 4, use either pip install --upgrade opencv-python or pip install --upgrade opencv-contrib-python.  I'm not sure which flavour you are using, but either one should work.
Comment: Thanks a bunch Ray! Using OpenCV 4 fixed it.
Comment: No problem at all.  If this issue has been resolved, please consider accepting this answer to let the community know you no longer need help.  That can be done by clicking on the checkmark icon at the top of my post, to the left underneath the up and down voting buttons.  Welcome to our community!


Set column width to content length in CSS Grid

Question: I looked at the documentation but did not find such property.
I want to fit all cells in one column to its content width using css grid.
For the first case I should apply this property for the container: grid-template-columns: auto auto;
But what should I do for the second case?
Comment: Have you tried `grid-template-columns: min-content auto`?
Comment: @besthost it's possible to use `max-content` to prevent wrapping
Comment: `min-content` will wrap any text after white space, so `white-space: nowrap;` can be used as a fix
Comment: @Michael_B Thanks, it worked for me! :) Very strange that there is no info about this prop in many css grid guides...
Answer: To make all columns "shrink-to-fit", use an inline-level grid container:

article {
  display: inline-grid;
  grid-template-columns: auto auto;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }

content

content

cell3

cell4

To make one column "shrink-to-fit", use min-content:

article {
  display: grid;
  grid-template-columns: min-content auto;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }

content

content

cell3

cell4

But auto with 1fr would also work because the fr would consume all free space on the line, collapsing the other column as much as possible:

article {
  display: grid;
  grid-template-columns: auto 1fr;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }

content

content

cell3

cell4

More info in the spec:

7.2. Explicit Track Sizing: the grid-template-rows and grid-template-columns properties
Comment: This `grid-template-columns: auto max-content;` worked for me.
Answer: Set the following on the grid container:
grid-template-columns: auto 1fr;

This sets the width of the first column to equal the width of the widest item in that column, and the width of the second column to get the remaining width of the grid.
To right-align the content of the second column we can simply use text-align: right
span:nth-child(2n) {
  text-align: right;
}

div {
  display: grid;
  grid-template-columns: auto 1fr;
}
span {
  padding: 0.5em;
}
span:nth-child(2n) {
  text-align: right;
}
span:nth-child(1) {
  background-color: beige; /* colors for demo */
}
span:nth-child(2) {
  background-color: wheat;
}
span:nth-child(3) {
  background-color: lightgreen;
}
span:nth-child(4) {
  background-color: salmon;
}

  some content here
  content
  cell3
  cell4

NB: Setting column widths with min-content is a little more aggressive :) and will set the width of the column to the width of the largest word in the column.

div {
  display: grid;
  grid-template-columns: min-content auto;
}
span {
  padding: 0.5em;
}
span:nth-child(2n) {
  text-align: right;
}
span:nth-child(1) {
  background-color: beige;
}
span:nth-child(2) {
  background-color: wheat;
}
span:nth-child(3) {
  background-color: lightgreen;
}
span:nth-child(4) {
  background-color: salmon;
}

  some content here
  content
  cell3
  cell4

Comment: This is the only one that worked for me (be it on rows).. Problem was that browser chose the min-content of the overlapping column next to it.
Comment: what if I want to apply that just to a cell? for example to span:nth-child(1) {
  background-color: beige;
}


How do I add taxonomy terms and vocabularies to an exportable deployment plan?

Question: I'm in the process of developing an installation profile for a new site. We're using Features to export much of our functionality, and are very interested in using the Deploy module integration with UUID to handle the thorny issues stemming from exported content not having the same unique IDs on multiple deployments. Being able to export entities into a deployment plan and import them with Features would be an absolute godsend, and this is working with basic node content from what I've seen so far (I'm familiar with the concept of creating a fetch-only deployment plan and exporting it later).
However, I have a content type that references multiple taxonomies, each with a closed, pre-defined vocabulary. These vocabularies (and their terms) need to be exported, so that they can be referenced by the appropriate fields (for instance, a list of terms representing venues should be selectable from a drop-down). I haven't yet found a way to add these to a deployment plan, despite hearing on the soon-to-be-deprecated UUID Features issue queue that this should be possible. Is there something I've overlooked, or is there a better approach?
Comment: Linked the relevant issue in my question. Deploy does seem like it will be a much more robust alternative, though at the moment it is rough around the edges.
Comment: Where did you hear that UUID Features is "soon-to-be-deprecated"?
Answer: I seem to have stumbled my way through to a solution. Vocabularies don't need to be exported via UUID, as they already have their own machine name, but any terms within those vocabularies still need to be added to a deployment plan so they can be exported (inadvertently adding a vocabulary to the plan throws errors).
Using the latest development snapshots (as of March 14, 2012) of UUID, Deploy, Entity Dependency API, Views and Rules, it is possible to stitch together a UI for adding taxonomy terms to a plan. First, a managed fetch-only deployment plan must be created.
Next, a Rules component must be created using Rules, with a taxonomy term as a single parameter and a single action that adds the entity to the selected deployment plan. Note, however, that the current development snapshot of Deploy does not allow you to use Rules to add to a fetch-only managed deployment plan (I had to write a trivial patch that allows this behavior).
Next, one should create a view of all taxonomy terms, adding a Bulk Operations checkbox using Views Bulk Operations. If you have created your Rules component as above, VBO will allow you to select your component as a task to perform on all checked entities.
Now that your form is configured, all that's left to do is visit the view and add the necessary taxonomy terms, and select the relevant components to export via Features. Gotcha: There is no dependency checking in Features after adding the taxonomy terms via uuid_entities. You have to remember adding the vocabulary yourself, or tragedy and error messages will ensue.
Answer: For Drupal 7 :
There are a few ways to do this

If you are importing the terms from another Drupal site use Node
export module - drupal.org/project/node_import
If you are planning to export or import from a csv file :
drupal.org/project/taxonomy_csv
If you just want to cut and paste the list (one per line) and add to
a vocabulary : drupal.org/project/batch_add_terms


Generalized Additive Model (k value)

Question: I am trying to have result with GAM using R.
In R, I am using mgcv and the code is following.

However, I do not understand what k value for?
If I want to see the seasonal effect on time then should I put k=12? (my data is daily variables from 2000.01.01~2003.12.31.)
please help me. :(
Comment: R tip:  see your argument `data = D`?  That means that `gam` will look for each of the variables within the `D`.  So you can dispense with `D$`.  This is basically syntactic sugar.  But if you don't wish to use it, lose the `data = D` argument.
Answer: k is the number of basis functions to use for each smooth term before any identifiability constraints are applied. Typically, for 1d bases, there will be one fewer basis functions than implied by k because of a lack of identifiability with the model intercept, but if may be even lower if other constraints apply.
The number of basis functions used to represent a smooth function puts an upper limit on the wiggliness of that function. The smoothness penalty(ies) for term determine the actual wiggliness of the smooth
k is best thought of as providing information as to the maximum allowed wiggliness of each smooth term.
For seasonal effects, you might want to use a cyclic spline basis; two are available in mgcv

a cyclic cubic regression spline basis, and
a cyclic P-spline basis.

If I had sufficient data, I would start with k = 10 or k = 15 for a term used to model the seasonal cycle, but this would only be required if I were including a smooth of Day of Year for example. I doesn't seem like you are doing this.
Just because you have daily data doesn't mean that smooth function of covariates are cyclic or need to have high numbers of basis functions to capture some sine-wave-like behaviour. For example; temperature varies seasonally both within and between days, but the effect of temperature on the response is unlikely to be cyclical.
So, for the terms you show in the model in the question, it doesn't seem like you need k = 12 or to use a cylic basis.
For terms like s(temp), s(hum), s(sea_pressure), and s(wind_speed), it is more likely that the is some effect as you increase / decrease any of these covariates but that the effect may saturate (the rate of increase / decrease gets slower as the covariate values increase)
The smooth of s(time) might require a more specialised behaviour. If this is time of day, then a cyclic smoother will enable 00:00 and 24:00 to  have the same estimated effect; if you don't assume there to be a discontinuity at midnight then a cyclic spline will ensure this.
If s(time) is related to the date of observation (so to capture a longer term trend in the data) then you may not want a cyclic smoother; it would force the two end-points of the time covariate to have equal effect, which is not what you would want if there is an increasing or decreasing trend over time.
You seem to have several indicator variables for the day of week. These are best recorded as a single factor variable in R, say day_of_week, with levels:
c('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')

R will then work out the correct dummy variables (or other contrast coding if required/specified).
A final comment; don't include the name of the data frame containing the data, D, in the model formula. If you want to predict, the predict() function will look for variables with names of the form D$foo in the new data supplied. As the data argument already allow you to indicate where the covariates come from, you will save yourself a lot of problems down the line if you exclude the D$ bits from all your terms.

Generalized Additive Model (k value)


Play 2.1.1: Use Logback Evaluators in application-logger.xml

Question: I am using in Play 2.1.1 for my project a custom logging configuration. Therefor I created a application-logger.xml in the conf directory. This works like a charm.
Now I wanted to add a logback evaluator (based on the official doc: http://logback.qos.ch/manual/layouts.html#Evaluators) to the logging configuration file to output the %caller information only in specific cases:
<configuration>

<evaluator name="DISP_CALLER_EVAL">
    <expression>logger.contains("a specific string")</expression>
</evaluator>

<conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel" />

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${application.home}/logs/application.log</file>
    <encoder>
        <pattern>%date - [%level] - %logger in %thread in caller: %caller{3, DISP_CALLER_EVAL}
            %message%n%xException%n</pattern>
    </encoder>
</appender>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%coloredLevel %logger{15} - %message%n%xException{5}</pattern>
    </encoder>
</appender>

<logger name="play" level="INFO" />
<logger name="application" level="DEBUG" />

<root level="ERROR">
    <appender-ref ref="STDOUT" />
    <appender-ref ref="FILE" />
</root>

However, if I start the play server after adding the evaluator snippet to the log configuration, no logging happens at all and the server doesn't execute the code at all. It looks that the server crashed.
Has anyone an working example of a logging configuration with an evaluator rule on Play 2.1.1?
Answer: Try this
<evaluator name="DISP_CALLER_EVAL" class="ch.qos.logback.classic.boolex.GEventEvaluator">
    <expression>logger.contains("a specific string")</expression>
</evaluator>


Como passar um IEnumerable Model para um Controller?

Question: Tenho uma página que me lista corretamente os meus registros. Mais eu tenho um Html.BeginForm para cada linha,
@model IEnumerable<Generico.Dominio.TB_POSSIBILIDADE>

    @{
       ViewBag.Title = "";
    }

                @if (Model.Count() > 0)
                {

                    foreach (var item in Model)
                    {

                        using (Html.BeginForm("GravarRegistro", "Possibilidade", FormMethod.Post))
                        {

                                    @Html.DisplayFor(c => item.DESCRICAO01) | R$ @Html.DisplayFor(c => item.VALOR01)
                                    @Html.TextBoxFor(c => item.VALORAPOSTA1, new { placeholder = "valor ", @class = "form-control" })

                                    @Html.DisplayFor(c => item.DESCRICAO02) | R$ @Html.DisplayFor(c => item.VALOR02)
                                    @Html.TextBoxFor(c => item.VALORAPOSTA2, new { placeholder = "valor ", @class = "form-control" })

                                    @Html.DisplayFor(c => item.DESCRICAO03) | R$ @Html.DisplayFor(c => item.VALOR03)
                                    @Html.TextBoxFor(c => item.VALORAPOSTA3, new { placeholder = "valor ", @class = "form-control" })

                                    <input type="submit" name="btnEnviar" id="btnEnviar" value="Enviar para o caixa" class="btn btn-primary" />

                                    <input type="reset" name="btnLimpar" id="btnLimpar" value="Limpar" class="btn btn-danger" />

                        }

                    }

                }

Problema: quando eu estou preenchendo os dados e envio a gravação tenho no controle:Mais a tabela está vindo vazia:
  public ActionResult GravarRegistro(TB_POSSIBILIDADE tabela)
        {

            try
            {

                string idusuario = (string)Session["idusuario"];
                string titulo    = (string)Session["descricaotitulo"];

                var tTabela = new CaixaAplicacao();
                tTabela.Inseri(idusuario,titulo, tabela.DESCRICAO01,tabela.DESCRICAO02,tabela.DESCRICAO03,
                               tabela.VALOR01,tabela.VALOR02,tabela.VALOR03,tabela.VALORAPOSTA1,tabela.VALORAPOSTA2,
                               tabela.VALORAPOSTA3,tabela.VALORTOTAL1,tabela.VALORTOTALRETORNO );
            }
            catch (Exception)
            {
                TempData["Erro"] = "Não foi possivel gravar o registro.";
                return RedirectToAction("SelecionarPossibilidade", "Possibilidade", new { id = @Session["idpossibilidadde"] });

            }

            return RedirectToAction("SelecionarPossibilidade", "Possibilidade", new { id = @Session["idpossibilidadde"] });
        }

html:gerado;

Paysandu PA x Juventude

27/07/2016 19:30 (quarta-feira)

                    Vencedor do Encontro

<form action="/Possibilidade/GravarRegistro" method="post">

                                    Casa | R$ 01,73
                                    <input class="form-control" data-val="true" data-val-number="The field VALORAPOSTA1 must be a number." data-val-required="O campo VALORAPOSTA1 é obrigatório." id="item_VALORAPOSTA1" name="item.VALORAPOSTA1" placeholder="valor " type="text" value="0" />

                                    Empate | R$ 03,60
                                    <input class="form-control" data-val="true" data-val-number="The field VALORAPOSTA2 must be a number." data-val-required="O campo VALORAPOSTA2 é obrigatório." id="item_VALORAPOSTA2" name="item.VALORAPOSTA2" placeholder="valor " type="text" value="0" />

                                    Fora | R$ 04,20
                                    <input class="form-control" data-val="true" data-val-number="The field VALORAPOSTA3 must be a number." data-val-required="O campo VALORAPOSTA3 é obrigatório." id="item_VALORAPOSTA3" name="item.VALORAPOSTA3" placeholder="valor " type="text" value="0" />

                                    <input type="submit" name="btnEnviar" id="btnEnviar" value="Enviar para o caixa" class="btn btn-primary" />

                                    <input type="reset" name="btnLimpar" id="btnLimpar" value="Limpar" class="btn btn-danger" />

</form>

Comment: Cigano Morrison, poderia me ajudar com o seu grande conhecimento? agradeço
Comment: Como ficou o HTML gerado desses formulários?
Comment: @CiganoMorrisonMendez, adicionei o hmtl, mais está gerando certo, veja ai, eu estou usando o IEnumerable porque eu estou criando um formulário para cada linha de registro, porque em alguns casos eu vou ter mais de 1
Answer: O Binding está errado. Veja o nome dos ids e dos names.
id="item_VALORAPOSTA1" name="item.VALORAPOSTA1"
id="item_VALORAPOSTA2" name="item.VALORAPOSTA2"
id="item_VALORAPOSTA3" name="item.VALORAPOSTA3"

Para funcionar, o Binding tinha que ser assim:
id="VALORAPOSTA1" name="VALORAPOSTA1"
id="VALORAPOSTA2" name="VALORAPOSTA2"
id="VALORAPOSTA3" name="VALORAPOSTA3"

Isto se resolve colocando seu formulário numa Partial, por exemplo:
_Formulario.cshtml
@model Generico.Dominio.TB_POSSIBILIDADE

@using (Html.BeginForm("GravarRegistro", "Possibilidade", FormMethod.Post))
{

            @Html.DisplayFor(c => Model.DESCRICAO01) | R$ @Html.DisplayFor(c => Model.VALOR01)
            @Html.TextBoxFor(c => Model.VALORAPOSTA1, new { placeholder = "valor ", @class = "form-control" })

            @Html.DisplayFor(c => Model.DESCRICAO02) | R$ @Html.DisplayFor(c => Model.VALOR02)
            @Html.TextBoxFor(c => Model.VALORAPOSTA2, new { placeholder = "valor ", @class = "form-control" })

            @Html.DisplayFor(c => Model.DESCRICAO03) | R$ @Html.DisplayFor(c => Model.VALOR03)
            @Html.TextBoxFor(c => Model.VALORAPOSTA3, new { placeholder = "valor ", @class = "form-control" })

            <input type="submit" name="btnEnviar" id="btnEnviar" value="Enviar para o caixa" class="btn btn-primary" />

            <input type="reset" name="btnLimpar" id="btnLimpar" value="Limpar" class="btn btn-danger" />

}

E o foreach:
foreach (var item in Model)
{
    @Html.Partial("_Formulario", item)
}

Comment: A sua resposta foi perfeita, funcionou, só fiquei com uma pequena dúvida,  os valores que são preenchidos na tela como VALORAPOSTA1
VALORAPOSTA2 e VALORAPOSTA3, são enviados para o controle, mais alguns campos que são apenas descrição que já vem preenchido do banco estão passando vazio, como exemplo Model.DESCRICAO01 e Model.VALOR01, tem como pegar estes valores também?
Comment: Tem. Você precisa colocar os campos no formulário também, mas não vejo muita utilidade em salvar descritivos. Ainda assim, se você realmente precisa mandar esses campos para o *Controller*, use `@Html.TextBoxFor()` ou `@Html.HiddenFor()`, se não quiser que eles apareçam.
Answer: Uma opção seria mudar a forma como você está renderizando a caixa de texto, invés de:
@Html.TextBoxFor(c => item.VALORAPOSTA1, new { placeholder = "valor ", @class = "form-control" })

Tente assim:
@Html.TextBox("VALORAPOSTA1", item.VALORAPOSTA1, new { placeholder = "valor ", @class = "form-control" })

Fazendo assim, o nome do controle vai corresponder ao nome da propriedade da sua classe de Model e ao fazer o POST você receberá os valores no Controller.
Comment: eu agradeço a sua resposta, mais eu preferi fazer usando o partial, mais se puder me ajudar nisso:  alguns campos que são apenas descrição que já vem preenchido do banco estão passando vazio, como exemplo Model.DESCRICAO01 e Model.VALOR01, tem como pegar estes valores também?
Comment: Uma vez que você obtém os campos na sua Controller, você deve preencher sua classe de Model. Depois na sua View você insere os campos com o mesmo nome da propriedade do seu Model, aí quando você fizer o Post ele envia os campos. Ou seja, você faria praticamente da mesma forma como você fez com o campo VALORAPOSTA1. Mas, quando você não quer que o campo seja editável você não usaria um TextBox, mas outro controle apenas para mostrar o texto e um controle que vai armazenar o valor e será útil para enviá-lo no Post,@Html.HiddenFor() , por exemplo.


Is variance really a thing?

Question: Is variance really something useful? Or is it just a byproduct or middle step to get to standard deviation by squaring the distance of each point to the mean because it was computationally/mathematically harder to take the absolute value of the distance in the past when then didn't have computers yet?
Comment: Taking absolute values was never difficult before computers (modern sense) were available. Any person computing by hand could just ignore negative signs. I remember doing it! In the 19th century probable error was often computed this way: there I am guessing, not remembering. That aside, how best to measure variability was never really about how easy it was to compute a measure.
Comment: The standard deviation shows up as being the *unique* relevant estimate of spread of data or a distribution when one considers the [Central Limit Theorem](https://stats.stackexchange.com/a/3904/919).  Among all possible ways of re-expressing the standard deviation one might consider, the additivity of the variance suffices to demonstrate its utility and importance.
Comment: Many answers here: https://mathoverflow.net/questions/1048/why-is-it-so-cool-to-square-numbers-in-terms-of-finding-the-standard-deviation/1092#1092
Comment: Yes, it is really a thing.
Comment: The mean squared error, ${\sigma_2}^2$, is extremely popular. But actually, in the past they used more often the mean absolute deviation, $\sigma_1$, (and other alternative measures) than nowadays. Except for useful mathematical properties (e.g. additivity) you also have, in the case of estimating the deviance parameter of the normal distribution that "The whole of the information respecting $\sigma$, which a sample provides, is summed up in the value $\sigma_2$" (see https://academic.oup.com/mnras/article/80/8/758/1063878).
Comment: That property relates to the spherical shape of the *normal distribution*. But, it is not universal. For example, in the case of a Laplace distribution then the mean absolute deviation is a more efficient estimator. In practice one may often encounter distributions that are not really normal distributions and the mean absolute deviation may be more robust for such variations from the ideally supposed distribution. The "superiority" (in the sense efficiency) of the mean squared error is more based on a mathematical model, which may not necessarily reflect the true nature of certain experiments.
Comment: I actually start to get confused now. What do you mean by *"harder to take the absolute value of the distance"*. Do you mean this in the sense of the cost function in regression being easier to minimize when you use squares? How do you otherwise see taking the absolute value as a difficult operation?
Comment: Variance has a number of important properties that make it useful in its own right. For example, consider https://en.wikipedia.org/wiki/Variance#Basic_properties and https://stats.stackexchange.com/questions/160427/partitioning-of-variance and https://stats.stackexchange.com/questions/133149/why-is-variance-instead-of-standard-deviation-the-default-measure-of-informati
Answer: Some advantages of the sample variance
$S^2 = \frac{1}{n-1}\sum_{i=1}^n (X_i - \bar X)^2:$
(1) For a population with variance $\sigma^2,$ the sample variance
is an unbiased estimator, $E(S^2) = \sigma^2.$
(2) For a sample from $\mathsf{Norm}(\mu, \sigma),$ one can show that
$\frac{(n-1)S^2}{\sigma^2} \sim \mathsf{Chisq}(n-1),$ the chi-squared
distribution with $n-1$ degrees of freedom. Thus, a 95% confidence interval for $\sigma^2$ is of the form $\left(\frac{(n-1)S^2}{U},\, \frac{(n-1)S^2}{U}\right),$ where $L$ and $U$ cut 2.5% of the probability from the lower
and upper tails, respectively, of $\mathsf{Chisq}(n-1).$
(3) If you know the sample size $n,$ sample mean $\bar X,$ and variance $S^2$
of two separate samples, you can use that information to find the sample size, mean, and variance of
the combined sample; similarly, for combining more than two samples. The computation for the variance involves some algebra with repeated
use of the alternative formula $(n-1)S^2 = \sum_i X_i^2 - n\bar X^2.$

In some circumstances, a disadvantage of the sample variance is that its value is greatly influenced by high outliers. For example, consider the following data
with $S_x^2 = 85.03.$ (Computations in R statistical software.)
x
 [1] 30.10 34.02 39.87 40.31 41.66 42.74 44.61 45.32 46.82 47.09
[11] 48.55 49.03 49.15 52.03 52.85 56.86 58.28 60.06 61.81 66.04
var(x)
[1] 85.02517

If the largest observation were 96.04 (say, due to data entry error or equipment failure), the variance would be 185.86.$
y = x; y[20] = 96.04; y
 [1] 30.10 34.02 39.87 40.31 41.66 42.74 44.61 45.32 46.82 47.09
[11] 48.55 49.03 49.15 52.03 52.85 56.86 58.28 60.06 61.81 96.04
var(y)
[1] 185.8567

By contrast, another way to measure variability is to take the difference
between the upper and lower quartiles. This difference is called the 'interquartile range' (IQR). The IQR is the same (11.38) for both versions of the data.
summary(x); IQR(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  30.10   42.47   47.82   48.36   53.85   66.04
[1] 11.3825
summary(y); IQR(y)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  30.10   42.47   47.82   49.86   53.85   96.04
[1] 11.3825

The IQR is sometimes used in boxplots to call attention to outliers in data.
boxplot(y, col="skyblue2", pch=19, horizontal=T)

In this boxplot of the data y, observation 96.04 is plotted separately
(as an outlier) because it lies beyond a 'fence' (not shown) located 1.5(IQR) above the upper quartile 53.85;
that is, $96.04 > 53.85 + 1.5(11.38) = 70.92.$
Note: If you know the sample size, sample median, and IQR of two separate
samples, you cannot generally use that information to find the median or IQR of the two samples combined.

Is variance really a thing?


Which modelling method - normal dependent but mixed independents

Question: My data has normally distributed dependent variables; however the independent variables are an eclectic mix.
They include categorical, nominal, continuous normal, continuous non-normal, and almost bimodal.
Which methods would be most appropriate for this? I can use both linear and nonlinear methods, including neural net. However, I do not have much experience with selecting the appropriate hidden layer activation functions.
I have read that some modelling methods are more appropriate when when dealing with these types of variables.
Answer: The fact that the independent variables are an "eclectic mix" does not, by itself, rule out any method, certainly not "regular" OLS regression. OLS regression makes assumptions about the error from the model, as measured by the residuals. It does not make assumptions about the distribution of the independent variables.
That said, other methods may, of course work better for your data. But that depends on the goals of your analysis and the exact nature of your data. e,g, Regression trees are very good at finding particular interactions and can find interactions that occur in only part of the data. Methods based on trees can be even more powerful, but at the expense of some interpretability.
Comment: Depending on the amount of data, number of variables, shape of relationships and so on, a lot of methods could be used. I strongly recommend a lot of graphical exploration first.
Comment: This is primarily data exploration. In that i want to assume no trends in the data are known. With this is mind there are relationships i expect to see (essentially as a validation for myself) but the main interest is to extract relationships other than these and at the same time a more descriptive result than 'As x increases so does y' which is what we have currently
Comment: is there anything reccomeded? Up to this point i have been looking predominantly at model results and interactive distribution plots. Neural nets seem to provide good data fits but only after initial modelling with partition, otherwise they pick out obscure variables before refinement.
Comment: I would say that regression and some variants of it are the easiest to understand. Splines and interactions can be explored. I find neural nets too much of a "black box" when data exploration is the main goal (but I admit I don't know much about neural nets).
Comment: Yes, it is the black box of neural nets which limits thier appeal for finding the internal relationships for this case. I find them very good at generating an accurate model (particularly in respect to consistency between training and validation).I often see Tree methods are rarely mentioned in continuous responses and this was one of my concerns. I do not have an extensive statistical education which i feel is limiting me, something i am keen to address!


Timeout Exception Wildfly Service Deployment

Question: I am trying to deploy a service configured in Jboss-wildfly (Wildfly 9.0.1). During deployment it gets stuck at specific moment and after 600 seconds I am getting a TimeoutException and deployment fails. I have increased the timeout period but still same issue occurs. The error I am getting is:
ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0348: Timeout after [600] seconds waiting for service container stability. Operation will roll back. Step that first updated the service container was 'add' at address '[
    ("core-service" => "management"),
    ("management-interface" => "http-interface")
]'
ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0190: Step handler org.jboss.as.server.DeployerChainAddHandler$FinalRuntimeStepHandler@4fe2e0d1 for operation {"operation" => "add-deployer-chains","address" => []} at address [] failed handling operation rollback -- java.util.concurrent.TimeoutException: java.util.concurrent.TimeoutException
    at org.jboss.as.controller.OperationContextImpl.waitForRemovals(OperationContextImpl.java:396)
    at org.jboss.as.controller.AbstractOperationContext$Step.handleResult(AbstractOperationContext.java:1384)
    at org.jboss.as.controller.AbstractOperationContext$Step.finalizeInternal(AbstractOperationContext.java:1332)
    at org.jboss.as.controller.AbstractOperationContext$Step.finalizeStep(AbstractOperationContext.java:1292)
    at org.jboss.as.controller.AbstractOperationContext$Step.access$300(AbstractOperationContext.java:1180)
    at org.jboss.as.controller.AbstractOperationContext.handleContainerStabilityFailure(AbstractOperationContext.java:964)
    at org.jboss.as.controller.AbstractOperationContext.doCompleteStep(AbstractOperationContext.java:590)
    at org.jboss.as.controller.AbstractOperationContext.completeStepInternal(AbstractOperationContext.java:354)
    at org.jboss.as.controller.AbstractOperationContext.executeOperation(AbstractOperationContext.java:330)
    at org.jboss.as.controller.OperationContextImpl.executeOperation(OperationContextImpl.java:1183)
    at org.jboss.as.controller.ModelControllerImpl.boot(ModelControllerImpl.java:453)
    at org.jboss.as.controller.AbstractControllerService.boot(AbstractControllerService.java:327)
    at org.jboss.as.controller.AbstractControllerService.boot(AbstractControllerService.java:313)
    at org.jboss.as.server.ServerService.boot(ServerService.java:384)
    at org.jboss.as.server.ServerService.boot(ServerService.java:359)
    at org.jboss.as.controller.AbstractControllerService$1.run(AbstractControllerService.java:271)
    at java.lang.Thread.run(Thread.java:745)

Does anyone know how to fix this problem?
Comment: Possible duplicate of [Concurrent Timeout exception on starting Jboss Wildfly 9.02 server](https://stackoverflow.com/questions/34064835/concurrent-timeout-exception-on-starting-jboss-wildfly-9-02-server)
Comment: Improved the grammar mostly
Comment: How large is the deployment?
Answer: Have you already increased the jboss.as.management.blocking.timeout value? If not you can try increasing it with CLI command as below
/system-property=jboss.as.management.blocking.timeout:add(value=800)
Along with increasing the timeout value make sure there is not any virus scan going on. Have you seen this issue before? If not what what changes you have made ?
Comment: I had an antivirus issue that didn't let me start WildFly. Killing the antivirus solved the problem


Is 'every exponential grows faster than every polynomial?' always true?

Question: My algorithm textbook has a theorem that says
'For every $r > 1$ and every $d > 0$, we have $n^d = O(r^n)$.'
However, it does not provide proof.
Of course I know exponential grows faster than polynomial in most cases, but is it true for all case?
What if the polynomial function is something like $n^{100^{100}}$ and exponential is $2^n$? Will the latter outgrow the former at some point?
Comment: Yes. Exponential of base $> 1$ will eventually grow faster than any polynomial.
Comment: For intuition, take logs on both sides and you have $100^{100}\log n$ versus $n\log 2$. Hopefully you believe that $\log n$ grows much slower than $n$...
Comment: The result is correct. In the very long run, $f(n)=(1.00000001)^n$ "beats" $g(n)=n^{9999999999}$. However, for all practical purposes, an "exponential" algorithm that takes time $f(n)$ on input of size $n$ may be much more practical than a "polynomial" algorithm that takes time $g(n)$.
Answer: Yes, it is true for all cases. This can be seen by noting that
$$\lim_{n\to\infty} \frac{n^k}{e^n} = 0$$
for any $k$. This can be seen by an application of L'Hospital's rule a number of times, or by using induction as here.
Answer: Let $n = k^2$.
Then $n^c = k^{2c}$ and $2^n = (2^k)^k$.
Clearly $2^k \ge k+1 > k$ so all we need is $k > 2c$.
In general if we want to find $n \in \mathbb{N}$ such that $r^n > n^c$ where $r > 1$, we can do essentially the same:
Let $n = ak^2$ where $a > \log_r(2)$.
Then $r^n > (2^k)^k$ and $n^c = a^c k^{2c}$.
It is then enough to choose $k$ such that $k > a$ and $k > 3c$, so that $n^c < k^{3c} < (2^k)^k < 2^n$.
Comment: @Niing: My answer may have been a bit cryptic, but it should have been decipherable after some effort. Given constant $c$, to prove $2^n > n^c$ as $n \to \infty$, let $n = k^2$ and observe that $2^n = (2^k)^k > k^k$ and $n^c = k^{2c}$, and so it should be clear that the desired inequality holds because $k > 2c$ as $n \to \infty$. Similarly, given constants $c$ and $r>1$, to prove $r^n > n^c$ as $n \to \infty$, let $n = ak^2$ where $a > \log_r(2)$, so $r^n = (2^{ak})^k > (2^k)^k$ and $n^c = a^c k^{2c} < k^{3c} < (2^k)^k$ because $a < k$ and $3c < k$ as $n \to \infty$.
Comment: I don't understand...
Comment: @Niing: If you still do not get it, specify exactly which part of my comment you cannot understand, and I will explain.
Comment: I've asked a question about how to prove what you just did... And I've read, at least for me, a lot of related posts. Your explanation is the best..., since you didn't use any advanced concept like the limit of a quotient. TLDR: thank you...
Comment: @Niing: Yes that is precisely the reason I posted my answer a year after the others, to demonstrate that we can in fact do a lot by purely elementary means. Of course, once we learn asymptotic expansion, we ought to always just use it, and in this case we can use $exp(n/c) > 1+n/c+n^2/2c^2 > n$ as $n \to \infty$. But it is good to know what we can do with simpler tools. =)
Comment: Actually, I'm really afraid of that it's, maybe, essential for math that I would always need some advanced tools to construct some idea before I could actually understand it... If that's the case, people are both creating and discovering math.
Comment: @Niing: That is true in general, but in this case it wasn't necessary; you just need to play around enough with what you have and then suddenly you see how to use it to do interesting things. Just like how the fact that $(x-y)^2 \ge 0$ for every reals $x,y$ can give you the fact that $(x+y)/2 \ge sqrt(x·y)$ for every positive reals $x,y$. And I posted an answer to your new question. =)
Answer: Hint: Yes. See Taylor expansion of exponential function.


Is haskell style pattern matching allowed in conventional mathematics and if not, how do you work out the numerator of an arbitrary rational number?

Question: Is it possible to define a function "Numerator" in the following way? $$N(a/b) = a$$
Or likewise is it possible to define a function "Denominator" like this? $$D(a/b) = b$$
These functions take a rational number, and match it against the pattern $a/b$, thus assigning the numerator to $a$ and the denominator to $b$.
This is common practice in functional programming languages like Haskell, and I am just dying to do similar in my standard mathematical escapades. Having access to this style of function would make my life much easier in a particular problem I'm working on right now.
If this is not possible (I haven't seen it done before), could someone kindly provide me with a formula or algorithm for working out the numerator of a rational number? (And the denominator for bonus points)
So given the number $1/2$, I want to know how to get at the $1$, and more generally, given $a/b$ I want to know how to get the $a$
You might wonder why I can't just do it by inspection: I'm dealing with a function which returns a rational number, and I only want the numerator, but because I only can see the function I can't see the numerator. In this way, I only have my number in the form $f(x)$ so I am unable to work out the numerator by inspection, I need some algorithm or formula for extracting it.
Comment: `formula or algorithm for working out the numerator of a rational number` In what form or format is that rational number? I guess it's not a fraction, otherwise you could cancel out the $\gcd$ and get $a,b$. But it could be a fixed point, or floating point, or continued fraction, or whatever other format, and the answer might not be the same in all cases.
Comment: Continued fractions are not rational right? (Or perhaps there is a distinction between finite and infinite continued fractions). In any case I'm looking for the numerator of a fraction that has been simplified as much as possible. So 2/4 should be simplified to 1/2 before extracting the denominator
Comment: Continued fractions are irrational iff infinite. It's still not obvious what the input is, though. In your example, if you know that the fraction is $2/4$ then simply divide both numerator and denominator by $\gcd(2,4)=2$ to get it into irreducible form $1/2$. Note that the $\gcd$ can be calculated using Euclid's algorithm.
Answer: That isn't a well-defined function, unless you specify some further conditions. Since $1/2 = 2/4$, we should have $f(2/4) = f(1/2) = 1$, not $2$.
But we can define a function $f$ such that $f(x) = a$, where $x = a/b$ in lowest terms. Because this uniquely specifies what $a$ is, this defines a function.
However, I don't think it's possible to express $f$ in terms of $+, -, \times, \div$.
Edit: you want $f$ expressed in "mathematical notation". The above is a valid mathematical definition of $f$, but I assume you're looking for a more algorithmic definition.
Such a thing will be hard to produce, unless you implement it inside the "rational" object. I would have said impossible earlier today, but I came across a result by Julia Robison, stating that you can tell if a rational number is an integer just using $+,\times,<$. That being said, it's wildly impractical to implement it using this.
If you're doing a proof, you can simply declare that the function exists, and move on.
Julia Robinson, Definability and Decision Problems in Arithmetic. The Journal of Symbolic Logic, Vol. 14, No. 2 (Jun., 1949) , pp. 98-114
Comment: Yeah, that's totally an acceptable function. But I'd be careful about using the phrase "with conventional terms". There's many functions out there that aren't definable in terms of arithmetic operators, and they are no less legitimate than any other.
Comment: so, would it be permissible for me to use your f(x) in a proof, even though it is impossible to state the definition with conventional terms?
Comment: You've been very helpful! If you just edit your answer to include a function definition for f that purely uses mathematical notation i will accept the answer. If it's not possible to do that just say and I will accept anyway.
Comment: (It's particularly the part where you say "x=a/b in lowest terms". I would like to know how to express "in lowest terms" using mathematical notation)
Comment: $a$ and $b$ are in lowest terms (equivalently, relatively prime) if: $d$ divides $a$ and $b$ implies $d=\pm 1$. Equivalently, there exist integers $x$ and $y$ such that $ax+by=1$.