How to get all inputs from a form - not working from selector

Question: I have the following html:

                          ×

                      <form id="modal_revenue_form" role="form" method="POST" action="">

                            Year
                            <select class="form-control select2" style="width: 100%;" id="modal_revenue_form_year" data-placeholder="Select a year">
                              <option value="" ></option>
                                                                <option value="2015" >
                                2015
                              </option>
                                                                <option value="2016" >
                                2016
                              </option>
                                                                <option value="2017" >
                                2017
                              </option>
                                                                <option value="2018" >
                                2018
                              </option>
                                                                <option value="2019" >
                                2019
                              </option>
                                                                <option value="2020"  selected >
                                2020
                              </option>
                                                                <option value="2021" >
                                2021
                              </option>
                                                                <option value="2022" >
                                2022
                              </option>
                                                                <option value="2023" >
                                2023
                              </option>
                                                                <option value="2024" >
                                2024
                              </option>
                                                                <option value="2025" >
                                2025
                              </option>
                                                              </select>

                            FPC
                            <input type="text" id="modal_revenue_form_fpc" class="form-control" placeholder="FPC"></input>

                            jan
                            <input type="text" id="modal_revenue_form_jan" class="form-control" placeholder="jan"></input>

                            feb
                            <input type="text" id="modal_revenue_form_feb" class="form-control" placeholder="feb"></input>

                            mar
                            <input type="text" id="modal_revenue_form_mar" class="form-control" placeholder="mar"></input>

                            apr
                            <input type="text" id="modal_revenue_form_apr" class="form-control" placeholder="apr"></input>

                            may
                            <input type="text" id="modal_revenue_form_may" class="form-control" placeholder="may"></input>

                            jun
                            <input type="text" id="modal_revenue_form_jun" class="form-control" placeholder="jun"></input>

                            jul
                            <input type="text" id="modal_revenue_form_jul" class="form-control" placeholder="jul"></input>

                            aug
                            <input type="text" id="modal_revenue_form_aug" class="form-control" placeholder="aug"></input>

                            sep
                            <input type="text" id="modal_revenue_form_sep" class="form-control" placeholder="sep"></input>

                            oct
                            <input type="text" id="modal_revenue_form_oct" class="form-control" placeholder="oct"></input>

                            nov
                            <input type="text" id="modal_revenue_form_nov" class="form-control" placeholder="nov"></input>

                            dec
                            <input type="text" id="modal_revenue_form_dec" class="form-control" placeholder="dec"></input>

                      </form>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" id="modal_revenue_create_update_button" class="btn btn-success"></button>

and the following jquery to set all inputs to a certain value:
$(document).ready(function() {
    function modal_revenue_form_clean(title) {
          $('#modal_revenue_title').text(title+' Revenue');
          $('#modal_revenue_create_update_button').text(title);
          $('#modal_revenue_form_hidden').empty();

          // Set date to today's year
          var d = new Date();
          var year = d.getFullYear()
          $('select#modal_revenue_form_year').val(year);
          $('select#modal_revenue_form_year').select2().trigger('change');

          $('#modal_revenue_form_fpc').val(0);

          // Clean all input <---- I don't get this alert below
          $("form#modal_revenue_form input").each(function(){
            alert('ok');
            $(this).val('dfgsdfgdf');
          });
          // Set all months value to 0
          @foreach(config('select.available_months') as $key => $month)
            $('#modal_revenue_form_{{ $month }}').val(0);
          @endforeach

          //modal_revenue_form_error_clean();
        }
});

This jquery code is in a function and when I call it, nothing happens, I don't get alerts. I ave checked on other website and it seems this is the way to select all inputs in a specific form.
Why is it not working?
Answer: You need wrap your code inside document ready as
$(document).ready(function(){
      $("form#modal_revenue_form input").each(function(){
        //alert('ok');
        $(this).val('dfgsdfgdf');
      });
});

$(document).ready(function(){
      $("form#modal_revenue_form input").each(function(){
        //alert('ok');
        $(this).val('dfgsdfgdf');
      });
});

!-- Modal Body -->

                      <form id="modal_revenue_form" role="form" method="POST" action="">

                            Year
                            <select class="form-control select2" style="width: 100%;" id="modal_revenue_form_year" data-placeholder="Select a year">
                              <option value="" ></option>
                                                                <option value="2015" >
                                2015
                              </option>
                                                                <option value="2016" >
                                2016
                              </option>
                                                                <option value="2017" >
                                2017
                              </option>
                                                                <option value="2018" >
                                2018
                              </option>
                                                                <option value="2019" >
                                2019
                              </option>
                                                                <option value="2020"  selected >
                                2020
                              </option>
                                                                <option value="2021" >
                                2021
                              </option>
                                                                <option value="2022" >
                                2022
                              </option>
                                                                <option value="2023" >
                                2023
                              </option>
                                                                <option value="2024" >
                                2024
                              </option>
                                                                <option value="2025" >
                                2025
                              </option>
                                                              </select>

                            FPC
                            <input type="text" id="modal_revenue_form_fpc" class="form-control" placeholder="FPC"></input>

                            jan
                            <input type="text" id="modal_revenue_form_jan" class="form-control" placeholder="jan"></input>

                            feb
                            <input type="text" id="modal_revenue_form_feb" class="form-control" placeholder="feb"></input>

                            mar
                            <input type="text" id="modal_revenue_form_mar" class="form-control" placeholder="mar"></input>

                            apr
                            <input type="text" id="modal_revenue_form_apr" class="form-control" placeholder="apr"></input>

                            may
                            <input type="text" id="modal_revenue_form_may" class="form-control" placeholder="may"></input>

                            jun
                            <input type="text" id="modal_revenue_form_jun" class="form-control" placeholder="jun"></input>

                            jul
                            <input type="text" id="modal_revenue_form_jul" class="form-control" placeholder="jul"></input>

                            aug
                            <input type="text" id="modal_revenue_form_aug" class="form-control" placeholder="aug"></input>

                            sep
                            <input type="text" id="modal_revenue_form_sep" class="form-control" placeholder="sep"></input>

                            oct
                            <input type="text" id="modal_revenue_form_oct" class="form-control" placeholder="oct"></input>

                            nov
                            <input type="text" id="modal_revenue_form_nov" class="form-control" placeholder="nov"></input>

                            dec
                            <input type="text" id="modal_revenue_form_dec" class="form-control" placeholder="dec"></input>

                      </form>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" id="modal_revenue_create_update_button" class="btn btn-success"></button>

Comment: Sorry, I forgot to mention that it is wrapped already in it... I will edit my post
Comment: did you wrap it content use bootstrap modal?
Comment: yes, I m using bootstrap 3 but why would it make anything different, jquery should only go through each input in my form, no?


Collecting and analysing data in RCT

Question: I am doing a research proposal. I am testing a new treatment combination in the experimental group and my control group only get placebo. I am planning to collect interval inferential data (blood test) and analysing it with T-test. Is T-testing the best way to analyse it? How can I justify why I chose this tool?
Comment: What do you mean by "interval inferential data"?
Comment: If this is a real study on real people as opposed to self-study (see the tag http://stats.stackexchange.com/tags/self-study/info for details) then you seriously need to get help before you start experimenting on people.
Comment: Do you mean Student's $t$ test (note lower case) or do you mean Hotelling's $T^2$ (note upper case).
Answer: Given that randomized allocation ensures theoretical equipoise, you correctly chose a test not encompassing adjustment for confounders. However, if you are facing repeated measures (eg blood test results before and after intervention), I would recommend using a repeated-measure ANOVA, a generalized linear model, or generalized estimating equations.
Comment: Thank you. I looked the ANOVA test and looks very complicated... I have never done any statistic study I am on a medical course.
Comment: @gingergi Are you using R?

Collecting and analysing data in RCT


Qual a melhor alternativa: defines, enums ou variáveis?

Question: Recentemente, em um projeto onde tenho que declarar muitas contantes, me veio essa dúvida. Qual a melhor opção define's, enum's ou variáveis constantes?
A princípio penso que usar enum seja a melhor alternativa por não poluir o código e funcionar melhor com o auto-completador do IDE, mas quais seriam os prós e contras de cada abordagem?
Exemplo das opções que tenho:
enum Pin
{
    PIN_00 = 0x10,
    PIN_01 = 0x11,
    PIN_02 = 0x12,
    // ... muitos outros
};

Ou:
#define PIN_00 0x10
#define PIN_01 0x11
#define PIN_02 0x12
// ... outros defines

Ou:
namespace Pin
{
     const int PIN_00 = 0x10;
     const int PIN_01 = 0x11;
     const int PIN_02 = 0x12;
     // ... Outros declarações
}

Comment: Melhor ou pior em absoluto não existem. Quais são os prós e contras de cada abordagem, no entanto, é algo que pode ser respondido.
Comment: Eu prefiro evitar define e enum pois nem sempre os compiladores conseguem tratar este tipo de informação na hora de mostrar os valores durante uma execução em debug mode.
Answer: Se todas as contantes estão relacionadas e você quer dar coesão a elas na forma de um tipo, enum é a melhor escolha, pois não permitem que por engano você atribua uma valor errado a elas.
Pin pin1 = PIN_00; //Ok
Pin pin2 = 0x10;   //Não compila

Agora se o propósito é apenas dar nome a um número mágico, existe controvérsia. Pessoalmente eu prefiro const do que #define, porque as variáveis const são tratadas pelo compilador mesmo. Você tem um identificador, com tipo e valor bem definidos. Já o define é tratado pelo pré-processador, podendo gerar resultados inesperados em alguns casos. Por exemplo:
const int CONST = 2 + 5;
#define DEFINE 2 + 5

int x = 3 * CONST;  //Resultado = 3 * (2 + 5)
int y = 3 * DEFINE; //Resultado = 3 * 2 + 5 !!!

Outro problema é que o tipo do define é apenas definido pelo literal, o que também pode gerar problemas:
#define FATOR 1.5

double val = FATOR / 2;

Se algum dia alguém mudar o valor de FATOR para 1 (em vez de 1.0) aquela divisão vira uma divisão inteira, cujo resultado é 0, em vez do 0.5 esperado. Este problema não acontece se FATOR for const double.
Answer: Existem diversos prós e contras de cada abordagem dependendo do contexto, com relação ao consumo de memória e desempenho acredito que o enum e a variável constante sejam iguais já que o enum é como uma variável mais fortemente tipada. Já o define não ocupa memória já que ele é avaliado pelo pré processador que substitui o trecho em que ele aparece pela sua definição.
Comment: @Lucas se for uma variavel global você deve  a fazer `static const`. Sendo local só o `const` basta. Nesse caso e se você nunca criar um ponteiro para a variável, a otimização é trivial e qualquer compilador vai aplicar "inline" na variável.
Comment: O impacto de memória e de desempenho é zero para todas as alternativas. No caso da variável, ela ocupará espaço na memória somente se você tentar criar um ponteiro para ela (nos outros casos isso não é possível).
Comment: @GuilhermeBernal No caso da variável, se eu utilizar essa abordagem, o compilador tratará a variável como um literal? Ou ele armazenará a variável na memória? Não entendi muito bem isso.


How to use JSTL  with Struts2 ?

Question: I have this code that actually works:
<s:iterator value="breadcrumb.links" var="link">
    <s:url action='%{#link.url}' var="url" />

       ${link.name}

</s:iterator>

How con I do the same thing but with c:foreach instead of s:iterator ?
I tried with:
<c:forEach items="${breadcrumb.links}" var="link">
    <s:url action='${link.url}' var="url" />

        ${link.name}

</c:forEach>

but I get the error:

According to TLD or attribute directive in tag file, attribute action does not accept any expressions

Thankyou.
Comment: Apart from the question, why do you want to do that ?
Comment: Becouse I don't feel confortable with struts tags s:iterator and OGNL %{#}. I'd like to stick to JSTL c:foreach and EL ${}. Also I always read that EL and OGNL can do the same things, only in different ways. But in this case I cant't find a way with EL.
Comment: This evening I'll try you code and post the results, thankyou.
Answer: To be more comfortable with Struts2 tags and OGNL language, read and bookmark this answer.
Since Struts2 tags only evaluate OGNL expressions (and not EL Expression, as you error clearly states), you need to access the JSTL object through the PageContext attribute (in OGNL #attr.something)  specified with var :
<c:forEach items="${breadcrumb.links}" var="link">
    <s:url action='%{#attr.link.url}' var="url" />

        ${link.name}

</c:forEach>

From OGNL Basics:

#attr['foo'] or #attr.foo
  : Access to PageContext if available, otherwise searches
  request/session/application respectively
Comment: Thank you, it works as expected. I also read some docs about OGNL, now it is a lot clearer. Maybe I'll just switch to struts2 tags + OGNL. Grazie mille.
Comment: Glad that helped, prego :]

How to use JSTL  with Struts2 ?


Relacionamento entre entidades

Question: Não estou conseguindo fazer a deleção do objeto selecionado.
Tenho duas classes, Autor e Livro, exemplo básico de funcionamento, para aprender o uso de Java Server Faces, até aqui tudo bem, funcionamento e etc. O problema é que na relação @ManyToMany, quando chamada a função pra excluir o registro, tanto, de autor e de livro, lança uma exceção de violação de constraint.
Segue a parte necessária para avaliação:
Modelo de Autor
@Entity
public class Autor implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "autor_id", unique = true, nullable = false)
    private Integer id;

    @ManyToMany(mappedBy="autores")
    private List<Livro> livros;

    //Demais campos, getters e setters
}

Modelo de Livro
@Entity
public class Livro implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "livro_id", unique = true, nullable = false)
    private Integer id;

    @ManyToMany
    @JoinTable(name = "livro_autor", joinColumns = {
        @JoinColumn(name = "livro_id", nullable = false, updatable = false) },
            inverseJoinColumns = {
        @JoinColumn(name = "autor_id", nullable = false, updatable = false) })
    private List<Autor> autores = new ArrayList<Autor>();

    //Demais campos, getters e setters
}

Bean Autor
@ManagedBean
public class AutorBean {

    private Autor autor = new Autor();

    public void removeAutor(Autor autor){
        new DAO<Autor>(Autor.class).remove(autor);
    }

    //Demais métodos omitidos
}

Bean Livro
@ManagedBean
@ViewScoped
public class LivroBean implements Serializable {

    private Livro livro = new Livro();
    private Integer autorId;
    public void removeLivro(Livro atualLivro){
        new DAO<Livro>(Livro.class).remove(atualLivro);
    }

    //Demais métodos omitidos
}

DAO
public class DAO<T> {

    private final Class<T> classe;

    public DAO(Class<T> classe) {
        this.classe = classe;
    }

    public void remove(T t) {
        EntityManager em = new JPAUtil().getEntityManager();
        em.getTransaction().begin();
        em.remove(em.merge(t));

        em.getTransaction().commit();
        em.close();
    }
}

A relação cria uma terceira tabela, esperado, com o nome livro_autor. Ao excluir, lança esse erro:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot delete or update a parent row: a foreign key constraint fails (`banco`.`livro_autor`, CONSTRAINT `FK33E9E1BAF971CF8` FOREIGN KEY (`autor_id`) REFERENCES `autor` (`autor_id`))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)

Se necessário alguma outra parte do código, só pedir. Os métodos omitidos são básicos, outros campos dos modelos, persistência, no caso do DAO, etc, tudo que não achei que acrescentasse algo na questão.
EDIÇÃO
Consegui fazer com que o campo do livro fosse excluído, o que está acontecendo agora é que se existir um livro para um dado autor, o autor não pode ser excluído, se não existe nenhum livro vinculado, o autor pode ser excluido.
Answer: Resolvido.
Após colocar a pergunta aqui, o programa executou a função de exclusão de livro, o que não havia acontecido antes de publicar a pergunta (sigh). Mesmo assim, a função de exclusão de autor estava dando o mesmo erro.
Tentei colocar:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "livro_autor", joinColumns = {
    @JoinColumn(name = "livro_id", nullable = false, updatable = false) },
        inverseJoinColumns = {
    @JoinColumn(name = "autor_id", nullable = false, updatable = false) })
private List<Autor> autores = new ArrayList<Autor>();

...o que tambem não funcionou.
Tentei passar o Cascade para a entidade do Autor, ficando assim:
@ManyToMany(mappedBy="autores", cascade = CascadeType.ALL)
private List<Livro> livros;

Não funcionou, mas ao alterar CascadeType.ALL para CascadeType.REMOVE funciona.
O erro dissecado seria que não podia excluir um livro que tinha livro vinculado na tabela livro_autor, e utilizando o CascadeType.REMOVE, toda a vez que eu removo um autor, o Hibernate remove automaticamente seus livros vinculados, o que me é esperado.

Relacionamento entre entidades


C# numeric base class

Question: I want to write a C# method that can accept any number.  Something like:
public static T Sum(T a, T b) where T : number {  // (not real code)
    return a + b;
}

But I don't see a "number" base class in C#, as exists in most other languages I've used.  The numeric value types are IComparable, IFormattable, IConvertible, IComparable, and IEquatable, but nothing that seems to have any arithmetic capabilities.  They're all structs, with no apparent common superclass, apart from object.  (Forgive me if I'm screwing up the meaning here, since I'm not too familiar with C# structs and precisely all the ways they are like or unlike classes.)
Am I missing something, or is it not possible to write a method in C# that does "a + b" without declaring exactly what a and b are in the context of the "+"?
Comment: (Replied to comment; to clarify - there **is** no casting nor overloading)
Comment: (Re your other comment about `IEnumerable.Sum`; note that MiscUtil provides generic versions of `Sum`, `Average`, etc - using `Operator` etc)
Answer: You will have to resort to using overloading. A little like the Math class is doing with function like Math.Max where it support all numeric types.
The link proposed by CD is also resourceful.
Comment: Or like the Linq extension methods are doing with IEnumerable.Sum and implement only half the numeric types!
Comment: Not necessarily. There are generic-based solutions (see my answer for more).
Answer: See this SO question for similar discussion.
Also, you can do this (with some tedious effort) if you're willing to create separate Types for each of the .Net core number types you want to use it for...
Create two structs, called say, MyInt, and MyDecimal which act as facades to the CTS Int32, and Decimal core types (They contain an internal field of that respective type.) Each should have a ctor that takes an instance of the Core CTS type as input parameter..
Make each one implement an empty interface called INumeric
Then, in your generic methods, make the constraint based upon this interface. Downside, everywhere you want to use these methods you have to construct an instance of the appropriate custom type instead of the Core CTS type, and pass the custom type to the method.
NOTE: coding the custom structs to properly emulate all the behavior of the core CTS types is the tedious part... You have to implement several built-in CLR interfaces (IComparable, etc.) and overload all the arithmetic, and boolean operators...
Answer: Unfortunately, no such class/interface exists.
Answer: int and the other numeric types are ValueTypes. As already said, all you can do is saying where T: struct. Well, you could use reflection to check if the type argument implements addition... but i'm not sure if that's a good idea.
Answer: The best you can do is where T : struct which requires a ValueType; all numerics are ValueTypes.
Unfortunately, so are all user-defined structs, so that's the drawback. There's no specific generic that will accept all numeric classes.
I hesitate to even suggest this, but you might consider runtime checks against the type of T in the method and throw if T is not an int, long, short, float, or double. Unfortunately, this will not help a programmer at compile-time.
Answer: This is a very common question; if you are using .NET 3.5, there is a lot of support for this in MiscUtil, via the Operator class, which supports inbuilt types and any custom types with operators (including "lifted" operators); in particular, this allows use with generics, for example:
public static T Sum<T>(this IEnumerable<T> source) {
    T sum = Operator<T>.Zero;
    foreach (T value in source) {
        if (value != null) {
            sum = Operator.Add(sum, value);
        }
    }
    return sum;
}

Or for another example; Complex<T>
Comment: It's kind of neat (or gross) that there's a library to do all the overloading and casting for me, but I don't consider "Operator.Add(a,b)" to be a solution to the problem of "a+b" not being generic.  If I want to become generic by writing a bunch of verbose code, I don't need a third-party library to do that.  :-)
Comment: There *is* no overloading nor casting. It is genuine generic-based code, with some clever use of Expression to pre-compile a delegate (per-type) that can do the arithmetic.
Comment: It might help if I clarify that `Add` is actually a generic method (`Add`); simply that in the example we're using generic-type-inference to avoid having to add the `` ourselves. But it is still there.
Comment: OK, I misspoke w.r.t. the approach MiscUtil uses, but I still don't consider Operator.Add(a,b) a solution.  :-)

C# numeric base class


Estimate of variance with the lowest mean square error

Question: Regarding estimators of variance from a iid sample of size $n$,  Karl Ove Hufthammer  says Estimates of variance from an iid sample:

if they do have a normal distribution, dividing by n+1 (sic!) will give the lowest mean square error.

Why does it give the lowest mean square error?
What does he mean by "(sic!)"?
Thanks!
Comment: *sic* is Latin for 'thus', usually in text meaning "exactly as in the original" (even if that looks wrong, or unlikely, or questionable)
Comment: @Glen_b: I know that meaning of sic, but I don't understand what Karl means in his comment.
Comment: *That* it's reasonable to ask in comments at the original; it's a clarification of his meaning, not a whole new question. However, I may offer the suggestion that since $n+1$ looks rather like the more usual $n-1$ (or $n$ for that matter), one might be tempted to think he simply made a sign error or something, and *sic* is perhaps intended to emphasize that, no, even if it might appear possible that he meant $n-1$ or $n$, he really does mean $n+1$, just as originally typed.
Comment: You may be interested in this paper: http://www.tandfonline.com/doi/abs/10.1080/00031305.2012.735209?af=R
Comment: @KarlOskar interesting; if I did it right, the estimator there corresponds to using $d =  (n-1)\,+\,2/n$ in the notation of my answer.
Answer: Define
$$s^2_d = \frac{\sum_{i=1}^n\left(x_i-\bar{x}\,\right)^2}{d}$$
The statistic $(n - 1)s_{n-1}^2 / \sigma^2$ follows a $\chi^2_{n-1}$ distribution. A $\chi^2_{n-1}$ has mean $n-1$ and variance $2(n-1)$. Hence $\text{E}(s_{n-1}^2) = \sigma^2$, and $\text{Var}(s_{n-1}^2) = 2\frac{\sigma^4 }{ n - 1}$.
Now $s_d^2 = \frac{n-1}{d} s_{n-1}^2$
$$\text{Bias}(s_d^2) = E(s_d^2)-\sigma^2 = \frac{n-1}{d}\sigma^2 -\sigma^2=\frac{n-1-d}{d}\sigma^2$$
$$\text  {Var}(s_d^2) = 2\sigma^4(n - 1) / d^2$$
$$\text{MSE} = \text{Bias}^2 + \text{Var}$$
Hence
\begin{eqnarray}
\text{MSE}(s_d^2) &=& \left(\frac{n-1-d}{d}\right)^2\sigma^4+ 2\sigma^4(n - 1) / d^2\\
 &=&\sigma^4\frac{(n-1-d)^2+2(n-1)}{d^2}\\
&=&\sigma^4\,f(d)\,,\end{eqnarray}
where $f(d)=1+\frac{(n-1)^2 + 2(n-1)-2(n-1)d}{d^2}$
$f(d)$ is at a turning point when $f'(d)=0$
i.e. when $d(-2(n-1))-2((n-1)^2 + 2(n-1)-2(n-1)d) = 0$
which occurs when $d-2=n-1$ ... i.e. when $d=n+1$
Showing that's a minimum rather than a maximum (or indeed a horizontal point of inflexion) is straightforward, but I'll leave it at that for now.
The relevant Wikipedia page does it more generally, getting a formula in terms of the excess kurtosis (which gives the same result in this case). I may incorporate an outline of that derivation at some point.


set c of convergent sequences in the Normed Linear Space of all bounded real sequences under the sup norm is complete

Question: Show that the set c of convergent sequences in the Normed Linear Space of all bounded real sequences under the sup norm is complete
my try: I know that the set of all bounded functions from a set X to R under the sup norm is complete.So the problem reduces to showing that the set c is closed
But I cant do that.Any hints.
Answer: The idea is that a Cauchy sequence of sequences is Cauchy "component-wise".
If you have a Cauchy sequence $(x_n^k)_{k=1}^\infty$ of bounded sequences I would show that after fixing an $n$, the sequence $(x_{n}^k)_{k=1}^\infty \subseteq \mathbb{F}$ is a Cauchy sequence, and hence it converges to some $x_{n} \in \mathbb{F}$. Then show that $\lim_{k \to \infty} (x_n^k) = x_n$. Also, you need to show $(x_n)$ is a bounded sequence.


Is space complete and separable?

Question: $\displaystyle M =\{x\in\mathbb{R}^{(0,1]} : x \text{ is continuous on } (0,1] \text{ and } x(t) = o(\ln{}t)\ (t \rightarrow +0)\} $. We will consider metric $\displaystyle\rho(x, y) = \int\limits_{0}^{1}|x(t)-y(t)|dt$.

Is $(M,\rho)$ complete space?
Is $(M,\rho)$ separable space?
If $(M,\rho)$ is not complete find its completion.

I've considered $\displaystyle x_k(t) = t^{\frac{1}{k}}\ln{}t$, $x_k \in M$. Obviously, $x_k \rightarrow \ln{}t\notin M$, as $\rho(x_k,\ln{}t) = 1- \displaystyle\frac{1}{(\frac{1}{k} + 1)^2} \rightarrow 0.$ In the same way we can show that it is Cauchy sequence. So, $(M, \rho)$ is not complete.
But I've stuck with two other questions. I think that completion of $M$ is $\mathbb{L}_1(0,1]$. How can one show it? If it is so, we will also have an answer for the second question. $\mathbb{L}_1(0,1]$ is separable, so $M$ is separable.
Answer: Integrability of $\ln t$ shows that $M$ is a subset of $L^{1}(0,1]$.
If $x \in C(0,1]$ then $x_i(t)=x(t)$ for $t \geq \frac 1 i, x_i(t)=itx_(\frac  1i)$ for $0<t<\frac 1 i$ defines a sequence in $M$ converging to $x$ in $L^{1}(0,1]$. Combined with the fact that continuous functions are dense in $L^{1}(0,1]$ it follows that $M$ is dense in $L^{1}(0,1]$. This implies that $L^{1}(0,1]$ is the completion of $M$.

Is space complete and separable?


promblem while trying to define two numbers in c# programe for average stock calculator

Question: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace average_stock_calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal  a, b, c, d, sum, average;

            Console.WriteLine("First purchase price:");

            a = Convert.ToDecimal(Console.ReadLine());

            Console.WriteLine("Second purchase price:");
            b = Convert.ToDecimal(Console.ReadLine());

            Console.WriteLine("Third purchase price:");
            c = Convert.ToDecimal(Console.ReadLine());

            Console.WriteLine("Fouth purchase price:");
            d = Convert.ToDecimal(Console.ReadLine());

            //Processing
            sum = a + b + c + d;
            average = sum/4;

            Console.WriteLine("Average buying price={0}", average);

            Console.ReadKey();
        }
    }
}

note: i want to add first purchase quntity and first purchase price together, i have no idea how to do it! can someone help?
it should look like this,
enter first purchase quntity & price
and i shuold be able to enter quntity 10 and price 20 together, and then at the end i should get the average buy quantity and price together.
Comment: Why would you *add* a quantity and a price? They'd have different units. Normally you'd *multiply* them together. If I have 5 things each costing $2, that's a cost of $10, not 7...
Comment: Additionally, your code doesn't currently ask for quantities at all... only prices.
Comment: am trying to create an application on which people can find out the average of stocks they bought on different dates also in different quantity and at different price.
Comment: None of that addresses anything in my comments though.
Comment: Are you trying to have an input, on the same line, for both quantity and price and then separate the input to different counters?
Comment: yes steve, youre right.
Answer: I made a simple modification for you.
Codes:
using System;

namespace ConsoleApp9
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Purchase a, b, c, d;
            Console.WriteLine("First purchase price and amount:");
            a = ReadL();
            Console.WriteLine("Second purchase price and amount:");
            b = ReadL();
            Console.WriteLine("Third purchase price and amount:");
            c = ReadL();
            Console.WriteLine("Fouth purchase price: and amount:");
            d = ReadL();

            //Processing
            Purchase Sum = new Purchase();
            Sum.price = a.price + b.price + c.price + d.price;
            Sum.amount = a.amount + b.amount + c.amount + d.amount;

            Purchase Average = new Purchase();
            Average.price = Sum.price / 4;
            Average.amount = Sum.amount / 4;

            Console.WriteLine("Average buying price={0},Average buying amount={1}", Average.price, Average.amount);

            Console.ReadKey();

            Purchase ReadL()
            {
                Purchase X = new Purchase();
                var inputs = Console.ReadLine().Split(' ');
                X.amount = Convert.ToDecimal(inputs[0]);
                X.price = Convert.ToDecimal(inputs[1]);
                return X;
            }
        }
        class Purchase
        {
            public decimal price { get; set; }
            public decimal amount { get; set; }
        }
    }
}

Output:


How can I create a CHECK constraint on a VARCHAR column in MSSQL specifying a valid set of characters that may appear in the data?

Question: I have a VARCHAR(30) column in a Microsoft SQL database representing a username. I'd like to add a CHECK constraint that allows only a certain range of characters to be used: specifically, a-z, A-Z, underscore and dash. What expression must I use?
Answer: create table t (
   a varchar(30) check (
      a like replicate('[a-zA-Z\_-]', len(a)) escape '\'));

If your collation is not case sensitive then you don't need both [a-z] and [A-Z].
Answer: CREATE TABLE T
(
 a VARCHAR(30) NOT NULL UNIQUE
    CHECK (a NOT LIKE '%[^a-zA-Z\_-]%' ESCAPE '\')
);


java.lang.ClassNotFoundException: com.google.apphosting.utils.remoteapi.RemoteApiServlet

Question: I am getting this error while deploying a new version.
Build tool: gradle
Although the same code with a different version that was deployed some time back is working well. The exceptions are as below. On local env code is working fine.
<code>org.eclipse.jetty.servlet.BaseHolder doStart:  (BaseHolder.java:101)
java.lang.ClassNotFoundException: com.google.apphosting.utils.remoteapi.RemoteApiServlet
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at com.google.apphosting.runtime.ApplicationClassLoader.findClass(ApplicationClassLoader.java:135)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.eclipse.jetty.util.Loader.loadClass(Loader.java:86)
    at org.eclipse.jetty.servlet.BaseHolder.doStart(BaseHolder.java:95)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:363)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:891)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:349)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1406)
    at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.startWebapp(AppEngineWebAppContext.java:175)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1368)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:778)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:262)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:522)
    at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.doStart(AppEngineWebAppContext.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:240)
    at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:178)
    at com.google.apphosting.runtime.jetty9.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:120)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchServletRequest(JavaRuntime.java:747)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchRequest(JavaRuntime.java:710)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:680)
    at com.google.apphosting.runtime.JavaRuntime$NullSandboxRequestRunnable.run(JavaRuntime.java:872)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:270)
    at java.lang.Thread.run(Thread.java:748)
</code>
build.gradle file is as below: I am sharing the main module file. Other build.gradle file are just the supporting files.
<code>/*
configurations {
    compile.exclude group: 'com.google.http-client'
}
*/

configurations.runtime {
    exclude group: 'com.ibm.websphere', module: 'uow'
    exclude group: 'org.apache.geronimo.specs', module: 'geronimo-servlet_2.5_spec'
    exclude group: 'javax.servlet', module: 'jsp-api'
    exclude group: 'com.sun', module: 'tools'
    exclude group: 'ant', module: 'ant'
    exclude group: 'com.wadpam', module: 'docrest-doclet'
    exclude group: 'com.wadpam', module: 'docrest-api'
}

dependencies {
    compile ('com.goldengekko:user-service:1.0.5') {
        transitive = true
    }
    compile ('com.goldengekko:security-support:1.0.2') {
        transitive = true
    }
    compile 'javax.servlet:servlet-api:3.0'
    compile("com.goldengekko:user-security-mgmt:2.1.112") {
        //exclude module: 'appengine-gcs-client'
        exclude module: 'docrest-doclet'
        exclude module: 'commons-dbcp'
        exclude module: 'spring-jdbc'
        exclude module: 'log4j'
        exclude group: 'javax.mail', module: 'mail'
        exclude module: "geronimo-jpa_3.0_spec"
        exclude group: "javax.activation", module: "activation"
        exclude group: "javax.servlet", module: "servlet-api"
        exclude group: 'com.google.http-client:google-http-client'
        exclude group: 'com.google.http-client', module: 'google-http-client-jackson2'
        exclude group: 'com.goldengekko', module: 'gae-support'
        //changing = true //for snapshot
    }

    compile('com.goldengekko:gae-support:2.0.24') {
        transitive = true
        exclude group: 'com.goldengekko', module: 'core-server'
        exclude group: 'com.google.http-client:google-http-client'
        exclude group: 'com.google.http-client', module: 'google-http-client-jackson2'
        exclude group: 'com.google.appengine.tools', module: 'appengine-gcs-client'
    }

    compile('com.google.appengine.tools:appengine-gcs-client:0.5') {
        transitive = true
        exclude group: 'com.google.http-client', module: 'google-http-client-jackson2'
        exclude group: 'com.google.api-client', module: 'google-api-client-appengine'
    }

    compile('com.google.api-client:google-api-client-appengine:1.23.0')

    compile ('com.google.http-client:google-http-client-jackson2:1.19.0')
    compile ('com.google.http-client:google-http-client:1.19.0')
    compile ('com.google.code.gson:gson:1.5')
    compile('net.sf.mardao:mardao-gae:2.3.3') {
        transitive = true
    }

    compile('com.goldengekko:core-server:1.0.57') {
        transitive = true
    }

    runtime 'org.springframework.social:spring-social-facebook:1.1.0.M1'

    compile ('com.goldengekko:crud-support:1.0.2') {
        transitive = true
    }

    compile ('com.goldengekko.android:networking:1.9') {
        transitive = true
    }
    compile('com.goldengekko:mobile-push-support:1.1.7') {
        transitive = false
    }

    compile('com.wadpam.gaelic:gaelic-oauth2-provider:1.0.8') {
        transitive = true
    }
    compile ('com.wadpam.gaelic:gaelic-domain:1.0.8') {
        transitive = true
    }a
    compile ('com.wadpam.gaelic:gaelic-appengine:1.0.8') {
        transitive = true
    }

    /*
    compile ('com.fasterxml.jackson.core:jackson-annotations:2.5.4') {
        transitive = true
    }
    compile ('com.fasterxml.jackson.core:jackson-databind:2.5.4') {
        transitive = true
    } */

    runtime ('cglib:cglib:2.2.2') {
        transitive = true
    }
    compile ('com.google.appengine:appengine-api-1.0-sdk:1.9.60') {
        transitive = true
    }
    compile ('com.google.appengine:appengine-api-labs:1.9.60') {
        transitive = true
    }

    compile group: 'commons-collections', name: 'commons-collections', version: '3.2.1'
    //providedCompile('javax.servlet:servlet-api:2.5') { transitive=false}
    compile('org.springframework:spring-core:4.0.9.RELEASE') {
        force = true
        transitive = true
    }
    compile ('org.springframework:spring-tx:4.0.9.RELEASE') {
        force = true
        transitive = false
    }
    compile ('commons-lang:commons-lang:2.6') {
        force = true
        transitive = false
    }

    compile ('org.springframework:spring-webmvc:4.0.9.RELEASE') {
        force = true
        transitive = true
    }
    compile ('com.ibm.websphere:com.springsource.com.ibm.websphere.uow:184.108.40.206') {
        force = true
        transitive = true
    }
    compile ('org.springframework:spring-oxm:4.0.9.RELEASE') {
        transitive = true
    }
    compile ('org.apache.axis:axis:1.4') {
        transitive = true
    }
    compile ('javax.xml:jaxrpc-api:1.1') {
        transitive = true
    }
    compile ('commons-discovery:commons-discovery:0.4') {
        transitive = true
    }
    compile ('wsdl4j:wsdl4j:1.6.2') {
        transitive = true
    }
    compile ('net.sf.ehcache:ehcache:1.6.2') {
        transitive = true
    }
    compile ('org.codehaus.groovy:groovy-all:1.7.2') {
        transitive = true
    }
    compile ('commons-io:commons-io:2.4') {
        transitive = true
    }
    compile ('commons-fileupload:commons-fileupload:1.3') {
        transitive = true
    }
    compile 'org.osgeo:proj4j:0.1.0'
    compile 'uk.co.jemos.podam:podam:3.3.2.RELEASE'
    compile 'net.sf.opencsv:opencsv:2.2'
    compile 'org.springframework.ws:spring-ws:1.5.9'
    compile 'com.amazonaws:aws-java-sdk-sns:1.10.26'
    compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.6.3'

    runtime ('org.springframework.social:spring-social-twitter:1.1.0.M1') {
        transitive = true
    }

    runtime('org.springframework.social:spring-social-salesforce:1.0') {
        transitive = true
    }

    runtime('com.goldengekko.social:spring-social-gaelic:1.0')
    runtime('com.goldengekko:core-domain:1.0.3')

    runtime('org.springframework.social:spring-social-core:1.1.4.RELEASE') {
        transitive = true
    }
    runtime('org.springframework.social:spring-social-facebook:1.1.1.RELEASE') {
        transitive = true
    }
    runtime('org.springframework.social:spring-social-google:1.0.0.M2') {
        transitive = true
        exclude group: 'com.google.http-client', module: 'google-http-client'
        exclude group: 'com.google.http-client', module: 'google-http-client-jackson2'
    }

    compileOnly 'com.goldengekko:docrest-doclet:3.0.7'

    compile 'net.sf.opencsv:opencsv:2.0'

    compile 'org.projectlombok:lombok:1.18.4'

}
</code>
Comment: Which version of the App Engine SDK for Java are you using? can you share the build.gradle as this error sounds to be because of missing the dependencies on it.
Comment: com.google.appengine:appengine-api-1.0-sdk:1.9.60
Comment: GAE sdk was discontinued. I have updated the version and it is working fine now.
Answer: This error is due to the old SDK,
here you can download the most updated version of it.


Differentiation of a matrix in respect to a vector

Question: Could someone show and explain the differentiation of the following
$$\frac{\partial(x^t Ax)}{\partial x} $$
Where x is a column vector and A is a symmetric square matrix. I'm in highschool so I have no experience with vector calculus and I only need this derivation for a partial derivative in a Lagrange function.
It should come out as $2Ax$
Thanks a lot,
Tom
Comment: $x$ is a *column* vector and $A$ is a *symmetric* square matrix?
Comment: Sorry yes that's correct on both counts
Answer: If you're not comfortable with vector calculus, try out the assertion on a small case, say $n=2$. Then you are trying to differentiate the scalar (one-dimensional) quantity
$$\begin{align}
Q(x_1,x_2):=x^TAx&=
\begin{matrix}(x_1 &x_2)\end{matrix}
\left(\begin{matrix}A_{1,1} &A_{1,2}\\
A_{2,1} &A_{2,2}\end{matrix}\right)
\left(\begin{matrix}x_1 \\x_2\end{matrix}\right)\\
&=x_1A_{1,1}x_1 + x_1A_{1,2}x_2 + x_2 A_{2,1}x_1 + x_2A_{2,2}x_2.
\end{align}
$$
Taking the partial derivative of $Q$ with respect to $x_1$ gives
$$
\frac{\partial Q}{\partial x_1}=2A_{1,1}x_1+A_{1,2}x_2 + x_2A_{2,1}=2(A_{1,1}x_1 + A_{1,2}x_2)\tag1$$
since $A_{1,2}=A_{2,1}$. We recognize the RHS of (1) as the first element in the column vector $2Ax$, which is the product of the scalar $2$ with the matrix $A$ and the column vector $x$.
A similar calculation shows that  $\frac{\partial Q}{\partial x_2}$ is the second element in $2Ax$.
EDIT: Now that you see how the $n=2$ case works, the general case is similar. Write out the matrix product:
$$
Q(x_1,x_2,\ldots,x_n):=x^TAx=\sum_{i=1}^n\sum_{j=1}^n x_iA_{i,j}x_j.
$$
For a fixed $k$ you compute the partial derivative of $Q$ wrt $x_k$ by considering which of the indices $i,j$ are equal to $k$:
$$\begin{align}
\frac{\partial Q}{\partial x_k}&=
\frac{\partial}{\partial x_k}(x_kA_{k,k}x_k)+
\frac{\partial}{\partial x_k}(\sum_{j\ne k}x_kA_{k,j}x_j)+
\frac{\partial}{\partial x_k}(\sum_{i\ne k}x_iA_{i,k}x_k)\\
&=2A_{k,k}x_k +\sum_{j\ne k}A_{k,j}x_j + \sum_{i\ne k} x_iA_{i,k}\\
&=2\sum_k A_{k,j}x_j,
\end{align}
$$
the last equality arising after relabeling index $i$ as $j$ and using the fact $A_{j,k}=A_{k,j}$. We recognize the final quantity as the $k$th element in the column vector $2Ax$.
Writing out the matrix product is typically the way to prove these vector calculus identities. You should be aware that different authors use different conventions for notation in these identities, depending on whether the derivative of a scalar with respect to a vector is seen as a column vector or as a row vector. See https://en.wikipedia.org/wiki/Matrix_calculus for a very detailed discussion.
Comment: Thanks for the answer. Do you think it'd be feasible to prove the assertion via induction for integers n greater than or equal to 2 just to be more rigorous?
Comment: @Nickkkk I've added some remarks on the general case. There's a pattern in the $n=2$ case that you can replicate for general $n$.
Answer: First of all, the convention in linear algebra is to express vector $x$ as a $n\times 1$ matrix. Conforming to this would reduce some confusion while doing complicated matrix algebra.
I convinced myself with the following two steps while struggling the first year of grad school, and hope it helps you.
Step1
before getting to the expression, I guess you had already met
$$
\dfrac {\partial Ax}{\partial x^T}=A
$$
let me explain this one first.
define $g(x): \mathbb R^n \rightarrow \mathbb R^m$ where the $i^{th}$ element of $g$ is $g_i(x_1,x_2,...,x_n)$. Then we call it "Jacobian", the $m\times n$ matrix of first partial derivative :
$$
\dfrac {\partial g(x)}{\partial x^T}=\dfrac {\partial (g_1,g_2,...,g_m)}{\partial (x_1,x_2,...,x_n)}
$$
where element in row i and column j is $g_{ij}=\dfrac {\partial g_i(x_1,x_2,...,x_n)}{\partial x_j}$
Now, let $g(x)=Ax$, then
$$
g_i(x_1,x_2,...,x_n)=a_{i1}x_{i1}+a_{i2}x_{i2}+...+a_{in}x_{in}
$$
and we get $\dfrac {\partial g_i(x_1,x_2,...,x_n)}{\partial x_j}=a_{ij}$
which means $\dfrac {\partial Ax}{\partial x^T}=A$
Step2
note that $x^TAx=x^T(Ax)$, using the product rule:
$$
\dfrac {\partial g^T h}{\partial x^T}= h^T \dfrac {\partial g}{\partial x^T}+g^T \dfrac {\partial h}{\partial x^T}
$$
we get
$$
\begin{align}
\dfrac {\partial x^TAx}{\partial x^T}&=(Ax)^T\dfrac {\partial x}{\partial x^T}+x^T\dfrac {\partial (Ax)}{\partial x^T}\\
&=x^TA^T+x^TA\\
&=x^T(A+A^T)\\
&=2x^TA
\end{align}
$$
the last line comes form the symmetry of $A$.
ps. many Ph.D. students in econ or some other fields still don't know why it is true, based on my observation...
Comment: Hey, thanks for the explanation before the problem, that definitely helped to lessen my confusion in this world of foreign mathematics. It seems like you took the partial derivative in respect to transpose x instead of x though. Did you incorrectly transcribe the question or am I missing something?
A Ph.D. in economics is my goal anyway, so I guess it's good that I've got the leg up now :)
Comment: well, I think the way you write $\frac{\partial(x^T Ax)}{\partial x}$ is not correct: the denominator cannot be a $n\times 1$ vector.
Comment: http://faculty.washington.edu/ezivot/econ424/portfolioTheoryMatrix.pdf
Page 12 lists a Lagrangian function partial differential with respect to column vector x , specifically (1.15)
Comment: x is a 3x1 vector and Sigma is a 3x3 vector
Comment: yeah, I see the notes, and this is why I don't like the way they do this... Note that when $m=1$, the Jacobian is $1\times n$, but economists likes to transpose it to $n\times 1$, Then, the r.h.s. of $\frac{\partial(x^T Ax)}{\partial x^T}=2x^T A$ is $2Ax$ since A is symmetric. To make it more reasonable, they also transpose the denominator on the l.h.s. It does enhance interpretation though, they can say the derivative w.r.t. $x_j$ is the jth row of f.o.c. but sacrifices accuracy.


Erro na passagem de parâmetros C#

Question: Estou com o seguinte erro:
Error   1   Cannot implicitly convert type 'System.DateTime' to 'string'

No seguinte código:
t.Codigo = GetValorDateTime(tabela, i, "DataDeContrato", DateTime.MinValue);

    public DateTime GetValorDateTime(DataTable pDados, int pLinha, String pNomeColuna, DateTime pValorPadrao)
    {
        DateTime retorno = pValorPadrao;
        if (pDados.Rows.Count > pLinha)
        {
            if (pDados.Columns.Contains(pNomeColuna))
            {
                object valor = pDados.Rows[pLinha].ItemArray[pDados.Columns[pNomeColuna].Ordinal];
                if (valor != null)
                    retorno = Convert.ToDateTime(valor);
            }
        }
        return retorno;
    }

Answer: O seu t.Codigo deve ser do tipo string, e o retorno do método é do tipo DateTime.
você pode tentar fazer assim:
t.Codigo = GetValorDateTime(tabela, i, "DataDeContrato", DateTime.MinValue).ToString();

Mas acredito que não seja isso que você queira, um DateTime não faz sentido como Codigo de alguma coisa. Talvez está errando a propriedade que deseja definir, possívelmente:
t.DataDeContrato = GetValorDateTime(tabela, i, "DataDeContrato", DateTime.MinValue);

Comment: Ops, era isso mesmo. Esqueci de alterar o nome após o CTRL+C CTRL+V hshshs

Erro na passagem de parâmetros C#


Crossed effects in lmer or lme4

Question: I conducted an experiment where I want to predict response times in a picture classification task from person characteristics (age, prior experience) and item characteristics (similarity; color, shape, background). All participants saw all items and the "similarity" characteristic comprises all combinations of color, shape and backgroup.
   subject     age    prior_exp tria        rt   sim color  shape backg
   <fct>     <dbl>        <dbl> <chr>    <dbl> <dbl>  <dbl> <dbl> <dbl>
 1 930179102    22            5 trial1   1647     0      0     0     0
 2 930179102    22            5 trial2   1949     1      1     0     0
 3 930179102    22            5 trial3   2198     1      0     1     0
 4 930179102    22            5 trial4   2051     1      0     0     1
 5 930179102    22            5 trial5   1475     2      1     1     0
 6 930179102    22            5 trial6   2402     2      0     1     1
 7 930179102    22            5 trial7   1399     2      1     0     1

I'm just getting started with mixed models. As I understand it, age and prior_exp are fixed effects and similarity is a random effect, and color/shape/backg are crossed factors. Is that correct? I fitted this model but am not sure, how to incorporate the crossed factors.
lmm <- lmer(rt ~ age + prior_exp + sim + (sim|subject), data = df)

Is my reasoning so far correct and can anybody please help me with the crossed factors or point me in the right direction?
Comment: Can you explain more about the factors similarity, color, shape, background. How many are there of each and how are they related ?
Comment: The task is similar to the game "Set". Particpants are presented with 4 cards and must decide whether the color, shape and backgroud displayed on those cards are all identical or all different across all cards. Color = 1 indicates that for this specific item, the color was equal in all cards. Similarity is the sum of all attributes (color, shape, background) that are equal across all cards.
Answer: Here, items are crossed with subjects because all subjects saw all items.
So subject and item should be the random effects, and the characteristic of them should be fixed effects. So according to your data, you will need an identifier for each item and the model will look something like this:
rt ~ age + prior_exp + color + shape + backg + (1|subject) + (1|item)

Note that, since similarity is the sum of the other item  attributes, then it isn't identified as a unique parameter, so you can't include it as a fixed effect along with the others (you could include it but exclude at least one of the other three though I don't see much point in that).
Comment: Thanks alot! The unique identifier would be "trial" in my case.
Comment: @achmed you're welcome, so just to be clear, each subject is exposed to each trial ?
Comment: Yes, each subject is exposed to each trial. "trial" is a misleading name, it should be "item".
Comment: OK then, that sounds good. My answer stands as it is :)

Crossed effects in lmer or lme4


Change HTML output of a view

Question: I have a view which displays products. The fields shown are altered via hook, and I want to add
 and
, when I find an appropriate field value. (I tried with adding style to the field in the UI, but the logic is somehow convoluted, so I would need to hard-code it.)
I need to encapsulate a complete row inside a
 when some field has some value. I have tried with views-view-fields.tpl.php and views-view-unformatted.tpl.php, but they seem not to "talk to each other", so I am failing miserably. Maybe should I approach by using views_view_result() and building the HTML myself?
Answer: To theme/design the complete row, you need to use Style output template file.
Click on Theme: Information in your view, in pop-up see the last file in Style output section. Copy the name and create file with same name and save this file at sites/all/themes/YOURTHEME/templates.
Then click on Style output, copy the code and paste into the newly created file. In this file, you can add your own HTML display the result.
Hope this helps.
Thanks
Answer: If you want to design the complete Row try Row Style Output which you found inside Theme Information
Try to create a file views-view-fields--view-name.tpl.php inside the themes/template folder and copy paste the content from views-view-fields.tpl.php file and design the view page yourself.
Thanks
Comment: Well, the theory is good, but the problem is that we have two separated files: one for each row of data, and the other file for each field in the row. I don't see that I can access to the data of one of the files from the other file, which is what is causing me the problems. Example: add in the view a field of taxonomy. Then in the tpl.php, just show the first instance of the taxonomy, and encapsulate all the rows of the same taxonomy in the same div.

Change HTML output of a view


DLL load error when trying to import opensim in the spyder IDE

Question: I'm following this tutorial specifically Installing Anaconda and the "opensim" Python package, all the steps worked out perfectly for the last step were I'm asked to type import opensim in Spyder and I'm getting this error. what can I do to resolve it ?

tried reinstalling Anaconda3 and opensim 4.4, but the problem persists.
made sure my PATH includes opensim4.4\bin

import opensim
Traceback (most recent call last):
<code>  File "C:\Users\obaid\AppData\Local\Temp\ipykernel_17468\2888301570.py", line 1, in <module>
    import opensim

  File "C:\Users\obaid\anaconda3\lib\opensim\__init__.py", line 6, in <module>
    from .simbody import *

  File "C:\Users\obaid\anaconda3\lib\opensim\simbody.py", line 13, in <module>
    from . import _simbody

ImportError: DLL load failed while importing _simbody: The specified module could not be found.
</code>
Answer: You can install using

conda install -c kidzik opensim


Combine a list of lists in R according to name of the lists

Question: How can I merge a list of lists so that list-objects with the same name are merged in the outer layer.
# List object 1
list_1 <- list(
  L1 <- list(
    A1 <- c(1, 2, 3)
  ),
  L2 <- list(
    A1 <- c(1, 2, 3)
))

names(list_1) <- c("layer_1", "layer_2")
names(list_1$layer_1) <- c("A1")
names(list_1$layer_2) <- c("A1")

# List object 2
list_2 <- list(
  L1 <- list(
    B1 <- c(4, 5, 6)
  ),
  L2 <- list(
    B1 <- c(4, 5, 6)
  ))

names(list_2) <- c("layer_1", "layer_2")
names(list_2$layer_1) <- c("B1")
names(list_2$layer_2) <- c("B1")

list_1_2 <- list(list_1, list_2)

Now I want to turn list_1_2 so that it gets this structure (with the possible to include multiple lists of lists (e.g., list_3, list_4 osv, although always with the outer layer being called layer_1, layer_2 and layer_3):
# End result
list_1_2 <- list(
  L1 <- list(
    A1 <- c(1, 2, 3),
    B1 <- c(4, 5, 6)
  ),
  L2 <- list(
    A1 <- c(1, 2, 3),
    B1 <- c(4, 5, 6)
  ))

names(list_1_2) <- c("layer_1", "layer_2")
names(list_1_2$layer_1) <- c("A1", "B1")
names(list_1_2$layer_2) <- c("A1", "B1")

list_1_2

Answer: You can use
do.call("modifyList", list_1_2)

to get the output you want. This is the same as calling modifyList(list_1_2[[1]], list_1_2[[2]]) but will also work if you have more lists in the collection


How to get a public URL from MFS folder?

Question: So ipfs gives us https based urls for files yet they are all unique, per-file and hash based. I want to get something like that yet for expandable folders with updatable files (say have 'parent hash/{fileIdPath}' link). How to get a link to a file from the ipfs Mutable File System (MFS) (a link that would stay the same after I update the file)?
Comment: This is a cool concept, but this isn't really a thing today in go-ipfs. You can get a CID for your MFS root, and as you know, that CID will change when you update your MFS. There's also IPNS, where you could get a single address, and update the CID that points to. You can also automate this process, and that sorta sounds like what you're asking for. If it is, I'm happy to write a full answer.
Answer: If I am understand the question you want to get access to the URL from a hash file path, please post your code so we can see what you have tried so far and what specifically is the issue
Here is a ref to IPFS

You will need a clients to access those resources over http

For e.g. ipfs-http-client, js-ipfs for js access

using ipfs-http-client

please install it like so
//npm install firstname.lastname@example.com if you want a specific version
npm install --save ipfs-http-client

Setup your permissions

$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin  '["http://example.com"]'
$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "POST", "GET"]'

Now you can access the information with client
const ipfs = window.IpfsHttpClient()

sample js

With the JS client, install js-ipfs
import { create } from 'ipfs-http-client'
const client = create()
// add your addres below and get the contents
// dor e.g. const client = create(new URL('http://istart.work:1010'))
const client = create(new URL('http://127.0.0.1:1010'))
const { cid } = await client.add('Hello world!')

Comment: No, my main and only problem is with folder contents creation\update: I want to get one base hash and many subfiles with addressing like on pin~ata in order to get something like `123hash/file1`, `123hash/file2` and have ability to add new files after to have `123hash/file4`  for example


Monotonicity of Frobenius norm

Question: $A,B\in \mathbb{R}^{n\times n}$,$A,B\succeq 0$,$B-A\succeq 0$, prove $\Vert A \Vert_F \leq \Vert B \Vert_F $
(explain of sign: If $X \succeq 0$, then there exists
another matrix $Y \succeq  0$ such that $Y^2 = X$. Such $Y$ is not unique in general, but we may denote it as $X^{1/2}$.)
This is my homework. I have no idea at all but suspecting the "$Y^2 = X$" should be "$Y^TY = X$".
I tried to let $A=X^2, B=Y^2, B-A=Z^2$, then $\|B\|_F^2$ can be wrote as the sum of the products of the elements of $X$ and $Z$, but that seems doesn't work.
$\|A+B\|_F^2=\|A\|_F^2+2\langle A,B\rangle_F+\|B\|_F^2$ may be useful, where $\langle A,B\rangle_{F}=\operatorname{trace}\left(A^{T}B\right)$.
Answer: Assume that $A, B$ are both symmetric.
Let $Z := B - A \succeq 0$. We have
$$\|B\|_F^2 - \|A\|_F^2
= \mathrm{tr}((A + Z)^2) - \mathrm{tr}(A^2)
= \mathrm{tr}(Z^2) + 2\mathrm{tr}(AZ)
\ge 0$$
where we use $\mathrm{tr}(AZ)
= \mathrm{tr}(A^{1/2}Z A^{1/2})
\ge 0.$
Another way.
Let $A = UVU^\top$ be the EVD.
Let $C = U^\top BU$.
From $B - A \succeq 0$,
we have $C - V \succeq 0$.
Thus, $C_{ii} - V_{ii} \ge 0$ for all $i$.
We have
$$\|B\|_F^2 - \|A\|_F^2
= \mathrm{tr}(B^2) - \mathrm{tr}(A^2)
= \mathrm{tr}(C^2) - \mathrm{tr}(V^2)
\ge \sum_{i=1}^n (C_{ii})^2 - \sum_{i=1}^n (V_{ii})^2 \ge 0.$$

Monotonicity of Frobenius norm


Changing existing NAT rule on Cisco ASA

Question: This is the exact line I want to edit
nat (inside,outside) source static thatplace thatplace destination static thisplace thisplace no-proxy-arp route-lookup

All I want to do is enable proxy-arp.
How can I do that?
Comment: "_All I want to do is enable proxy arp._" No, you do not want to enable proxy ARP. That is a security hole, and you should not do that. Properly configured routing will not require proxy ARP.
Answer: Ignoring whether the desired proxy-arp change is appropriate for the environment (nods to @ron-maupin), the way to accomplish the stated objective from ASA CLI is to "no out" the command, then re-enter with the option removed.
no nat (inside,outside) source static thatplace thatplace destination static thisplace thisplace no-proxy-arp route-lookup
nat (inside,outside) source static thatplace thatplace destination static thisplace thisplace route-lookup

The CLI parameter is no-proxy-arp. There is not a proxy-arp parameter. Absence of the no-proxy-arp parameter enables proxy-arp on the NAT rule.
After making nat changes the ASA's xlate table (show xlate) will keep previous xlate entries in the xlate table in place until the associated conn ends (at which point the xlate timeout kicks in. clear xlate will forcefully clear the xlate table (clear xlate is intrusive, only perform during maintenance window).

Changing existing NAT rule on Cisco ASA


Why the jquery function is not triggered?

Question: I would like to trigger a popup box using the function provide by jquery easyui,
the code are following, it is not trigger : when i click open , there is no popup box opened,
also the popup box element is not hidden, it should work as i following their tutorial material. Thank you
The code :
Head Extract:

Body: extract :
<button onclick="javascript:$('#win').window('open')"> Permission Settings</button>

        <form style="padding:10px 20px 10px 40px;">

Name: <input type="text">

Pass: <input type="password">

                Ok
                Cancel

        </form>

Whole part:
<?
include("../connection/conn.php");
session_start();

if($_SERVER['REQUEST_METHOD'] == "POST"){

if (!isset($_POST['subscribe']))
$_POST['subscribe']=0;
if (!isset($_POST['unsubscribe']))
$_POST['unsubscribe']=0;

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {

    $listName = $_POST['lname'];
    $listFromName = $_POST['fname'];
    $listReplyTo = $_POST['remail'];
    $listSubject = $_POST['sub'];
    $listRemindSub = $_POST['subscribe'];
    $listRemindUnSub = $_POST['unsubscribe'];
    $listReminder = $_POST['creminder'];

    $query="INSERT INTO list (ListID,ListName,FromName,ReplyTo,Subject,IsRemindSub,IsRemindUnSub,CreateDate,Reminder) VALUES ('',?,?,?,?,?,?,CURDATE(),?)";
    $stmt = $conn->prepare($query);

    $stmt->bindParam(1, $listName , PDO::PARAM_STR);
    $stmt->bindParam(2, $listFromName, PDO::PARAM_STR);
    $stmt->bindParam(3, $listReplyTo, PDO::PARAM_STR);
    $stmt->bindParam(4, $listSubject, PDO::PARAM_STR);
    $stmt->bindParam(5, $listRemindSub, PDO::PARAM_INT);
    $stmt->bindParam(6, $listRemindUnSub, PDO::PARAM_INT);
    $stmt->bindParam(7, $listReminder, PDO::PARAM_STR);

    $stmt->execute();

}
catch(PDOException $e)
    {
    die ($e->getMessage().' Back');
    $conn->rollBack();
    }

try {
    $lastID=$conn->lastInsertId();
    $query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'Email','{email}')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'FirstName','{fname}')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'LastName','{lname}')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
}
catch(PDOException $e)
    {
    die ($e->getMessage().' Back');
    $conn->rollBack();
    }

try {
    $userID = $_SESSION['username'];
    $query="INSERT INTO user_list (UserID,ListID,UserListRights) VALUES (?,$lastID,'Edit')";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(1, $userID, PDO::PARAM_STR);

    $stmt->execute();

}
catch(PDOException $e)
    {
    die ($e->getMessage().' Back');
    $conn->rollBack();
    }

$conn = null;

?>

You have created a list. By default Mail Address, First Name , Last Name is in your list. Add more field if you want. Back

<?
}else{?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="stylesheet" type="text/css" href="../plugin/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../plugin/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../style/form.css" />

<form id="addlist" method="post" action="add.php" >

Create your new subscriber list

Create a new list before adding subscriber * indicates required

* List name:
Add your list name

<input id="lname" name="lname" class="required" />

Reminder:
Remind the details of your list

<textarea id="creminder" name="creminder" cols="52" ></textarea>

Permission Setting ...

Open to other users: <input type="checkbox" class="checkbox" name="public" value="1">
Or

<button onclick="javascript:$('#win').window('open')"> Permission Settings</button>

Name: <input type="text">

Pass: <input type="password">

                Save
                Close

Email me when ...

People subscribe: <input type="checkbox" class="checkbox" name="subscribe" value="1">

People unsubscribe: <input type="checkbox" class="checkbox" name="unsubscribe" value="1">

<input class="submit" type="submit" name="submit" value="Submit"/>

</form>

<?
try{
$sql = '
    SELECT   *
    FROM     list,user_list
    WHERE    user_list.UserID=?
    AND list.ListID=user_list.ListID
';
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$result= $stmt->fetchAll();
$num_rows= $stmt->rowCount();
}
catch(PDOException $e)
    {
    die ($e->getMessage().' Back');
    }
$conn = null;
if ($num_rows == 0) {
    echo '
You have not created any list yet.
';}
else {
    echo '
Your Subscriber List

You have created '.$num_rows.' list(s).
';
foreach ($result as $set)
{
echo '
List Name : '.$set['FromName'].'

';
echo '
Subscriber :

';
echo '
Create Date : '.$set['CreateDate'].'

';
echo '
';
}}
    ?>

<?
}
?>

Comment: I think you need to include the plugin script *after* the jQuery script.
Comment: lot of code always confuses so remove extra code that need not to understand your problem
Comment: $('#win').window('open'); is the plugin script
Comment: http://www.jeasyui.com/tutorial/win/win1.php
Comment: I am following that tutorial , have a look it is easy and short. thank you
Answer: Change your scripts to this order:
<link rel="stylesheet" type="text/css" href="../plugin/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../plugin/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../style/form.css" />

so the plugin comes after the jQuery script.
Comment: the other problem is when i click the open button, it act like a submit button and post the form as well as generate a pop up windows.I have not set the button as submit type. Why it behave in a submit type? Thank you.
Comment:  Permission Settings
Answer: At first sight, the script references are not in the correct order: you need to reference first jQuery and then jQuery EasyUI:

Comment: thanks, it works. Also, what can i do to specific escape the css code ?that is becasue ,,,, ,  and i want to escape the css code of form
Comment: the other problem is when i click the open button, it act like a submit button and post the form as well as generate a pop up windows.I have not set the button as submit type. Why it behave in a submit type? Thank you.
Comment: Add `return false;` to cancel default behavior of the button. This is though another problem than the question itself.
Comment: so werid . It does not generate the popup after i add return false; but it will still posting my form . why it behave like this?
Comment: I will repost the question because there are more question then i expected. thank you. Please follow the other question if you like


spl autoload register error

Question: I'm writing some classes that I want to load using the spl_autoloader_register() function. I've created a file named autoloader.php and I've saved it inside the folder where I'm saving all the classes needed for my project.
So, to verify if it work, I've loaded it using require_once inside a test php page, but unfortunately the console log show me an error output PHP Warning:  include_once(lib\DataManager.php): failed to open stream: No such file or directory.
The test file is inside the same folder who host all the classes, is this error because of this motivation?
Here is the autoloader code
<?php
function autoloader($className){
    include_once($className . '.php');
}

spl_autoload_register('autoloader');

?>

and here is how I tried to instantiate it from the test page
<?php

require_once 'autoloader.php';
require_once 'config.php';

use lib\DataManager as DataManager;

$dataManager = new DataManager($db);

?>

Answer: You got it almost right. The problem is because it's not pointing to the correct local filesystem to find the file. The following autoloader will work with a relative plugin model, and a library folder model. This will assume the on your configuration file you have defined a variable $GLOBALS['config']->lib that defines a filesystem folder that could contains extra system libraries. Of course, this could defined differently, it depends of the application.
<?php
function autoloader($className){
    $paths=[getcwd(),$GLOBALS['config']->lib];
    foreach($paths as $p){
        $filename = str_replace('\\','/',$p.'/'.$className.'.php');
        if (is_readable($filename)) {
            require_once($filename);
            return;
        }
    }
}
spl_autoload_register('autoloader');
?>

This will work taking on consideration two scenarios, class is relative to the last requested script, if not tries a predefined folder with classes. Once it's found and loaded it should return, to avoid keep trying loading other paths.
On the array more paths to try could be defined, but try to keep it no more of four paths for performance reasons. Also the order of the paths are the priority where to look first.
This script should work on PHP 5.4 up.
Comment: I'm new to this advanced concept of PHP so I'm very glad for your help. For now I'm testing the autoload function inside the same folder, but as i can understand I need to adapt it to work also if I want to use it from another folder of my project, is this right?
Comment: I'm not sure what you mean by "relative to the last requested file". The `__FILE__` and `__DIR__` constants represent the file and directory *where they are used*, and are not affected by anything else in the program.
Comment: @Carlos H I've tried but it will generate the same error. Maybe I'm doing something wrong with namesapces?
Comment: @user9741470 This works assuming that your class is relative to the script that you request. Is this a web application or a CLI application? Normally, on my projects, I create a "library" folder where I put all my classes, this model is good for fixed applications. However, the relative model of execution is useful for the plugin model.
Comment: The class will work for a normal web app. The path of the classes will be u/lib/classes.php so now I have the problem that the autoloader will look inside the lib folder and doesn't find the class files needed, but they are all in that path. In future I want to use autoload from the front controller so I want to solve this issue and understand what I'm doing wrong.
Comment: I updated my answer to a more generic answer. This works from PHP 5.4 up. It Includes 2 paths options, but could be adjusted to include more paths.
Comment: To test if the problem was with the autoloader or with the namespaces, I've moved out from the classes folder the `autoload.php` file. Now it works, but I can't figure out whats was the problem.
Comment: If you noticed from my code I get rid off the `__FILE__` and instead I'm using `getcwd()` instead. This should allow the autoloader to be anywhere else, but it will depends of the path of the entry point script. I will not recommend it 100% but you could alter your current working directory using `chdir()`.
Answer: Relative paths are not processed relative to the file where they are written, but rather the "current working directory" of the PHP process (often, the document root of your web process, but not worth relying on).
To reference the location of the current source file, PHP provides two magic constants:

__FILE__ is the fully-qualified filename of whatever source file you write it in
__DIR__ is the directory containing that file

So, assuming your classes are in the same directory as the definition of your autoloader function, you can write this:
function autoloader($className){
    include_once __DIR__ . DIRECTORY_SEPARATOR . $className . '.php';
}

The __DIR__ is resolved once, when the function is compiled, so whenever this function is run, it will always refer to the directory where this function was defined, regardless of where it was called from, or how the script is run.
(Note that include, require, include_once, and require_once are keywords not functions, and don't need brackets around them. It won't hurt to add them in general, but can cause confusion in some cases, so is best avoided.)
Comment: @user9741470 So, what is the correct path? The first rule of debugging is *always* break the problem down: try to write a line with `echo` that displays the correct full path, using whatever [string functions](http://php.net/manual/en/ref.strings.php) help you. Then put that next to `include_once`.
Comment: @user9741470 Read the error message carefully. Is `'/Applications/MAMP/htdocs/kiraMVC/u/lib/lib\DataManager.php'` the correct file path, or not?
Comment: @user9741470 Again, break the problem down. You have two strings: a directory name, which you can know by writing `echo __DIR__;`, and a class name, which you can check by writing `echo $className;`. Now throw away all your code and write a PHP file with nothing but those two strings, and play with string functions until it echoes the path where you know that class is defined; don't think about loading, or relative paths, just make that string. As soon as you've done that, the logic for your autoloader will become obvious; if it breaks for a different case, repeat the exercise.
Comment: I already tryed with the `__DIR__` but I got the same error `PHP Warning:  include_once(): Failed opening '/Applications/MAMP/htdocs/kiraMVC/u/lib/lib\DataManager.php' for inclusion (include_path='.:/Applications/MAMP/bin/php/php7.0.8/lib/php') in /Applications/MAMP/htdocs/kiraMVC/u/lib/autoloader.php on line 3
[25-Jun-2018 19:20:39 Europe/Berlin] PHP Fatal error:  Uncaught Error: Class 'lib\DataManager' not found in /Applications/MAMP/htdocs/kiraMVC/u/lib/demo.php:11`
Comment: The correct path is `kiraMVC/u/lib/` but the autoloader won't find the files inside te lib folder
Comment: since the autoloader is in the same folder of the test file, it will load the last folder of the classes path that is lib. so in the error message when I've added the `__DIR_` it will add two times the final folder of the required script. If i remove it, it will look inside the folder but it won't load the classes. I assume that this is because it can't load the right path.

spl autoload register error


PPPoE link has IP address, but 100% loss

Question: I couldn't figure out what's the problem with the PPPoE link. Here is the log entries I have found on pfSense. The interface is up and IP address has been requested, but all packets are said to be lost at 100%.
This is the overview of these two gateways
https://i.stack.imgur.com/x6Vru.jpg

And the configuration page
https://i.stack.imgur.com/cW1or.jpg

And link to the log entries:
http://paste.ubuntu.com/10768804/
<code>Apr 7 11:16:35  ppp: [opt1_link0] LCP: auth: peer wants PAP, I want nothing
Apr 7 11:16:35  ppp: [opt1_link0] PAP: using authname "xxxxxxx"
Apr 7 11:16:35  ppp: [opt1_link0] PAP: sending REQUEST #1 len: 24
Apr 7 11:16:35  ppp: [opt1_link0] LCP: LayerUp
Apr 7 11:16:35  ppp: [opt1_link0] PAP: rec'd ACK #1 len: 85
Apr 7 11:16:35  ppp: [opt1_link0] MESG: 0;User(email@example.com) Authenticate OK, Request Accept by chinamobile.com
Apr 7 11:16:35  ppp: [opt1_link0] LCP: authorization successful
Apr 7 11:16:35  ppp: [opt1_link0] Link: Matched action 'bundle "opt1" ""'
Apr 7 11:16:35  ppp: [opt1_link0] Link: Join bundle "opt1"
Apr 7 11:16:35  ppp: [opt1] Bundle: Status update: up 1 link, total bandwidth 64000 bps
Apr 7 11:16:35  ppp: [opt1] IPCP: Open event
Apr 7 11:16:35  ppp: [opt1] IPCP: state change Initial --> Starting
Apr 7 11:16:35  ppp: [opt1] IPCP: LayerStart
Apr 7 11:16:35  ppp: [opt1] IPCP: Up event
Apr 7 11:16:35  ppp: [opt1] IPCP: state change Starting --> Req-Sent
Apr 7 11:16:35  ppp: [opt1] IPCP: SendConfigReq #5
Apr 7 11:16:35  ppp: [opt1] IPADDR 0.0.0.0
Apr 7 11:16:35  ppp: [opt1] COMPPROTO VJCOMP, 16 comp. channels, no comp-cid
Apr 7 11:16:35  ppp: [opt1] PRIDNS 0.0.0.0
Apr 7 11:16:35  ppp: [opt1] SECDNS 0.0.0.0
Apr 7 11:16:35  ppp: [opt1] IPCP: rec'd Configure Request #1 (Req-Sent)
Apr 7 11:16:35  ppp: [opt1] IPADDR 172.31.0.1
Apr 7 11:16:35  ppp: [opt1] 172.31.0.1 is OK
Apr 7 11:16:35  ppp: [opt1] IPCP: SendConfigAck #1
Apr 7 11:16:35  ppp: [opt1] IPADDR 172.31.0.1
Apr 7 11:16:35  ppp: [opt1] IPCP: state change Req-Sent --> Ack-Sent
Apr 7 11:16:35  ppp: [opt1] IPCP: rec'd Configure Reject #5 (Ack-Sent)
Apr 7 11:16:35  ppp: [opt1] COMPPROTO VJCOMP, 16 comp. channels, no comp-cid
Apr 7 11:16:35  ppp: [opt1] IPCP: SendConfigReq #6
Apr 7 11:16:35  ppp: [opt1] IPADDR 0.0.0.0
Apr 7 11:16:35  ppp: [opt1] PRIDNS 0.0.0.0
Apr 7 11:16:35  ppp: [opt1] SECDNS 0.0.0.0
Apr 7 11:16:35  ppp: [opt1] IPCP: rec'd Configure Nak #6 (Ack-Sent)
Apr 7 11:16:35  ppp: [opt1] IPADDR 172.31.111.xx
Apr 7 11:16:35  ppp: [opt1] 172.31.111.xx is OK
Apr 7 11:16:35  ppp: [opt1] PRIDNS 18.104.22.168
Apr 7 11:16:35  ppp: [opt1] SECDNS 126.96.36.199
Apr 7 11:16:35  ppp: [opt1] IPCP: SendConfigReq #7
Apr 7 11:16:35  ppp: [opt1] IPADDR 172.31.111.xx
Apr 7 11:16:35  ppp: [opt1] PRIDNS 22.214.171.124
Apr 7 11:16:35  ppp: [opt1] SECDNS 220.127.116.11
Apr 7 11:16:35  ppp: [opt1] IPCP: rec'd Configure Ack #7 (Ack-Sent)
Apr 7 11:16:35  ppp: [opt1] IPADDR 172.31.111.xx
Apr 7 11:16:35  ppp: [opt1] PRIDNS 126.96.36.199
Apr 7 11:16:35  ppp: [opt1] SECDNS 188.8.131.52
Apr 7 11:16:35  ppp: [opt1] IPCP: state change Ack-Sent --> Opened
Apr 7 11:16:35  ppp: [opt1] IPCP: LayerUp
Apr 7 11:16:35  ppp: [opt1] 172.31.111.xx -> 172.31.0.1
Apr 7 11:16:36  ppp: [opt1] IFACE: Up event
</code>
Answer: Please check the "Dial on Demand" and at Idle Timeout put 0 if you do not want the connection to be closed, or put the number of seconds when you need it to be closed, I think it should be at lest 30 minutes.


How to get proper Z position of a gameObject when using ScreenToWorldPoint?

Question: I thought I previously had a solution to the problem but it seems that it isn't working as well as it should. Basically, I want to move a gameObject in 3D using the mouse while keeping the Z position the same. If I click and drag the gameObject, it should follow the cursor around without changing the depth of its position.
The code that I had was this:
screenSpace = Camera.main.WorldToScreenPoint(transform.position);
mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
mouseInWorld = Camera.main.ScreenToWorldPoint(mousePosition);

This worked fairly well, but the depth changed ever so slightly every time I moved the object. Why doesn't Unity work if I just do:
mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObject.transform.position.z);

Answer: There are a number of potential causes for this, but the most common would be there's a Rigidbody or Collider enabled that is interacting in some form with the environment that is causing the target object to move.
Try and set the mousePosition as 0:
mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);

If this works fine, then there is some form of interference either via the Physics system or another component etc that is changing the Z position.
Bear in mind that manually modifying an objects position depends heavily on when you update it.
Feel free to update me with more information if this is not the case, and I'll try to get back to you.
Comment: Sorry, I might've stated the problem a bit weirdly. Let me try and explain. If I put the z as transform.position.z, then the object does keep its z position. However, its x and y coordinates are not in line with where the mouse is, so the object is always a set distance away from the mouse.
Comment: Ah I see! That's due to some simple math, since the mouse is expecting a z position that is different to the one you've got.
Comment: Forgot to reply, to fix this I'll need a little more context - what are you planning to do? A simple plane at the same height of the character could be raycasted to, which you could then move the character to shortly after.

This would prevent the odd drift that you're getting now.


how do I make Drupal Zen sub theme mobile friendly?

Question: I have changed over to using the Zen theme (instead of Omega) on my drupal site, I have a Superfish menu configured with default settings for SF Small Screen plugin to enable on browser width (screen width 768px which is default). It worked perfectly on Omega where i had exactly the same settings, but now with my Zen sub theme, the menu doesn't change to a mobile friendly version when i reduce the browser width on safari. I have my site installed on localhost and looking at view source it shows:
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width">

Yet using the same site with omega theme it shows:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" >

Am i missing a setting on Zen to enable mobile responsive?
I have ticked all these settings on my zen sub theme:
Add HTML5 and responsive scripts and meta tags to every page.
 Add Respond.js JavaScript to add basic CSS3 media query support to IE 6-8.
 Add HTML5 shim JavaScript to add support to IE 6-8.
 Add meta tags to support responsive design on mobile devices.
Can anyone help?
Comment: There are a few possibilities here and I need more information. Is the Superfish menu a seperate contributed module? Where does it come from? Is the Superfish menu HTML markup identical in both themes? Basically you need to locate the media query styles which change the menu appearance at 768px.
Comment: Hi, the menu is the Drupal module called Superfish. Its the same module Im using in both Zen and Omega sub themes.
Comment: Hi, I have now gone back and activated the Omega theme, and its not working on that either, so my info above is not correct. Is wrong now on both themes. the menu is the Drupal module called Superfish. Its the same module Im using in both Zen and Omega sub themes. I will go back to a previous version when it worked and see whats changed. will come back with more info. thanks
Answer: I have just checked the Superfish project status and there are bug reports that Superfish breaks with jQuery versions 1.9 and above. Check what version of jQuery is loading and check if there are any Javascript errors in your browser console.
If that is the problem, you may have to wait for the next version update, or roll back to jQuery 1.8 for the time being.
Superfish jQuery 1.9 Bug Report
Comment: really appreciate your help. I have managed to resolve the problem now. I had upgraded the super fish module automtically via the Status screen, but not upgraded the Superfish library. Once I did that so they were both on the latest versions, and flushed cache it works again. I must have spent 2 or 3 hours googling to resolve this problem. I was thrown off course because I had switched themes from Omega to Zen which gave me a bit of a bum steer. School boy error really, must always check latest versions of module and any related library . thanks
Comment: No problem, glad it's sorted!
Answer: I have managed to resolve the problem now. I had upgraded the super fish module automtically via the Status screen, but not upgraded the Superfish library. Once I did that so they were both on the latest versions, and flushed cache it works again. I must have spent 2 or 3 hours googling to resolve this problem. I was thrown off course because I had switched themes from Omega to Zen which gave me a bit of a bum steer. School boy error really, must always check latest versions of module and any related library .


How to troubleshooting a D7 website that doesn't load (Gateway Timeout)

Question: A website of mine, using D7, suddenly doesn't load. I always receive a Gateway Timeout error.
The strange is that with a ftp client I can browse the website as usual
What are the steps I should follow to troubleshooting this situation?
Comment: If you get a 504, you need to confirm that the problem isn't between you and the webserver first. What do you mean "browse" the site with an ftp-client? Do you mean with a CLI client? Then does your normal client use a proxy that is malfunctioning? Until we can show that this has any kind of connection to Drupal, I think this sounds off-topic.
Comment: I'd look at how much ram you have available too in your php.ini.
Comment: Thank you very much for your help. Now I better understand the problem. I don't think this post is off-topic, because the problem is anyway related with Drupal (with other cms I didn't have this kind of problem). I've checked the memory limit, is 64M. I've contacted my provider in order to solve the problem and/or increase the memory limit (it's a shared host)
Answer: I solved the problem disabling the Database logging module.
I had the same problem also in another website (D7 + Database logging module, solved disabling the Database logging module)
Hope this helps.


How many 13 hand cards have one ace?

Question: I know the answer is ${4 \choose 1}{48 \choose 12}/{52 \choose 13}$. But I have trouble rationalizing it. Why is it not ${13 \choose 1}{4 \choose 1}{48 \choose 12}/{52 \choose 13}$ as in choose which of the $13$ spots the ace goes into and then choosing which of the $4$ aces and then choosing the rest of the twelve hands? I know it's wrong, but why is it wrong to think like this? Sorry I am really bad at combinatorics. Thanks.
Comment: because what you call the spots of the cards is irrelevant. A hand with an ace on the first spot and $12$ cards on the other spots does not differ from a hand with a an ace on the second spot accompanied by the same cards.
Answer: Remember, when it comes to hands, for example a five card hand
$A2346$ is the same as $6A234$. In other words, all $5!$ arrangements are equivalent. So, it does not matter  which 'spot' the Ace goes in, for example. We just care that the Ace is in our hand.
Hence, for a 13 card hand, we have to choose one ace, and there are $\binom{4}{1}$ ways to do it. Next, we choose the rest of the cards. Since they cannot be aces, then we have $52-4 = 48$ cards to choose from. So there are $\binom{48}{12}$ ways to choose the rest. Finally, there are $\binom{52}{13}$ ways to make a 13 card hand.
Thus the probability of making a hand with just one ace is
$$\frac{\binom{4}{1}\binom{48}{12}}{\binom{52}{13}}  =\frac{9139}{20825} = 0.438847539$$
Note $\binom{n}{k} = \frac{n!}{k!(n-k)!}$.

Addendum:
I'm not too familiar with games using 13 card hands, like Bridge (I think). But I am familiar with 5 card poker hands.
Let's say I want to calculate the probability getting a full house.
This would be something like $AAAKK$. Here is an instance where you do need $\binom{13}{1}$.
First I choose the rank that I want to be the triple. There are 13 ranks and so there are $\binom{13}{1}$ ways to choose the rank for the triple. Notice that I am not counting where the triple goes, but which rank will be constitute the triple. Let's say I choose Ace. There are four aces (diamonds,spades, clubs, hearts) but I only need 3. There are $\binom{4}{3}$ ways to choose the three suits of the aces. Next I choose the other rank and which two suits will make the double. There are $\binom{12}{1}$ ways to choose the other rank, and $\binom{4}{2}$ ways to choose the suits. Finally, there are $\binom{52}{5}$ ways to make a hand. Hence, the probability of making a full house is
$$\frac{\binom{13}{1}\binom{4}{3}\binom{12}{1}\binom{4}{2}}{\binom{52}{5}} = \frac{6}{4165} = 0.0014405762.$$
Answer: The answer you claim to know is the fraction, not the number.
To determine the number you have to consider the difference of combinations and permutations. In the second case, order is important, in the first case not.
Only in the case where order is important, you'd have to multiply by 13.
The formulas for the number of combinations of card sets, you seem to understand perfectly.
Answer: Your heading talks of number of hands, but
if you are interested in the probability, you can use permutations,(though involving unnecessary complexity for this problem), but what you did was to use permutations for one card and combinations for the rest.
If you use permutations whole hog, Pr $=\dfrac{52\cdot^{48}P_{12}}{^{52}P_{13}}$ will give the same result.
Or even the oddball approach of allowing choice of slots only to the first occupant, but in both numerator or denominator, would do, Pr $=\frac{52\cdot\binom{48}{12}}{13\cdot\binom{52}{13}},$
but needless to say, simplest is best, which here is to just use combinations. !
Added
If, as per the header, you are interested in the number of hands, a hand just doesn't consider the order in which the cards are dealt.
Answer: You can reason as follows: One of the hands that interest you is made up of an ace and 12 non-aces. The ace is selected as $1$ in $4$, the non-aces as $12$ in $52 - 4$. So there are $\binom{4}{1} \binom{52-4}{12}$ such hands. In all, there are $\binom{52}{13}$ hands.
In general, to approach such complex situations, it pays off to look for a way to describe what you are trying to count, hopefully as a sequence of independent decisions (pick the ace, pick the other cards). Counting the number of sequences is easy. And it avoids stupid mistakes. Just take care that there is just one description for a particular object, or that each object has e.g. 2 descriptions.
Check the MIT lecture notes by Lehman, Leighton, and Meyer "Mathematics for Computer Science" (there are very often new editions, look around). Relevant is part III "Counting", in particular the examples with poker hands (section 15.7 in the current edition).

How many 13 hand cards have one ace?