Como obter o Paramentro em um Web service em C# enviado do Android

Question: Estou consumindo um Web service desenvolvido em C#, a partir de uma aplicação em Android. Ao enviar tipos simples por parâmetro como string, int ou long, consigo obter a informação normalmente apenas colocando o mesmo tipo no parâmetro da declaração do método Web service. Mas não sei como obter um objeto complexo criado em java dentro do método web service em C#.
O objeto enviado tem o mesmo nome em ambas aplicações, mas não são exatamente iguais devido nomes das propriedades.
obs:
-Estou usando o Ksoap2 no android, e a classe esta sendo serializada e enviada para para o web service sem erros.
-talvez poderia obter o objeto como XML, mas que tipo eu colocaria no paramento?
Chamada web service
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        PropertyInfo object = new PropertyInfo();
        object.setName("obj");
        object.setValue(ordemServicoBO);
        object.setType(ordemServicoBO.getClass());

        request.addProperty(object);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.encodingStyle = SoapSerializationEnvelope.ENC;
        envelope.setOutputSoapObject(request);
        envelope.addMapping(NAMESPACE, "ordemServicoBO",new OrdemServicoBO().getClass());
        envelope.implicitTypes = true;
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.debug = true;
        androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

        androidHttpTransport.call(SOAP_ACTION, envelope);//Aqui a chamada é feita normalmente sem erro, e entra no método do web service

        SoapObject responseNoXML = (SoapObject)envelope.bodyIn;

Classe em Java
public class OrdemServicoBO implements KvmSerializable {

private long idOrdemServico;
private long IdOrdemServicoCategoria;
private long idOrdemServicoLocal;
private long idHotel;
private long idUsuarioExecutante;
private long idUsuarioSolicitante;
private long idArea;
private String dataAbertura;
private String descricao;
private String status;
private AreaBO areaBO;
private UsuarioBO usuarioSolicitante;
private UsuarioBO usuarioExecutante;
private OrdemServicoCategoriaBO ordemServicoCategoriaBO;

public void setOrdemServicoCategoriaBO(OrdemServicoCategoriaBO ordemServicoCategoriaBO) {
    this.ordemServicoCategoriaBO = ordemServicoCategoriaBO;
}

public OrdemServicoCategoriaBO getOrdemServicoCategoriaBO() {
    return ordemServicoCategoriaBO;
}

public void setUsuarioExecutante(UsuarioBO usuarioExecutante) {
    this.usuarioExecutante = usuarioExecutante;
}

public void setUsuarioSolicitante(UsuarioBO usuarioSolicitante) {
    this.usuarioSolicitante = usuarioSolicitante;
}

public UsuarioBO getUsuarioExecutante() {
    return usuarioExecutante;
}

public UsuarioBO getUsuarioSolicitante() {
    return usuarioSolicitante;
}

public void setDataAbertura(String dataAbertura) {
    this.dataAbertura = dataAbertura;
}

public void setDescricao(String descricao) {
    this.descricao = descricao;
}

public void setIdArea(long idArea) {
    this.idArea = idArea;
}

public void setIdHotel(long idHotel) {
    this.idHotel = idHotel;
}

public void setIdOrdemServico(long idOrdemServico) {
    this.idOrdemServico = idOrdemServico;
}

public void setIdOrdemServicoCategoria(long idOrdemServicoCategoria) {
    IdOrdemServicoCategoria = idOrdemServicoCategoria;
}

public void setIdOrdemServicoLocal(long idOrdemServicoLocal) {
    this.idOrdemServicoLocal = idOrdemServicoLocal;
}

public void setIdUsuarioExecutante(long idUsuarioExecutante) {
    this.idUsuarioExecutante = idUsuarioExecutante;
}

public void setIdUsuarioSolicitante(long idUsuarioSolicitante) {
    this.idUsuarioSolicitante = idUsuarioSolicitante;
}

public void setStatus(String status) {
    this.status = status;
}

public String getDataAbertura() {
    return dataAbertura;
}

public long getIdArea() {
    return idArea;
}

public long getIdHotel() {
    return idHotel;
}

public long getIdOrdemServico() {
    return idOrdemServico;
}

public long getIdOrdemServicoCategoria() {
    return IdOrdemServicoCategoria;
}

public long getIdOrdemServicoLocal() {
    return idOrdemServicoLocal;
}

public long getIdUsuarioExecutante() {
    return idUsuarioExecutante;
}

public long getIdUsuarioSolicitante() {
    return idUsuarioSolicitante;
}

public String getDescricao() {
    return descricao;
}

public String getStatus() {
    return status;
}

public void setAreaBO(AreaBO areaBO) {
    this.areaBO = areaBO;
}

public AreaBO getAreaBO() {
    return areaBO;
}

@Override
public Object getProperty(int arg0)
{
    switch(arg0)
    {
        case 0:
            return getDataAbertura();
        case 1:
            return getDescricao();
        case 2:
            return getStatus();
        case 3:
            return getIdOrdemServicoCategoria();
        case 4:
            return getIdOrdemServico();
        case 5:
            return getIdOrdemServicoLocal();
        case 6:
            return getIdArea();
        case 7:
            return getIdHotel();
        case 8:
            return getIdUsuarioExecutante();
        case 9:
            return getIdUsuarioSolicitante();

    }
    return null;
}
@Override
public void setProperty(int arg0, Object arg1)
{
    switch(arg0)
    {
        case 0:
            setDataAbertura(arg1.toString());
            break;
        case 1:
            setDescricao(arg1.toString());
            break;
        case 2:
            setStatus(arg1.toString());
            break;
        case 3:
            setIdOrdemServicoCategoria(Long.parseLong(arg1.toString()));
            break;
        case 4:
            setIdOrdemServico(Long.parseLong(arg1.toString()));
            break;
        case 5:
            setIdOrdemServicoLocal(Long.parseLong(arg1.toString()));
            break;
        case 6:
            setIdArea(Long.parseLong(arg1.toString()));
            break;
        case 7:
            setIdHotel(Long.parseLong(arg1.toString()));
            break;
        case 8:
            setIdUsuarioExecutante(Long.parseLong(arg1.toString()));
            break;
        case 9:
            setIdUsuarioSolicitante(Long.parseLong(arg1.toString()));
            break;
    }

}
@Override
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2)
{
    switch(arg0)
    {
        case 0:
            arg2.type = PropertyInfo.STRING_CLASS;
            arg2.name = "CategoryId";
            break;
        case 1:
            arg2.type = PropertyInfo.STRING_CLASS;
            arg2.name = "Description";
            break;
        case 2:
            arg2.type = PropertyInfo.STRING_CLASS;
            arg2.name = "Name";
            break;
        case 3:
            arg2.type = PropertyInfo.INTEGER_CLASS;
            arg2.name = "CategoryId";
            break;
        case 4:
            arg2.type = PropertyInfo.INTEGER_CLASS;
            arg2.name = "CategoryId";
            break;
        case 5:
            arg2.type = PropertyInfo.INTEGER_CLASS;
            arg2.name = "CategoryId";
            break;
        case 6:
            arg2.type = PropertyInfo.INTEGER_CLASS;
            arg2.name = "CategoryId";
            break;
        case 7:
            arg2.type = PropertyInfo.INTEGER_CLASS;
            arg2.name = "CategoryId";
            break;
        case 8:
            arg2.type = PropertyInfo.INTEGER_CLASS;
            arg2.name = "CategoryId";
            break;
        case 9:
            arg2.type = PropertyInfo.INTEGER_CLASS;
            arg2.name = "CategoryId";
            break;

        default:break;
    }

}
@Override
public int getPropertyCount()
{
    return 10;
}
}

Método Web service C#
[WebMethod]
public OrdemServicoBO Exportar(OrdemServicoBO ordemServicoBO)//quando é executado o androidHttpTransport.call() é chamado esse método, mas o retorno, que é o mesno recebido por parâmetro, esta vazio.
{
    return ordemServicoBO; //Atualmente retorna vazio
}

classe em C#
public class OrdemServicoBOAPP
{
    private long _idOrdemServico;

    public long IdOrdemServico
    {
        get { return _idOrdemServico; }
        set { _idOrdemServico = value; }
    }
    private long _IdOrdemServicoCategoria;

    public long IdOrdemServicoCategoria
    {
        get { return _IdOrdemServicoCategoria; }
        set { _IdOrdemServicoCategoria = value; }
    }
    private long _idOrdemServicoLocal;

    public long IdOrdemServicoLocal
    {
        get { return _idOrdemServicoLocal; }
        set { _idOrdemServicoLocal = value; }
    }
    private long _idHotel;

    public long IdHotel
    {
        get { return _idHotel; }
        set { _idHotel = value; }
    }
    private long _idUsuarioExecutante;

    public long IdUsuarioExecutante
    {
        get { return _idUsuarioExecutante; }
        set { _idUsuarioExecutante = value; }
    }
    private long _idUsuarioSolicitante;

    public long IdUsuarioSolicitante
    {
        get { return _idUsuarioSolicitante; }
        set { _idUsuarioSolicitante = value; }
    }
    private long _idArea;

    public long IdArea
    {
        get { return _idArea; }
        set { _idArea = value; }
    }
    private String _dataAbertura;

    public String DataAbertura
    {
        get { return _dataAbertura; }
        set { _dataAbertura = value; }
    }
    private string _descricao;

    public string Descricao
    {
        get { return _descricao; }
        set { _descricao = value; }
    }
    private string _status;

    public string Status
    {
        get { return _status; }
        set { _status = value; }
    }
    private AreaBOAPP _areaBO;

    public AreaBOAPP AreaBO
    {
        get { return _areaBO; }
        set { _areaBO = value; }
    }
}

Comment: Fernando, por favor poste o código relevante. Existem vários bibliotecas para Android capazes de fazer *unmarshalling* do XML em um objeto. Minha recomendação seria o [Simple](http://simple.sourceforge.net/).
Comment: acredito que se você enviar o objeto com o nome das propriedades iguais o próprio c# irá mapear esse objeto.
Comment: Coloquei o mesmo nome nas propriedades e nada mudou. Se eu pudesse obter o XML como string daria pra montar o objeto manualmente, mas já mudei para string e tbm vem vazio.
Comment: Se o webservice é seu e está em WCF aconselho anotar os métodos e criar endpoints para trabalhar com Rest. Sua vida será bem mais fácil. De qualquer modo, talvez o Aerogear sirva para você: http://aerogear.org/
Answer: Pelo seu código parece que você já aprendeu a implementar a interface KvmSerializable para mapear objetos complexos para XML e vice-versa. Caso contrário, veja esse exemplo do Wsdl2Code (que, por sinal, é uma ferramenta excelente para gerar esse tipo de boilerplate code para você). Uma vez que você esteja com o mapeamento dos objetos complexos pronto, a chamada é razoavelmente simples:
Você já adicionou um mapeamento de um um nome para uma classe. Nesse caso não sei se ordemServicoBO é um nome de um elemento na chamada ou na resposta do seu serviço. No caso do serviço Exportar você precisa mapear as duas para o mesmo tipo de objeto (OrdemServicoBO):
// Estou assumindo algumas coisas sobre o WSDL e o serviço Exportar
// O nome "ordemServicoBO" podem ser completamente diferente
// Em alguns casos pode ser que o request ou a resposta estejam encapsuladas, em
// outro objeto, etc
envelope.addMapping(NAMESPACE, "ordemServicoBO", new OrdemServicoBO().getClass());

Feito isso, vamos adicionar as propriedades do request (conforme mapeamento acima que prevê um parâmetro ordemServicoBO)
// Veja que novamente o nome desa propriedade depende do seu WSDL
request.addProperty("ordemServicoBO", ordemServicoBO);

Ao fazer a chamada, assumindo que os mapeamentos estejam corretos, seu serviço do lado do .NET irá receber um objeto completo:
 androidHttpTransport.call(SOAP_ACTION, envelope);

Mais uma vez assumindo que o seu WSDL retorna um tipo complexo de resposta diretamente no corpo da resposta, para recuperar o valor do lado do Android basta fazer um cast desse objeto:
 OrdemServicoBO result = (OrdemServicoBO) envelope.getResponse();

Caso exista algum tipo de indireção você precisará tratar isso manualmente (novamente vide exemplo do Wsdl2Code)
Obtendo os XMLs gerados para efeito de debugging:
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);

androidHttpTransport.requestDump; // string contendo a chamada
androidHttpTransport.responseDump // string contendo a resposta

TL;DR

Você já está mapeando tipos complexos através da interface KvmSerializable
Agora é questão de acertar os mapeamentos entre namespaces, nomes e classes conforme seu WSDL.
Use as propriedades requestDump e responseDump para obter Strings contendo XML

Dicas:

Use um cliente externo como o SoapUI para testar chamadas e respostas. Ajuste o OrdemServicoBO até que a variável requestDump fique idêntica ao XML de request do SoapUI.
Verifique seu WSDL (exemplo), todos os elementos e mapeamentos devem responder aos namesnas tags <s:element>.
A ferramenta Wsdl2Code pode gerar tudo isso para você.

Fonte: ksoap2-android -  Coding Tips And Tricks
Comment: Sim, eu estava olhando da perspectiva errada. Enviei o objeto como o WS esperava e com a ajuda do requestDump tornou muito mais fácil. Apesar do C# montar automaticamente o objeto, algo que não gosto muito. Mas de qualquer maneira funcionou e ajudou muito. Obrigado
Comment: Vou olhar o Wsdl2 e estuda-lo. Acredito que a serialização do esteja sendo feita corretamente, pois não aponta erros e o conteúdo do bodyout parece estar correto. A obtenção de de tipos complexos como retorno do WS tbm esta certo, pois já estou fazendo isso sem problemas. Mas minha duvida está na parte do envio de objetos complexos em que vc diz "Ao fazer a chamada, assumindo que os mapeamentos estejam corretos, seu serviço do lado do .NET irá receber um objeto completo", qual é o tipo do parâmetro que o lado .NET vai receber? uma string com o XML do objeto enviado? Algum tipo XML?
Comment: Olá Fernando. Acho que você está olhando isso da perspectiva errada. O .NET pode consumir um DTO como você está fazendo sem problemas. Com isso o .NET irá gerar um WSDL para esse e os demais métodos declarados. Tente apendar `?wsdl` ao seu serviço para ver o que o .NET gerou. Agora é sua responsabilidade fazer o cliente serializar o objeto do *request* exatamente como o .NET espera receber o objeto.
Comment: Como você está tentando gerar o *request* manualmente muito provavelmente está cometendo erros de serialização (dica: preste atenção no seu método `getPropertyInfo`) além de não estar usando os nomes de elementos esperados pelo .NET.
Comment: Então minha dica é, ou use o `wsdl2code` para gerar tudo bonitinho a partir do WSDL (realmente não tem muito o que aprender, basta exportar o WSDL, submeter no site e fazer download do *client* gerado) ou tente acertar esse tipo de detalhe na unha.
Comment: Para acertar esse tipo de detalhe na unha novamente te recomendo furar a abstração, utilizar um cliente externo com o [SoapUI](http://www.soapui.org/) para testar o serviço manualmente e aprender a construir os *payloads* para o seu serviço (já que o problema está no *request*). Uma vez que você tenha entendido como o seu *web service* funciona, faça com que seu código no Android construa o exato mesmo tipo de *payload* modificando o código cliente (você pode obter o *XML* crú através do método *androidHttpTransport.requestDump*). Ficou mais claro?
Comment: O que é importante ficar claro aqui é: A nível de SOAP o que existem são *payloads* no corpo de um *envelop*. O trabalho todo aqui é fazer com que o seu código cliente faça *marshalling* do objeto enviado na maneira que o serviço espera receber no *request*, e, analogamente, *unmarshalling* corretamente daquilo que o serviço retorna (essa segunda parte você disse que já acertou).
Comment: Fico feliz em ajudar Fernando. Se o problema está resolvido não se esqueça de aceitar minha resposta ;).


Is it possible to add a timer to a button?

Question: I have a button that performs an action, is it possible to create a timer so the button can only be used every 6 hours or so?
Would need to be for each specific user, so if one user presses the button, it won't affect another user's cooldown or ability to press it.
Here's the form

<form action="addgold.php">
<input type="submit" name="Add gold" value="Work" onclick="addgold()" />
</form>

And here's the action that the button performs if it is needed
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
include("header.php");
include("connect.php");
if(isset($_SESSION['userlogin'])){
$username = $_SESSION['userlogin'];
$sql = "SELECT stats.id, stats.gold, users.id, users.username FROM stats, users WHERE users.username     = '$username' AND stats.id = users.id";
$retval = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($retval, MYSQL_ASSOC))
{
echo "Gold :{$row['gold']}
 ".

     "--------------------------------
";
}
$row = mysqli_fetch_row($retval);
$result = $row[0];

echo "Back to main page";
}else{
?>

<?php
echo "fail";
}
?>

I found a similar answer to this in another Stackoverflow question (this site has everything) that said it can only be done in javascript, which is fine besides I haven't a clue about javascript!
There was some code he/she put with it
window.setTimeout(function() {
document.forms['form_name'].submit();
}, 1000);

But where do I put that? into my php page? if so, where?
Comment: It is not JAVA but it is a Javascript. Huge difference.
Comment: You need to save the user and the last time he clicked the button ( preferrably in a database ).
Comment: @tttpapi I know sorry, edited!
Comment: @DOCASAREL Yeah that makes sense, can you point me in the right direction to learn the code? I can't find anything like that
Answer: It is really important how you want the button will work.
1) Is it only for registered users
Save it to database. And then just check the DB time difference.
2) For everyone
If it does not have to be 100 % accurate you can use a session or you can also save the information to DB and then check the difference.
Comment: Saving it through the database seems the best way :) I'll get on it, thanks!
Answer: Assuming your app has authentication in place, which identifies each user uniquely, you can create a table in your DB (or add a column to your users table) which stores  the last time a user has pressed the button as a DATETIME type.
Then all you have to do when the page is requested is calculate the difference between the current time and the one stored in your DB. Using mysql:
SELECT HOUR(TIMEDIFF(NOW(),last_pressed)) AS time_passed FROM my_table

If the difference is less than 6 hours you simply remove or disable the button. Do note that removing the button is not enough and you have to block the action on the server side as well, because a seasoned user can send the request via the browser's URL bar or using curl without using the button.
If you don't have proper session authentication, you can resort to @ploutch's solution, and save the IP address instead of the user ID. This is not perfect because the headers sent to the server can be tampered with by the client.
Answer: If you put your limiter in javascript, it will be done client-side, which means if a user knows about programming, he'll easily be able to go around that protection.
If you really want to enforce a time limit between clicks, it should be done server-side, but that means that the server must be able to recognize clients. What is generally done is using the IP address (even if it's not perfect), which you can get by checking the $_SERVER['REMOTE_ADDR'] variable in PHP.
Answer: If you want to compel observance of  time limit between clicks surely you would need to use $_SESSION[] in php(server side) for this purpose and save the information to the database.
Answer: Try setTimeout function in javascript
<input type="button" value="click" id="click" onclick="foo(this);"/>

in javascript
function foo(obj) {
    obj.disabled = true;
    setTimeout(function() {
        obj.disabled = false;
    }, 2000);
}


How can I even out a random distribution while minimising how far each data point is moved?

Question: I have a software application which uses a queue and multiple processors to process those jobs. Jobs get re-run on a daily basis for customers, but we also have new customers signing up regularly.
The problem is that customers generally sign up during office hours, and the daily re-running of the jobs simply schedules the job to run at the same time every day. This means that we have built up quite large spikes of work during the day, with very few jobs running overnight.
I would like to even out the spikes in this job queue, but I also want to minimise how far each individual job is moved from it's original time slot. In other words, I would rather move 100 jobs by 5 minutes each than move 1 job by an hour to achieve an even distribution of jobs over the whole 24 hour period.
Answer: This is a problem in optimal control.  But you only need a few tools to get a practical solution for your problem.
1) a way to estimate the time distribution of jobs from new customers.  Plotting the hourly, daily, and weekly averages for instances of jobs from new customers will give you a feel for the periodicity of the distribution.  Then you can fit the distribution to a time-dependent Poisson process, with terms for minute/hour/day/week.
2) quantification of your "loss function."  Based on your statement I would imagine that your loss function will include a term penalizing concentrations of jobs in short time periods and a term penalizing time delays on jobs in a nonlinear fashion.  Supposing $t_1,...,t_2$ represents the times at which jobs are executed, and $d_1,...,d_m$ represents the delays for job 1, job 2, etc., your loss function might look like
$$
L = k_1 \sum_{i=1}^m (\sum_{j=1}^m I(t_i - t_j < T))^2  + k_2 \sum_{i=1}^m d_i^2
$$
where $k_1$ and $k_2$ are positive constants, and $T$ is a 'critical' time period (like 5 minutes).
3) simulation of various control policies (scheduling of recurring jobs) to find their expected loss.  Given a policy of running daily jobs at time $x_1,...,x_l$ you would draw from your distribution of new jobs to get times of new jobs $y_1,...,y_m$ (where $m$ is random).  You can estimate the expected loss by doing the simulation many times and averaging the loss function over the runs.


If we didn't have examples of irrational numbers, would we know they exist?

Question: Irrational numbers are very easy to find. Square roots require only a little bit more than the most basic arithmetic. So it might be that this question is impossible to answer because it presupposes a world where math looks completely different to what it really does. I am hoping this is not the case.
If we didn't have examples of irrational numbers, would $\mathbb{R}$ and $\mathbb{Q}$ be assumed to be the same set?
Can we construct a proof that irrational numbers exist without giving examples?
Comment: As a relevant point, we know there are [Uncomputable Numbers](https://en.wikipedia.org/wiki/Computable_number) though, for obvious reasons, nobody can write one down.  We know this via counting arguments...there can be only countably many programs but there are uncountably many reals.
Comment: One counter-example is enough to prove that we cannot express some quantities using rational numbers.
Comment: Interesting question! It's kind of related to the concept of a [complete metric space](https://en.wikipedia.org/wiki/Complete_metric_space). If our idea of a "number" was just "something of the form $a/b$ for an integer $a$ and a positive integer $b$", we could still do a lot of arithmetic. We could prove that there is no number $x$ such that $x^2 = 2$. However, there is a *sequence* $(x_n)$ such that $x_n^2$ gets as close to $2$ as we want. (eg $14/10, 141/100, \dotsc$). This begs the question "is there a number system where sequences like this converge to a value?". This is $\Bbb R$.
Comment: Although I gave an answer I also downvoted. If we didn't have irrational numbers, then what is $\mathbb{R}$? How are you asking the question "would $\mathbb{R}$ and $\mathbb{Q}$ be assumed to be the same?
Comment: @T_M Yes, thus my hesitation in the first part. But it turns out there are great answers, as I had hoped.
Answer: From the surrounding discussion it seems that perhaps there are two questions here:

What is the impetus to define the real numbers and how do we get such a definition?

Given a definition of $\mathbb{R}$ can we prove that irrational numbers exist without constructing examples?

My answer addresses the latter question.
You can prove that the real numbers are uncountable (there is no bijection between the real numbers and the integers).
You can prove the rational numbers are countable (there is a bijection between the rational numbers and the integers).
So $\mathbb{R}\setminus\mathbb{Q}$ is nonempty.
Since I don't know your background I will add some more.

A bijection between two sets $X$ and $Y$ is a function $f:X\to Y$ that is both one-to-one and onto, i.e, for all $x,y\in X$, $f(x)=f(y)$ implies $x=y$; and for all $y\in Y$ there is $x\in X$ such that $f(x)=y$.

An infinite set is $X$ countable if there is a bijection $f:X\to \mathbb{N}$.

It is a famous result of Cantor (called a diagonal argument) that $\mathbb{R}$ is uncountable.

It is a standard (and good practice) exercise that $\mathbb{Q}$ is countable.

It is a standard (and good practice) exercise that if $X$ and $Y$ are countable then so is $X\cup Y$. So if $\mathbb{R}\backslash \mathbb{Q}$ were countable then so would be $\mathbb{R}$.

So altogether, this actually shows that not only do irrational numbers exist, but there are more irrational numbers than rational numbers because the set $\mathbb{R}\backslash\mathbb{Q}$ must be uncountable by the above points.
By the way, the same kind of proof shows that transcendental numbers exist and there are more transcendental numbers than algebraic numbers. Indeed, the set of algebraic numbers is also countable and so its complement in $\mathbb{R}$ is uncountable.
Comment: @MauroALLEGRANZA If you don't presuppose a definition of $\mathbb{R}$ then how does one interpret the question: "Would $\mathbb{R}$ and $\mathbb{Q}$ be the same set?"
Comment: But this proof presupposes a *definition* of reals... Assuming (as per the OP's question) that we haven't found any irrational (that means that we are still thinking that the ration side/diagonal is expressible by some "convoluted" fraction), what are the "reals" ?
Comment: Dedekind cuts (ie bounded above subsets $A$ of $\mathbb{Q}$ without a greater element such if $x \in A$ and $y < x$, then $y \in A$), for instance.
Comment: @MauroALLEGRANZA We might notice that not every bouded set of rationals has a *least* upper bound. At that point we might decide that such non-existent suprema do not deserve to be called numbers and leave it at that. But we might find these non-existing numbers useful because we *can* do useful computations with them - similar to how "impossible" square roots of negative numbers might help find (real) roots of polynomials by "blindly" computing with them, which is how historically imaginary/complex numbers got promoted from weird auxiliary construction to actual numbers
Comment: @MauroALLEGRANZA I should add that I take your point about the philosophical question of defining the reals. But there are plenty of definitions of the reals that don't require one to assume the existence of irrationals. So have that philosophical discussion and decide on a definition of $\mathbb{R}$. Then my answer (rather Cantor's) shows that irrationals exist.
Comment: From my point of view, the "counterfactual" question in the title: "What happened if we do not discovered the proof of the irrationality of $\sqrt 2$ ?" is difficult to answer... Ancient [Egyptian math](https://en.wikipedia.org/wiki/Ancient_Egyptian_mathematics) "lived" about 2.000 years using fractions without "irrationals" at all. The big "divide" is between ancient "others" math and Ancient Greek math that **discovered** it. The interesting fact is the link with "proof": Greek math discovered the "irrationality" phenomenon and this led them to invent the "tool" named *mathematical proof*.
Comment: Thus, assuming this point of view (a sort of "alternative history" scenario), maybe we do not have the concept of mathematical proof available...
Comment: @MauroALLEGRANZA Yes, it is an interesting discussion and I like your points. I hope that if for some reason the human brain had a blind spot for algebra/arithmetic, we still would have developed the concept of mathematical proof through other means like geometry.
Comment: But the proof **was** developed through geometry... The proof of the irrationality is a geometrical one (no algebra) :-)
Comment: @MauroALLEGRANZA Yes of course I know that. But the statements involving commensurability of diagonals of squares with their sides still have algebraic flavor on their face. Compare to something like Desargues' Theorem in which the algebra is much more esoteric. One could imagine a scenario in which humans could not perceive of notions like commensurability, while still making sense something like of Desargues' Theorem and proving it.
Comment: Thanks @halrankard... I liked your original answer better, it was very simple and clear. Oh well, this is better for posterity I suppose. Like you said, my question presupposes the definition of real numbers.
Answer: halrankard's answer is good but this may help as well.
It is common to define various sets which are larger than the rational numbers $\mathbb{Q}$ yet still smaller than the reals $\mathbb{R}$.  By larger and smaller here, I just mean one is a strict subset of the other.
halrankard mentions the Algebraic numbers $\mathbb{A}$.  These are the roots to polynomials with rational coefficients.  $\sqrt{2}$ is algebraic but $\pi$ is not.
Larger again, are the Computable numbers.  Informally, these are ones that an ideal computer, e.g. a Turing machine, could calculate.  $\pi$ is computable, you can calculate it to any desired precision in a finite time.
Larger again are the Definable numbers.  Informally, we can specify these precisely yet we cannot even compute them.  We know that there are numbers which are definable but not computable.  They are necessarily rather weird.  See this earlier question.
And this is still not all real numbers.  All of these sets are countable.  This means that although intuitively each set is bigger than the previous one, they can all be put into one to one correspondence with the smallest infinite set: the natural numbers $\mathbb{N}$.  We could assign each definable number a unique natural number label without missing any.
However, we know that the real numbers are not countable so there must be undefinable numbers and that most real numbers are undefinable.
So, one of these last two sets might be like what you want: we know that they exist but we cannot point to any examples.  No one will ever prove that a specific number is undefinable since, if they could specify which number they are talking about then it is definable
Answer: I think the answers so far miss a very basic point: Perhaps the most famous proof in mathematics shows that there is no rational number $x$ with $x^2 = 2$. This is not the same as saying "$\sqrt{2}$ is irrational". The reason they are not the same is because the former can be articulated as a statement just about rational numbers, before any development of the reals or the square root function or any concept of "irrationality". Now it is up to you whether or not you want to try to expand to a larger number system in which $x^2 = 2$ has a solution.


generate sequence in sql select

Question: I need to write a query that will generate a sort of sequenced ID for each record... so for example:

ID      Customer Name
-------------------------
C1000   customer #1
C1010   customer #2
C1020   customer #3
C1030   customer #4

now, these "C1000" ids don't exist... only the customer names.  I need to generate them when I do the select... so I can save off the output, and then import into the new system.
how can I do a:

select
   'C' + (some kinda code/math that generates the count based on a sequence?  or row number?),
   name
from Customers

================================================
I ended up doing the following (so I could configure start# and increment size):

DECLARE @start int;
DECLARE @inc int;
set @start = 1000;
set @inc = 10;

Select 'C' + CAST(@start + (@inc * (ROW_NUMBER() OVER (ORDER BY name))) as varchar) as NewID, Name
from customer

Comment: You'll need something to order by or the generated sequences will be unpredictable (will change between runs).
Answer: Use ROW_NUMBER() as in this example.

generate sequence in sql select


itextsharp não acrescenta páginas em loop

Question: Coloquei meu codigo dentro de um FOR para exibir varias paginas conforme a contagem do mesmo. Acontece que ele mostra apenas a ultima pagina, e não todas que deveriam.
For s  = 0 To 9
html = "
 "& s & "
"

'PDF
Using reader As TextReader = New StringReader(html)
 Dim pdfwrite As PdfWriter = PdfWriter.GetInstance(document, Response.OutputStream)'
 document.Open()
 document.NewPage()'
 XMLWorkerHelper.GetInstance().ParseXHtml(pdfwrite, document, reader)
End Using
next
document.close()

'Visualiza
Dim resp As HttpResponse = Me.Response
resp.ContentType = "application/pdf"
resp.AddHeader("Content-Disposition", "filename=sigov" & Now.Day & Now.Month & Now.Year & Now.Second & ".pdf")

Comment: não seria `html +=` para concatenar ?
Answer: Achei este exemplo que funcionou perfeitamente.
Sub Main()
Using doc = New Document(PageSize.A4, 50, 50, 50, 50)
        Using writer As PdfWriter = PdfWriter.GetInstance(doc, Response.OutputStream)
        doc.Open()
        doc.AddTitle("PPN Rebate Invoice")
        doc.AddAuthor("PPN")
        for i as integer = 0 to 9
          Dim html = "<!DOCTYPE html><title>Test</title>
This is a test:" & i & "
"
          Using reader As TextReader = New StringReader(html)
              XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, reader)
              doc.NewPage
          End Using
        Next
        doc.Close()
        'if i = 9 then doc.NewPage()
    End Using
End Using
End Sub


AWS SSM as a valueFrom for task in Terraform not working

Question: I am defining a task in AWS which I already have working using aws_ecs_task_definition module. I am setting up some environtment variables using the environtment var in terraform module but some of the will be provided throug AWS SSM. The normal creation without AWS SSM is:
environment : [
        {
          name : "user",
          value : "name"
        },
      ],

This works like a charm.
Then I tried:
environment : [
        {
          name : "user",
          valueFrom : "my_env_var_name_in_ssm"
        },
      ],

But it doesn't work. When I go to the UI of the task definition the ENV variable is not there, neither in the UI's json definition.
Then I tried to create them in the UI and the task work perfect and I saw that when you setup valueFrom, the ENV variable is created under the secrets section of the json definition. So I tried to replicate it in Terraform such as:
secrets : [
        {
          name : "user",
          valueFrom : "my_env_var_name_in_ssm"
        },
      ],

But it doesn't work neither. The task definition json is:
{
  "ipcMode": null,
  "executionRoleArn": "arn",
  "containerDefinitions": [
    {
      "dnsSearchDomains": null,
      "environmentFiles": null,
      "logConfiguration": null,
      "entryPoint": null,
      "portMappings": [
        {
          "hostPort": 8080,
          "protocol": "tcp",
          "containerPort": 8080
        },
        {
          "hostPort": 8793,
          "protocol": "tcp",
          "containerPort": 8793
        }
      ],
      "command": null,
      "linuxParameters": null,
      "cpu": 7,
      "environment": [
        {
          "name": "name",
          "value": "harcoded"
        },
      ],
      "resourceRequirements": null,
      "ulimits": null,
      "dnsServers": null,
      "mountPoints": [],
      "workingDirectory": null,
      "secrets": null,
      "dockerSecurityOptions": null,
      "memory": null,
      "memoryReservation": 128,
      "volumesFrom": [],
      "stopTimeout": null,
      "image": "image_arn",
      "startTimeout": null,
      "firelensConfiguration": null,
      "dependsOn": null,
      "disableNetworking": null,
      "interactive": null,
      "healthCheck": null,
      "essential": true,
      "links": null,
      "hostname": null,
      "extraHosts": null,
      "pseudoTerminal": null,
      "user": null,
      "readonlyRootFilesystem": null,
      "dockerLabels": null,
      "systemControls": null,
      "privileged": null,
      "name": "my-name"
    }
  ],
  "placementConstraints": [],
  "memory": null,
  "taskRoleArn": "arn",
  "compatibilities": [
    "EC2"
  ],
  "taskDefinitionArn": "arn",
  "family": "family-name",
  "requiresAttributes": [
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.ecr-auth"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.21"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.task-iam-role"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-ecr-pull"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.task-eni"
    }
  ],
  "pidMode": null,
  "requiresCompatibilities": [],
  "networkMode": "awsvpc",
  "cpu": null,
  "revision": 2,
  "status": "ACTIVE",
  "inferenceAccelerators": null,
  "proxyConfiguration": null,
  "volumes": []
}

As you can see the json returns: "secrets": null,
When the terraform run a container_definitions like this:
container_definitions = jsonencode(
  [
    {
      name = aws_ecs_cluster.cluster.name,
      image = "${var.image_url}:latest",
      cpu = 7,
      dnsSearchDomains = null,
      network_configuration = "awsvpc",
      entryPoint = null,
      portMappings = [
        {
          hostPort = 8080,
          protocol = "tcp",
          containerPort = 8080
        },
        {
          hostPort = 8793,
          protocol = "tcp",
          containerPort = 8793
        }
      ],
      command : null,
      linuxParameters : null,
      environment : [
        {
          name : "name",
          value : "harcoded"
        },
      ],
      secrets : [
        {
          name : "parameter-name",
          valueFrom : "arn:aws:ssm:eu-west-2:111111111:parameter/my_env_var_name_in_ssm"
        },
      ],
      resourceRequirements : null,
      ulimits : null,
      dnsServers : null,
      mountPoints : null,
      workingDirectory : null,
      secrets : null,
      dockerSecurityOptions : null,
      memoryReservation : 128,
      volumesFrom : [],
      stopTimeout : null,
      startTimeout : null,
      firelensConfiguration : null,
      dependsOn : null,
      disableNetworking : null,
      interactive : null,
      healthCheck: null
      essential : true,
      links : null,
      hostname : null,
      extraHosts : null,
      pseudoTerminal : null,
      user : null,
      readonlyRootFilesystem : null,
      dockerLabels : null,
      systemControls : null,
      privileged : null
    }
  ]
  )
}

terraform apply worked fine but the secrets are not in the output of the terraform performed actions, so it's normal that the json definition shows null. Then I guess the real issue is how to writte it in terraform.
How can I use AWS SSM as a valueFrom in AWS ECS task defined in Terraform? As you can see the json is
Comment: "terraform apply worked" - so the secret correctly gets resolved? If so, I'm not sure what is the issue?
Answer: Your task definition has secrets defined twice. Once with a value, and once with null:
See the first and last lines in this block I copied from the code you posted:
  secrets : [
    {
      name : "parameter-name",
      valueFrom : "arn:aws:ssm:eu-west-2:111111111:parameter/my_env_var_name_in_ssm"
    },
  ],
  resourceRequirements : null,
  ulimits : null,
  dnsServers : null,
  mountPoints : null,
  workingDirectory : null,
  secrets : null,

You need to remove the line secrets : null because it is overriding the earlier setting.
Comment: boh, thank you @MarkB I checked the script several times and I didn't see it. Sorry for the dumb question.


Why are we allowed to divide by $x$ in the following differential equation?

Question: Suppose we have a second order linear differential equation $x\frac{d^2y}{dx^2}+\frac{dy}{dx}-xy=xe^x$.Often we divide both sides by $x$ to get $\frac{d^2y}{dx^2}+\frac{1}{x}\frac{dy}{dx}-y=e^x$,and then proceed towards solution.Why does this make no harm as far as the solution of the differential equation is considered.We were trying to find $y=\phi(x)$ whose domain is $\mathbb R$.But,now we are finding a solution $y=\psi(x)$ whose domain is $\mathbb R-\{0\}$.Of course it is clear that the family of solutions $\phi(x)$ and $\psi(x)$ are equal except one has $0$ in domain and other does not ,I mean we can extend the other one to $\mathbb R$ by assigning some value at $0$ so that the extension is continuous.Does this make sense?Is this why we can divide by $0$ without worrying about losing anything?
Answer: Of course you have to worry about dividing by $x=0$. Having $x$ as a coefficient (especially of the highest-order term) is often a sign that you should expect some kind of weird behaviour of the solutions at $x=0$.
Comment: What kind of weird behaviour are you talking about,please write a bit more elaborately.
Comment: Well, for example it might happen that initial value problems with data at $x=0$ have infinitely many solutions, or no solutions, depending on what the data are.
Comment: please add an explicit example in you answer.
Comment: It would be a useful exercise to try to construct your own examples... But very well, consider $xy'+y=0$ with $y(0)=0$ vs. $y(0)=1$.


MySQL query to get non-data for unassigned dates

Question: I have a table with weekly data that looks like:
<code>userID       Site             date
------      ------           ------
Smith    Ferris Wheel       2009-07-13
Jones   Outerspaceland      2009-07-13
LChar   Ferris Wheel       2009-07-14
Smith     Underworld        2009-07-16
Jones     Fish Bowl         2009-07-17
Munson    Go-Go Tech        2009-07-16
</code>
Currently I have a PHP script that first gets the date range (Monday -- Friday), then does a query for each userID for that date range. Then, I loop through the results and check for gaps between dates. If there is gap, it outputs the date and the Site is listed as "Stay Home." It has to account for several days in a row (like if the user is only stationed on Monday and Friday that week), and it has to an extra step at the end of each week to make sure that if the user is staying home after Wednesday (thus having Thursday and Friday to fill in as gaps).  So there are three checks it has to make, one for users not starting on Monday, one for gaps between days, and one for users ending before Friday...plus it has to account for days in a row for any of those situations.
The script basically creates an array of the date range to check against, and it has worked fine for months. HOWEVER
I was wondering, is there a MySQL function to have days off returned for each user? So that I can have it fill in "Stay Home" in the query and not have to run a funky script that takes forever to explain to other people working with me on my script?
Thanks!
Answer: Easy!
Flip the query around!
That is:

Create a lookup table with the days of the week
Sculpt a query that performs a LEFT_OUTER_JOIN on the lookup table and your table DAYNAME(field).  That is, it will return all rows from the lookup table and only those that match in your table,,,

I'm not sure if you want to filter by person .. the criteria would look like userid = 'person' or userid is null
The resulting  data will look be ...

A ROW for ALL DAYS
In the row, UserIDs will exist for  Non Blank Days and be null for days skipped
Comment: If I have a table that is just Monday - Sunday that I could reuse over and over, is there a date function that will, based on the actual date range reverse those weekdays into actual dates? One of my goals is to have as much of, if not all of, my html actual returned by the SQL query using concat and whatnot, so while using your idea does the trick for finding missing days, it would be ideal if it returned those missing weekdays as the missing dates (wrapped up in the html tags etc).
Comment: Yes, it is possible to get both.   Does your table include only a weeks worth of data?

Include in the query a calculated column that does a date calculation based up on the starting date (which you pass in).

There is also the option of UNION on a small table with dates and grouping by to remove any duplicates.
Comment: IF by a week's worth of data you mean doe the table only have data for one specific week, no. If you mean does it only every query for one week's worth of data, usually, but not always, so no again. I think I'll have to go with Joel's suggestion of having a table of dates instead. I would much rather have a lighter table of just 7 values, but it seems that to really get everything I want without the luxury of temp tables, I'll have to just have a 365 * 20 value table with just every day of the year.
Comment: A table of dates would work.

If you didn't want to maintain date data, you could even probably fudge it with a table of partial dates...etc.

or Temp tables...

Good luck


symmetric distribution around zero

Question: I have a probability distribution function as following, in my simulations, when I plot f(x) versus x, it is symmetric around zero, but I can't prove it mathematically, can anybody help?
\begin{equation}
f(x)= (1/2\pi)  \int _{-\infty}^{\infty}    \frac{e^{-\frac{(x-\theta)^2}{2(\theta^2+1)}}  e^{-\frac{\theta^2}{2}} }{\sqrt{\theta^2+1}}               d\theta
\end{equation}
actually assume that $x=h\theta+n$ where $h,\theta,n$ all have Gaussian distribution, i.e $h \sim N(1,1), ~~\theta \sim N(0,1), ~~n \sim N(0,1)$, so
\begin{equation}
f(x)=   \int _{-\infty}^{\infty} f(x|\theta) f(\theta)                  d\theta
\end{equation}
Answer: If you substitute $t=-θ$
$$\begin{equation}
f(x)= (1/2\pi)  \int _{-\infty}^{\infty}    \frac{e^{-\frac{(x-\theta)^2}{2(\theta^2+1)}}  e^{\frac{\theta^2}{2}} }{\sqrt{\theta^2+1}}               d\theta \\=
 (1/2\pi)  \int _{-\infty}^{\infty}    \frac{e^{-\frac{(x+t)^2}{2(t^2+1)}}  e^{\frac{t^2}{2}} }{\sqrt{t^2+1}}               dt= \\
 (1/2\pi)  \int _{-\infty}^{\infty}    \frac{e^{-\frac{(-x-t)^2}{2(t^2+1)}}  e^{\frac{t^2}{2}} }{\sqrt{t^2+1}}               dt=f(-x)
\end{equation}$$

symmetric distribution around zero


ssh agent forwarding fails with "Could not open a connection to your authentication agent"

Question: I receive a Could not open a connection to your authentication agent error message when I attempt to connect from an intermediate server to a third server using the agent forwarding option (-A) of an OpenSSH client. The first connection to the intermediate server goes smoothly using a key loaded into ssh-agent. The error message is displayed when attempting a connection to the final server.
My OpenSSH client is set to allow forwarding with ForwardAgent yes in ~/.ssh/config, and the intermediate server has AllowAgentForwarding yes in the daemon's configuration file. The client config is not overridden by a system level file.
I'm not using a terminal multiplexer in order to avoid an error stemming from environment variables not being set. To run the agent, I use exec ssh-agent zsh and verify that both SSH_AUTH_SOCK and SSH_AGENT_PID are present in the local environment. I use ssh-add to add the private keys for the intermediate and final server, respectively; I verify they are added with ssh-add -l.
All servers are of a recent version (OpenSSH 5.3) and the client is OpenSSH 6.2.
Answer: I'm posting this here because I spent a lot of time trying to find a solution using Google, reading man pages, and consulting a popular book on SSH, all to no avail.
The key to finding the problem was poring over the debugging output.
debug1: Remote: Agent forwarding disabled: mkdtemp() failed: Permission denied

The intermediate machine is a virtual server (RHEL 6.4) hosted by a cloud provider that uses an AWS stack. For reasons I can't explain, this is what permissions on the /tmp directory were set to:
drwxr-x--- 19  727  727  4096 Nov 28 05:30 tmp

Grep'ing through /etc/passwd I couldn't find a user with an ID of 727.
Correcting the permissions like so solved my woes:
sudo chown 0:0 /tmp
sudo chmod 1777 /tmp

Can anyone speak to the peculiar ownership of the /tmp directory?
Comment: no idea why you had these permissions. 1777 permissions and root as owner should be standard for /tmp on all Linux distributions. A wild theory for the strange owner could be that someone was trying to issue `chmod 727 tmp` for whatever reason and did a `chown 727 tmp` instead...
Comment: I contacted the provider and they stated that all new instances have root as owner of `/tmp`. I'm thinking that, when I updated over 270MB of packages after initial boot, one of the relevant RPMs made the change.
Comment: Good on ya for poring over the debugging output. This also resolved the issue I was having, same symptoms as yours.
Answer: For anyone looking for the entire process to forward keys and get the debug logs along with fix it is as follows:
Create ~/.ssh/config
Host [IP of HOST]
    ForwardAgent yes

Run ssh-agent
eval "$(ssh-agent)"

Add the key you want forwarded to the ssh agent:
ssh-add [path to key if there is one]/[key_name].pem

Log into the remote host:
ssh -A -v [user]@[hostname]

view the debug logs upon ssh
debug1: Remote: Agent forwarding disabled: mkdtemp() failed: Permission denied
Last login: Tue Nov 10 22:57:07 2020 from 10.100.28.239

while logged into the remote machine view tmp permission.
make sure the user has permission to access the tmp folder
ls -la /tmp/
sudo chown 0:0 /tmp
sudo chmod 1777 /tmp

my issue was I created a user to run the server under and that user did not have the permissions needed for the temp folder. I did not want to use root as that is not best practice. The fix was the same. :)


References for consulting statisticians to offer their clients

Question: This question illustrates the difficulty of a person mastering statistics and probability on their own, in the face of weakly developed resources like Wikipedia.
It occurred to me that consulting statisticians, and there are a few here, may routinely face the challenge of explaining certain concepts and methods to a client.  This is the flip side of the pedagogical coin.  When one has mastered the concept, it may make sense to conduct a particular avenue of analyses, but one's references may either be inappropriate or difficult to share with a client.  So, are there common resources that consulting statisticians like to suggest to their clients?  (See update #1 regarding more advanced or specialized topics.)
I can think of a few books that may be useful, but I suspect that a lot of clients will go about searching the web, as Developer did, and will come across rather inane material on Wikipedia.  In my answer to Developer, I suggested the NIST Handbook as one such reference that could be used.  What else?

Update 1: As Peter Flom has pointed out, for more advanced material or narrower pursuits, it may not be easy to offer a single point of reference.  This is correct and I should have worded the question differently for those cases.  In such cases, how do consultants find and share accessible references?  I believe that many consultants will take the time to write something new in order to explain things to their client, but those aren't references that are found and shared.
Some ideas:

Tutorials written by the consultant or others
Case studies or analyses from projects that demonstrate the same concepts
Excerpts of books (as I'd suggested in my answer to Developer), which describe the concept

What else might be a source or how else do you actually go about finding such references?  I realize this is an open ended question, but my answer to Developer shows some of the ways I'd approach this problem.  I don't mean to ask of all the ways that one could address this, but in one's own experience, how have you typically provided such explanatory resources?
Comment: It is answerable because accessible isn't the operative term.  :)  Instead, "how have you typically provided" is one operative phrase.  This is open ended, and I agree that CW is perfectly appropriate.  Thanks for making it so.
Comment: There is an inherent difficulty with this question, though: its interpretation appears to require a subjective understanding of "accessible," which will vary among consultants and their clients.  Can it really be answered, then?
Comment: Because this question is admittedly open-ended and solicits personal experience, it is a good candidate for CW.
Answer: In my experience, no clients have ever requested additional materials to understand a concept or method; I provide that.  About one client in 20 has requested additional materials for pursuing further study or for documentation: many of them have been lawyers or consultants (with scientific/engineering backgrounds).  In all these cases they have felt a need for a resource, suitable for self-study, that explains fundamental statistical ideas in a non-mathematical way and provides examples of their application.  I typically then have given them a copy of either of the following classic texts, depending on the depth of their interest and the time they might have available:

Darrell Huff, How to Lie With Statistics.
Freedman, Pisani, Purves, Statistics (any edition).

At one time I was giving away so many copies of How to Lie... (it was only $3.95 in the local university bookstore) that a competitor jokingly characterized this as "distributing [his] bible."
Comment: Great suggestions!  By the way, if you order more than 10-20 copies of a book, publishers will often give you a *nice* discount.  At around 100 copies of a book, you're doing them a favor and doing their marketing for them.  When the book is revised, that's a lot of owners who may want to replace their edition.  :)
Answer: These example lean more towards the biostatistics realm but for physical references there are many, many, many, many, many, many, many references geared towards our non-statistical collaborators.
And for online references, sometimes a statistics software package will have a really good statistics guide.  One example.
Comment: I checked all your links and downloaded the last one but to me all look elementary statistics as I categorized them as a.
Answer: I'm a consulting statistician, mostly to graduate students and researchers in the social, behavioral and medical sciences.
When I need to explain something to a client, they rarely want references for their own edification (although they often want them for papers).  Usually I will just explain what I am doing in my own words, using their example to help them understand things. This lets me respond at different levels to different clients.
Once you get past elementary statistics, there's no ONE source that's right - statistics is too broad a field.
But building on what @Mike Wierzbicki said, I also like the documentation in a lot of SAS' statistical PROCs.
Comment: My observations agree.  Beyond introductory material, it is hard to suggest a particular well-known reference.  I should update the question to address this.  Perhaps I should have asked how one might find & share accessible references for narrower or more advanced topics.
Comment: (+1) There are good points in this answer: `...explain what I am doing in my own words, using their example...`. To my experience in teaching programming languages it is one of good solutions. The third paragraph: `Once you get past elementary statistics, ...statistics is too broad a field.` is also productive and motivational. The language of the comment is also positive.
Answer: I highly recommend the book "Statistics as Principled Argument" by Robert Abelson. It's a small book, with almost no formulas, suitable for anyone who's had any introduction to statistics at all, and for many people who have had a lot of courses. I reviewed it on my blog here


How to handle `defer` in a function when using intermediary resources

Question: Given the following function
func jsonBodyReader(config Config, r *http.Request) (io.Reader, error) {
    bodyReader := io.LimitReader(r.Body, config.Reports.Max.Body)
    // defer r.Body.Close()

    gzipReader, err := gzip.NewReader(bodyReader)
    if err != nil {
        return nil, err
    }
    // defer gzipReader.Close()

    return io.LimitReader(gzipReader, config.Reports.Max.Json), nil
}

what would be the best way to handle the deferred close of r.Body and gzipReader?
Is it really necessary to always return all intermediary resources/streams/readers to be able to defer/close them in the parent function?
Another example
func save(target string, reader io.Reader) (io.Reader, *os.File, error) {
    file, err := os.Create(target)
    if err != nil {
        return reader, nil, err
    }
    /// defer file.Close()

    return io.TeeReader(reader, file), file, nil
}

In this case I have to return os.File just to be able to call file.Close() in the parent.
I found this related question: How to defer resource cleanup when that resource outlives the scope of the surrounding function? Unfortunately the suggested solutions are still awkward for my use case.
Answer: If the caller of a function has to read from a file or stream opened or modified by a function, you cannot defer-close it in that function. The stream  or file would be closed when the function returns, failing the caller who will try to read from it.
In your first example, you have two limited readers, one to limit the body, and the other to limit the json unzipped. You can do something like this:
func jsonBodyReader(config Config, r *http.Request) (io.ReadCloser, error) {
    bodyReader := io.LimitReader(r.Body, config.Reports.Max.Body)
    gzipReader, err := gzip.NewReader(bodyReader)
    if err != nil {
        return nil, err
    }
    return readerCloser{
       Reader:io.LimitReader(gzipReader, config.Reports.Max.Json),
       cl: r.Body,
    }, nil
}

where
type readerCloser struct {
   io.Reader
   cl io.Closer
}

func (r *readerCloser) Close() error { return r.cl.Close() }

The readerCloser type allows you to return a ReaderCloser that the caller can read from and close, which will close the source stream.


Examples of matrix groups with centralizer isomorphic to $\Bbb C$ or $\Bbb H$

Question: By Schur's Lemma, the centralizer $C(G)$ of an irreducible matrix groups $G\subseteq\mathrm{GL}(\Bbb R^d)$ is an $\Bbb R$-division algebra, and thus, isomorphic to either $\Bbb R$, $\Bbb C$ or $\Bbb H$ (the quaternions). I always had the feeling that $C(G)\cong \Bbb R$ is the generic case. This is because I only know the example $G\cong \mathrm U(1)$ (considered as a real matrix group of dimension two) with $C(G)\cong\Bbb C$. I do not know an example for $C(G)\cong\Bbb H$ at all.

Questions:

What examples are there with $C(G)\cong \Bbb H$?
What other examples are there with $C(G)\cong \Bbb C$?
Have the groups with a given centralizer been "classified" in some sense? That is, is there a result of the form "all $G$ with $C(G)\cong \Bbb C$ are of the following form: ..." or the like?

Note that I want $G$ to be irreducible! But I don't care whether $G$ is finite or a Lie group or not nice at all.
Comment: For $C*G)\cong {\mathbb C}$, take $G=U(n)$ regarded as a subgroup of $GL(2d, {\mathbb R})$. I am not sure about quaternions. Lastly, I am not sure what the last question even means. For instance, there are many irreducible representations of $U(n)$. One can say that they are all built using a combination of some standard constructions.
Comment: @MoisheKohan Do all of the representations of $\mathrm U(n)$ have $\Bbb C$ as centralizer? And do you know whether the groups with a given centralizer have been classified?
Comment: @MoisheKohan I replaced the confusing third question, I hope this was okay.
Comment: All **irreducible** representations of $U(n)$ have ${\mathbb C}^*$ as the centralizer. If you like even more interesting examples, you can use irreducible representations of other simple Lie groups or restrictions of these to Zariski dense  subgroups.
Comment: @MoisheKohan Great, thank you. How do I know which other Lie groups provide examples (other than subgroups of $\mathrm U(n)$)? And this is probably where my initial third question was aiming for: what is an intuition guiding me to decide whether a group has a certain centralizer? Is there something we know of $\mathrm U(n)$ that helps me to find further examples. Or isn't there anything like this and I have to inspect every group on a case by case basis?
Answer: Well, that is just a homework exercise I set in my representation theory class a few weeks ago. (It is based on a problem I was given myself in a class I took in Aachen last milennium.) It is giving an example for which the endomorphism ring is $\mathbb{H}$. Since I'm lazy you get the problem text:
Let $i=\sqrt{-1}$ and $G=\langle{
\left(\begin{array}{rr}
0&1\\%
-1&0\\%
\end{array}\right),
\left(\begin{array}{rr}
i&0\\
0&-i\\%
\end{array}\right)%
}\rangle$ be the quaternion group of order 8.
a) Construct an irreducible representation of $G$ over the
real numbers, acting on a $4$-dimensional vectorspace $V\cong \mathbb{R}^4$.
( Hint: Use an $\mathbb{R}$-basis of $\mathbb{C}$ to get an $\mathbb{R}$-basis of $\mathbb{C}^2$.
To show that no 2-dimensional
submodule exists, consider images of a nonzero vector $(a,b,c,d)$ in this subspace under different elements of $G$, and show that they will yield a basis of at least a 3-dimensional subspace.)
b) Determine the endomorphism ring $End_{\mathbb{R} G}(V)$.
(Hint: The elements of $End_{\mathbb{R} G}(V)$ are $4\times 4$ matrices that
commute with the generators of $G$. Use this to deduce conditions on their
entires. Then show that every matrix fulfilling these conditions commutes
with $G$.)
c) By Schur's lemma $End_{\mathbb{R} G}(V)$ must be a division ring. Can you
identify it?
Comment: Thank your for your answer! In retrospect, I remember that $\mathrm{SU}(2)$ was such a group. Now, i there an easy way to describe further groups with this centralizer?


Transparent PNG div not showing on iOS devices

Question: I currently have a HTML page with a PNG image overlaying it with instruction on. When the page is clicked/touched the PNG disappears which is how I want it. However its the PNG image causing me issues as it shows up fine in safari but not on iOS devices. If anyone can help me I would be greatly appreciative.
HTML:

CSS:
#overlay {
background: rgba(0, 0, 0, .4);
position:absolute;
z-index: 1;
}

Jquery:
$(document).ready(function() {
    var overlay = $('#overlay');
    overlay.on('click', function (e) {
        overlay
            .hide()
            .off();
    });
});

Comment: space in the filename is probably causing this error
Comment: ios has a maximum file size it is able to load for png images - if they are too large they just don't bother.  Is the width and height you have shown the actual width and height of the original image or are you resizing it?
Comment: Hi Alex, I tried taking the space out but still not showing. The div with the dropped opacity is showing but just not the PNG inside it. Pete, that is the actual size of the image so not very big at all. That shouldn't be too big should it?
Answer: I had a similar situation on a website, where the image file would be squeezed into the dimensions but at full resolution. So you end up with a 300x425px box with nothing but black or transparency because the image is not being scaled.
Here are some possible fixed. iOS do not like shorthand notations for css so use
background-color: rgba(0, 0, 0, 0.4);

If it is the same issue as I had you can add a zoom, which often fixes the issue.
#overlay img{
zoom = 1;
}

Also there is a limit of 3mp or 3000x1000 resolution limit on files rendering on iOS. So make sure your image isn't too big for the iOS.
Hopefully that helps you out.
Comment: Hi Pazbi, I will give that a go now. Where do I add the Zoom element? To the CSS or the img source in HTML ?
Comment: Sorry, you apply it to the img, I'll update my answer.
Comment: Just tried your answer but still not working. Anything else you may think it might be?
Comment: Do you have a jsfiddle or link?


node/sequelize/node with TS - how to cast to number and cast back to string inside a map with OR operator

Question: I am trying to do addition of the currency prices which i am getting as an array of objects. But each time i receive this data, currency type can differ between 3 and stays same in the whole array of objects.
My problem here is that when i try to do the addition idk about the key beforehand which key(currency_type) it is. I have tried an approach using map and OR operator.
Here is the controller:
  const getHistorycalPrices = async (req: IGetHistorycalPricesRequest, res: IGetHistorycalPricesResponse) => {

      try {
        if (!req.query.currency) {
          res.status(400).send({
            success: false,
            message: "Could not get historycal prices",
          });
          return;
        }

        // Gets currency column by query from crypto DB table
        const allPrices = await Crypto.findAll({ attributes: [req.query.currency, 'createdAt'], order: [['createdAt', 'DESC']] });

        if (!allPrices) {
          res.status(400).send({
            success: false,
            message: "Could not get historycal prices",
          });
          return;
        }

        // Get first row from crypto DB table
        const firstRowPrices = await Crypto.findByPk(1);

        if (!firstRowPrices) {
          res.status(400).send({
            success: false,
            message: "Could not get first row prices",
          });
          return;
        }

        res.status(200).send({
          success: true,
          message: "Successfully retrieved historycal prices",
          data: allPrices.map((price) => ({
            cryptoPrices: (+price.BTCUSD + +firstRowPrices.BTCUSD).toString() ||
                          (+price.ETHUSD + +firstRowPrices.ETHUSD).toString() ||
                          (+price.LTCUSD + +firstRowPrices.LTCUSD).toString(),
            createdAt: price.createdAt.toDateString(),
          })),
        });
        return;
      } catch (e) {

        res.status(500).send({
          success: false,
          message: "Server error",
        });
        return;
      }
    };

Right now when I'm sending the data if it's the first line I'll get -

But if it's the ETHUSD OR the LTCUSD I'll get -

There is a problem with my OR operator in the allPrices.map but I can't understand what it is.
Answer: You can use the Optional chaining operator(?.).
allPrices.map((price) => ({
        cryptoPrices: (+price?.BTCUSD + +firstRowPrices?.BTCUSD ||
                      +price?.ETHUSD + +firstRowPrices?.ETHUSD ||
                      +price?.LTCUSD + +firstRowPrices?.LTCUSD).toString(),
        createdAt: price.createdAt.toDateString(),
      })),
    });

Another way: Instead of OR operator, try using the ternary operator.
allPrices.map((price) => ({
     cryptoPrices:(("BTCUSD" in price)?(+price.BTCUSD + +firstRowPrices.BTCUSD):
                  ("ETHUSD" in price)?(+price.ETHUSD + +firstRowPrices.ETHUSD):
                  (+price.LTCUSD + +firstRowPrices.LTCUSD)).toString(),
     createdAt: price.createdAt.toDateString(),
     })),
});


Fabric v2.0 in kubernetes (minikube) - error Peer channel - error validating proposal: access denied: channel [] creator org [Org1MSP]


SQL- How to grab a large list of data instead of iterating each query

Question: I gather a list of items for each item I check the database with SQL query with the following code:
SELECT *
FROM task_activity as ja
join task as j on ja.task_id = j.id
WHERE j.name = '%s'
  AND ja.avg_runtime <> 0
  AND ja.avg_runtime is not NULL
  AND ja.id = (SELECT MAX(id) FROM task_activity
               WHERE task_id = ja.task_id
                 and avg_runtime <> 0
                 AND ja.avg_runtime is not NULL)
  % str(task.get('name'))).fetchall()

But do I need to iterate through the list and make a query for everyone. This list is quite large at times. Can I just make one query and get back a list data set?
In this particular query I'm only looking for the column avg_runtime with the task id and the maximum id will be the last calculated runtime.
I don't have access to the database other then to make queries. Using Microsoft SQL Server 2012 (SP1) - 11.0.3349.0 (X64)
Answer: You might be able to speed this up using row_number(). Note, I think there's a bug in your original query. Should ja.avg_runtime in the subquery just be avg_runtime?
sql = """with x as (
    select
        task_id,
        avg_runtime,
        id,
        row_number() over (partition by ja.task_id order by ja.id desc) rn
    from
        task_activity as ja
            join
        task as j
            on ja.task_id = j.id
    where
        j.name in ({0}) and
        ja.avg_runtime <> 0 and
        ja.avg_runtime is not null
) select
    task_id,
    avg_runtime,
    id
from
    x
where
    rn = 1;"""

# build up ?,?,? for parameter substitution
# assume tasknames is the list containing the task names.
params = ",".join(tasknames.map(lambda x: "?"))
# connection is your db connection
cursor = connection.cursor()
# interpolate the ?,?,? and bind parameters
cursor.execute(sql.format(params), tasknames)
cursor.fetchall()

the following index should make this query pretty fast (although it depends how many rows are being excluded by the filters on ja.avg_runtime):
create index ix_task_id_id on task_activity (task_id, id desc);

Comment: Will you see edit does that affect anything? Basically I input the name of the task with the formatter.
Comment: @user3590149 You need to build SQL with `j.name in ('%s', '%s2', ...)`. I'm not sure what language you're using to build this up. It looks somewhat prone to SQL injection as things stand.
Comment: @user3590149 I've not used Python much, but I've put something in to build up some parameters for substitution and then executing them. You'll have to fill in some gaps in my knowledge.
Comment: What database library are you using? I've assumed ODBC (pyodbc) in this example.
Comment: I can't test this until tomorrow. How does the 'create index work'? This another query?
Comment: SQLAlchemy is what I'm using if that changes anything.
Comment: if name was equal TESTNAME, can show me how to make the query just alone from the rest? Just as a with query. What does the ({0}) mean?
Comment: {0} is read by the format function. It substitutes a string in in it's place. e.g. `"Hello {0}".format("Loz")` would return `"Hello Loz"`. I'm using this because you need to bind one parameter for each name in the list. so it ends up with "name in (?,?,?,?) with one question mark for each parameter. Then cursor.execute can take a list of parameters and substitute the values for the question marks. This also takes care of SQL Injection problems. SQLAlchemy sits on top of a DBAPI implementation: http://docs.sqlalchemy.org/en/rel_0_9/dialects/mssql.html Do you know which you are using?
Comment: It comes up with mssql ODBC. I believe that's pyodbc. I'm getting a problem saying that I can't send only a maximum of 2100, do you have suggestion to deal with this.
Comment: Ultimately in your query the second value is the only value I need but if there is no entry or if the entry is blank then I need to disregard. Is this possible?
Comment: DO you have more than 2100 task names in your list? If so, you'll need to process in batches of less than that.
Comment: Yes I do. Going to have to do some research on how to do that? Any suggestions.
Comment: You need to cut your list into sublists of less than 2000, then call a procedure to do the database bit on each sublist. If the list of tasks is already stored on the database somewhere, you may be able to adapt the query to use it instead.


Script não mostra o caminho inteiro

Question: Código:
for i in `find $1 -name $4 -type f` ; do
path=`readlink -f $4`
words=`cat "$i" | wc -w`
echo "$path: $words palavras"
done

Imprime:
/home/miglui/Desktop/SO/teste.txt: 14 palavras
/home/miglui/Desktop/SO/teste.txt: 48 palavras
/home/miglui/Desktop/SO/teste.txt: 29 palavras

Devia Imprimir:
/home/miglui/Desktop/SO/teste/1/teste.txt: 14 palavras
/home/miglui/Desktop/SO/teste/2/teste.txt: 48 palavras
/home/miglui/Desktop/SO/teste/teste.txt: 29 palavras

O código não está a imprimir o caminho inteiro dos ficheiros. Onde poderá ser o erro?
Comment: pq vc nao faz ``path=`pwd $4```?
Comment: @lucas-virgili Porque tem de mostrar o nome do ficheiro no fim do caminho.
Answer: Quando você chama a seguinte linha do script:
path=$(readlink -f $4)

Você está usando o argumento $4. Apesar de você não ter colocado um exemplo de chamada para esse script, creio que o argumento $4 é o nome do arquivo (exemplo: teste.txt). Só o nome do arquivo não vai servir. Tem que ser o caminho do arquivo achado pelo find.
No caso, você tem que indicar a linha:
path=$(readlink -f $i)

Já que o $i é a variável da iteração que contém o caminho completo do arquivo, e é o que você usa corretamente para contar a quantidade de palavras com o wc.
Answer: Tenta
x=$"$(find -type f)"
for i in $x
    do echo -n "$i: "
    wc -w $i|cut -d " " -f1 -z
    echo -n " palavras"
    echo
done

Script não mostra o caminho inteiro


Adding character to timestamp

Question: I am currently stuck on an issue with renaming files.
import java.io.File;
import java.io.IOException;

public class FileRename {
    public static void main(String[] argv) throws IOException {

        File folder = new File("x:\\chadhold\\test\\");

        File[] listOfFiles = folder.listFiles();
        if(listOfFiles != null){

            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    File f = new File("x:\\chadhold\\test\\"+listOfFiles[i].getName());
                    String currentName = f.getName();
                    currentName = currentName.replace(".D**************", ".D******.T********");
                    f.renameTo(new File("x:\\chadhold\\test\\" + currentName));
                   // f.renameTo(new File("x:\\chadhold\\test\\" +currentName.substring(0, currentName.lastIndexOf("."))));
                }
            }
        }
        System.out.println("conversion is done");
    }
}

So what i am trying to do here is find files that start with .D
These files are end with a timestamp which is why i am using ***** because each file will be named differently.
I need to put a .T and remove the last 2 characters from the file names.
Hopefully i explained this good enough!
Thanks in advance.
Comment: Please include sample input/output names.
Comment: You can use foo.startsWith(".D") to find appropriate strings, and then use .substring to get portions of a String to concatenate back together.
Comment: AFK0281.EETM.D1TWP015-02.20170208200225253=>
AFK0281.EETM.D1TWP015-02.D170208.T200225253
Comment: It looks like what you really want to do is replace the last section of the filename (delimited by a .) with a D{date}.T{time}, right?
Comment: Yes correct @DomenicD.
Comment: Minor comment- strings are immutable, so a replace return would be a new object
Answer: Rather than using the replace method on the string, you'd be better off making a method that parses the filename and returns a new one.
public static void main(String[] args) {
    System.out.println(newFileName("AFK0281.EETM.D1TWP015-02.20170208200225253"));
}

private static String newFileName(String currentName) {
    String[] parts = currentName.split("\\.");
    String last = parts[parts.length - 1];
    parts[parts.length - 1] = "D" + last.substring(2, 8) + ".T" + last.substring(9);

    StringBuilder sb = new StringBuilder();
    for (String s : parts) {
        sb.append(s).append(".");
    }
    String newName = sb.toString();
    return newName.substring(0, newName.length() - 1);
}

Output is

AFK0281.EETM.D1TWP015-02.D170208.T200225253
Comment: I'm sorry, i'm not much of a java developer. Could you make the adjustments to my code provided?
Comment: just replace where you were doing the replace with `currentName = newFileName(currentName)`
Comment: StringUtils cannot be resolved.
I appreciate you helping me btw.
Comment: You would have needed to add it as a dependency. I updated the code to not have that dependency. It's not pretty though.
Comment: Not exactly. I guess you are a newb. ;) https://hastebin.com/keyeqobipe.vbs
Comment: Yes big noob haha, Now im getting this error http://i.imgur.com/9SUnYku.png
Comment: sure. Would appreciate it if you'd accept the answer.

Adding character to timestamp


Como fazer para ao checar uma checkbox ela mude a cor de fundo de uma td de uma tabela e ao deschecar ela retorne para sua cor normal

Question: Bom, eu tenho este código, e ele funciona em partes, quando eu checo a checkbox ele muda a cor da minha td, porém ao deschecar a cor não retorna ao normal, alguém poderia me ajudar? Desde já agradeço.

 $('.checkbox-regularC').click(function(){
     $('.linhaCdSRotinaTurma').css('background-color','#fff');
     $('.linhaCdSRotinaTurma').css('cursor','auto');
 })

.linhaCdSRotinaTurma {

    background-color: #cccc;
    cursor: not-allowed;
    border: 0px;

}

             <input type="checkbox" class="checkbox-regularC">

                 Titulo

             Alternativas

Comment: Vai ser só uma ou são várias na mesma tela?
Comment: Vai ter apenas uma tr uma linha, né porém com várias colunas
Comment: Newton, como você é usuário novo, dá uma lida neste link https://pt.stackoverflow.com/tour para saber o que fazer ao fazer perguntas e receber respostas. Abs!
Answer: Você pode verificar se o checkbox está checado para assim fazer a ação que deseja:
$('.checkbox-regularC').click(function(){
    if ($('.checkbox-regularC').is(':checked')) {
        $('.linhaCdSRotinaTurma').css('background-color','#fff');
        $('.linhaCdSRotinaTurma').css('cursor','auto');
    } else {
        //voltar a cor ao normal
    }
});

Comment: Moça, funcionou não
Comment: Perdão, erro de sintaxe ali na hora de fechar o click, fiz a correção ali.
Comment: Qualquer coisa tu dá um console.log($('.checkbox-regularC').is(':checked'));
Answer: Uma forma de fazer isso usando um objeto com os estilos.
Você verifica se está checado com $(this).is(":checked"), que retorna true (se estiver checado) ou false (caso não esteja checado).
O objeto opts possui uma função com os estilos entre chaves {} que retorna os valores dependendo do valor no parâmetro i da função, alternando as propriedades usando ternários (saiba mais sobre operador ternário).
Uma das vantagens do ternário é evitar repetição de código quando se quer pegar um valor ou outro baseando-se numa condicional. Exemplo:
// se i for true, a cor será #fff, caso contrário será #ccc
i ? '#fff' : '#ccc'

Definindo estilos entre chaves {} usando .css:
O seu código pode ser simplificado. Você está usando .css para o mesmo elemento duas vezes:
$('.linhaCdSRotinaTurma').css('background-color','#fff');
$('.linhaCdSRotinaTurma').css('cursor','auto');

Usando as chaves {}, você pode definir múltiplas propriedades num bloco só, sem que seja necessário repetir o mesmo elemento:
$('.linhaCdSRotinaTurma').css({
   'background-color':'#fff',
   'cursor':'auto'
});

A diferença é que neste formato você deve separar os valores com dois-pontos : em vez de vírgula.
Outra coisa há se notar é que você pode escrever os nomes das propriedades fora das aspas, mas caso haja um hífen -, você deve removê-lo e escrever a primeira letra após em maiúsculo:
'background-color' -> backgroundColor

Exemplo:
$('.linhaCdSRotinaTurma').css({
   backgroundColor:'#fff',
   cursor:'auto'
});

Veja o código em funcionamento:

$('.checkbox-regularC').click(function(){
   var opts = function(i){
      return {
         'background-color': i ? '#fff' : '#ccc',
         'cursor': i ? 'auto' : 'not-allowed'
      };
   }

   $('.linhaCdSRotinaTurma')
   .css(opts($(this).is(":checked")));
});
.linhaCdSRotinaTurma {

    background-color: #cccc;
    cursor: not-allowed;
    border: 0px;

}

         <input type="checkbox" class='checkbox-regularC'>

            Titulo

         Alternativas

Answer: Você pode criar uma classe CSS específica para quando o checkbox estiver marcado, também, e aplicar nas tags HTML de acordo com o estado do checkbox.

$(function () {
  $('.checkbox-regularC').on('change', function() {
    var classes =
      $(this).is(':checked') ?
        ['linhaCdSRotinaTurma','linhaCdSRotinaTurmaMarcada'] :
        ['linhaCdSRotinaTurmaMarcada','linhaCdSRotinaTurma'];

      $('.' + classes[0]).addClass(classes[1]).removeClass(classes[0]);
  });
});

.linhaCdSRotinaTurmaMarcada {
    background-color: #fff;
    cursor: auto;
}

.linhaCdSRotinaTurma {
    background-color: #cccc;
    cursor: not-allowed;
    border: 0px;
}

            <input type="checkbox" class="checkbox-regularC">

                Titulo

            Alternativas


Summation and integral representations of special functions

Question: I have a slightly strange (and possibly quite vague) question that I'm keen to hear people's thoughts on. In my recent work, I have been coming across various infinite series and integrals that cannot be evaluated analytically (at least Mathematica doesn't evaluate them). For example, see Summation of a quotient with a square root.
Ideally, I'm thinking that there should be special function representations for these, but maybe they just haven't been invented yet? Is it reasonable to seek out possible routes for getting special functions defined by such representations such that their properties can be found (by suitable experts i.e. probably not me!) and how would I go about doing this? Is this how some special functions have been defined/invented historically? If Mathematica (or an equivalent) could then have these as built in functions, it would make my notebooks run far quicker. Am I being crazy thinking this?
Answer: My answer below is far to be a definitive answer. Better, it can be consideredas as a  too long comment.
You are absolutely right to say that  << Ideally, I'm thinking that there should be special function representations for these, but maybe they just haven't been invented yet? >>. Nevertheless "inventend" is questionable to mean "studied, described, published, referenced, standardized,... ".
I would like to cite : << A special function has to acquire a background of property, descriptions, formulas and derivations as extended as possible. Before becoming a referenced special function, its name has to be spread in the literature in order to become familiar. More importantly, the function should be useful in a branch of mathematics or physics >> ( From page 3 in https://fr.scribd.com/doc/34977341/Sophomore-s-Dream-Function ).
A discussion about the use of special functions  : pp.18-36 in https://fr.scribd.com/doc/14623310/Safari-on-the-country-of-the-Special-Functions-Safari-au-pays-des-fonctions-speciales . (Paper for general public).
A list of special functions : https://en.wikipedia.org/wiki/List_of_mathematical_functions#Other_standard_special_functions
Your question : << Is it reasonable to seek out possible routes for getting special functions defined by such representations such that their properties can be found... ? >>.
This is a big question which is far to be fully solved. In fact this question cannot be raised without to specify the list of special functions to be considered in the search.
From precursor a long time ago by Joseph Liouville and others : https://en.wikipedia.org/wiki/Liouville%27s_theorem_(differential_algebra)
A relevant answer is : https://en.wikipedia.org/wiki/Risch_algorithm
The method used in WolframAlpha and other softwares of this kind are variants of the Risch_algorithm.


How to know if jQuery UI is being included

Question: Is there a good way of checking for if jQuery UI is being included on the current page request?
Found drupal_get_library(), and drupal_add_library(), but neither of them allows me to check if it is being included.
I am trying to do this from the theme, and then load a jquery.ui.touch-punch library to enable iPad/iPhone support.
Answer: There's no built in way but as drupal_add_library() uses Drupal's static pattern you can find out by doing this:
function ui_is_included() {
  // Get the list of libraries included in this page load
  $libs = drupal_static('drupal_add_library');

  // The system library will pretty much always exist as it includes jQuery,
  // but it's just good sense to check just in case.
  if (isset($libs['system'])) {
    // If the system library array includes UI then make sure it's enbabled
    return isset($libs['system']['ui']) && $libs['system']['ui'] === TRUE;
  }

  // UI is not loaded if we've got to this point
  return FALSE;
}

You can even compress that down a bit:
function ui_is_included() {
  $libs = drupal_static('drupal_add_library');
  return isset($libs['system']['ui']) && $libs['system']['ui'];
}

I'd advise calling this function as late on in the page build process as possible, to ensure that all modules have had a chance to request that UI is added. hook_preprocess_html() in your theme's template.php file might be a good place to put it.


Remove Column from a GridView (VB.NET 2008)

Question: {VB.NET 2008 using Northwind Microsoft Database}
How can i remove a column with name like id only from the demogrid ? (Without using sql code)
<code>    Dim strSQL As String = _
     "SELECT * FROM Products WHERE CategoryID=1"

    Try
        Using adapter As New OleDbDataAdapter(strSQL, _
          My.Settings.OleDbConnectionString)

            Dim ds As New DataSet
            adapter.Fill(ds, "ProductInfo")

            demoList.DisplayMember = "ProductName"
            demoList.ValueMember = "ProductID"

            demoGrid.DataSource = ds.Tables("ProductInfo")

        End Using

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
</code>
Answer: You can remove the column you don't like
<code>GridViewName.Columns.Remove("ColumnName")
</code>


Interpreting odds ratio of an ordinal regression when independent variables are negative percentages

Question: I'm trying to express the results of an ordinal regression with a certain "perspective", and I'm confused.
My dependent variable is an ordinal representing the progression in a scale of negative outcome (e.g. 0 = ok, 1 = bad outcome, 2 = very bad outcome).
My independent variables are negative percentages that represent the percentual change in a measure between two time points (i.e. +X% if there was an increase, -Y% if the measure decreased).
I have the following ORs:
<code>Percentual change in var A: 0.895 (95% CI: 0.801; 0.988)
Percentual change in var B: 0.870 (95% CI: 0.559; 1.337)
Other variable:             1.007 (95% CI: 0.995; 1.019)
Age:                        0.970 (95% CI: 0.895; 1.045)
</code>
I am interpreting these ORs as follows:
Percentual change in var B, Other variable, and age have their CIs touching 1; this means that I cannot refute the hypothesis that they have no effect on $Bad_Outcome.
Percentual change in var A has a significant effect on $Bad_outcome (statistically speaking). The 0.895 OR means that an increase in var a (e.g. a change from, say, -7% to -6%) is associated with an odds 0.895 times the odds of passing from an ok outcome (0) to a bad outcome (1), or from a bad outcome (1) to a very bad outcome (2) (I am not sure if this is correct).
Given that my previous interpretation is correct, how can I "translate" this results taking as reference the decrease in the percentual change in var A?
In plain English: I'd like to express the results as the odds of having a worse outcome (from ok to bad, and from bad to very bad) when var A decreases (say, from -6% to -7%), but I'm confused by this "reversal of perspective", and I'm not sure how to "convert" the OR. I was thinking of 1/OR, but I'm really uncertain.
Answer: You make a lot of assumptions without verification.  It is seldom the case that % change is the correct summary measure for two time points.  It assumes that effects are through a ratio but % change is an asymmetric measure (as opposed to log ratio).  You didn't check the Tukey mean-difference (Bland-Altman) plot to see if the log ratio is the proper summary of the two as opposed to the difference or other measure.  You didn't check that the coefficients of the two measures (or their logs) have a ratio of -1.0 if the two were used as separate variables in the regression model.
Once you get the proper model formulated you can plot the two variables (or their log ratio or difference or some nonlinear function of them using regression splines) against the outcome to get a better interpretation than odds ratios as two arbitrary settings.
Comment: Googling?  You need to get some good books and spend a great deal of time studying them.  Your desire to take the ratio of two logs points out that you need to start with algebra.  Regarding references about change measures see http://biostat.mc.vanderbilt.edu/ManuscriptChecklist
Comment: It would be great if you could find a local biostatistician to collaborate with.  Getting back to your question, the link I provided above provides a lot of information.  The basic problem with % change related to asymmetry is shown in an example.  Suppose that one subject began with X=1 and changed to X=2.  That is a 100% increase.  To get back to where she started (X=1) requires a 50% decrease.  Thus in the data a 100% increase is balanced by a 50% decrease, but the average over two subjects (one with X=1 going to X=2 and the other X=2 going to X=1) is the wrong answer of 25%.
Comment: Thank you for your observations, they are extremely interesting. I have a bit of googling ahead of me before I can fully appreciate your suggestions :) Now I have a few questions... Can you expand a bit about the asymmetricity of % change? Also, by using log ratio are you suggesting that I should transform my data in log and then compute the ratio? (eg. log(measure_at_time2)/log(measure_at_time1)
Comment: I'm a medical student, and at the moment I have only basic textbooks (Martin Bland's An introduction to medical statistics, which was a required textbook when I took my biostatistics lessons a few years ago, and Motulsky's Intuitive biostatistics, which I purchased on my own initiative seeing a lot of positive reviews on amazon). I recognize that they are inadequate for anything beyond the basics, so I was planning to purchase intermediate-to-advanced statistical textbooks - if you have any suggestions, I'm listening. I am aware of my deficiencies in basic math; I'm working on it.


Predicate Logic question (attempted, assistance required)

Question: I'm trying to work out a class exercise and I've got myself stuck. Any help would be appreciated. Thank you.
I am to use use predicate logic reasoning techniques to solve the following problem:
All academics who are computer scientists are programmers or mathematicians. Any logistician is a philosopher. Jack Jones is not a philosopher and he is not a programmer. Prove that if Jack Jones is a logistician, he is not a computer scientist.
Here's what I have done so far.
All academics who are computer scientists are programmers or mathematicians.
All (∀) academics who are computer scientists (B) are programmers or mathematicians (C).
 ∀x[B(x) -> C(x)]
Any logistician is a philosopher.
Any (∀) logistician (F) is a philosopher (G).
(∃x)[F(x) -> G(x)]
Jack Jones (x) is not a philosopher (H) and he is not a programmer (J).
¬H(x) /\ ¬J(x)
Prove that: if Jack Jones is a logistician, he is not a computer scientist.

If Jack Jones is not a programmer then he cannot be a computer scientist.
Jack Jones is not a philosopher, however, not all philosophers are logisticians (or not all logisticians are philosophers).
Meaning Jack Jones can be a logistician without being a philosopher and a computer scientist.
Comment: How exactly are you to prove this?  You give an informal proof ... is that what you are supposed to do?
Answer: Some of the information is irrelevant, but it can be proven as follows:

Cx = x is a computer scientist
Px = x is a programmer
Lx = x is a logistician
Fx = x is a philosopher
j = Jack Jones

\begin{array}{l}
& \{1\} & 1. & \forall x[Lx \Rightarrow Fx] & \text{ Prem. }\\
& \{2\} & 2. & \neg Fj \land \neg Pj & \text{ Prem. }\\
& \{3\} & 3. & Lj & \text{ Assum. }\\
& \{1\} & 4. & Lj \Rightarrow Fj & \text{ 1 UE }\\
& \{1,3\} & 5. & Fj & \text{ 3,4 MP }\\
& \{6\} & 6. & Cj & \text{ Assum. }\\
& \{1,3,6\} & 7. & Fj \land Cj & \text{ 5,6 $\land$I }\\
& \{1,3,6\} & 8. & Fj & \text{ 7 $\land$E }\\
& \{1,3\} & 9. & Cj \Rightarrow Fj & \text{ 6,8 CP }\\
& \{2\} & 10. & \neg Fj & \text{ 2 $\land$E }\\
& \{1,2,3\} & 11. & \neg Cj & \text{ 9,10 MT }\\
& \{1,2\} & 12. & Lj \Rightarrow \neg Cj & \text{ 3,11 CP }\\
\end{array}
Explanation:

Premise: For every x, if x is a logistician, x is a philosopher.
Premise: Jack Jones is neither a philosopher nor a programmer.
Let's assume that Jack is a logistician.
From our premise on line 1, if Jack is a logistician, he is a philosopher.
It follows from our assumption that he is a philosopher.
Let's assume that Jack is also a computer scientist.
Given these assumptions, Jack would be both philosopher and a computer scientists. (This step may seem redundant, but it's use by logicians to establish a connection between the propositions.)
Jack is a philosopher. (Because of line 7, this assertion is now shown to depend on line 1, 3 and 6, whereas before it depended only on line 6. Again, it's used to establish a logical connection.)
If Jack is a logistician, he is a philosopher. (Because line 7 is shown to depend on line 3, line 7 is considered to be a logical consequence of 3, establishing the implication. The assumption on 3 is discharged.)
According to the premise on 2, Jack is not a philosopher;
Therefore Jack cannot be a logistician. (This is the application of Modus Tollens, together with the implication on line 9. If Jack were a logistician, line 9 says that he would also be a philosopher, contradicting the premise.)
Based on the assumption on line 3, the conclusion is established: If Jack is a logistician, he is not a computer scientist. (The assumption on 3 is also discharged.)
Comment: Thank you for your answer. Is there any chance you could explain it step by step please?
Comment: @Mcclaine. I edited my answer to explain the steps.


How to understand Views SQL statement?

Question: I try to figure out the meaning of View's sql statement.
This following is Views auto-generate sql statement:
SELECT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_hierarchy ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
INNER JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE (( (taxonomy_vocabulary.machine_name IN  ('book_category')) ))

What's the meaning of {...}?, It seems a table name, I try to copy above sql to mysql, But mysql alert me:
SQL Syntax error.
So I try to remove {...}, Like this :
SELECT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM
 taxonomy_term_data
LEFT JOIN  taxonomy_term_hierarchy ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
INNER JOIN taxonomy_term_data ON taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN  taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid

But Mysql alert me:
Not unique table/alias: 'taxonomy_term_data'
What's the problem of Views's SQL?
Answer: Only remove the curly brackets, not what's inside the them. The brackets contain the actual table name, and directly after is the table alias which is used later.
This should work (only brackets removed):
SELECT taxonomy_term_data.name AS taxonomy_term_data_name,
       taxonomy_term_data.vid AS taxonomy_term_data_vid,
       taxonomy_term_data.tid AS tid,
       taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM   taxonomy_term_data taxonomy_term_data
       LEFT JOIN taxonomy_term_hierarchy taxonomy_term_hierarchy
              ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
       INNER JOIN taxonomy_term_data taxonomy_term_data_taxonomy_term_hierarchy
               ON taxonomy_term_hierarchy.parent =
                  taxonomy_term_data_taxonomy_term_hierarchy.tid
       LEFT JOIN taxonomy_vocabulary taxonomy_vocabulary
              ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE  ((( taxonomy_vocabulary.machine_name IN ( 'book_category' ) )))

Note that if your tables has a prefix, i.e. drupal_ then you need to add that to the table name, because that's the reason the brackets are used, in case of table prefix.
Cheers,

How to understand Views SQL statement?