ASP.NET C# retrieve multiple value from database and add in session

Question: How to add multiple column values from a SQL Server database and insert in session[]?
Just FirstName is working, when I add LastName, I get an error.
string constr = sql connection here.... ;

using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = @email"), cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = @email"))
    {
        cmd.Parameters.AddWithValue("@email", TextboxUsr.Text);
        cmd.Connection = con;
        cmd2.Parameters.AddWithValue("@email", TextboxUsr.Text);
        cmd2.Connection = con;

        con.Open();

        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            if (sdr.Read())
            {
                string fName = sdr["FirstName"].ToString();
                //string lName = sdr["LastName"].ToString();

                string userFullName = fName;
                Session["New"] = userFullName;
            }
        }

        //con.Close();
    }
}

Comment: `I add LastName is given error.` what error? did you notice that `cmd` does not select `LastName`? Why you have `cmd` and `cmd2`?
Answer: Step 01 : Read more about SQL and C# Basics
you need to read more in

SQL SELECT Statement
.net - What is the C# Using block and why should I use it? - Stack Overflow
c# - SqlConnection.Close() inside using statement - Stack Overflow
c# - var versus concrete type usage - Stack Overflow
$ - string interpolation - C# Reference | Microsoft Docs

Step 02 : Use Select in a correct way

change
SqlCommand
cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = @email"),
cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = @email"))

to
SqlCommand
cmd = new SqlCommand("SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = @email")

Step 03 : read the full code
var sql = @"SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = @email";
using (var con = new SqlConnection(constr))
using (var cmd = new SqlCommand(sql, con))
{
    con.Open();
    cmd.Parameters.AddWithValue("@email", TextboxUsr.Text);
    using (var sdr = cmd.ExecuteReader())
    {
        if (sdr.Read())
        {
            var fName = sdr["FirstName"].ToString();
            var lName = sdr["LastName"].ToString();
            var userFullName = fName + " " + lName;
            Session["New"] = userFullName;
        }
    }
}

Comment: do still need help ?


drupal entity property show in views

Question: I am using ECK module to create entity type. Now i want to show property of that entity to be show with views. Is there any way to do it?
Comment: In dev version the property is available in view. :)
Answer: If ECK doesn't define the entity and property types for views, you will have to do that yourself using either hook_views_data or hook_views_data_alter.

drupal entity property show in views


Join 2 tables results in query timeout

Question: I have a few tables created in AWS Athena under "TestDB". These tables are created by running an AWS Glue crawler through the S3 buckets. I am trying to create a new table by joining 2 existing tables under "TestDB". It is a simple left outer join as follows:
CREATE TABLE IF NOT EXISTS TestTab1
AS (
  SELECT *
  FROM (
    (
      SELECT col1, col2, col3, col4
      FROM "TestDB"."tab1" a
      WHERE a.partition_0 = '10-24-2021'
        AND substring(a.datetimestamp, 1, 10) = '2021-10-24'
    )
    LEFT OUTER JOIN (
      SELECT  col1, col2, col3,col4
      FROM "TestDB"."tab2" b
      WHERE b.partition_0 = '10-24-2021'
        AND substring(b.datetimestamp,1,10) = '2021-10-24'
    )
    ON (a.col1 = b.col1)
  )
)

The query scans around 5GB worth of data but times out after ~30 mins since that is the timeout limit. Other than requesting an increase in timeout limit, is there any other way to create a join of 2 tables on AWS?
Comment: Maybe using AWS Lambda? https://aws.amazon.com/pt/blogs/big-data/automating-bucketing-of-streaming-data-using-amazon-athena-and-aws-lambda/
Answer: It's very hard to say from the information you provide, but it's probably down to the result becoming very big or an intermediate result becoming big enough for the executors to run out of memory and having to spill to disk.
Does running just the query work? You can also try to run EXPLAIN SELECT … to get the query plan and see if that tells you anything.

Your query is unnecessarily complex with multiple nested SELECT statements. I think Athena's query planner will be smart enough to rewrite it to something like the following, which is easier to read and understand:
CREATE TABLE IF NOT EXISTS TestTab1 AS
SELECT col1, col2, col3, col4
FROM "TestDB"."tab1" a LEFT JOIN "TestDB"."tab2" b USING (col1)
WHERE a.partition_0 = '10-24-2021'
  AND b.partition_0 = '10-24-2021'
  AND substring(a.datetimestamp, 1, 10) = '2021-10-24'
  AND substring(b.datetimestamp, 1, 10) = '2021-10-24'

Join 2 tables results in query timeout


Is it possible to validate an object field only if it is not null?

Question: There are two existing variants of this question:

Validate only if the field is not Null : A solution to a conditionally handling a String field
Hibernate validation - only validate if object is not null : The only answer demonstrates the behavior and hints at how you could handle it when triggering the validation manually.

My question adds the qualifier of how can I do this when using @Valid on an object which may be null.
The use case here is that we have two fields where one or the other need to be not null (Custom validator on the class that contains the fields). When one is not null, I need it to be valid. Do I then need to fully and manually validate that object within my custom validator, adding more responsibility to it than it was intended for?
Using only annotations in this case causes a NullPointerException to be thrown, which breaks it out of validation before it could be handled. Is there not currently a way to do this?
Comment: `@Valid` references are only followed when they are not null. Can you show your classes and describe where exactly the NPE is raised (stacktrace)?
Comment: I'd say that this a complex enough use case to require you to use a custom validator. Write your logic inside a validator, give it an annotation and do what you need to do.
Comment: @Gunnar you are indeed correct. I did a simple test case and it worked as you said. It is now working in the more complex use case as well. Go ahead and write an answer so I can mark this mystery as solved.
Answer: @Valid references are only followed when they are not null, so something else must be causing your NPE.
Comment: Is there a reference somewhere where this is explicitly stated?
Answer: @Valid references does not seem to be followed only if they are not null.
If I provide a custom validation annotation without checking for null, It throws a NPE. You need to check for null value yourself inside the validator.
For example:
    public class EmailListValidator implements ConstraintValidator<EmailListConstraint, String> {

    @Override
    public void initialize(final EmailListConstraint emailListConstraint) {
    }

    @Override
    public boolean isValid(final String emailList, final ConstraintValidatorContext cxt) {
        if (emailList != null) {
           // Validation logic here
        }
        return true;
    }
}

Here is a link from baeldung website on how to implement a custom validation annotation :
https://www.baeldung.com/spring-mvc-custom-validator


How to draw a DFA for (a|ba)(a|ba)*

Question: I met a question concerning draw a DFA for $\left(a\vert ba\right)\left(a\vert ba\right)^\ast$.
I firstly tried to expand the regular expression to a $\varepsilon$-NFA, then plan to transform it to a DFA. However, I feel there is something wrong when I expand $\left(ba\right)^\ast$. Because when I use the closure method to convert my $\varepsilon$-NFA to DFA, some states could not accept b, so even I draw the 'DFA', it may be not the correct DFA.
So is it a normal situation under this $\left(ba\right)^\ast$ condition? Or it is because where I got wrong? Please tell me if you have any thoughts, thank you!
The following is what I have tried for your kind reference.
Comment: Hi, as I said in the same question that you posted a while ago, all you need to do is to add a "reject" state to $q_1$ that rejects any strings with $bb$ in them ($q_1$, reading $b$, goes to $q_2$ which is non-accepting, and q_2, reading anything, stays in $q_2$). https://math.stackexchange.com/questions/3324704/describe-the-language-accepted-by-this-nfa-and-convert-it-to-dfa/3324710#3324710
Answer: Here is a solution. The double circled state is the only accept state. The start state is the one with a nondescript arrow going into it.

As you can see, once two $b$'s follow each other directly, we go to the lower right state, from which no escape is possible. Any other string that is nonempty and ends with an $a$ gets accepted.

How to draw a DFA for (a|ba)(a|ba)*


Liferay 7 MVC Resource Command: react with JS on return value

Question: I have a Liferay 7.3 MVC Resource Command which is something like this:
public boolean serveResource(
        ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
 try {
   // my code goes here

   return false;
 }catch(Exception e){

  return true;
 }
}

I call this Command from JavaScript with this:
var req = new XMLHttpRequest();
req.open("POST", '${upload}', true)

req.onload = function (event) {
    console.log("success");
}

req.onerror = function (event) {
    console.log("error");
}

// do request
req.send(form_data);

The problem now is that always the "onload" function is called also when the MVC ResourceCommands sends back true in the catch clause.
So my question: How can I know in JavaScript when my ResourceCommand was succesfull or not?
Answer: Javadoc isn't all that clear about the purpose of the boolean return type. Especially as GenericPortlet.serveResource has a void return type.
However, thinking about what can happen within your // my code goes here block makes it clearer what to expect: The client can't rely on the boolean result to be signaled back: You could (and typically do) access the ResourceResponse's output stream, send all the data you like, and it can long be at the client when you finally return true; from this code. That means that the framework has no chance to intercept or redirect any communication that has been made already.
Also, a simple true/false return value wound not give you any control over what kind of error is signaled to the client. Is it 401? 404? 418? 500? Or would it return 200 with a HTML error message? A JSON encoded error?
If you rely on the result of this operation: Keep control over it. I can't tell you what the boolean return value is for, but it ain't for the benefit of the browser. You decide if you use a HTTP status code for your error signalling, or a specific payload. And once you implement that, you know what to expect on the JS side.
Remember that you'll have to decide for either "ok case" or "error case" before you ever send any data back to the client. If you started delivering the "ok" result to the client and suddenly run into an Exception, you might have delivered half of it to the client, but can't rely on changing horses, e.g. you can't start over, sending an error message as the response might already be (half) on the way to the browser.
Comment: okay thanks, then I have to change my code logic because I rely on the true and false return value


O tipo de um sistema operacional pode ser microkernel + monolítico?

Question: Baseando-se no que se diz que um sistema monolítico reúne todas os procedures e linka em um grande binário, onde procedures podem chamar outros procedures.
O microkernel tem como objetivo minimizar o "serviço" feito diretamente do kernel(terceirizando), seja utilizando uma hierarquia de processos com cada um tendo o seu nível de permissão.
E aí que vem a bala:

A desvantagem do monolítico é o problema resolvido pelo uso de microkernels.
Desempenho do monolítico é maior.
O uso de microkernels me garante maior segurança, como que um driver defeituoso não será capaz de derrubar o meu sistema, pois roda em processo separado e não diretamente no kernel.

Ou seja, é possível uma união destes dois?
Comment: Para quem acha que *off-topic* pode abrir uma discussão no meta sobre o assunto que é um pouco inusitado. Antes de responder consultei o SOen e lá o assunto é bem aceito. Não sei porque aqui não deveria ser então.
Answer: Sim, é possível. Claro que os detalhes do que dá para conciliar depende da arquitetura específica. Tem um verbete sobre isto na Wikipedia. Como bem demonstra o artigo há controvérsias se realmente é híbrido mesmo.
Na minha concepção todos os sistemas mais conhecidos são híbridos. Na maioria da vezes soluções híbridas são melhores. Note que "maioria das vezes" significa que as decisões devem ser híbridas também, não podem ser dogmáticas (dogmatismo só serve para experimentos, e olhe lá). E uma das coisas que ajudam confirmar isto é que o kernel do Linux hoje não é mais um só binário (loadable modules). Não estudo especificamente o assunto então alguém poderá dizer que seria errado classificar o Linux como híbrido, eu respeitaria isso. Só não dá para dizer que algo é ou não é por puro marketing, afinal todos os envolvidos com seus produtos vão querer puxar para o lado que mais lhe interessa.
Outro ponto importante é que a terceira premissa já foi desmentida na prática e há controvérsias quanto a segunda, pelo menos em teoria é possível ter um microkernel muito rápido, ou pelo menos no mesmo nível que um monolítico.
Microkernel na Wikipedia.
Coloquei no GitHub para referência futura.


MS Excel - Pivot Table - Accessing the source data when it isn't a tab in the spreadsheet

Question: I have a spreadsheet that is emailed to me by an outside vender.  It contains a bunch of pivot tables.  I really couldn't care less about the pivot tables, I just want the underlying data.  The data comes from a sql server that I don't have access to, but the data is stored within the spreadsheet.  Is there anyway that I can access the data, (I think it's the PivotCache) directly without drilling into one of the pivot tables?
I'd love some sort of ODBC/ADO.Net command that I can use from SSIS.  But am open to just about anything that doens't require me to open and save the workbook.
I'd also like to avoid macros if at all possible.
Answer: Here's the answer.  Or at least what I did to resolve my problem.
There is really no way to accss the underlying PivotCache data except via pivot tables.  So direct accss was out.  I ended up using a script task with excel ole to dynamically create a pivot table with the data I needed at run time.  Once the script task is done, I then use the new pivot table as my dataflow source.  Excel can be a little tricky to automate, but it's worth it.


EF - Default value for new column with automatic migration

Question: I use EF code first and automatic migrations. I want to add a new column to my model - a boolean column to present "active" (true) or "inactive" (false). How can I add this column and set a default value ("true") for the rows that already in the DB - with automatic migrations?
Answer: Tamar, you need set default value, see next sample:
<code>namespace MigrationsDemo.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class AddPostClass : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Posts",
                c => new
                    {
                        PostId = c.Int(nullable: false, identity: true),
                        Title = c.String(maxLength: 200),
                        Content = c.String(),
                        BlogId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.PostId)
                .ForeignKey("dbo.Blogs", t => t.BlogId, cascadeDelete: true)
                .Index(t => t.BlogId)
                .Index(p => p.Title, unique: true);

            AddColumn("dbo.Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3));
        }

        public override void Down()
        {
            DropIndex("dbo.Posts", new[] { "Title" });
            DropIndex("dbo.Posts", new[] { "BlogId" });
            DropForeignKey("dbo.Posts", "BlogId", "dbo.Blogs");
            DropColumn("dbo.Blogs", "Rating");
            DropTable("dbo.Posts");
        }
    }
}
</code>
Comment: EF 7 will support default values from the model http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2929682-support-database-default-values-in-code-first


Shor's Code-Knill Laflamme Theorem.

Question: I'm new to Quantum Error Correction, and I have a question on Shor's Code.
If we have a protected subspace, $V \subset \mathbf{C}^2\otimes \cdots \otimes \mathbf{C}^2$
$V=\operatorname{span}\{|0_{l}\rangle, |1_{L}\rangle.$ We also consider Pauli basis of $\mathbf{C}^2\otimes \cdots \otimes \mathbf{C}^2$ of 9 copies, and constructed as follows: Take the basis of $M_2$ consisting of:
\begin{eqnarray} \nonumber
X=\begin{pmatrix}
0 & 1\\
1 & 0
\end{pmatrix},
Y= \begin{pmatrix}
0 & i \\
-i & 0
\end{pmatrix}, Z=\begin{pmatrix}
1 & 0\\
0 & -1
\end{pmatrix} & \text{and} &  1_2.
\end{eqnarray}
We list the 1-Paulis as $U_1,\cdots ,U_{28}.$
Define the error map as $\mathscr{E}:M_{2^9}\rightarrow M_{2^9}$ by $\mathscr{E}(X)=\frac{1}{28}\sum_{i=1}^{28}U_iXU_i^*$. $\mathscr{E}$ is completely positive and trace preserving. How do we say that it satisfies the Knill Laflamme Theorem and thus ensure the existence of a recovery operator?
I would really appreciate the help! Thank you!
Comment: ***[Cross-posted on quantumcomputing.SE](https://quantumcomputing.stackexchange.com/q/8517/55)***
Comment: @luftbahnfahrer  Hi, yes I now understand that we have to show $\langle 0_L|U_iU_j|1_L\rangle=0$. I'm a little confused on how to formulate $U_i$.
Answer: It may help to define the following operators for $k\in\{1,\dots,9\}$
\begin{align*}
 X_k &= I\otimes \cdots \otimes I \otimes X\otimes I \otimes \cdots \otimes I\\
 Y_k &= I\otimes \cdots \otimes I \otimes Y\otimes I \otimes \cdots \otimes I\\
 Z_k &= \underbrace{I\otimes \cdots \otimes I}_{k-1\text{ times}} \otimes Z\otimes \underbrace{I \otimes \cdots \otimes I}_{9-k\text{ times}}.
\end{align*}
We may now explicitly define the operators $U_1,\dots, U_{27}$ as
$$
U_{9a+k} = \left\{\begin{array}{ll}
X_{k}& \text{ }a =0\\
Y_{k}& \text{ }a =1\\
Z_{k}& \text{ }a =2\\
\end{array}\right.
$$
for $a\in\{0,1,2\}$ and $k\in\{1,2,\dots,9\}$ and $U_{28} = I\otimes I \otimes I\otimes I\otimes I \otimes I\otimes I\otimes I \otimes I$.

To show that these operators satisfy the conditions of the Knill-Laflamme Theorem, you must show that
$$
\langle 0_L|U_i^*U_j|1_L\rangle=0
$$
and
$$
\langle 0_L|U_i^*U_j|0_L\rangle=\langle 1_L|U_i^*U_j|1_L\rangle
$$
for all $i,j\in\{1,\dots,28\}$.

We can cluster the nine qubits into three groups of three by writing the logical states as:
$$
|0_L\rangle=\left(\frac{|000\rangle + |111\rangle}{\sqrt{2}}\right)^{\otimes 3}\qquad\text{and}\qquad
|1_L\rangle=\left(\frac{|000\rangle - |111\rangle}{\sqrt{2}}\right)^{\otimes 3}.
$$
We see that each of the operators $U_1,\dots,U_{28}$ acts on at most one of the clusters of three qubits. It should be obvious that $\langle 0_L|U_i^*U_j|1_L\rangle = 0$ for all $i,j\in\{1,\dots,28\}$. (Can you see why?) It remains to check that $\langle 0_L|U_i^*U_j|0_L\rangle=\langle 1_L|U_i^*U_j|1_L\rangle$.
To see how each of the above operators acts on $|0_L\rangle $ and $|1_L\rangle$, it will help to see how they act on each cluster of three qubits.  It may easily be verified that each of the following is orthogonal to each other and orthogonal to $\lvert 000\rangle + \lvert 111\rangle$:
\begin{align*}
X\otimes I\otimes I \left(\lvert 000\rangle + \lvert 111\rangle\right) &= \lvert 100\rangle + \lvert 011\rangle\\
I\otimes X\otimes I \left(\lvert 000\rangle + \lvert 111\rangle\right) &= \lvert 010\rangle + \lvert 101\rangle\\
I\otimes I\otimes X \left(\lvert 000\rangle + \lvert 111\rangle\right) &= \lvert 001\rangle + \lvert 110\rangle\\
Y\otimes I\otimes I \left(\lvert 000\rangle + \lvert 111\rangle\right) &= i(\lvert 100\rangle -\lvert 011\rangle)\\
I\otimes Y\otimes I \left(\lvert 000\rangle + \lvert 111\rangle\right) &= i(\lvert 010\rangle - \lvert 101\rangle)\\
I\otimes I\otimes Y \left(\lvert 000\rangle + \lvert 111\rangle\right) &= i(\lvert 001\rangle - \lvert 110\rangle)
\end{align*}
From this, it is clear that the vectors
$$
\lvert 0_L\rangle,X_1\lvert 0_L\rangle, \cdots X_9\lvert 0_L,\rangle,Y_1\lvert 0_L\rangle, \cdots Y_9\lvert 0_L\rangle
$$
are pairwise orthogonal. It follows that
$$
\langle 0_L|X_kY_l|0_L\rangle = \langle 0_L|X_k|0_L\rangle= \langle 0_L|Y_l|0_L\rangle=0
$$
for all $k,l\in\{1,\dots 9\}$.
Analogously, it may easily be verified that each of the following is orthogonal to each other and orthogonal to $\lvert 000\rangle - \lvert 111\rangle$:
\begin{align*}
X\otimes I\otimes I \left(\lvert 000\rangle - \lvert 111\rangle\right) &= \lvert 100\rangle - \lvert 011\rangle\\
I\otimes X\otimes I \left(\lvert 000\rangle - \lvert 111\rangle\right) &= \lvert 010\rangle - \lvert 101\rangle\\
I\otimes I\otimes X \left(\lvert 000\rangle - \lvert 111\rangle\right) &= \lvert 001\rangle - \lvert 110\rangle\\
Y\otimes I\otimes I \left(\lvert 000\rangle - \lvert 111\rangle\right) &= i(\lvert 100\rangle +\lvert 011\rangle)\\
I\otimes Y\otimes I \left(\lvert 000\rangle - \lvert 111\rangle\right) &= i(\lvert 010\rangle + \lvert 101\rangle)\\
I\otimes I\otimes Y \left(\lvert 000\rangle - \lvert 111\rangle\right) &= i(\lvert 001\rangle + \lvert 110\rangle)
\end{align*}
From this, it is clear that the vectors
$$
\lvert 1_L\rangle,X_1\lvert 1_L\rangle, \cdots X_9\lvert 1_L,\rangle,Y_1\lvert 1_L\rangle, \cdots Y_9\lvert 1_L\rangle
$$
are pairwise orthogonal.  It follows that
$$
\langle 1_L|X_kY_l|1_L\rangle = \langle 1_L|X_k|1_L\rangle= \langle 1_L|Y_l|1_L\rangle=0
$$
for all $k,l\in\{1,\dots 9\}$.
It now follows that
$$
\langle 0_L|U_i^*U_j|0_L\rangle=\langle 1_L|U_i^*U_j|1_L\rangle =0
$$
in the case when $i,j\in\{1,2,\dots,18,28\}$. It therefore remains to check the case when at least one of $i$ or $j$ is in $\{19,20,\dots,27\}$ (i.e. when either $U_i=Z_k$ or $U_j = Z_l$ for some $k\in\{1,\dots,9\}$ or $l\in\{1,\dots,9\}$).
Note that
$$
Z\otimes I \otimes I(\lvert 000\rangle+\lvert 111\rangle) = I\otimes Z \otimes I(\lvert 000\rangle+\lvert 111\rangle) = I\otimes I \otimes Z(\lvert 000\rangle+\lvert 111\rangle) = \lvert 000\rangle-\lvert 111\rangle
$$
and that
$$
Z\otimes I \otimes I(\lvert 000\rangle-\lvert 111\rangle) = I\otimes Z \otimes I(\lvert 000\rangle-\lvert 111\rangle) = I\otimes I \otimes Z(\lvert 000\rangle-\lvert 111\rangle) = \lvert 000\rangle+\lvert 111\rangle.
$$
Note that if $U_i$ and $U_j$ do not act on the same cluster of 3 qubits, then it must be the case that
$$
\langle 0_L|U_i^*U_j|0_L\rangle=\langle 1_L|U_i^*U_j|1_L\rangle=0.
$$
It remains to check the cases when $U_i$ and $U_j$ do act on the same cluster of 3 qubits.

I'll leave the rest to you.
Comment: Since, $U_i $'s are normalised, that would imply that $\sum_{i=1}^{28}U_i^*U_i=I$, would this be the relation that helps prove $\langle0_L|U_i^*U_j|1_l \rangle$?
Comment: That relation will not help you here. It is trivial anyway, since $U_i^*U_i=I$ for each $i$.
Comment: I see, so my current understanding for the condition to be true $i \neq j$ and when $i=j, \langle 0_L|U_i^*U_j | 1_L \rangle=\alpha_{ij}\delta$ right?
Comment: No. You must show that $\langle 0_L|U_i^*U_j|1_L\rangle=0
$ and $\langle 0_L|U_i^*U_j|0_L\rangle=\langle 1_L|U_i^*U_j|1_L\rangle$ for all $i,j\in\{1,\dots,28\}$.
Comment: If $i=j$, then $U_i^*U_i=I$ and it trivially holds that $
\langle 0_L|I|1_L\rangle =0$ and $
\langle 0_L|I|0_L\rangle=1=
\langle 1_L|I|1_L\rangle$.

Shor's Code-Knill Laflamme Theorem.


Series for $(1-z)^{-\frac{1}{2}}$ and application?

Question: How could I obtain
$$\sum_{k=0}^{\infty} {4k \choose 2k} \frac{z^{2k}}{2^{4k}}$$
from
$$\sum_{k=0}^{\infty} {2k \choose k} \frac{z^k}{2^{2k}}$$
which is $(1-z)^{-\frac{1}{2}}$. I can't manage to take out only the even terms of the sum... Can you help me please?
Answer: Any time you have a series $f(z)=\sum_{k=0}^\infty a_kz^k$, you get $$\sum_{k=0}^\infty a_{2k}z^{2k} = \frac{f(z)+f(-z)}{2}$$
and similarly:
$$\sum_{k=0}^\infty a_{2k+1}z^{2k+1} = \frac{f(z)-f(-z)}{2}$$


Disable registration functionality for sub-domain in Drupal 7

Question: I am using Domain access module for my multi-site creation and using common database for both the site:
1. example1.com (Default domain)
2. example2.com (sub domain)

I want default registration functionality for default domain (example1.com), but don't want this functionality on sub domain (example2.com).
If I configure this registration functionality only for Administrators from admin section (Home » Administration » Configuration » People) from default domain (example1.com) look like below screenshot:

Then this will be applicable for both example1.com and example2.com, as I am using common database and common tables for both the sites.
So can anyone please guide me how can I disable the Registration functionality for sub domain (example2.com) and use this same for default domain (example1.com).
Thanks in advance.
Answer: According to this answer on SO (to a 'similar' question posted 'a bit before' this question ...), this is a possible answer to this question (= quote from that question):
= = = Start = = =
As far as I know you can have different variables per domain (Because the Registration option is a variable) using the latest Domain Access module (currently 7.x-3.11 from 2014-Mar-02). It can be done with a submodule named Domain Settings. Enable it if haven't done yet.
If for any reason does not work for you I would suggest to use the Domain Variable module to handle variables for each domain.
= = = Stop = = =


Why $\sup_{0\leq |x|\leq \varepsilon_k}|T\rho(x)|<\infty $?

Question: Let $T:\mathbb R^n\to \mathbb R^n$ linear, $\rho:\mathbb R^n\to \mathbb R^n$ a function s.t. $\lim_{x\to 0}\rho(x)=0$ and $(\varepsilon_k)$ a sequence that converge to $0$.
1) Is it obvious that $$\sup_{0\leq |x|\leq \varepsilon_k}|T\rho(x)|<\infty \ \ ?$$
2) Does $$\lim_{k\to \infty }\sup_{0\leq |x|\leq \varepsilon_k}|T\rho(x)|=0$$

For 1), I know that $T$ is continuous. So, I would say it's true if $\rho$ is continuous, but there is no reason for this to be true, no ?
2) Same, if $\rho$ is continuous, then yes, but I think it's wrong a priori, but I can't find a counter example...
Answer: If $\rho$ is just a function, (1) can't be true. Just take $n=1$ and $T(x)=x$. The claim reduces to $|\rho(x)|$ being bounded on the interval $[-\epsilon_k,\epsilon_k]$. Without further conditions on $\rho$ in connection to the sequence $\epsilon_k$, there is no reason for that to be true (however, it is true for $k$ large enough as shown below).
(2) however is true. Since $\rho(x) \rightarrow 0$, for any $\epsilon>0$ there exists $\delta>0$ such that $\|x\|<\delta \Rightarrow \|\rho(x)\|<\epsilon$. Choose $N$ large enough such that $k>N \Rightarrow \epsilon_k<\delta$. Then $k>N \Rightarrow \|\rho(x)\|<\epsilon$ for all $x$ with $\|x\|<\epsilon_k$, which implies
$$k>N \Rightarrow \sup_{0\leq \|x\|<\epsilon_k} \|T(\rho(x))\| \leq \|T\| \sup_{ 0\leq \|x\|<\epsilon_k} \|\rho(x)\|<\|T\| \epsilon.$$
This implies (2).
Comment: For (1), in fact $\rho(x)$ is bounded on all $\mathbb R$ (I forget this hypothesis). For (2) you used the norm of $T$. But if $T$ was a continuous function (and not linear) would it be also true ?
Comment: You need $T(0)=0$ and continuity of T only at 0.
Answer: I guess you didn't search to long ;-)
1) Since $\rho(x)\to 0$, it's bounded in a neighborhood of $0$. i.e. $|\rho(x)|\leq C$ if $|x|\leq \delta$ for a certain $\delta$. Since $T$ is continuous, $|T\rho(x)|\leq \|T\||\rho(x)|\leq C\|T\|<\infty .$ Therefore the $\sup |T\rho(x)|<\infty $.
2) Of course it work ! Use continuity of $T$.
Comment: For 2), I see that $\sup_{0\leq |x|\leq \varepsilon_k}|T\rho(x)|\leq \|T\|\sup_{0\leq |x|\leq \varepsilon_k}|\rho(x)|$, but why $\sup_{0\leq |x|\leq \varepsilon_k}|\rho(x)|\to 0$ when $k\to \infty $ ?
Comment: The first one is only true, if $k$ is big enough. You may have some $x$ with $|x|> \delta$. For example $\rho(x)=0$ for $x\in[-1,1]$ and $\rho(x)=\frac{1}{x-1}$ for $x\in\mathbb{R}\setminus[-1,1]$. Also choose $T(x)=x$. Hence if $\varepsilon_k$ is still larger than $1$, this $\sup$ will become infinite.


tf.custom_gradient with multiple inputs

Question: tf.custom_gradient accepts only one Tensor x, what if this op needs more than one inputs?
For example, to define the gradient of Softmax which needs input x and label?
Update
Thanks for the suggestion from @AllenLavoie, I use a Python list as input.
def self_define_op_multiple_inputs():
    @tf.custom_gradient
    def loss_func(input_):
        x = input_[0]
        label = input_[2]

        def grad(dy):
            return [dy, dy]

        return x - label, grad

    x = tf.range(10, dtype=tf.float32)
    y = tf.range(10, dtype=tf.int32)

    loss = loss_func([x, y])

if __name__ == '__main__':
    self_define_op_multiple_inputs()

It seems that it will convert the Python list to a Tensor. The snippet above will raise a TypeError:

TypeError: Cannot convert a list containing a tensor of dtype <dtype: 'int32'> to <dtype: 'float32'> (Tensor is: <tf.Tensor 'range_1:0' shape=(10,) dtype=int32>)

How to fix it?
Comment: @AllenLavoie I created an issue on [github](https://github.com/tensorflow/tensorflow/issues/21756)
Comment: The documentation says `x` and `y` can both either be Tensors or sequences of Tensors. Did this not work for you?
Comment: @AllenLavoie Actually this is exactly what confused me. I don't understand what's *sequences* of Tensors, does it mean a Python `list` of Tensor?
Comment: My interpretation is Python `list` (or `tuple`, etc.). So `len(x)` is the number of inputs to the operation, `len(y)` is the number of outputs.  Then the gradient function takes `len(y)` `Tensor` argument and returns `len(x)` `Tensor`s.
Comment: @AllenLavoie I tried to use `list` but it seems like a `list` will be converted as a `Tensor`, which will cause an error if there are multiple inputs with different type and matched shape. The question has been updated.
Comment: I see, so the documentation is off. Rather than taking a list of `N` arguments, the function takes `N` positional arguments. `def loss_func(x, label):` works for me (but I didn't test very deeply). Could you file a bug?
Answer: I ran into a similar problem yesterday and found this post, and I believe I know what you are running into. Problem is that while using @tf.custom_gradient, the function that it decorates can have multiple inputs (instead of a list of tensors). Look at the following code(note that it's just a test code with no actual meaning):
@tf.custom_gradient
def loop1(x,a):
    def grad(dy):
        return dy*3,dy*2
    n = tf.multiply(x,a)
    return n,grad

By using two inputs x and a, you have to return two gradients respectively in the grad function. dy*3 corresponds to the gradient of x and dy*2 corresponds to the gradient of a.
I think in this function the documents make people very confusing, but you can still use multiple inputs, just make sure that you also have the same number of gradients, or else you will run into errors.
Comment: Can we return `None` as gradients for unused terms ?
Answer: I believe you need something like this a tf Graph input:+
n_input is the input number
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None])

Does this answer your question ?
Comment: Thanks for your help. But it seems that you didn't understand what I am talking about. `tf.custom_gradient` is not a computational graph. You can read docs for more details.

tf.custom_gradient with multiple inputs


How are the equational reasoning operators used in practice?

Question: The Agda Standard Library exports some operators that allow you to write proofs in a manner similar to what you would do on paper, or how it is taught in the Haskell community. While you can write "conventional" Agda proofs in a somewhat systematic manner by refining a Goal using with abstractions, rewrites or helper lemmas as needed, it isn't really clear to me how a proof using the equality reasoning primitives "comes to be".
That is, while you can find examples about what these proofs look like when they are finished and type-check here and there, these already worked examples don't show you how they are developed in a systematic step-by-step (maybe hole-driven) manner.
How is it done in practice? Do people "refactor" an already existing proof? Do you try to "burn the candle from both sides" by starting with the left-hand and right-hand sides of the initial Goal and a hole in the middle?
Furthermore, the Agda documentation states that if the equality reasoning primitives are in scope, "then Auto will do equality reasoning using these constructs". What does that mean?
I would appreciate it if someone could point me in the right direction, or even post an example of how they develop these kinds of proofs step-by-step, what questions they ask themselves as they go through it, where they put the holes and so on. Thanks!
Answer: I think it would be more helpful for you to look at the definitions for equational reasoning for Identity here Equational Reasoning. The main point is that it is just a nicer way to apply transitivity chains and allowing the user to see the actual expression in code, rather than the proof evidence which is not that easy to read.
The way I go about building a proof using equational reasoning for any setoid is this. With the example of natural numbers
open import Relation.Binary.PropositionalEquality
open ≡-Reasoning

data ℕ : Set where
  zero : ℕ
  succ : ℕ → ℕ

_+_ : ℕ → ℕ → ℕ
m + zero   = m
m + succ n = succ (m + n)

Let's take commutativity as an example.
This is how I start with the goals.
comm+ : ∀ m n → m + n ≡ n + m
comm+ m zero     = {!!}
comm+ m (succ n) =
  begin
    succ (m + n)
  ≡⟨ {!!} ⟩
    succ n + m
  ∎

Now I see the original expression and goal and my goal proof is between the brackets.
I work only on the expression leaving the proof objects untouched and add
what I think should work.
comm+ : ∀ m n → m + n ≡ n + m
comm+ m zero     = {!!}
comm+ m (succ n) =
  begin
    succ (m + n)
  ≡⟨ {!!} ⟩
    succ (n + m)
  ≡⟨ {!!}⟩
    succ n + m
  ∎

Once I think I have a proof, I work on the proof objects that justify my steps.
Regarding the auto-tactic, you should not bother with that in my opinion. It's not being worked on for a while.
Comment: I mean it's an application of the transitivity rule for transitive relations.
Instead of writing `trans p (trans q s)` , you can use the reasoning package to write `_ ≡⟨ p ⟩ _ ≡⟨ q ⟩ _ ≡⟨ s ⟩`
Comment: Thanks for answering my question(s) with an example! Question: Did you mean "reflexivity chains" in the sense of explicit normalization steps, or (if not) could you expand on what you mean by "transitivity chains"?


Returning a reference to local variable and its behaviour

Question: I'm just working with the basics of C++ and tried the below lines of code,
int& func()
{
    int localnum = 10;
    return localnum;
}

int main()
{
    int &i = func();
    cout<<"value : "<<i<<endl;
    cout<<"value : "<<i<<endl;
    return 0;
}

Here, I'm returning a local variable as reference(which I shouldn't do actually, but I did it just to learn the behaviour).
I think even though the func() execution is completed the value of localnum will be still held and not destroyed until any process uses the memory space (but sets some bits/flags so that remaining process treats this memory chunk as free and can use it)  - Correct me if I'm wrong
Just to check this I'm printing the value of i. In my case, this is the output

value : 10
value : 264952704

This is the same scenario even if I'm using a pointer and returning an address in place of reference.
My question is, I'm not running any process in between those prints, but still the value is getting changed. So that means any other process in my system is using the memory area of localnum in between those prints?
Comment: It is undefined behavior, so the behavior can be anything. There's not too much point in trying to reason about it - basically you're returning a reference to a memory location that can be reused (since the lifetime of the object is finished). How it might be reused is arbitrary. The local variable is typically allocated on the stack and the compiler uses the stack for a variety of things - like calling the output functions.
Comment: Are you aware that `<<` is an operator which implies some execution of library functions? You did use some `# includes' in your MCVE, didn't you? Even if you did not provide the MCVE... So there is no need for "a different process".
Answer: If you reason purely about the language, this is simply undefined behavior, so theoretically the result could be anything.
Following your reasoning about the implementation, there's no need for another process to overwrite a local variable, usually allocated in the stack. Among other things, any call to another function will do. In this case, your first call to the operator << of the cout object involves a function invocation, which re-used the stack area that was used by func(), resulting in overwriting the memory location where the variable localnum was temporarily created.
But again, the observed result is not consistent; it depends much on the implementation, compiler, compiler options etc..
Answer: The use of << implies quite a lot of activity, without needing a different process. Check the #includes you needed in the example program you are quoting from. By the way giving the whole code of that would be called a "MCVE". https://stackoverflow.com/help/mcve
Actually the only activity able to change "your" stack is the same process, even the same thread within that process. Because each process has its own stack.
The memory you are talking about is the stack. The administration data to that is not more than a pointer to the first useable part of memory; and maybe an implicit knowledge how big the stack is in total. I.e. there are no separate flags for each byte on the stack, that would add a serious amount of memory needed for the stack.
For the fact that you get the "10" only once, for the same code being executed I offer the following (compiler depending but probably common) explanation:

start the first line with the <<
read the value of i
put the value somewhere it will not be overwritten
(possibly a CPU register, or somewhere safe on the stack,
i.e. a place which is reserved for tha purpose in this activity)
use the stack to do the streaming to output
doing so overwrites the variable
but the value is already somewhere else and safe
output it successfully
do all that again for the second line,
but this time the value is the overwritten one

Just to repeat what you yourself and some comments said:
Using stack after leaving a function is evil.
Answer: It's undefined behavior, which means anything is possible. What really happens, depends on implementation of compiler.
Answer:
I think even though the func() execution is completed the value of localnum will be still held and not destroyed until any process uses the memory space (but sets some bits/flags so that remaining process treats this memory chunk as free and can use it) - Correct me if I'm wrong

since this is an UB, you are not entirely correct. Some compiler might set a bit/flag and some other compiler might set the value to zero... since UB gives each compiler the freedom to do what it likes your explanation is just one of many (although I think it's the most common one)

My question is, I'm not running any process in between those prints, but still the value is getting changed. So that means any other process in my system is using the memory area of localnum in between those prints?

If your process isn't doing it, and the value is changed, then, yes, someone else is changing the value. Note that even though you are not changing the value in that address directly, your code might be implemented in a way that does change it behind your back (the << operator for example, as Yunnosch said)

Here, I'm returning a local variable as reference(which I shouldn't do actually, but I did it just to learn the behaviour).

I wouldn't recommend on learning a behaviour from a UB case. It varries from machine to machine.
Answer: since int localnum is scoped to func function you are actually returning a reference to something that is no longer available after the function returns


Are these proofs of two Halting Problems rigorous?

Question: I apologize if this question is more suited for CS Stack Exchange, but since my question is primarily about rigor rather than the Halting Problem in particular, I felt like this is a place to post it.
My reference for the first proof are from these excellent slides (p. 32).
Firstly, two definitions. For any program P, code(P) is P in string format. For any program P, H(code(P), a) returns true if and only if the instance P(a) halts. Now, consider the following program in C syntax:
void D(string x) {
    if (H(x, x) == true) {
        while (true);
    }
    else {
        return;
    }
}

Now the proof of the impossibility of H existing follows immediately. D(code(D)) either halts or it does not.

It halts, which means that H(code(D), code(D)) returns true. But by the definition of D, this means that D(code(D)) does not halt (we fall into the first branch which leads into an infinite loop).
It does not halt, which means that H(code(D), code(D)) returns false. But by the definition of D, this means that D(code(D)) halts (we fall into the second branch which leads immediately to a return statement).

This seems pretty formal and satisfactory to me, but I have doubts since the more mathematical exposition of the Halting Problem which I read was much more complicated and incomprehensible to me. Am I missing something?
If we consider programs with $2$ or more parameters, the argument is almost exactly the same. More interesting is the case of a halting function which decides whether a program with zero parameters halts.
We can consider this program:
void D() {
    if (H(x) == true) {
       while (true);
    }
    else {
        return;
    }
}

and try substituting code(D) for the free variable x. But here the problem arises. If we do that, we have changed D itself, which means that it isn't code(D) we are substituting into D in the first place! Let me know if the following fix succeeds:
We consider two programs:
void A() {
    if (H(code(B)) == true) {
       while (true);
    }
    else {
        return;
    }
}

void B() {
    A();
}

A() either halts or it does not.

It halts, which means that B() halts, which means that H(code(B)) returns true. But by the definition of A, this means that A() does not halt (as before, we fall into the first branch).
It does not halt, which means that B() does not halt, which means that H(code(B)) returns false. But by the definition of A, this means that A() halts (as before, we fall into the second branch).

I do not really doubt the correctness of these results, but I am concerned about their possible lack of rigor. I would appreciate feedback about their correctness and formality, and also an explanation why the mathematical version of the Halting Problem is much more complicated. Thank you. :)
P.S. This is a response to spaceisdarkgreen's excellent answer.
I tried making his suggestions concrete. So, consider the following function:
void DHasCodeD() {
    if (H(code(D), code(D)) == true) {
        while (true);
    }
    else {
        return;
    }
}

The halting problem now transfers over to the program D(x). This answers my initial question: supposing that H(x, y) exists, we can also derive a contradiction from a zero-parameter function.
However, what's bugging me here is that we are using a halting oracle with two parameters. We have not shown that H(x) does not exist. After all, what if H(x) is weaker than H(x, y)?
We try the following:
DZero() {
    if (H(code(DHasCodeD)) == true) {
        while (true);
    }
    else {
        return;
    }
}

The proof by contradiction transfers again. But in my mind, this proof is problematic because it presupposes the existence of a halting oracle with two parameters. To be convinced, I would have to see a proof by contradiction involving only H(x).
Comment: each of the three instances of "else {return;}" are redundant fluff that should be removed for clarity.
Comment: The way you have presented these proofs are unnacceptable levels of rigour. You need to use sentences like "Suppose we have a computable function $H$ that, ...". Instead what you have written "H returns true" - this is unamibiguous and yeah as you have it written here these are not rigorous arguments. You have the gist though your vocabulary should be far more specific to the situation at hand, instead you are using several assumptions when writing just a single sentence of definitions here.
Comment: @Snared I disagree. Even though the programs would be semantically correct without that piece of code, I left them in to illustrate the point of the program terminating.
Answer: The first argument looks perfectly fine to me.
The problem with your latter two examples is that the functions aren't self contained... you reference a "free variable" in one and external definitions in the others. A computable function (i.e. the things that we assign code numbers)  is the whole shebang, not just some auxilliary function you might define within a program.
In fact, the slickest way to proceed is to not allow any functions with zero arguments, or with more than one argument, since any computable function of arbitrary arity can be simulated by a computable function with one variable, by ignoring the input in the zero argument case or using a tupling function in the greater-than-one argument case.
But we can still show that the halting problem for zero-argument functions isn't computable, directly from the halting problem for one-argument functions that you proved. The key is that from the code for any one-argument computable function and an argument we want to pass it, we can computably write code for a zero-argument function that does the same thing... we just hardcode the argument and proceed as in the original function.
So if we wanted to tell if a given computable function $f$ halts on input $x$, we could just compute the code the zero-variable function equivalent to the computation of $f(x),$ then pass it into the halting oracle for zero-variable functions. Thus, the halting problem for one-variable functions is reducible to the halting problem for zero-variable functions, so if the former is not computable, neither is the latter.

Edit As requested, more details.
The crucial thing here is the existence of a computable function that acts like the following python function:
def make_zero_argument(input_function, argument):
    def output_function():
       return input_function(argument)
    return output_function

only it operates on the code number of the input function (in some reasonable numbering of the one-argument computable functions) and returns a code number for the output function (in some reasonable numbering of the zero-argument computable functions).
For instance, it takes a code for this function
def f(x):
    output = 1
    for i in range(1, x + 1):
        output *= i
    return output

and the number $10101$ and returns a code for this function
def g():
    x = 10101
    output = 1
    for i in range(1, x + 1):
        output *= i
    return output

It's difficult to write down explicitly (and of course is dependent on the specific model of computation and the choice of numberings), but still is obviously computable given that the numberings are reasonable... e.g. it's obvious what I did to the text of $f$ to get the text of $g$ can be done programmatically. Even though it's not the python function written down above, we'll still call this computable function make_zero_argument.
Then we define the one-argument halting function in terms of the zero-argument halting function as follows:
def H_1(function_code, input):
    return H_0(make_zero_argument(function_code, input))

Comment: Thank you for your answer. I added some additional questions to the P.S. section of my question, and I would be very grateful for any help! :)
Comment: @Godbless you have things backwards. My argument shows that if $H(x)$ exists then $H(x,y)$ exists. It presupposes $H(x)$, then constructs $H(x,y)$ from $H(x)$, and since we know $H(x,y)$ doesn't exist, we have a contradiction from $H(x).$
Comment: I tried carrying out your suggested construction of $H(x, y)$ from $H(x)$ for $D$. However, as outlined in my postscript, the problem is that $D$ already has $H(x, y)$ in its body, so it presupposes its existence. From this, it seems to me that there must be some restriction on the $f$s referred to in your answer.
Comment: I guess that I don't really have a problem with your proof by contradiction, as another user has explicated it nicely and I get it now. What worries me is that I have not been able to construct a concrete paradoxical function `D()` using the suggestion you provided, for the reasons I already stated.
Comment: @Godbless Your attempts above don't make sense to me, and violate my point about functions needing to be self-contained. I added detail and some pseudo-code (hopefully python is okay... first-class functions make the *idea* of the function easy to express, even though, as I note, we really need to be doing some encoding and decoding here, which requires some messy details to write down explicitly).
Answer: First of all we let $halt_1:S_1 \times \Sigma^* \rightarrow \{0,1\}$ denote the halting function for programs with one input. Here $S_1$ is a suitable subset of $\Sigma^*$ denoting all syntactically correct programs (with one input). So given any two strings $s \in S_1$ and $t \in \Sigma^*$ we say that $halt_1(s,t)=1$ iff the program with code $s$ halts when given the input $t$. We say that $halt_1(s,t)=0$ iff the program with code $s$ does not halt when given the input $t$.
The first point is that there is no program that takes on two input strings and computes the function $Halt_1:\Sigma^* \times \Sigma^* \rightarrow \{0,1,2\}$. In other words:

$Halt_1:\Sigma^* \times \Sigma^* \rightarrow \{0,1,2\}$ is not a (total) computable function.

Here we have $Halt_1(i,j)=halt_1(i,j)$ for all $i \in S_1$ and $j \in \Sigma^*$. However, when $i \notin S_1$ and $j \in \Sigma^*$ we have $Halt_1(i,j)=2$.

Now using the result in previous paragraph we can show several more results. First of all consider the function $halt_0:S_0 \rightarrow \{0,1\}$. Here $S_0$ is a suitable subset of $\Sigma^*$ denoting all syntactically correct programs with no input. So given a string $s \in S_0$ we say that $halt_0(s)=1$ iff the program with code $s$ halts. We say that $halt_0(s)=0$ iff the program with code $s$ does not halt.
Now consider a function $Halt_0:\Sigma^* \rightarrow \{0,1,2\}$. Here we have $Halt_0(i)=halt_0(i)$ for all $i \in S_0$. However, when $i \notin S_0$ we have $Halt_1(i)=2$.
Now using the fact that $Halt_1:\Sigma^* \times \Sigma^* \rightarrow \{0,1,2\}$ is not a (total) computable function we can show that $Halt_0:\Sigma^* \rightarrow \{0,1,2\}$ is not a (total) computable function. This is shown by the usual "reduction". We first suppose that $Halt_0:\Sigma^* \rightarrow \{0,1,2\}$ was a (total) computable function. Then there exists a program that computes $Halt_0:\Sigma^* \rightarrow \{0,1,2\}$. Using the existence of program in previous sentence, we can show that there exists a program that computes the function $Halt_1:\Sigma^* \times \Sigma^* \rightarrow \{0,1,2\}$. However, that would mean that $Halt_1:\Sigma^* \times \Sigma^* \rightarrow \{0,1,2\}$ is computable (which was mentioned above to be false). Therefore our assumption of $Halt_0:\Sigma^* \rightarrow \{0,1,2\}$ being a computable function was incorrect.

At the risk of confusing things a bit further, I think there is one more thing to mention. It would happen often that one would not see a distinction between the sets $S_0$ and $S_1$. Instead a single set $S$ will be used. In the latter case, a single program can be thought of as calculating 0-ary,1-ary (2-ary, n-ary etc.) partial computable functions.
Whether such a distinction between $S_0$ and $S_1$ is necessary or not depends on the specific definition of computational model (more specifically, conventions regarding input variables).
Comment: This was a very nice explanation! Thank you very much. For completeness, consider also adding a more "mathematical" proof of the nonexistence of $\mathrm{Halt}_1$. ;)


Nested insert in Linq to SQL?

Question: How do i put a nested insert into database using Linq to SQL
my Table is like this:
[Post]
--Post ID
--Post Title

[Attachment]
--Post ID (PFK)
--AttachmentID (PK)
--IMGID (FK)
--VIDID (FK)

[IMG]
--IMGID (PK)

it's a M:N table
basically when i submit a form , it go together with the attachments within the form. Im ok with insert Post, but strugling with the inserting attachments since i dont have any POST ID yet...
so what do you think is the best solution for this kind of problem?
Thank you
Comment: Did you find the solution for M:N relation ? If yes, please post the solution.
Answer: If you create a two-way Association between Post and Attachment, so you can do the following:
Post post = new Post { /* Set some fields perhaps */ };
Attachment attachment = new Attachment { /* Same here */ };
attachment.Post = post; // That is the association you need to create
dataContext.Posts.InsertOnSubmit(post);
dataContext.SubmitChanges();

LINQ-to-SQL will then handle the insertion of the Attachment(s) automatically.
I haven't used the DBML designer in a while, but I'm fairly sure you can say that a Post has Attachments and that an Attachment has a Post. And when you say attachment.Post = post, the setter for Post internally will do _post.Attachments.Add(attachment) where _post is a private member of the Attachment entity. Then, when you submit the Post, it will loop through the Attachments and insert them too.
Comment: i think this is M:1 how about M:N between post and IMG?

Nested insert in Linq to SQL?


How to get the string store in an array in php

Question: I have a string that I trim first to remove extra characters and store it to a variable.
sampel output:
    variable: place1 place2

Now what I want to do is store it to an array. But how can I do that? is there a function that will detect if there is a white space? because every white space that it detects I would want the string to be stored in an array.
Any method or help is greatly appreciated! Thanks!
Comment: Is this a PHP, JavaScript, or jQuery question?
Answer: Use explode():
$array_of_parts = explode(' ', 'place1 place2');
echo $array_of_parts[0]; // place1
echo $array_of_parts[1]; // place2

Answer: explode() is the function you're looking for.
$string = 'place1 place2';
$arr = explode(' ', $string);

Comment: Thanks! So thats how it is, haha! :D
Comment: oh! so that's how it is.. LOL! I just found out. hahaha
Answer: you can use explode() function:
$yourString = 'place1 place2';
$exploded = explode (' ', $yourString);
echo $exploded[0];
echo $exploded[1];


Multinomial Count Models

Question: Is it possible to model a dependent variable which is both multinomial and count? If so, how would one do so with a tool such as R?
For example, suppose that my dependent variable looks like this:

On the level of an individual student I could estimate the probability of graduation for each term, then sum the estimated probabilities across students. However, suppose that my data is pre-aggregated, so I want to estimate the model above on the university level.
My explanatory variables could be things like:

count of students with sufficient credits to graduate
count of students with declared graduation dates for Summer, Fall, and Spring
count of students with more than 120 credits earned
Answer: There are different possibilities that come to mind.

You could use three different models, one for summer graduations, one for fall graduations, one for spring graduations. For this, you could use standard count models in R, say Poisson or NegBin regression, using (say) glm().
The advantage of this approach is of course its simplicity. The disadvantage is that you cut your data by two thirds in each separate analysis.

Or you run a single big model (again using glm()) and include an indicator factor variable that tells the model whether a particular data point is from a summer, fall or spring semester. You could then also look at interactions between predictors.

You could also model and forecast the total number of graduations per year using count data models as above, and then break this total prediction down by forecasted proportions, where you'd predict the proportions using any of the two approaches above.
This is essentially the "top-down" approach in hierarchical forecasting, and it can improve the accuracy of your predictions on the lower levels.

Another possibility is to use the "optimal combination" approach to hierarchical forecasts, which I personally have found to increase accuracy on all levels. Here is an introduction to hierarchical forecasting in general and the "optimal combination" approach specifically.

Alternatively, you could see the entire exercise as one in forecasting an entire curve, namely the function that maps quarters to graduation totals. This is an example of functional-data-analysis. In R, you could look at the fda package. See this and this earlier question.
I'm not aware of anything that specifically looks at count functional data, but if the numbers in your example are representative, you may be dealing with sufficiently large numbers that approximating using the normal distribution is good enough. (Which also applies to the other approaches outlined above.)

Multinomial Count Models


Kendo datasource shema.data does not work for dropdownlist

Question: I have Odata WebApi, and I want to populate my dropdownlist with data from there.
I have datasource:
var postsDataSource = new kendo.data.DataSource({
                type: 'odata',
                serverFiltering: true,
                transport: {
                    read: {
                        url: "/odata/Posts",
                        dataType: "json"
                    },
                },
                schema: {
                    model: kendo.data.Model.define({
                        Id: "Id",
                        RegionId: "RegionId"
                    }),
                    data: function (res) {
                        debugger;//this code is inaccessible!
                        console.log(res);
                        return res.value;
                    }
                },
            });
and dropdownlist like this:
var posts = $("#searchPost").kendoDropDownList({
            optionLabel: "Выберите регион...",
            dataTextField: "NameRu",
            dataValueField: "Id",
            dataSource: postsDataSource,
        }).data("kendoDropDownList");

This part of code executes odata query and return me the following json response in the firebug's console:
{
  "odata.metadata":"http://localhost:11029/odata/$metadata#Posts","odata.count":"13","value":[
    {
      "Id":0,"Number":"Lenina45","RegionId":1,"NameRu":"\u041b\u0435\u043d\u0438\u043d\u0430 45","NameKz":"\u041b\u0435\u043d\u0438\u043d\u0430 45","ShortName":"\u041b\u0435\u043d\u0438\u043d\u0430 45","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
    },{
      "Id":1,"Number":"Zhumabaeva15","RegionId":2,"NameRu":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","NameKz":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","ShortName":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
    },
    .....
  ]
}

Right after this response I am getting the following strange error:
TypeError: d.d is undefined;
And dropdownlist doesn't show me above json response.
When I populated kendo grid with odata web api, the following code in datasource solved my problem:
schema: {
                    data: function (res) {
                        return res.value;
                    }
                },

but now, when I use it for dropdownlist it doesn't work at all, it's inaccessible.
PS> Sorry for my bad English.
Answer: You Data Is on the inner object "value" on your response , your response consist on page size , metadata url so we need to prase the data that kendo dataSource can understand here is a exsample
: Note Remove "type: 'odata'" and check , since you are saying the dataSource where the Data is from the Data function no need of it as I think.
var postsDataSource = new kendo.data.DataSource({
                serverFiltering: true,
                transport: {
                    read: {
                        url: "/odata/Posts",
                        dataType: "json"
                    },
                },
                schema: {
                    model: {
                        Id: "Id",
                         fields: {
                           Id: { type: "number" },
                           NameRu: { type: "string" },
                            NameKz: { type: "string"},
                            ShortName: { type: "string" }
                        }
                    },
                    data: function (response) {
                        return response.value;
                    },
                    total: function(response) {
                     return response.odata.count;
                     }
                },
            });

try this hope this helps.
Comment: Thanks a lot for your answer! I've just added this `total: function(response) {
                     return response.odata.count;
                     }` from your sample, and it works for me. I use "type:'odata'" to be able to apply server filtering for cascade dropdowns.


How to get the list of EC2 instances created by Member users in OU in AWS

Question: I have my AWS account. I have created multiple member users instead of IAM Users.
Memebers usera has created multiple EC2 instances & other resources.
Can we get a list of running instances created by memeber users, through CLI ?
Comment: Sorry, but your question is unclear. Could you please Edit your question and add more details? For example, what do you mean by "Member users in OU"? What do you mean by "list of EC2 instances for the member users"? How are the EC2 instances associated with these "members"?
Comment: How can we get the list of running instances in AWS through AWS CLI
Answer: In your comment you asked: "How can we get the list of running instances in AWS through AWS CLI"
This AWS CLI command will list instances filtered by State, returning the Instance ID:
<code>aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query Reservations[].Instances[].InstanceId --output text
</code>
This will list all running Amazon EC2 instances in your account for the default region that you have defined in the AWS CLI configuration.
It is not possible to limit the listing to only instances launched by specific people. Once an instance is launched, it belongs to the AWS Account and is not associated with a specific IAM User. If you wish to track usage by specific users, either add a Tag to the resource or use AWS CloudTrail to identify who launched the instance.
Comment: Thanks for your kind response. The above command shows the list of running instances created by IAM Users. But in our scenario i have an AWS account, in which i have created an OU (Organizational Unit) & we have created many users inside this OU. Now we would like to list the instances, created by these users.  If you could do a favor in this cause i shall be highly obliged to you.  Thanks in advance
Comment: This is not possible. Instances are associated with an AWS Account. They are _not_ associated with the IAM User that launched the instance. You would need to examine records in AWS CloudTrail to discover who launched the instances. Alternatively, you could require that people add a Tag when launching their instance, so you can identify who launched it.


android file.getUsableSpace returns zero with getExternalFilesDir(null), only after deleting other files

Question: I have an app that sometimes needs to save files. Before writing, it checks usable space on the device. Here is the code I'm using to check space, with log statements.
String state = Environment.getExternalStorageState();
Log.d("Classname", "external storage state is " + state);
File file = new File(getExternalFilesDir(null) + File.separator);
Log.d("Classname", "file exists " + file.exists());
long usableSpace = file.getUsableSpace();
Log.d("Classname", "Space available " + usableSpace);

I've received a bug report that after deleting other files, around 3-5 MB, on a device that has around 3 GB free, getUsableSpace is returning 0 when trying to save another file.
The log before adding the first file:
11:21:46.879: external storage state is mounted
11:21:46.879: file exists true
11:21:46.880: Space available 3185496064

The log after deleting the first file, trying to add a second:
11:21:57.811: external storage state is mounted
11:21:57.822: file exists false
11:21:57.823: Space available 0

I have external storage permissions in my manifest, and have tried checking whether the storage is mounted and calling mkdir() when creating the external storage file, and the bug persists. I also had the tester reboot the device, thinking it might have just gotten into a weird state.
Does anyone have any ideas why this might be happening?
Answer: I found it. The solution was in the way deleting happens – if the last file deleted is gone, I was cleaning up the directory getExternalStorageDir was looking for, so when I tried to getUsableSpace on it, the directory didn't exist.


Proof of lemma about product of irreducible polynomials over finite fields

Question: Reading this Wikipedia page while learning about polynomials over finite fields, I came upon the following lemma:
For $i ≥ 1$ the polynomial $x^{q^i}-x \in \mathbf{F}_q[x]$
is the product of all monic irreducible polynomials in $\mathbf{F}_q[x]$ whose degree divides $i$.
What is this lemma properly called, and how is it proved?
Answer: Hints:
Denoting by $\;k:=\overline{\Bbb F_q}\;$ an algebraic closure of $\;\Bbb F_q\;$ , prove that for any $\;n\in\Bbb N\;$ we have that
$$\Bbb F_{q^n}=\left\{\;\alpha\in k\;:\;\;\alpha^{q^n}-\alpha=0\;\right\}$$
and now use/prove that $\;\Bbb F_{q^m}\le\Bbb F_{q^n}\;$ (the left field is a subfield of the right field) iff $\;m\le n\;,\;\;m,n\in\Bbb N$
Comment: I'm so sorry, but I cannot understand your answer. When would $α^{q^n}$ equal $α$?
Comment: @Mints97 Precisely when $\;\alpha\in\Bbb F_{q^n}\;$ . What part you didn't understand? First, you have to prove that the given set is a field wrt the operations modulo $\;q\;$, and then you must prove it has precisely $\;q^n\;$ elements. For this you could use things you know about roots of polynomials over a field. The second part is a more or less straightforward application of the multiplicativity degree of a tower of fields, together with the first part perhaps, or in some other way.
Comment: I'm... sorry... I probably shouldn't have asked this question yet... I just don't know enough yet to understand your answer. I haven't learned about multiplicativity degrees or about towers of fields... But I guess I could try to understand it again when I get comfortable with all these concepts.
Comment: This is wrong. You should replace$m \leq n$ by $m \mid n$.
Answer: See: Irreducible Polynomials over a Finite Field
(search "splits" there)
With q prime, let $g(x)=x(x^{{q^i-1}}−1)$ , why every element of $F_{q^i}$  is a root of g(x) ?
My hint:
a) 0 is easy
b) $F_{q^i}-\{0\}$  is a cyclic multiplicative group of order ${q^i-1}$ so its elements satisfy $x^{{q^i-1}}−1=0$
c) g(x) has now every root it can afford !
The rest of the proof uses Galois theory (that's why "degree divides i" in your post and why the algorithm in the wiki you gave is fast enough).
I would like to say thanks to you : your post and the algorithm motivate me to learn more about Galois theory.
The proof is found in: https://www.jmilne.org/math/CourseNotes/FT.pdf
You should save that file and use Foxit to read it, then search for "Each monic irreducible polynomial f of degree" in the PDF.
PS: on SEP1993 (Fermat's Year), in the mad rush to Fermat's Last, after studying math for ca 70 days, I directly read the chapter "Galois theory" in Serge Lang book ("Algebra") using TOP-DOWN method : I went back to previous chapters if necessary. The method worked thanks to this legendary book which I borrowed from a layman-library!! Now a SEARCHable e-version can be had for < 20 USD, I think.
Hint for graduates: free PDFs :  https://www.jmilne.org/math/CourseNotes/


Is there a regulation about the shape of the posts of a football goal?

Question: I mostly saw posts of football goals with a circular bases, but sometimes I saw posts (and crossbars) with very square basis.
<code>| Is there a regulation about it?
</code>
It seems to me that the poles with square base are dangerous for a collision with a player.
Answer: As with much of this stuff, this is explicitly covered in the Laws of the Game. In this case, Law 1 The Field of Play, Goalposts (page 9):

The goalposts and crossbar [...] must be square, rectangular, round or elliptical in shape and must not be dangerous to players.

Given that the Laws explicitly allow square or rectangular posts, I don't think you're going to be able to make an argument that they are disallowed just because you think they're dangerous.


Trying to get a property of a non-object in 'mymodule_node_access()'

Question: In a custom module, I try to make this code work :
function mymodule_node_access($node, $op, $account) {
  if ($node->type = 'devis' and $op = 'view') {
    $field_language = field_language('node', $node, 'field_project');
    $project_node = node_load($node->fields->field_project[$field_language][0]['value']);
    if ($project_node->uid == $account->uid) {
      return NODE_ACCESS_IGNORE;
    }
    else {
      return NODE_ACCESS_DENIED;
    }
  }
}

I get the following notice:

Trying to get a property of a non-object in mymodule_node_access()

I don't know where the problem is.
Answer: $node in hook_node_access() can be either a string for the content-type or a node object.
I had to test if it was a string or an object.
if (is_string($node)) {
  return NODE_ACCESS_IGNORE;
}
else {
  // ...
}

Answer: Fields are directly on the node object, you're currently trying to find them in another object called fields.
Change this:
$project_node = node_load($node->fields->field_project[$field_language][0]['value']);

To this:
$project_node = node_load($node->field_project[$field_language][0]['value']);

And it should work.
Comment: Beat me to it. I was also going to add that all fields are attached to a [Drupal node object](https://www.drupal.org/node/49768) directly as the property `field_{field_name}`.
Comment: Thank ou for your fast answer, I changed it and still have the same notice, I really don't know what is the matter


Optimizing Treatment Group Assignments

Question: When setting out experiments, I want to make sure treatment groups are as balanced as possible. Instead of using randomization, I've started to use the following process. I first collect some measurements from the potential experimental units I have at my disposal. Then, I generate all the different possible combinations of treatment groups using all these potential experimental units (yes - I know it's computationally intensive). Finally, I see which combination keeps means, variances, and possibly higher-order moments of the measurements I took as consistent as possible across groups.
I'm wondering if I need to take into account degrees of freedom somehow. I know the process I described above is something you do before an experiment even begins and isn't really related to the final statistical analysis, but I can't help thinking about degrees of freedom with all these parameters I'm calculating.
As an aside, I've decided that, when you're placing n experimental units into each treatment group, that it only makes sense to calculate up to the nth or the (n - 1)th moment, but this idea is still a work in progress.
Does anyone have any thoughts? Thank you in advance for your help - I'm very grateful.
Answer: if you hava few and categorical covariates variable(pre-experiment measurements) , you can try block: This approach achieves almost perfect balance between covariates, and degrees of freedom don't matter
if you have many or continuous covariates variable, you can try Rerandomization: here the degrees of freedom still don't matter here
Comment: Thanks - this answer wasn't quite what I was hoping for, but it was the first time I heard of rerandomization, so I really appreciate that

Optimizing Treatment Group Assignments


Adding product to blog sidebar

Question: In Drupal 8 commerce 2, how would I embed a product with an add to cart button and select ID of my choosing into the sidebar of a blog post?
Comment: I don't understand why this has been voted down?
Answer: This can be done please see this issue from drupal.org
https://www.drupal.org/project/commerce/issues/2935377

Adding product to blog sidebar


Unresponsiveness with async event handlers in WPF in .NET 4.5

Question: I have created a simple async operation which is being kicked of when the button is clicked. Here is the whole code:
public partial class MainWindow : Window {

    public MainWindow() {
        InitializeComponent();
    }

    private async void Button_Click_1(object sender, RoutedEventArgs e) {

        var htmlString = await DowloadPage("http://example.com");
        txtBlock1.Text = htmlString;
    }

    public async Task<string> DowloadPage(string uri) {

        using (WebClient client = new WebClient()) {

            var htmlString = await client.DownloadStringTaskAsync(uri);
            return htmlString;
        }
    }

}

Very easy. But when I click the button, I experience unresponsiveness on the UI thread. When I try to move around the window while the page is being downloaded, I am unable to.
Any idea what is going wrong?
Edit:
I tried with HttpClient in .NET 4.5 and it worked out pretty great as expected:
public async Task<string> DowloadPage(string uri) {

    using (HttpClient client = new HttpClient()) {

        var response = await client.GetAsync(uri);
        var htmlString = await response.Content.ReadAsStringAsync();
        return htmlString;
    }
}

Comment: BTW there is a new [HttpClient Class](http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx) in .NET 4.5 which is designed for `async`/`await`.
Comment: @dtb I am aware of that. Thanks but the issue here is different.
Comment: How long is `htmlString`?  It may simply take some time to render the `txtBlock1` with it.
Comment: @dtb do you think that newing up the `WebClient` would cause that blocking?
Comment: No, creating a `WebClient` instance is really lightweight. Have you checked how long `htmlString` is (see my comment above)?
Comment: @dtb I tried the same without putting the result to TextBlock. The result is the same.
Comment: Can you check if it happens with HttpClient as well?
Comment: @dtb can u confirm that it works as expected on your machine if possible?
Comment: @dtb see my edit to the question. HttpClient worked perfectly.
Comment: It looks like WebClient is doing some work on the UI thread then; I guess it's not really designed for use with `async`/`await`. Any reason you can't use HttpClient?
Comment: None, this is just a try out. I just wondered why it was happening.
Comment: File a [bug report](http://connect.microsoft.com/VisualStudio).
Answer: WebClient uses HttpWebRequest, which unfortunately is not very asynchronous, even if you use the "asynchronous" methods. It does a blocking DNS lookup, at least. It may also block during proxy negotiation and/or the initial HTTP connection.
An older release of HttpClient was just using a wrapper around HttpWebRequest. I requested a truly-asynchronous HttpClient, but never heard a response. The last time I checked HttpClient, it was still part of MVC; ASP.NET Web API wasn't around at that time, so they may have fixed HttpClient since then. Or the difference in behavior between WebClient and HttpClient on your machine may just have to do with DNS caches or some such.
Comment: Inside the download method (not the handler), should it ConfigureAwait(false) since its particular continuation doesn't need to be on the UI thread?  Obviously the handler shouldn't do so. :)
Comment: I would. It's best practice to do so, but (in this case) it won't cause any problems (like deadlocks) if he doesn't - it's just not as efficient as it could be.
Comment: I assume that since the questioner said HttpClient 'worked out great' that it was indeed 'fixed' to your liking?
Comment: I believe it has not been fixed. I examined it in dotPeek and the same call structure exists (`HttpClient` -> `HttpWebRequest` -> `ServicePoint` -> blocking DNS request).


Filtro de Portfolio com Javascript Puro

Question: Estou tentando abandonar o jQuery, porem, encontrei uma dificuldade agora, fazer um Filtro, estilo aqueles que se encontra em Portfolio, porem com JS Puro, so encontrei em jQuery ou CSS3 (na internet), nada com JS Puro, alguem conseguiria me ajudar? Realmente nao consegui fazer nada do genero com JS, nem consigo imaginar como fazer (alem de definir classes e dar display: none e block, mas nao fica tao legal. Um exemplo de como funciona é esse
Answer: Vou lhe passar uns exemplos todos com CSS sem utilizar JavaScript.
Segue os exemplos:
    Exemplo 1:
    Link: JSFiddle ou CodePen
*Para testar o Exemplo 1 aqui mesmo:

/* CSS reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td {
 margin:0;
 padding:0;
}
html,body {
 margin:0;
 padding:0;
}
table {
 border-collapse:collapse;
 border-spacing:0;
}
fieldset,img {
 border:0;
}
address,caption,cite,code,dfn,th,var {
 font-style:normal;
 font-weight:normal;
}
ol,ul {
 list-style:none;
}
caption,th {
 text-align:left;
}
h1,h2,h3,h4,h5,h6 {
 font-size:100%;
 font-weight:normal;
}
q:before,q:after {
 content:'';
}
abbr,acronym { border:0;
}
section, header{
 display: block;
}
/* General Demo Style */
body{
 background: #e0e3ec;
 font-weight: 400;
 font-size: 15px;
 color: #393b40;
 overflow-y: scroll;
}
a{
 color: #333;
 text-decoration: none;
}
.container{
 width: 100%;
 position: relative;
 text-align: center;
}
.clr{
 clear: both;
}
.container > header{
 padding: 20px 30px 10px 30px;
 margin: 0px 20px 10px 20px;
 position: relative;
 display: block;
 text-shadow: 1px 1px 1px rgba(0,0,0,0.2);
    text-align: center;
}
.container > header h1{
 font-family: 'BebasNeueRegular', 'Arial Narrow', Arial, sans-serif;
 font-size: 35px;
 line-height: 35px;
 position: relative;
 font-weight: 400;
 color: #6d7aa1;
 text-shadow: 1px 1px 1px rgba(0,0,0,0.3);
    padding: 0px 0px 5px 0px;
}
.container > header h1 span{
 color: #8997c0;
 text-shadow: 0px 1px 1px rgba(255,255,255,0.8);
}
.container > header h2{
 font-size: 16px;
 font-style: italic;
 color: #82858e;
 text-shadow: 0px 1px 1px rgba(255,255,255,0.8);
}
/* Header Style */
.codrops-top{
 font-family:'Arial Narrow', Arial, sans-serif;
 line-height: 24px;
 font-size: 11px;
 background: #000;
 opacity: 0.9;
 text-transform: uppercase;
 z-index: 9999;
 position: relative;
 -moz-box-shadow: 1px 0px 2px #000;
 -webkit-box-shadow: 1px 0px 2px #000;
 box-shadow: 1px 0px 2px #000;
}
.codrops-top a{
 padding: 0px 10px;
 letter-spacing: 1px;
 color: #ddd;
 display: block;
 float: left;
}
.codrops-top a:hover{
 color: #fff;
}
.codrops-top span.right{
 float: right;
}
.codrops-top span.right a{
 float: none;
 display: inline;
}

p.codrops-demos{
 text-align:center;
 display: block;
 padding: 14px;
}
p.codrops-demos a,
p.codrops-demos a.current-demo,
p.codrops-demos a.current-demo:hover{
    display: inline-block;
 border: 1px solid #6d7aa1;
 border-color: #7784aa #6d7aa1 #6d7aa1 #7784aa;
 padding: 4px 10px 3px;
 font-size: 13px;
 line-height: 18px;
 margin: 0px 3px;
 font-weight: 800;
 -webkit-box-shadow: 0px 1px 1px rgba(0,0,0,0.1);
 -moz-box-shadow:0px 1px 1px rgba(0,0,0,0.1);
 box-shadow: 0px 1px 1px rgba(0,0,0,0.1);
 color: #fff;
 text-shadow: 1px 1px 1px rgba(0,0,0,0.6);
 -webkit-border-radius: 5px;
 -moz-border-radius: 5px;
 border-radius: 5px;
 background: #8997c0;
 background: -moz-linear-gradient(top, #8997c0 0%, #6d7aa1 100%);
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#8997c0), color-stop(100%,#6d7aa1));
 background: -webkit-linear-gradient(top, #8997c0 0%,#6d7aa1 100%);
 background: -o-linear-gradient(top, #8997c0 0%,#6d7aa1 100%);
 background: -ms-linear-gradient(top, #8997c0 0%,#6d7aa1 100%);
 background: linear-gradient(top, #8997c0 0%,#6d7aa1 100%);
}
p.codrops-demos a:hover{
 background: #8997c0;
}
p.codrops-demos a.current-demo,
p.codrops-demos a.current-demo:hover{
 color: #424d71;
 text-shadow: 0px 1px 1px rgba(255,255,255,0.3);
}
/* Media Queries */
@media screen and (max-width: 767px) {
 .container > header{
  text-align: center;
 }
 p.codrops-demos {
  position: relative;
  top: auto;
  left: auto;
 }
}

.ff-container{
 width: 564px;
 margin: 10px auto 30px auto;
}
.ff-container label{
 font-family: 'BebasNeueRegular', 'Arial Narrow', Arial, sans-serif;
 width: 25%;
 height: 30px;
 cursor: pointer;
 color: #777;
 text-shadow: 1px 1px 1px rgba(255,255,255,0.8);
 line-height: 33px;
 font-size: 19px;
 background: #ffffff;
 background: -moz-linear-gradient(top, #ffffff 1%, #eaeaea 100%);
 background: -webkit-gradient(linear, left top, left bottom, color-stop(1%,#ffffff), color-stop(100%,#eaeaea));
 background: -webkit-linear-gradient(top, #ffffff 1%,#eaeaea 100%);
 background: -o-linear-gradient(top, #ffffff 1%,#eaeaea 100%);
 background: -ms-linear-gradient(top, #ffffff 1%,#eaeaea 100%);
 background: linear-gradient(top, #ffffff 1%,#eaeaea 100%);
 filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eaeaea',GradientType=0 );
 float:left;
 box-shadow: 0px 0px 0px 1px #aaa, 1px 0px 0px 0px rgba(255,255,255,0.9) inset, 0px 1px 2px rgba(0,0,0,0.2);
}
.ff-container label.ff-label-type-all{
 border-radius: 3px 0px 0px 3px;
}
.ff-container label.ff-label-type-3{
 border-radius: 0px 3px 3px 0px;
}
.ff-container input.ff-selector-type-all:checked ~ label.ff-label-type-all,
.ff-container input.ff-selector-type-1:checked ~ label.ff-label-type-1,
.ff-container input.ff-selector-type-2:checked ~ label.ff-label-type-2,
.ff-container input.ff-selector-type-3:checked ~ label.ff-label-type-3{
 background: #646d93;
 background: -moz-linear-gradient(top, #646d93 0%, #7c87ad 100%);
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#646d93), color-stop(100%,#7c87ad));
 background: -webkit-linear-gradient(top, #646d93 0%,#7c87ad 100%);
 background: -o-linear-gradient(top, #646d93 0%,#7c87ad 100%);
 background: -ms-linear-gradient(top, #646d93 0%,#7c87ad 100%);
 background: linear-gradient(top, #646d93 0%,#7c87ad 100%);
 filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#646d93', endColorstr='#7c87ad',GradientType=0 );
 color: #424d71;
 text-shadow: 0px 1px 1px rgba(255,255,255,0.3);
 box-shadow: 0px 0px 0px 1px #40496e, 0 1px 2px rgba(0,0,0,0.1) inset;
}
.ff-container input{
 display: none;
}
.ff-items{
 position: relative;
 margin: 0px auto;
 padding-top: 20px;
}
.ff-items a{
 display: block;
 position: relative;
 padding: 10px;
 background: #fff;
 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
 margin: 4px;
 width: 160px;
 height: 120px;
}
.ff-items a span{
 display: block;
 background: rgba(113,123,161, 0.9);
 font-style: italic;
 color: #fff;
 font-weight: bold;
 padding: 20px;
 position: absolute;
 bottom: 10px;
 left: 10px;
 width: 120px;
 height: 0px;
 overflow: hidden;
 opacity: 0;
 text-align: center;
 text-shadow: 1px 1px 1px #303857;
 -webkit-transition: all 0.3s ease-in-out;
 -moz-transition: all 0.3s ease-in-out;
 -o-transition: all 0.3s ease-in-out;
 -ms-transition: all 0.3s ease-in-out;
 transition: all 0.3s ease-in-out;
}
.ff-items a:hover span{
 height: 80px;
 opacity: 1;
}
.ff-items li img{
 display: block;
}

.ff-items li{
 margin: 0px;
 float: left;
 height: 148px;
 width: 0px;
 -webkit-transform: scale(0,0);
 -moz-transform: scale(0,0);
 -o-transform: scale(0,0);
 -ms-transform: scale(0,0);
 transform: scale(0,0);
}
.ff-container input.ff-selector-type-all:checked ~ .ff-items li{
 width: 188px;
 -webkit-transform: scale(1,1);
 -moz-transform: scale(1,1);
 -o-transform: scale(1,1);
 -ms-transform: scale(1,1);
 transform: scale(1,1);
 -webkit-transition: -webkit-transform 0.3s linear;
 -o-transition: -o-transform 0.3s linear;
 -ms-transition: -ms-transform 0.3s linear;
 transition: transform 0.3s linear;
}
.ff-container input.ff-selector-type-1:checked ~ .ff-items .ff-item-type-1,
.ff-container input.ff-selector-type-2:checked ~ .ff-items .ff-item-type-2,
.ff-container input.ff-selector-type-3:checked ~ .ff-items .ff-item-type-3
{
 -webkit-transition: -webkit-transform 0.3s linear, width 0s linear 0.3s;
 -moz-transition: -moz-transform 0.3s linear, width 0s linear 0.3s;
 -o-transition: -o-transform 0.3s linear, width 0s linear 0.3s;
 -ms-transition: -ms-transform 0.3s linear, width 0s linear 0.3s;
 transition: transform 0.3s linear, width 0s linear 0.3s;
 -webkit-animation: scaleUp 0.3s linear 0.4s forwards;
 -moz-animation: scaleUp 0.3s linear 0.4s forwards;
 -o-animation: scaleUp 0.3s linear 0.4s forwards;
 -ms-animation: scaleUp 0.3s linear 0.4s forwards;
 animation: scaleUp 0.3s linear 0.4s forwards;
}
.ff-container input.ff-selector-type-1:checked ~ .ff-items li:not(.ff-item-type-1),
.ff-container input.ff-selector-type-2:checked ~ .ff-items li:not(.ff-item-type-2),
.ff-container input.ff-selector-type-3:checked ~ .ff-items li:not(.ff-item-type-3)
{
 -webkit-animation: scaleDown 0.3s linear forwards;
 -moz-animation: scaleDown 0.3s linear forwards;
 -o-animation: scaleDown 0.3s linear forwards;
 -ms-animation: scaleDown 0.3s linear forwards;
 animation: scaleDown 0.3s linear forwards;
}
@-webkit-keyframes scaleUp {
 50% { width: 188px; -webkit-transform: scale(0,0); }
    100% { width: 188px; -webkit-transform: scale(1,1); }
}
@-webkit-keyframes scaleDown {
 0% { width: 188px;-webkit-transform: scale(1,1);}
 99% { width: 188px; -webkit-transform: scale(0,0);}
    100% { width: 0px; -webkit-transform: scale(0,0); }
}
@-moz-keyframes scaleUp {
 50% { width: 188px; -moz-transform: scale(0,0); }
    100% { width: 188px; -moz-transform: scale(1,1); }
}
@-moz-keyframes scaleDown {
 0% { width: 188px;-moz-transform: scale(1,1);}
 99% { width: 188px; -moz-transform: scale(0,0);}
    100% { width: 0px; -moz-transform: scale(0,0); }
}
@-o-keyframes scaleUp {
 50% { width: 188px; -o-transform: scale(0,0); }
    100% { width: 188px; -o-transform: scale(1,1); }
}
@-o-keyframes scaleDown {
 0% { width: 188px;-o-transform: scale(1,1);}
 99% { width: 188px; -o-transform: scale(0,0);}
    100% { width: 0px; -o-transform: scale(0,0); }
}
@-ms-keyframes scaleUp {
 50% { width: 188px; -ms-transform: scale(0,0); }
    100% { width: 188px; -ms-transform: scale(1,1); }
}
@-ms-keyframes scaleDown {
 0% { width: 188px;-ms-transform: scale(1,1);}
 99% { width: 188px; -ms-transform: scale(0,0);}
    100% { width: 0px; -ms-transform: scale(0,0); }
}
@keyframes scaleUp {
 50% { width: 188px; transform: scale(0,0); }
    100% { width: 188px; transform: scale(1,1); }
}
@keyframes scaleDown {
 0% { width: 188px; transform: scale(1,1);}
 99% { width: 188px; transform: scale(0,0);}
    100% { width: 0px; transform: scale(0,0); }
}

      <input id="select-type-all" name="radio-set-1" type="radio" class="ff-selector-type-all" checked="checked" />
      All
      <input id="select-type-1" name="radio-set-1" type="radio" class="ff-selector-type-1" />
      Web Design
      <input id="select-type-2" name="radio-set-1" type="radio" class="ff-selector-type-2" />
      Illustration
      <input id="select-type-3" name="radio-set-1" type="radio" class="ff-selector-type-3" />
      Icon Design

            Chameleon

            Tutorials (wip)

            Flower

            Symplas website

            TRON: Mobile version

            Cake

            Tailoring accessories

            App icon

            Event Planning

    Exemplo 2:
    Link: JSFiddle ou CodePen

    Exemplo 3:
    Link: JSFiddle ou CodePen
Obs: Coloquei os exemplos no JSFiddle e no CodePen para poder uma melhor visualização.
Comment: Excelente, muito bom.
Comment: Muito bom mesmo.

Filtro de Portfolio com Javascript Puro


How can I adapt ANOVA for binary data?

Question: I have four competing models which I use to predict a binary outcome variable (say, employment status after graduating, 1 = employed, 0 = not-employed) for n subjects. A natural metric of model performance is hit rate which is the percentage of correct predictions for each one of the models.
It seems to me that I cannot use ANOVA in this setting as the data violates the assumptions underlying ANOVA. Is there an equivalent procedure I could use instead of ANOVA in the above setting to test for the hypothesis that all four models are equally effective?
Answer: Contingency table (chi-square). Also Logistic Regression is your friend - use dummy variables.

How can I adapt ANOVA for binary data?


install boot with raid 1 in 3 TB disks

Question: I'm trying to install /boot in a RAID 1 using 3 TB disks. As the RAID partition do not let you manage partitions than more than 2 TB, CentOS automatically configures the partitions using GPT.
My current machine (HP Proliant ML110 G4) does not support EFI/GPT so it uses MBR to boot the system. If I configured the /boot using a standard partition it works but it does not work if I installed the /boot using RAID 1. The system can not boot and it does not throw any error. Is it possible to install /boot in a RAID 1 with 3 TB disks if my system does not support EFI? I'm using CentOS 6.3.
Answer: Did you make sure to install the boot loader on all of the hard drives? With a raid1 set as your boot partition you have to install grub on each hard drive in turn - or at least you used to with smaller disks using MBR partitioning
I'm just now doing this on a server I have (upgrading storage space) so I'm curious if you found an answer
And to those that say "don't do this, it's ridiculous", what's ridiculous is purchasing a new server you'll just have to landfill later, and which probably uses more energy than the one it's replacing (if the one its replacing was built for low power to begin with) just so you can have a whizzy server getting even more bored than the one it replaced as it is dishing out bits as a NAS when it's bottlenecked by the network anyway. The moral is to never question why people are doing things, in context almost anything makes sense.

install boot with raid 1 in 3 TB disks


Jquery - two select, option - count between and disable

Question: I need advice. I have some number of rooms eg 2 or more.
Standard for one person and "single"
Standard for two people and with "double"
It is still the same room. This means that if I select 1x single, the 2x double option will be disabled and the available 1x option will remain and vice versa.
Now I can only block the entire select. I only need to block options.

var x = 2;
$("#frm-step1-standard1").change(function() {
  var va = $(this).val();
  if (va >= x) {
    $("#frm-step1-standard12").attr('disabled', 'disabled');
  } else {
    $("#frm-step1-standard12").removeAttr('disabled', 'disabled');
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css">

      Typ
      Night
      Price 1 room
      Number of rooms

      2
      5 €

        <select name="standard1" id="frm-step1-standard1">
          <option style="color: red;" value="0">0</option>
          <option style="color: red;" value="1">1</option>
          <option style="color: red;" value="2">2</option>
        </select>

      2
      0 €

        <select name="standard12" id="frm-step1-standard12">
          <option value="0">0</option>
          <option value="1">1</option>
          <option value="2">2</option>
        </select>

Answer: i hope it's your answer:

   var x = 2;
$("#frm-step1-standard1").change(function() {
  var va1 = $(this).val();
  var va2 = $("#frm-step1-standard12").val();
  if (va1+va2 >= x) {
    $("#frm-step1-standard12>option[value=2]").attr('disabled', 'disabled');
  } else {
    $("#frm-step1-standard12>option[value=2]").removeAttr('disabled', 'disabled');
  }
});

 $("#frm-step1-standard12").change(function() {
  var va1 = $(this).val();
  var va2 = $("#frm-step1-standard1").val();
  if (va1 + va2 >= x) {
    $("#frm-step1-standard1>option[value=2]").attr('disabled', 'disabled');
  } else {
    $("#frm-step1-standard1>option[value=2]").removeAttr('disabled', 'disabled');
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css">

      Typ
      Night
      Price 1 room
      Number of rooms

      2
      5 €

        <select name="standard1" id="frm-step1-standard1">
          <option style="color: red;" value="0">0</option>
          <option style="color: red;" value="1">1</option>
          <option style="color: red;" value="2">2</option>
        </select>

      2
      0 €

        <select name="standard12" id="frm-step1-standard12">
          <option value="0">0</option>
          <option value="1">1</option>
          <option value="2">2</option>
        </select>

Comment: Thanks, but that's not it yet. The sum of select one and two values can be max 2. I select one = 1, then select two can be max 1
Select one + select two = 2
Comment: @aha009 check again!
Comment: There is still a mistake. When I select select one = 2, then I can select select two = 1. The sum should be max 2.
Comment: try with :  var x = 1;
Answer: I have expanded the solution from @foadabd
Is there a more elegant solution? I need it to be dynamic.
var x can be any number.
It still doesn't work properly.

var x = 2;
$("#frm-step1-standard1").change(function() {
  var va1 = parseInt($(this).val());
  var va2 = parseInt($("#frm-step1-standard12").val());
  if (va1 + va2 >= x) {
    $("#frm-step1-standard12>option[value=1]").attr('disabled', 'disabled');
    $("#frm-step1-standard12>option[value=2]").attr('disabled', 'disabled');
  } else if (va1 + va2 == 1) {
    $("#frm-step1-standard12>option[value=1]").removeAttr('disabled', 'disabled');
  } else if (va1 + va2 == 0) {
    $("#frm-step1-standard12>option[value=1]").removeAttr('disabled', 'disabled');
    $("#frm-step1-standard12>option[value=2]").removeAttr('disabled', 'disabled');
  }
});

$("#frm-step1-standard12").change(function() {
  var va1x = parseInt($(this).val());
  var va2x = parseInt($("#frm-step1-standard1").val());
  if (va1x + va2x >= x) {
    $("#frm-step1-standard1>option[value=1]").attr('disabled', 'disabled');
    $("#frm-step1-standard1>option[value=2]").attr('disabled', 'disabled');
  } else if (va1x + va2x == 1) {
    $("#frm-step1-standard1>option[value=1]").removeAttr('disabled', 'disabled');
  } else if (va1x + va2x == 0) {
    $("#frm-step1-standard1>option[value=1]").removeAttr('disabled', 'disabled');
    $("#frm-step1-standard1>option[value=2]").removeAttr('disabled', 'disabled');
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css">

      Typ
      Night
      Price 1 room
      Number of rooms

      2
      5 €

        <select name="standard1" id="frm-step1-standard1">
          <option style="color: red;" value="0">0</option>
          <option style="color: red;" value="1">1</option>
          <option style="color: red;" value="2">2</option>
        </select>

      2
      0 €

        <select name="standard12" id="frm-step1-standard12">
          <option value="0">0</option>
          <option value="1">1</option>
          <option value="2">2</option>
        </select>

Answer: I've reduced the code so you don't need to have multiple change statements for the dropdowns.
Demo

var x = 2;
var selector = $("#frm-step1-standard1,#frm-step1-standard12");
selector.change(function() {
  var va1 = $(this).val();
  var va2 = selector.not(this).val();
  if (va1 + va2 >= x) {
    $("option[value=2]", selector.not(this)).hide()
  } else {
    $("option[value=2]", selector.not(this)).show()
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css">

      Typ
      Night
      Price 1 room
      Number of rooms

      2
      5 €

        <select name="standard1" id="frm-step1-standard1">
          <option style="color: red;" value="0">0</option>
          <option style="color: red;" value="1">1</option>
          <option style="color: red;" value="2">2</option>
        </select>

      2
      0 €

        <select name="standard12" id="frm-step1-standard12">
          <option value="0">0</option>
          <option value="1">1</option>
          <option value="2">2</option>
        </select>