How to "trick" R into producing treatment effects in a treatment * dummy model?

Question: I'm running some basic regressions which can be specified compactly as the formula: y~treatment*dummy.
Say there are several ($m$) treatments, $T_1,\ldots,T_m$ (with $T_1$ being the reference/control); the dummy is also multifaceted (categorical), taking $n$ values $D_1,\ldots,D_n$
Then (suppressing the observation index and error) the above formula specification basically returns the specified formula as
$$y=T^TBD$$
Where $T$ is the $m\times 1$ vector $[1, T_2, \ldots, T_m]$ of treatment indicators (excluding the reference treatment), $B$ is the $m\times n$ matrix of coefficients $\{\beta_{i,j}\}_{i=1,j=1}^{m\quad n}$, and $D$ is the $n\times 1$ vector $[1, D_2,\ldots, D_n]$ of dummy indicators (excluding the reference category).
This is all well and good, but the resulting coefficients in $B$ don't really have any clean interpretation, especially for my application. In particular, I'm looking for significant treatment effects--consider trying to answer the following: was Treatment 5 significantly better among individuals in category 3?
In the above specification, we'd be examining $\mathbb{E}[y|T_5,D_3]-\mathbb{E}[y|T_1,D_3]=\beta_{5,0}+\beta_{5,3}$, so we could add the coefficients we get out and use, e.g., a Wald test to determine significance.
However, consider the equivalent specification (I'm 100% sure someone besides has written it this way before since it took me all of 20 minutes to come up with):
$$y = \delta_0 + \sum_{j=2}^n\beta_j D_j + \sum_{i=2}^m \sum_{j=1}^n \gamma_{i,j}T_iD_j$$
Now the treatment effect is $\mathbb{E}[y|T_5,D_3]-\mathbb{E}[y|T_1,D_3]=\gamma_{5,3}$.
So this latter formulation has the convenient property that we can read our treatment effects right off our regression summary (especially including standard errors); its major drawback is that there's no way to supply this as an R formula parsimoniously, or at least I can't see a way to.
Does anyone have any experience with some secret formula or package to deal with this (I imagine exceedingly common) specification?
Answer: I have to struggle a bit with the mathematical notation, if I but in the following formula that you provided:
$$y = \delta_0 + \sum_{j=1}^n\beta_j D_j + \sum_{i=1}^m \sum_{j=0}^n \gamma_{i,j}T_iD_j$$
Isn't that essentially saying that there should be one coefficient per dummy variable (excluding the first), and then one coefficient per combination of T and D? In that case, you could simply write the formula as:
y ~ group + treatment:group

But when including interaction terms, it is often recommended that you should include all the main terms that are included in the interaction terms:
y ~ group * treatment

Comment: I've been thinking about it some more, and I think that the group + group:treatment approach makes sense, so go for it!
Comment: Nevertheless, my answer remains the same. Using R notation, you can do it like group:treatment or group + group:treatment or group*treatment, you will still get the same number of categories. When including interaction terms, the usual recommendation in textbooks is to also include the main effects, which in this case corresponds to y ~ group * treatment.
Comment: actually `y ~ group + treatment:group` does not exclude the reference level of `group`, so your answer is correct. I just get the feeling you're not understanding why I disagree with the "textbook recommendation"
Comment: By the way, check [here](http://stackoverflow.com/a/32682826/3576984) for a simpler way to implement this in R ;-)


Notation to describe function which maps from natural numbers to set of natural numbers

Question: If $f$ is a function which maps natural numbers to natural numbers, we'd write $\;f:\mathbb{N}\rightarrow\mathbb{N}$. But how would you say that $f$ maps from natural numbers to sets of natural numbers?
Answer: $f:\Bbb N\to\mathcal P(\Bbb N)$ is the most usual way. $\mathcal P(\Bbb N)$ is the set of all subsets of $\Bbb N$.
$f\in\mathcal P(\Bbb N)^{\Bbb N}$ is also used. (If $A$ and $B$ are sets, $B^A$ usually means the set of functions from $A$ to $B$).
Comment: To the OP: re: the second notation, note that the number of functions from an $n$-element set to a $k$-element set is $k^n$ when $n, k$ are finite. So that's where that notation comes from.
Comment: Power set can also be denoted $2^\mathbb{N}$ as well - just in case someone encounters that. Cheers. (Motivation for this notation: A subset can be represented as a "binary string" (whether you can order it, visualize it or not hence the scare quotes) with one bit for each element of the whole set, a 1 bit tagging a member in the subset, and a 0 bit tagging a member not in the subset. Thus there should be $2^{|X|}$ possibilities so the notation $2^X$ for the power set of $X$. Essentially the same as the second notation in the post but used somewhat differently.)
Answer: The power set is noted $\mathcal P(\mathbb N)$ it is the set of all subsets of $\mathbb N$.
So if you have a function from integers to integers this would be $f:\mathbb N\to A$ where $A\in\mathcal P(\mathbb N)$, but this is the same as $A\subset \mathbb N$.
And if you have a function from integers to sets this would be $f:\mathbb N\to \mathcal P(\mathbb N)$.


Unreachable code detected na conexão com banco

Question: Opa boa noite,
Pessoal to com um duvida certeza que é algo bobo, é que não to acostumado a usar um classe de conexão externa no desenvolvimento, tinha esse mau-habito mas agora fui usar e to encontra um Unreachable code se alguem conseguir me ajudar/explicar o porque agradeço :) Segue classe e método o erro ta no con.desconectar();:
public class Conexao:IDisposable
{
    private static string stringConexao = ConfigurationManager.ConnectionStrings["stringConexao"].ConnectionString;

    private SqlConnection con = new SqlConnection(stringConexao);

    public void conectar()
    {
        if (con.State == System.Data.ConnectionState.Closed)
        {
            con.Open();
        }
    }

    public void desconectar()
    {
        if (con.State == System.Data.ConnectionState.Open)
        {
            con.Close();
        }
    }

    public SqlConnection getCon()
    {
        return con;
    }
}

public int cadastrarAssociado (Associado assoc)
    {
        using(Conexao con = new Conexao())
        {
            using(SqlCommand comando = new SqlCommand(procCadastrar, con.getCon()))
            {
                comando.CommandType = System.Data.CommandType.StoredProcedure;

                comando.Parameters.AddWithValue("@cpf", assoc.Cpf);
                comando.Parameters.AddWithValue("@nome", assoc.Nome);
                comando.Parameters.AddWithValue("@rg", assoc.Rg);
                comando.Parameters.AddWithValue("@data_nasc", assoc.Nascimento.Date);
                comando.Parameters.AddWithValue("@endereco", assoc.Endereco);
                comando.Parameters.AddWithValue("@apto", assoc.Apto);
                comando.Parameters.AddWithValue("@cidade", assoc.Cidade);
                comando.Parameters.AddWithValue("@estado", assoc.Estado);
                comando.Parameters.AddWithValue("@email", assoc.Email);
                comando.Parameters.AddWithValue("@usuario", assoc.Login);
                comando.Parameters.AddWithValue("@senha", assoc.Senha);

                try
                {
                    con.conectar();

                    return Convert.ToInt32(comando.ExecuteScalar());

                    con.desconectar();
                }
                catch (SqlException)
                {
                    throw;
                }
            }
        }
    }

Comment: Só remover a linha! e sua classe conexão não foi implementado IDisposable?
Comment: Mas se eu remover a linha a conexão não vai fechar, Foi o IDisposable só pra quando terminar de usar o using tirar da memória
Comment: Se você implementar `IDisposable` e colocar o desconectar nele sim! porque está usando `using`;
Comment: Realmente agora me toquei, não falei que era algo bobo dispose ja é um close, kkkkk obrigado
Comment: coloquei na reposta!
Answer: Implementa a interface IDisposabe como no código abaixo:
public class Conexao: IDisposable
{
    private static string stringConexao = ConfigurationManager.ConnectionStrings["stringConexao"].ConnectionString;

    private SqlConnection con = new SqlConnection(stringConexao);

    public void conectar()
    {
        if (con.State == System.Data.ConnectionState.Closed)
        {
            con.Open();
        }
    }

    public void desconectar()
    {
        if (con.State == System.Data.ConnectionState.Open)
        {
            con.Close();
        }
    }

    public SqlConnection getCon()
    {
        return con;
    }

    public void Dispose()
    {
        desconectar();
        GC.SuppressFinalize(this);
    }
}

Remova a linha: con.desconectar();, como você utilizou o using ele vai chamar o dispose de forma transparente e automática de um objeto.
C# - Por que usar using?


Mathematica: Specifying assumptions/domains doesn't seem to work?

Question: I frequently have trouble trying to place limits on Solve or Reduce using assumptions and domains.  For example, this code:
Assuming[x > 0 && x < 1, Solve[(1 - (1 - x)^3)^3 == x, x, Reals]]

Produces results both with complex number, and with x outside the range specified.  The exact output is long (and includes the desired results), but a subset is pasted below.  What is going on?
$$\left\{\{x\to 0\},\{x\to 1\},\left\{x\to 1-\frac{\left(1-i \sqrt{3}\right) \left(\frac{1}{2} \left(-9+\sqrt{93}\right)\right)^{1/3}}{2 3^{2/3}}+\frac{1+i \sqrt{3}}{2^{2/3} \left(3 \left(-9+\sqrt{93}\right)\right)^{1/3}}\right\}\right\}$$
Answer: Solve[{(1 - (1 - x)^3)^3 == x, 0 < x < 1}, x, Reals] works fine in Mathematica 8... Reduce[{(1 - (1 - x)^3)^3 == x, 0 < x < 1}, x, Reals] is pretty much equivalent.
Comment: @JandR: As a point of note, `Solve` changed between v.7 and v.8. In v.7 the third param was for variables to eliminate, and in v.8 it is for the domain. Also, according to the [docs](http://reference.wolfram.com/mathematica/ref/Assuming.html), `Assuming` only affects those functions that have an `Assumptions` option. So, you have to include your assumptions as extra equations passed to `Solve` and `Reduce`, as J.M. shows.
Comment: Well, `Assuming[]` does not seem to be suited for use with `Solve[]` or `Reduce[]`; better to input the constraints along with the equations for these.
Comment: Hmmm.. I am on 7 right now, but I believe I had the same problem on my home computer, which has 8 (for students).  I'll double check when home.  But even if it is just for 7, I still don't get why it doesn't work.  The code we entered was exactly the same.
Comment: Hmmm... ok when I use reduce, and I do it the way you suggest, it works.  Solve still gives me complex numbers.  But, this is better, thanks!
Comment: Still have the problem in v8, but only sporatically.  I guess I'll just assume it's a bug.
Comment: I would like to disagree. Your first example does NOT work fine in Mathematica 8: In[16]:= Solve[{(1 - (1 - x)^3)^3 == x, 0 < x < 1}, x, Reals]

During evaluation of In[16]:= Solve::eqf: x<1 is not a well-formed equation. >>


Why least square problem always has solution for arbitrary b?

Question: We know from linear algebra, the least square solution of linear equation system :
$$Ax=b$$ always exists. That is, the equation
$$A^TAx=A^Tb$$ always has at least one solution.
Most of us explain it existence by interpreting least square problem as a matter of orthogonal projection. It's correct, I know. But can we prove this by showing that the rank of matrix $$A^TA$$ is equal to the rank of the augmented matrix:$$[A^TA,A^Tb]$$for any given vector b?
I've worked for hours but failed to show that.
Although there is a similar thread in mathematics.SX, but I personally think there is no good answer presented there. So I address this problem again.
Thanks at first!
[update]
Now I come up with a proof for this proposition:
suppose that rank $A^TA$=k, and the matrix $[A^TA,A^Tb]$ has one more column than $[A^TA]$, so rank $[A^TA,A^Tb]\ge k$. But on the other hand, we have $[A^TA,A^Tb]=A^T[A,b]$, using the rank inequality, we have $rank [A^TA,A^Tb]\le rank A^T$. Since (we can prove that) $ rank A^TA= rank A= rank A^T$ for any given matrix A. So the inequality is actually $rank [A^TA,A^Tb]\le k$.
Combining the two inequalities, we have $rank [A^TA,A^Tb]=rank A^TA$. Q.E.D.
Comment: @AlexR I don't think the "squareness" of the matrix implies anything about solvability of the system.
Comment: Actually all you need is that the right hand side vector of $A^TAx=A^Tb$ lies in the column space of the matrix $A^TA$ and hence this system has always at least one solution, which is not necessarily unique unless $A$ has full column rank. Obviously the fact that the matrix is square does not mean anything with respect to the fact whether this system is solvable or not.
Comment: All you need is that $A^T A$ is square to guarantee at least one solution... And $A^T A$ is square for any $A$.
Comment: @AlexR:But $A^TA$ can be not inversable
Comment: Note "at least one" solution. Else you'd need the projection argument in some form (The image of $A^T$ in the $A^T b$ does this)
Comment: @AlexR: Why the case that the rank of $A^TA$ is k-1, while the rank of $[A^TA,A^Tb]$ is k doesn't exit? can you figure it out?
Comment: If your solution is significantly different from the ones at the other question, I'd encourage you to post it as an answer to the other question, so everything is in one place the next time someone comes looking.
Comment: @AlgebraicPavel can you add why $A^T b$ is necessarily in the column-space of $A^T A$?
Answer: You can decompose $b$ into a vector $Av$ in the column space of $A$ and a vector $w$ orthogonal to that column space: $Av+w=b$. Then $A^tAv+A^tw=A^tb$. But $w$ is orthogonal to the row space of $A^t$, so $A^tw=0$, so $A^tAv=A^tb$.


How to add horizontaly aligned static text on the Y axis of a Telerik chart

Question: I have a telerik RadCartesianChart and i just want to add horizontaly aligned static text on the Y axis of the chart.
Below is the chart xaml`
<code>         <telerik:RadCartesianChart.VerticalAxis>
                <telerik:LinearAxis Minimum="-10" Maximum="100" MajorStep="10" FontFamily="Verdana" FontSize="9" ShowLabels="True" LabelFitMode="None">
                </telerik:LinearAxis>
            </telerik:RadCartesianChart.VerticalAxis>

            <telerik:RadCartesianChart.HorizontalAxis>
                <telerik:LinearAxis Minimum="1" Maximum="100" MajorStep="10" ShowLabels="True" FontFamily="Verdana" FontSize="9" >
                </telerik:LinearAxis>
            </telerik:RadCartesianChart.HorizontalAxis>

            <telerik:RadCartesianChart.Grid>
                <telerik:CartesianChartGrid MajorLinesVisibility="XY">
                    <telerik:CartesianChartGrid.MajorXLineStyle>
                        <Style TargetType="Line">
                            <Setter Property="Stroke" Value="#868686"/>
                        </Style>
                    </telerik:CartesianChartGrid.MajorXLineStyle>
                    <telerik:CartesianChartGrid.MajorYLineStyle>
                        <Style TargetType="Line">
                            <Setter Property="Stroke" Value="#868686"/>
                        </Style>
                    </telerik:CartesianChartGrid.MajorYLineStyle>
                </telerik:CartesianChartGrid>
            </telerik:RadCartesianChart.Grid>

            <telerik:RadCartesianChart.Series>

                <telerik:ScatterPointSeries Cursor="Arrow" DisplayName="Name" ItemsSource="{Binding}" ShowLabels="True" >
                    <telerik:ScatterPointSeries.XValueBinding>
                        <telerik:PropertyNameDataPointBinding  PropertyName="X" ></telerik:PropertyNameDataPointBinding>
                    </telerik:ScatterPointSeries.XValueBinding>

                    <telerik:ScatterPointSeries.YValueBinding>
                        <telerik:PropertyNameDataPointBinding PropertyName="Y"></telerik:PropertyNameDataPointBinding>
                    </telerik:ScatterPointSeries.YValueBinding>

                    <telerik:ScatterPointSeries.LabelDefinitions>
                        <telerik:ChartSeriesLabelDefinition HorizontalAlignment="Center" Strategy="{StaticResource strategy}">

                        </telerik:ChartSeriesLabelDefinition>

                    </telerik:ScatterPointSeries.LabelDefinitions>
                </telerik:ScatterPointSeries>

                <!--ScatterAreaSeries-->
                <telerik:ScatterAreaSeries XValueBinding="X"  YValueBinding="Y"   ZIndex="-200" Fill="Red" ShowLabels="True">
                    <telerik:ScatterAreaSeries.DataPoints>
                        <telerik:ScatterDataPoint XValue="0" YValue="200"/>
                        <telerik:ScatterDataPoint XValue="200" YValue="0"/>
                    </telerik:ScatterAreaSeries.DataPoints>
                </telerik:ScatterAreaSeries>

                <telerik:ScatterAreaSeries XValueBinding="X"  YValueBinding="Y"   ZIndex="-200"  Fill="Yellow" ShowLabels="True">
                    <telerik:ScatterAreaSeries.DataPoints>
                        <telerik:ScatterDataPoint XValue="0" YValue="140"/>
                        <telerik:ScatterDataPoint XValue="140" YValue="0"/>
                    </telerik:ScatterAreaSeries.DataPoints>
                  </telerik:ScatterAreaSeries>

                <telerik:ScatterAreaSeries XValueBinding="X" YValueBinding="Y"   ZIndex="-200" Fill="Green" ShowLabels="True">
                    <telerik:ScatterAreaSeries.DataPoints>
                        <telerik:ScatterDataPoint XValue="0" YValue="90" Label="Category" />
                        <telerik:ScatterDataPoint XValue="90" YValue="0"/>
                    </telerik:ScatterAreaSeries.DataPoints>
                    <telerik:ScatterAreaSeries.LegendSettings>
                        <telerik:SeriesLegendSettings   Title="Low                       Moderate               High               Significant               Critical" />
                    </telerik:ScatterAreaSeries.LegendSettings>
                    </telerik:ScatterAreaSeries>
                </telerik:RadCartesianChart.Series>

        </telerik:RadCartesianChart>`
</code>
Answer: all i needed was setting the Title property
<code>  <telerik:RadCartesianChart.VerticalAxis>
                <telerik:LinearAxis Minimum="-10" Maximum="100" MajorStep="10" FontFamily="Verdana" FontSize="9" ShowLabels="True" LabelFitMode="None" Title="This is all i needed to set">
                </telerik:LinearAxis>
               </telerik:RadCartesianChart.VerticalAxis>
</code>


how to get the submitted value of tableselect

Question: function test($form, &$form_state){
   $form = array();

   $header = array(.............);

   $values = array(.............);

   $form['table'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $rows,
      '#multiple' => $IsCheckbox,
      '#empty' => t('No users found'),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
  return $form;
} // end of function test()

function test_submit($form, &$form_state){

$selected = $form_state['values']['table'];

drupal_set_message($selected)  // displays array index (0,1,2 etc)

return;
}

How to get the selected table row values in Drupal form. Need assistance on the issue. Any help would be appreciated.
Comment: you can go thru this array using PHP foreach function
Answer: You can exclude unselected options with array_filter, e.g.
$selected = array_filter($form_state['values']['table']);

Comment: One usually works with values and not labels in form submissions, but if you absolutely need the labels then you'll need to loop through `$form['table']['#options']` and match that up against what you now have in `$selected`
Comment: That's just basic PHP, nothing Drupal-specific about it
Comment: Thank you Clive :) But $selected returns only the selected array index. How to get array values in Submit. Please assist further
Comment: I'm a newbie in Drupal. Will you please elaborate


Playing Chords per word

Question: I need help. I'm struggling to play chords per word on the piano. I love the piano and know a decent amount of information and songs on it, however i struggle with playing the chord per word.
Here is an example:

           C                               AM
Now I've heard there was a secret chord

         C                                    AM
That David played and it pleased the Lord

         F                          G                          C       G
But you don't really care for music do you

These chords i can never get correct and they always sound off. Could i be playing them wrong?
Comment: Unfortunately, your example doesn't show how the words scan timing wise. 'One chord per word' can't be the case, as there is one chord for 8 words/9 syllables, then 4 chords for 9 words/11 syllables. Can you be more clear, please? The chord shapes are o.k.
Comment: Note to others: the example song in the OP is Leonard Cohen's "Hallelujah".
Comment: That edit provides a better idea, thanks, Shev., but even so, it's not easy reading stuff written like that, unless you know the song. In which case, why read it?
Answer: You'll have trouble playing from that page, because the chords are marked at the wrong places.
Refer to the sheet music.  It will make your life much easier.
Comment: I suspect the chords were aligned better in an original version.  Formatting can fall apart when a document goes online.
But lyrics and chord symbols are merely a mnemonic for someone who knows a song.
Comment: Clarified nicely! Don't you (like me) just hate it when chords are stuck on the end of a line - no clue as to how long they last, or when to play them? And this sounds to me more like 6/8 than 12/8, certainly in parts.
Answer: In general, we don't play chords per word, Normally chords change at measure/phrase level, depending on the style, however we play notes per melody line syllables.
Check the following answer for some suggestions.
Piano Chord example
More about melody line:
In music, a song will generally have two parts, one is melody and another is chord.
Melody is the song lyric lines that we sing, while chords are the harmony music that supports the melody, normally melody will be played in the higher octave range and chords are played in the lower octave range(if we are just accompanying someone else's vocal, then we play just chords, chord in the higher range and the root of the chord in the lower range). We can assume of the melody as vocal solo and chords as background music to the vocal. In four part songs/chorals, it will have four voices generally the top voice soprano would be the melody line and the lower voices (alto, tenor, bass) would be like chords.
Normally for each syllables in the lyric words, there would be a note (melody note) assigned, (in special cases a syllable would have more that one note(melisma)), but a chord will continue for a measure/phrase,
Try the following lesson
Piano Accompaniment Styles
Comment: Hey guys, i dont think i was as clear as i could have been (and yeah the formatting changed i only just realised) what i mean to say is that i don't know where to go for the chords, do i go a higher octave, a lower octave, stay the same? I just don't know. Also when i play it, it always seems out of place and doesn't fit to the song at all. It sounds like someone forgot the chords and just pressed whichever chord they thought would work. But it doesn't. Also with the sheet music i can't find for a lot of the songs i wish to play (this isn't just about Hallelujah)
Comment: Also Bruce i think you understand what i mean, although i don't think i completely understand the melody line syllables, could you please elaborate? Thanks
Comment: updated my answer with more details.

Playing Chords per word


how do i delete or rename a step function execution in AWS

Question: we use step functions heavily - they are great - they mean that if something fails - we can fix the code or manually fix the input and then re-run it without a client ever being aware something went wrong.
So - we see failed executions as sort of like a "todo" - they don't happen very often - so when an alert tells us something failed, we bring it up, work out what to do to fix it - and fix it.
But obviously - the old failure just hangs around.   Still looking like a todo.
In the perfect world, we'd like to archive it - make it go away somewhere so it's just not in the list, but we can get at it if we wanted to.
Failing that - we'd like to delete it.
Failing that - even being able to rename it from x to [FIXED] x would help.
NOTE - deleting the whole step function isn't an option - we just want to address a single execution.
Answer: Unfortunately there's currently no way for StepFunctions to edit nor delete an execution.
If it helps, you could filter the list by status "Success" (just for aesthetics), but I know this doesn't answer the original question.
Comment: thanks - that's what my googling told me - but I was hoping someone on stack overflow would have a better answer.    Oh well - writing a chrome extension that will pretend to do it.
Answer: You can now recover a failed step function.
https://aws.amazon.com/blogs/compute/introducing-aws-step-functions-redrive-a-new-way-to-restart-workflows


Alterar coluna para indentity utilizando T-SQL no SQL Server

Question: Preciso alterar uma coluna existente em uma tabela para que ela fique com a propriedade identity utilizando T-SQL e então inserir dados nesta tabela. A coluna já contem dados e após esta inserção, devo novamente alterar esta coluna desabilitando a propriedade identity. Atualmente preciso inserir os dados manualmente, vendo qual o ultimo número inteiro (index) para completar a inserção. Como fazer isso corretamente?
Comment: quero que seja gerado automaticamente um por um desde o ultimo acrescentado, e também no final do código volte a não gerar automaticamente.
Comment: Se é o que estou entendendo veja [isso aqui](https://technet.microsoft.com/pt-br/library/bb734402(v=sql.110).aspx)`SET IDENTITY_INSERT [ database_name . [ schema_name ] . ] table { ON | OFF }`
Comment: Não entendi você que colocar o id um a um ou que ele seja gerado automaticamente?
Answer: Acho que a sua pergunta ainda está um pouco confusa, você não está apresentando o seu problema real e partindo de uma solução que pode ser inadequada. Se o campo está marcado com IDENTITY é porque ele deve possuir alguma importância de integridade ou referencial para alguma relação externa.
Contudo, se você deseja realizar um INSERT definindo manualmente esse valor seja incrementando manualmente ou preenchendo gaps que podem ter ficado depois que alguns registros foram excluídos você deve usar a seguinte instrução:
SET IDENTITY_INSERT [SUA_TABELA] ON;
GO

INSERT INTO [SUA_TABELA] (ID, Campo, ...) VALUES (4, 'Valor', ...)
GO

SET IDENTITY_INSERT [SUA_TABELA] OFF;
GO

Referência: SET IDENTITY_INSERT (Transact-SQL)
Comment: só para complementa `SET IDENTITY_INSERT [SUA_TABELA] OFF;
GO` ; no final
Comment: Editado, thanks @MarconcilioSouza
Answer: Se você que inserir um id automaticamente e depois voltar a inserir um a um você tem que usar SET IDENTITY INSERT (SQL Server Compact).
Ele permite que valores explícitos sejam inseridos na coluna de identidade de uma tabela.
Sintaxe
SET IDENTITY_INSERT table { ON | OFF }

Mais detalhes aqui
Answer: Rodrigo, até onde sei, não tem como realizar essa alteração sem excluir e recriar a coluna. E para fazer isso via script e manter os dados já existentes acho que seria inviável.
Não seria mais fácil, quando o código não for enviado pelo usuário, você fazer uma função que te retorne o ID + 1 e gravar o registro normalmente?
Comment: Vou fazer desta forma mesmo assim vou continuar procurando, mas facilitaria muito ter alguma forma de fazer isso.
Obrigado


Different treatment of parameters: lambdas vs. defines in Scheme

Question: I have two constructs that I expected to be functionally the same, but they are not and I can't figure out why.
Using define
(define (x2 . b)
  (display b)
  (newline))

(x2 3 4 5) => (3 4 5)

Using lambda
((lambda (. b)
   (display b)
   (newline))
   3 4 5) => Error: invalid use of `.'

In the R5RS, both definitions and lambdas accept . To make them behave identically I could construct the lambda like this:
((lambda b
   (display b)
   (newline))
   3 4 5) => (3 4 5)

That is one of the valid constructs listed in report's definition of formal parameters. But if I attempt to use it with define, it results in an argument number mismatch error.
(define (x2 b)
  (display b)
  (newline))

(x2 3 4 5) => Error: bad argument count

I thought (define (x y) y) was just syntactic sugar for (define x (lambda (y) y)). It seems like that is true only in most cases. Can anyone explain the rationale for the different behavior?
Answer: These expressions represent an anonymous procedure with a fixed arity:
(define (x y) y)
(define (x y z) z)

And they're equivalent to:
(define x (lambda (y) y))
(define x (lambda (y z) z))

But take this procedure, with a variable number of arguments:
(define (x . y) y)

It's only equivalent to:
(define x (lambda y y))

Continuing with the examples, this procedure has a single mandatory parameter and the others are variable:
(define (x y . z) z)

And its equivalent form would be:
(define x (lambda (y . z) z))

So, the syntax is a bit different between the implicit/explicit use of a lambda for defining procedures with a variable number of arguments, which is what the dot notation is used for in this case.
Also, syntax like '( . b) is invalid, because in this case the dot notation is representing an improper list, that is, a list whose last element is not the empty list. On the other hand, this is valid: '(a . b). This explains why the expression (lambda ( . x) x) is invalid; and given that (lambda (x) x) represents an anonymous procedure with a single mandatory parameter, we're left with (lambda x x) for representing an anonymous procedure with only a variable number of arguments and no mandatory arguments.
As far as I know the only rationale for why things are like this is by convention, and possibly because it's easier to parse.
Answer: (. arguments) is invalid syntax. The dot indicates the separation between two parts of a pair and you have no first part here. I do see that you actually mean arguments here and that it should not be a list at all.
The define that looks like this:
(define (name . arguments)
  ..)

Are the same as:
(define name
  (lambda arguments
    ..))

An example with one argument:
(define (name arg1 . arguments)
  ..)

Becomes
(define name
  (lambda (arg1 . arguments)
    ..))

The reason is simple: (cdr '(name . arguments)) ; ==> arguments and (cdr '(name arg1 . arguments)) ; ==> '(arg1 . arguments).


Venn Diagram Set Theory Question

Question: So Given that Set A and B are disjoint, then A intersection C and B intersection C are also disjoint.
Now I'm having trouble figuring out how to exactly draw That A intersection C and B intersection C are also disjoint. Would I just draw Set C in the middle of Set A & B and then A intersects with B and Set C intersects with B?
Comment: https://en.m.wikipedia.org/wiki/Disjoint_sets
Answer: I think you pretty much have it. The diagram would look something like this:
Comment: Thank you so much. I assumed that's how it looked but wasn't completely sure.
Answer: Any Venn diagram you draw will provide only an example of your claim being true. I'm not sure how much this would help to build intuition. The best way to get an intuitive grasp of this fact is probably to draw a Venn diagram with $A$ and $B$ disjoint, then try (in vain) to draw in a third set $C$ such that $A \cap C$ and $B \cap C$ intersect. A few seconds of trying to make such a diagram should make it clear why one cannot exist.
Without any visuals at all, it may help to realize that this fact follows from distributivity of set intersection: $(A \cap C) \cap (B \cap C) = (A \cap B) \cap C = \varnothing \cap C = \varnothing$.
Concrete examples also give great intuition. Take any two mutually exclusive properties to characterize the disjoint sets $A$ and $B$. Let's use wet and dry. Now, define a set $C$ with any other property, maybe purple. We know that nothing is wet and at the same time dry. It's also pretty clear that nothing is wet and purple and at the same time dry and purple.

Venn Diagram Set Theory Question


Calculating payments and APR for simple interest loans - different interest accrual methods.

Question: I work for a small financial institution as an auditor. We do various small loans that are always simple interest. Currently, we calculate payments on loans using the =PMT() method in Excel.
There are a few problems:

We state on our contracts the interest accrual method is Actual/365. However, as I understand it, the Excel =PMT() function is Actual/360.
Business wants to start accepting loans where the days to first payment can vary between 30 - 50 days. =PMT() doesn't account for this.
We already accept loans that have an odd last payment amount. =PMT() doesn't account for this.

I'm concerned we are not always complying with Regulation Z that requires the APR stated on the contract be within a certain tolerance of the actual APR when completing the calculation manually. I've spot checked a few of our loans with APRWIN which does this calculation for you (https://www.occ.gov/tools-forms/tools/compliance-bsa/aprwin-software.html) and some of them are out of tolerance. But I don't even know of APRWIN is the right tool as I don't know what interest accrual method is using do perform its calculation.
I brought all of this up internally. No one seems to know how to create a payment formula that will account for all of this. Myself included, I'm terrible at math. We have been going back and forth on the issue for months now and still no one has been able to come up with a suitable formula.
I'm very frustrated and stressed that no one is able to solve this. I'm looking for help in getting a set of formulas that will accomplish this.
I'm looking for:

A payment calculation formula that:

Uses interest accrual method Actual/365.
Can account for odd days to first payment. So, I can give the formula the contract start date and the first payment date, and the payment amount will adjust accordingly. (All other payments will be on a monthly schedule.)

Is APRWIN the right tool to use in order to verify the calculated APR if the interest accrual method is Actual/365?

If not, an APR calculation formula that works for interest accrual method Actual/365, can account for odd days to first payment, and can also account for an odd last payment amount.
Some sort of explanation as to why this works. Think of the audience as someone who has a very basic understanding of financial math. Like, they understand how to put a simple amortization table together.

Links that have been brought to my attention, but don't fully explain how these formulas may change for different interest accrual methods, or odd payment schedules:
https://stackoverflow.com/questions/9329017/calculating-apr-using-reg-z-appendix-j
https://www.fdic.gov/regulations/laws/rules/6500-3550.html
How to calculate APR using Newton Raphson
Comment: I think this question would be more suited in Economics SE
Comment: I used to work with this in car finance - maybe you could give an example of a simple interest repayment, and what the APR is that you get for that?  There is an Excel IRR function that could obtain the monthly IRR over a stream of differently sized payments, that could then be converted to APR by $(1 + i)^{12} - 1$
Comment: odd days to first payment - in EXCEL you could have a table of dates with payment amount, and a field that is daily internal rate of return - you could then use goal seek to find the irr that gives you zero present value (where the loan itself is a negative payment).
Comment: you could use Newton Raphson, but is seems a bit fiddly, goal seek in Excel will just guess until it gets the answer super quickly with modern computers.
Answer: With Goal Seek - I put some formulae behind the scenes to work out number of days old the loan was, and multiplied by $(1 + i)^n$ to get a stream of present values, then used goal seek to get i - finally annual rate (APR?) is $(1+i)^{365} - 1$

that's an idea - however I notice your US financial regulations have all sorts of rules to do with days and converting them into fractions of months - but the general idea could still be used.
Comment: Could you be a little more clear?
Comment: no not really, The question was too general to address really - and he never came back
Answer: Excel's financial functions absolutely can't properly handle an unusual days to first payment, but it's easy to do manually.
Check out https://www.bankersonline.com/forum/ubbthreads.php/topics/1403020/constant_payment_amount_loan_c.html
Here's my implementation in pseudocode, works really well and matches the hundreds of banks I work with:
<code>var dailyRate = InterestRate / 36500;
var longdays = DaysToFirstPayment - 30;
var principle = AmountFinanced;
var odddaysint = longdays * dailyRate * principle;
var r = InterestRate / 1200;
var c = Pow(1.0 + r, NumberOfPayments); // 1+r ^ NumberOfPayments
var adjustedPrincipal = AmountFinanced + odddaysint;
var A = adjustedPrincipal * r * c / (c - 1);
Payment = Round(A, 2); // 2 decimal places
</code>
I am assuming monthly payments.  This should be easy to adapt to Excel.
DaysToFirstPayment is the # of days from the start of the loan until the first payment is due.
I'm not addressing the APR issue.


Load nodes into div using AJAX

Question:
I've created a views block that loads all nodes of a certain content
type.
I've added the Content: Has taxonomy term ID contextual filter

This works great. In the preview area if I change the value in the "preview with contextual filters" input field it changes the nodes that load below according to which taxonomy term ID I input.
How can I have this same functionality on a normal Drupal page?
I will have a list of links on the page with an href value of the taxonomy term ID. When I click a link, I need it to load all nodes that have been associated with that particular taxonomy term into an empty div using AJAX.
I've read somewhere on here that if the nodes just contain some basic text then using a pure AJAX solution might not be the best but rather accomplish the same thing using views.
Comment: Which version of Drupal are you using?
Answer: Here is the javascript I ended up using to load a views block using AJAX and pass in a contextual filter from the href value of given link on page.
<code>function getInfo(args) {

  $.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
      view_name: 'agent_lookup',
      view_display_id: 'agent_lookup_block', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#ajax-target').html(viewHtml);
        //Drupal.attachBehaviors(); //check if you need this.
      }

    },
        error: function(data) {
         alert('An error occured!');
        }
  });
}

$('.ajax_button').once().click(function(e){
    e.preventDefault();
    var the_id = $(this).attr('href');
    noSlashes = the_id.replace(/\//g,'');
    getInfo(noSlashes);
});
</code>
Answer: Sounds like removing the contextual filter and instead exposing the taxonomy term filter in your view could be what you need.
Or for a more complicated solution, this could work well.
http://www.stevepolitodesign.com/blog/load-content-drupal-ajax-without-coding

Load nodes into div using AJAX


Lag with CALayer when double tap on the home button

Question: When I put shadow etc. with CALayer my app is lagging when I double tap on the home button to see tasks running. I don't have any other lag, just when I double tap.
I call this method 20 times to put 20 images :
- (UIView *)createImage:(CGFloat)posX posY:(CGFloat)posY imgName:(NSString *)imgName
{
    UIView *myView = [[UIView alloc] init];

    CALayer *sublayer = [CALayer layer];
    sublayer.backgroundColor = [UIColor blueColor].CGColor;
    sublayer.shadowOffset = CGSizeMake(0, 3);
    sublayer.shadowRadius = 5.0;
    sublayer.shadowColor = [UIColor blackColor].CGColor;
    sublayer.shadowOpacity = 0.8;
    sublayer.frame = CGRectMake(posX, posY, 65, 65);
    sublayer.borderColor = [UIColor blackColor].CGColor;
    sublayer.borderWidth = 2.0;
    sublayer.cornerRadius = 10.0;

    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = sublayer.bounds;
    imageLayer.cornerRadius = 10.0;
    imageLayer.contents = (id) [UIImage imageNamed:imgName].CGImage;
    imageLayer.masksToBounds = YES;
    [sublayer addSublayer:imageLayer];

    [myView.layer addSublayer:sublayer];

    return myView;
}

I have commented all my code except this, so I'm sure the lag comes from here. Also I've checked with the Allocations tools and my app never exceeded 1Mo. When I'm just putting images without shadow etc. everything works fine.
Answer: Try setting a shadowPath on the layer as well. It will need to be a rounded rect since you've got rounded corners on your layer.
CALayer has to calculate where it is drawing, and where to put the shadow, if it doesn't have a shadow path. This has a big effect on animation performance.
Another way to improve performance with CALayers is to set the shouldRasterize property to YES. This stores the layer contents as a bitmap and prevents it having to re-render everything.
Comment: I tried to add this :
UIBezierPath *path = [UIBezierPath bezierPathWithRect:sublayer.bounds];
    sublayer.shadowPath = path.CGPath;

But it doesn't change anything. Am I doing something wrong ?
Comment: No, that's what I meant. Sorry it doesn't help. Is there a reason you're using two layers added to a view's existing layer instead of, say, creating a UIImageView and changing the properties of its layer? That would probably have better performance.
Comment: No reason at all, I just followed a tutorial. I'm gonna try with an UIImageView and tell you back. Thanks for your help.
Comment: ok I remember why. Cause when I work with UIImageView, I have a bug with cornerRadius. I have white rect part all around my radius corner. I can join a screenshot if you doesn't understand what I mean. So I made a "container" all around my image to have a proper radius. Whatever, I tried with an UIImageView (I have the corner radius bug) and when I commented this line : imgView.layer.cornerRadius = 10.0; my program doesn't lag anymore. So the lag doesn't come frome shadow but from my weird bug. Any ideas ?
Comment: I'm sure it's the complexity of the layers. Try shouldRasterize, see edited answer.
Comment: Yeah I already tried it but my images looks bad and still lagging but less than shouldRasterize set to NO
Comment: I'm running out of ideas then. Is the image a different size to the view you are putting it in? Have you profiles using the time profiler in instruments?
Comment: My images are larger than the view. And for time profiler, I never used it. And again, thanks for your time.


How to evaluate $\int_{-1}^1 \int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}} \frac{2}{(1+x^2+y^2)^2}dydx$

Question: Problem: Evaluate the integral
$$\int_{-1}^1 \int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}} \frac{2}{(1+x^2+y^2)^2}dydx$$
I am having a hard times understanding this concept and I couldn't solve this question. I was stuck at changing the cartesian to polar. Thank you for helping.
Comment: Hi, welcome to Math SE. This isn't an "unusual" Cartesian-to-polar problem. More generally$$\int_{-a}^a\int_{-\sqrt{a^2-x^2}}^\sqrt{a^2-x^2} f(x,\,y)dydx=\int_0^{2\pi}\int_0^arf(r\cos\theta,\,r\sin\theta)drd\theta$$for $a>0$.
Comment: Welcome to Math stack exchange. Can you please put in your attempt at solving the solution. Your description of what you tried is unclear.
Comment: Hint: draw the region of integration.
Answer: Recall polar coordinates are defined as $(x, y) \mapsto (r \cos(\phi), r \sin(\phi))$. It is an easy exercise to show that the determinant of the Jacobian reads $r(\cos(\phi)^2+\sin(\phi)^2)$.
Let us denote the integral by $I$. Substitute according to the rule given above and obtain
$I = \int_{r=0}^{1} \int_{\phi=0}^{2\pi} \frac{2}{\left(1+r^2\right)^2} r d\phi dr$.
I'll leave it as a tiny exercise for your to derive the boundaries of the intergral. In case you're not sure how to obtain them, a sketch might help!
Now we see, that we can directly carry out the integral over $\phi$ and obtain
$I = \int_{r=0}^{1} \frac{4\pi}{\left(1+r^2\right)^2} r  dr$.
It remains to calculate the integral over $r$. A simple substitution $t:=1+r^2$ yields
$I = \int_{t=1}^{2} \frac{2\pi}{t^2} dt = \pi$, where I leave the intermediate steps (like correctly determining the boundaries I gave) as an exercise.
Comment: Thank you it was very explaining!


What does a direct sum of tensor products look like?

Question: I understand that tensor product is distributive over direct sums, but what happens when we have $(v_{1}\otimes w_{1})\oplus (v_{2}\otimes w_{2})$?
Comment: No useful simplifications can be made. It's exactly like when we have an expression of the form $ab + cd$ in ordinary algebra. That's true whether you're talking about vectors or vector spaces here.
Answer: Since you mention direct sums, I assume that $v_1,v_2,w_1,w_2$ are vector spaces (even though spaces are usually denoted by upper case letters)
There is no general formula for such case (see the last proposition). This is because there no distribution of addition over multiplication for numbers (real or integers).
On the level of dimensions we know that
$$\dim(V\otimes W)=\dim(V)\dim(W)$$
and
$$\dim(V\oplus W)=\dim(V)+\dim(W).$$
Thus
$$\begin{split}\dim((V\oplus W)\otimes Z)&=(\dim(V)+\dim(W))\dim(Z)\\
&=\dim(V)\dim(Z)+\dim(W)\dim(Z)\\
&=\dim(V\otimes Z)+\dim(W\otimes Z)\\
&=\dim((V\otimes Z)\oplus(W\otimes Z)).\end{split}$$
So in this case, by looking at dimensions, we can guess what $(V\oplus W)\otimes Z$ should be isomorphic with.
On contrary, we do not have a law that says $ab+c=ac+bc$. So we cannot make a transformation on the level on dimensions, cause we are stuck at the first step.
$$\dim((V\otimes W)\oplus Z))=\dim(V)\dim(W)+\dim(Z)$$
More concretely, let $\dim(V)=2$, $\dim(W)=3$ and $\dim(Z)=5$. So
$$\dim((V\otimes W)\oplus Z))=11$$
and it is a prime number. So it cannot be of the form $X\otimes Y$, where $X,Y$ are some combination of $V,W,Z,\oplus,\otimes$ and brackets.
On the other hand, for $\dim(V)=\dim(W)=\dim(Z)=1$ we have that
$$\dim((V\otimes W)\oplus Z))=2.$$
Thus if $(V\otimes W)\oplus Z$ is presented as direct sum, it need to have at most $2$ components. This means that the only possibility is that $(V\otimes W)\oplus Z\cong X\oplus Y$ with $X$ and $Y$ being combination of $V,W,Z$ and $\otimes$.
Thus, we conclude

Proposition. If there is a way of presenting $(V\otimes W)\oplus Z$ as a combination of $V,W,Z,\oplus,\otimes$ and brackets that works for $V,W$ and $Z$, then it is of form $X\oplus Y$ where $X$ and $Y$ is a combination of $V,W,Z$ and $\otimes$.

Going back to the case where $\dim(V)=2$, $\dim(W)=3$ and $\dim(Z)=5$ we look at all possible summands of $11$ and we try to fit $X$ and $Y$ according to this decomposition.
$1+10=11$. This case will not work, because all $V,W,Z$ have dimensions greater then $1$. Thus IMPOSSIBLE!
$2+9=11$. In this case $X$ has to be $V$. However there is no way to write $9$ dimensional vector space $Y$ in terms of $V,W,Z,\otimes$ such that $X\oplus Y$ would posses all spaces $V,W,Z$. Thus IMPOSSIBLE!
$3+8=11$. In this case $X$ has to be $W$. However there is no way to write $8$ dimensional vector space $Y$ in terms of $V,W,Z,\otimes$ such that $X\oplus Y$ would posses all spaces $V,W,Z$. Thus IMPOSSIBLE!
$4+7=11$. In this case $X$ has to be $V\otimes V$. However there is no way to write $7$ dimensional vector space $Y$ in terms of $V,W,Z,\otimes$. Thus IMPOSSIBLE!
So we are left with $5+6=11$. However, by looking at the dimensions we see that the only way to write it, is by putting $X=Z$ and $Y=V\otimes W$. And this is precisely our starting point (but with just position changed).
Thus, we finally conclude

Proposition. There is no other representation of $(V\otimes W)\oplus Z$ in terms of $V,W,Z,\oplus,\otimes$ and brackets that works for all vector spaces $V,W,Z$.


Is there a way to copy the content of a text file generated while Jenkins execution into Slack

Question: I am new to Jenkins, exploring......
My problem statement is,
After Jenkins execution, a text file(Output.txt) is being generated into Workspace. The requirement is, I want to copy the contents of that .txt file and print it on Slack notification message.
I tried to create an "Execute Shell" inside that I wrote:
echo myVar=Property \> Something\\bin\\Release\\Output.txt

After that I used the EnvInject plugin, inside that in properties file path I have given the full path of Output.txt
In post-build build-action, I have selected Slack notification, in custom message I have written:
Data is- $myVar
Data is- $Property

Now When I am executing this Job I got Slack Notification, but didn't got the data of Output.txt.
I got this on Slack:
Data is- $myVar
Data is- $Property

What I am expecting, if Output.txt hold hello world then I want:
Data is - hello world

in Slack notification.
Comment: There is a plugin with simple usage of sending slack notifications via Jenkins...
https://plugins.jenkins.io/slack/
Comment: Thanks for your Answer. I know that but how to use the Contents of a text file that is in Jenkins Workspace into the Slack Notification plugin.
Comment: Do you want to attach it as a file or reading and writing to a message?
Comment: No, I do not want to attach the file with a slack notification. The Only thing I want is to print the content of Output.txt in Slack Notification. So, My Concern is about how to fetch the data from that Output.txt(Basically this file holds some data which is coming from API ) and print it into Slack (With the help of the plugin present in Post-build Action). Thanks in Advance!!
Answer: upload file .txt
Read .txt in jenkins
I think the best option is to read the .txt in jenkins, pass it to a variable and place it in the notification
Comment: Thanks for the Answer Alex, Would you please elaborate on how to read a text file from Jenkins Workspace and store it in a variable (As the Content inside Output.txt might be of Multiple Strings ).  And how to use that Variable in the Slack Notification Part. (As One Variable defined in One section bounded within the Section). Thanks in Advance!!


T-test: is the difference of the means in my sample's two subgroups equal to a given difference of means?(SPSS)

Question: I've recently reread the section about t-test, comparing means in two independent subgroups and know the formula, how to compute the t-coefficient.
Now I'm facing the question, whether the difference in my subgroups is the same as the difference, given by some other, larger study. In the t-formula it is easy to insert the theoretical difference of means - just put in the numerator of
$$ T = { \bar x_1 - \bar x_2 \over \cdots} $$ the theoretical difference
$$ T = { (\bar x_1 - \bar x_2) - (\mu_1-\mu_2) \over \cdots} $$
(if I recall the formula correctly).
But I don't find an option in SPSS to insert that theoretical difference in the calculation.

Q: Is there any procedure to get that comparision or at least some workaround in SPSS?

Rereading the section in "Bortz, Statistik für Sozialwissenschaftler" it seems, that it could be a workaround, to simply "correct" for the theoretical difference. For instance if I have the theoretical difference of means being 2.5 (years of age of the groups of male and female students, male being 2.5 years older than the female in the larger study) then I could add 2.5 to the means of the female students (if (sex=1)age=age+2.5 .) and test for difference=0 now. Is that a meaningful option?
Comment: Why would you treat the other study as it were a population, when it, too is based on a sample? Why is its own uncertainty not taken into account in your test?
Comment: @Glen_b: it is very easy to imagine, that the "larger study" is some survey of the census with a good exhaustion of the population and that one can find the very accurate estimate for the population in some journal's article. Then there is a class for introductory statistics where students take some (likely ad-hoc) sample with two groups and want to learn how to do the following task: test whether their heuristical difference of means deviates from the "theoretical"/"reference" one - according to the simple formula like in Bortz, but of course also in wikipedia et. al., using i.e. SPSS...
Answer: Yes, if you subtract the hypothesized difference from the first group and test for a difference of 0 it's the same as testing for the hypothesized difference -- or as you suggest, add the hypothesized difference to the second group and test for a difference of 0.
Indeed either of those approaches is simply a rearrangement of the numerator:
Let $\delta = \mu_1-\mu_2$, then
$ (\bar x_1 - \bar x_2) - (\mu_1-\mu_2)$
$\quad=  (\bar x_1 - \bar x_2) - \delta$
$\quad=  (\bar x_1- \delta) - \bar x_2 \qquad$  (1)
$\quad=  \bar x_1 - (\bar x_2+ \delta) \qquad$  (2)


Execute function on submit if form is validated

Question: Relative beginner at JS, wanting to run a button animation function when the submit button is pressed, but only if the form is validated.
Here's the code:
HTML
<form id="contact-form" method="post">
...
<button class="btn" type="submit" id="submit" name="submit">Send</button>
</form>

JS:
const name = document.getElementById("name");
const email = document.getElementById("email");
const message = document.getElementById("message");
const contactForm = document.getElementById("contact-form");
const errorElement = document.getElementById("error");
const successMsg = document.getElementById("success-msg");
const submitBtn = document.getElementById("submit");

const validate = (e) => {
  e.preventDefault();

  if (name.value.length < 3) {
    errorElement.innerHTML =
      "Your name should be at least three characters long.";
    return false;
  }

  ... /*various other rules for form fields */

  if (message.value.length < 15) {
    errorElement.innerHTML = "Please write a longer message.";
    return false;
  }

  errorElement.innerHTML = "";
  successMsg.innerHTML =
    "Thank you! I will get back to you as soon as possible.";

  e.preventDefault();
  setTimeout(function () {
    successMsg.innerHTML = "";
    document.getElementById("contact-form").reset();
  }, 6000);

  return true;
};

const emailIsValid = (email) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};

submitBtn.addEventListener("click", validate);

// Event listeners

/* $('.btn').on('click', toggleBtn); */

/* THE ANIMATION TRIGGERED BY CLASS CHANGE */
function toggleBtn() {
  alert("working");
  btn = this;
  btn.classList.add("is-active");
  setTimeout(function () {
    btn.classList.remove("is-active");
  }, 2500);
}

Have tried various 'if' statements and combinations, but can't quite get there!
Any help very welcome.
Answer: You should use the submit event of the form and cancel it. After you're done with validation and animation, you can form.submit() to submit, this time for real.

const contactForm = document.getElementById("contact-form");
const submitBtn = document.getElementById("dont-name-submit");

function validate(form) {
  var input = form.querySelector("[name=tetris]");
  if (!input.value) {
    input.classList.add("invalid");
    return false;
  }
  input.classList.remove("invalid");
  return true;
}

contactForm.addEventListener("submit", function(ev) {
  ev.preventDefault();

  // do validation
  if (!validate(contactForm)) {
    return;
  }

  // do animation
  submitBtn.classList.add("is-active");
  setTimeout(function() {
    submitBtn.classList.remove("is-active");

    actual_submit();
  }, 2500);

})

function actual_submit() {
  $.ajax({
    type: 'post',
    url: 'https://matt-rudd.com/message.php',
    data: $('form').serialize(),
    success: function() {
      alert('form was submitted');
    }
  });
}
.btn {
  transition: 2s;
  transform: scale(1)
}

.is-active {
  transform: scale(2)
}

.invalid {
  background: rgba(255, 128, 128, 0.9);
  border: 1px solid red;
}

<form id="contact-form" method="post">
  try submitting this required field empty:

  <input name="tetris">

  <input class="btn" type="submit" id="dont-name-submit" value="Send">
</form>
Comment: Thanks - still having an issue with my errors not working - down to this toublesome line 89:

`submitBtn.addEventListener("click", validate);`

Code section:

`contactForm.addEventListener("submit", function(ev) {
  ev.preventDefault();

https://codepen.io/matt-rudd/pen/LYdjQrN

  // do validation
/* ISSUE IS WITH THIS NEXT LINE - not working! */ submitBtn.addEventListener("click", validate);
  // do animation
  btn.classList.add("is-active");
  setTimeout(function () {
    btn.classList.remove("is-active");
  }, 2500);
  // then submit
})
/// AJAX FOR PHP FORM SEND`
Comment: Full code: https://codepen.io/matt-rudd/pen/LYdjQrN
Comment: You had 2 event handlers for `submit`. I modified my example a bit hope it makes more sense.
Comment: Thanks - I've tried those amendments but I'm still not able to get my own validation messaging live... just the generic pop-ups (not sure where they come from - perhaps hard-coded into the browser on detection of form element?)

I know live links are likely frowned upon here but would appreciate you taking a look to see if you can spot any glaring errors?

https://codepen.io/matt-rudd/pen/abYyVbN

Spent hours trying various options so thanks a ton for this help!
Comment: still baffled why submitBtn.addEventListener("click", validate); prevents the reset of my code from running?

When this line is commented out, code below it runs and the email sends.
Comment: I got a "Your message has been sent" when I checked it. You are not supposed to validate using `confirm()` but using your own logic. But since fields are marked as `required` you don't have to validate at all. So remove the `confirm` section.
Comment: Hey, thanks - but removing the confirm section leaves me with the same issue - the emails send ok but I get the default required messages (white box popups) instead of the custom text messages flashing up below the button as desired.

It's either include line 105 and the error/success messaging works but the submit animation and email send doesn't fire - or comment out and the submit button and email send works but not the custom error messaging.

Hopeful there's a way to get all three elements working together - just not sure how to code that.
Comment: The default required messages appear if you add `required` to the inputs. Otherwise you should apply your own logic for validating. If validation fails, you should `return` and not continue to `actual_submit()`
Comment: Ah I see. Have removed the 'required's.

I've reached the limit of my JS knowledge so far, when it comes to the validation bit though.

I think I'm fairly close to understanding this!

The custom validation code beginning 'const validate = (e) => {
  e.preventDefault();' (line 56) ends in return: true.

Then 'submitBtn.addEventListener("click", validate);' runs the validation code.

What I need to do is figure out how to run the rest of the code (button animation and email send) if that 'validate' returns 'true'.
Comment: I think what's throwing me here is this portion: `const validate = (e) => {
  e.preventDefault();`

I'm more familiar with standard `function ...() {`

Here's the pen again if you are able to spare a few more minutes unpacking this for me!

https://codepen.io/matt-rudd/pen/RwMxRwa
Comment: I have updated the snippet here. See if it makes more sense.
Comment: WONDERFUL! Thank you - it was the simple syntax of the validation if statement I wasn't familiar with.

i see how you converted it into a more straight forward function - the only casualty of this is I then lose the form reset after submission.

So I need to work out how and where to add this back in:

`setTimeout(function () {
    successMsg.innerHTML = '';
    document.getElementById('cf').reset();

  }, 6000);`

Huge thanks for your help here!
Answer: Put required in the inputs you want to be validated. Read more

testForm.addEventListener('submit', (e) => {
  e.preventDefault();
  testForm.classList.add('expanded')
})
form {
  transition: 600ms ease-out;
}

form.expanded {
  transform: translateX(50px)
}
<form id="testForm">
   <input required type="text"><button>submit</button>
 </form>
Comment: That's great, thanks loads! That got my animation working.

So nearly there... The only problem I have now is that broke my custom error messages that appear in text below the button (my preferred way of displaying 'required').

Perhaps a Codepen best to illustrate?

https://codepen.io/matt-rudd/pen/eYMEJQj

Seems to be a conflict with the const on line 7 and the class/id of the button element?

Would be great to get both the required text notices and button animation on validation working together if poss!
Comment: @MattRudd  Ahh, in that case, then the other answer is better suited for that application. The key is to stop execting the submit event handler (`return`) when your validate function returns false
Comment: ok thanks loads for your help.


Monitorar Diretório com Java Web

Question: Estou trabalhando em uma aplicação Java Web, utilizando o servidor Apache Tomcat e tenho a necessidade de monitorar, ou "ouvir" um diretório no servidor. De forma assíncrona, e permanente. Pois quando um arquivo for criado neste diretório, eu preciso examinar e mover o mesmo para o diretório correto.
Eu até consegui utilizar o Watch Service API, porém consegui funcionar somente para uma aplicação java local (jar).
Há possibilidade de utilizar para web? Ou existe alguma outra maneira mais eficaz?
Comment: Segue o link da minha duvida http://pt.stackoverflow.com/questions/116281/monitoramento-de-diret%C3%B3rio-faz-o-sistema-parar-de-responder-a-intera%C3%A7%C3%B5es
Comment: não sei o seu caso mas eu estou tendo problemas quando inicio o watch preciso fazer alterações no visual e isso não acontece até mesmo minha aplicação swing não fecha depois de ativo. Estou procurando uma solução mas sem sucesso.
Comment: @DevAgil consegue postar melhores detalhes do problema ou do código mesmo?
Answer: Atenção com a versão do Java
Sim, pode utilizar para aplicação Web Sim, sem problemas, até mesmo por que está na plataforma Java SE. Só se atente par ao fato da versão Java, vc deve usar no mínimo a versão 1.7 da plataforma. Então cheque se o servidor Web ou EE está de acrodo com essa versão do Java. Dependendo da versão do Tomcat, pode ser que vc não consiga usar.
O Watch Service é muito poderoso, deve te atender perfeitamente.
Comment: Ai depende muito do design da sua aplicação, realmente é difícil eu te dizer a frio. Por exemplo, eu não sei se vc estará usando EJBs, outros frameworks. Em fim, o que eu recomendaria é vc Startar o serviço no Init do seu Servlet Mapeado no Web.xml, colocando um Thread lá, mas novamente, é muito difícil dizer sem ter todos os detalhes em mão. E é claro podem surgir diferentes soluções e abordagens. Eu começaria pensando no init do Servlet
Comment: Legal @FilipeGonzagaMiranda, e como eu posso deixar ela executando permanentemente após o deploy? Necessito do uso de threads?
Comment: Acredito que o Init do Servlet ajuda, é uma aplicação web (servlet) simples mesmo, apenas com o objetivo de monitorar um diretório, analisar os arquivos e mover para os diretório destino. Nada de EJB ou outros frameworks. Obrigado

Monitorar Diretório com Java Web


Format a date so it can be written into Oracle ("Not a valid month" error)

Question: Having trouble with finding the proper syntax for this.  Here's my field on the ASP side:
<input type="text" id="EI_Open_AuditStartDt" class="datepicker" runat="server"
    name="EI_Open_AuditStartDt" value='<%#Eval("Audit_Start_Date") %>'
    style="width: 100px" />

Here's part of my code-behind in C#:
HtmlInputText EI_Open_AuditStartDt = (HtmlInputText)DataGrid_Open.Rows[e.RowIndex].FindControl("EI_Open_AuditStartDt");
TextBox EI_Open_TransCIT = (TextBox)DataGrid_Open.Rows[e.RowIndex].FindControl("EI_Open_TransCIT");

string StartDt = String.Format("{0:dd-mmm-yyyy}", EI_Open_AuditStartDt.Value);
string TransCIT = EI_Open_TransCIT.Text;

DataGrid_RootCauses.EditIndex = -1;

OracleConnection conn = GetConnection();
try
{
    using (OracleCommand cmd = new OracleCommand("CST_AMR_WRITE_OPENSTATUS", conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        using (OracleDataAdapter da = new OracleDataAdapter(cmd))
        {
            cmd.Parameters.AddWithValue("v_StartDt", OracleType.DateTime).Value = StartDt;
            cmd.Parameters.AddWithValue("v_TransCIT", OracleType.VarChar).Value = TransCIT;

The problem is, when it gets to string StartDt, it still sees the value as, say, "03/24/2017" instead of "24-MAR-17", so I'm getting the "Not a valid month" error.
Can anyone see what I'm doing wrong?
Comment: My guess is that the stored procedure is taking a string rather than a date argument.
Comment: @GordonLinoff Wouldn't it say not a valid date instead of month? You're most likely right either way because it says `OracleType.DateTime` and theres a string being inserted (can't be good?)
Comment: Well, this makes sense.  So how would I format that properly so it can be passed as a date?
Comment: I'd suggest using [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. i.e. `yyyy-MM-dd`
Comment: As I understand error raised from Oracle DB, it means that oracle `NLS_DATE_FORMAT` differs from `dd-mmm-yy`. if have access to oracle procedure you can set there `execute immediate 'alter session set nls_date_format = ''dd-mmm-yy''';` this command , or you can execute it from client side in the same session, or change string literal format to db format. I guess your DB format is `DD/MM/YY`.
Comment: I can confirm the Oracle data type is "DATE".  So, if anyone knows the correct syntax to use to convert a value in C#/ASP from MM/DD/YYYY to the proper format in Oracle, I'd appreciate it.
Answer:
Verify the format of the data stored in the Oracle DB.
Attempt to insert the data as a raw string, in that format and see if it succeeds.

That takes your calling code out of the possible variables affecting your problem.

If that still doesn't work, you have to look at the stored procedure and figure out if it's converting formats without your knowledge.
If you don't have the ability to see the stored procedure, you are going to have to try a bunch of different formats in your calling code until you find the right one.
Answer: I would suggest inserting the value using ISO 8601 format - i.e. yyyy-MM-dd
var StartDt = Date.ParseExact(EI_Open_AuditStartDt.Value,"dd-MM-yyyy", CultureInfo.InvariantCulture););
//.....
cmd.Parameters.AddWithValue("v_StartDt", OracleType.DateTime).Value = StartDt.ToString("yyyy-MM-dd");

Although, there is a good chance that you could do away with the date formatting in the param add, and simply hand it the StartDt object.
cmd.Parameters.AddWithValue("v_StartDt", OracleType.DateTime).Value = StartDt;

Answer: format in C# var StartDt = Date.FormatExact(EI_Open_AuditStartDt.Value, "DD/MM/YY"); or if to be exact to format of your database nls_date_format.
Or you can use c# DateTime  and do following , note that function returns bool, you can check it in if operator and then assign myDTvar to command parameter.

DateTime myDTvar;
DateTime.TryParseExact(StartDt, "dd-mmm-yyyy", null,
                                   DateTimeStyles.None, out myDTvar)
Answer: I came up with this, and it worked:
DateTime dt1 = Convert.ToDateTime(EI_Open_SubmissionDt.Value);
var SubDt = String.Format("{0:dd-MMM-yyyy}", dt1);

Would anyone with more C#/Oracle experience than I (which is pretty much everyone) care to poke holes in it?  Is this a legitimate answer, or are there potential issues with it?


jquery datepicker: alert when certain days are clicked on the jquery datepicker

Question: i have a certain dates that come from database and want to block those dates from selecting, how would i do that?
like Alert when certain days are clicked on the jquery datepicker?
i am using asp.net C#. and pass the dates from server side to client?
any help?
Answer: I think you would have to use the onSelect event of the datepicker to do this.
Per Jquery Documentation:
<code>$('.selector').datepicker({
   onSelect: function(dateText, inst) { //check for date and show alert }
});
</code>
HTH
Comment: i am more interested to know returning the data from server to client
Comment: You can use Jquery .ajax and return all the dates to be stored in the client end (say a hidden control).
Comment: @Raja: can you show me some sample lines how would you go after?
Comment: its interesting that you think it can be done (not sure how) but other says it cant (http://stackoverflow.com/questions/2695961/jquery-datepicker-disable-federal-holidays). if you have done similar then share me how you have achieved and very much interested to know.
Comment: I totally agree with them. There is no such thing as disabling a date in the datepicker. Your question was to give out an alert. The way you do it is when the date is selected (using select method) you check it with predefined dates (say federal holiday which you bring it using ajax) and give out an alert that the date cannot be picked. HTH
Answer: var disabledDates = ['04/30/2010', '05/01/2010'];
$(function(){
<code>$('#datepicker').datepicker({

    dateFormat: 'dd/mm/yy',
    beforeShowDay: editDays
});

function editDays(date) {
    for (var i = 0; i < disabledDates.length; i++) {
        if (new Date(disabledDates[i]).toString() == date.toString()) {
             return [false];
        }
    }
    return [true];
 }
</code>
});


Is this a reasonable use of hook_user_presave?

Question: The documentation for hook_user_presave says that

This hook is primarily intended for modules that want to store properties in the serialized {users}.data column [...]

Instead, I'm using it to check that a change of email address does not clash with any email address in a database separate from the database for my drupal site. If it does, I do
$edit['mail'] = $account->mail;

so that the update to mail does not go through, but the rest of the edit is unaffected. (I also put up a warning message, under the assumption that the only time the email changes is when someone changes it manually.)
With anything web-related being outside my usual field, I'm not sure if using this method in a different way than intended is too clumsy or unsafe. Is it ok to use this method in this way?
Answer: If you look at the documentation page for Drupal 8, you will notice that sentence is not used anymore.

Act on a user account being inserted or updated.
This hook is invoked before the user account is saved to the database.
Modules that want to store properties in the serialized {users}.data column, which is automatically loaded whenever a user account object is loaded, may add their properties to $account->data in order to have their data serialized on save.

The fact the hook has different parameters in Drupal 8 doesn't change its purpose. In fact, with Drupal 8 you could use the following code.
$account->mail = $account->original->mail;

$account->original contains the value returned from entity_load_unchanged().
Although on Drupal hook_user_presave() is normally used for the purpose you noticed, you could use it for the purpose you described.
The alternative would be to add a form submission handler to the user edit form which is executed before the default form submission handler. The pro of using hook_user_presave() is that it works also when a module programmatically save a user object using user_save().
Comment: I notice that the Drupal 8 version has different parameters, and doesn't look like it can be treated the same way I'm treating this version. I.e. `$edit` and `$account` as being separate and different from one another.
Comment: The different arguments accepted from the hook don't change its purpose. What you are trying to achieve can be achieved also with Drupal 8; see the updated answer.
Comment: Obviously, I need to learn to navigate the documentation better. :)


What is the relation between "derivations" and the "derived subalgebra" of a Lie algebra?

Question: As I understand the term "derivation" in the context of Lie Algebra $L$ is a $\delta\in End(L)$ such that $\delta$ satisfies "Leibniz's rule" or what is often called product rule for differentiation.
The derivations form a Lie-subalgebra of $End(L)$ under the Lie-bracket.
There is also the derived subalgebra which is the Lie-subalgebra generated by $\{ [x,y]:x,y\in L\}$. It is somewhat analogous to the derived subgroup.
My question which I think is quite natural is what is the exact relationship between a derivation and derived subalgebra. Or to put it more clearly, since these names are very similar there must be some kind of relationship. (I thought that the set of derivations $Der(L)\subset End(L)$ is a derived subalgebra of $End(L)$. i.e. $Der(L)=[End(L),End(L)]$. But I am pretty sure, this is not quite true.
Answer: No, $Der(L)$ need not be $[End(L),End(L)]$. For an abelian Lie algebra $L$ of dimension $n$ over $K$ we have $Der(L)=End(L)$, but
$[End(L),End(L)]=[M_n(K),M_n(K)]$, which is the vector space of traceless matrices of size $n$.
The derived ideal $[L,L]$ equals $ad(L)(L)$, where $ad(L)$ is the space of inner derivations.
Comment: Thank you. Then, is there no explicit relationship between the two similarly coined terms
Comment: Apparently not; the name "derived", see [here](https://math.stackexchange.com/questions/1331357/origin-of-the-term-derived-subgroup) might not come from "derivation", but of course the derivative is essential for the correspondence between Lie groups and Lie algebras.


Access all children of a certain node with simplexml and php

Question: I have a question and the answer is sure simple, but it just lacks of understanding from my side.
I have a xml file with following look (short example)
<item id="1234">
    <property name="country_id">
        <value>4402</value>
    </property>
    <property name="rc_maintenance_other">
    </property>
    <property name="claim_right_shareholder">
    </property>
    <property name="charges_other">
    </property>
    <property name="other_expenses_heating">
    </property>
    <property name="unpaid_bills_amount">
    </property>
    <property name="iv_person_phone">
        <value>03-6756711</value>
    </property>
</item>
<item id="9876">
   ...
</item>

My problem is, I want to read all propertys from the one item with the id 1234 with their attribute and their value, if exists, in an array.
I know how to access the certain Item with xpath. (Thanks to this wonderful stackoverflow community :) )
But how can I use the children() function only to a certain item?
Like this
foreach ($item[id="1234"]->children() as $property) {

Thank you so much!
Comment: First write the code how to access the *item* element you want the children from. Store it in a variable. Call the children() method on it. As you wrote you know how the first part works, and you know about the children() method so it's basically only putting those two together.
Comment: possible duplicate of [SimpleXML get element content based on attribute value](http://stackoverflow.com/questions/4736417/simplexml-get-element-content-based-on-attribute-value)
Comment: But I might not understand your question fully, maybe shed some light. Do you mean to get all descendants?
Comment: possible duplicate of [Implementing condition in XPath and XQuery](http://stackoverflow.com/questions/3448005/implementing-condition-in-xpath-and-xquery)
Answer: I hope this can help you.
Code
$xml = new SimpleXMLElement('<item id="1234">
    <property name="country_id">
        <value>4402</value>
    </property>
    <property name="rc_maintenance_other">
    </property>
    <property name="claim_right_shareholder">
    </property>
    <property name="charges_other">
    </property>
    <property name="other_expenses_heating">
    </property>
    <property name="unpaid_bills_amount">
    </property>
    <property name="iv_person_phone">
        <value>03-6756711</value>
    </property>
</item>');

foreach ($xml->xpath('//item[@id="1234"]') as $item)
{
    foreach ($item->children() as $child) {
      echo $child['name'] ."\n";
    }
}

Output

country_id
rc_maintenance_other
claim_right_shareholder
charges_other
other_expenses_heating
unpaid_bills_amount
iv_person_phone

Example: http://sandbox.onlinephpfunctions.com/code/4e0ddba2ed273ab4a20dc9379ea9ed0d669a4c0d
Comment: Thank you it works fine! I knew it was simple but my brain just didn't want to output it. I generate the path before with the $id variable and call it like this `foreach ($xml->xpath($path) as $item)`
Comment: And in case, somebody else need it, here how to access the values of the property nodes as well:

`$path = '//item[@id="'.$id.'"]';
 foreach ($xml->xpath($path) as $item) {
  foreach ($item->children() as $child) {
   foreach ($child->children() as $value) {
    echo $child['name'] ." = ".$value."";
   }
  }
 }`
Answer:
But how can I use the children() function only to a certain item?

The SimpleXMLElement::children()Docs method is used always to a certain element in Simplexml. So you can do that by just using it.
$element->children();

The manual coins it this way:

Finds children of given node


Countably categorical theories, Engelers article

Question: The famous characterization of countably categorical theories state that such a theory is equivalent with a theory with a finite amount of $n-$types for each $n$, a theory where all models are atomic, a theory which has a saturated elementarily prime model etc. This theorem is cited, in both Chang/Kieslers Model theory, Hodges Model theory and Rothmalers Introduction to model theory, to be a result from 1959 by Engeler, Ryll-Nardzewski and Svenonius all independently. The paper which is cited as Engelers part is the following paper:

Engeler E., A characterization of theories with isomorphic denumerable models, Notices of the American Mathematical Society 6 (1959) 161.

However, when I search on MathSciNet or Zentralblath math for this article nothing appears. Often articles (especially obscure old soviet articles) can not be accessed but are still indexed by these sites, yet this paper (which even belongs to the AMS thus should at least be on MathSciNet) does not appear. When I google the paper, I only find more books and papers which cite it. When I look at Engelers webpage he does not mention it as one of his papers (and he seems to have a quite extensive list).
My question is why? Why can't I find this paper? Why isn't it mentioned anywhere except in references? Where can I find this paper?
Comment: In a library${}$?
Answer: A similar question was asked over at MathOverflow. In the comments, Andreas Blass wrote

'Long ago, the Notices of the AMS published essentially just meeting announcements and abstracts of talks. The Calabi citation seems to be well within this "long ago", so it is probably just an announcement of results, not a real paper.'

All of Engeler's papers listed on MathSciNet prior to 1963 are in German. So it seems likely that the Notices "paper" was a brief English-language announcement of a result that appeared in full in a German-language publication (this is supported by the fact that the citation gives just a single page number). Just based on the title, the following paper seems most likely - but maybe someone who has access to the paper (which I do) and speaks German (which I don't) can verify this.

Engeler, Erwin Äquivalenzklassen von n-Tupeln. (German) Z. Math. Logik Grundlagen Math. 5 1959 340–345.
Comment: I haven't checked the paper itself, but the review on MathSciNet (by Paul Lorenzen) doesn't mention a characterization of countable categoricity.  The main theorem described in the review is (what is now called) the omitting types theorem.  I'll keep looking in MathSciNet for the right paper.
Comment: Ah, thanks, I should have thought to look at the review! I guess it's possible that Engeler announced the result in the Notices but never published a proof. @AndreasBlass
Comment: Well, that review was in German, but another Engeler paper, with an English review (by Azriel Lévy), has another ingredient of the result in question. In "Unendliche Formeln in der Modelltheorie" [Z. Math. Logik Grundlagen Math 7 (1961) 154-160] Engeler characterizes countably categorical theories as those in which all models realize the same types. That plus the omitting types theorem gets you a pretty big part of the theorem in the  question.
Comment: Ah, good thinking with the paper written in german. When I looked at the 3 Citations of the german paper you mention above I find that 2 of the papers (one is Macpherson's survey of homogeneous structures) mention it as the origin of Engeler's result and the third I don't have acess to, yet mention Ryll-Nardzevski and Svenonius as referenses, thus probably draws the same connection. I still find it kinda strange though that none cites this paper before Macpherson in 2011. Maybe he also got curious when he wrote his paper and looked it up properly. Anyway, this answers my questions, thanks.


Redirecting after processing partial view with ajax results in next page loading inside the partial view's div.

Question: I have two partial views in a parent page. The problem is when I call redirect to local once the form has successfully been submitted the next page is loaded in the place of the partial view inside the parent. The other form is visable as well. Here's the action methods and view logic associated with one of them as they're almost identical. How do I fix this?
[AllowAnonymous]
    public ActionResult _LoginPartial(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return PartialView(new LoginModel());
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult _LoginPartial(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return PartialView(model);
    }

The portion of the parent page that renders the partial
@{
if(!WebSecurity.IsAuthenticated){

Use a Creative Works account to log in.

@Html.Action("_LoginPartial", new {returnUrl = ViewBag.ReturnUrl })

}

}
The partial view
@using (Ajax.BeginForm("_LoginPartial", new {returnUrl = ViewBag.ReturnUrl},
new AjaxOptions(){UpdateTargetId = "loginForm",
InsertionMode = InsertionMode.Replace
})) {

 @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Log in Form</legend>

                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)

                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)

                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })

        <input type="submit" value="Log in" />
    </fieldset>

    }

Comment: As you are using `AjaxOptions()` you can give js function for `OnComplete` event. Doesn't that work? Like `new AjaxOptions(){UpdateTargetId = "loginForm",
InsertionMode = InsertionMode.Replace, OnComplete="Redirect()"
}`
Answer: Change the ajax form Ajax.BeginForm to a regular form Html.BeginForm so that the response is handled by the browser instead of the ajax callback.  Alternatively you could manually redirect the browser on the ajax callback if it is successful.


Código não funciona [PYTHON]

Question: Escrevi um script simples que capta as notas de alunos através de uma lista auxiliar e depois joga tudo dentro de uma lista maior, incluindo a média dos alunos que é calculada durante o código.
Criei um while com a flag 999 para sair da iteração e o programa permite que o usuário (que poderia ser um professor por exemplo) acesse as notas do aluno para entender a média que é mostrada no menu.
O usuário precisa digitar um número indexador, caso ele digite um out of range o programa fica preso no loop até que ele digite um número válido.
O problema é que depois que eu digito uma vez um indexador inexistente ele continua preso no loop mesmo depois de eu digitar um indexador válido.
Segue código:
dados = []
geral = list()
while True:
    dados.append(input('Nome do aluno: '))
    dados.append(float(input('Nota 1: ')))
    dados.append(float(input('Nota 2: ')))
    media = (dados[1] + dados[2]) / 2
    dados.append(media)
    geral.append(dados.copy())
    dados.clear()
    resp = ' '
    while resp not in 'SN':
        resp = input('Quer cadastrar mais alunos? [S/N] ').strip().upper()[0]
    if resp == 'N':
        break
print('-' * 35)
print('ALUNOS CADASTRADOS'.center(35))
print('-' * 35)
print(f'{"Código":<8}{"Nome":<17}{"Média Final":5}')
for i, (nome, n1, n2, media) in enumerate(geral):
    print(f'{i:<8}{nome:<15}{media:5}')
print()
relatorio = 0
while relatorio != 999:
    relatorio = int(input('Você quer analisar as notas de qual aluno? (DIGITE 999 para PARAR) '))
    while relatorio not in range(len(geral)):
        relatorio = input(f'Aluno não existente. Digite um número entre 0 e {len(geral) - 1}: ')
    print(f'Histórico de notas do aluno {geral[relatorio][0]}: ', end='')
    print(f'{geral[relatorio][1]}, {geral[relatorio][2]}')
print('PROGRAMA DE NOTAS ENCERRADO.')

Answer: Uma solução é validares se o valor que inseres existe o número de posições no dict, variável "geral".
file.py
dados = []
geral = list()
while True:
    dados.append(input('Nome do aluno: '))
    dados.append(float(input('Nota 1: ')))
    dados.append(float(input('Nota 2: ')))
    media = (dados[1] + dados[2]) / 2
    dados.append(media)
    geral.append(dados.copy())
    dados.clear()
    resp = ' '
    while resp not in 'SN':
        resp = input('Quer cadastrar mais alunos? [S/N] ').strip().upper()[0]
    if resp == 'N':
        break
print('-' * 35)
print('ALUNOS CADASTRADOS'.center(35))
print('-' * 35)
print(f'{"Código":<8}{"Nome":<17}{"Média Final":5}')
for i, (nome, n1, n2, media) in enumerate(geral):
    print(f'{i:<8}{nome:<15}{media:5}')
print()
relatorio = 0
while relatorio != 999:
    relatorio = int(input('Você quer analisar as notas de qual aluno? (DIGITE 999 para PARAR) '))
    if relatorio < len(geral):
      print(f'Histórico de notas do aluno {geral[relatorio][0]}: ', end='')
      print(f'{geral[relatorio][1]}, {geral[relatorio][2]}')
print('PROGRAMA DE NOTAS ENCERRADO.')

Código não funciona [PYTHON]


ActiveRecord/ARel modify `ON` in a left out join from includes

Question: I'm wondering if it's possible to specify additional JOIN ON criteria using ActiveRecord includes?
ex: I'm fetching a record and including an association with some conditions
record.includes(:other_record).where(:other_record => {:something => :another})

This gives me (roughly):
select * from records
left outer join other_records on other_records.records_id = records.id
where other_records.something = another

Does anyone know how I can specify an extra join condition so I could achieve something like.
select * from records
left outer join other_records on other_records.records_id = records.id
    and other_records.some_date > now()
where other_records.something = another

I want my includes to pull in the other_records but I need additional criteria in my join.  Anything using ARel would also be great, I've just never known how to plug a left outer join from ARel into and ActiveRecord::Relation
Comment: Could you make your example more concrete? The something_else is a little hard to follow.
Comment: Just changed it to a different condition, basically, I want to be able to join on more than just the foreign key.
Answer: I can get you close with ARel. NOTE: My code ends up calling two queries behind the scenes, which I'll explain.
I had to work out LEFT JOINs in ARel myself, recently. Best thing you can do when playing with ARel is to fire up a Rails console or IRB session and run the #to_sql method on your ARel objects to see what kind of SQL they represent. Do it early and often!
Here's your SQL, touched up a bit for consistency:
SELECT *
FROM records
  LEFT OUTER JOIN other_records ON other_records.record_id = records.id
    AND other_records.some_date > now()
WHERE other_records.something = 'another'

I'll assume your records model is Record and other_records is OtherRecord. Translated to ARel and ActiveRecord:
class Record < ActiveRecord::Base

  # Named scope that LEFT JOINs OtherRecords with some_date in the future
  def left_join_other_in_future
    # Handy ARel aliases
    records = Record.arel_table
    other   = OtherRecord.arel_table

    # Join criteria
    record_owns_other = other[:record_id].eq(records[:id])
    other_in_future   = other[:some_date].gt(Time.now)

    # ARel's #join method lets you specify the join node type. Defaults to InnerJoin.
    # The #join_sources method extracts the ARel join node. You can plug that node
    #   into ActiveRecord's #joins method. If you call #to_sql on the join node,
    #   you'll get 'LEFT OUTER JOIN other_records ...'
    left_join_other = records.join(other, Arel::Nodes::OuterJoin).
                              on(record_owns_other.and(other_in_future)).
                              join_sources

    # Pull it together back in regular ActiveRecord and eager-load OtherRecords.
    joins(left_join_other).includes(:other_records)
  end

end

# MEANWHILE...

# Elsewhere in your app
Record.left_join_other_in_future.where(other_records: {something: 'another'})

I bottled the join in a named scope so you don't need to have all that ARel mixed in with your application logic.
My ARel ends up calling two queries behind the scenes: the first fetches Records using your JOIN and WHERE criteria, the second fetches all OtherRecords "WHERE other_records.record_id IN (...)" using a big list of all the Record IDs from the first query.
Record.includes() definitely gives you the LEFT JOIN you want, but I don't know of a way to inject your own criteria into the join. You could use Record.joins() instead of ARel if you wanted to write the SQL yourself:
Record.joins('LEFT OUTER JOIN other_records' +
             ' ON other_records.record_id = records.id' +
             ' AND other_records.some_date > NOW()')

I really, really prefer to let the database adapter write my SQL, so I used ARel.
If it were me, I'd consider putting the additional join criterion in the WHERE clause. I assume you're asking because putting the additional criterion on the join makes the query's EXPLAIN look better or because you don't want to deal with NULLs in the other_records.some_date column when there aren't any related other_records.
Answer: If you have a simple (equality) extra join condition it could simply be
record.includes(:other_record).where(:other_record => {:something => :another,
                                                       :some_date => Time.now})

But if you need the greater than comparison the following should do it.
record.includes(:other_record).where([
  'other_records.something = ? and other_records.some_date > ?',
   another, Time.now])

Hope that helps.


Rails is using PATCH when I would expect it to use POST

Question: I'm working on an application for assessing student work. When a student creates a new Post most of the time Rails uses the POST verb and life is good. However if the work is late and the Post has been scored as missing then Rails tries to create it (using the same route) with the PATCH verb instead of POST and creating the Post fails.
I error message that I see in Heroku's log is:
ActionController::RoutingError (No route matches [PATCH] "/users/55/posts")

As far as I can tell the difference between the two situations is the existence of an instance of a Score when Rails decides to use the PATCH verb. The score model includes this line:
  belongs_to :post, touch: true

Could this be responsible for the difference in behavior? I thought it might, but there is not Post object created when the Score on the missing assignment is created (the way I checked this was to by typing Post.where(user: score.user) to bin/rails c. The result was an empty array.
Is there a way to force Rails to do a POST when it wants to do a PATCH?
Answer: Hard to diagnose without more information. You can use form_for @user, method: :post do |f| to explicitly instruct Rails to use the POST method.
Comment: What information would be helpful? I wasn't sure what would be helpful to add.


Why do some swimmers wear two caps?

Question: Just now I saw Michael Phelps competing in the 400m Medley heats (London Olympics 2012). After he finished the race, I saw him take off two caps. I can imagine that a swimmer uses one, but what is the reason for wearing two caps?
Is this something new? Does it help him swim faster?
Answer: Actually, most swimmers at this level of competition wear two caps. Dana Vollmer, who won gold with a new world-record time in the 100m butterfly, actually lost her outer cap in the pool on the return leg of that event.
Thus, the first reason; redundancy. These caps are latex rubber, which doesn't mix well with chlorine and will eventually degrade, and as Dana's swim shows, even a brand-new cap can slip right off. If the swimmer, especially a female swimmer, had only one cap, losing it and releasing their hair would drastically increase the drag they have to swim against in the water.
Second, as Rory states, a common (though not universal) way to put all your headgear on is to put one swim cap on, then put your goggles on, then cover the goggle strap with another swim cap. Not only does it reduce drag on the goggle strap (which is minor), it helps keep your goggles in one place (MUCH more important). I was on a swim team when I was much younger, and I lost count of how many times the shock of entering the water ripped my goggles right off my eyes. You still have to swim if it happens, but it becomes a HUGE distraction that can take you right out of the race. At your average junior swim meet, losing a race to your goggles is embarassing but not devastating. At the Olympics, it would be a heartbreaker.
Comment: I wouldn't say *most* swimmers wear two caps, but at the higher level of competition, those small benefits of peace of mind that your gear won't come off and reduced drag from goggles can be the difference between a spot on the podium or not.
Comment: I'll rephrase; most *professional competitive* swimmers. Most recreational swimmers don't even bother with one.
Answer: The two caps are also made of different materials.  The inner cap is latex, which stays on the head better, but wrinkles.  The outer cap is silicone, better for reducing drag.

"The outer silicone cap better maintains the shape and does not
  wrinkle as much, thereby causing less drag," Salo told Yahoo! Sports. - Why do Olympic-level swimmers wear two caps?
Answer: It is for speed- if you have your goggles on over your cap it upsets water flow, so the second cap over that holds the goggles safely on and streamlines the head.
Sure, it's an infinitesimally small benefit, but at that level it is important.
Additionally, some sports manufacturers make some specifically to be worn like this to reduce drag further.
Comment: Why not put the goggles below a single cap? You then have the same advantages, right?
Comment: goggles over a cap pretty much fixes the strap in place higher up than you can do on a bare head, due to friction. Much more comfortable.
Answer: It helps them swim faster. it not for hair. Its help b/c the water will just flow over the cap. I know because we are talking about it in science
Comment: For the first cap I agree, but I am specifically asking for the second one. What does it add fluid dynamically speaking?
Answer: he wore two caps only because if one comes off he has a back up already on and it supports the goggles making them stay in their lace under the second cap as the goggles may come off from diving.
Comment: Thanks for your answer, but I don't really see how it adds anything as compared to the answers that are already there?

Why do some swimmers wear two caps?