Minimum distance for a site between two towns

Question: Mathematical modelling problem...
Two towns, A and B, on a straight line 12km apart. I want to put a site on the straight line between the two towns. From the site, travel to A is three times as often as travel to B. I want to position the site so that the amount of travel from the site to the towns is minimized.
Assumptions I have given the model are
(i) The towns and the site can be represented by points.
(ii)    The land is flat.
(iii)   The mode of transport for the run can travel in straight lines.
(iv)    The mode of transport is full for each run
(v) The run will take three times as often to A as it will to B from the site.
(vi)    We can sum the journey to both towns to get the total.
All I have is $3x + (12-x)$
I understand that the site needs to very close to A (thanks to comments and answer given already) but for this problem I require an expression in $x$ that I can differentiate, letting $\frac d{dx}=0$ and solving for $x$ and then show that it is a maximized such that the second derivative $>0$
Any solution or help with this would be greatly appreciated
Comment: Think about it: one round trip to $A$ and one round trip to $B$ is 24 km no matter what. So all you need to do is to minimize distance for trips to $A$, i.e. locate site as close to $A$ as possible..
Comment: Why are you squaring $x$?
Comment: Because to get a derivative it couldn't just be x? Not sure why tbh
Comment: When you say the run will take three times as often to A as it wil be to B from the site, do you by any change mean the time taken at all?
Comment: @SatishRamanathan time isn't a factor as far as the question goes it's amount of travel
Comment: @Vasya yes, that makes sense now
Answer: We can assume the site is on the line segment $AB$.

Let $x$ be the distance of the site from $A$, where $0 \le x \le 12$.

The total distance traveled is given by $d=(3n)x + n(12-x)$, where $3n,n$ are the (constant) number of trips to $A,B$, respectively.

Then $d = (2n)x + 12n$, hence for $x \in [0,12]$, the minimum is achieved at $x=0\;$(i.e., place the site at $A$).
Comment: Ahhh.. I get it, minimum distance is 24km so placing the site at A makes it to B and back in 24km. THAT simple? Brilliant!
Comment: It's not in the question but I think that I have to assume that the mode of transport is full for every journey, when n isn't a factor then. Your solution makes sense to me but placing the site at A would mean a travel of 12km the B everytime..
Comment: Yes, but the savings is the zero distance to $A$ for $75$% of the trips. Take the simple case of $4$ trips, $3$ to $A$, and $1$ to $B$.


How to update components of a JPanel if some action is performed in another JPanel?

Question: I would like to update a JPanel if some action is performed in another JPanel.
Example:
A JPanel with BorderLayout contains the following:
1.) Class LabelPanel which extends JPanel and contains a JLabel that displays a value
 2.) Class ButtonPanel which extends JPanel and contains a JButton
If the user clicks the JButton, the value of the JLabel should be increased by 50 .
The JLabel should somehow be called by an ActionListener listening to the JButton. How could you do that?
MainPanel:
public class MainPanel extends JPanel {
   public MainPanel() {
      this.setLayout(new BorderLayout());

      this.add(new LabelPanel());
      this.add(new ButtonPanel());

   }
}

LabelPanel:
public class LabelPanel extends JPanel {
   public LabelPanel() {
      this.add(new JLabel("Value: " + 0));
   }
}

ButtonPanel:
public class ButtonPanel extends JPanel {
   public ButtonPanel() {
      this.add(new JButton());
   }
}

Comment: Absolutely nothing stops you from doing that. You add the ActionListener to the button, and have it update the label. Whether or not it is in a different panel is immaterial.
Comment: Thank you. I updated my question so that it reflects my problem better. The JPanels are in seperate class files.
Answer: The answer isn't difficult. Lets say your JButton is called button and your JLabel is called label, you can do something like this:
button.addActionListener((ActionEvent e) -> // register ActionListener
{
    int value = Integer.parseInt(label.getText()); // get current value of the label
    value += 50; // increase value by 50
    label.setText(Integer.toString(value)); // update text of the label
});

Answer: You need the following,

private TextField tfCount;  // declare component TextField
  private Button btnCount;    // declare component Button
  private int count = 0;      // counter's value

btnCount = new Button("Count");     // allocate Button instance
add(btnCount);                     // "this" Frame adds btnCount
btnCount.addActionListener(this);

 // ActionEvent handler - Called back when the button has been clicked.
   @Override
   public void actionPerformed(ActionEvent evt) {
      count = Integer.parseInt(tfInput.getText());
      count += 50;                     // incrase the counter value
      tfCount.setText(count + ""); // display on the TextField
                                   // setText() takes a String
   }


SOLR Snippet with link to PDF

Question: I'm using Apache SOLR as search engine. Everything works fine, indexing as I want, showing the data as I want. I only need to show the PDF which belongs to a certain snippet on a search result. Example:
Result 1: Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

Result 2: Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

Result : Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

The idea is, to have a list of snippets which can be either on the node itself or in a pdf (or any other file) which is attached to this node and link to it (in file case).
Tika extension and Apachesolr_attachments are in place and working.
I get the $vars['snippets'] from hook_apachesolr_search_snippets($vars) and I can modify the output. But I don't see how I could add more information to it.
Any help appreciated.
Answer: you can add extra field to solr.
you need to implement
hook_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id)
and there $document->addField('pdf_field_name', 'your_url');
also you need to implement hook_apachesolr_query_prepare(DrupalSolrQueryInterface $query)
and add there $query->addParam('fl', 'pdf_field_name');
then in your search-result.tpl.php
$pdf_field_name should be available (after reindexing)
Comment: Thank you for your answer. This is ok so far. Your solution works for one part. But the snippet still does not know to which pdf file in which field it belongs. Any ideas about that? How could I enhance the infos there?
Comment: Or in other words, is there a way to extend this '['snippets']['content'][0]' with the filename of the field the snippet belongs too?

SOLR Snippet with link to PDF


Hibernate envers ignores types from hibernate-types-52 library

Question: I'm having an entity which is audited using hibernate envers. Using "jsonb" type from hibernate-types-52 library for one of the fields. Example:
@Entity
@Audited
@Table(name = "entity")
class Entity() {

@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
var field1: Map<String, Any> = emptyMap()

}

And here's the generated SQL:
 create table entity (
    field1 jsonb
 )

create table entity_aud (
    field1 uuid
 )

As you can see, jsonb type is not being used for field1 in _aud table. Experiencing same behavior when using psql_enum type. This of course makes an exception, when trying to persist an entity. How can I make envers recognize such a types and make it generate schema accordingly?
Answer: Most likely, this is because Hibernate maps the JDBC Types.OTHER to PostgresUUIDType.
As I explained in this article, you can create a custom Dialect that extends the PostgreSQLDialect:
public class PostgreSQL10JsonDialect
        extends PostgreSQL10Dialect {

    public PostgreSQL10JsonDialect() {
        super();
        this.registerHibernateType(
            Types.OTHER, JsonNodeBinaryType.class.getName()
        );
    }
}

And if we provide the custom PostgreSQL10JsonDialect via the hibernate.dialect configuration property:
<property
    name="hibernate.dialect"
    value="com.vladmihalcea.book.hpjp.hibernate.type.json.PostgreSQL10JsonDialect"
/>


Como chamar uma função no javascript através de uma caixa de texto?

Question: Queria saber como posso chamar uma função por meio de uma caixa de texto. exemplo:
<input type="text" value="load()"/>

Mas não é exatamente a função load, eu queria que o digitador pudesse chamar qualquer função mesmo.
Comment: A sua pergunta está pouco clara. Quer que o utilizador escreva código no input para ser corrido? ou uma função que corra quando o utilizador escreve texto no input?
Comment: código no input para ser corrido :)
Comment: Você gera o código através de alguma linguagem? caso sim poste aqui, pois talvez seja mais prático inserir o `value` através dela...
Answer: Você pode usar o eval().
Experimente assim:
var input = document.querySelector('input[type=text]');
input.addEventListener('blur', function(){
    eval(this.value);
});

Porém recomendo fortemente a ler isto sobre o eval();
Exemplo
Comment: +1 Sua ideia é muito melhor que a minha... nem me veio à mente =)
Comment: Nossa, funcionou \o/ (nunca ia pensar em usar a função eval). Mas é garantido que funciona mesmo com qualquer função mesmo? Tipo $('#content').html('dddddddd')
Comment: @IagoBruno, sim. Teste este: __http://jsfiddle.net/326EU/2/__
Comment: @IagoBruno, isso parece difícil :/ Acho que daria uma boa nova pergunta! Uma ideia (com muitas excepções) é __[testar se tem parenteses assim (link)](http://jsfiddle.net/326EU/3/)__: `input.value.match(/\(?(.*)\)/);`
Comment: @IagoBruno, um caso onde falha é por exemplo: _"Eu sou o Sérgio (irmão do João)"_
Comment: Se não me engado, "seTimeout" também pode fazer a mesma coisa do eval =p
Comment: Se não for pedir muito, teria algum jeito de detectar se o texto escrito dentro de um input é algo javascript?
Comment: Nos meus testes funcionou seu método, mas você acha que pode dar erro em algum caso? Pq ví que ele checa se tem parenteses no value..
Answer: Todos os objetos definidos via código direto na raiz do escopo vão parar no objeto window, e portanto você pode fazer assim:
window["nome do método"]();

Assim vai chamar a função que você quer pelo nome.
Answer: Basta utilizar os atributos do tipo onevent da tag input.
Por exemplo:
<input type="text" onkeydown="alert('keydown')" />

http://jsfiddle.net/MdX76/


Impedir usuário de digitar tipo de logradouro

Question: Meu formulário possui um drop para TIPO DE LOGRADOURO (Alameda, Avenida, Caminho, estrada, etc. a lista não é grande e poderia ser inclusa manualmente dentro do if) , e um input para digitar o NOME DO LOGRADOURO. Eu preciso impedir que o usuário digite o TIPO DE LOGRADOURO no campo NOME DO LOGRADOURO, para evitar duplicidade de dados. Dessa forma, se o usuário digitar "Rua das flores" no campo NOME DO LOGRADOURO, o formulário deve imediatamente remover a string "Rua ", seja no onblur ou no envio do formulário. Que função javascript posso usar para executar esta tarefa?
//drop com tipos de logradouro

            Tipo de logradouro*
            <select id="tipoLogradouro" name="itemImovel.tp_logradouro" required class="form-control">
                <option value="" selected></option>
                @foreach (var item in ViewBag.TipoLogradouro)
                {
                    <option value="@item.propriedade_dominio1">@item.propriedade_dominio1</option>
                }
            </select>

//input para nome do logradouro

            Logradouro*
            <input type="text" id="logradouro" name="itemImovel.ds_logradouro" onchange="bucarCartorio(0);" maxlength="255" value="@Imovel.ds_logradouro" class="form-control" required>

Answer: Existem várias estratégias para isso, abaixo uma que deve ajudar.
//Pego todos os tipos que existem
const tipos  = document.querySelectorAll("#tipoLogradouro option");
//Pego o input com a informação inserida
const iLogradouro = document.getElementById("logradouro");

//Criando uma função que faz a verificação
verificaLogradouros = function(){
    //armazeno o valor informado
    logradouro = iLogradouro.value;
    //Itero por cada tipo
    tipos.forEach((oTipo) =>{
    //armazeno o valor
    tipoLogradouroAtual = oTipo.value;
    //crio uma ExpressãoRegular para verificar o que foi escrito de maneira 'Case Insensitive'
    re = new RegExp(tipoLogradouroAtual, "i");
    // verifico que no valor informado, aparece o texto
    if(re.test(logradouro)){
        //substituo o tipo por texto vazio
        iLogradouro.value = logradouro.replace(re, "");
    }
    });
};

//anexo ao evento blur
iLogradouro.addEventListener('blur', verificaLogradouros);

Comment: Funcionou perfeitamente, após alguns ajustes. A função só não remove o espaço que o usuário digitou após o logradouro, problema que consegui resolver usando trim()
Comment: Que bom que funcionou... Lembre-se de marcar a resposta.


Fitting a sinusoid to $n$ points

Question: I was inspired by a closed question to consider the following problem.
Given a set of $n$ points $\{ (x_i, y_i) , i = 1,..., n \}$ where $n \ge 4 $, find the sinusoid function of the form
$ y = f(x) = a \cos (k x )+ b \sin (k x) + c $
that fits these points, assuming they do lie on a single sinusoid.
My attempt:
Define the error function
$E = \displaystyle \sum_{i=1}^n \left( a \cos (k x_i) + b \sin (k x_i) + c - y_i \right)^2 $
Then find its partial derivatives $\dfrac{\partial E}{\partial a}, \dfrac{\partial E}{\partial b}, \dfrac{\partial E}{\partial c}, \dfrac{\partial E}{\partial k} $, set them to zero, and numerically solve the resulting nonlinear system of $4$ equations in the parameters $a,b,c,k$.
EDIT: I have implemented this method of solving for the parameters by solving the nonlinear system of the $4$ partial derivatives being equal to zero, but it did not work as I hoped it would (it diverged).  So I modified the method and used the steepest descent (the simplest minimization algorithm) to minimize the error function, with $n = 8$, and it did converge, but it needs more testing over several choice of parameters and different number of points.
My Question:
I wonder if a non-numerical method exists for finding $a,b,c,k$ in closed form.
Thank you for any hints or full solutions.
Comment: I assume there is nothing special about fitting 4 points (one could run your procedure for n points). Your procedure is essentially a case of nonlinear least squares: https://en.wikipedia.org/wiki/Non-linear_least_squares
Comment: This kind of nonlinear least-squares fit is quite standard. The usual problem, without convexity, is to decide if you are reaching local or global   minima in the optimization procedure.
Comment: You make explicit expressions $a(k)$, $b(k)$ and $c(k)$ and you just have a nonlinear equation in $k$ to solve.
Comment: @ClaudeLeibovici How do I make these explicit expressions $a(k), b(k)$ and $c(k)$ ? Can you elaborate on this ?
Answer: For the general case of $n$ data points
Suppose that $k$ is known. Define for this value $C_i=\cos(kx_i)$ and $S_i=\sin(kx_i)$. So, the model is
$$y=a \,C+b \,S+c$$ Use the normal equations
$$\sum_{i=1}^n y_i=a \sum_{i=1}^n C_i+\sum_{i=1}^n S_i+n \,c$$
$$\sum_{i=1}^n C_i\,y_i=a \sum_{i=1}^n C^2_i+b\sum_{i=1}^n C_i\,S_i+c\, \sum_{i=1}^n C_i$$
$$\sum_{i=1}^n S_i\,y_i=a \sum_{i=1}^n  C_i\,S_i+b\sum_{i=1}^n S^2_i+c\, \sum_{i=1}^n S_i$$
Solve explicitly these three linear equations to have $a(k)$, $b(k)$ and $c(k)$. So now, you just need to minimize
$$E(k) =  \sum_{i=1}^n \left( a(k) \cos (k x_i) + b(k) \sin( k x_i )+ c(k) - y_i \right)^2$$ which you can plot to locate more or less its minimum. At this point, start a Newton method using numerical derivatives to make $E'(k)=0$.
Comment: I tried your method and it worked like a charm !!  Thank you very much.

Fitting a sinusoid to $n$ points


Does EM algorithm consistently estimate the parameters in Gaussian Mixture model?

Question: I am studying the Gaussian Mixture model and come up with this question myself.
Suppose the underlying data is generated from a mixture of $K$ Gaussian distribution and each of them has a mean vector $\mu_k\in\mathbb{R}^p$, where $1\leq k\leq K$ and each of them has the same co-variance matrix $\Sigma$ and assume this $\Sigma$ is a diagonal matrix. And assume the mixing ratio is $1/K$, i.e., each cluster has same weight.
So in this ideal example, the only job is to estimate the $K$ mean vectors $\mu_k\in\mathbb{R}^p$, where $1\leq k\leq K$ and the co-variance matrix $\Sigma$.
My question is: if we use EM algorithm, will we be able to consistently estimate $\mu_k$ and $\Sigma$, i.e., when sample size $n\rightarrow\infty$, will the estimator produced by EM algorithm achieve the true value of $\mu_k$ and $\Sigma$?
Answer: If the algorithm is initialized with random values each time, then no, the convergence will not necessarily be consistent. Non-random initialization will presumably produce the same result every time, but I don't believe that this would necessary produce the "correct" values of $\mu_k$.
As an aside, by fixing the mixing ratio to $1/K$ and fixing $\Sigma$ to be diagonal, the algorithm becomes very similar to the $k$-means algorithm. This also has inconsistent convergence, depending on the random initialization.
Comment: Could you give more details please? E.g. what data you were using, how you initialised the parameters etc.
Comment: I numerically experimented, at least for 2 independent classes of normal distribution, the EM produces consistent estimator of the class mean. However, K means cannot do that, I proved it mathematically
Comment: Agree with @dcorney. It really depends on the initial values you will choose.  At least in practice wrong choice of initial values lead to unconsistent estimation (I use mixtools R package)


Integer and Float divisions in C

Question: Can Anyone tell me why this happens .....
I compiled and executed it with the latest GCC compiler.
Please don't give suggestions like "place %f in place of %d" and etc..
#include <stdio.h>

int main(void)
{
    printf("%d" , 3.0 / 2.0);
    return 0;
}

Expected Output : 1
Gives Output : 0
#include <stdio.h>

int main(void)
{
    printf("%f" , 3 / 2);
    return 0;
}

Expected Output : 1.000000
Gives Output : 0.000000
Comment: Possible duplicate of [What happens when I use the wrong format specifier?](https://stackoverflow.com/questions/16864552/what-happens-when-i-use-the-wrong-format-specifier)
Answer: In the first case, you pass an expression of type double when the format specifier expects an int, and in the second case you pass an expression of type int when the format specifier expects a double.
Using the wrong format specifier invokes undefined behavior as dictated by the C standard, meaning you can't reliably predict how your program will behave.  Different compilers may manifest undefined behavior in different ways, as well as different optimizations settings on the same compiler.
Attempting to reason away undefined behavior serves no purpose.  Just make sure your program is well behaved, which in this case means using the correct format specifier.
That being said, compilers for x86 systems typically pass floating point parameters in floating point registers while integers are passed on the stack.  So when printf tries to read a parameter of a given type it ends up reading whatever garbage happened to be where it was looking because the actual parameter isn't there at all.
Answer: Computing platforms—sets of hardware and software working together—define how arguments should be passed to functions. This specification of how arguments are passed is part of a specification typically called the application binary interface (ABI).
The details about how an argument should be passed may depend on several factors, including:

its size,
its alignment requirement,
its fundamental type (integer, floating-point, pointer, et cetera),
whether it is an aggregate of some sort, such as a structure or union, and
whether all the details about the argument are known at compile time.

The means by which an argument should be passed may include:

whether it is passed in a register, on the stack, or in memory,
how it is aligned in memory, and
which set of processor register it is passed in.

The expression 3 / 2 has an int type. It will be passed in the way the ABI specifies for an int argument. When you specify %f in a printf format, printf expects a double, and printf looks for the argument in the place the ABI specifies for a double.
Thus, in printf("%f" , 3 / 2);, there is no guarantee that printf even sees the int value that was passed. It may get data from the wrong memory or register entirely.
If printf does get the data for the int value, it will interpret those bytes as if they were double value. The values of bytes have different meanings when they are encoding an int than when they are encoding a double. So the values in the bytes that encode an int value of 1 do not encode a 1 when they are encoding a double value. So, even if printf, when it is formatting a double for %f, gets the bytes for the int value of 1, the characters it produces are not likely to be "1".
The C standard defines how you should use printf and its format specifiers so that the ABI can work. When you violate the C rules about matching argument types with format specifiers, the C standard does not define what behavior results. It leaves you at the mercy of the C implementation. Historically, this meant you were violating the ABI, and the program would break for the reasons I describe above. Over time, compilers have become more aggressive about optimization and other program transformations, with the result that violating the rules of the C standard can transform program behavior in more surprising ways.

Integer and Float divisions in C


Não é possível inicializar um objeto genérico com herança

Question: Estou com dificuldade em aceitar uma classe herdada como tipo genérico de uma classe.
public class Teste
    {
        private void Testando()
        {
            var dog = new Cachorro();
            dog.Nome = "Toy";
            dog.Patas = 4;
            dog.MesesGestacao = 3;
            dog.Especie = "Cachorro";

            Animal a1 = dog;
            Mamifero m1 = dog;

            Pet<Animal> p1 = new Pet<Cachorro>(); // Esta linha não compila.
        }
    }
    class Animal
    {
        public string Especie { get; set; }
    }
    class Mamifero : Animal
    {
        public int MesesGestacao { get; set; }
    }
    class Cachorro : Mamifero
    {
        public string Nome { get; set; }
        public int Patas { get; set; }
    }
    class Pet<T> where T : Animal
    {
        public string Apelido { get; set; }
    }

O erro:

Severity   Code    Description Project File    Line    Suppression State

Error  CS0029  Cannot implicitly convert type 'Pet' to 'Pet'

Mas o cachorro é um animal...
Poderiam auxiliar no entendimento do por que isso não funciona?
Como eu poderia converter um Pet<Cachorro> em um Pet<Animal>?
Answer: Você precisa aprender sobre variância.
Um objeto composto só pode ter a variância de acordo com a herança se for explicitado que isso é permitido, caso contrário ela não é automática.
E há uma outra questão que C# não permitiu o uso de covariância em classes, apenas interfaces e delegados, então terá que implementar essa variância em uma interface e usar em sua classe para que funcione.
Não sei se funcionará como deseja, mas o exemplo não é bom para determinar se na verdade deveria usar outra cosia no lugar. Pode ser que tenha como fazer melhor para o caso específico. Veja funcionando:
public class Program {
    public static void Main() {
        var dog = new Cachorro() { Nome = "Toy", Patas = 4, MesesGestacao = 3, Especie = "Cachorro" };
        IPet<Animal> p1 = new Pet<Cachorro>();
    }
}
class Animal {
    public string Especie { get; init; }
}
class Mamifero : Animal {
    public int MesesGestacao { get; init; }
}
class Cachorro : Mamifero {
    public string Nome { get; init; }
    public int Patas { get; init; }
}
interface IPet<out T> where T : Animal {
    public string Apelido { get; init; }
}
class Pet<T> : IPet<T> where T : Animal {
    public string Apelido { get; init; }
}´

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


how do i refactor middlewares routes in express?

Question: I have a question. Following this code:
const express = require('express');
const usersRouter = require('./routes/users');
const carsRouter = require('./routes/cars');

const app = express();
app.use(express.json());

app.use('/users', usersRouter);
app.use('/cars', carsRouter);
//and other app use routes

module.exports = app;

the question is about app.use routes, imagine having 50, 100, 1000 of routes, it isnt a best practise to update app.js everytime! how to refactor it the right way?
Answer: There are two possible cases:

there are actually 50, 100, 1000 different functions (or routers) that corresponds that many routes. In this case, you need to organize them in some neat way. I suggest scanning folders and calling app.use them in a cycle.
there aren't so many different functions, but instead there are copy/paste code or maybe some few routes correspond to one function. This means you can either organize that functions in an array and then, make app.use inside of a loop. Or, maybe you can create generic muddleware that analyzes path and calls proper function to deal with the request:

    app.use(function(req, res, next) {
      if (req.path.match(/.../)) {
        return ...
      }
      if (req.path.match(/.../)) {
        return ...
      }

      ...

      // if nothing matches, run the next middleware
      next();
    });


Why are there opposite rules for dividing positive numbers and negative numbers?

Question: I'm in confusion from some time about division of negative numbers. When we divide a positive number with a positive number, for example  $$5/3 = 1.66 $$
we see what is biggest multiple of 3 which is either equal or less than $5$. But in terms of negative numbers, it is not similar to positive numbers. For example, $$ -5/3=-1.66$$ in this example we see the smallest multiple of $3$ which is equal to or greater than $-5$.
My question is why are there two different rules for division?
I'm extremely sorry if I'm asking a foolish question. I'm developing an interest in mathematics and I think I should know the basic thing before proceeding forward. I tried to search about this question but couldn't get results.
Thank you in advance!
Answer: As Thomas Andrews says, remember that multiplication and division have the same operator precedence. That is, the following is true:
$$\frac{A\cdot B}{C\cdot D} = (A\cdot B)/(C\cdot D) = A\cdot (B/C)/D = A\cdot (B/(C\cdot D)) = A\cdot (B/D)/C...$$
So what I do when I do division involving negative numbers, is I always factor out the minus sign as a multiplication by negative one ($-1$). Then, I rearrange the terms such that I do the division on the positive numbers, and deal with the $-1$s later. This way, I only remember the positive rule, and the minus sign simply changes the sign of the answer. In your case, I would use the following factorization:
$$-5/3 \rightarrow A=-1 ~~ B=5 ~~ C = 1 ~~ D = 3 \rightarrow (A\cdot B)/(C\cdot D) =$$
$$(A\cdot B)/(C\cdot D) = A\cdot (B/D)\cdot 1/C = -1\cdot (5/3)\cdot 1/1=-1\cdot 1.66\cdot 1 = -1.66$$
Comment: @jameselmore, thanks for the edit. I figured based upon the OP's questions that he's probably not all that high a level in math, so I didn't want to use confusing notation, but your edits definitely help. Thanks for leaving the general formatting layout intact!
Answer: Probably much more notationally simple to write treat $-1.66$ as $-(1.66)$ than as $(-1)+0.66$
Answer: Think about it this way: you work with absolute values (so the "biggest" thing applies) and $$+/+ = -/- = +$$ $$+/- = -/+ = -$$
This is what you would find convenient considering $\mathbb{Z}$ as a ring and finding the "smallest number in division sense" (meaning numbers that can't be divided further)... well, plus or minus them.
Comment: can you please explain your answer in little brief please .


Contrapositive/contradiction proofs and why do they work

Question: Show that if x and y are two integers whose product is even, then at least one of the two
must be even (use the contrapositive argument)
now the thing is I understand how to prove this with a contrapositive argument and without. what I don't get is why proving it with a contrapositive argument works.
The prove would be that
assume x an y are both odd. you do some calculations and get that xy is odd. I don't understand how this proves the other 2 possibilities.  Whats to say that xy isn't ALWAYS odd and we just walked into this nicely. I can only see one way to properly prove this and this is to go through every single (3) case and work it out.  I get that contrapositive arguments are meant to take the idea that x-> q so not x -> not q
but i don't see why cant BOTH results be "wrong"
Answer: $P\implies Q$ has a contraposition $\neg Q\implies\neg P$.
We can use a simpler proposition to make understanding why easier.
We know that all squares are rectangles.  This can be rewritten as "if this shape is a square, then this shape is a rectangle".  The contraposition is "if this shape is not a rectangle, then there is no way that this shape is a square".
Now we draw a shape.  Using geometry, we identify that this shape is not a rectangle.  Therefore, there is no way that this shape is a square.
Now we draw a second shape.  Using geometry, we identify that this shape is a rectangle.  Therefore, there is a possibility that this shape is a square (but we do not care, nor do we know).

Going back to your statement, if $xy$ is always odd, since your statement does not have anything to do with $xy$ being odd, you have no conclusion.  You simply do not care.  You only care that if you have $xy$ is even.


How do I randomly get variables from a mysql database? (using php with dbo connection)

Question: My question clearly states it in the heading, anyway a more elaborate question is how can I randomly show a variable (eg. name) from a mysql database using php with a dbo connection in xampp environment.
Here is what I've come up with from scratch:-
 <?php
                $db = new PDO
                ('mysql:dbname=lab1;host=localhost;charset=utf8','root',
                '');
                $stmt = $db->prepare('SELECT * FROM countries');
 ?>

                <meta charset="UTF-8"/>

RANDOM!

<?php
                $stmt -> execute();
                foreach($stmt as $row){
                $something = array ($row['name'] . $row['name']);
                }
                $rand_keys = array_rand($something, 1);
                echo $something[$rand_keys[0]] . "\n";
?>

Seems to not work when I try opening it (from localhost)
Comment: Maybe look into `RAND()` and `LIMIT 1` and just do it in the sql?
Comment: ^ just dont order by rand if its a large table
Comment: I'd hope the countries table is not larger than a couple hundred ... =D
Comment: "seems to not work" doesn't describe the observed behavior sufficiently. Consider enabling PDO exceptions (since there isn't any error handling shown in the code).  `->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);`.  Also, do `SELECT name FROM` if that's the only column you need to reference, that's more efficient that returning *every* column in the table. And for the future reader, it's much more apparent *how many* columns are being returned, and what the *names* of the columns being returned. The savings on the developer writing `SELECT *` is vastly outweighed by disadvantages.
Comment: I'm not sure I follow your question, but it sounds like you want value from a random row in a table?  If so, that's what Randall's comment does.  If not, please explain.
Comment: the table is only taking 1 row with 4 fields supposedly  (or i could simply minimize the query to a specific field), not that big however, I don't know how to call a variable using an index in the array in a random manner
Comment: 4 columns? so you want a random column not row?
Comment: sorry I was not able to make my question clear, so basically I have a table in mysql, with 4 columns and as of now it has 2 inputted rows, now I want to be able to echo lets say just 1 field (randomly) as I refresh the file when opened from localhost...
Answer: You can use order by RAND() like others suggested. But I think the way you trying does not work because the way you are adding elements into the array. Like the following line:
$something = array ($row['name'] . $row['name']);

does not push multiple elements (eg. country names) into the array. It replaces the previous value by a concatenated string of the same country name repeated twice. (so if the country name is Afghanistan your array will always have one element AfghanistanAfghanistan
Change your code like below:
<?php
            $stmt -> execute();
            $something = [];
            foreach($stmt as $row){
                $something[] = $row['name'];
            }
            $rand_keys = array_rand($something, 1);
            echo $something[$rand_keys[0]] . "\n";
?>

Hope this will work.
Comment: I have edited my answer. This should get rid of the Notice
Comment: this has helped me load in the value properly, however, it's only outputting 1 value, I've got 2 rows and yet it wont randomly output either one but it just outputs 1...
Comment: so you are saying you always see the same country name? can you show me a dump of you `$something` variable? do a print_r($something) right before the `$rand_keys ...` line ?
Answer: Based off your comment of "sorry I was not able to make my question clear, so basically I have a table in mysql, with 4 columns and as of now it has 2 inputted rows, now I want to be able to echo lets say just 1 field (randomly) as I refresh the file when opened from localhost..." ... you will need to do a compound randomize :)
Start with this sql change to randomly just grab one row (of all columns):
SELECT * FROM countries ORDER BY RAND() LIMIT 1

Then retrieve that one row, and then randomly pick from the available columns:
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM);// PDO example, important to fetch by indexes, not associative names

echo $row[ rand(0,count($row)) ];

That should randomly pull one column from the randomly grabbed row.


Existe uma forma de saber os nome do Servidor do Banco da Dados

Question: Existe um commando sql que possa informar o servidor e a base de dados em que está sendo executado o select?
Estou a disposição para mais detalhes
Answer: Sim. você pode usar o seguinte select.
select @@SERVERNAME, DB_NAME()

Comment: Opa, veleu. Consegui também achar pelo SELECT * FROM sys.servers que além do server mostra os links dos outros servers. Unico problema é que eu gostaria de saber qual o nome do Alias do server. Existe como?
Comment: @EmanuelF, alias do server? Refere-se a DNS ou virtualhost?
Comment: Foi atribuido um nome ao servidor. Temos um nome que aponta para o servidor.
Comment: o `@@SERVERNAME` não trás esse nome?
Comment: Sim, ele trás o nome: SRV1 mas eu tenho atribuido para ele o nome: dbDWserver1


Determine all ordered pair (x,y) of positive integers such that $y^{2}−(x+ 2)2^x=1$.

Question: This is what I have come up so far,

y has to be odd. Since $(x+2)  2^{x}$ is always even, hence $(x+2)2^x+1$ is always odd. Thus, y must be an odd number.

$$y^2 \equiv1(mod 4)$$Since all square numbers either congruent to 0 or 1 (mod 4), but $y^2$ is odd, it has to be congruent to 1 (mod 4).

After re-writing $y=2k+1$, I am able to use quadratic formula to get k in term of x $$k=\frac{-4\pm\sqrt{16+(4)(4)(x+2)(2^x)}}{8}$$ So far, I only know that $x=5,y=15$ is a solution. I would greatly appreciate if anyone can help.
Comment: The  solution you mean must be  $y=15(not 9) $ and  $x=5$
Answer: Rearrange first to get
$$(x+2)2^x = y^2-1.$$
Then factoring the RHS gives
$$(x+2)2^x = (y-1)(y+1).$$
Now, this implies $y-1 = a2^{m}$ and $y+1 = b2^{n}$ for some $a,b \in \mathbb{N}$ such that $ab=(x+2)$, and some $m,n \in \mathbb{N} \cup \{0\}$ such that $m+n=x$. Now, note that $2^{\min\{m,n\}}$ is a factor of both $a2^m$ and $b2^n$. And so $a2^m$ and $b2^n$ must differ by a multiple of $2^{\min\{m,n\}}$. However, as $y-1 = a2^m$ and $y+1 =b2^n$ differ by precisely 2 this implies that $2^{\min\{m,n\}}$ is either 1 or 2 and so $\min\{m,n\}$ is either 0 or 1 and so at least one of $m,n$ is 0 or 1.
Case 1: If $m \in \{0,1\}$ then on the one hand $y-1 \le a 2^m \le 2(x+2)$, and also $y+1 \ge 2^n = 2^{x-m} \ge 2^{x-1}$. But on the other hand, $y+1 = (y-1)+2$ so putting this together gives $$2^{x-1} \le y+1 = (y-1) +2 \le 2(x+2) +2,$$ which yields
$$2^{x-1} \le 2(x+2)+2.$$
There are no solutions to this for $x \ge 6$, as the LHS is larger than the RHS for all such $x$.
Case 2: If $n \in \{0,1\}$ then on the one hand $y+1 \le 2(x+2)$ and also $y-1 \ge 2^{x-1}$. But on the other hand $(y+1)=(y-1)+2$ so putting this together gives
$$2^{x-1} \le y-1 = (y+1) - 2 \le 2(x+2) -2,$$
which yields
$$2^{x-1} \le 2(x+2)-2.$$
There are no solutions to this for $x \ge 5$.
So now all that is left to do is to check whether or not there is a solution to this for $x \in \{1,2,3,4,5\}$. This can be done easily by just checking for each such $x$. [I got $x=5,y=15$ as the one solution.]
Comment: @Mahmoudalbahar lets say both $m,n$ are at least 2. Then both $2^m$ and $2^n$ would be multiples of $2^2=4$, and so this implies  $a2^m$ and $b2^n$ would both be multiples of 4. But then this would imply that **the difference** $|a2^m - b2^n|$ of these 2 integers must also be a multiple of 4. But this is impossible as $a2^m =(y-1)$ and $b2^n =(y+1)$ so their difference is $(y+1)-(y-1) =2$, and 2 is not a multiple of 4.
Comment: thank you for your help.
Comment: please  clarify this part of your answer ...I feel like I am not capable of understanding it well " and as $y-1$ and $y+1$ differ by 2 this implies that at least one of $m,n$ is 0 or 1."
Answer: $y^2 - 1 = (x+2)2^x$
$(y-1)(y+1)= (x+2)2^x$.
Now $y- 1, y+2$ must both be even and $\gcd(y-1,y+1) = 2$ so
So one of $y-1$ or $y+1$ must be divisible by $2$ but not any higher power of $2$.  And the other must be divisible by a power of $2$ that is at least $2^{x-1}$.
The very least the term divisible by $2^{x-1}$ can be is $2^{x-1}$.  And the very most the other term, that is only divisible by $2$ and no higher power, can be is $2(x+2)$.  But for significantly large $x$ we will have $2^{x-1} > 2(x+2)$.  However the difference between the terms, $y+1$ and $y-1$ is fixed at $2$.
So we can find an upper bound for the possible value of $x$.
$2^{x-1} - 2(x+2)$ can not be more than $2$.
A bit of mucking $2^{x-1} - 2(x+2) \le 2$ means $2^{x-1} \le 2x + 6$ means $2^{x-2} \le x + 3$ and for $x =5$ we have $2^{5-2} = 5 + 3$ but $2^{6-2} > 6+3$ and by induction we can just say that $2^{x-2}$ will double as $x$ increases by $1$ whereas $x+3$ will only increase by $1$.
So we must have $x \le 5$.
So just try them.
What we are looking for is that $(y-1)(y+1) = (x+2)2^x = [2m]\cdot [N]$ where $m$ is odd and $N$ is divisible by at least $2^{x-1}$ and the difference between $N$ and $2m$ is exactly $2$.
$x= 5$ gives us a perfect $(x+2)2^x = 7\cdot 32 = (2\cdot 7)\cdot 2^4$ where $2^4 - 2\cdot 7 = $ exactly $2$ so $y-1=14; y+1 = 16$ and $y = 15$ is a solution.
No others work.
$x =4$ gives us $(x+2)2^x= 6\cdot 16=\begin{cases}(2\cdot 3)\cdot 16\\(2\cdot 1)\cdot 48\end{cases}$ neither gives us a difference of $2$.
$x= 3$ gives us $(x+2)2^x = 5\cdot 8= (10)\cdot 4=2\cdot 20$ which fails.  As does $x=2$ ($(x+2)2^x=16 =2\cdot 8$) and $x=1$ ($(x+2)2^x= 6=6\cdot 1$... this really fails as when $y$ is odd $(y-1)(y+1)$ is always divisible by $8$).
$x= 5; y = 15$ is the only solution.


Issue with Camera in fragment

Question: I have Activity which contains ViewPager which implements FragmentPagerAdapter with 3 fragments and I have implemented Camera in one of the fragments using SurfaceView. So when users swipes to the left from my home fragment he is able to use Camera (like in WhatsApp). The issue is when starting app (where I get some data across internet and put into listview) or sometimes swipping to the left or right Camera appears in main or home fragment for a second or less and then disappers and home fragment is presented at it should be.
Here is the problem when downloading data, camera occupies home fragment until
 data is loaded. And for now that is for a second or less:
  https://i.stack.imgur.com/wsEUy.jpg
And this is how home fragment actually looks after downloading data:
 https://i.stack.imgur.com/AUv3V.png

I tried with adding background color to my home Fragment container xml
  but that didn't work.

I followed this example to implement camer in fragment:
https://github.com/rexstjohn/UltimateAndroidCameraGuide/blob/master/camera/src/main/java/com/ultimate/camera/fragments/NativeCameraFragment.java
Can someone help or give some suggestions what's happening and what to do? Thanks
Comment: A code snippet would be more helpful.
Comment: I found solution which works in my case. I posted as na answer if someone in future stuck in same problem. Thank you all for trying to help.
Comment: Can u explain more about this .. i am not getting your point.what you wants.
Comment: Thanks for your response. I added 2 images and description.
Comment: The Camera fragment is on the left, so it is the first, isn't it? When initialization is slow, the second ('home') fragment is not added to the pager. You should create all fragments first, and fill them with data (and camera preview) later.
Comment: @AlexCohn thanks for suggestion. I tried that but that didn't work either as it happens also when I swipe from camera fragment back to the home fragment. Camera preview occupy home fragment for a sec and then dissaperas.
Answer: I found solution which fits my needs. So here it is if someone in future stuck with same issue. Somehow the problem was when I add my CamerPreview to View in my case that was FrameLayout and that was in OnCreateView of CameraFragment. Even if I try to start camera preview when CameraFragment is visible to user and stop preview when it's not visible that didn't help I was always getting flash over home fragment by Camera preview when swipping to the left or right.
So I create new Fragment which is like placeholder and I added it to FragmentPagerAdapter and then there was an option to create my CameraFragment using FragmentTransaction when my placeholder fragment is visible to user (that works too) but I used ViewPager detecting when user starts swipping to the left then FragmentTransaction begins to replace my placeholder fragment with actuall CameraFragment.
Transaction isn't quite somooth like for example in WhatsApp (If someone knows how they done that and wants to share, that would be great) but it's working without issues and no flashing over home fragment.
Of course if someone have and idea how to improve solution or some another better solution feel free to share it.
Comment: They probably use ViewPager, they could simply have a transparent fragment 'on the left' and camera view under the view pager.
Comment: And if you use the deprecated Camera API, make sure you open the camera in a separate Handler thread (so that Camera.open() and callbacks do not cause congestion on the UI thread).
Comment: @AlexCohn thanks I found your explanation how to open Camera using `HandlerThread` vote up for that. And now it's more smoothly even I think `FragmentTransaction` glitches UI little.
Comment: Actually, WhatsApp is cheating on the camera fragment. When you swap left/right, the preview is not moving; it is only revealed more or less. This suggests (I didn't try to reverse engineer their layout, though it is possible) that they have the preview surface always ready under the other layers, and only have to deal with turning camera on or off in time. I believe this is a more robust approach than putting the preview surface in a fragment inside a ViewPager. Some devices may not be happy with camera preview surface being partially out of the actual screen.
Comment: That's interesting. I noticed that camera is not turnd on immediately when you swap left sometimes it waits probably checking is camera available and then turn on even layout is presented in some gray screen. But what do you think how they made swipe left to the camera without using `ViewPager` and fragment?

Issue with Camera in fragment


Arrangement of buttons

Question: I have created an array of buttons but all the buttons are arranged in vertical order.
I want 3 buttons in one row, next 3 buttons in second row and so on.
Here is my code please check it where it should be done.
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout layout = (LinearLayout)findViewById(R.id.liLayout);
    for (int i = 1; i < 10; i++)
    {

        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(

                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        Button b = new Button(this);
        b.setText("" + i);
        b.setId(100 + i);
        b.setWidth(50);
        b.setHeight(20);
        layout.addView(b, p);

    }
}

Answer: public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//should have a vertical orientation
LinearLayout layout = (LinearLayout) findViewById(R.id.liLayout);

LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(

            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
    );

LinearLayout rowLayout = null; **<--null will cause an exception**
*layout.addView(rowLayout)* **<--must be added to make sure the object/element exist/not null**

for (int i = 1; i < 10; i++)
{
     if( (i % 3) == 1 )
     {
          rowLayout = new LinearLayout( this );
          layout.addView( rowLayout, p );
     }//if
     Button b = new Button(this);
     b.setText(""+ i);
     b.setId(100+i);
     b.setWidth(50);
     b.setHeight(20);
     rowLayout.addView(b, p); **<-- you can't add to rowLayout at first, because it doesn't exist yet**
}

}
Regards,
 Stéphane
Comment: hi stephane..the statements rowLayout=new LinearLayout(); gives an compilation error.."The constructor LinearLayout is not defined" and when i give rowLayout=new LinearLayout(null) its working..but gives runtime error
Comment: hey stephane..what should i do for make the buttons fill the screen horizontally, (and all be equally sized),becoz above all buttons i have textbox..so how can i integrate all this so that all of them fill the screen horizontally
Comment: @Anshuman the first thing to do would be to accept my answer. :) The second would be to give a weight of toe all 3 buttons b.setWeight(1) inside their parent.
Answer: Copy, paste, enjoy..
<RelativeLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content">

<Button android:id="@+id/button1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="Button1"/>

<Button android:id="@+id/button2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toRightOf="@+id/button1"
        android:layout_alignTop="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:text="Button2"/>

<Button android:id="@+id/button3"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toRightOf="@+id/button2" android:layout_alignTop="@+id/button2" android:layout_alignBottom="@+id/button2"
        android:text="Button3"/>

<Button android:id="@+id/button4"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignRight="@+id/button1"
        android:text="Button4"/>

<Button android:id="@+id/button5"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:text="Button5"/>

<Button android:id="@+id/button6"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignLeft="@+id/button3" android:layout_alignRight="@+id/button3"
        android:layout_below="@+id/button3"
        android:text="Button6"/>

<Button android:id="@+id/button7"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignLeft="@+id/button4"
        android:layout_alignRight="@+id/button4"
        android:layout_below="@+id/button4"
        android:text="Button7"/>

<Button android:id="@+id/button8"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/button5"
        android:layout_alignLeft="@+id/button5"
        android:layout_alignRight="@+id/button5"
        android:text="Button8"/>

<Button android:id="@+id/button9"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/button6" android:layout_alignLeft="@+id/button6" android:layout_alignRight="@+id/button6"
        android:text="Button9"/>

and read this:Android Layout Tricks #1
Comment: suppose i had to crate create 100 buttons..than what should i do..simply adding 100 of buutons like this..think if i nedd 1000 of buttons.
Comment: well... i would populate them inside a grid view.
Comment: for all 1000 buttons..thats not efficient for a developer

Arrangement of buttons


For $X$ compact Hausdorff, $f: X \to Y$ surjective, there is at most one topology on $Y$ that makes $f$ continuous and $Y$ Hausdorff.

Question: I know the theorem that if a space $X$ is compact Hausdorff then there is no finer or coarser topology that is both compact and Hausdorff. So if we assume some topology $\tau$ exists that makes $f$ compact and $Y$ Hausdorff, there is no coarser or finer topology that satisfies this. How do we prove that there isn't some incomparable topology which causes this to be true?
Answer: Suppose a topology $\tau$ makes $f$ continuous and $Y$ Hausdorff.  Then $\tau$ is contained in the quotient topology with respect to $f$, since the quotient topology is the finest topology that makes $f$ continuous.  But the quotient topology is compact and $\tau$ is compact Hausdorff, so this can only happen if the quotient topology is the same as $\tau$.  Thus the only possible such topology $\tau$ is the quotient topology.
Answer: This is basically rephrasing Eric's answer:
Given $f \colon X \to Y$ continuous and surjective, this map factors as $X \twoheadrightarrow X/f \to Y$, where $X/f$ is the quotient. The map $\bar f \colon X/f \to Y$ is bijective (because $f$ is surjective) and continuous. But $X/f$ is compact and $Y$ is Hausdorff, so automatically $\bar f$ is a homeomorphism. (This is easily seen by considering images of closed sets.)  Thus the topology on $Y$ is unique.
Note that we didn't need the assumption that $X$ is Hausdorff.
Answer: Suppose that $\tau$ and $\tau'$ are Hausdorff topologies on $Y$ making $f$ continuous. Let $U\in\tau$; $f^{-1}[U]$ is open in $X$. Let $K=X\setminus f^{-1}[U]$; $K$ is closed in $X$ and therefore compact, so $f[K]$ is compact and therefore closed in $\tau'$. But $f[K]=Y\setminus U$, so $U\in\tau'$, and hence $\tau\subseteq\tau'$. Similarly, $\tau'\subseteq\tau$, so $\tau=\tau'$.


python geocode.replace(" ", "") Internal server error

Question: I need help with the string.replace(" ", "")
I am using google geocode and it is returning the geocode as
(-1.2890979, 36.90147) --------- return latitude,longitude
I have stored the geocode in a variable called location
I want to send the coodinates without the brackets and without the space
but location.replace give a 500 Internal server error.
Any suggestions on what i can do to correct this?
Comment: That's a tuple, not a string. Thus, you can't replace any characters. Instead, the parentheses and comma are just for representation; the coordinates themselves are just a pair of floating point numbers.
Comment: Why do you use 'foursquare' tag?
Comment: Have you stored the value of `latitude, longitude` in location? That's a tuple and should be accessed as `location[0]` for latitude and `location[1]` for longitude
Comment: @Evert How can i assign a variables as lat,long so i can pass it on to another api?
Comment: @KosukeOgawa It's because I need to pass the lat,long to the Foursquare Add Venue endpoint. Now, am getting the response {u'meta': {u'errorType': u'param_error', u'code': 400, u'requestId': u'5aa116731ed2190ba3c830b5', u'errorDetail': u'll must be of the form XX.XX,YY.YY (received 36.90147)'}, u'response': {}}
Comment: @SudheeshSinganamalla How can i combine the two so that i can pass it to Foursquare api in the ll parameter which must not have space or the brackets.
Comment: Well, what does that api accept? Just a string perhaps? Can you add a link and a relevant quote from the documentation to your question? It must be documented somewhere. `XX.XX,YY.YY` is ambiguous.
Comment: @Evert Not much is given but an example is given : {44.3,37.2} The description : {required unless near is provided. Latitude and longitude of the user's location. Optional if using intent=global} The doc is here: https://developer.foursquare.com/docs/api/venues/search
Comment: You should add that information into your question, not in (just) a comment.
Comment: But have you tried send it as a "xxx.xxx,yyy.yyy" string?
Comment: @Evert I never knew about tuples before this post. But after some research, i found that i can convert the tuple into string by using str(tuple)...With this, yes, i can send the coordinates as string by replacing the unnecessary characters from the tuple (i.e. space & brackets)
Comment: Well, `str(sometuple)` will give you the space and parentheses. Just use string formatting: `"{},{}".format(*sometuple)` should do it.
Answer: The coodinates from google geocode,
(-1.2890979, 36.90147) --------- return latitude,longitude
are not string but tuple.
That means you cannot use the replace function. Instead convert the tuple using str(tuple) where tuple is the location variable.
Then use the replace function to remove the unnecessary characters.
Comment: Don't use `str.replace()`; just apply string formatting for the tuple elements.


Configuring static route in ubuntu

Question: Number of NIC card of my desktop = 2.
eth0: 10.255.2.191
netmask 255.255.255.0
default gateway 10.255.2.1
broadcast 255.255.255.0

I have bought a switch and want to provide Internet service to another 4 desktops. My PC will act as router. I have configured the /etc/network/interfaces file.
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 10.255.2.191
netmask 255.255.255.0
network 10.255.2.0
broadcast 10.255.2.255
gateway 10.255.2.1

auto eth1
iface eth1 inet static
address 192.168.0.9
netmask 255.255.255.248
broadcast 192.168.0.15
gateway 10.255.2.1
up route add -net 192.168.0.8/29 gw 10.255.2.1 dev eth1

Host Desktop:
There are 4 host desktops. One of host desktop configuration is given below:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static

address 192.168.0.10
network 192.168.0.8
netmask 255.255.255.248
gateway 192.168.0.9

But Host desktop cannot connect to Internet. What should I do?
Answer: 1) Your dekstop's network settings are wrong, the gateway should only be defined for the eth0 interface, and the line route add -net 192.168.0.8/29 gw 10.255.2.1 dev eth1 just doesn't make any sense at all: the computer already has a route to the 192.168.0.8/29 network, as it's directly connected to one of its NICs.
2) You need to enable IP forwarding in the desktop, and also configure IPTABLES to allow routing. Depending on your desktop's current configuration, these steps might be needed or not.

Configuring static route in ubuntu


Problema com variáveis que recebem conteúdo de um comando shell

Question: Tenho um problema em um shell script que estou usando de teste para uma futura tarefa. O script é simples... tenho um arquivo texto que possui 2 colunas com o delimitador ";". Na primeria coluna há sites na internet e na segunda um número de 1 e 3.
O arquivo texto com o nome dos sites se chama dados_entrada e possui o conteúdo abaixo
www.uol.com.br;1
www.bol.com.br;2
www.google.com;3
www.globo.com;2

Um segundo script que fará a leitura desse arquivo é o que estou tendo problemas. Tento armazenar o conteúdo em uma variável porém algum erro está ocorrendo pois a variável fica em branco. De forma simplificada, estou testando direto diretamente no shell.
file_name=dados_entrada

endereco= head -n 1 $file_name | cut -d ";" -f1 |  tail -n 1
num_ping= head -n 1 $file_name | cut -d ";" -f2 |  tail -n 1

Ao executar os 2 comandos acima, ele escreve na tela os valores correspondentes que deveriam estar na variável porém ao entrar com o comando echo $endereco e echo $num_ping , o conteúdo é vazio conforme trecho abaixo:
caio@caio-debian:~/Documentos$ echo $endereco

caio@caio-debian:~/Documentos$ echo $num_ping

caio@caio-debian:~/Documentos$

Atualmente uso o Debian como SO.
caio@caio-debian:~/Documentos$ uname -a
Linux caio-debian 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 GNU/Linux

Alguém saberia me dizer o que estou errando?
Agradeço pela força!
Comment: Isto responde à sua pergunta? [Para que serve o $() \[cifrão seguido de parêntesis\] no BASH?](https://pt.stackoverflow.com/questions/327578/para-que-serve-o-cifr%c3%a3o-seguido-de-par%c3%aantesis-no-bash)
Answer: Adicionei a utilização do operador $() para atribuir corretamente a saída do comando para a variável.
Para verificar o valor da variável o comando echo deve ser executado no próprio script, onde o valor atribuído a variável ainda está disponível.
file_name=dados_entrada

endereco=$(head -n 1 $file_name | cut -d ";" -f1 | tail -n 1)
num_ping=$(head -n 1 $file_name | cut -d ";" -f2 | tail -n 1)

echo $endereco
echo $num_ping

Saída no terminal:
www.uol.com.br
1

Comment: Cara, é isso mesmo! Juro que não faltei a aula de declaração de variável! Obrigado mesmo pela força! Deu certíssimo!!


Redirecting doesn't work with a custom form in a block

Question: I developed a custom form with FAPI and added a block for it.
Block is included only on one specific page (basic node).
When user submits this form it should redirect user to external site (URL is a return value from another external site).
For this purpose I've used $form['redirect'] which was working when this form was used as standalone page.
In block it won't redirect and instead the same page is loaded.
I tried other methods too for redirecting such as php header location and drupal_goto but none of them work.
Perhaps there is something node level overriding that prevents the form redirect?
EDIT:
Block is a very basic implementation on code level. API based hook_info and hook_view functions accompanied with custom content function (which returns form markup:drupal_get_form('my_form')).
The redirect is defined on hook_form_submit($form, &$form_state) in which it first makes two calls to external web services and based on return values it either redirects or shows message:
<code>// Debug shows that this evaluates true
if (!filter_var($webservice1, FILTER_VALIDATE_URL) === false) {
    $form_state['redirect'] = $webservice1;
} else if ($webservice1 == 'ok' && $webservice2 == 'ok') {
    drupal_set_message(theme_item_list($formvalues),'status');
} else {
  drupal_set_message('Error', 'error');
}
</code>
Comment: please show your code, without it we can only guess at what is wrong
Comment: does the form submit, and does the page refresh? I ask because it could be assuming as a block form, it's an ajax call and thus bypassing any redirect
Comment: Yes, it does submit and also the page is refreshed. Referring to above piece of code I tried also drupal_set_message in place of redirect it showed status message, so it confirms that.
Comment: are you sure $webservice1 is still returning the correct value - I don't know why it would change from a page to a block, but weird things do happen
Comment: If it wasn't it wouldn't evaluate true in 1st if statement. Perhaps I need to create a temporary workaround and just print that webservice URL as link in status message. Or even in a modal/popup. But the best case would automatic redirect without extra steps.
Answer: I believe the redirect should be <code>$form_state['redirect']</code>
Comment: Yes it is. Like stated in the description it works that way if the form is used as standalone page. Now that it is as block content the same method doesn't work for some reason.
Comment: in your answer you wrote `$form['redirect']` instead of `$form_state['redirect']`


How to resolve my error in bootstrap.inc?

Question: I use Drupal 7.38 and I have taken the backup from server side and added in my local server. Then the following error showns up:

Fatal error: require_once(): Failed opening required
'D:\xampp\htdocs\kaya/sites/all/modules/commerce_invoice_receipt/commerce_invoice_receipt.admin.inc'
(include_path='../lib;D:\xampp\htdocs\kaya\sites\all\modules\custom\commerce_citrus\lib;.;D:\xampp\php\PEAR')
  in D:\xampp\htdocs\kaya\includes\bootstrap.inc on line 3186

How can I resolve this error?
Answer: The file

D:\xampp\htdocs\kaya/sites/all/modules/commerce_invoice_receipt/commerce_invoice_receipt.admin.inc

Is missing; the Commerce Invoice Receipt module is installed on your site, so the file needs to exist.
If you've lost the file(s) somehow, just download the module again and put it back in place.
If you've removed it on purpose, but without uninstalling the module, follow the above first, then disable and uninstall it. Then you can remove the files safely.
Comment: thanks dud. thank you so much. you save my lots of time.


Looking for proof of monicity of co-product insertions

Question: Let C be a category satisfying the following axioms:

C contains an initial element, designated $0$;
C contains a terminal element, designated $1$;
$0$ and $1$ are not isomorphic;
$1$ is a separator in C; i.e. $((f_0, f_1:X \rightarrow Y) \wedge (\forall x:1\rightarrow X \; [f_0 \circ x = f_1 \circ x])) \Rightarrow (f_0 = f_1)$;
for any objects $A_0$, $A_1$ in C, their co-product $A_0 \oplus A_1$ is an object of C.

I'm looking for a proof of (or counterexample for) the following assertion:

All the canonical insertions of any binary co-product in C are monic.

Thanks!
PS: This question is derived from an exercise (2.12, p. 33) in Lawvere and Rosebrugh's Sets for Mathematics (2003).  The original wording of the exercise is:

Prove on the basis of the axioms for $\cal{S}$ [i.e. Set] so far introduced that if $i_0:A_0 \rightarrow A, i_1:A_1 \rightarrow A$ is a sum in $\cal{S}$, then $i_0$ is a monomapping.

The five axioms I listed are those "so far introduced", as I understand them (except for the first one, which simply states that $\cal{S}$ is a category), and the definition given for "sums" is exactly the definition for co-products.    The reason for leaving open the possibility that the assertion is false is that I may have misunderstood some aspect of the question, or of the axioms.  In this case, a counterexample would help me see where I'm going wrong.
Comment: @Zhen Lin: I'm not playing a riddles game here.  I'm working very hard to teach myself CT, from books in my spare time.  No class, no teacher, no time.  It's hard enough as it is.  If you don't want to help me, that's fine, but please don't treat me like a child.
Comment: Let $\iota_A \colon A \sqcup B$ be a coproduct injection. We have to show that for every distinct $f \neq g \colon X \rightarrow A$ the condition $\iota_A \circ f \neq \iota_B \circ g$ is satisfied. Let us assume $f \neq g$. $1$ is a generator, so if $f \neq g$ then there exists $x \colon 1 \rightarrow A$. Thus we have morphisms $id_A \colon A \rightarrow A$ and $f \circ x \circ ! \colon B \rightarrow A$, where $!$ is the unique morphism to the reminal object...
Comment: ...By universality of the coproduct, there is a morphism $h \colon A \sqcup B \rightarrow A$ such that $h \circ \iota_A = id_A$. Thus, $\iota_A$ is split mono, so mono.
Comment: What are your thoughts on this question? And by the way: what is an ISO proof?
Comment: @Theo: ISO="in search of" (fixed title to make it clearer); I think the assertion is true, but I have no idea of how one proves it; I've worked on it for a few hours, and have not gotten any traction at all.
Comment: @kjo: Does it help if I tell you the claim is false?
Comment: @kjo: That was merely a hint to look for a counterexample. I don't know what your background is, so I can't judge whether you would be well-placed to find one or not. If you're not I can give details. All I know is that you are reading  _Sets for Mathematics_ —that was also *my* first introduction to category theory, because I didn't have enough background to appreciate the textbooks aimed at students with more mathematical background. But for all I know you've completed several abstract algebra classes and have for some reason decided to pick up this book rather than, say, Mac Lane's classic.
Comment: [...] For what it's worth, it's been two and half years or so since I picked up _Sets for Mathematics_ and it's only now—after finishing a full 3 years of undergraduate mathematics—that I feel well-placed to begin really understanding category theory. Many interesting examples simply aren't available if you don't know enough algebra or topology or geometry.
Comment: @Mockup: Nice! I was having trouble seeing how to get an arrow $B \to A$ and I was thinking about splitting it between the case that there is some arrow $1 \to A$ and the case that there aren't but then I got stuck there.
Comment: @Zhen Lin: sorry for my testy reply.  Too many times I have received responses that accuse me of trying to get a solution to some school homework problem on the cheap, or insinuated as much.  When one is 52, long out of school, and studying independently in the little spare time one has, such responses get particularly irritating.  Also, thanks for the counterexample you posted.  Even though, as Theo Buehler noted, it did not fully satisfy all the axioms I posted, thinking about the way in which it failed to do so led me to a lot of illuminating results.  I wish now I had copied it down!
Answer: I must say I do not understand Beroal's completion/simplification of the comment. Let me allow to restate the argument.
Let $\iota_A \colon A \rightarrow A \sqcup B$ be a coproduct injection.

Observation:
If we had any morphism $r \colon B \rightarrow A$, then we could apply the universal property of the coproduct to the morphisms $id_A \colon A \rightarrow A$ and $r \colon B \rightarrow A$ to obtain a morphism $h \colon A \sqcup B \rightarrow A$ that commutes with the identity $id_A$, and thus makes the injection $\iota_A$ a split monomorphism.

We have to show that for every pair of distinct morphisms $f \neq g \colon X \rightarrow A$ they precomposition with $\iota_A$ gives different morphisms --- that is: $\iota_A \circ f \neq \iota_A \circ g$. So, let us take such $f$ and $g$. Because the terminal object $1$ is a separator of the category and $f \neq g$, there exists $x \colon 1 \rightarrow A$. Therefore we have a morphism $r = f \circ x \circ ! \colon B \rightarrow A$, where $!$ is the unique morphism to the terminal object, what by the above observation completes the proof.

Zhen, my comment to your former answer about extensive categories, was just like a shoot to a fly with a cannon. Here is a simpler and more accurate argument, which consists of three relatively easy to prove facts:

it suffices for a category to be distributive to have monic coproduct injections
every cartesian closed category with coproducts is distributive
every topos is cartesian closed and has coproducts
Comment: $h$ does not commute with the identity $id_A$ because $h\circ id_A$ is not allowed.
Answer: This is Mockup's proof, completed/simplified.
Definition. An object $A$ is inhabited if there exists an element of $A$.
Lemma 0. For every inhabited $A$ and every object $B$ there exists a constant morphism of type $B\to A$. Proof. It is $e\circ u$, where $e$ is that element of $A$, $u:B\to 1$. Qed.
Lemma 1. Suppose that an object $A$ is not inhabited. Every morphism $f$ from $A$ is a monomorphism. Proof. Suppose $e_0, e_1$ are elements of $A$. This contradicts that $A$ is not inhabited, then $e_0=e_1$. Then $f$ is an injective morphism. Then by Exercise 2.7 $f$ is a monomorphism. Qed.
Your question. Proof. Using the axiom of excluding middle, $A$ is inhabited or $A$ is not inhabited. If $A$ is not inhabited, then $\iota_0:A\to A+B$ is a monomorphism by Lemma 1. Suppose $A$ is inhabited, then there exists $c:B\to A$ by Lemma 0. $[id(A),c]\circ\iota_0 = id(A)$ by algebraic properties of the coproduct, then $\iota_0$ is a split monomorphism, then it is a monomorphism. Qed.
Square brackets denote sum of morphisms. Sum of morphisms is extracted from universal property of a coproduct, as well as the algebraic properties which I referred to. Moreover, a coproduct may be defined algebraically. Unfortunately, this seems to be omitted in your textbook.
Answer: I hope it's OK to post yet another proof.

Let $i_0:A_0 \rightarrow A, i_1:A_1 \rightarrow A$ be a sum in $\cal{S}$.  To prove that $i_0$ is monic, the following simple lemma is useful.  It follows directly from the definition of separator in the trivial case where there are no morphisms from the separator to some other object:
Lemma: Let $G$ be a separator in some category $\cal{C}$, and suppose for some object $X$ in $\cal{C}$ there are no morphisms $G \to X$.  Then, for any object $Y\;$ in $\cal{C}$ there can be at most one morphism $X \to Y.\;\;$
Now, to prove that $i_0$ is monic, we consider two cases.
Case $0$: there are no morphisms $1 \to A_0$.  In this case, if $\; \exists f:X \to A_0$, then there can be no morphisms $1 \to X$ either (otherwise, a morphism $1 \to A_0$ could be constructed by composing a morphism $1 \to X$ with $f\;$).  Since $1$ is a separator in $\cal{S}$, by the lemma above, $f\;$ is the only morphism $X \to A$.  Therefore, $i_0$ is (vacuously) monic.
Case $1$: there is a morphism $a:1\to A_0$.  Then we also have the morphism $a \; \circ \; !_{A_1}:A_1 \to A_0$ (where $!_{A_1}$ is the unique morphism $A_1 \to 1$), which, together with $1_{A_0}:A_0 \to A_0$, entails the existence of a unique morphism $u:A_0 \oplus A_1 \to A_0$ with $u \circ i_0 = 1_{A_0}$ and $u \circ i_1 = {a} \; \circ \; !_{A_1}$.  This means that $u$ is a left inverse of $i_0$, which implies that $i_0$ is left-cancellable, or, equivalently, that $i_0$ is monic. $_\blacksquare$

While thinking about this problem, I realized that a very simple category (which Goldblatt calls $\mathbf{2}$), consisting of two objects, an initial $0$ and a terminal $1$, and three mandatory morphisms (the two identities, and $0 \to 1$) satisfies all the five axioms in the original problem statement (although vacuously so for axiom 4 and "most" of axiom 5).  This explains to me why my intuitions based on my prior knowledge of standard set theory led me astray so often: there's a lot more to $\cal{S}$ than those axioms allow for.
This also relates to what I see as the only merit in my proof (and the reason I decided to post it even though other fine proofs had already been posted), namely that it reflects the bipartite structure that the five axioms impose on the category (and epitomized by the category $\mathbf{2}$ described above), in which objects are partitioned into two non-empty equivalence classes according to whether they are codomains to some morphism with domain $1$ or not.

Thanks to all who responded.  This was an unexpectedly instructive exercise.
Comment: This looks good. Just a very small typo: at the very end of case 1 you want to say that $i_0$ is monic, not $1_{A_0}$.
Comment: Thanks for looking over the proof.  Typo fixed!


Auto Update this column after 24 P.M ( 0.00 A.M ) with PHP?

Question: I have this column "ALLTime" ( int (4) type ) !

My query Update for it ( for all ID of account_vip table )
mysql_query(Update account_vip SET ALLTime = ALLTime - 1);

Example: ALLTime column all now are 8, so after 0.00 AM, they will become 7 !
But i want it Auto Update - 1 after 24 P.M ( 0.00 A.M ) and don't get negative ( like -1, -2, ..., -n ), just working when ALLTime still >= 0 !
Comment: No one here for do your job. Here you can find the way of solving but you have to do it yourself. If you not able to do it than please learn it first and than do it yourself.
Comment: if you want to this automatically after 00 AM than you have set a cron job to do this.
Comment: U didn't respond yesterday on same kind of question
Comment: Md.SahadatHossain can you do that with PHP ?
devpro sorry bro, this is other kind question :(
Comment: Billy, you want this to happen every day at midnight?
Comment: @Phiter Fernandes Yes, after 24 PM ( 0.00 AM ) sir !
Comment: You should read up on [EVENTS](https://dev.mysql.com/doc/refman/5.7/en/create-event.html)
Comment: Read this http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428
Comment: @devpro: can you write help, my english and php very bad :(
Answer: Update account_vip SET ALLTime = ALLTime - 1 WHERE ALLTime > 0

will affect only rows where ALLTime is more than 0.
Thank you.
Comment: Yes i know, but I need It "Auto Update" like my post said !
Comment: In MySQL, it can not happen automatically. We need to use triggers or trigger the update from client side (for example, PHP code)
Comment: Yes, i use it with PHP, sorry i wrote didn't enough !
Comment: Please set a CRON job to run just past midnight and execute PHP code, `mysql_query(Update account_vip SET ALLTime = ALLTime - 1 WHERE ALLTime > 0);`
Comment: I don't know PHP, can you help !
Comment: Please look at this example, http://www.w3resource.com/php/function-reference/mysql_query.php
Comment: But how to set cron job with php, i don't know php
Comment: You set CRON jobs using your server control panel (eg, Webmin, cPanel) - given it's a Linux server. It is also possible to set up a CRON from command line, yet that's a subject of advanced Linux admin knowledge. So, if it's a Linux server, please look at your control panel.
Answer: First of all you need to create a CRONJOB and set schedule as you need and your query should be:
Update account_vip SET ALLTime = ALLTime - 1 WHERE ALLTime > 0;

Use ALLTime > 0; it will not update -ve value.
Comment: @tom-chadaravicius yes u can say that. :)
Comment: IMHO, our answers are identical (smile)
Comment: Can you have me write some PHP with this !
Comment: @billy this will help u http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428


Why is there no match for third place for the UEFA Euro 2020?

Question: Today I turned on the TV and wanted to watch the game for third place of UEFA Euro 2020 between Spain and Denmark, but there was nothing. Why is there no match for third place?
In the FIFA World Cup 2018 in Russia, Belgium and England faced each other, and Belgium won 2-0 (1-0).
After doing some research, I found out that there was also no match for third place at the previous UEFA Euro 2016 in France.
Comment: It's worth noting that third-place playoffs usually take place the day *before* the final, not on the same day, so if there had been a third-place playoff, you would already have missed it.
Comment: Agreed, you have right ;-)
Answer: The European Championships used to have a 3rd-place playoff, but it was discontinued after Euro 1980. Attendance was poor (24,652 spectators in a stadium that could hold 81,000), and according to The Athletic, TV viewing figures were also disappointing. As a result, UEFA decided there simply wasn't enough interest in the playoff to justify continuing to hold it.
It should be noted that attendance was poor throughout the tournament, but host nation Italy (one of the teams in the 3rd-place playoff) had consistently attracted crowds of 40-60,000 during the group stages. For their third-place playoff match to experience such a massive drop in attendance convinced UEFA that people simply didn't care about its outcome.
By comparison, the third-place playoff at the 1978 World Cup attracted 69,659 spectators to a 74,624-capacity stadium, only 2,000 less than the attendance for the final. As a larger and more prestigious tournament, the World Cup is able to generate a much higher level of interest in its third-place playoff, and so has never seen fit to get rid of it.
Comment: Okay, thanks. So no game for 3rd place will be made due to no interest...
Comment: As I recollect, those games also tended to be rather underwhelming, with players being obviously disinterested in the outcome, and coaches sometimes sending in a B-team.


Resolving "php54w-common-5.4.24-1.w6.x86_64 conflicts php-common < 5.4.0"

Question: We're running CentOS release 6.5 and PHP 5.4.24, and I'm trying to get mcrypt-php installed.
When I follow the instructions at https://stackoverflow.com/questions/17109818/install-php-mcrypt-on-centos6, however, the process errors out.
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php-mcrypt.x86_64 0:5.3.3-3.el6 will be installed
--> Processing Dependency: php(zend-abi) = 20090626 for package: php-mcrypt-5.3.3-3.el6.x86_64
--> Processing Dependency: php(api) = 20090626 for package: php-mcrypt-5.3.3-3.el6.x86_64
--> Running transaction check
---> Package php-common.x86_64 0:5.3.3-27.el6_5 will be installed
--> Processing Conflict: php54w-common-5.4.24-1.w6.x86_64 conflicts php-common < 5.4.0
--> Finished Dependency Resolution
Error: php54w-common conflicts with php-common-5.3.3-27.el6_5.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

I get the feeling I need to upgrade/uninstall/reinstall PHP, but I've only found instructions on how to do this for php53 and I don't want to risk taking the server offline.
Any thoughts?
Answer: It looks like you're using a 3rd-party repo to provide PHP 5.4, and the package php54w-common from that repo is conflicting with php-mcrypt (which is presumably coming from epel), which is expecting the default CentOS 6 version of php-common.
Your 3rd-party PHP provider might provide their own version of mcrypt (try yum info php54w-mcrypt and see if that gives you anything).  Otherwise, you're out of luck and you'll need to:

Find another package of PHP mcrypt compatible with php54w-common
Revert to the CentOS-supported PHP 5.3 instead of using PHP 5.4
Build your own PHP 5.4 mcrypt package against the ones from your 3rd-party provider

Good luck!


Question on generalized eigenspaces of commuting matrices

Question: The following question came up as a though while I was reading. I cannot see how to proceed on it.
Let us have $M_1,\ldots,M_n$ be commuting matrices. I know that that the generalized eigenspaces are the same across the $M_i$. However, is it true that for each generalized eigenspace, $V$, where $V$ is the generalized eigenspace of $\lambda_i$ for $M_i$, there exists $v\in V$ such that $v$ is an eigenvector for all the $M_i$.
A related question is if it is even true that the $M_i$ need have a common eigenvector (I see how an answer to this question implies an answer to my first question, so these seem equivalent)
I have tried to come up with examples for which what I said is not true, but this has been to no avail. From the generalized eigenspaces I do not see how to proceed.
Thank you for any help.
Comment: What do you mean that the generalized eigenspaces are the "same"? The most you can conclude is that they are invariant subspaces of the other matrices.
Answer: Hopefully, this might help you to successfully resolve your problem. :)
Let $ M_{1},\ldots,M_{n} $ be commuting $ (k \times k) $-matrices over an algebraically closed field $ \mathbb{F} $ of characteristic $ 0 $. Then $ {\frak{g}} := \text{Span}(\{ M_{1},\ldots,M_{n} \}) $ can be viewed as an abelian, hence solvable, Lie-subalgebra of $ \text{End}(V) \cong {\mathbf{M}_{k \times k}}(\mathbb{F}) $. Applying Lie's Theorem to $ {\frak{g}} $, we see that there exists a vector $ v \in \mathbb{F}^{k} $ that is a simultaneous eigenvector of $ M_{1},\ldots,M_{n} $.
Comment: Functioning link for Lie's theorem: http://www.math.rwth-aachen.de/~Max.Neunhoeffer/Teaching/liealg/liealgchap4.pdf .


Action of $\mathfrak{sl}({V})$ in tensor spaces

Question: what is the natural action of $\mathfrak{sl}({V})$ in tensor spaces ?
Answer: If $L$ is a Lie algebra and $V$ and $W$ are representations of $L$, then an action of $L$ on $V\otimes W$ is given by $x.(v\otimes w) = (x.v) \otimes w + v \otimes (x.w)$. It is a nice little exercise to check that this makes $V\otimes W$ a representation of $L$.
Answer: Here's the standard explanation for why Tobias' answer is the natural action to use on the tensor product.  First, the natural action of the group $G = SL(V)$ on a tensor product $U \otimes W$ (where $U$ and $W$ are $G$-representations) is $g \cdot (u \otimes w) = (g \cdot u) \otimes (g \cdot w)$.
Since $\mathfrak{g} = \mathfrak{sl}(V)$ is the tangent space at the identity of $G$ and $U$ and $W$ become $\mathfrak{g}$-representations by differentiating the $G$-representation, the same should be true of $U \otimes W$.  So let $c(t) : (-\epsilon, \epsilon) \rightarrow G$ be a curve in $G$ passing through the identity (i.e. $c(0) = \text{id}$).  Then $X = c'(0) \in \mathfrak{g}$ and the action of $X$ on $u \otimes w$ is obtained by differentiating the action of $c(t)$ on $u \otimes w$ and evaluating at $0$.  So
\begin{align*}
X \cdot (u \otimes w) & = \left[ c(t) \cdot (u \otimes w) \right]'(0) \\ &= \left[ (c(t) \cdot u) \otimes (c(t) \cdot w) \right]'(0) \\ &= \left[ (c'(0) \cdot u) \otimes (c(0) \cdot w) \right] + \left[ (c(0) \cdot u) \otimes (c'(0) \cdot w) \right]  \\ &= (X \cdot u) \otimes w + u \otimes (X \cdot w).
\end{align*}
In the calculation, we used the product rule to evaluate the derivative and we used that $c(0) = \text{id}$ and $c'(0) = X$.  Of course, everything here is done over either the real numbers or complex numbers, which are the primary fields we use for our geometric intuition.
Comment: Nice answer! Once can also derive the induced action on the Lie algebra from the identity $\Phi(e^X) = e^{\phi(X)}$ for $X \in \mathfrak{g}$, $\Phi : G \to \text{GL}(V)$ and $\phi : \mathfrak{g} \to \textrm{gl}(V)$. $G$ is some Lie group and $\mathfrak{g}$ the Lie algebra of $G$.


Whats the code to create a no limit table?

Question: I want to create an html table but it must not have limits in sides.
Can you help me?
Comment: It's still very unclear what you want. Try drawing a quick image, and editing it into your question.
Comment: You want to do what now?
Comment: its like a table that fills the whole screen from sides, but still with limits above and bellow
Comment: I think maybe (guessing) the OP wants either a paginated or scrolling table. (?)
Comment: Perhaps you mean a table of limited height but unlimited width - perhaps that expands in width to enclose its contents?
Answer:

cell content


Why can't we find an open ball $B_r(k)$ for all $k\in K$?

Question: I've read this demonstration:

This may be silly and confusing but the basic idea seems to be that for any point not in $K$, we can find a certain open ball $B_r (x)$ such that $B_r (x) \subset K^c$. This is reasonable to me. But why can't we:

Find an open ball $B_r(k)$ for all $k\in K$?

I believe this would generate some contradiction but I couldn't find it. Perhaps what I am asking is a bit nonsense but I need this to have peace. I know that the theorem is demonstrated and I know that the the complement of an open set is closed but I still feel this piece of information is needed. What would break if we assume that we can always find an open ball $B_r(k)$ for all $k\in K$?
Comment: What breaks is that if $x\in K$, then union of the sets $G_m$ never cover $x$. You will need to get an open set $G\ni x$ to cover it. Then, when you get the finite cover, $G$ might be part of it. After the finite cover is chosen there is no way to ensure that points of $K^c$ are not outside of the $G_k$ of the finite cover. Sure, the finite cover covers all of $\Omega$, but that might be only thanks to $G$ being in the finite cover.
Comment: What do you mean when you write "Find an open ball $B_r(k)$ for all $k\in K$"? A ball such as *what* happens?
Answer: I think you are asking if we can go about doing the proof differently. I wrote down an alternate proof (though the idea is the same) that hopefully captures your question.
Let $K$ be a compact set and we show that $K^\complement$ is open. To this end, fix $x\in K^\complement$ and notice that for any $y\in K$, $r_y := d(x, y) > 0$ since $y \neq x$. Observe that
$$
K\subseteq \bigcup_{y\in K} B\left(y, \frac{r_y}{2}\right).
$$
Therefore, we have an open cover for $K$ and can extract a finite sub-cover. Let $y_1, \dots, y_n$ be such that
$$
K\subseteq \bigcup_{j=1}^n B\left(y_j, \frac{r_{y_j}}{2}\right).
$$
Define $\delta = \min_{1\leq j \leq n}\frac{r_{y_j}}{2}$ and observe that $B(x, \delta)\subseteq K^\complement$. Indeed, for any $y\in B(x, \delta)$ and any $j = 1, \dots, n$ we have
$$
d(z, y_j) \geq d(y_j, x) - d(x, z) > r_{y_j} - \delta \geq r_{y_j} - \frac{r_{y_j}}{2} = \frac{r_{y_j}}{2}.
$$
hence $z\not\in B(y_j, r_{y_j}/2)$ for any $j=1, \dots, n$. Since these balls cover $K$, we see that $z\not\in K$ or rather $z\in K^\complement$.


Using SIMD in a Game Engine Math Library by using function pointers ~ A good idea?

Question: I have been reading Game Engine Books since I was 14 (At that time I didn't understand a thing:P)
Now quite some years later I wanted to start programming the Mathmatical Basis for my Game Engine. I've been thinking long about how to design this 'library'. (Which I mean as "Organized set of files") Every few years new SIMD instructionsets come out, and I wouldn't want them to go to waste. (Tell me if I am wrong about this.)
I wanted to at least have the following properties:

Making it able to check if it has SIMD at runtime, and use SIMD if it has it and uses the normal C++ version if it doesn't. (Might have some call overhead, is this worth it?)
Making it able to compile for SIMD or normal C++ if we already know the target at compile time. The calls can get inlined and made suitable for Cross-Optimisation because the compiler knows if SIMD or C++ is used.

EDIT - I want to make the sourcecode portable so it can run on other deviced then x86(-64) too
So I thought it would be a good solution to use function pointers which I would make static and initialize at the start of the program. And which the suited functions(For example multiplication of Matrix/Vector) will call.
What do you think are the advantages and disadvantages(Which outweights more?) of this design and is it even possible to create it with both properties as described above?
Christian
Comment: You might want to look at [compiler intrinsic functions](http://en.wikipedia.org/wiki/Intrinsic_function) functions. There are many that maps directly to SIMD instructions, and if the target platform doesn't support that specific instruction the compilers today should be smart enough to emulate the instruction. See g.e. [here for VS2012 intrinsics](http://msdn.microsoft.com/en-us/library/26td21ds%28v=vs.110%29.aspx).
Comment: SSE2 instructions have been available for at least 10 years now. Are you sure you care about games running on older machines (assuming we're not talking games on mobile phones or something like that).
Comment: @MatsPetersson I edited my question! I forgot the very important goal to add that it must be portable to about any system.
Comment: @JoachimPileborg I think it's nice that they emulate it, but I wouldn't want my code to be compiler specific which it will be if I use compiler intrinsics from VS2012.
Comment: You will have some "unportable" code if you are using SIMD extensions. The intrinsics are actually fairly portable, as they work with VS, GCC and Intel compilers. Obviously, not on ARM or PowerPC processors...
Comment: @MatsPetersson I understand that. I want it to be able to decide at runtime and compiletime(for inlining) if they are supported, so it's possible to use it on ARM or PowerPC.
Answer: It's important to get the right granularity at which you make decision on which routine to call. If you do this at too low a level then function dispatch overhead becomes a problem, e.g. a small routine which just has a few instructions could become very inefficient if called via some kind of function pointer dispatch mechanism rather than say just being inlined. Ideally the architecture-specific routines should be processing a reasonable amount of data so that function dispatch cost is negligible, without being so large that you get significant code bloat due to compiling additional non-architecture-specific code for each supported architecture.
Comment: If you read the online documentation for IPP it talks about the dispatch mechanism. As for design, that's a big subject, but essentially what I said above: design your library functions so that they operate on a sufficiently large data set, e.g. a row, tile or block of pixels in the case of image processing. Ideally you should process chunks of data that fit within cache so that you can combine multiple function calls on the same data while it's still in cache.
Comment: Since most functions in a math library are rather small, would you suggest dropping the property of it being able to deduce if it has SIMD at runtime and use it if available? and moving the decision of using SIMD to a higher level? I am sure it would be more efficiënt but it's probably unavoidable to get code bloat that way.
Comment: Typically to get any real benefit from SIMD each routine should operate on a reasonably large data set, i.e. not just say adding two SIMD vectors, but adding two 1D or 2D arrays. That way you get good efficiency with the routine itself and the function dispatch overhead is not significant. Look at how Intel handles this in e.g. its IPP library.
Comment: I can find the IPP library on Intels site, but do you mayby have a link to the insides of the library? How would you suggest me to design my math library?
Answer: The simplest way to do this is to compile your game twice, once with SIMD enabled, once without. Create a tiny little launcher app that performs the _may_i_use_cpu_feature checks, and then runs the correct build.
The double indirection caused by calling a matrix multiply (for example) via a function pointer is not going to be nice. Instead of inlining trivial maths functions, it'll introduce function calls all over the shop, and those calls will be forced to save/restore a lot of registers to boot (because the code behind the pointer is not going to be know until runtime).
At that point, a non-optimised version without the double indirection will massively outperform the SSE version with function pointers.
As for supporting multiple platforms, this can be easy, and it can also be a real bother. ARM neon is similar enough to SSE4 to make it worth wrapping the intructions behind some macros, however neon is also different enough to be really annoying!
#if CPU_IS_INTEL

#include <immintrin.h>
typedef __m128 f128;

#define add4f _mm_add_ps

#else

#include <neon.h>
typedef float32x4 f128;

#define add4f vqadd_f32

#endif

The MAJOR problem with starting on say Intel, and porting to ARM later is that a lot of the nice things don't exist. Shuffling is possible on ARM, but it's also a bother. Division, dot product, and sqrt don't exist on ARM (only reciprocal estimates, which you'll need to do your own newton iteration on)
If you are thinking about SIMD like this:
struct Vec4
{
  float x;
  float y;
  float z;
  float w;
};

Then you may just be able to wrap SSE and NEON behind a semi-ok wrapper. When it comes to AVX512 and AVX2 though, you'll probably be screwed.
If however you are thinking about SIMD using structure-of-array formats:
struct Vec4SOA
{
  float x[BIG_NUM];
  float y[BIG_NUM];
  float z[BIG_NUM];
  float w[BIG_NUM];
};

Then there is a chance you'll be able to produce an AVX2/AVX512 version. However, working with code organised like that is not the easiest thing in the world.


What exactly is the "proportion of variability explained"?

Question: One often hears to say "more than 70% variability is explained by ..." What exactly is meant by this? Th proportion of the sum of squares (SSE), or mean sum of squares (MSE)? For example in the following anova table:
                                    Df Sum Sq Mean Sq F value Pr(>F)
as.factor(site)                    444   8357   18.82   163.1 <2e-16 ***
as.factor(year)                     12    569   47.43   410.9 <2e-16 ***
as.factor(month)                     5    863  172.53  1494.8 <2e-16 ***
as.factor(year):as.factor(month)    60    769   12.82   111.1 <2e-16 ***
Residuals                        34188   3946    0.12
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
7176 observations deleted due to missingness

could we say that most of the variability was explained by site? We see that site covers most of the SSE but as there is a lot of sites, the MSE for site is almost the lowest in the table.
And how would I interpret this in practice? I want to know where is the variability, whether it varies mostly accross time or space. Is the site actually the biggest source of variability, or is it a month and year? Shall I read SSE or MSE column for this purpose?
PS: please note I am not a professional statistician, so if you are about to respond with a lot of math then please make also some simple summary for dummies :-)
Comment: possible [duplicates](http://stats.stackexchange.com/questions/32206/why-compare-sum-of-squares-with-anova-and-not-mean)
Comment: my question is not purely technical as the linked one; it has a bit of the interpretational/philosophical level. I don't stick to particular technology like anova; I try to find proper means to answer my question.
Comment: you use % in SSE but not in MSE which is what you are looking in the first part of the question.
Comment: Thanks @Metrics! And what do you think is more appropriate to consider, if I want to answer the question whether my variable varies mostly in time or in space (i.e. accross sites)?
Comment: I think it should be site/space since SSE is higher for that.
Answer: When you hear "more than 70% variability is explained by ...", the speaker is referring to the sums of squares (SS), not the mean squares (MS).  I should note that exactly what they mean is not certain; they could be referring to either eta-squared or partial eta-squared:
\begin{align}
\eta^2&=\frac{SS~IV_j}{SS~Total}  \\
~\\
~\\
\eta^2_\text{partial}&=\frac{SS~IV_j}{SS~IV_j+ SS~Residuals}
\end{align}
Part of the reason why is that the SS can be partitioned (at least if you are using type I SS, see here), but the MS cannot.
You raise a good point that there is more opportunity for a given factor to contribute to the variability in the response when there are more groups in that factor (this assumes, of course, that there is real variability in the levels of the factor).  Many people forget, or are ignorant of, this fact.  Unfortunately, it is not possible to get around this issue.  The implication of this is that the question 'which factor is most important' may not be answerable in an absolute sense, but only relative to something else.
Comment: Thanks gung! So what (SSE or MSE) do you think is more appropriate to consider, if I want to answer the question whether my variable varies mostly in time or in space (i.e. accross sites)? You can use my example for explanation. Thanks!
Comment: It is more appropriate to use SS, not MS.


How can I convert char to string?

Question:
This question pertains to a pre-release version of Rust.
This younger question is similar.

I tried to print one symbol with println:
fn main() {
    println!('c');
}

But I got next error:
$ rustc pdst.rs
pdst.rs:2:16: 2:19 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:2     println!('c');
                          ^~~
error: aborting due to previous error

How do I convert char to string?
Direct typecast does not work:
let text:str = 'c';
let text:&str = 'c';

It returns:
pdst.rs:7:13: 7:16 error: bare `str` is not a type
pdst.rs:7     let text:str = 'c';
                       ^~~
pdst.rs:7:19: 7:22 error: mismatched types: expected `~str` but found `char` (expected ~str but found char)
pdst.rs:7     let text:str = 'c';
                             ^~~
pdst.rs:8:20: 8:23 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:8     let text:&str = 'c';
                                  ^~~

Answer: Use char::to_string, which is from the ToString trait:
fn main() {
    let string = 'c'.to_string();
    // or
    println!("{}", 'c');
}

Comment: It's from the `ToString` trait, which is automatically implemented on anything that implements the `Display` trait, which includes `char`. (`impl ToString for T where T: Display + ?Sized`) This indirection, however, means that this won't show up in documentation, and is just something you have to memorize/learn.
Comment: Yes, weirdly the docs refer to to_string() but never actually define it.
Answer: Using .to_string() will allocate String on heap. Usually it's not any issue, but if you wish to avoid this and want to get &str slice directly, you may alternatively use
let mut tmp = [0u8; 4];
let your_string = c.encode_utf8(&mut tmp);

Comment: To complete this answer and actually get the `&str` out, you need `std::str::from_utf8(&tmp).unwrap()`.
Comment: @BallpointBen not really - `encode_utf8` returns `&mut str` already.
Comment: Whoops, sorry, you're right
Answer: You can now use c.to_string(), where c is your variable of type char.
Comment: This doesn't seem documented explicitly, but it's true because char's implement Display and Display implementations require to_string, but you wouldn't know that from the Display documentation, this is documented on the ToString trait. Which is not very good. https://doc.rust-lang.org/std/string/trait.ToString.html

How can I convert char to string?