How do I join using a string with a comma separated value?

Question: I want to join 2 tables, one table having an email field and the other having a comma separated email list.
This is the scenario:
Tables
Team
--------------
- team_id
- email_list (this is a comma separated email address)

Persons
--------------
 - person_id
 - email

I tried something like this:

SELECT team.* FROM team INNER JOIN persons ON trim(persons.email) IN (CONCAT('\'',REPLACE(REPLACE(team.email_list,' ',''),',','\',\''),'\''))

but the string inside the IN clause seems to be like this "'email1','email2','email3'"
Any ideas to make it work?
Answer: MySQL has a built-in function that can help with comma-separated lists:
SELECT  . . .
FROM team t INNER JOIN persons p
  ON FIND_IN_SET(p.email, t.email_list);

But you won't be happy with the performance, since it can't be optimized to use an index.
See also my answer to Is storing a comma separated list in a database column really that bad?
Comment: Thanks for this! I figured that this is going to be bad for performance... but I have to do it temporarily..
Answer: I have used this for MSSQL, personally I don't like it, but for that one report or data tasks it does the trick.
declare @team table (team_id int,email_list varchar(8000));
declare @persons table (person_id int,email varchar(64));

insert into @team
SELECT 1,'email@example.com,email@example.com' union all
SELECT 2,'email@example.com,firstname.lastname@example.com' union all
SELECT 3,'firstname.lastname@example.com,firstname.lastname@example.com' union all
SELECT 4,'email@example.com,email@example.com,email@example.com' UNION ALL
SELECT 3,'firstname.lastname@example.com,email@example.com'
;

insert into @persons
select 1,'email@example.com' union all
select 2,'firstname.lastname@example.com' union all
select 3,'email@example.com';

select
  Team.team_id,
  Team.email_list,
  Person.person_id,
  Person.email 'matched_on'
from
  @team Team
  INNER JOIN @persons Person on ','+Team.email_list+',' LIKE '%,'+Person.email+',%';

Updated as per David findings
Comment: This will erroneously match `email@example.com` in a list containing `firstname.lastname@example.com`. To fix it use `on ',' + Team.email_list + ',' like '%,' + Person.email + ',%'`.


How can I show that the order of this element divides the gcd?

Question: I have the following problem:

Let $C_m$, $C_n$ be two finite cyclic groups of cardinality $m$ and $n$ respectively. Let $d=\gcd(m,n)$ and consider the morphism of groups $$f:C_m\rightarrow C_n$$Show that for every $x\in C_m$, $ord(f(x))$ is a divisor of $d$

My Idea was the following:
Let us first fix two generators for $C_m,~C_n$ i.e.$$C_m=\langle g \rangle,~~~C_n=\langle h\rangle$$ Now $$f(x)^m=f(g^i)^m\stackrel{\text{f is a morphism}}{=}f(g^m)^i=f(1)^i=1~~~~~~~~~(1)$$ where $1\leq i\leq m-1$. Similarly since $f(x)\in C_n$ we know that $f(x)=h^j$ for some $1\leq j\leq n-1$. Therefore $$f(x)^n=(h^j)^n=1^j=1~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(2)$$ But now from $(1)$ it follows that $ord(f(x))|m$ and similarly from $(2)$ that $ord(f(x))|n$ thus we are done.
Does this work so?
Answer: You can conclude from $(1)$ that the order of $f(x)$ divides $m.$
By LaGrange's Theorem and the fact that $f(x)\in C_n,$ you can conclude that the order of $f(x)$ also divides $n.$ (Do you see why?) At that point, you're basically done. Your work in $(2)$ almost does this, though I'd add $$...=\left(h^j\right)^n=h^{jn}=h^{nj}=\left(h^n\right)^j=1^j=....$$ The last equality above is where you use LaGrange's Theorem.
Comment: ah so my way is correct, but I only need to specify why $$f(x)^n=1$$ as you did. Did I understood this correctly?
Comment: Yes, that's correct.
Comment: perfect thanks!


$A$ has more columns than rows and has full row rank, show there exist infinitely many $B$ s.t. $AB=I$

Question: If A $\in M_{m\times n}(R)$ such that $n>m$.
Prove that if $\text{rank} (A) = m$ then there are infinitely many matrices $B \in \ M_{n\times m} (R)$ such that $ AB = I_m$
So the question is defining a matrix $A$, in a set of matrices where the number of columns is always greater than the number of rows, and if $A$ has full row rank, then there are infinitely many matrices $B$ such that $AB$ creates the identity matrix.
I'm not sure where to go with this question, could anyone please help?
ETA
Thank you to everyone for their answers, the question makes sense now.
Answer: Full row rank implies existence of at least one right inverse, because the linear system $Ax=b$ has a solution for every $b$; if $b_i$ is a solution of $Ax=e_i$ (where $e_i$ is the $i$-th column of the $m\times m$ identity) and $B=[b_1\ b_2\ \dots\ b_m]$, then $AB=I$ by construction.
Next we show that we can modify $B$ without changing the result. Let $v\ne0$ be any vector such that $Av=0$. Such a vector surely exists because of the rank-nullity theorem (alternatively, because the consistent system $Ax=0$ has free variables). Consider the matrix
$$
C=[\,\underbrace{v\ v\ \dots\ v}_{m}\,]
$$
so that
$$
A(B+C)=AB+AC=AB+0=I_m
$$
Since there are infinitely many choices of a vector $v$, you're done.
Comment: Nicely done. I love this proof.
Comment: This can obviously be generalized: take as $C$ any matrix whose columns belong to the null space of $A$. In this way we get *all* right inverses for $A$, once a right inverse $B$ is fixed, as $B+C$.
Answer: The matrix $A$ is a surjective linear transformation $\mathbb{R}^n \to \mathbb{R}^m$ and its kernel, say $K$, has dimension $k = n - m > 0$.
Take a standard basis vector $e_i \in \mathbb{R}^m$. Since $A$ is surjective and not injective (kernel has positive dimension) you have infinitely many preimages w.r.t $A$. Hence take some $b_i \in \mathbb{R}^n$ such that $A b_i = e_i$.
Now define $B \colon \mathbb{R}^m \to \mathbb{R}^n$ by simply declaring that the standard basis vector $e_i \in \mathbb{R}^m$ is mapped to $b_i$, i.e. $B(e_i) = b_i$. This amounts to say that the $i$-th column of $B$ is precisely $b_i$.
By construction $A B (e_i) = A b_i = e_i$ for any $i = 1, \dots, m$. Hence $A B = I_m$.
Answer: The objective of this answer is to give a quite general form for matrices $B$.
The full rank condition implies that there exist a $m \times m$ invertible submatrix of $A$.
Let us assume at first that the left-most block $C$ of $A$ is such a submatrix.
Then, with the following notations:
$A=\begin{pmatrix}
C & D
\end{pmatrix}
\ \ \ (1)$
$B=\begin{pmatrix}
C^{-1}(I_m-DE)\\
E
\end{pmatrix}
\ \ \ (2)
$
we have $AB=I_m$ for any $E$.
Remark:
The set of such matrices $B$ is an affine space $R=v+V$, where $V$ is a vector space with dimension at most $m \times (n-m)$.
If the leftmost block is not invertible, consider the columns $A_{k_1}, A_{k_2}, \cdots A_{k_m}$ of $A$, which assembled, give an invertible matrix. We consider the $n \times n$ permutation matrix that sends $k_1, k_2, \cdots k_m$ to $1,2,\cdots, m$, and leaves unchanged the other indices of $1,2...n$. It is rather easy to see that if the lines of $B$ (as described by (2)) are "scrambled" by the same permutation, the result is preserved.
(one can give a more rigorous treatment for this last part).
Comment: I am almost sure that the form I give for matrices $B$ is the most general, but I have not time enough this week end to check it.


Como ordenar campo do tipo VARCHAR em CodeIgniter

Question: Como ordenar campos do tipo VARCHAR na classe model do CodeIgniter?
Já conseguir no SQL puro dessa forma:
order by strtodate(dtdespesa, '%d-%m-%Y') desc;

Contudo a versão do CodeIgniter que estou utilizando, a 3.1.6, não reconhece essa função: strtodate.
$this->db->order_by (strtodate('dtandamento', '%d/%m/%Y'));

Versão do CI: 3.1.6
Versão do PHP 5.3.7
Comment: Coloca o código do codeigniter formando a query com a função
Comment: $this->db->order_by (strtodate('dtandamento', '%d/%m/%Y'));
Comment: a função está funcionando certinha, o que está pegando é o order_by
Comment: já tentou: `$this->db->order_by("strtodate('dtandamento', '%d/%m/%Y')", 'ASC', FALSE);`?
Comment: @VirgilioNovic, acabei de tentar. Deu a mesma mensagem:

Message: Call to undefined function strtodate()
Comment: coloque todo o código!
Comment: Funcionou!!! Só acrescentei o nome da outra tabela e ordenou do jeito que eu queria. Muito obrigado @VirgilioNovic

$this->db->order_by ("str_to_date(andamento.dtandamento, '%d-%m-%Y')", 'DESC', FALSE);
Comment: Ramiro coloquei como resposta!
Answer: No último parâmetro do método order_by coloque FALSE, para que o texto digitado seja incluído sem alteração no que foi escrito, ou seja, os dados não serão escapado, exemplo:
$this->db->order_by("strtodate('dtandamento', '%d/%m/%Y')", 'ASC', FALSE);

no seu caso em especifico:
$this->db->order_by ("str_to_date(andamento.dtandamento, '%d-%m-%Y')", 'DESC', FALSE);


Insert rest at the start of a measure in MuseScore

Question: I have this:

but I want the rest at the beginning of the measure. How do I do that?
Answer: Unfortunately, there's currently no option in MuseScore to move notes horizontally, nor is there anything akin to an "insert" mode.
As such, the best solution here will be a simple cut-and-paste work around. Select all of the pitches you want to keep, copy them, and paste them (in this case) starting on the second eighth note of the measure. Then, replace the opening of the measure with an eighth rest.
See also https://musescore.org/en/node/11944, a discussion which reaches the same conclusion.

If this feature is really necessary for you, there are two things you might consider:

Since MuseScore is open source, you could technically program the feature you're looking for. Especially if you're fluent in C++ and/or Qt (the languages used to write MuseScore), this may be an option for you. (Note that the discussion above mentions that this might be a waste of time, and I don't completely disagree.)
Another option would be to switch to a notation program that does have this feature. One possibility would be LilyPond, a free and open-source program that uses text-based input. Thus if you have a string of three eighth notes followed by a rest (c8 e g r) but you want to put the rest first, all you have to do is move it: r8 c e g.
Comment: Its so strange...
Comment: @AndersLindén It does seem like an option to be included, I agree. See my edit for some further discussion.
Answer: I just tried this and was able to simply drag the rest to the beginning of the measure.  Using v1.3r5702
Comment: This no longer seems possible in MuseScore 2. Ian, does moving the rest actually push the remaining pitches later in the measure, or is it just a visual fix where the rest, still at the end of the measure, is just visually moved to the beginning? That is to say, does moving the rest this way affect playback?
Comment: Yikes, Musescore is already on version 2.3.2 (I have that version). It seems that your version is pretty outdated.
Comment: I admit that it is quite old, and that is a very good question which I should have thought of checking, myself!  So I cranked it back up and added a whole note in the following measure.  It appears that the movement of the rest is merely cosmetic as you can still hear it between the quarter note and the whole note.  So probably the ability to move that rest is a bug in my version which was later corrected.  Thanks for the additional conversation on this.
Comment: @IanMoote No, thank *you*! That's great to know. And welcome to [music.se]!


Why Caratheodory Extension Theorem called Extension Theorem?

Question: Caratheodory Extension Theorem tells us that we can "extend" our measure on algebra to measure on $\sigma$-algebra. So what we extend in this case is the set on which we can use this measure (measure is the same). Conclusion: the Theorem is called "extension" because we extend algebra to $\sigma$-algebra (generated by this algebra). Am I right?
I usually see the words "extension" and "restriction". When we try to construct a Lebesgue Measure from outer measure we "restrict" outer measure to the $\sigma$-algebra.
So simultaneously we "restrict" outer measure to $\sigma$-algebra and "extend" algebra to $\sigma$-algebra?
Answer: Yes, although you should not say that the "measure is the same" (in fact in general the extension is not unique, but it is defined elsewhere anyway).
Also yes for your second question, although again a minor glitch: "the" $\sigma$-algebra is not unique.


Alteração da versão do MySQL

Question: Tenho essa tabela em MySQL chamada logou:
id | idconta | dia
Essa consulta no Mysql sempre fucnionou no meu servidor:
SELECT dia FROM logou GROUP BY YEAR(dia), MONTH(dia) ORDER BY dia DESC

Mas agora que o sistema foi para o servidor do cliente, e tudo indica que é uma outra versão de MySQL ou um SQL Server (pode ser? Cliente é da Bélgica, e são MUITO chatos em falar detalhes do servidor deles), essa consulta apresenta esse erro:

Expression #1 of SELECT list is not in GROUP BY clause and contains
  nonaggregated column 'eusoucomp-br-qa.logou.dia' which is not
  functionally dependent on columns in GROUP BY clause; this is
  incompatible with sql_mode=only_full_group_by

O que pode ser? E como corrigir?
Comment: você tem acesso ao banco ?
Comment: @MarconcilioSouza não... Esse é o rpoblema, apenas envio os arquivos para eles, e 10 dias depois eles colocam no ar.
Answer: A partir do MySQL 5.7 o comportamento padrão do MySQL foi modificado e o modo ONLY_FULL_GROUP_BY inserido por padrão. Se você fizer:
mysql> SET sql_mode = '';

E será possível executar a consulta sem erros (mas você precisará fazê-lo a cada sessão).
A melhor solução é fazer algo assim utilizando a função ANY_VALUE():
SELECT ANY_VALUE(dia) as dia FROM logou group by year(dia), month(dia) ORDER BY dia DESC;

Fiz os testes aqui usando a versão 5.7.21-0ubuntu0.17.10.1 e, curiosamente, na versão 10.1.30-0ubuntu0.17.10.1 do MariaDB este problema nem mesmo ocorre.
Comment: Oi, onde eu colocaria essa linha? mysql> SET sql_mode = '';
No arquivo de conexão ao banco de dados?
Comment: Se você alterar a consulta e usar o ANY_VALUE() não precisará mexer no sql_mode (pela sua dúvida, você não tem acesso ao servidor). Para alterar esta configuração procure nos arquivos de configuração do MySQL em "/etc/mysql/mysql.conf.d/mysqld.cnf" ou "/etc/mysql/my.cnf", haverá uma parte do arquivo identificada como _[mysqld]_ e lá deverá estar a linha sql_mode, remova apenas o ONLY_FULL_GROUP_BY de lá e reinicie o serviço.

Alteração da versão do MySQL


Printing records alternative way

Question: Is there a way to directly display the content of a query in Mysql using C?
What I mean is:
through mysql shell if I type : SELECT * FROM table_name; I get the query result in a neat and formatted way.
If I want to do the same thing using Api C I have to write several lines of codes and the final result is far from being nice (at least this is my personal experience )
For example :
void display_Table1(MYSQL *conn)
{
int jj,ii;

    char query[512];
    sprintf(query, "SELECT * FROM Table1 ;");

    if (mysql_query (conn, query)) {
                printf("\nErrore query:\n");
        printf("%s", mysql_error(conn),"\n");

    result = mysql_store_result(conn);
    if (result) {
         num_rows = mysql_num_rows(result);
         num_fields =mysql_num_fields(result);
         //printf("Number of rows=%u  Number of fields=%d \n", num_rows,num_fields);
         //printf(" ");
        }
            else
            {
               printf("Result set is empty");
            }

        // Print column headers

            fields = mysql_fetch_fields(result);

            for(jj=0; jj < num_fields; jj++)
            {
                printf("\n%s\t\t",fields[jj].name);
            }
            printf("\n\t ");

        // print query results

            while(row = mysql_fetch_row(result)) // row pointer in the result set
            {
                for(ii=0; ii < num_fields; ii++)
                {
                    printf("%s\t", row[ii] ? row[ii] : "NULL");  // Not NULL then print
                }
                printf("\n");
            }
    if(result)
            {
                mysql_free_result(result);
                result = NULL;
            }

}
}

That's a knotty problem to solve. I get headers one after the other in a vertical way.
I also get

Commands out of sync; you can't run this command now
Answer: Firstly, there is no direct way to print out a formatted display. What you can do, is use
MYSQL_FIELD *field = mysql_fetch_field (resultset);
col_len = field->max_length;
if(col_len < strlen(field->name))
    col_len = strlen(field->name);

to find out the maximum width of a column, and the space the data accordingly.

Printing records alternative way


Como transformar um Objeto em XML no formato especificado?

Question: Gostaria de gerar o XML para uma requisição que vou realizar no Java a partir de um objeto. O XML que eu quero gerar é o seguinte:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<v:Envelope xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
  <v:Header>
    LGE Nexus 5
    <j></j>
    -2574.2675703366904
    <c>ANDROID</c>
    <d>6.0.1</d>
    <e>4.1.5</e>
    <f>127.0.0.1</f>
    <g>79f7bfca9d83085965c523eefc267339d61abb8f</g>
    <k>1702a351-0c04-47c1-a785-486118238872</k>
    <h>-4703.798004479785</h>
    <l>2017-08-08 15:42:39</l>
    <m>8797e74f0d6eb7b1ff3dc114d4aa12d3</m>
  </v:Header>
  <v:Body>
    <n0:getStatus xmlns:n0="http://soap.ws.placa.service.sinesp.serpro.gov.br/">
      ABC123
    </n0:getStatus>
  </v:Body>
</v:Envelope>

A classe que estou utilizando está assim atualmente:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import org.w3c.dom.Document;

/**
 *
 * @author Lucas Souza [email@example.com]
 */
@XmlRootElement
public class Request {

  private String plate;

  private String device;
  private double latitude;
  private String operationalSystem;
  private String majorVersion;
  private String minorVersion;
  private String ip;
  private String token;
  private String uuid;
  private double longitude;
  private String date;
  private String hash;

  public Request() {
    this.device = "LGE Nexus 5";
    this.operationalSystem = "ANDROID";
    this.majorVersion = "6.0.1";
    this.minorVersion = "4.1.5";
    this.ip = "127.0.0.1";
    this.hash = "8797e74f0d6eb7b1ff3dc114d4aa12d3";
  }

  @XmlElement(name = "a")
  public String getPlate() {
    return plate;
  }

  public void setPlate(String plate) {
    this.plate = plate;
  }

  @XmlTransient
  public String getDevice() {
    return device;
  }

  public void setDevice(String device) {
    this.device = device;
  }

  @XmlTransient
  public double getLatitude() {
    return latitude;
  }

  public void setLatitude(double latitude) {
    this.latitude = latitude;
  }

  @XmlTransient
  public String getOperationalSystem() {
    return operationalSystem;
  }

  public void setOperationalSystem(String operationalSystem) {
    this.operationalSystem = operationalSystem;
  }

  @XmlTransient
  public String getMajorVersion() {
    return majorVersion;
  }

  public void setMajorVersion(String majorVersion) {
    this.majorVersion = majorVersion;
  }

  @XmlTransient
  public String getMinorVersion() {
    return minorVersion;
  }

  public void setMinorVersion(String minorVersion) {
    this.minorVersion = minorVersion;
  }

  @XmlTransient
  public String getIp() {
    return ip;
  }

  public void setIp(String ip) {
    this.ip = ip;
  }

  @XmlTransient
  public String getToken() {
    return token;
  }

  public void setToken(String token) {
    this.token = token;
  }

  @XmlTransient
  public String getUuid() {
    return uuid;
  }

  public void setUuid(String uuid) {
    this.uuid = uuid;
  }

  @XmlTransient
  public double getLongitude() {
    return longitude;
  }

  public void setLongitude(double longitude) {
    this.longitude = longitude;
  }

  @XmlTransient
  public String getDate() {
    return date;
  }

  public void setDate(String date) {
    this.date = date;
  }

  @XmlTransient
  public String getHash() {
    return hash;
  }

  public void setHash(String hash) {
    this.hash = hash;
  }

  public String toXML() throws JAXBException, ParserConfigurationException, SOAPException, IOException {
    Document document;
    Marshaller marshaller;
    SOAPMessage soapMessage;
    ByteArrayOutputStream outputStream;
    String output;

    document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    marshaller = JAXBContext.newInstance(Request.class).createMarshaller();
    marshaller.marshal(this, document);
    soapMessage = MessageFactory.newInstance().createMessage();
    soapMessage.getSOAPBody().addDocument(document);
    this.fillHeaders(soapMessage.getSOAPHeader());
    outputStream = new ByteArrayOutputStream();
    soapMessage.writeTo(outputStream);
    output = new String(outputStream.toByteArray());

    return output;
  }

  private void fillHeaders(SOAPHeader soapHeader) throws SOAPException {
    soapHeader.setAttribute("b", this.device);
    soapHeader.setAttribute("i", String.valueOf(this.latitude));
    soapHeader.setAttribute("c", this.operationalSystem);
    soapHeader.setAttribute("d", this.majorVersion);
    soapHeader.setAttribute("e", this.minorVersion);
    soapHeader.setAttribute("f", this.ip);
    soapHeader.setAttribute("g", this.token);
    soapHeader.setAttribute("k", this.uuid);
    soapHeader.setAttribute("h", String.valueOf(this.longitude));
    soapHeader.setAttribute("l", this.date);
    soapHeader.setAttribute("m", this.hash);
  }
}

Porém o XML que estou tendo em retorno utilizando o método Result#toXML é o seguinte:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header b="LGE Nexus 5" c="ANDROID" d="6.0.1" e="4.1.5" f="127.0.0.1" g="79f7bfca9d83085965c523eefc267339d61abb8f" h="605.0793837821" i="142.74057974918404" k="84f4a062-3cca-42f0-9dd6-262efe5a5d4f" l="2017-08-08 15:50:38" m="8797e74f0d6eb7b1ff3dc114d4aa12d3" />
    <SOAP-ENV:Body>
        <request>
            ABC123
        </request>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Como posso configurar meu objeto e realizar o toXML da maneira correta, mais indicada e que reproduza o XML como especificado?
Basicamente o que eu vejo na diferença entre os formatos é:

Envelope criado;
Prefixo v nas tags;
Elementos no Header;
Nome do método no Body;
Atributo xmlns na chamada;
Comment: Não existe nenhum método `addElement` ou parecido em `SOAPHeader`?
Comment: @LINQ até tem, mas ele recebe um `Name` ou `QName` e não tem onde colocar o valor. Fico meio perdido
Answer: Eu utilizo o JAXBContext para geração dos XMLs. Segue abaixo exemplo de conversão para XML;
public static String toXml(Object object) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(object.getClass());
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // formata o xml
    m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // Retirar tag inicial
    StringWriter sw = new StringWriter();
    m.marshal(object, sw);
    String xmlString = sw.toString();

    return xmlString;
}

Para os atributos ficarem com o nome correto na geração eu utilizo as seguintes anotações:
@XmlRootElement(name = "soapenv:Envelope")
@XmlAccessorType(XmlAccessType.FIELD)
public class SoapenvEnvelope implements Serializable {

    private static final long serialVersionUID = 1L;

    @XmlAttribute(name = "xmlns:soapenv")
    private String xmlnsSoapenv;

    @XmlAttribute(name = "xmlns:geop")
    private String xmlnsGeop;

    @XmlElement(name = "soapenv:Header")
    private String soapenvHeader = "";

Sendo @XmlAttribute os atributos que irão dentro da tag e @XmlElement identifica os atributos da entidade.
Comment: Mas dessa forma eu tenho que montar os elementos na mão, não vejo como isso irá resolver meu problema, já que eu quero montar de acordo com o objeto sem precisar ficar me preocupando muito com `tags`. Se for pra montar na mão prefiro fazer um `replace` de `string`
Comment: @Sorack você vai ter preencher os valores do objeto (apenas isso). O método que eu citei como exemplo irá fazer a conversão de forma automática. Esse processo é **MUITO** mais simples do que utilizar o replace do java.
Comment: Você consegue adaptar pra retornar como esperado?
Comment: Sim! Basta você utilizar as anotações corretas e o xml vai gerar da forma que você espera
Comment: Você vai ter um pojo Envelope com a seguinte anotação @XmlRootElement(name = "v:Envelope"). Este pojo vai ter 2 atibutos: **1** - header com a anotação @XmlElement(name = "v:Header") e **2** -  body com a seguinte anotação: @XmlElement(name = "v:Body")
Answer: Utilizei o método SOAPHeader.addHeaderElement para criar os elementos que seriam necessários no cabeçalho. Após isso fiz o tratamento como String, afinal o namespace é obrigatório em determinados elementos. O código final da classe foi o seguinte:
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

/**
 *
 * @author Lucas Souza [email@example.com]
 */
@XmlRootElement(name = "getStatus", namespace = "http://soap.ws.placa.service.sinesp.serpro.gov.br/")
public class Request {

  private final String prefix = "v";

  private String plate;

  private String device;
  private Double latitude;
  private String operationalSystem;
  private String majorVersion;
  private String minorVersion;
  private String ip;
  private String token;
  private String uuid;
  private Double longitude;
  private String date;
  private String hash;

  public Request() {
    this.device = "LGE Nexus 5";
    this.operationalSystem = "ANDROID";
    this.majorVersion = "6.0.1";
    this.minorVersion = "4.1.5";
    this.ip = "127.0.0.1";
    this.hash = "8797e74f0d6eb7b1ff3dc114d4aa12d3";
  }

  @XmlElement(name = "a")
  public String getPlate() {
    return plate;
  }

  public void setPlate(String plate) {
    this.plate = plate;
  }

  @XmlTransient
  public String getDevice() {
    return device;
  }

  public void setDevice(String device) {
    this.device = device;
  }

  @XmlTransient
  public Double getLatitude() {
    return latitude;
  }

  public void setLatitude(Double latitude) {
    this.latitude = latitude;
  }

  @XmlTransient
  public String getOperationalSystem() {
    return operationalSystem;
  }

  public void setOperationalSystem(String operationalSystem) {
    this.operationalSystem = operationalSystem;
  }

  @XmlTransient
  public String getMajorVersion() {
    return majorVersion;
  }

  public void setMajorVersion(String majorVersion) {
    this.majorVersion = majorVersion;
  }

  @XmlTransient
  public String getMinorVersion() {
    return minorVersion;
  }

  public void setMinorVersion(String minorVersion) {
    this.minorVersion = minorVersion;
  }

  @XmlTransient
  public String getIp() {
    return ip;
  }

  public void setIp(String ip) {
    this.ip = ip;
  }

  @XmlTransient
  public String getToken() {
    return token;
  }

  public void setToken(String token) {
    this.token = token;
  }

  @XmlTransient
  public String getUuid() {
    return uuid;
  }

  public void setUuid(String uuid) {
    this.uuid = uuid;
  }

  @XmlTransient
  public Double getLongitude() {
    return longitude;
  }

  public void setLongitude(Double longitude) {
    this.longitude = longitude;
  }

  @XmlTransient
  public String getDate() {
    return date;
  }

  public void setDate(String date) {
    this.date = date;
  }

  @XmlTransient
  public String getHash() {
    return hash;
  }

  public void setHash(String hash) {
    this.hash = hash;
  }

  public String toXML() {
    Transformer transformer;
    Document document;
    Marshaller marshaller;
    SOAPMessage soapMessage;
    ByteArrayOutputStream outputStream;
    StreamResult result;
    String output;

    try {
      document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      marshaller = JAXBContext.newInstance(Request.class).createMarshaller();
      marshaller.marshal(this, document);
      soapMessage = MessageFactory.newInstance().createMessage();
      transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      this.fillEnvelope(soapMessage.getSOAPPart().getEnvelope());
      this.fillBody(soapMessage.getSOAPBody(), document);
      this.fillHeader(soapMessage.getSOAPHeader());
      outputStream = new ByteArrayOutputStream();
      result = new StreamResult(outputStream);
      transformer.transform(soapMessage.getSOAPPart().getContent(), result);
      output = outputStream.toString();
      output = fillXMLString(output);
    } catch (JAXBException | ParserConfigurationException | SOAPException | TransformerException ex) {
      throw new RuntimeException(ex);
    }

    return output;
  }

  private void fillEnvelope(SOAPEnvelope envelope) {
    Iterator prefixes;
    envelope.setPrefix(this.prefix);

    prefixes = envelope.getNamespacePrefixes();

    while (prefixes.hasNext()) {
      String currentPrefix = (String) prefixes.next();

      envelope.removeNamespaceDeclaration(currentPrefix);
    }
  }

  private void fillHeader(SOAPHeader soapHeader) throws SOAPException {
    soapHeader.setPrefix(this.prefix);

    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "b")).setValue(this.device);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "c")).setValue(this.operationalSystem);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "d")).setValue(this.majorVersion);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "e")).setValue(this.minorVersion);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "f")).setValue(this.ip);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "g")).setValue(this.token);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "h")).setValue(String.valueOf(this.longitude));
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "i")).setValue(String.valueOf(this.latitude));
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "j")).setValue("");
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "k")).setValue(this.uuid);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "l")).setValue(this.date);
    soapHeader.addHeaderElement(new QName(soapHeader.getNamespaceURI(), "m")).setValue(this.hash);
  }

  private String fillXMLString(String xml) {
    xml = xml.replace(" xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\"", "");

    return xml;
  }

  private void fillBody(SOAPBody soapBody, Document document) throws SOAPException {
    soapBody.addDocument(document);
    soapBody.setPrefix(this.prefix);
  }
}

E o resultado foi:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<v:Envelope xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
  <v:Header>
    LGE Nexus 5
    <j/>
    -2574.2675703366904
    <c>ANDROID</c>
    <d>6.0.1</d>
    <e>4.1.5</e>
    <f>127.0.0.1</f>
    <g>79f7bfca9d83085965c523eefc267339d61abb8f</g>
    <k>1702a351-0c04-47c1-a785-486118238872</k>
    <h>-4703.798004479785</h>
    <l>2017-08-08 15:42:39</l>
    <m>8797e74f0d6eb7b1ff3dc114d4aa12d3</m>
  </v:Header>
  <v:Body>
    <ns2:getStatus xmlns:ns2="http://soap.ws.placa.service.sinesp.serpro.gov.br/">
      ABC123
    </ns2:getStatus>
  </v:Body>
</v:Envelope>


Polar coordinates in dynamical systems

Question: Using Polar coordinates, show that the system
\begin{align}
\dot x &= x -y -x(x^2 + y^2)   \\
\dot y &= x +y -y(4x^2 + y^2)
\end{align}
gives $\dot r = r - r^3 (1+\frac34 \sin^2(2\theta))$.
You are given that this system has a single fixed point located at $(x, y) = (0, 0)$.
I understand that
\begin{align}
r\dot r &= x\dot x + y\dot y   \\
&= x^2 -xy -x^2(x^2+y^2) +xy +y^2 -y^2(4x^2+y^2)  \\
&= x^2 + y^2 -x^2(x^2 +y^2) -y^2(4x^2+y^2)  \\
&= x^2 + y^2 -x^4 -y^4 -5x^2y^2.
\end{align}
However, I cannot understand the final step to the answer.
It follows after this to find radii $r_1 < r_2$ such that $\dot r > 0$ for $r < r_1$ and $\dot r < 0$ for $r > r_2$. How does one go about this?
Answer: Hint.
Adding
$$
x\dot{x} = x^2 - x y -x^2(x^{2} + y^{2})\\
y\dot{y} = y x + y^2 -y^2(4x^{2} + y^{2})
$$
we obtain
$$
\frac 12\frac{d}{dt}(x^2+y^2) = x^2+y^2-x^2(x^{2} + y^{2})-y^2(4x^{2} + y^{2})
$$
substituting now
$$
x = r \cos\theta\\
y = r \sin\theta
$$
we obtain
$$
\dot r = r-(1+\frac 34\sin^2(2\theta))r^3
$$
so we have an isolated unstable equilibrium point at $r=0$ and an stable limit cycle as can be depicted in the attached figure

Polar coordinates in dynamical systems


Ok to cut continuous variable into irregular intervals?

Question: I have a predictor variable (water height in metres) and a response variable (feeding rates of birds). The relationship between them looks similar that shown in the plot below.
tidal_effect <- iris[,3:4]
library(plyr); tidal_effect <- rename(tidal_effect, c("Petal.Length" = "feeding.rate", "Petal.Width" =  "water.height"))

tidal_effect_extra <- data.frame(water.height = sample(seq(2.5, 3, 0.1), 50, replace = T), feeding.rate = sample(seq(4, 4.5, 0.1), 50, replace = T))

tidal_effect_extra <- rbind(tidal_effect, tidal_effect_extra)

library(ggplot2)
ggplot(tidal_effect_extra, aes(water.height, feeding.rate)) + geom_point() + xlab("water.height (m)")

I'm considering cutting water height into a three level factor. As can be seen in plot above, the obvious point at which to cut water height is about 0.7, 2.5 and 3, which means that the distance between the minimum/maximum values at each level of the factor are not equal
I can cut the predictor variable like this:
tidal_effect_extra$water.height.cut <- cut(tidal_effect_extra$water.height, breaks = c(0, 0.7, 2.5, 3), labels = c("low", "mid", "high"))

And then perform this model:
lm(feeding.rate ~  water.height.cut, tidal_effect_extra)

My question: is there anything wrong with cutting water height into groups in which distances between the minimum/maximum values at each level of the factor are not equal?
Comment: Okay in what sense? Your question is too vague. Statistics is not some priesthood where we can either declare your actions as anathema or as sanctioned - and even less so without context - it depends on what you're trying to achieve and what characteristics of the resulting analysis are important. Such data-dependent actions can certainly have *consequences*, but if those consequences don't matter to you, you may well regard the result as 'okay'. On the other hand, such a choice may impact your results in ways that matter to you deeply. How could we tell? You don't give anything to go on.
Comment: The scatterplot does not suggest there is any merit to making water height a polychotomous variable.  Instead, it looks like the data may have been collected in a small number of groups and that each group has contributed its own smaller circular cloud of points--perhaps only five or six groups were involved. If that is the case, you need to approach this question differently by accounting for this grouping in your model (so that the correlations it induces will properly be accommodated).
Comment: Why not model water height as a continuous variable, rather than cut it, and use non-linear analysis? That could be useful if the underlying science supports the idea that feeding rate is maximum at some intermediate water height.
Comment: or rather, (1) this is obviously a data driven and has the limitations of other data driven approaches (increase variance and decreased bias) (2) unclear if you're really getting any benefit from the split (how is this better than using all the data) (3) but  is how we learn about data. If same cut-points seem in multiple samples you've possibly learned something about the relationship of the data
Comment: sure, why not....?
Comment: question amended to provide more context
Answer: Partially answered in comments:
Why not model water height as a continuous variable, rather than cut it, and use non-linear analysis? That could be useful if the underlying science supports the idea that feeding rate is maximum at some intermediate water height. – EdM
The scatterplot does not suggest there is any merit to making water height a polychotomous variable. Instead, it looks like the data may have been collected in a small number of groups and that each group has contributed its own smaller circular cloud of points--perhaps only five or six groups were involved. If that is the case, you need to approach this question differently by accounting for this grouping in your model (so that the correlations it induces will properly be accommodated). – whuber


Write Trace Logs to text file in ASP.NET Core

Question: I have an application written in .NetFramework 4.5 and the trace logs are added in the simplest possible way:
    System.Diagnostics.Trace.WriteLine("Method in: ");
    //
    //
    //
    System.Diagnostics.Trace.WriteLine("Method out: ");

We use to write the trace logs into a text file using the <configuration /> tag in web.config.
    <configuration>
      <system.diagnostics>
        <trace autoflush="true" indentsize="4">
          <listeners>
            <add name="app-logger" type="System.Diagnostics.TextWriterTraceListener"
                 initializeData="logfile.txt" />
            <remove name="Default" />
          </listeners>
        </trace>
      </system.diagnostics>
    </configuration>

I'm trying to implement the same functionality in .NetCore 3.1 but where should I place the <configuration /> tag?
Comment: You can [redirect all traces to your `ILogger`](https://stackoverflow.com/q/54537694/2698119), and then configure that logger to output to a file.
Comment: @Métoule - Thanks for the suggestion. It will work to achieve the scenario.
Answer: You can use Serilog for logging into Text file.
https://nblumhardt.com/2016/10/aspnet-core-file-logger/


Matlab RandomForest prediction error calculation

Question: I am using Random Forests in Matlab for regression. After educating my model on train data, I want to get MSE on test data not used in training. I do that two ways:

call predict and directly calculate MSE using predicted and actual values
call error and use built in TreeBagger functionality to do the same task.

In first case I get 10 times bigger result. Why? The only explanation I have, is that built in function somehow discounts outliers in prediction, but I am not sure how exactly it is done.
Can somebody, please, explain all this to me.
Answer: If you use predict on a train set, the result will be highly overfitted and meaningless -- this actually applies to all ML algorithms, and this is why test sets, cross-validations and similar stuff is used.
However, one of the big advantages of bagging is that it can produce an approximation of error on train set as it would be a test -- this is called out-of-bag (OOB) and those predictions (available in OOBPred) are used by Matlab in error to produce "true" error.
Comment: I am using predict on test set. It's written in my question. From Matlab help: "err = error(B,X,Y)  computes mean squared error (MSE) for regression trees for each tree, for predictors X given true response Y." What you are talking about is (again Matlab reference quote):"err = oobError(B) computes mean squared error (for regression trees) for out-of-bag observations in the training data".
Comment: Okay, it's really shamefull but I must admit that difference between Matlab built in function and my direct calculations appeared due to two factors: 1) typo in my MSE formula, 2) setting mode 'individual' in error command and getting array of errors per tree in forest, instead of total error. I will accept mbq's answer because actually his comment lead me to check TreeBagger's options one more time and find my mistakes.


Detect the finish of `UIPopoverController` programmatic dismissal animation

Question: UIPopoverControllerDelegate protocol have popoverControllerDidDismissPopover: method which invoked after popover has finished it's dismissal animation. However, if popover is dismissed programmatically, above-mentioned delegate method is not called.
Is there any way to detect the finish of programmatically triggered dismissal animation? In a nutshell, how to implement something like -[UIPopoverController dismissPopoverAnimated:completion:]?
P.S. Running completion block with 0.5 seconds timer is ugly
Answer:
However, if popover is dismissed programmatically, above-mentioned delegate method is not called.

A popover in iOS 8 is a presented view controller. Thus, if a popover is dismissed programmatically nowadays, it is done by calling dismissViewControllerAnimated:completion: which has a completion block where you'll be called back. You should not be using UIPopoverController at all.


Moment Estimate of theta

Question: Consider a random variable $X$ whose pdf is $f(x;θ)=θx^{θ−1}$ for $0<x<1$ and zero otherwise.
i) Show this is a density function
ii) determine the moment estimate of theta on the basis of a random sample $x_1,\ldots,x_n$
for part ii) does this mean use the method of moments to find the estimator?
Comment: Note that (implicitly) the parameter $\theta$ is positive. Of course we do not have a density function if $\theta\le 0$.
Comment: "show the pdf is non negative for 0<x<1...how?" Are you serious? To show that this function is nonnegative (everywhere, not only on (0,1)) is a problem, really?
Answer: I think Andre Nicholas adequately answered your question regarding f>0. I will address the moment estimate:
The idea of a moment estimate is to relate a moment to the desired parameter, then estimate it using the sample moment estimates. Lets try the expected value of X:
$E[X] = \int\limits_{0}^1 x(\theta x^{\theta-1}) dx = \int\limits_{0}^1 \theta x^{\theta} dx = [\frac{\theta x^{\theta+1}}{\theta+1}]_{x=0}^{x=1} = \frac{\theta}{1+\theta}$
Therefore, you can estimate $\theta$ with $\frac{\hat\theta}{1+\hat\theta}= \bar x\rightarrow \hat\theta = \frac{-\bar x}{\bar x-1}$. That is the moment estimate. Contrast this with the maximum likelihood estimate of a sample:
Likelihood ($L$) of sample of values, $x=\{x_1...x_N\}$ is $L(x;\theta)=\theta^N\prod\limits_{i=1}^Nx_i^{\theta-1}$. Taking the logarithm, we get the log-likelihood function, which is easier to optimize:
$\mathcal{L}(x;\theta) = N\ln(\theta) + (\theta-1)\sum\limits_{i=1}^N \ln(x_i)$
Take the derivative wrt $\theta$ and set equal to $0$. Solving for $\theta$ we get:
$\hat\theta_{mle} = \frac{-N}{\sum\limits_{i=1}^N \ln(x_i)}$ which will in general give different estimates from the method of moments.
Sometime the MLE is a better (i.e., more efficient) estimator. I tested this by simulating from your density for $\theta = 3$, and seeing the sampling distribution of each estimator for a sample size of 20. See below:

As you can see, the distributions are almost identical, so neither is really preferred here.
Answer: For the second part, the method of moments simply indicates that we equate each population raw moment with the corresponding sample raw moment; that is to say, let $${\rm E}[X^k] = \frac{1}{n} \sum_{i=1}^n X_i^k,$$ for as many positive integers $k$ that will uniquely determine all the parameters of the distribution.  In this case, there is only a single parameter, so using the $k = 1$ case, we want to find the value $\theta$ such that ${\rm E}[X] = \bar x$, the sample mean.  This requires us to determine the expected value of $X$, which is straightforward:  $${\rm E}[X] = \int_{x=0}^1 x f(x;\theta) \, dx.$$  I leave the remainder to you as an exercise.

Moment Estimate of theta


Clicking on Links in a Table using Protractor

Question: I have a dynamic table, whose first column consists of links. Is there any way to always click on the first element in that column?
P.S - Any solution to click on the element, without the addition of ID's to the column elements would be highly appreciated.
Edit: The Javascript code to create the first column
$('#list').DataTable({
  "bLengthChange": false,
  "iDisplayLength": 50,
  order: [[ 0, "asc" ]],
  data : listData,
  columns: [
    {
      data : 'entityName',
      render: function(data, type, full, meta){
        return ''
          + ''
        + data
        + ''
        + '';
      }
    },
    {
      data : 'serviceExecutive',
      render: function(data, type, full, meta){
        return data;
      }
    }
  ]
});

I want to click on the first element in this column
Comment: Can you please post some sample code
Answer: Try this
link =element(by.id('tableID')).all(by.tagName('td')).get(1).all(by.tagName('a'));
    link.click();

Comment: Your Welcome @Sid
Answer: Try to locate your link by XPath:
element(by.xpath("//table//a")).click()

same with CSS selector:
$("table a").click()

This should click on the first link in a table. If it doesn't work as expected, provide with appropriate HTML code sample to get more suitable solution


How can I ensure automatically that a module is disabled on my live site?

Question: I'm using a development -> staging -> live server workflow, and all three sites run off the same Git repository. The repository contains a few modules (a custom module for Selenium testing, etc.) that I never want to run on the live site.
Is there a way (in settings.php, perhaps?) to block a module from ever being enabled? I suppose I could also remove it from the repository, but my workflow is easier if I keep everything together.
Answer: You can hide modules from the admin UI by using the hidden property in the module's .info file:
hidden = TRUE

This method might be useful if you want to make sure the module is never enabled via the UI.
In case you're interested in how to do the opposite (stop a module from being disabled), it's also done in the .info file by setting the required parameter:
required = TRUE

Once you've done that Drupal will see the module as a 'core' module and stop it from being disabled through the admin UI.
Comment: The intent was to ask for the opposite, the question is now updated to properly reflect this.
Comment: @Letharion So it was, I've re-arranged the answer it should make more sense now
Comment: hidden = TRUE ftw
Comment: Thanks!  Knowing how to hide modules to prevent them from being enabled in the Core UI is very useful.  However, in my case I am more worried about accidentally enabling the modules myself.
Answer: In the standard Drupal deployment methodology, only code is move from dev -> stage -> prod, and only the database moves from prod -> stage -> dev.  Since modules' enabled state is stored in the database, if you follow this workflow, you do not need to worry about your dev modules becoming enabled in production.
Your problem then becomes the inverse: how to insure that your dev modules are automatically enabled for you when you move your database to dev.  If you use Drush sql-sync to move your database, then the example file sync_enable.drush.inc shows how to enable dev modules as a post-sql sync task. You can also automatically disable production-only modules such as securepages if you wish.
Comment: Yes, you're right.  I was confused because my site is still in development and I am currently pushing changes from the dev database to production, since production has no data yet.  This will obviously change once I launch the site.
Comment: Marking this the answer because it clarifies why I won't have the problem I thought I would have.
Comment: I should also add that if you wish, you may, during your development phase use the same technique to enable and/or disable modules when you push your database to your not-yet-live production system.  I usually just keep the dev modules on in this scenario, until I'm almost ready to publish, at which point I turn them off on prod and adopt the prod -> dev workflow.
Answer: There is a module that does almost exactly what you ask: Environment Modules. The only difference is that is does not disable modules based on the environment (dev/staging/production), but it enables them. That means that your normal site configuration should contain only the modules you need on the live site, and you configure Environment Modules to enable additional development modules only on the dev server.
If you decide to try/use this module, I'd like to hear how it works for you.
Comment: http://drupal.org/project/env may help
Comment: That's an interesting module, but I already use features (with the Features module) and a controller module which enables all my custom features, giving me basically the same benefit.  What I'm trying to do is make sure I don't accidentally enable a module on the wrong version of the site.
Answer: I'm not aware of a supported way to "block" a module. You could attempt to force the issue by having a module with a high weight that does
db_query("DELETE FROM system WHERE name IN ('module 1', 'module 2')");

but that seems like risky business.
I would do it in some form of deployment script, that you probably have anyway to handle the dev->stage->production workflow. My team keeps a build configuration with each site that is used to deploy the site. It would then be easy to have a list of modules that should be removed after each deploy on the production server.
Answer: Checkout the Habitat module. It allows you to set modules that should be enable or disabled on the different environments you have. You can set this in settings.php. I use a settings.php that loads an environment specific settings.php and in these I have the habitat setting for each environment.
Answer: You can check it with module_exists
if (module_exists('mymodule', 1.2) {
  if($myliveip == 'myliveip')
   drupal_uninstall_module('mymodule');
}

And call this in your modules hook_init
API
Comment: `module_exists()` accepts just the name of the module as argument; the second parameter you pass it in your snippet is not used from the function. It is not clear what the purpose of `if($myliveip == 'myliveip')` should be. The question has been edited; the OP is asking how to be use a module is enabled on the production server.
Comment: Adding this to hook_init() is also a weak idea, it will be called on every single page load, well after the module is disabled.
Comment: @kiamlaluno, @ Alex, Thanks for figuring me the risk.


Why is a quaternion a + bi + cj + dk not equal to a + (b+c+d)i

Question: i² = -1
j² = -1
k² = -1
But
a + bi + cj + dk is not equal to a + (b+c+d)i
why not ?
Comment: You left out $ijk=-1$, which is what shows you they can't be equal
Comment: This is because taking square destroy information. eg. $1^2 = 1 = (-1)^2$ doesn't imply $1 = -1$.
Comment: What is $i$, $j$ or $k$? Are they the unit vectors  used to represent the axes of a Cartesian coordinate system?
Comment: Why should it be?
Comment: You probably have not studied some higher vector notes. They are assumed to be $i=(1,0,0)$, $j=(0,1,0)$ and $k=(0,0,1)$ in $R^3$.
Comment: @mrs https://en.m.wikipedia.org/wiki/Quaternion
Comment: @BrianMoehring: Dear friend I know that. I want to be sure of it. Thanks.
Comment: Based on your record, I assumed you did, but to a casual observer your second post would seem more confusing than clarifying.
Answer: Because $i, j, k$ aren't equal. In the quaternions, $-1$ has even more square roots than it does in the complex numbers.
Answer: $$\forall a,b,c,d,a',b',c',d' \in \Bbb R: a + bi +cj +dk = a'+ b'i+c'j+d'k \iff a=a', b=b', c=c', d=d'$$ just as if we'd have written a $4$-tuple $(a,b,c,d)$ for the quaternion. The coefficients uniquely determine the number.
In particular $i = 0+1i + 0j + 0k \neq j = 0 + 0i + 1j + 0k$ etc. The roots of $-1$ are $i,-i,j,-j,k,-k$ already showing the quaternions are not a field (already obvious from non-commutativity: $ij=k, ji=-k$ etc.) as in a field a quadratic like $x^2+1$ can have at most $2$ roots, not $6$.


Create a jpeg file in c:\imagesFolder based on the Image stored in the database in vb.net

Question: I have pictures of each employee stored in SQL database with Image database.
Select pic from empimages where emp_ID=10

give the picture of that employee in binary format.
How do I create a physical jpeg in C:\images folder based on the above query in vb.net.
Thanks
Answer: In what format do you have the file? As a byte array? In that case, simply write
My.Computer.FileSystem.WriteAllBytes( _
    "C:\images\" & imagename & ".jpg", ImageData, False)

Answer: Here is a good tutorial relating to this: Creating Binary Files using Visual Basic
You should be able to just take the data from the blob and write it to a file this way. Hope it helps.


Statistic test when bias is not random

Question: Is there a statistical test that I can use to say that there is bias in the result of my analysis but the bias only occurs at certain region. The scatter plot below probably will make more sense:

Basically this are the residuals vs observed data. I hope you can see that as the observed data increases, the residual increases. The overall result was unbiased calculated using mean error, but clearly something is wrong at the higher end. Hope to get some ideas. Thanks
Answer: Testing residuals is not common practice (see for example) R: test normality of residuals of linear model - which residuals to use) In this case your plot could be an indication of non-linearity, did you try to add an quadratic component in your model (assuming it is a regression model)? Basically you square the data and add it to the model.

Statistic test when bias is not random


Syncopated piano sustain pedal playback on Finale

Question: I'm trying to write a piano score on Finale 2014 with sustain pedals such that there is not any gap between them. I have tried the Custom Line Tool from the Smart Shape Tool, adjusting each pedal's hooks as close as possible, without leaving any space uncovered. However, when playing, it sounds a gap without pedal at the ending of each pedal.

How could this task be done?
Answer: Make 2 versions:

a print version (like your example)
and an audio where you keep the notes like you want (try with edit note length or accents e.g. tenuto in %)
Answer: Notate the pedal under the first three notes as shown, then write simile.


Embedding a file into C# .NET application and then reading it in slowly?

Question: I have a rather large resource (2MB) that I'm embedding into my C# application ... I want to know read it into memory and then write it to disk to use it for later processing?
I've embedded the resource into my project as build setting
Any sample piece of code will help me startup.
Comment: "as build setting" doesn't mean anything.  Do you see it in the Resources tab or is it visible in the Solution window?
Answer: var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("namespace.resource.txt"))
{
    byte[] buffer = new byte[stream.Length];
    stream.Read(buffer, 0, buffer.Length);
    File.WriteAllBytes("resource.txt", buffer);
}

Answer: You need to Stream in the resource from Disk, since the .NET Framework likely won't load your resources until you access them (I'm not 100% sure, but I'm fairly confident)
While you stream the contents in, you need to write them back as well to disk.
Remember, this will create the filename as "YourConsoleBuildName.ResourceName.Extenstion"
For example, if your project target is called "ConsoleApplication1", and your resource name is "My2MBLarge.Dll", then your file will be created as "ConsoleApplication1.My2MBLarge.Dll" -- Of course, you can modify it as you see fill fit.
    private static void WriteResources()
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        String[] resources = assembly.GetManifestResourceNames();
        foreach (String name in resources)
        {
            if (!File.Exists(name))
            {
                using (Stream input = assembly.GetManifestResourceStream(name))
                {
                    using (FileStream output = new FileStream(Path.Combine(Path.GetTempPath(), name), FileMode.Create))
                    {
                        const int size = 4096;
                        byte[] bytes = new byte[size];

                        int numBytes;
                        while ((numBytes = input.Read(bytes, 0, size)) > 0)
                            output.Write(bytes, 0, numBytes);
                    }
                }
            }
        }
    }

Answer: Try the following:
Assembly Asm = Assembly.GetExecutingAssembly();
var stream = Asm.GetManifestResourceStream(Asm.GetName().Name + ".Resources.YourResourceFile.txt");
var sr = new StreamReader(stream);
File.WriteAllText(@"c:\temp\thefile.txt", sr.ReadToEnd);

The code assumes that your embedded file is called YourResourceFile.txt and that it is in a folder in your project called Resources. And of course the folder c:\temp\ must exist and be writeable.
Hope it helps.
/Klaus


Are these sets not convex?

Question: Definition of convex set says: an object is convex if for every pair of points within the object, every point on the straight line segment that joins them is also within the object. From: Wikipedia-Convex Set.
But I have also heard that if a curve has a upward curvature then its convex otherwise its convex. Have a look at the following figure. The black line is the curve and the red shaded portion is the set. Also, in the second set, it has upward and downward curves.
Only one thing I can think of is: though both sets have downward pointing curves, their curvatures are still positive, am I correct? And can anybody please elaborate on this?
Comment: $$"\mathsf{set}"\in\text{Question's formulation}\nrightarrow[\mathsf{set\textrm{-}theory}].$$
Comment: Set theory gives me the creeps.
Answer: Those sets are convex. What you may be thinking of is a convex function, defined as a function whose epigraph is a convex set: http://en.wikipedia.org/wiki/Convex_function.

A concave function is a function whose hypograph is a convex set.
Comment: So, if a line segment lies in the domain for any two points but the graph of the function lies above those two points then its not convex. Am I right?
Comment: Also, why the difference between the definitions of convex sets and convex functions?
Comment: It makes sense, but I have never heard of the word hypograph...
Comment: A function is convex iff epigraph is convex. A closed convex set can be associated with a convex function (its support functional).

Are these sets not convex?


Python remove characters until letter or number

Question: I am working on a script that reads a file that contains a linux tree output, and I would like to remove the tree formatting at the beginning of each line.  However I would like to keep the spacing that is in the string after the first letter or number.
This is what I have so far:
<code>import re
with open(tree_loc) as f:
    for line in f:
        if 'batman' in line:
            line = re.sub(r'[^\w*]', '', line)
            print(line)
</code>
Comment: Try `re.sub(r'^\W+', '', line)`
Answer: How about a non regular-expression solution?
<code>>>> from string import letters, digits
>>> from itertools import dropwhile
>>>
>>> keep = set(letters + digits)
>>> s = '$@@^test123'
>>> ''.join(dropwhile(lambda c: c not in keep, s))
'test123'
</code>


Obtaining one a.s. convergence from another

Question: I'm reading a probability theory paper and it has a result that, in effect, says that if $X_k$ is a sequence of random variables, if $Y$ is a random variable, if $\phi_k$ is a random subsequence of $\{k\geq 1\}$ with $\{\phi_k-\phi_{k-1}\}_{k\geq 2}$ being i.i.d. random variables with finite expectation, if $A$ is some event, if $c$ is a constant, if
$$\frac{\log P(\{X_{\phi_k}\in A\}\vert Y)}{k}\xrightarrow{\rm{a.s.}}c$$
and if
$$\phi_k/k \xrightarrow{\rm{a.s.}} \mathbb{E}[\phi_2-\phi_1]$$ then
$$\frac{\log P(\{X_{k}\in A\}\vert Y)}{k}\xrightarrow{\rm{a.s.}}c/\mathbb{E}[\phi_2-\phi_1]$$
There is no explanation given in the paper and so, I assume its trivial but I don't understand why this would be true? I can attach the paper if specifics about $X_k,\phi_k,A$ are needed to answer the question. Thanks for your response.
EDIT: Here is the paper. It's in proposition 3.15 and the two equations I'm referring to are the last equation of page 18 and the first equation of page 19.
Comment: Yes it would be nice to attach the paper, since it may answer some questions: is there independence between $(X_i)$ and $(\phi_k)$? $P(X_k\in A)$ is deterministic as well as $P(X_{\phi_k}\in A)$ so why the almost sure convergence instead of a usual convergence?
Comment: @DavideGiraudo Sure thing, I've attached the paper and edited the question. I'm not sure about the independence part but I meant $P(X_k\in A)$ to be a random variable. I'll edit that too.
Answer: I think it is trivial because of the following:
Define $Z_{k}:=\log P(\{X_{k}\in A\}|Y)$
Then,
\begin{align}
\frac{Z_{\phi_k}}{k} &= \frac{Z_{\phi_k}}{\phi_k}\cdot \frac{\phi_k}{k} \\
\implies \frac{Z_{\phi_k}}{\phi_k} &\xrightarrow{\rm{a.s.}} \frac{c}{\mathbb{E}[\phi_2-\phi_1]}
\end{align}
This clearly means $\frac{Z_{k}}{k} \xrightarrow{\rm{a.s.}} \frac{c}{\mathbb{E}[\phi_2-\phi_1]}$.


How to create a jQuery loop to change anchor links based on JSON file

Question: I have a page which contains a select drop down, which contains country names, this then displays logos for brands based in that country.
However each of these brands have a country specific URL, which will need to change depending on the user selected country from the select.
The JSON file has the Brand Names that match the same names used for my data attribute.
Here is an idea of how the JSON structure is:
{
"US": [
    { "Brand": "Brand1", "Link": "http://www.example.com/" }
],
"Germany": [
    { "Brand": "Brand1", "Link": "http://www.example.com/de" },
    { "Brand": "Brand2", "Link": "http://www.example.com/germany" }
],
"France": [
    { "Brand": "Brand1", "Link": "http://www.example.com/france" },
    { "Brand": "Brand3", "Link": "http://www.example.com/fr" },
    { "Brand": "Brand4", "Link": "http://www.example.com/french-site" },
    { "Brand": "Brand5", "Link": "http://www.example.com/francais" }
],
"UK": [
    { "Brand": "Brand1", "Link": "http://www.example.net/" },
    { "Brand": "Brand3", "Link": "http://www.example.org" },
    { "Brand": "Brand6", "Link": "http://www.example.co.uk" }
]
}

How can I loop through my list of brand logos using jQuery, using the data-brand-name attribute in my markup, to change the anchor links based on what I have in my JSON file?
For example like:

When user selects France from the select drop down, the brands belonging to French show up. I want the French links for these brands to be added into the anchor of the li tags.

Here is an example of my HTML:
<select name="select-choice" id="selectCountry">
    <option value="UK">UK</option>
    <option value="US">US</option>
    <option value="Germany">Germany</option>
    <option value="France">France</option>
</select>

Answer: Add onchange event listener to the select and pass the value of the selected option. The retrieve the value using the selected option from the json.
Instead of hardcoding the list in the html , create dynamic li while iterating the json

let json = {
  "US": [{
    "Brand": "Brand1",
    "Link": "http://www.example.com/"
  }],
  "Germany": [{
      "Brand": "Brand1",
      "Link": "http://www.example.com/de"
    },
    {
      "Brand": "Brand2",
      "Link": "http://www.example.com/germany"
    }
  ],
  "France": [{
      "Brand": "Brand1",
      "Link": "http://www.example.com/france"
    },
    {
      "Brand": "Brand3",
      "Link": "http://www.example.com/fr"
    },
    {
      "Brand": "Brand4",
      "Link": "http://www.example.com/french-site"
    },
    {
      "Brand": "Brand5",
      "Link": "http://www.example.com/francais"
    }
  ],
  "UK": [{
      "Brand": "Brand1",
      "Link": "http://www.example.net/"
    },
    {
      "Brand": "Brand3",
      "Link": "http://www.example.org"
    },
    {
      "Brand": "Brand6",
      "Link": "http://www.example.co.uk"
    }
  ]
}

function showBrand(val) {
  let brandList = '';
  json[val].forEach(function(item) {
    brandList += `

      ${item.Brand}

`
  })
  document.getElementById('brands').innerHTML = brandList;
}
<select name="select-choice" id="selectCountry" onchange='showBrand(this.value)'>
  <option value="" selected>Select</option>
  <option value="UK">UK</option>
  <option value="US">US</option>
  <option value="Germany">Germany</option>
  <option value="France">France</option>
</select>

Comment: Thanks - unfortunately I need to do this using jQuery
Answer: You don't need any hard-coded, empty links that need to be looped over and configured. Just build the list items and the links dynamically based on looping over your object and then append the newly created items to the list.
See comments for further details:

let myObj = {
  "US": [
    { "Brand": "Brand1", "Link": "http://www.example.com/" }
  ],
  "Germany": [
    { "Brand": "Brand1", "Link": "http://www.example.com/de" },
    { "Brand": "Brand2", "Link": "http://www.example.com/germany" }
  ],
  "France": [
    { "Brand": "Brand1", "Link": "http://www.example.com/france" },
    { "Brand": "Brand3", "Link": "http://www.example.com/fr" },
    { "Brand": "Brand4", "Link": "http://www.example.com/french-site" },
    { "Brand": "Brand5", "Link": "http://www.example.com/francais" }
  ],
  "UK": [
    { "Brand": "Brand1", "Link": "http://www.example.net/" },
    { "Brand": "Brand3", "Link": "http://www.example.org" },
    { "Brand": "Brand6", "Link": "http://www.example.co.uk" }
  ]
};

// Locate the correct DOM element to work with
let $list = $("ul.flex");

// Set up a change event handler on the select
$("#selectCountry").on("change", function(){

  $list.html("");                 // Clear out old list entries
  let country = $(this).val();    // Store the country name

  // Loop over all the corresponding links in the object
  $(myObj[country]).each(function(idx, item){
    // Conditionally set the green-underline class
    let gu = this.Brand.replace("Brand", "") > 4 ? "" : "green-underline";

    // Create a new bullet with hyperlink in it
    let $newItem = $('
' + item.Brand + '
');

    // and append to list
    $list.append($newItem);
  });

});
li { padding-bottom: 3px; }
.green-underline a { text-decoration:none; border-bottom:2px dashed green; }
.US { background-color:aliceblue; }
.Germany { background-color:lightgreen; }
.France { background-color:#f99; }
.UK { background-color:#ff9; }

<select name="select-choice" id="selectCountry">
    <option value="">--- Please Select Country ---</option>
    <option value="UK">UK</option>
    <option value="US">US</option>
    <option value="Germany">Germany</option>
    <option value="France">France</option>
</select>

Comment: Thanks - I need the list items hardcoded as they contain the classes to show the background image for each brand. The list items will also have the country names they belong to as class names, so that they show/hide based on user selection. (unfortunately this wasn't done using an object in the first place, so have to continue with it for now)
Comment: @ImranR My solution is already adding the class names you showed in your post. Any other data can easily be added dynamically as well. I'll update the post to show this.
Comment: @ImranR Take a look at my updated answer. In particular, select France and look at the results, then right-click any of the hyperlinks and choose "Inspect". You will see that the right classes get added to the bullets.
Answer: As solution, I first loop through the country keys and add them into the select with append(). Then when someone select one country, it update the list with their names and links that belong to the country.

objs = {
  "US": [
      { "Brand": "Brand1", "Link": "http://www.example.com/" }
  ],
  "Germany": [
      { "Brand": "Brand1", "Link": "http://www.example.com/de" },
      { "Brand": "Brand2", "Link": "http://www.example.com/germany" }
  ],
  "France": [
      { "Brand": "Brand1", "Link": "http://www.example.com/france" },
      { "Brand": "Brand3", "Link": "http://www.example.com/fr" },
      { "Brand": "Brand4", "Link": "http://www.example.com/french-site" },
      { "Brand": "Brand5", "Link": "http://www.example.com/francais" }
  ],
  "UK": [
      { "Brand": "Brand1", "Link": "http://www.example.net/" },
      { "Brand": "Brand3", "Link": "http://www.example.org" },
      { "Brand": "Brand6", "Link": "http://www.example.co.uk" }
  ]
};

$.each(objs, function(country, brands){
  $("#selectCountry").append('<option value="' + country + '">' + country + '</option>');
});

$("#selectCountry").change(function(){
  let brands = objs[$("#selectCountry").val()];
  $.each(brands, function(key, brand){
    $("#myList").append('
' + brand.Brand + '
');
  });
});

<select name="select-choice" id="selectCountry">
  <option value=""></option>
</select>

I hope it will help!
Comment: Hello @ImranR, as I can see there is a lot of solution. My distinctively, dynamically use key for feeding the select, provide the anchor text and links, and use 100% jQuery. Moreover, I thought about `brand.Brand.toLowerCase()` in order to keep the same class name format. I hope it is fitting with your needs.


Whats better: stress test the entire system vs profiling and stress testing specific parts?

Question: I work in a company that is entirely on the cloud and we have started a stress testing project. The idea is to load everything in production to a new environment and run stress tests on it to find the total capacity of the system and where the bottlenecks are.
Now, I remember a time when we stress tests physical servers as well as private clouds and I remember that it was almost impossible to get a complete copy of production and all its moving parts. Also, even with stress testing tools like sysbench, Jmeter and ab, you never could exactly simulate traffic just like production.
We would usually monitor and profile production as much as we could, identify an issue and then try to fix that specific issue by simulating it in the stress testing environment.
To calculate capacity we used to (and some still do) use a calculation to predict when capacity will be met or if the response time is below satisfactory levels.
Considering that the project to recreate production and stress test it is quite time and resource consuming, is this the best way to go to find bottlenecks in the system and measure capacity, or is the "old" way better?
Comment: They both have their advantages and will find different bugs.  Unfortunately, this is a really broad question that is likely more art (and opinion) than science and you may not draw good answers for the Stack Exchange style format.
Comment: But, for what it's worth:  I always start a project with individual unit/component tests, and never finish a project until it has focused customer scenario validation and benchmarking.
Comment: I am just saying that stress testing your system is inaccurate as you make a lot of assumptions as you are writing your tests. Example, a user will randomly click on a random button on the web page every 1-10 seconds. Then times that user to 200 concurrent users and see how your system reacts.  Usually with stress testings in this way, you compare a before and after. You get a baseline, you make a change and you test it. I don't see how this large recreation of production can be an accurate test for real life traffic and future capacity.
Answer: It is always better to stress the entire system and use a production-like environment (or even production).
First of all check out Can a proportionately scaled down testing environment find performance load issues? question and its answers.
An application's underlying infrastructure is constructed of many different components such as caches, web servers, application servers and disks(I/O). Bandwidth and CDNs also play a role in its function and therefore have to be taken into consideration during scaling. Each component behaves differently in the application according to how it was configured and scaled. However, the tiered structure makes it difficult to calculate how each should be tested and scaled.
So if possible always go for the system testing in a real conditions. If it is not possible, you can still run load tests testing against a scaled-down environment, however don't expect you will be able to exactly extrapolate the results like this machine has 10Gb of RAM and is able to survive 1000 RPS, that machine has 20Gb of RAM therefore it will be 2000 RPS - it won't work this way.
Comment: My question was different, I am asking why is it better to stress test the entire system over monitoring the system and only stress testing certain bottlenecks when they occur. From your example: you said you have different components, different caches, CDNs and you don't know how they will behave when scaled. But you do know when they are reaching their capacity from your monitoring and you may be able to replicate a stress test more accurately for a single component than you can for the entire system.


Maximum likelihood estimation for $\alpha$ with population pdf $f(x;\alpha)=\frac{2}{\alpha^2}(\alpha-x)I_{(0,\alpha)}(x)$

Question:
A sample of size two is taken from the distribution $ f(x;\alpha)=\frac{2}{\alpha^2}(\alpha-x)I_{(0,\alpha)}(x)$. We need to find the maximum likelihood estimator for $\alpha$.
The likelihood function $$L(x_1,x_2;\alpha)=\frac{2}{\alpha^2}(\alpha-x_1)\frac{2}{\alpha^2}(\alpha-x_2)I_{(0,\alpha)}(x_1,x_1)$$
i.e. $$L(x_1,x_2;\alpha)=\frac{4}{\alpha^4}(\alpha-x_1)(\alpha-x_2)I_{(0,y_2)}(y_1)I_{(y_1,\alpha)}(y_2)$$
where $y_1=\min(x_1,x_2)$ and $y_2=\max(x_1,x_2)$.

Since we have a higher power of $\alpha$ in the denominator, first I thought of taking $\hat\alpha=y_1$ but that would make $L=0$, similarly for $\hat \alpha=y_2$.
Considering another method - Maximizing the numerator and minimizing the denominator. Maximizing numerator gives $\hat \alpha=\bar{x}$ and minimizing denominator gives $\hat \alpha=y_1$.
What should we do here?
EDIT: I tried another way, first we'll be able to maximize the likelihood function if the indicator functions are $1$, taking their values as $1$ and maximizing the function gives $$\hat \alpha=\frac{3\sum x_i}{4} \pm \frac{\sqrt{9\sum x_i^2-14x_1x_2}}{4}$$
I also plotted $L(x_1,x_2;\alpha)=\frac{4}{\alpha^4}(\alpha-x_1)(\alpha-x_2)I_{(0,y_2)}(y_1)I_{(y_1,\alpha)}(y_2)$ for fixed values $(x_1,x_2)$ and observed that at $\hat \alpha=\frac{3\sum x_i}{4} + \frac{\sqrt{9\sum x_i^2-14x_1x_2}}{4}$ the function indeed attains a maximum, but what about the other root?
Also the question asks whether this statistic is sufficient or not. How do I tackle that one?
Comment: Because $\alpha$ governs the support, the location, and the scale, I would expect the MLE to be some function of the mean, variance, and minimum. For some $x$'s it will be the min, and for other $x$'s some function of the moments. You will need to split to different regions of $x$.
Comment: Same question with a particular sample: https://stats.stackexchange.com/q/317874/119261.
Answer: The MLE does exist. You have calculated the likelihood directly, it is positive for $\alpha > \max(x_1, x_2)$. Then pass to the loglikelihood, calculate its derivative and set it to zero. I then find the same root as you. The other root is probably a false solution. You could plot the loglikelihood as function of alpha, and then also plot the two roots to see.
As for sufficiency, can you factor the likelihood function, and then use the factorization theorem?
Comment: The factorization yields that $(\sum x_i,x_1x_2,y_1,y_n)$ are jointly sufficient, and this should imply that the $\hat \alpha$ obtained above can't be sufficient ?
Comment: That sounds correct, yes.


Como faço para Autodetect do firefox com Selenium webdriver em c# (Visual Studio)

Question: Preciso selecionar o Autodetect do profile do Firefox antes de rodar meu script, pois nas configurações de rede do browser está vindo como usar configurações do sistema. Dessa forma não consigo nem abrir o sistema.
Consegui fazer com java, mas aqui tem, coisas que já conhecemos, exigências da empresa para fazer com c# no Visual Studio.
Segue Código feito em Selenium WEBDriver Java:
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.Proxy.ProxyType;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TestesdeLayoutdeTelaSimulacaoEscolhadePlanoPortal {

      private static ArrayList<String> urlList = new ArrayList<String>();

       @BeforeClass
       public static void setup() {

           urlList.add("http://satktsao02web01:8085/front-sales/#/simulation");
       }

 @Test
       public void passTraffixThroughProxyTest() {
 DesiredCapabilities capability = new DesiredCapabilities();
           addProxyCapabilities(capability);

           for (@SuppressWarnings("unused") String url : urlList){
               WebDriver driver = new FirefoxDriver(capability);
               driver.get("http://satktsao02web01:8085/front-sales/#/simulation");
               driver.manage().window().maximize();
                  public static DesiredCapabilities addProxyCapabilities(DesiredCapabilities capability) {
           Proxy proxy = new Proxy();
           **proxy.setProxyType(ProxyType.AUTODETECT);**

           capability.setCapability(CapabilityType.PROXY, proxy);
           capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
           return capability;
       }
    }
  }
}

Comment: DÊ mais informações, mostre como fez em Java.
Comment: **proxy.setProxyType(ProxyType.AUTODETECT);** ---> Desconsiderar **
Answer: Resolvido, segue para C#:
var ff = new FirefoxProfile();
ff.SetPreference("network.proxy.type", (int)ProxyKind.AutoDetect);
var driver = new FirefoxDriver(ff);


continuity of functions on intervals

Question: Suppose that $f : (a,b) \to \mathbb R$ is continuous. Then, there is a continuous $g : [a,b] \to \mathbb R$ such that $g(x) = f(x)$ for all $x \in (a,b)$. That is, a function defined and continuous on an open interval $(a,b)$ can be extended to a continuous function on all of $[a,b]$.
True or False? If true, prove. If false, give a counterexample.
I think its false. As a counterexample:
Let $f(x) = ({x^2}-x-2)/(x-2)$, where $x>2$. Then, $f:(2,\infty) \to \mathbb R$ is continuous.
Let $g : [2,\infty] \to \mathbb R$ such that $g(x) = f(x)$ for all $x \in (2,\infty)$.
Now, $g(x)$ is not defined on $x = 2$ and is therefore discontinuous.
Thus, a function defined and continuous on an open interval (a,b) cannot always be extended to a continuous function on all of $[a,b]$.
Is my answer correct?
Comment: Function $f:(2,\infty)\to\mathbb{R}$ as you defined can be extended by $g:\mathbb{R}\to\mathbb{R}$, $x\mapsto x+1$
Answer: Hint:
What about $f:(0,1)\to\mathbb{R}$ defined by $f(x)=1/x$?
Comment: Yes, the statement is false.
Comment: Yes, cause $1/x\to\infty$ as $x\to 0^{+}$.
Comment: This function cannot be extended to a continuous function on all of [a,b]?
Comment: No, I see that function $\underline{can}$ be extended to a continuous function $g$ in many ways. So I sugest another function $f$ as you can see.
Comment: But the statement is false according to you right?
Comment: Ok, so $f : (0,1) \to \mathbb R$ defined by $f(x) = 1/x$ cannot be extended?
Answer: Of course false!!!!!
Consider for example the function tan(x) in $(-\pi/2, \pi/2)$ which tends to $-\infty$ at $(-\pi/2)^+$ and tends to $+\infty$ at $(\pi/2)^-$. None continuous function $g$ defined on $[-\pi/2,\pi/2]$ can extend $f=\tan$. (otherwise $g(-\pi/2)=+ \infty $ for example which impossible)

continuity of functions on intervals


Shared objects with libraries and directory inclusions in Cmake

Question: I'm very new to Cmake, and I'm trying to use it as an alternative to this approach, which did not work fine.
My structure is actually simple, I have:
App/src/
App/src/so1
App/src/so2
App/src/so3

And in each App/src/soN folder, I have a .cpp file, that shall be compiled into a shared object.
I know I must add a CMakeLists.txt file in each folder listed above, but I'm really lost with the library linkage and inclusion.
For example, suppose there are the following files under App/src/so1:
App/src/so1/so1.hpp
App/src/so1/so1.cpp

And the shared object so1.so requires -I /some/dir/include, and also needs to be linked to -L /some/other/dir/lib -l otherdirlib. What are the appropriate directives for to make this using CMake?
Answer: EDIT:
Use file and GLOB_RECURSE:

GLOB_RECURSE will generate a list similar to the regular GLOB, except
  it will traverse all the subdirectories of the matched directory and
  match the files.

I advice you to rearrenge your files like this:
app/
 |_ src/
 |_ include/
 |_ CMakeLists.txt
so1/
 |_ src/
 |_ include/
 |_ CMakeLists.txt
so2/
 |_ src/
 |_ include/
 |_ CMakeLists.txt
so3/
 |_ src/
 |_ include/
 |_ CMakeLists.txt
CMakeLists.txt

The CMakeLists.txt in app folder:
SET (APP_NAME app)

# Print variables to stdout
MESSAGE ( STATUS )
MESSAGE ( STATUS "Configuring ${APP_NAME}:" )
MESSAGE ( STATUS )

# Source code files
FILE (GLOB_RECURSE SOURCE_FILES src/*.cpp include/*.h include/*.inl)

# Compiler options
IF (CMAKE_COMPILER_IS_GNUCXX)
  ADD_DEFINITIONS (-ansi -Wall -Wextra -Werror -pthread)
ENDIF ()

# Build application
ADD_EXECUTABLE (${APP_NAME} ${SOURCE_FILES})

TARGET_LINK_LIBRARIES (${APP_NAME}
  ${SO1_LIB}
  ${SO2_LIB}
  ${SO3_LIB}
)

INSTALL (TARGETS ${APP_NAME} RUNTIME DESTINATION bin PERMISSIONS OWNER_READ OWNER_WRITE  OWNER_EXECUTE GROUP_READ GROUP_WRITE  GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)

The CMakeLists.txt in each lib folder would be something like this(change the LIB_OUTPUT_NAME in each file accordingly):
SET (LIB_OUTPUT_NAME so1)

# Print variables to stdout
MESSAGE ( STATUS )
MESSAGE ( STATUS "Configuring ${LIB_OUTPUT_NAME}:" )
MESSAGE ( STATUS )

# Source code, headers and test files
FILE (GLOB_RECURSE HEADER_FILES include/*.h include/*.inl)
FILE (GLOB_RECURSE SOURCE_FILES src/*.cpp include/*.h include/*.inl)
FILE (GLOB_RECURSE TEST_SRC_FILES tests/*.cpp tests/*.h tests/*.inl)

# Compiler options
IF (CMAKE_COMPILER_IS_GNUCXX)
  ADD_DEFINITIONS (-ansi -Wall -Wextra -Werror -pthread)
ENDIF ()

# Build library
ADD_LIBRARY (${LIB_OUTPUT_NAME} SHARED ${SOURCE_FILES})

Then in the main CMakeLists.txt:
CMAKE_MINIMUM_REQUIRED (VERSION 2.6)
PROJECT (App CXX)

# Set common variables
IF ("${CMAKE_BUILD_TYPE}" STREQUAL "Release")
  SET (BUILD_DIR build/release)
ELSE ()
  SET (BUILD_DIR build/debug)
ENDIF ()

# Print variables to stdout
MESSAGE ( STATUS )
MESSAGE ( STATUS "Building App:" )
MESSAGE ( STATUS "change a configuration variable with: cmake -D<Variable>=<Value>" )
MESSAGE ( STATUS "CMAKE_INSTALL_PREFIX = ${CMAKE_INSTALL_PREFIX}" )
MESSAGE ( STATUS "CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}" )
MESSAGE ( STATUS "CMAKE_PREFIX_PATH = ${CMAKE_PREFIX_PATH}" )
MESSAGE ( STATUS )

# Remove build directory on clean target
SET_DIRECTORY_PROPERTIES (PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES ${BUILD_DIR})

# Include directories
INCLUDE_DIRECTORIES (
  "app/include"
  "so1/include"
  "so2/include"
  "so3/include"
)

# Add common compiler flags
IF (CMAKE_COMPILER_IS_GNUCXX)
  SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CPP_FLAGS_RELEASE} -O2")
  SET(CMAKE_CXX_FLAGS_DEBUG  "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g)
ENDIF ()

# Build all dynamic Libraries
ADD_SUBDIRECTORY (smartmatic ${BUILD_DIR}/so1)
SET (SO1_LIB ${CMAKE_CURRENT_SOURCE_DIR}/${BUILD_DIR}/so1/so1.so)

ADD_SUBDIRECTORY (saes-runtime ${BUILD_DIR}/so2)
SET (SO2_LIB ${CMAKE_CURRENT_SOURCE_DIR}/${BUILD_DIR}/so2/so2.so)

ADD_SUBDIRECTORY (saes-devices ${BUILD_DIR}/so3)
SET (SO3_LIB ${CMAKE_CURRENT_SOURCE_DIR}/${BUILD_DIR}/so3/so3.so)

# Add dynamic lib to app build for linking.
ADD_SUBDIRECTORY (so1 ${BUILD_DIR}/so1)
SET (SO1_LIB  ${CMAKE_CURRENT_SOURCE_DIR}/${BUILD_DIR}/so1/so1.so)

ADD_SUBDIRECTORY (so2 ${BUILD_DIR}/so2)
SET (SO2_LIB  ${CMAKE_CURRENT_SOURCE_DIR}/${BUILD_DIR}/so2/so2.so)

ADD_SUBDIRECTORY (so3 ${BUILD_DIR}/so3)
SET (SO3_LIB  ${CMAKE_CURRENT_SOURCE_DIR}/${BUILD_DIR}/so3/so3.so)

# Build Application
ADD_SUBDIRECTORY (app ${CMAKE_CURRENT_SOURCE_DIR}/${BUILD_DIR}/app)

More information on:
http://www.cmake.org/cmake/help/cmake2.6docs.html
Comment: +1 Thank you very much for your assistance, but I haven't yet been able to produce the makefiles. I have some particular questions: what, in your post, states I'm producing shared objects? where is the linkage with dynamic libraries (`-L /path/to/mylib -l mylib`)? The inclusion seems to work fine, I guess these two are the only left dependencies now. I'm able to add the path with `link_directories ("path/to/mylib")`, but I don't know which name to use in `target_link_libraries (??? mylib)`. From what I think, `???`  should be replaced for each `.so` produced.
Comment: I may haven't been clear, but I do actually have to compile each `soN/soN.cpp, soN/soN.hpp` into a shared library, so there would first be a `soN.o`, and then, a `soN.so`. I'm mean, I'm not going to have an  unique executable, I'll just have `N` shared objects `.so`.
Comment: Oh those are dynamic libs, then you DO need a CMakeLists in each folder, let me update the post.
Comment: I guess it's fine; you actually got me going nuts, trying to make this run, but now I guess I've learned a bit of `cMake` -- at least enough for to build one proper `CMakeLists.txt` in each folder I need. I'll try to finish things here, and I ask for help if I get stuck at any step. I've just noticed your edit; thanks for the answer!