Expected difference between largest and second largest of i.i.d. random variables

Question: Let $(X_i)_{i\geq 0}$ be i.i.d. nonnegative random variables with continuous density function $f$. Let
\begin{align}
\mu_n = \mathbb{E}[X_{(n)}-X_{(n-1)}]
\end{align}
be the expected difference between the largest and second largest of the first $n$ random variables.
Question: Can we show that $\mu_n$ is decreasing in $n$?
We can assume the density $f$ to be decreasing for $x>0$ and the mean of the order statistics to be well-defined; in particular, assume $\mathbb{E}[X_i]<\infty$.
Edit: My intuition tells me that $\mu_n$ is generally decreasing in $n$, but I have been unable to prove it. I am more interested in simple conditions under which the result is true, rather than a specific counterexample where it is not.
Comment: Do you want $\mu_{n+1} < \mu_n$ for all $n \geq 2$, or do you just want some $m$ such that it holds for all $n \geq m$?
Comment: You haven't even assumed $\mathbb E[X_i]$ exists, so I see no reason to think even that $\mu_n$ exists.
Comment: Looks like [this question](https://math.stackexchange.com/questions/24743/does-exceptionalism-persist-as-sample-size-gets-large) had been posed already and answered in the negative by the existence of non-"ES short" distributions?
Comment: @RobertIsrael Thank you for pointing that out. I have updated the question.
Answer: It turns out that the claim is false. For example, assume the common CDF $F(\cdot)$ of $X_i$'s takes the form
$$ F(t) = (1-p) (1 - (1-t)^m) + p t^m, \qquad 0 \leq t \leq 1$$
where $p \in (0, 1)$ and $m \geq 1$ are prescribed parameters. It is designed so that $X_i$'s approximately have Bernoulli distribution with parameter $p$ for $m$ large enough. So, if $\tilde{X}_i$'s are i.i.d. random variables having $\operatorname{Ber}(p)$ distribution, then
\begin{align*}
\mu_n := \mathbb{E}[X_{(n)} - X_{(n-1)}]
&\approx \mathbb{E}[\tilde{X}_{(n)} - \tilde{X}_{(n-1)}] \\
&= \mathbb{P}(\tilde{X}_{(n)} = 1 \text{ and } \tilde{X}_{(n-1)} = 0) \\
&= n p(1-p)^{n-1} =: \tilde{\mu}_n.
\end{align*}
Since $\tilde{\mu}_n$ is not monotone in $n$, we can expect that the same is true for $\mu_n$ if $m$ is large. Indeed, below is the graph of $\mu_n$ (blue dots) and $\tilde{\mu}_n$ (orange dashed curve) corresponding to $m = 10$ and $p = \frac{1}{10}$:
Answer: Edit: As kindly pointed out by Sangchul Lee, the computations do not suffice as a proof and only the correct parts shall be kept:
The maximum $X_{(n)}$ (and second order $X_{(n-1)}$ too) still has finite expectation:
$$ E \left[X_{(n)} \right] = E \left[\max_{0 \leq i \leq n} X_i \right] \leq E \left[\sum_{i=0}^n X_i \right] = \sum_{i=0}^n E[X_i] < \infty.$$
So we can actually write $\mu_n = E[X_{(n)}] - E[X_{(n-1)}]$ and use the general relation $E[Y] = \int_0^{\infty} 1-F_Y(x) dx$. Here, by independence
$$F_{X_{(n)}}(x) = P[ \forall \, 0 \leq i \leq n: X_i \leq x ] = F(x)^{n+1},$$ for $F:=F_{X_0}$.
Similarly (since the called events are disjoint)
\begin{align} F_{X_{(n-1)}}(x) &= P[\max_{0 \leq i \leq n}Xi \leq x] + P[ \exists 0 \leq i_0 \leq n:  \, \forall i_0 \neq i \leq n: X_i < x, X_{i_0} > x] \\ &= F(x)^{n+1} + (n+1)F(x)^n(1-F(x)).\end{align}
More generally, the distribution function of $X_{(k)}$ is $\sum_{j=k+1}^{n+1} \binom{n+1}{j} F(x)^j [1-F(x)]^{n+1-j}$, as also pointed out by Sangchul Lee to be found on Wikipedia.
So, in total
\begin{align*}\mu_n &= E[X_{(n)}] - E[X_{(n-1)}] \\
&= \int_0^{\infty} 1-F(x)^{n+1} dx - \int_0^{\infty} 1-[F(x)^{n+1} + (n+1)F(x)^n(1-F(x))] dx \\ &= \int_0^{\infty} (n+1)F(x)^n(1-F(x)) \, dx \end{align*}
Comment: (+1) Your approach seems promising, but I am not sure if your formula for the CDF of $X_{(n)}$ and $X_{(n-1)}$ are correct. In OP's setting, $X_{(n)}$ and $X_{(n-1)}$ are the largest and second largest elements in the *first $n$ variables*, respectively. Then according to [Wikipedia article](https://en.wikipedia.org/wiki/Order_statistic#Cumulative_distribution_function_of_order_statistics), we have $$F_{X_{(n)}}(x)=F(x)^n\qquad\text{and}\qquad F_{X_{(n-1)}}(x)=F(x)^n+n F(x)^{n-1}(1-F(x)).$$
Comment: @SangchulLee That is correct, thank you. I edited the post and do not arrive at the conclusion anymore.
Comment: @Alex Nice work. I guess the question becomes, under what simple conditions is your expression for $\mu_n$ decreasing in $n$?
Comment: @svonimir I think you should ask the follow-up question in a separate post


Simple probability system

Question: A system consists of four components ${1,2,3,4}$. There are two routes ${1,2,4}$ and ${1,3,4}$ to complete the system. If all four components have equal reliability of $0.9$, what is the reliability of the system at a given time instant?
My answer:
I know how to calculate the reliability of the two routes, $(.9)^3$ and $(.9)^3$, but how do you combine these two to get a total reliability?
Answer: We assume independence.  This may not be entirely realistic, but we need some assumption or information about possible interactions between the components.
The system works if and only if $1$ and $4$ work and at least one of $2$ or $3$ works.
The probability that $2$ or $3$ both fail is $(0.1)(0.1)$. So the probability at least one works is $1-(0.1)^2=0.99$.
Thus our system reliability is $(0.9)(0.99)(0.9)$.

Simple probability system


How do I add a description to the node title form field?

Question: This might sound stupid, but I can't find a way to do it. I need to add a description to the node title, just like I add a description to other fields. How can I do it?
Answer: In a hook_form_alter() or hook_form_FORM_ID_alter(), add a description attribute to the node form element array:
 //Add a title field description
  $form['title']['#description'] = t('Enter your awesome title field details.');

Answer: In Drupal 8 is pretty similar inside the same hook_form_alter():
$form['title']['widget'][0]['value']['#description'] = t('Enter your awesome title field details.');

Answer: Node title help text module can be used to add help text to node title. Configuration is available to add description per content type
https://www.drupal.org/project/node_title_help_text


set @Html.DropDownList selected item

Question: Basically my action return a viewModel with a List - each language has anID and a title
So in my view I have the following fropdown
<code>@Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name"), "SELCT  LANGUAGE----->",new { id = "ddlLanguages" })
</code>
SOmy question is - as I will have other views with dropdown and I will save in a session the id of the chosen language so when the user is redirected back by to this view
I want to be able to say  something like this
<code>ddllanguages.SelectedItem = @HttpContext.Current.Session["langID"]
</code>
Answer: <code>@Html.DropDownList(
    "Languages",
    new SelectList(
        Model.lstLanguages,
        "LanguageID",
        "Name",
        Session["langID"]
    ),
    "<-----SELECT  LANGUAGE----->",
    new { id = "ddlLanguages" }
)
</code>
Comment: @MilkaSalkova, StackOverflow is an English only website, so please adhere to this rule. Let me translate your question for others: *is it possible to check whether the session contains a value and if it doesn't put 2 for example*. The answer is, yes, you can do that pretty easily. Just use the null coalescing operator: `Session["langID"] ?? "2"`.
Comment: Благодаря - а знеш ли дали мога да направя проверка - ако сесията не е нула - да е стойността на сесията, ако Session is null -  тогава да сложа примерно две
Comment: Thankkks Darin and please forgive me for my mistake :)
Comment: @DarinDimitrov - I have similar issue and I'm using dropdownlistfor here and also I want to assign the session value to the dropdownlistfor,I followed your answer but everytime entire list of element is getting binded to the dropdown with first element as Select .Here I want the session value to be shown in the dropdown.Please help.

set @Html.DropDownList selected item


The call is ambiguous between the following methods or properties. Use Oracle on Asp.net Core

Question: i'm trying to build a solution for .NET 5.0, ORACLE, ASP.NET Identity with N-tier architecture.
Now i've this error

Error CS0121  The call is ambiguous between the following methods or
properties:
`Microsoft.EntityFrameworkCore.SqlServerModelBuilderExtensions.UseIdentityColumns(Microsoft.EntityFrameworkCore.ModelBuilder,
int, int)' and
'Microsoft.EntityFrameworkCore.OracleModelBuilderExtensions.UseIdentityColumns(Microsoft.EntityFrameworkCore.ModelBuilder,
int, int)' ......EXAMPLE_SCHEMA_ContextModelSnapshot.cs

Error is in both .UseIdentityColumns() instructions
<code>{
    [DbContext(typeof(EXAMPLE_SCHEMA_Context))]
    partial class EXAMPLE_SCHEMA_ContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder    modelBuilder)
        {
            modelBuilder
                .HasDefaultSchema("TEST")
                **.UseIdentityColumns()**
                .HasAnnotation("Relational:MaxIdentifierLength", 30)
                .HasAnnotation("ProductVersion", "5.0.1");

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
            {
                b.Property<int>("Id")
                    .ValueGeneratedOnAdd()
                    .HasColumnType("NUMBER(10)")
                    **.UseIdentityColumn();**

                b.Property<string>("ClaimType")
                    .HasColumnType("NVARCHAR2(2000)");

                b.Property<string>("ClaimValue")
                    .HasColumnType("NVARCHAR2(2000)");

                b.Property<string>("RoleId")
                    .IsRequired()
                    .HasColumnType("NVARCHAR2(450)");

                b.HasKey("Id");

                b.HasIndex("RoleId");

                b.ToTable("AspNetRoleClaims");
            });

..........
</code>
Comment: It looks like you have references to both EF Core SQL Server and EF Core Oracle providers installed. If you are using Oracle, remove the Microsoft.EntityFrameworkCore.SqlServer Nuget Package.
Answer: Thanks to steve-py
It was that problem but it's very strange that mechanism reported in the article clearly mentioned the use of that library.


Left invariant vector field induces constant components

Question: My question specifies on that the left translation of a left invariant vector field on a Lie group $G$ can be seen as a parallel transport along all possible curves. How can I see that this is true?
I found a result saying that the vector field $V=V^\alpha e_{\alpha}$ is left invariant if and only if $V^\alpha$ is constant with respect to any left invariant frames $e_\alpha$. I cant see how this follows from the definition
The definition of Left-invariant vector field is given as follows:
Definition:
A vector field $V$ on a Lie group G is left invariant if $$\textrm dL_gV(x)=X(L_g(x))=X(gx)$$
with $x,g\in G$.
I hoped this result and the fact that $G$ is parallelizable (this will give me the trivial connection if we use the left invariant frame $e_\alpha$ and the covariant derivative along a curve $\gamma(t)$ is then $V'(\gamma(t))$ ) will give that the covariant derivative vainishes. Is this reasoning correct?
Thank you for any help
Comment: well, you pretty much have the right ideas. There is a unique connection which makes all left-invariant vector fields parallel. The uniqueness part follows from the fact that you can find a global frame of left-invariant vector fields, so that the connection is uniquely determined (write the difference of 2 such connections and apply it to an arbitrary linear combination of left-invariant vector fields). As to the existence part, you should only check that it is well-defined, so that if you change the frame of left-invariant vector fields, then the corresponding covariant derivatives agree.
Comment: But this is true because the change of basis matrix has constant coefficients. Indeed, such a frame is determined by its value at the identity element in the group.
Answer: Recall that any Riemannian manifold $(M,g)$ admits a unique symmetric metric connection $\nabla$ by the fundamental theorem of Riemannian geometry, and it is determined by the Koszul formula:
$$2g(\nabla_Y X, Z) =Xg(Y, Z) + Yg(X, Z) - Zg(X, Y) -g([X, Z], Y) - g([Y, Z], X)
- g([X, Y], Z)$$
Suppose now that we had a compact Lie group $G$ with a bi-invariant metric $\eta$. There's a special class $\mathcal{G}$ of vector fields on $G$ which are left-invariant, i.e., $X \in \mathcal{G}$ iff $dL_g X_h = X_{gh}$ where $L_g : G \to G$ is multiplication by $g$. Any element $X$ of $\mathcal{G}$ is obtained from left-translating a tangent vector $X_e$ in $\mathfrak{g}$ to extend to all of $G$. Notice that left-invariant vector fields have constant inner product (or angles between them stay globally constant) because for any two left-invariant vector fields $U$ and $V$, $$\eta(U_{gh}, V_{gh}) = \eta(dL_gU_h, dL_g V_h) = \eta(U_h, V_h)$$ where the second equality derives from the left-invariance of $\eta$.
Therefore if $X, Y, Z$ are vector fields in $\mathcal{G}$, $\nabla$ a symmetric connection on $G$ compatible with $\eta$, we invoke the Koszul formula. By the previous comment, $X\eta(Y, Z), Y\eta(X, Z)$ and $Z\eta(X, Y)$ are all zero so we are left with
$$2\eta(\nabla_Y X, Z) = -\eta([X, Z], Y) - \eta([Y, Z], X) - \eta([X, Y], Z)$$
Up until this point we have not needed the right-invariance of $\eta$. But the following lemma is the relevant key: If $U, V, W$ are vectors fields in $\mathcal{G}$, then $\eta([U, V], W) = \eta(U, [V, W])$. To see this, let $g_t$ be the element of $G$ defined as $\partial_t g_t = V(g_t)$ with initial condition $g_0 = e$ (so it's a flowline of $V$ starting at $e$). Write $\eta(U, W) = \eta(dR_{g_t}U, dR_{g_t}W)$ using right-invariance of $\eta$. Differentiate with respect to $t$ at $t = 0$ to obtain $0 = \eta(\mathcal{L}_V U, W)+\eta(U, \mathcal{L}_V W)$, and writing the Lie derivatives as brackets gets the desired formula.
Therefore $\eta([X, Z], Y) = -\eta([X, Y], Z)$ and $\eta([Y, Z], X) = \eta([X, Y], Z)$, which upon plugging in the previous formula we obtain $2\eta(\nabla_Y X, Z) = -\eta([X, Y], Z)$. Since this holds for all left-invariant vector fields $Z$, we conclude the formula (after using $[X, Y] = -[Y, X]$)
$$\boxed{2\nabla_Y X = [Y, X] = \mathcal{L}_Y X}$$
In particular your question is easily answered, as $\nabla_X X = 1/2 \mathcal{L}_X X = 0$, implying every left-invariant vector field $X$ on $(G, \eta)$ is parallel.
One can completely understand the geodesics of $G$ using this fact. Consider the Riemannian exponential map $\text{exp} : \mathfrak{g} \to G$ given by $\exp(v) = \gamma(1)$ where $\gamma$ is the solution to the ordinary differential equation $\nabla_{\gamma'} \gamma' = 0$ with initial condition $\gamma(0) = e$, $\gamma'(0) = v$. If we define the left-invariant vector field $V$ on $G$ as $V_g = dL_g v_e$, then consider the integral curve $\gamma_V$ of $V$ defined as the solution to the ordinary differential equation $\gamma_V'(t) = V(\gamma_V(t))$ with initial condition $\gamma_V(0) = e$. Definitionally, the tangent field to $\gamma_V$ is $V$, and $\nabla_V V = 0$ as $V$ is left-invariant, so $\gamma_V$ is a solution to the initial value problem, therefore by uniqueness $\gamma_V = \gamma$.
So alternatively we can define $\exp : \mathfrak{g} \to G$ as $\exp(v) = \gamma(1)$ where $\gamma$ is a one-parameter subgroup of $G$ with $\gamma(0) = e$ and $\gamma'(0) = v$ ($\gamma$ is in fact tangent to $V = dL v$). The geodesics of $G$ are exactly the image of one-parameter subgroup of $G$.
As an addendum, here's one argument to construct a bi-invariant metric  on any compact connected Lie group $G$ (a hands-on construction is given in doCarmo, "Riemannian Geometry" problem $7$ of Ch. $1$). Pick any Riemannian metric $g(-, -)$ on $G$, and let $\mu$ be the Haar measure on $G$ (which is a bi-invariant measure). Define $\eta$ by the averaging formula
$$\eta(X, Y) = \int_{G \times G} g(dL_g dR_h X, dL_g dR_h Y)\; d\mu(g) d\mu(h)$$
Clearly $\eta$ is bi-invariant by construction (this argument is in Milnor, "Morse theory", Ch. $21$)


jqGrid page return null

Question: i have problem with jqGrid and dynamical data binding.
The problem is, that I allways get Null for parameter page. I am working with MVC3 and jqGrid 4.4.1.
 var dataToSend = {
            mrpId: selPRid,
            mrpFilter: cookMainFilter,
            divId: randomId,
            chartId: chartId
        };

        $("#gridMeasurementsTableView" + randomId).jqGrid({
            url: '/DataMonitor/CreateMeasurementTableView/',
            datatype: "json",
            mtype: 'POST',
            postData: $.toDictionary(dataToSend),
            jsonReader : {
                root: "rows",
                page: "page",
                total: "total",
                records: "records",
                repeatitems: false,
                cell: "cell",
                id: "id"
               },
            colNames: ['Date', 'Value'],
            colModel: [
                { name: 'Timestamp', index: 'Timestamp', width: 280,
                    formatter: function (cellvalue, options, rowObject) {
                            return new Date(parseInt(cellvalue.substr(6, cellvalue.length - 8), 10));
                        }
                },
                { name: 'Value', index: 'Value', width: 200, align: 'center' }
            ],
            loadui: "disable",
            loadtext: "Loading",
            viewrecords: true,
            height: "100%",
            caption: "Measurements2",
            pager: $("#gridpager" + randomId),
            rowNum: 10,
            sortname: 'Value',
            sortorder: "asc",
            rowList: [10, 50, 100]
        });

and function for getting data is define like this:
 public ActionResult CreateMeasurementTableView(string sidx, string sord, int page, int rows, int mrpId, FilterMRPParameters mrpFilter, string divId, string chartId)

br,
Jan
Answer: Try to change postData: $.toDictionary(dataToSend) to postData: dataToSend.

jqGrid page return null


Raidz in FreeNAS eating more space than expected

Question: I just got 6 new 2TB drives, and added them to my FreeNAS box. I have only dealt with RAID1 previously, and each setup has given what I was expecting.
However, with the 6*2TB drives, I wanted to maximize the space available, so I went with raidz. But I seem to be missing space. I have 8.6TB available after the raidz was built. Maybe I did my math horribly wrong, but (N-1) x S(min) (where N=6 and S(min)=2TB) should result in 10TB. (I understand it would be more like 9.something)
Does raidz actually consume more then 1 drive worth of space? Or could their possibly be another problem?  (All drives have been independently verified that 2TB of space is available)
Answer: Freenas/Zfs reserves a small fragment of drive space. So besides having only ~1.82TB of actual space. ZFS reserves 1/64th of drive space for its own means, thus 'stealing' another ~28gb from you on every drive. Also freenas makes a 2gb swap file on every drive, Then losing the 1 drive to Raidz, 8.6TB seems pretty close.
Source: http://cuddletech.com/blog/?p=261
edit Freenas swap file on every drive added.


Advantages of counterbalancing vs. randomizing stimuli

Question: I'm designing an experiment, in which 40 participants answer 10 questions, 5 in condition $A$ and 5 in condition $B$, and I'm interested in the difference between the two conditions.
It's not clear to me what's the best way to allocate questions to each condition.
A simple solution is to counterbalance - generate two lists:
\begin{align}
{\rm List}\ 1\ &=\ Q1A,\ Q2B,\ Q3A,\ Q4B,\ Q5A,\ Q6B,\ Q7A,\ Q8B,\ Q9A,\ Q10B  \\
{\rm List}\ 2\ &=\ Q1B,\ Q2A,\ Q3B,\ Q4A,\ Q5B,\ Q6A,\ Q7B,\ Q8A,\ Q9B,\ Q10A
\end{align}
and randomly assign participants to one or other.
Alternatively, I could randomly assign 5 questions to each condition for each participant, fully randomizing the stimuli.
I plan on analysing the result using a mixed effects model, as I'm expecting some missing cases:
lmer(dv ~ condition + (condition|question) + (condition|subject))

My question is this: Is it more statistically appropriate to counterbalance, or to randomize in such a situation?
Answer: I think the pros of counterbalancing are basically their convenience for you.  You set up two questionnaires and you're done.  If you have many people using each list, you can add List as a factor and test to see if it has any effect.
The cons of counterbalancing are that there may be some effect of, say, $Q1$ and $Q3$ being in the same condition.  That is the case now in both of your lists (they are both in $A$ in list 1, and both in $B$ in list 2).  In fact there are many such possibilities (all evens in same condition, etc.).  There are also possible order effects ($Q1$ always comes before $Q2$, etc.).  It is possible to create a set of lists that counterbalances across all possibilities, but that is a lot of permutations.  Randomizing makes all possibilities equally likely (in the long run) and thus marginalizes over (washes out) these possible effects.  Presumably, these effects are not actually of interest to you (they are nuisance variables).  If so, randomizing better controls for these issues.  As such, randomization has a theoretical advantage.  However, the effects may be quite small in reality; so small in fact, that this isn't something you really need to worry about.  And randomization is likely to be a pain.
Comment: So there's no statistical reason to counterbalance rather than randomize? That's really what I wanted to hear - it's pretty painless to fully randomize condition and order nowadays (thanks, [OpenSesame](http://osdoc.cogsci.nl/)).
Comment: There is no real advantage of counterbalancing in practice, @Eoin. If you did have every permutation represented, w/ adequate nj per permutation, you could test specific hypotheses (assuming you wanted to). But the number of permutations is so large N would be prohibitive, & I assume this is a nuisance. Thus, *no* there is no reason to counterbalance (rather than fully randomize) other than convenience.


Clairification on Plane Symmetries of a Chessboard: Rotation vrs Reflection

Question: I just wanted to confirm this with someone.
When we refer to reflections of the chessboard about the diagonal, we are not talking about rotations (which would assume that the chessboard has the same face on the bottom and top). Instead, if use a matrix to represent the chessboard, we are referring to swapping the tiles (entry $(i,j)$) on the chessboard with their counterparts on the other side of the diagonal (with $(j,i)$).
Is this true?
Answer: A rotation is never a (single) reflection; the former is orientation preserving, and the latter isn't. And yes: if you use a matrix to represent the board, a reflection across the northwest-southeast diagonal corresponds to a transposition of the matrix.


INSERT INTO Não envia os dados para a base de dados

Question: Tenho o seguinte código:
$con=mysqli_connect("localhost","esferinf_fpessoa","*****","esferinf_factura");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql = ($con, "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ('$dia, $cliente',$toalhetes, $higienico, $bidons)");
$result = mysqli_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
    header('Location: index.php');
}
else {
    echo "ERROR";
}

Contudo, os dados não são enviados para a BD.
Qual é o problema?
Answer: Na sua string de consulta, remova a variavel $con, mudando
$sql = ($con, "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ($dia, $cliente,$toalhetes, $higienico, $bidons)");

para
$sql = "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ($dia, $cliente,$toalhetes, $higienico, $bidons)";

O mysqli_query() no modo procedural pede dois argumentos: a conexão, e a string de consulta. Seu código deve ficar assim:
$result = mysqli_query($con, $sql);

É recomendado que utilizar prepared statements para evitar sql injection. Utilizando isso, seu código deve ficar assim:
$sql = "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES (?, ?, ?, ?, ?)";

$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "sssss", $dia, $cliente, $toalhetes, $higienico, $bidons);
mysqli_stmt_execute($stmt);

em stmt_bind_param() o sssss significa o tipo do argumento, ou seja cinco argumentos do tipo string.
s: para 'string'
i: para 'inteiro'
d: para 'double'
b: para 'blob'

Answer: Utilize aspas nas variáveis de inserção:
$sql = ($con, "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ('$dia', '$cliente','$toalhetes', '$higienico', '$bidons')");
$result = mysqli_query($sql);


Qual a diferença entre codec, formato de arquivo e extensão?

Question: Já vi falar que mp3, mp4 e etc... usa o mesmo codec, mas o que são cada uma e qual a diferença?
Answer: Vamos pegar um exemplo: "imagem.jpg"

Formato do arquivo: é a forma como os dados são armazenados no arquivo. Nesse caso é uma imagem, que foi "compactada" com o compressão JPG/JPEG. Em muitos tipos de arquivo além do conteúdo em si isso implica em ter um cabeçalho (header) no começo do arquivo contendo informações sobre esse conteúdo (metadados) como identificador do formato de arquivo, dimensões (no caso de imagens), autor, local, encoding utilizado, etc.

Codec: (de "codificador-decodificador") é o software que foi utilizado para, a partir de um arquivo no formato "padrão" ou mais simples, gerar um arquivo no formato esperado. Ou seja, é o codec que gerar o gera o arquivo no formato certo. Outros exemplos seriam mpg e mkv para vídeo, ou seja, exitem codecs que processam um vídeo e geram videos compactados nesses outros formatos.

Extensão: nada é mais é que a parte do nome do arquivo que identifica o formato ou o tipo do arquivo. No exemplo, o ".jpg" é extensão que indica que é um arquivo com o formato JPG/JPEG. Uma observação é que, a extensão é usada pelos programas que vão abrir esse arquivo para "saber" que foi codificado (encoding) naquele formato, mas isso não significa que necessariamente aquele arquivo está nesse formato. As extensões ajudam o SO a associar determinado programa a um tipo de formato de arquivo, assim por exemplo ao clicar num arquivo o SO sabe qual software deve usar para "abrir" ou "ler" aquele arquivo. Existiu uma restrição histórica para a extensão ter no máximo três letras, mas hoje isso não é mais verdade, embora possa ser visto em algumas extensões tradicionais como .exe, .zip, .txt, .jpg, .gif, etc.

Como bônus temos também o termo formato de compressão, que tem a ver com comprimir dados (codec) em um formato mais portável (compactado) e/ou mais otimizado para transmissão. Essa compressão pode ser lossy (sofre perda de informação em relação ao original) ou lossless (não há perda). Por exemplo, MPEG é uma família de formatos lossy voltado para streaming de áudio/vídeo que inclui o MPEG-1 Layer 3, que é o famoso MP3. PKZIP e RAR são formatos conhecidos de compressão lossless de arquivos em geral (arquivos .zip e .rar, respectivamente). Note que certos arquivos compensa compactar, para fins de transporte/armazenamento, outros já são orginalmente bem compactados por algum outro formato e há pouca ou nenhuma vantagem em compactar em outro, podendo deixar o arquivo inclusive maior do que já era.
Comment: @Gustavosoares Ótimo. Lembra do [tour]? Pode aceitar a resposta então :)
Comment: https://i.pinimg.com/736x/d5/54/5d/d5545d8fb22c51574148c2fa709ec1d3--betrayal-so-sad.jpg
Comment: kkkkkkkkkkkkkkk....:D
Comment: muito boa essa imagem @Piovezan :D
Comment: Isso respondeu totalmente minha pergunta
Comment: Ok então vou lá
Comment: @Gustavosoares É pequeno gafanhoto, eu vi o +1 mas faltou "aceitar" mesmo, que é marcar verdinho abaixo desse número à esquerda da resposta. Veja [aqui](https://pt.stackoverflow.com/questions/495152/qual-a-diferen%c3%a7a-entre-codec-formato-de-arquivo-e-extens%c3%a3o#comment919644_495152)
Comment: @Piovezan, o +1 que viu é meu e o outro é seu.


Solving Coupled Eigenvalue equations

Question: I wish to solve the following set of coupled eigenvalue equations. How should I do it?
For real matrices $A$,$B$,$D$ and vectors $x \in R^m$, $y \in R^n$
$$
A x + B y = \lambda x
$$
$$
B^T x + D y = \mu y
$$
where, $A$ and $D$ are symmetric.
Background:
I am trying to solve the following optimization problem:
$$
\min x^T A x + y^T D y + x^T By
$$
$$
\textrm{such that } \, x^T x = 1 , y^T y = 1
$$
This leads to the above eigenvalue problem. $\lambda$ and $\mu$ are the Langrangian parameters for the constraints.
EDIT: I need to actually find numerical solutions for these equations given $A$, $B$, $D$
Comment: From the optimization, I just realized I want to maximize $\lambda + \mu$
Answer: If you write $I^m$ for an $m \times m$ identity matrix, you can make a big matrix equation out of it $$\left(\begin {array}{c  c}A-\lambda I^m & B\\B^T & D-\mu I^n \end {array}\right)\left(\begin {array}{c}x \\ y \end {array}\right)=0$$    which is a classic eigenvalue problem.  Chapter 11 of Numerical Recipes (free for the obsolete versions) or any numerical analysis text can help you.
Comment: Can you please explain?
AFAIU, This is not the classic Eigenvalue Problem because there are 2 parameters $\lambda$ and $\mu$. Numerical Recipes does not give methods to solve such problems
Comment: This was my first thought, too. But he wants to normalize the $x$ and $y$ parts to unit vectors *independently from each other*, and I don't see how to factor that in here.
Answer: This is not a complete solution... but maybe this will help.
Write $u = \begin{pmatrix}x\\y\end{pmatrix}$. Then the objective can be written as $u^TQu$ where $Q = \begin{pmatrix}A & B/2\\B^T/2 & D\end{pmatrix}$. The constraints can be written as $u^TM_1u = 1$ and $u^TM_2u = 1$.
Now, for $\alpha\in(0,1)$, let $M = \alpha M_1 + (1-\alpha)M_2$. Form a constraint as $u^TMu = 1$. It is clear that the minimization with this constraint alone will give a lower bound on the required minimum value. This minimization can be done easily. Let $R = \sqrt{M}$, as $M$ is p.d., and $v = Ru$. Then, the constraint is simply $v^Tv = 1$ and the objective can also be written as $v^TQ'v$, where $Q' = R^{-1}QR^{-1}$. The solution to this is the minimum eigenvalue of $Q'$, which can be obtained by Ritz iterations etc.
Hence the supremum of these lower bounds give a lower bound for for the given minimization problem. The interesting thing to prove is that the supremum of these lower bounds for various $\alpha\in(0,1)$ is the required minimum. This can be shown easily when $B=0$, but I haven't been able to prove it in the general case.
Answer: Append x and y
form z belonging to R (m+n) by appending y to x
So, now, you will get
m * (m+n) matrix on the left hand side through 1st equation and n*(m+n) matrix on the left hand side through 2nd equation.
your variable is of size m+n.
hence, append the two equations...
now, you get a square matrix on the LHS of size m+n *m+n -- solve
Comment: This is an eigenvalue problem. lambda and mu are not known before hand, so this will not work
Answer: Perhaps adding the two equations in order to reeduce it to one equation with eqienvalue (lambda + mu) and Eqienvector x+y is the trick. Then find the inverse using a calculator or standard methods. But there is probably a trick involving the fact that the matrices satisfies the properties they do.
Comment: This does not work

Solving Coupled Eigenvalue equations


Problem with IIS 7.0 / PHP and new website in different physical location on hard drive (NOT WWWROOT)

Question: First of all congrats to everyone who posts over here and contributes for a better environment ... Anyways, lets boil it down to the problem.
Step 1 - I downloaded IIS 7.0 for windows 7 x64 and installed it.  Everything is working fine and displaying the default website as expexted.
Step 2 - I then downloaded the PHP web Platform installer installed php ...together with php manager 1.0.  I then created a folder in default website ..... put an index.php in it with (phpinfo) converted this newly created folder to an application and  it all showed up and worked a charm....
Step 3 - I then was developing a particular PHP application which requires saving of files onto the server and for some strange reason was unable to save.... thought it was all boiling down to folder permissions maybe... So I went through the permissions but the folder inherits permissions from inetpub... and am not changing that ... therefore i went to the next step
Step 4 - I tried creating a new website in IIS (files located in different physical location on hard drive... read write permissions enabled - full control) but it did not show up (with the index.php in the folder) so this was funny so i did further testing...
Step 5 - Created a new website ... did the usual settings (default app pool ... inserted an alias .. and located the SAME APPLICATION i created earlier in the wwwroot to see if it shows up.. and it didn't .....................
Now I am quite short of ideas.  It is weird how php applications within the wwwroot folder work fine but cannot seem to get saving operations to work in here... But it is just as weird that when i located the application which works through localhost does not work from the newly created website e.g. http://testmylocalphp.com (with physical path to the same app file above).
I really would appreciate your help on this.  I would like to solve the saving issue ... and hopefully create a phproot folder use it separate from the wwwroot and get it to show in the browser ... in this manner I can put my php work in it and ... I use wwwroot for asp.net ....
Your input on this subject is most welcome.
I send my best regards to everyone
Al
PS: I used to use IIS 6.0 but never ran into these problems ...
Comment: Give IUSR read / write permissions as per your requirement.
there is also a IUSR or IIS user group but iusr should do it for you.
Comment: IIS_IUSRS. . . had full control ... sorry if i did not say it before ...
Answer: There are 2 user accounts that may come into play.  One is the app pool identity set on the app pool, and the other is the anonymous user account set on the website (I assume that you're using anonymous).
First off, on the website Authentication / Anonymous settings, set that to use the app pool identity.  Then you only have 1 user to worry about.
For the app pool, you can set a custom user, or use IIS APPPOOL{app pool name}.  That's the user that needs write permissions on disk.  Also make sure that the PHP app isn't writing to a different folder than you expect ... one that doesn't have permissions.
For why PHP doesn't work under another site, do you get any error or status code?  It may be the binding isn't correct.
Some great tools to help are:
- process monitor from sysinternals.com.  Pretty easy to learn and it's a quick download and free.  Run it while you reproduce the issue.  Then stop it so that it doesn't overwhelm you with data.  Search for the word 'denied'.  That should jump right to where your issue is.  (use this for both the first site and second site issues)
- IIS logs will tell what status code you get for the second issue issue.
- Failed Request Tracing (FRT) can be set at the site level, and it will also tell you a lot.  This will be more helpful on the second site issue.
Comment: I looked into the issue in detail and still seem not to find the cause to the problem. Let me try and explain myself better (maybe it's my explanation I don't know).  The anonymous user and the IIS_IUSRS groups were both added properly in the permissions.  I put the anonymous user in the Website ... and the IIS_IUSRS in the applicaiton folder.  Let's start first things first.  I need to be able to create a website which is separate of wwwroot folder (in a different location) and I want to be able to host it on my local iis7. so far its like DNS is not responding..and the page doesnt turn up.
Comment: Ok, check things in this order:
- ping the domain and make sure that it resolves to the correct IP
- make sure that your new website has bindings for that new IP.  Leave the host header blank unless you require it
- setup a test.html page with a simple 'test' in the body.  Make sure that works
- once you get that working, then try a simple test.php page.

That breakdown in steps will hopefully narrow down at which point it's broken.
Comment: ok now ... the response i got is ....
Comment: ok now ... the response i got from ping was as expected ... "Ping request could not find host http://mytestsite.bz/. Please check the name an
d try again." ... so it is not responding ... I only put an http binding and on port 80 ... am I doing anything wrong in this regard?
Comment: Ok, that's helpful.  That means that the issue isn't related to the http binding or IIS settings.  It's up at the DNS level.  Make sure that mytestsite.bz is registered in your hosts file, network domain server or on the web, depending on what it is.  For a quick test, just drop it in your hosts file in c:\windows\system32\drivers\etc\hosts.
Comment: but shouldnt the hosts file be updated automatically when we create a binding?
Comment: Update: You my friend are a genius :) The hosts file was not updated ... but still i do not understand why.  Now for the second problem.  I still seem to not manage to get write permissions to work on this folder.  Do you have an idea how to resolve this? May I remind you that I am using PHP.  I also could manage to put the folder on a physically different position on the hardrive.
Comment: Great, glad you have the DNS part working successfully now.  The hosts files aren't maintained automatically so it needed that manual step.  For the permissions issue, what you described above sounds correct.  Maybe there is a folder inheritance problem.  The tool that will help you is Process Monitor from www.sysinternals.com.  It's free, a quick learn, and safe on dev or production machine.  Have it running while you reproduce the problem, stop it, then search for the word 'denied'.  That should lead you to where the missing permission is.


Why is this code stopping? VB ASP.NET

Question: Hey I am coding using Visual Studio 2003. My program worked fine until I introduced a dll I made using CreateObject.
Code:
Set docs2 = server.CreateObject("DocGetter.Form1")
docs2.GetDocument oXMLDom,numID

It appears to be getting stuck at this code. I've already used regasm to register the dll.
What else could be wrong?
Comment: This is a web app, is DocGetter.Form1 an actual form object?
Comment: CreateObject is EVIL!  No place for it in the .Net code.
Answer: Add a reference to the dll in your project and instantiate the object like this:
Dim docs2 As New DocGetter.Form1()

If that doesn't make sense, then fix it so it does.  There's no good reason to use CreateObject in .Net code. (Okay, that's hyperbole.  But the principal is sound).
Answer: Can you clarify - is this a web app or a client (winform) app? Form1 sounds like a winform. ASP.NET runs at the server, so showing a form would be inappropriate - it would happen at the server, not the client. In short, don't do this!
I also can't see where "stored procedures" figures in this, so I've removed the tag.
What are you trying to do? Options for showing something more complex at the client include:

dhtml
flash
silverlight
clickonce [requires windows client]
ocx [not recommended]
Comment: aps.net uses the form paradigm
Comment: @Joel - indeed, but without more context from the OP it is unclear whether this Form1 is a webform or a winform.
Answer: I'd bet money that this function isn't defined with this name and/or parameters.
docs2.GetDocument oXMLDom,numID

But because of the way you're instantiating the object, the compiler has no way of knowing this... I think.

Why is this code stopping? VB ASP.NET


How to save field data

Question: I need to programmatically save field data (during node save I want to take the title & path alias and store it in a link field called field_alternative_titles_title).
Which functions can I use here? Do I use field_attach_insert or hook_field_storage_pre_insert to save the link field?
Comment: The nature of the code will obviously depend on the specifics - can you edit your question and show the code you've tried, explaining where it's going wrong?
Comment: I hope that made it clearer
Comment: I think so...if I understand you right, `hook_node_presave()` might be the best place. It gives you access to the whole node before changes get sent to the database, and you can safely manipulate field data before it gets persisted
Comment: what entity your field is attached to? is it attached to the same bundle? or you want to store it directly to DB?
Comment: My field is attached to a field collection item, and that field collection item is attached to a content type of mine
Comment: What I want to be able to do Is to just populate the field, and then associate it via bundle with the field collection item it is attached to (field_alternative_titles).
But I don't know how to do that.
Comment: so during saving a node of content type A you want to store a value in a field which is not attached to that content type?
Comment: One more thing , I wont realize if you have answered my question if you don't mention me using @
Comment: @Alireza Tabatabaeian The field isn't technically attached to the content type, but the field collection that it is attached to is attached to the content type
Answer: At first you need to implement hook_node_presave($node)

Act on a node being inserted or updated.
This hook is invoked from node_save() before the node is saved to the
  database. Parameters
$node: The node that is being inserted or updated.

So it reacts when a node is going to be saved , then you have to check if the node type is the proper node type . then setting field value , so this is some code snippet :
function mymodule_node_presave($node) {
  if($node->type == "Your Node Type") {
      //dsm($node);//it will show the structure of node
      // as example
      $data = $node->title.'-'.drupal_get_path_alias('node/'$node->nid);
      $node->field_alternative_titles_title[$node->language][0]['value'] = "data";//check the node structure,this code wont work for sure
  }
}

of-course this is just an snippet , to make it work you have to know the structure of your content type , Devel module will help you , install and enable it so dsm function will work.
Comment: Will my field_alternative_titles_title table in my database get populated with this code? @Alireza Tabatabaeian
Comment: It had to, if the node which is going to be saved contains field_alternative_titles_title , then it will affected in DB
Comment: Now, if the node doesn't contain the field_alternative_titles_title field, but instead contains the field collection item field_alternative_titles, and the field collection item field_alternative_titles contains the field field_alternative_titles_title. Would it still work if that was the case?
Comment: if it is a part of node (no matter how or how deep just seen in form in enough in this case) yes it will works but you have to address it right . maybe $node->field_alternative_titles_title is not the right destination , to find the right destination use dsm function

How to save field data


Logistic regression assumptions for a model with many binary independent variables

Question: I am working on developing a logistic regression model that uses qualitative variables only ($n=990$). My remit is to define the equation that can identify the most relevant characteristics of a survey respondent that is favorable towards Company X. The proposed equation is similar to the following:
\begin{align}
{\rm Fav} = &a*{\rm age} + b*{\rm CoAware} + c*{\rm IssueAware} + d*{\rm readnewspaper} + e*{\rm region} + \\
            &f*{\rm income}\ldots
\end{align}
The dependent variable is "Company Favorability" (0 = Unfavorable/Neither | 1 = Favorable). There are currently 25 independent variables, 20 of which are binary IVs that range from highly correlated to the DV (awareness of Company) to not significant (gender). I also have 5 categorical variables that indicate region of the country, age (in categories), party affiliation, income level, and education.
I am almost certain that I need to use a logistic regression model for this approach. However, when I test my assumptions, I have having a very difficult time proving a linear relationship between the dichotomous independent variables and the logit transformation of the DV.
My other problem is that, I am somewhat overwhelmed by possible interaction effects. There are 34 possible options using 25 variables - leading me to over 50 million possible combinations.
I have three questions:

Is there a better method to model with a binary dependent variable?
Am I missing something in the assumptions? (ie: Do I need to indeed prove the linear relationship if all of my variables are dichotomous)
Would it be better to approach this by looking at multicollinearity first, to reduce the number of variables overall, and then look at linear relationships with the logit of the DV?
Comment: I admire the work and the hard thinking that this question reflects (+1).  You're concerned with many important issues with which many of us struggle.  Unfortunately I think the answers will come not from a few paragraphs but from ongoing practice, study, and in-depth consultation with experts.
Answer: If all your regressor variables are binary, then the linearity assumption is vacuous! so can be ignored.  But you say you have variables like age, which is not binary.  Then you can consider using a spline of age instead of age directly, which leads to GAMs (generalized additive models) or the use of regression splines.  I found this useful when there are one or a few such variables.
Then consider which interactions you consider plausible, then start with your model.
Comment: Elements of Statistical Learning has a good section on GAMs, IIRC.
Comment: Hey sir, do you have a good resource for the mathematical side of GAMs?
Answer: Here are some thoughts:

If you only want to identify relevant variables (e.g., you don't want to test pre-existing hypotheses, and you aren't trying to build the optimal model for predicting favorability later), you might try either CART, or combining logistic regression with LASSO penalization.
There is no assumption of 'linearity' in logistic regression.  In general, people consider LR to be a non-linear model.  There is some sense in which any model assumes it is properly specified, and it is possible (with a continuous variable) that you could need a squared term (e.g.) for the model to be reasonably well specified, but even that isn't true with only dichotomous variables.
It is often best to try to reduce your independent variables first.  However, you still won't have to worry about 'linearity'.
Comment: In this case (ie, your binary variables) you don't need to worry about linearity, @APCOInsight.
Comment: gung:  you are probably right it is more of a semantic reference! But, however it is expressed, there is an assumption there, which is void if the predictor is binary.
Comment: @kjetilbhalvorsen, that's certainly true.
Comment: @kjetilbhalvorsen and gung: Thank you both for your comments and advice! Does this mean that a LR model is invalid, or I don't need to worry about linearity? I think I will try Gung's suggestion of the LR with LASSO penalization and reduced number of IVs. To be honest, I have suggested that this analysis be much better viewed as a cluster analysis rather than deriving a formula for an "ideal" respondent - but need to show that we've attempted this approach nonetheless.
Comment: No, there IS an assumption of linearity. Wiev the logistic regression as a GLM (generalized kinear model). The linearity is in the linear predictor, while the probability itself is a non-linear function of that linear predictor. Else, what you says make sense.
Comment: @kjetilbhalvorsen, the "non-linear model" part is just a throwaway comment, you're right about that. But neither OLS nor LR really assumes linearity, there is simply the assumption that the model is properly specified, which may amount to linearity in some cases. I suspect this is more of a semantic difference.


IPC MSG Queue how to identify message type of each message that is sent?

Question: I just learned about MSG queues and I tried to write two processes with common keys, where one sends messages and another reads messages then removes the queue. But the problem is, I want to know which message had which type when they're sent.
Here is my console results:

MSG sent: MSG_6
MSG sent: MSG_2
MSG sent: MSG_8
MSG sent: MSG_9
MSG sent: MSG_8
MSG sent: MSG_3
MSG sent: MSG_6
MSG sent: MSG_6
MSG sent: MSG_2
MSG sent: MSG_5
Recieved type: 5, MSG_6
Recieved type: 5, MSG_2
Recieved type: 5, MSG_8
Recieved type: 5, MSG_9
Recieved type: 5, MSG_8
Recieved type: 5, MSG_3
Recieved type: 5, MSG_6
Recieved type: 5, MSG_6
Recieved type: 5, MSG_2
Recieved type: 5, MSG_5
Now removing the QEUE in 3 seconds

I was expecting that mtype would be same as each MSG sent. However, as you can see receiver process only prints very last MSG type. If I'm able to get each MSG types so that I can sort them in a some way.
IPC_COMMON.h where both sender and receiver includes this header file.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>

#define TEST_ERROR    if (errno) {fprintf(stderr, \
                      "%s:%d: PID=%5d: Error %d (%s)\n", \
                      __FILE__,         \
                      __LINE__,         \
                      getpid(),         \
                      errno,            \
                      strerror(errno));}
#define MSG_LEN 120

struct msgbuf {
    long mtype;
    char mtext[MSG_LEN];
};

#define MY_KEY 0x123456
#define MSGTYPE_RM  7

SENDER.c

#include "testCommon.h"
#include <time.h>

int main() {
    int id_q;
    struct msgbuf my_msg;
    int typeArr[10];
    int i;

    id_q = msgget(MY_KEY, IPC_CREAT | 0600);
    TEST_ERROR;

    srand(time(NULL));

    for(i = 0; i < 10; i++) {
        typeArr[i] = rand() % 10;
        my_msg.mtype = typeArr[i];
        printf("Printing types %d\n", typeArr[i]);
    }

    for(i = 0; i < 10; i++) {
        switch(typeArr[i]) {
        case 0:
            strcpy(my_msg.mtext , "MSG_0");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 1:
            strcpy(my_msg.mtext , "MSG_1");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 2:
            strcpy(my_msg.mtext , "MSG_2");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 3:
            strcpy(my_msg.mtext , "MSG_3");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 4:
            strcpy(my_msg.mtext , "MSG_4");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 5:
            strcpy(my_msg.mtext , "MSG_5");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 6:
            strcpy(my_msg.mtext , "MSG_6");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 7:
            strcpy(my_msg.mtext , "MSG_7");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 8:
            strcpy(my_msg.mtext , "MSG_8");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        case 9:
            strcpy(my_msg.mtext , "MSG_9");
            msgsnd(id_q, &my_msg, MSG_LEN, 0);
            printf("MSG sent: %s\n", my_msg.mtext);
            break;
        default:
            fprintf(stderr, "Error occurred\n.");
            TEST_ERROR;
        }
    }
    return 0;
}

RECEIVER.c

#include "testCommon.h"

int main() {
    int q_id, num_bytes, i;
    struct msgbuf my_msg;
    num_bytes = 0;
    q_id = msgget(MY_KEY, IPC_CREAT | 0600);
    TEST_ERROR;

    while (1) {
        /* now receiving the message */
            for(i = 0; i < 10; i++) {
            num_bytes += msgrcv(q_id, &my_msg, MSG_LEN, 0, 0);
            printf("Recieved type: %ld, %s \n", my_msg.mtype, my_msg.mtext);
            }
            if(num_bytes >= 0)
            break;
    }
    printf("Now removing the QEUE in 3 seconds\n");
    sleep(3);
    msgctl(q_id, IPC_RMID, NULL);
}

Comment: "*as you can see receiver process only prints very last MSG type*" -- no, I can't see that, because I choose not to load or try to read your images.  Do not post images of text.  Rather, copy & paste the text *as* text.  Use code-block formatting for it to avoid line breaks and similar being mangled.
Comment: You post a header that you label as `IPC_COMMON.h`.  Is this the same thing that the two programs reference as `testCommon.h`?
Comment: Do not test `errno` to try to determine whether an error has occurred.  This can produce both false positives and false negatives.  Functions that can fail provide direct means to detect that, generally in the form of special return values.  Checking those is how you must determine whether an error occurred.  *Some*, but not all, functions use `errno` to convey the nature of such failures.  Consult `errno` for that information only (immediately) after a function indicates that it failed.
Comment: Message types must be strictly greater than 0.  Your test code affords the possibility that some of those you use are 0.
Comment: thank you for your answer and comments, sorry about the picture tho, you seem irritated. I'll keep that mind from now on.
Answer:
I was expecting that mtype would be same as each MSG sent.

There are a few issues with your code, which I have mostly raised in comments on the question.  But the main issue appears to be that you set my_msg.mtype for the last time before you send any messages to the queue.  You set the mtext data each time, but not mtype.  I would expect, then, that all the messages come across with the message type designated in the sender by typeArr[9], as that's the last mtype value you set.
You might try this instead of the sender's two for loops:
    for (i = 0; i < 10; i++) {
        my_msg.mtype = 1 + rand() % 9;
        sprintf(my_msg.mtext, "MSG_%ld", my_msg.mtype);
        ssize_t result = msgsnd(id_q, &my_msg, MSG_LEN, 0);
        if (result == -1) {
            // handle error ...
        } else {
            printf("MSG type %ld sent: %s\n", my_msg.mtype, my_msg.mtext);
        }
    }


Filtering through data in a column based on cell value

Question: I need to do the two following things:
1) Delete all rows whereby Current Entity Name equals
Subscription Line of Credit
Other Assets
Net Other Assets
Liabilities
Cash and Cash Equivalents.
2)Append "#UP#" to all of the remaining records of Current Entity Name.
(i.e if Current Entity Name = St Georges Hospital, after running macro, it should end up as #UP#St Georges Hospital).
Current Entity is in column D.
I have the following codes:
Sub Test()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim CurrentEntityColumn As Integer
Dim POColumn As Integer
Dim DomColumn As Integer
Dim i As Long

 MsgBox ("Select Investment Analysis_Before")
Sourcefile = Application.GetOpenFilename()
Workbooks.Open (Sourcefile)

CurrentEntityColumn = Cells(Rows.Count, "D").End(xlUp).Row
For i = 1 To CurrentEntityColumn
If Cells(i, "D").Value = "Subscription Line of Credit" Or Cells(i, "D").Value = "Other Assets" Then
Cells(i, "D").EntireRow.Delete
End If

Next i
End Sub

However, the code dont seem to be working as it only deletes whatever that I put last in the or argument. In this case it only deletes rows which column D contains "Other Assets". Subscription Line of Credit is not deleted.
I also observed that this error only occurs when I use entirerow.delete. I have tried using changing the font color if cell contains "Subscription Line of Credit" and it works fine.
Can anyone tell me what have I done wrongly and also any ideas to complete task 2? Thanks
Answer: what about:
If Cells(i, "D").Value = "Subscription Line of Credit" Then
  Cells(i, "D").EntireRow.Delete
ElseIf Cells(i, "D").Value = "Other Assets" Then
  Cells(i, "D").EntireRow.Delete
Else
  Cells(i, "D").Value = "#UP#" & Cells(i, "D").Value
End If


Force ECS to wait for previous container to have exited before deploying new task version

Question: I have a couple of ECS services that cannot under any circumstances run two instances of a container (embedded elasticsearch, mysql). Is there any way to force ECS to wait until the container has actually stopped (not just transitioned to DEPROVISIONING) before deploying the new task revision?
Answer: Yes, I recently struggled with this issue as well. Set deployment_maximum_percent=101 (you can't do 100 because it can't be the same as deployment_minimum_percent)


Jotai - Update a async loadable atom

Question: Current Code
const asyncAtom = atom(async () => {
  const res = await (
    await fetch("http://localhost:3000/api/transactions")
  ).json();
  return res;
 });

const loadableAtom = loadable(asyncAtom);
const [transactions] = useAtom(loadableAtom);

How can I update the transactions if I want to refetch the data?
With setTransactions I get the error "This expression is not callable. Type 'never' has no call signatures.ts(2349)".
Answer: The answer is to make the response the loadable atom and the request a setter atom, in your example:
const responseAsync = atom(null)

const setAsyncAtom = atom(null, async (get, set) => {
  const res = (
    await fetch("http://localhost:3000/api/transactions")
  ).json();
  set(responseAsync, res)
 });

const loadableAtom = loadable(responseAsync);
const [transactions] = useAtom(loadableAtom);

...... (in component)

const [, refreshData] = useAtom(setAsyncAtom)

So you can call refreshData on demand when you need to refresh data.
Answer: loadable(responseAsync) might  not right, since loadable expect to receive async atom, otherwise loadableAtom  wont have state of 'loading' | 'hasData' | 'hasError'. refer to https://jotai.org/docs/utilities/async

Jotai - Update a async loadable atom


Problemas com caixa de cadastro de email css

Question: Olá, estou com um probleminha ao adicionar uma caixa de email no meu blog, aquelas que cadastra para o usuário receber atualizações por email.
Eu coloco a cor da font branca mas nn faz efeito, mesmo adicionando "!important".
aqui está a imagem

/* CSS EMAIL SUBSCRIBE */
#email-subscribe {padding:20px;background:#4dbfd9;}
#email-subscribe h4.title {font-size:16px;color:#FFFFFF;font-weight:400;line-height:1;text-align:center;text-transform:uppercase;margin-bottom:0;}
#email-subscribe h4.title span {display:inline-block;font-weight:700;font-size:30px;margin-top:15px;}
#email-subscribe input.email-field {color:#fff;background:#4dbfd9;margin-top:0px;}
#email-subscribe input {color:#fff;border:1px solid rgba(255,255,255,.4);width:100%;text-align:center;-moz-box-sizing:border-box;box-sizing:border-box;padding:0.662em 1.247em;margin:0;box-shadow:none;outline:0;border-radius:2px;font-size:14px;line-height:19px;}
#email-subscribe input.submit {background:#4dbfd9;color:#fff;margin-top:20px;font-size:14px;font-weight:300;cursor:pointer;transition:all .3s;}
#email-subscribe input.submit:hover {background:#fff;color:#4dbfd9!important}

Receba Atualizações
 EM SEU EMAIL

<form action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=blogspot/vYnG', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true" _lpchecked="1">
<input class="email-field" type="text" value="" placeholder="digite seu e-mail aqui" name="email" />
<input type="hidden" value="blogspot/vYnG" name="uri" /><input type="hidden" name="loc" value="pt_BR" />
<input class="submit" name="submit" type="submit" value="Cadastre-se agora" />
</form>

Answer: Opa, eai. Pelo que vi você tentando mudar a cor do texto, mas no caso o que voce precisa mudar é a cor do placeholder e para isso adicione essa linha como fiz aqui. E espero ter ajudado!!!
 #email-subscribe input::-webkit-input-placeholder {
   color: #fff;

}

/* CSS EMAIL SUBSCRIBE */
#email-subscribe {padding:20px;background:#4dbfd9;}
#email-subscribe h4.title {font-size:16px;color:#FFFFFF;font-weight:400;line-height:1;text-align:center;text-transform:uppercase;margin-bottom:0;}
#email-subscribe h4.title span {display:inline-block;font-weight:700;font-size:30px;margin-top:15px;}
#email-subscribe input.email-field {color:#fff;background:#4dbfd9;margin-top:0px;}
#email-subscribe input {color:#fff;border:1px solid rgba(255,255,255,.4);width:100%;text-align:center;-moz-box-sizing:border-box;box-sizing:border-box;padding:0.662em 1.247em;margin:0;box-shadow:none;outline:0;border-radius:2px;font-size:14px;line-height:19px;}
#email-subscribe input.submit {background:#4dbfd9;color:#fff;margin-top:20px;font-size:14px;font-weight:300;cursor:pointer;transition:all .3s;}
#email-subscribe input.submit:hover {background:#fff;color:#4dbfd9!important}
 #email-subscribe input::-webkit-input-placeholder {
   color: #fff;

}

Receba Atualizações
 EM SEU EMAIL

<form action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=blogspot/vYnG', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true" _lpchecked="1">
<input class="email-field" type="text" value="" placeholder="digite seu e-mail aqui" name="email" />
<input type="hidden" value="blogspot/vYnG" name="uri" /><input type="hidden" name="loc" value="pt_BR" />
<input class="submit" name="submit" type="submit" value="Cadastre-se agora" />
</form>

Comment: Não entendi o por quê do negativo... Parece funcionar...
Comment: Segue uma referencia http://tableless.com.br/estilizar-e-formatar-placeholder-de-inputs/
Comment: Eu fiz isso e teve um pequeno bug que foi criar uma margin automaticamente. Consegui resolver o problema assim:

#email-subscribe input.email-field,  #email-subscribe input::-webkit-input-placeholder{color:#fff;margin-top:0px;}

Muuito obrigado amigo <3 xeruh kkjj
Comment: agora eu gostaria de saber como eu faço para que ao clicar na caixa, o nome "Digite seu e-mail aqui" some, e quando clicado em outra coisa fora da caixa, as palavras voltem pro lugar.
Answer: Acho que oque você quer e mudar a cor do placeholder, com color: #fff; no placeholder deve resolver
Comment: Opa, já consegui arrumar o erro. Obrigado :) :D


Are member-initialization lists really more efficient?

Question: I agree with the consensus that it's generally best to initialise C++ data members in a member initialization list rather than the body of a constructor, but I am sceptical of this explanation

The other (inefficient) way to build constructors is via assignment, such as: Fred::Fred() { x_ = whatever; }. In this case the expression whatever causes a separate, temporary object to be created, and this temporary object is passed into the x_ object's assignment operator. Then that temporary object is destructed at the ;. That's inefficient.

Is this actually correct? I would have expected the compiler to elide the default-constructed temporary object which is immediately replaced by assignment in the body. I don't know why I expected this but having read the above claim I guess I have been quietly assuming it for years.
Are member initialization lists actually more efficient? If so, is it for this reason?
Comment: That would seem to expect the compiler to perform a complete code analysis of what happens in the body of the constructor, which it probably won't do. So yes, initialisation lists are, magic compilers aside, more efficient, and also, IMHO, easier to read.
Comment: the compiler could only "elide" the default construction through the "as-if" rule, so it needs to be able to figure out there is no difference. Given that it is trivial to avoid this by suitably initializing, why not do it?
Comment: Initialization followed by assignment operator is not a copy-elision scenario
Answer: In the words of Alexandrescu & Sutter (item 9) Don't pessimize prematurely

Avoiding premature optimization does not imply gratuitously hurting
  efficiency. By premature pessimization we mean writing such gratuitous
  potential inefficiencies as:
• Defining pass-by-value parameters when pass-by-reference is
  appropriate. (See Item25.)
• Using postfix + + when the prefix version is just as good. (See
  Item 28.)
• Using assignment inside constructors instead of the initializer
  list. (See Item 48.)

Whenever you are writing assignments inside constructors, your code reviewers will be on alert: is something special going on? Did he really want some special two-stage initialization (because there is an implicit default construction of the member being generated anyway!). Don't surprise the readers of your code gratuitously.
Note that Alexandrescu & Sutter go on in Item 48 to discuss the potential inefficiency, but don't claim anywhere that there an actual inefficiency in real optimized code. That is also beside the point, it's about expressing intent and avoiding the risk of inefficiency.
Answer: Using member init list,
#include <string>

struct Fred {
  Fred() : x_("hello") { }
  std::string x_;
};

int main() {
  Fred fred;
}

Clang 3.9.1 and gcc 6.3 generate the following with -O3 -fno-exceptions (Compiler Explorer):
main:                                   # @main
        xor     eax, eax
        ret

If we do an assignment in the body instead:
#include <string>

struct Fred {
  Fred() { x_ = "hello"; }
  std::string x_;
};

int main() {
  Fred fred;
}

both generate a lot more code, e.g. Clang 3.9.1 outputs this:
main:                                   # @main
        push    rbx
        sub     rsp, 32
        lea     rbx, [rsp + 16]
        mov     qword ptr [rsp], rbx
        mov     qword ptr [rsp + 8], 0
        mov     byte ptr [rsp + 16], 0
        lea     rdi, [rsp]
        xor     esi, esi
        xor     edx, edx
        mov     ecx, .L.str
        mov     r8d, 5
        call    std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_replace(unsigned long, unsigned long, char const*, unsigned long)
        mov     rdi, qword ptr [rsp]
        cmp     rdi, rbx
        je      .LBB0_2
        call    operator delete(void*)
.LBB0_2:
        xor     eax, eax
        add     rsp, 32
        pop     rbx
        ret

.L.str:
        .asciz  "hello"

So it seems member init lists really are more efficient, at least for some cases, even with modern compilers.
Comment: that's actually depressing to see that modern compilers won't optimize this away.
Answer:
Are member initialization lists actually more efficient? If so, is it for this reason?

Generally yes. With member initialization you pass value directly to a constructor, otherwise a default-constructed object would be created and then assignment operator would be called. Note this is not about "temporary" mentioned in quote you provided, this is about field itself.
You can see it live here
class Verbose {
public:
    Verbose() { std::cout << "Verbose::Verbose()" << std::endl; }
    Verbose( int ) { std::cout << "Verbose::Verbose(int)" << std::endl; }
    Verbose &operator=( int )  { std::cout << "Verbose::operator=(int)" << std::endl; }
};

class A {
public:
    A() : v( 0 ) {}
    A(int)  { v = 0; }
private:
    Verbose v;
};

int main() {
    std::cout << "case 1 --------------------" << std::endl;
    A a1;
    std::cout << "case 2 --------------------" << std::endl;
    A a2( 0 );
    // your code goes here
    return 0;
}

output:
case 1 --------------------
Verbose::Verbose(int)
case 2 --------------------
Verbose::Verbose()
Verbose::operator=(int)


$\chi^2$ test of homogeneity for three-way contingency table

Question: I have a three-way contingency table in which the marginal totals for two sides are fixed and for the third are random. I'm wondering how to perform a chi-square test for homogeneity for such a three-way contingency table.
Example

Assume both Trt and Gender marginal totals are fixed.
Thanks
Comment: @AndyW No, only the math-mode subset is supported (The engine is called MathJax, see [its page](http://www.mathjax.org/) for detailed docs). Yet I think a proper way to post tables is plain text in code block, so it could be copyable.
Comment: When you say *homogeneity*, are you trying to test whether the treatments have the same response proportions of $R/(R+NR)$ with gender as a confounding variable, or that the treatments have the same proportions as each other and for both genders?
Comment: Just my curiosity - any particular reason that the M-F split is so unbalanced?  This seems odd to have a *fixed total* of 274 for F and only 46 for M.  Or are these based on "population" proportions - there is a 274:46 split in the population of F to M?
Answer: I would approach this as a hypothesis test (but then I am a Bayesian, and we always tend to do things a bit differently).  I take it by homogeneous that you mean homogeneous in the "way" which did not have its totals fixed.
If we index the cell counts as $n_{ijk}$ for $i=1,\dots,I$ for the first way, and $j=1,\dots,J$ for the second way, and $k=1,\dots,K$ for the third way.  This gives a total of $IJK$ cells in your contingency table.  The "saturated model" is to assume that each cell is a multinomial distributed variable, with an individual long run frequency, so
$$p(n_{111},\dots,n_{IJK}|\theta_{111},\dots,\theta_{IJK})=n_{\bullet\bullet\bullet}!\prod_{i=1}^{I}\prod_{j=1}^{J}\prod_{k=1}^{K}\frac{\theta_{ijk}^{n_{ijk}}}{n_{ijk}!}\propto\prod_{i=1}^{I}\prod_{j=1}^{J}\prod_{k=1}^{K}\theta_{ijk}^{n_{ijk}}$$
If a row total had been fixed, then we would get:
$$p(n_{111},\dots,n_{IJK}|\theta_{111},\dots,\theta_{IJK})=\prod_{i=1}^{I}n_{i\bullet\bullet}!\prod_{j=1}^{J}\prod_{k=1}^{K}\frac{\theta_{ijk}^{n_{ijk}}}{n_{ijk}!}\propto\prod_{i=1}^{I}\prod_{j=1}^{J}\prod_{k=1}^{K}\theta_{ijk}^{n_{ijk}}$$
If a row and column totals had been fixed, then we would get:
$$p(n_{111},\dots,n_{IJK}|\theta_{111},\dots,\theta_{IJK})=\prod_{i=1}^{I}n_{i\bullet\bullet}!\prod_{j=1}^{J}n_{\bullet j\bullet}!\prod_{k=1}^{K}\frac{\theta_{ijk}^{n_{ijk}}}{n_{ijk}!}\propto\prod_{i=1}^{I}\prod_{j=1}^{J}\prod_{k=1}^{K}\theta_{ijk}^{n_{ijk}}$$
This shows that whether the row totals are fixed or random, is not relevant to inference about the $\theta_{ijk}$ parameters - as this will simply change the factorial in the denominator.  This is called the "likelihood principle".  However it is relevant if you are going to be predicting a new set of counts sampled in the same way that you sampled your data.  This is usually how the standard statistician will think though (in terms of "if I did this experiment again...").
But for a hypothesis which is not sharp, such as two parameters being equal, but not restricted to be equal to anything the "prior predictive" distribution is what matters (at least from a Bayesian perspective) - and this certainly depends on the sample design!  This is quite interesting for the "likelihood principle" is a bit subtle - your interest must be in the particular values of the parameters and not whether two parameters are equal.  It is quite easy to see that the prior predictive distribution will depend on the sample design.
My answer to this question should be easily adapted to your case.  I can provide more details if you are uncertain how to adapt it to your case.
You can also use a poisson GLM with a log-link function to do this test, and it amounts to testing that a certain interaction term in the glm is zero, so you can use the Pearson residuals from the output of the glm to do your chi-square test - you can also use the deviance table.
UPDATE
Having denied the likelihood principle here is actually incorrect on my part, for making inference on the $\theta_{ijk}$ parameters.  This is easily seen by first computing odds ratios and then renormalising - the part related to the sampling design will cancel out.  What an ass I made of myself, talking about "subtle" and all that!  To show this more explicitly, I will write out $A\equiv A(n_{111},\dots,n_{IJK})$ as the constant which depends on how the experiment was done and which totals were fixed and which were random (independent of the $\theta_{ijk}$ parameters).  I will show the final answer does not depend on $A$.  So we we have:
$$p(n_{111},\dots,n_{IJK}|\theta_{111},\dots,\theta_{IJK})=A\prod_{i=1}^{I}\prod_{j=1}^{J}\prod_{k=1}^{K}\theta_{ijk}^{n_{ijk}}$$
For the specific problem I will let $i$ denote gender, $j$ denote treatment, and $k$ denote the response, so we have $I=2,J=3,K=2$.  Now I am going to assume that these are exhaustive classes.  This can be re-phrased as restricting the domain of generality to those units which could be classified into this table - and not as "something else" which isn't in the table (e.g. a fourth treatment).  This places some restrictions on the values of $\theta_{ijk}$, namely that they sum to 1:
$$\sum_{i=1}^{2}\sum_{j=1}^{3}\sum_{k=1}^{2}\theta_{ijk}=1$$
And we have a hypothesis to consider:
$$H_{0}:\text{Response does not differentiate between treatments and gender}$$
Or in mathematical terms
$$H_{0}:\theta_{i_{1}j_{1}k}=\theta_{i_{2}j_{2}k}\;\;\;\forall i_{1},j_{1},i_{2},j_{2},k$$
Now this basically means that there is only one parameter in the table $\theta$, and we have an integral to do (letting $D\equiv n_{111},\dots,n_{IJK}$ and $I$ denote the prior information):
$$p(H_{0}|D,I)=\frac{p(H_{0}|I)p(D|H_{0},I)}{p(D|I)}=\frac{p(H_{0}|I)}{p(D|I)}\int_{0}^{1}p(\theta|H_{0},I)p(D|\theta,H_{0},I)d\theta$$
$$=\frac{p(H_{0}|I)}{p(D|I)}A\int_{0}^{1}p(\theta|H_{0},I)\prod_{i=1}^{I}\prod_{j=1}^{J}\theta^{n_{ij1}}(1-\theta)^{n_{ij2}}$$
$$=\frac{p(H_{0}|I)}{p(D|I)}A\int_{0}^{1}p(\theta|H_{0},I)\theta^{n_{\bullet\bullet 1}}(1-\theta)^{n_{\bullet\bullet 2}}d\theta$$
Now nothing in the hypothesis says what the actual rate is, so $p(\theta|H_{0},I)=p(\theta|I)$ - this must depend on the prior information.  A conservative choice is the uniform one, this will adopted for all priors, and we have:
$$p(H_{0}|D,I)=\frac{p(H_{0}|I)}{p(D|I)}A \frac{\Gamma(n_{\bullet\bullet 1}+1)\Gamma(n_{\bullet\bullet 2}+1)}{\Gamma(n_{\bullet\bullet\bullet}+2)}
=\frac{p(H_{0}|I)}{p(D|I)}A \frac{\Gamma(46)\Gamma(276)}{\Gamma(322)}$$
And it looks like $A$ is relevant, but we have yet to calculate $P(D|I)$.  In order to do this, we must think about what the alternatives to $H_0$ are.  These are fairly obvious: that the response differs by treatment and not by gender; by gender and not by treatment; or by both gender and by treatment
$$H_{1T}:\theta_{ij_{1}k}=\theta_{ij_{2}k}\;\;\;\forall i,j_{1},j_{2},k$$
$$H_{1G}:\theta_{i_{1}jk}=\theta_{i_{2}jk}\;\;\;\forall i_{1},i_{2},j,k$$
$$H_{2}:\theta_{i_{1}j_{1}k}\neq\theta_{i_{2}j_{2}k}\;\;\;\forall i_{1},j_{1},i_{2},j_{2},k$$
These could be further broken down into statements about the individual cells, but this is not necessary.  As before we will set uniform priors for the unrestricted parameters, and for $H_{1T}$ we get an integral
$$\int_{\sum_{ik}\theta_{ik}=1}\prod_{i,k=1}^{2}\theta_{ik}^{n_{i\bullet k}}\prod_{i,k=1}^{2}d\theta_{ik}=\frac{\Gamma(n_{1\bullet 1}+1)\Gamma(n_{1\bullet 2}+1)\Gamma(n_{2\bullet 1}+1)\Gamma(n_{2\bullet 2}+1)}{\Gamma(n_{\bullet\bullet\bullet}+4)}$$
Now if you are like me, you will be able to see the pattern.  The probabilities of each are written below:
$$p(H_{0}|D,I)=\frac{p(H_{0}|I)}{p(D|I)}A \frac{\Gamma(n_{\bullet\bullet 1}+1)\Gamma(n_{\bullet\bullet 2}+1)}{\Gamma(n_{\bullet\bullet\bullet}+2)}$$
$$p(H_{1T}|D,I)=\frac{p(H_{1T}|I)}{p(D|I)}A \frac{\prod_{i,k}\Gamma(n_{i\bullet k}+1)}{\Gamma(n_{\bullet\bullet\bullet}+4)}$$
$$p(H_{1G}|D,I)=\frac{p(H_{1G}|I)}{p(D|I)}A \frac{\prod_{j,k}\Gamma(n_{\bullet jk}+1)}{\Gamma(n_{\bullet\bullet\bullet}+6)}$$
$$p(H_{2}|D,I)=\frac{p(H_{2}|I)}{p(D|I)}A \frac{\prod_{i,j,k}\Gamma(n_{ijk}+1)}{\Gamma(n_{\bullet\bullet\bullet}+12)}$$
Note that all of these probabilities contain the factor $\frac{A}{p(D|I)}$.  So if we were to take odds ratios they would just cancel out.  That is both $A$ and $P(D|I)$ cannot change the relative relationships between the 4 hypothesis - thus $A$ is irrelevant for answering this question as is $P(D|I)$.  It does not matter whether you had fixed designs or random ones - it only matters that the likelihood function has the form I wrote at the start.  So I will give my results in odds ratio form, with $H_0$ the denominator in the odds.  Now if we assume that all hypothesis are equally likely, then these also drop out of the odds ratios.  To go from odds ratios to probabilities is easy
$$P(H_0|D,I)=\left(\sum_{h} \frac{P(H_h|D,I)}{P(H_0|D,I)}\right)^{-1}$$
And the results are given below, which shows that you would have to be crazy to reject $H_{0}$ in favour of the alternatives (the probability has first 60 decimal digits of 9 before the first non 9 digit).  I also did a quick $\chi^{2}$ test and this gave values of $\chi^{2}=5.49$ on $5$ degrees of freedom, for a p-value of 0.36 (note that this is inflated because of some cells below 10, so the fit is much better than what $\chi^{2}$ test indicates).
$$
\begin{array}{c|c}
\text{Hypothesis} & \text{prior odds vs }H_{0} & \text{posterior odds vs }H_{0} \\ \hline
H_{0} & 1 & 1 \\
H_{1T} & 1 & 5\times 10^{-61} \\
H_{1G} & 1 & 9\times 10^{-147} \\
H_{2} & 1 & 4\times 10^{-214} \\
 \end{array}
$$
Comment: I've posted on data example. Would you like to answer specifically to this problem. Thanks


Example for $f\in L^q$ with $\log|f|^q\not\in L^1$

Question: This question is motivated by an exercise in Folland's Real Analysis:

One can prove (a) by Jensen's inequality as long as $\log|f|^q\in L^1$ and separately deal with the case when $\log|f|^q\not\in L^1$.
Here is my question:
Could anyone come up with an example of $f$ satisfying the assumption in the exercise but $\log|f|^q\not\in L^1$?
Answer: Let $X=[0,1]$ with Lebesgue measure and $f(x)=e^{-1/x}$.


Como receber os dados em JSON (REST)

Question: Olá, eu to aprendendo a programar, estou no 1 semestre de desenvolvimento e to sendo cobrado no trabalho pra aprender a fazer isso, e eu gostaria de saber se o que eu fiz ta certo ou não
<!DOCTYPE html>

 <meta charset="utf-8">
 <title>Formulário de cadastro</title>
 <link rel="stylesheet" href="css/form.css">

Formulário de cadastro

<form name="form" id="form" class="cadastro" action="" method="post" onsubmit="return validarForm();" required>

    Nome:
    <input type="text" id="nome" name="nome" placeholder="Digite seu nome completo..." required>

    Senha:
    <input type="password" id="senha" placeholder="Digite sua senha" required>

    Confirme sua senha:
    <input type="password" id="senhanovamente" placeholder="Digite sua senha novamente" required>

    CPF:
    <input type="text" id="cpf" required>

    E-mail:
    <input type="email" id="email" placeholder="jhon@emai l.com.br" required>

    CEP:
    <input type="text" id="cep" required>

    Endereço:
    <input type="text" id="endereco" required>

    Bairro:
    <input type="text" id="bairro" required>

  Complemento:
  <input type="text" id="complemento">

  Cidade:
  <input type="text" id="cidade" required>

  Estado:
  <input type="text" id="estado" required>

  Numero:
  <input type="text" id="numero" required>

  Telefone:
  <input type="text" id="telefone" placeholder=" DDD 999999999" required>

  <button type="button" name="button" id="enviar">Enviar</button>
  <button type="reset" name="button">Limpar</button>

  </form>

Agora a parte de js
$("#enviar").click(function(){

  var nome = $("#nome").val();
  var cpf = $("#cpf").val();
  var email = $("#email").val();
  var rua = $("#endereco").val();
  var complemento = $("#complemento").val();
  var bairro = $("#bairro").val();
  var cep = $("#cep").val();
  var cidade = $("#cidade").val();
  var estado = $("#estado").val();
  var telefone = $("#telefone").val();
  var numero = $("#numero").val();
  var localidade =  {rua,complemento,bairro,cep,cidade,estado,numero};
  var investidor = {nome,cpf,email,localidade,telefone};

  $.ajax({
    url: "http://api.webhookinbox.com/i/LjzRS86F/in/",
    type: "POST",
    data: {"investidor":{"nome":nome, "cpf":cpf, "email":email, "localidade":{"rua":rua,"complemento":complemento,"bairro":bairro,"cep":cep,"cidade":cidade,"estado":estado,"numero":numero},"telefone":telefone}},
    contentType: "application/json",
    success: function(data){
      console.log(data.serialize());
  },
  error: function(error){
       console.log("Something went wrong", error);
   }
  });
});

pfvr, eu to precisando muito de ajuda, e eu não tenho ideia de como resolver isso... os dados no webhook estão sendo enviados errado, era pra enviar em JSON
(desculpem pelo "leiguismo")
Comment: em `$.ajax({ ... });`, troque `contentType: "application/json"` para `dataType: "json"`
Comment: Mesmo erro......
Comment: Troque o `data: ...` por `data: JSON.stringify(...)`
Comment: nem enviou mais
Comment: que erro dá, no console?
Answer: Usando dataType: "json" você precisa ter certeza que a resposta do servidor é no formato JSON, no caso do webhookinbox por padrão responde apenas com texto OK. Da forma que utilizou acima, o post irá dar erro, porém irá retornar readyState: 4 e status: 200. Que significa sucesso, mas como o formato da resposta não está em JSON catch será um erro.
Observado as Docs do Jquery:

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none
  is specified, jQuery will try to infer it based on the MIME type of
  the response (an XML MIME type will yield XML, in 1.4 JSON will yield
  a JavaScript object, in 1.4 script will execute the script, and
  anything else will be returned as a string). The available types (and
  the result passed as the first argument to your success callback) are:

...

"json": Evaluates the response as JSON and returns a JavaScript
  object. Cross-domain "json" requests are converted to "jsonp" unless
  the request includes jsonp: false in its request options. The JSON
  data is parsed in a strict manner; any malformed JSON is rejected and
  a parse error is thrown. As of jQuery 1.9, an empty response is also
  rejected; the server should return a response of null or {} instead.
  (See json.org for more information on proper JSON formatting.)

Tente utilizar o código abaixo:
$("#enviar").click(function() {

    var nome = $("#nome").val();
    var cpf = $("#cpf").val();
    var email = $("#email").val();
    var rua = $("#endereco").val();
    var complemento = $("#complemento").val();
    var bairro = $("#bairro").val();
    var cep = $("#cep").val();
    var cidade = $("#cidade").val();
    var estado = $("#estado").val();
    var telefone = $("#telefone").val();
    var numero = $("#numero").val();
    var localidade = {
        rua,
        complemento,
        bairro,
        cep,
        cidade,
        estado,
        numero
    };
    var investidor = {
        nome,
        cpf,
        email,
        localidade,
        telefone
    };

    var dataJSON = {
        "investidor": {
            "nome": nome,
            "cpf": cpf,
            "email": email,
            "localidade": {
                "rua": rua,
                "complemento": complemento,
                "bairro": bairro,
                "cep": cep,
                "cidade": cidade,
                "estado": estado,
                "numero": numero
            },
            "telefone": telefone
        }
    };

    $.ajax({
        url: "https://api.webhookinbox.com/i/0HLzO6AL/in/",
        type: "POST",
        data: dataJSON,
        success: function(data) {
            console.log(data);
        },
        error: function(error) {
            console.log("Something went wrong", error);
        }
    });
});

Comment: então, tem algum "webhookinbox" que recebe em JSON ?
Comment: Com esse código, deu a mesma coisa que eu tinha conseguido, só que mesmo assim, não vai em JSON
Comment: Ele vai em JSON sim, a resposta do server que não é em JSON. Tente utilizar e criar um serviço com: https://www.mockable.io/
Comment: Eu consegui pelo webhook, só preciso saber como tirar o %5b e %5d, e substituilos pelos couchetes

Como receber os dados em JSON (REST)