Automatically call method after __init__ in child class

Question: I have the following code:
class Parent:
    def __init__(self) -> None:
        print(f"init Parent")

class Child(Parent):
    def __init__(self) -> None:
        super().__init__()
        print(f"init Child")

    def post_init(self):
        print(f"post init")

Child()

Here I get the output:
init Parent
init Child

Is it possible to modify the code in the Parent-class to call the post_init method from the Child-class automatically after the ___init___() of the Parent and the Child-class. I would like to have the following output:
init Parent
init Child
post init

I don't want to modify the Child-class!!!
I have already tried to define a decorator in the Parent-class, but I failed.
EDIT:
The Parent-class is a pattern-class and is multiple used in multiple children. So I don't want to take care every time i use the Child-class. Is it possible on using the abstract-package?
Comment: Probably possible with metaclasses or perhaps something along the lines of the new `__init_subclass__`. But as most people here would ask, "why?" EDIT: I misinterpreted the question slightly due to the title, but explaining why would still be good.
Comment: Thank you for your answer. I have edited the question to improve it. Please take a look.
Answer: Using __init_subclass__ to override the __init__:
class Parent:
    def __init__(self):
        print(f"init Parent")

    def __init_subclass__(cls, *args, **kwargs):
        super().__init_subclass__(*args, **kwargs)
        def new_init(self, *args, init=cls.__init__, **kwargs):
            init(self, *args, **kwargs)
            self.post_init()
        cls.__init__ = new_init

Supporting grandchildren
To only call after a grandchild class's __init__, we need an additional check to see if the __init__ being called is that of the grandchild's:
class Parent:
    def __init__(self):
        print("init Parent")

    def __init_subclass__(cls, *args, **kwargs):
        super().__init_subclass__(*args, **kwargs)
        def new_init(self, *args, init=cls.__init__, **kwargs):
            init(self, *args, **kwargs)
            if cls is type(self):
                self.post_init()
        cls.__init__ = new_init

Example usage:
class Child(Parent):
    def __init__(self):
        super().__init__()
        print("init Child")

    def post_init(self):
        print("post init")

class Grandchild(Child):
    def __init__(self):
        super().__init__()
        print("init Grandchild")

_ = Grandchild()

Output:
init Parent
init Child
init Grandchild
post init

Comment: Thank you. This solution works. I have to test it later if it is the best for my need.
Comment: And then someone defines a *grandchild* class, and they get *two* `post_init` calls every time they instantiate the grandchild.
Comment: @user2357112supportsMonica I suppose one could use a counter/flag to determine the distance from `Parent`... but then what would one do about situations where the grandchild is also a child of `Parent`? EDIT: Nevermind, the easiest thing would be to keep track of the number of `post_init`  calls.
Comment: Thank you for help. Including your last edit (Supporting grandchildren) it works as I want. But finally I must say it is a pity to have no built-in-function (e.g. __post_init__) to simply run a method after initialization.
Answer: You can also write code like this:
class Meta(type):
    def __call__(cls, *args, **kwargs):
        instance = super().__call__(*args, **kwargs)
        instance.post_init()
        return instance

class Parent(metaclass=Meta):
    def __init__(self) -> None:
        print(f"init Parent")

class Child(Parent):
    def __init__(self) -> None:
        super().__init__()
        print(f"init Child")

    def post_init(self):
        print(f"post init")

Child()

Comment: What if my Parent-class is also a child of an other class (e.g.: class Parent(QWidget, metaclass=Meta):). Now I get the error: ```TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases```
Comment: In such a case, `__init_subclass__` is the best choice.


Commutative ring of 2x2 matrices and showing unity

Question: Let $R$ be a commutative ring with unity and $M(2, R)$ the ring of $2$ × $2$ matrices with entries from $R$. Show that $A ∈ M(2, R)$ is a unit if and only if $det(A)$ is a unit in $R$.
So, suppose that $A \in M$ and that it is a unity. Then we have that  $(A)(A^{-1}) = I = (A^{-1})(A)$ since this is a commutative ring. So this means that since $A$ is invertible, it has a determinant. I'm having trouble proceeding from this point. I was thinking maybe $det (A^{-1}) = \frac {1}{det(A)}$ and $det(A)det (A^{-1}) = 1$. Since $A$ has entries from $R$, it would follow that $det(A) \in R$. So since $det(A)det (A^{-1}) =1$, $A$ is a unity in $R$. And then I would have to prove the reverse implication of this.
Any help would be appreciated. Please note: $R \neq \Bbb R$. My instructor was explicit about this fact.
Comment: The proof that the adjugate of $A$ times $A$ is the scalar matrix having $\det A$ on the diagonal works over any commutative ring.
Comment: Actually from $\det(A)\det(A^{-1})=1$ it follows that $\det(A)$ is a unit in $R$ not that $A$ is a unit Now go the other way and show if $\det(A)$ is a unit in $R$ then $A$ is a unit in the matrix group.
Comment: Whoops sorry. I meant that $det (A)$ is a unit in $R$. Did I make any other mistakes? @coffeemath
Comment: Nid- No that was the only error. Aristide's answer below finishes the if and only if.
Answer: Suppose $A$ is invertible, there exists $B$ such that $AB=I$, $det(AB)=det(A)det(B)=1$ so $det(A)$ is invertible. done.
Suppose that $det(A)$ is invertible, write $A=\pmatrix{a&c\cr b&d}$, the inverse of $A$ is ${1\over{det(A)}}\pmatrix{d &-c\cr -b&a}$ done


Netplan doesn't delete bond interface when removed from config

Question: I have a working bond config, set via Netplan
Example, netplan config:
network:
  bonds:
    bond0:
      addresses: [10.10.10.135/26]
      gateway4: 10.10.10.128
      interfaces: [ens1f0, ens1f1]
      nameservers:
        addresses: [188.8.131.52, 18.104.22.168]
      parameters: {mii-monitor-interval: 100, mode: 802.3ad, transmit-hash-policy: layer3+4}
  ethernets:
    ens1f0: {dhcp4: false}
    ens1f1: {dhcp4: false}
  version: 2

Then I update Netplan config to no longer use a bond:
network:
  ethernets:
    ens1f0: {dhcp4: true}
    ens1f1: {dhcp4: true}
  version: 2

When I apply the netplan config, the individual ethernet interfaces are configured properly, but the bond is not deleted from the system.
I have to manually delete it, ex: ip link delete dev bond0
Why is this? Is there a way to make Netplan apply the config exactly as defined?
Answer: The issue that you're facing is included by design. See the Known Issues portion of the netplan-apply manpage:
KNOWN ISSUES
       netplan  apply will not remove virtual devices such as bridges and bonds that have been created,
       even if they are no longer described in the netplan configuration.  That is due to the fact that
       netplan operates statelessly and is not aware of the previously defined virtal devices.

       This  can  be  resolved  by manually removing the virtual device (for example ip link delete dev
       bond0) and then running netplan apply, by rebooting, or by creating a temporary  backup  of  the
       YAML  state in /etc/netplan before modifying the configuration and passing this state to netplan
       (e.g.  mkdir -p /tmp/netplan_state_backup/etc &&  cp  -r  /etc/netplan  /tmp/netplan_state_back‐
       up/etc/ then running netplan apply –state /tmp/netplan_state_backup)


retorno nulo ao cadastrar novo produto, mas quando edito consigo salvar não dar nenhum erro

Question: Olá pessoal estou com problemas aplicação jsf, cdi, quando cadastro novo produto dar retorno nulo, mas quando edito faz edição normalmente. dar erro
ago 28, 2016 12:52:37 AM com.sun.faces.lifecycle.ProcessValidationsPhase execute
ADVERTÊNCIA: /produtos/CadastroProduto.xhtml @40,74 value="#{cadastroProdutoBean.produto.sku}": Target Unreachable, 'produto' returned null
javax.el.PropertyNotFoundException: /produtos/CadastroProduto.xhtml @40,74 value="#{cadastroProdutoBean.produto.sku}": Target Unreachable, 'produto' returned null
Caused by: javax.el.PropertyNotFoundException: Target Unreachable, 'produto' returned null

cadastroProduto.xhtml
 <ui:define name="titulo">#{cadastroProdutoBean.editando ? 'Edição de Produto' : 'Novo Produto'}</ui:define>

<ui:define name="corpo">

    <f:metadata>
        <o:viewParam name="produto" value="#{cadastroProdutoBean.produto}" />
        <f:event listener="#{cadastroProdutoBean.inicializar}" type="preRenderView"/>
    </f:metadata>

    <h:form id="frmProduto">

#{cadastroProdutoBean.editando ? 'Edição de Produto' : 'Novo Produto'}

                <f:selectItem itemLabel="Selecione a categoria"/>
                <f:selectItems value="#{cadastroProdutoBean.categoriasRaizes}" var="categoria"
                               itemValue="#{categoria}" itemLabel="#{categoria.descricao}"/>

                <f:selectItem itemLabel="Selecione a subcategoria"/>
                <f:selectItems value="#{cadastroProdutoBean.subcategorias}" var="subcategoria"
                               itemValue="#{subcategoria}" itemLabel="#{subcategoria.descricao}"/>

                <f:convertNumber maxFractionDigits="2" minFractionDigits="2"/>

    </h:form>

cadastroProdutoBean.java
@Named
@ViewScoped
public class CadastroProdutoBean implements Serializable {

public static final long serialVersionUID = 0L;

@Inject
private Categorias categorias;

@Inject
private CadastroProdutoService cadastroProdutoService;

private List<Categoria> categoriasRaizes;
private List<Categoria> subcategorias;

private Produto produto;
private Categoria categoriaPai;

public CadastroProdutoBean() {
    limpar();
}

//@PostConstruct
public void inicializar() {
    System.out.println("Inicialinado....");

    if (FacesUtil.isNotPostback()) {
        categoriasRaizes = categorias.raizes();
        if (this.categoriaPai != null) {
            carregarSubCategorias();
        }
    }

}

public void carregarSubCategorias() {

    subcategorias = categorias.subcategoriasDe(categoriaPai);
}

private void limpar() {
    this.produto = new Produto();
    categoriaPai = null;
    subcategorias = new ArrayList<>();
}

public void salvar() {
    this.produto = cadastroProdutoService.salvar(this.produto);

    limpar();

    FacesUtil.addInfoMessage("Produto Salvo com sucesso!");
}

public Produto getProduto() {
    return produto;
}

public void setProduto(Produto produto) {
    this.produto = produto;

    if (this.produto != null) {
        this.categoriaPai = this.produto.getCategoria().getCategoriaPai();

    }
}

public List<Categoria> getCategoriasRaizes() {
    return categoriasRaizes;
}

@NotNull
public Categoria getCategoriaPai() {
    return categoriaPai;
}

public void setCategoriaPai(Categoria categoriaPai) {
    this.categoriaPai = categoriaPai;
}

public List<Categoria> getSubcategorias() {
    return subcategorias;
}

public void setSubcategorias(List<Categoria> subcategorias) {
    this.subcategorias = subcategorias;
}

public boolean isEditando() {
    return this.produto != null && this.produto.getId() != null;
}

}
Produto.java
@Entity
@Table(name = "produto")
public class Produto implements Serializable {

private static final long serialVersionUID = 0L;

private Long id;
private String nome;
private String sku;
private BigDecimal valorUnitario;
private Integer quantidadeEstoque;
private Categoria categoria;

@Id
@GeneratedValue
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@NotBlank
@Size(max = 80)
@Column(nullable = false, length = 80)
public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

@NotBlank
@SKU
@Column(nullable = false, length = 20, unique = true)
public String getSku() {
    return sku;
}

public void setSku(String sku) {
    this.sku = sku == null ? null : sku.toUpperCase();
}

@NotNull(message = "é obrigatório")
@Column(name = "valor_unitario", nullable = false, precision = 10, scale = 2)
public BigDecimal getValorUnitario() {
    return valorUnitario;
}

public void setValorUnitario(BigDecimal valorUnitario) {
    this.valorUnitario = valorUnitario;
}

@NotNull
@Min(0)
@Max(value = 9999, message = "Tem um valor muito alto")
@Column(name = "quantidade_estoque", nullable = false, length = 5)
public Integer getQuantidadeEstoque() {
    return quantidadeEstoque;
}

public void setQuantidadeEstoque(Integer quantidadeEstoque) {
    this.quantidadeEstoque = quantidadeEstoque;
}

@NotNull
@ManyToOne
@JoinColumn(name = "categoria_id", nullable = false)
public Categoria getCategoria() {
    return categoria;
}

public void setCategoria(Categoria categoria) {
    this.categoria = categoria;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    Produto other = (Produto) obj;
    if (id == null) {
        if (other.id != null) {
            return false;
        }
    } else if (!id.equals(other.id)) {
        return false;
    }
    return true;
}

public void baixarEstoque(Integer quantidade) {
    int novaQuantidade = this.getQuantidadeEstoque() - quantidade;

    if (novaQuantidade < 0) {
        throw new NegocioException("Não há disponibilidade no estoque de "
                + quantidade + " itens do produto " + this.getSku() + ".");
    }

    this.setQuantidadeEstoque(novaQuantidade);
}

public void adicionarEstoque(Integer quantidade) {
    this.setQuantidadeEstoque(getQuantidadeEstoque() + quantidade);
}

repositorio categorias.java
public class Categorias implements Serializable {

public static final long serialVersionUID = 0L;

@Inject
private EntityManager manager;

public Categoria porId(Long id) {
    return manager.find(Categoria.class, id);
}

public List<Categoria> raizes() {
    return manager.createQuery("from Categoria where categoriaPai is null",
            Categoria.class).getResultList();

}

public List<Categoria> subcategoriasDe(Categoria categoriaPai) {

    return manager.createQuery("from Categoria where categoriaPai = :raiz",
            Categoria.class).setParameter("raiz", categoriaPai).getResultList();
}

categoriaConverter.java
@FacesConverter(forClass = Categoria.class)
public class CategoriaConverter implements Converter {

   // @Inject
private Categorias categorias;

public CategoriaConverter() {
    categorias = CDIServiceLocator.getBean(Categorias.class);
}

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
    Categoria retorno = null;

    if (value != null) {
        Long id = new Long(value);
        retorno = categorias.porId(id);
    }

    return retorno;
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    if (value != null) {
        return ((Categoria) value).getId().toString();
    }
    return "";
}

categoria.java modelo
@Entity
@Table(name = "categoria")
public class Categoria implements Serializable {

private static final long serialVersionUID = 0L;

private Long id;
private String descricao;
private Categoria categoriaPai;
private List<Categoria> subcategorias = new ArrayList<>();

@Id
@GeneratedValue
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@Column(nullable = false, length = 60)
public String getDescricao() {
    return descricao;
}

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

@ManyToOne
@JoinColumn(name = "categoria_pai_id")
public Categoria getCategoriaPai() {
    return categoriaPai;
}

public void setCategoriaPai(Categoria categoriaPai) {
    this.categoriaPai = categoriaPai;
}

@OneToMany(mappedBy = "categoriaPai", cascade = CascadeType.ALL)
public List<Categoria> getSubcategorias() {
    return subcategorias;
}

public void setSubcategorias(List<Categoria> subcategorias) {
    this.subcategorias = subcategorias;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 29 * hash + Objects.hashCode(this.id);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Categoria other = (Categoria) obj;
    if (!Objects.equals(this.id, other.id)) {
        return false;
    }
    return true;
}

CadastroProdutoService.java
 public class CadastroProdutoService implements Serializable {

   private static final long serialVersionUID = 0L;

@Inject
private Produtos produtos;

@Transactional
public Produto salvar(Produto produto) {
    Produto produtoExistente = produtos.porSku(produto.getSku());

    if(produtoExistente != null && !produtoExistente.equals(produto)){
        throw new NegocioException("Já existe um produto com sku informado.");
    }
    return produtos.guardar(produto);
}

Repositório Produtos
public class Produtos implements Serializable {

private static final long serialVersionUID = 0L;

@Inject
private EntityManager manager;

public Produto guardar(Produto produto) {
    return manager.merge(produto);
}

@Transactional
public void remover(Produto produto) {
    try {
        produto = porId(produto.getId());
        manager.remove(produto);
        manager.flush();
    } catch (PersistenceException e) {
        throw new NegocioException("Produto não pode ser excluido");
    }
}

public Produto porSku(String sku) {
    try {
        return manager.createQuery("from Produto where upper(sku) = :sku", Produto.class)
                .setParameter("sku", sku.toUpperCase()).getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

// @SuppressWarnings("uncheked") quando estiver reclamando codigo em "amarelo" retorna lista tipada order
public List<Produto> filtrados(ProdutoFilter filtro) {
    Session session = manager.unwrap(Session.class);
    Criteria criteria = session.createCriteria(Produto.class);

    if (StringUtils.isNotBlank(filtro.getSku())) {
        criteria.add(Restrictions.eq("sku", filtro.getSku()));
    }
    if (StringUtils.isNotBlank(filtro.getNome())) {
        criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE));//where queoque apareça antes ou depois "%joao%" //wherre nome like'%joao%'
    }
    return criteria.addOrder(Order.asc("nome")).list();
}

public Produto porId(Long id) {
    return manager.find(Produto.class, id);
}

public List<Produto> porNome(String nome) {
    return this.manager.createQuery("from Produto where upper(nome) like :nome", Produto.class)
            .setParameter("nome", nome.toUpperCase() + "%").getResultList();
}

Answer: O escopo de view do mbean só faria a chamada ao construtor quando você saísse da página. Dessa forma o problema deve estar no teu método salvar:
this.produto = cadastroProdutoService.salvar(this.produto);
Verifica se o serviço de fato está retornando um valor não nulo.
Comment: Acho que não. postei código repositório e classe serviço Produto dê uma olhada, retorno null para produto
Comment: o problema era no método inicializar valeu obrigadão, pela atenção
Comment: Ah sim. Tava comentada a anotação PostConstruct antes aí nem pensei nesse método. Que bom que funcionou então :)
Answer: [RESOLVIDO] o Problema era no método inicializa não instanciei produto, cadastroProdutoBean.java
@PostConstruct
public void inicializar() {
System.out.println("Inicialinado....");

if (FacesUtil.isNotPostback()) {
    categoriasRaizes = categorias.raizes();
    if (this.categoriaPai != null) {
        carregarSubCategorias();
    }
}

}
da forma que deu certo
    @PostConstruct
public void inicializar() {
    System.out.println("Inicialinado....");

 this.produto = new Produto();<<<<< foi este cara aqui
    if (FacesUtil.isNotPostback()) {
        categoriasRaizes = categorias.raizes();
        if (this.categoriaPai != null) {
            carregarSubCategorias();
        }
    }

}


Como editar uma Partial Class?

Question: Peguei um projeto de um cliente e tem uma classe que está como parcial. Quando clico para ir na referencia abre o arquivo, mas no projeto eu não acho o arquivo, e tem o seguinte texto no arquivo da classe:
//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

Nunca usei partial class, como funciona e como edito?
Comment: Você quer saber o conceito de `partial class` ou quer saber se pode editar o arquivo?
Comment: gostaria de editar, pois não estou encontrando o arquivo, oque seria esse auto generated.
Answer: Definição
Partial class é apenas uma forma de separar duas partes do código de uma classe em arquivos distintos. Não tem nenhum segredo ou semântica especial. É essencialmente uma forma de facilitar a organização de código e indicar para o compilador que os dois códigos disponíveis nos dois arquivos com uma classe de mesmo nome não é um erro de duplicação e sim um código é complementar ao outro e deve ser compilado como se fosse uma coisa só.
Uso
Em geral este tipo de artifício só deve ser usado por geradores de código, assim uma parte é gerada em um arquivo e ninguém deve mexer neste arquivo. Em outro arquivo tem as partes do código da classe que o programador pode mexer sem causar problemas.
Claro que nada impede que o programador mexa na parte gerada, mas não deveria. É uma proteção organizacional apenas para deixar claro quais são as partes que pode mexer e as partes que não pode, mas não protege de fato.
Se você for criar alguma classe que precise ser parcial, basta usar o modificador partial antes de class para indicar que haverá uma outra parte, faça isto nos dois arquivos que possuem as duas partes, não precisa mais nada. Mas lembre-se que você só deveria usar isto se criar um gerador e deseja que uma parte não seja modificada.
Partial Method
Na documentação acima se fala em partial method que é um método que só possui a declaração sem um corpo. Neste caso o corpo estará no outro arquivo. É uma forma de garantir que a assinatura do método não seja mudada no outro arquivo. Se ela for mudada, o compilador indicará problemas.
Não mexa em código gerado
Então o arquivo que você quer mexer não deveria ser mexido.
Onde achar os arquivos
Os arquivos costumam ficar juntos no projeto, senão na mesma pasta, em alguma outra relacionada. Tente verificar pelo Windows Explorer todos os arquivos disponíveis no projeto. O nome do arquivo provavelmente fará alguma menção a partial ou designer ou pelo menos terá um nome semelhante ao arquivo que você quer mexer e não consegue achar. Se achar no Windows Explorer, pode ficar mais fácil localizá-lo no VS.
Veja no VS se os arquivos não estão agrupados no projeto. Clique no sinal de mais [+] para abrir os arquivos relacionados. Dependendo da verão pode ser um triângulo ou outro símbolo, mas é o que abre a árvore de arquivos.
Mas vou reforçar, não edite esta parte a não ser que você saiba muito o que está fazendo e conheça todas as implicações, o que não deve ser o caso.
Coloquei no GitHub para referência futura.
Answer: O @Maniero explicou muito bem - que um partial class é apenas uma classe divida em várias arquivos.
Exemplo:
auto/Pessoa.cs
namepsace App.Gente {
  public partial class Pessoa {
      public Pessoa() {
      }
  }
}

manual/Pessoa.cs
namespace App.Gente {
  public partial class Pessoa {
     //não pode ter construtor aqui, pois já está definido no outro arquivo
     //porém pode ter tantas quantas funções/métodos que queira

     public void FazAlgo() {

     }
  }
}

Main.cs
public static class Main {
   Pessoa p = new Pessoa(); //chama o consturtor em auto/Pessoa.cs
   p.FazAlgo(); //chama o método definido em manual/Pessoa.cs
}

Obs: O partial class deveria ser no mesmo namespace, independente da localização do arquivo físico. Se for em outro namespace, é outra classe.

Como editar uma Partial Class?


PostgreSQL: Syntax error at or near "14" when trying to run a delete query

Question: First question here!
So I have a table with a row like this:
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

I would like to run a query that delete all the data in my table older than 14 days.
This is my query:
DELETE FROM customers WHERE timestamp < NOW() - INTERVAL 14 DAY;

This is the error: syntax error at or near "14"
Anyone knows why this is not working and/or how could I achieve my goal??
Many thanks!!
Answer: The interval value must be quoted:
DELETE FROM customers WHERE created_at < NOW() - INTERVAL '14 DAYS';

See the doc
Comment: @LucaTomarelli: Instead of addin a "Thanks!" comment, it is custom here to upvote and/or accept an answer if it helped...
Answer: DELETE FROM customers WHERE created_at < NOW() - INTERVAL '14 DAY';

Comment: @LucaTomarelli: Instead of addin a "Thanks!" comment, it is custom here to upvote and/or accept an answer if it helped...
Answer: Another variation on the existing answers (possibly easier to remember):
DELETE FROM customers WHERE timestamp < NOW() - '14 days'::interval;


Is $\mathbb{R}$ is the union of a negligible and a meager set?

Question: A subset of $\mathbb{R}$ is said to be "negligible" iff it is of Lebesgue measure zero, and "meager" iff it is contained in a countable union of nowhere dense closed sets (i.e., closed sets with empty interior).
https://mathoverflow.net/questions/176488/can-we-define-an-empirically-generic-real-number claims to show a simple example of this, but I fail to see it in the question text. I also checked other questions here, but I didn't really see an explicit demonstration anywhere, nor a reference to one. So, how does one prove that claim?
Comment: One easy way to break up the reals is into a set of rationals and irrationals. The rationals are a negligible set, so if (and I don't think it's possible) you can show that the irrationals are a meager set you are done.
Comment: The example given in the question partitions the reals into the set of oft-repeater in base $b$, which is negligible, and the complement of that set, which is meagre. (I've not actually checked the assertions; I'm just pointing out that the question does offer an example.)
Comment: @bof that was my point
Answer: Pick an enumeration of the rationals, say, $\mathbb Q=\{q_n:n\in\mathbb N\}$. Take $A_k=\bigcup_n (-\frac{1}{2^{n+k}}+q_n,q_n+\frac{1}{2^{n+k}})$. Now, consider $X=\bigcap_k A_k$, $X$ has measure zero because the measure of $\mu(A_k)\leq \frac{1}{2^k}$ and $X^c$ is meagre because is a countable union of closed nowhere dense sets (since each $A_k$ is dense open).
Comment: This actually clarified my brainfart after some thinking about it. Thanks!


Horizontal Tabs rendered as rendering collapsible fields

Question: Although I have set up the a Content Type's display to use Horizontal Tabs

It's rendering as collapsible fields:

Does anyone have ideas on how to correct this?
Answer: In commons_origins theme's template.php file, fieldset default functions are overridden("function commons_origins_fieldset"), pls comment or remove it to have display as tabs. Or clone this theme as custom theme in sites/all/themes folder and create as new theme by removing this function.


Proving that if $f(x) \le g(x)$ then $f(x_0) \le g(x_0)$

Question: Suppose $f: D \to \mathbb R$ and $g:D \to \mathbb R$, $x_0$ is an accumulation point of $D$, and $f$ and $g$ have limits at $x_0$. If $f(x) \le g(x)$ for all $x \in D$, then
$\lim \limits_{x \to x_0}f(x) \le \lim \limits_{x \to x_0}g(x)$
Assume that $\forall x \in D$,   $f(x)$ and $g(x)$ both have limits at some point $x_0$ and $f(x) \le g(x)$
We know that $\lim \limits_{x \to x_0}f(x) = f(x_0)$ and $\lim \limits_{x \to x_0}g(x)=g(x_0)$
$\therefore f(x_0) \le g(x_0)$ because $f(x) \le g(x) $  $\forall x \in D$
Comment: But I feel like you used the statement you are trying to prove in your proof.  You have to prove if $f(x) \leq g(x)$ for all $x$, then $f(x_{0}) \leq g(x_{0})$.  But in your last line you said "well, $f(x_{0}) \leq g(x_{0})$ **because** $f(x) \leq g(x)$ for all $x$".  In other words, you used something you weren't allowed to use in your proof.
Comment: This is just what french people calls "Principe de prolongement des inégalités" where $\mathbb R$ can be replaced by a complet metric space.
Answer: The two answers already posted do provide enough detail as to how a correct proof would go. I am puzzled why a bounty is put on this question, asking for more detail. I will try to provide more comments related to proposed proof by OP.
First off, the question does not ask about $f(x_0)$ and $g(x_0)$, it is not assumed that $f(x_0)$ and $g(x_0)$ are defined. In other words, it is not assumed that $x_0\in D$. If $x_0$ were a member of $D$, then there is nothing to prove since it is given that $f(x) \le g(x)$ for all $x\in D$, hence in particular for $x_0$. But as we are not given that $x_0$ is in $D$ we should be prepared for the worse, and should not assume that $x_0\in D$.
Therefore any reference to $f(x_0)$ and $g(x_0)$ is meaningless.
Example to illustrate the above comments, as well as the statement of the problem. Let $p(x)=\dfrac{x^2+x-2}{x-1}$ and $q(x)=\dfrac{x^2+2x-3}{x-1}$.
The domain of $p$ and $q$ is $(-\infty,1)\cup(1,\infty)$. We have $p(x)<q(x)$ for all $x$ in $(-\infty,1)\cup(1,\infty)$ since $q(x)-p(x)=\dfrac{x^2+2x-3-(x^2+x-2)}{x-1}=\dfrac{x-1}{x-1}=1>0$. Here $x_0=1$ and $p(x_0)$ and $q(x_0)$, that is, $p(1)$ and $q(1)$ are undefined. But we could  find the limits, $\lim\limits_{x\to1}p(x)=\lim\limits_{x\to1}\dfrac{x^2+x-2}{x-1}=\lim\limits_{x\to1}\dfrac{(x+2)(x-1)}{x-1}=\lim\limits_{x\to1}(x+2)=1+2=3$, and
$\lim\limits_{x\to1}q(x)=\lim\limits_{x\to1}\dfrac{x^2+2x-3}{x-1}=\lim\limits_{x\to1}\dfrac{(x+3)(x-1)}{x-1}=\lim\limits_{x\to1}(x+3)=1+3=4$.
So indeed $\lim\limits_{x\to1}p(x)\le\lim\limits_{x\to1}q(x)$, as $3\le4$.
Concerning the statement by OP that: "We know $\lim \limits_{x \to x_0}f(x) = f(x_0)$ and $\lim \limits_{x \to x_0}g(x) = g(x_0)$", well we do not know that since we were not given that $f$ and $g$ are continuous functions. Even when $x_0\in D$ it may happen that $\lim \limits_{x \to x_0}f(x)\not = f(x_0)$ and or that $\lim \limits_{x \to x_0}g(x) \not= g(x_0)$. But as already discussed, the case when $x_0\in D$ is trivial, since then we may simply use that $f(x)\le g(x)$ is given for all $x\in D$.
The above was only an example to help illustrate the statement of the problem, and to make it easier to motivate and appreciate the correct proof.
It should be emphasized in any proof of the above problem, when considering the limits, that $x$ approaches $x_0$ but $x$ remains different of $x_0$ (whether or not $x_0$ belongs to $D$). To make this answer self-contained, here is a proof (which I tried to make look different than the two proofs already posted, to avoid repetition). Let
$\lim \limits_{x \to x_0}f(x)=L$ and $\lim \limits_{x \to x_0}g(x)=M$.
We need to prove that $L\le M$. It is enough to prove that for every $\varepsilon>0$ we have $L<M+\varepsilon$ (once this is done we may let $\varepsilon\to0$ to conclude $L\le M$). So fix $\varepsilon>0$. Then there is $\delta_1>0$ such that $L-\dfrac\varepsilon2<f(x)<L+\dfrac\varepsilon2$ whenever $x\in(x_0-\delta_1,x_0+\delta_1)$ with $x\not=x_0$. Similarly there is $\delta_2>0$ such that $M-\dfrac\varepsilon2<g(x)<M+\dfrac\varepsilon2$ whenever $x\in(x_0-\delta_2,x_0+\delta_2)$ with $x\not=x_0$. Let $\delta=\min\{\delta_1,\delta_2\}$ and using that $x_0$ is an accumulation point of $D$ pick $y\in D\cap(x_0-\delta,x_0+\delta)$ with $y\not=x_0$ (it is important that such a point $y\in D$ exists so we could compare $f(y)$ and $g(y)$). Then $L-\dfrac\varepsilon2<f(y)\le g(y)<M+\dfrac\varepsilon2$ hence $L<M+\varepsilon$ which completes the proof.
Comment: You should consider revise your last paragraph; it is incorrect now. Note that the space for answering is not a space for commenting others' answers. If you think you are correct, just say so in your own space.
Comment: I revised it, please let me know if you have any objections of the current version. Thank you
Answer: The argument seems not substantial; I mean it looks to me like a restatement of what is to be proved.
We may argue by contradiction. Let $p:= \lim_{x \to x_{0}}f(x)$; let $q := \lim_{x \to x_{0}}g(x)$; let $p > q$. Then there is some $\delta > 0$ such that $0 < |x-x_{0}| < \delta$ implies
$$
|f(x) - p|, |g(x) - q| < \frac{p-q}{3};$$
but this implies that for $0 < |x-x_{0}| < \delta$ we have $f(x) > g(x)$, a contradiction.
Answer: Try this :
Put $h(x)=g(x)-f(x)$; It remains to show that

If $h(x)\geq 0 \forall x $ then $\lim_{x\to x_0} h(x)\geq  0$

Proof: Suppose $\lim_{x\to x_0} h(x)=l$.Let $l<0$ then corresponding to $\epsilon=\dfrac{-l}{2}>0 \exists \delta >0 $  such that  $0<|x-x_0|<\delta \implies |h(x)-l|<\epsilon \implies \dfrac{3l}{2}<h(x)<\dfrac{l}{2}$
Since $l<0\implies h(x)<0 \forall x\in (x_0-\delta,x_0+\delta)\setminus \{x_0\}$ contradiction to $h(x)\geq 0 \forall x$
Comment: The last line is formally incorrect, as $h(x)$ need not be defined at $x_0$. It is important to not assume that $x_0\in D$.
Answer: I am posting this just to add some diversity to the approaches taken to solve this problem.
Recall that if the limit of a function exists, it is equal to the limit inferior and limit superior defined as follows :
$$
\liminf_{x \to x_0} f(x) = \lim_{\delta \to 0} \left( \inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \right)
\limsup_{x \to x_0} f(x) = \lim_{\delta \to 0} \left( \sup_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \right).
$$
The function
$$
\inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x)
$$
is monotone decreasing as a function of $\delta$, since if $\delta$ becomes smaller, the set over which we take the infimum contains less elements, thus the infimum can only grow, not decrease. Similarly, the function
$$
\sup_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x)
$$
is a monotone increasing function of $\delta$. (Note that the fact that the infimum is monotone decreasing means that when $\delta$ becomes smaller, the infimum increases (and not decreases as the name "monotone decreasing" suggests) since we are thinking in the other direction). Assuming that the limit exists, both the infimum and supremum and continuous functions of $\delta$ at $\delta = 0$ and the limit of the infimum/supremum equals the limit of $f$ as $x \to x_0$. Also note that since both functions are monotone, we have
$$
\lim_{\delta \to 0} \left( \inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \right) = \sup_{\delta \to 0} \left( \inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \right), \qquad \lim_{\delta \to 0} \left( \sup_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \right) = \inf_{\delta \to 0} \left( \sup_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \right)
$$
Now that I have introduced the infimum and supremum, let's try to solve the exercise. The assumption $f(x) \le g(x)$ implies that for every $\delta > 0$ small enough so that this infimum is not $-\infty$,
$$
 \inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \le \inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } g(x)
$$
hence taking the supremum over all $\delta > 0$, we get
$$
\lim_{x \to x_0} f(x) = \sup_{\delta \to 0} \left( \inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } f(x) \right) \le \sup_{\delta \to 0} \left( \inf_{x \in ]x_0-\delta,x_0+\delta[ \backslash \{x_0\} } g(x) \right) = \lim_{x \to x_0} g(x).
$$
Since the limit exists, we could have done the reasoning symmetrically using the limit superior instead. As you can see, the tools used are maybe a bit more advanced but the fact becomes much more trivial (which is why we create advanced tools in the first place!).
Hope that helps,


What is the name for this probablity law: $P(A\mid B)=1-P(A'\mid B)$?

Question: What is the name for this probability law:
$$P(A\mid B)=1-P(A'\mid B).$$
Answer: It is called the Complement Rule.
(taken from comment by Decaf-Math)


Get the css properties using jquery

Question: I use
$('#mybutton').css('padding-top')

its work perfectly in firefox but its not work in chrome. Help me to write generalized way to get css property values in all the browsers
Thanks in advance
Comment: It is working fine even chrome also. I have tested it. And if you want width then you can use .width()
Answer: In general, to read css property you can follow the same way as you stated in Question i.e.
$('#mybutton').css('padding-top');

To read width or height, jQuery provided functions like .width() or .height().
NOTE - don't forget to put $ at the start of statement
$('#mybutton').width();

EDIT as suggested by @ RokoC.Buljan, put your jquery script inside document.ready or $(function(){..}); to ensure that DOM is ready, see below examples
$(document).ready(function(){
    $('#mybutton').width();
    $('#mybutton').css('padding-top');
});

OR
$(function(){
    $('#mybutton').width();
   $('#mybutton').css('padding-top');
});

DEMO Link
Comment: Thank you but in this same way can i take padding properties.
Comment: General way of reading css property is same as you posted i.e. `$('#mybutton').css('padding-top');`. Can you please share jsfiddle link with your problem statement? I shall look into it.
Comment: Try to put `$('#mybutton').css('padding-top');` in `$(function(){});` as suggested in answer. working link http://jsfiddle.net/r2eqeL2a/7/
Comment: This is the link of jsfiddle http://jsfiddle.net/VenkatesanNarayanan/bcwc49de/5/ thanks in advance
Comment: it is showing `undefined` on both chrome and firefox.
Comment: You have to give some value for `padding-top` then it will give you an alert
Comment: After giving padding also its not comming http://jsfiddle.net/VenkatesanNarayanan/bcwc49de/12/
Comment: you are trying to find `#btn` inside `$controls`, but here `$controls` itself is `div` with `id=btn`, use this link http://jsfiddle.net/bcwc49de/13/
Comment: Thank you it works. if i want to take that button css property how i can take for eg:-http://jsfiddle.net/VenkatesanNarayanan/bcwc49de/14/
Comment: Could you please upvote and accept this answer if you are satisfied with the solution
Comment: sorry I don't have sufficient reputation to vote up this answer.But i really satisfied with your answers thank you very much
Answer: Make sure DOM is ready before targeting your elements:
$(function(){ // DOM is now ready

   var val = $('#myButton').css('desired-property');
   console.log( val );

});

Answer: It is working fine even in chrome also. I have tested it. Please check your selector may be you are making mistake there.

Get the css properties using jquery


Bounding the symmetric difference of a Borel set with a finite union of intervals

Question:
For $A \subset \mathbb{R}$ a bounded Borel set. Show that for all $\epsilon > 0$  there exists a set $U$ which is a finite union of intervals such that $\lambda_1(A \triangle U)\leq \epsilon$ With $\triangle$ being the symmetric difference of $A$ and $U$

I'm currently in a measure theory class and I have this question and I just don't know where to start. I have a feeling I may need to use the definition of an outer measure, as well as the fact that the complement of an interval in the semi-algebra of intervals in $\mathbb{R}$ is a finite union of intervals, but I'm not sure. I'm really struggling in this module in knowing how to approach questions so if anyone had any advice I'd really appreciate that.
Edit: $\lambda_1$ is the Lebesgue measure on $\mathbb{R}$
So for an interval $(a,b]$ we have that $\lambda_1((a,b])=b-a$
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Do you recall how $\lambda_1$ is defined?
Comment: I've added that since I didn't define it, I've just looked again at my notes. It's the unique measure that agrees with the length function on $\mathbb{R}$, from the Carathéodory Extension Theorem? I still don't really see a way forward.
Answer: Hints: (1) Use outer measure to approximate $A$, to within measure $\varepsilon/2$, by an open superset. (2) Recall that an open subset of $\mathbb R$ is the union of countably many disjoint intervals. The measure of the open set is the sum of the measures of those intervals. (3) Approximate that infinite sum, to within measure $\varepsilon/2$, by a finite partial sum.
Comment: Ah right thank you, that gives me $\lambda_1(A) = \sum_{n=1}^{k} \lambda_1(I_n) + \epsilon $ is that right?


Failed to use mongrel on Windows server with Rails 3 and Ruby 2.1

Question: I'm trying to install redmine on a windows 2008 server.
It works with webrick.
Now I'm trying to put it in production with mongrel.
But when I start mongrel I have the following error:

E:/Ruby/Ruby21/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- 2.1/http11 (LoadError)
  from E:/Ruby/Ruby21/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:inrequire'
  from E:/Ruby/Ruby21/lib/ruby/gems/2.1.0/gems/mongrel-1.2.0.pre2-x86-mingw32/lib/mongrel.rb:17:in rescue in \<top (required)>'
  from E:/Ruby/Ruby21/lib/ruby/gems/2.1.0/gems/mongrel-1.2.0.pre2-x86-mingw32/lib/mongrel.rb:13:in\'
  from E:/Ruby/Ruby21/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in require'
  from E:/Ruby/Ruby21/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:inrequire'
  from E:/Ruby/Ruby21/lib/ruby/gems/2.1.0/gems/mongrel-1.2.0.pre2-x86-mingw32/bin/mongrel_rails:13:in \<top (required)>'
  from E:/Ruby/Ruby21/bin/mongrel_rails:23:inload'
  from E:/Ruby/Ruby21/bin/mongrel_rails:23:in `'

I don't really know Ruby and can't figure out what the error means.
Thanks for your help
Answer: I'm not familiar with redmine, but I think problem is that you want to run Mongrel server, which is very old, and maybe not compatible with ruby2 (which you use). You can try add to Gemfile.local gem 'thin', for example, and make bundle install. I hope this manual will help you.
Comment: Thanks for your idea. Unfortunately I have the same kind of issue with thin, failing to load eventmachine. But the two errors have something in common, the failing gems are postfixed with -x86-mingw32. CAn it be the source of the issues ?
Comment: After a lot of tries I have a better understanding of the way things work. Obviously gems postfixed with -x86-mingw32 contains libs in .so format and different versions of the .so files are provided for different versions of Ruby. mongrel only comes with libraries for ruby 1.8 and 1.9. Eventmachine is available for ruby 1.8, 1.9 and 2.0. But thanks to this blog [link](http://blog.cloud-mes.com/2014/10/06/compile-eventmachine-1-dot-0-3-in-ruby-2-dot-1-3-on-windows/) I was able to compile for ruby 2.1. Thanks for your help.


Images loading fine on day 1, broken on day 2

Question: Strange problem.
Images on my production site are 100% working at one point (right after getting a refresh from staging), and within a day or two, some images on some pages become broken links.
(Production is updated from staging through mysql database dump/restore).
As I continue to watch this over the course of subsequent days, more pages in production experience this symptom, but the images are always there in staging - never broken.
Here's some data...
When viewing the content of a page in the staging environment, an inserted image looks like this (Admin UI - view Source).
...installed one of the Outlook toolbars.

[[{\"type\":\"media\",\"view_mode\":\"media_large\",\"fid\":\"123\",\"attributes\":
{\"alt\":\"\",\"class\":\"media-image image-style-large image-style-large image-style-large\",
\"height\":\"298\",\"typeof\":\"foaf:Image\",\"width\":\"264\"}}]]

Who can ...

When the Staging content is pushed to Production, viewing the same page in the Admin UI on the production server, the content starts out exactly the same and the image renders fine.
Within a day or two, the Production page changes (presumably by something Drupal Cron is doing) to something like this:
...installed one of the Outlook toolbars.

Who can ...

The "img src" version that creeps in is a bad URL -
http://default/sites/default/....

I've grep'ed my daily mysqldumps for this bad URL string, and each day there are a different number that creep in.
    for file in /data/mysqldumps/*sql
    do
      echo -n $file
      echo -n ": "
      grep -o "http://default" $file | wc -l
    done

/data/mysqldumps/20121205-160101.sql: 0 (Zero occurrences on Dec 5 because I pushed
                                         on that date, & all images were known good)
/data/mysqldumps/20121206-160101.sql: 106
/data/mysqldumps/20121207-160102.sql: 130
/data/mysqldumps/20121208-000101.sql: 138
/data/mysqldumps/20121209-000101.sql: 157
/data/mysqldumps/20121210-000101.sql: 158

No local Admin changes have occurred on production, and nothing but cron is running there.
What can be causing this? It's only happening in production (which is totally awesome).
Any suggestions on troubleshooting?
Thanks,
Mark
Comment: Do you have $base_url defined in settings.php?
Comment: In researching further, the entries in the database only appear in these tables:

         cache_field,
         cache_metatag,
         cache_form,
         watchdog.

I've updated base_url, and I'm keeping an eye on it to see if it recurs after that change.
Comment: I suspect you have something weird going on with fetching pages from localhost.  If this appears to do the trick, I will write up what I suspect is happening.
Comment: The addition of the configuration parameter "$base_url" set to the real name of the site in settings.php has solved this problem.  What I still do not understand (from the original problem) is how editing a page in the Admin UI on the production server would show me page content (source) from Cache tables rather than from DB tables where the true "origin" content is.  Is that how the editor is really designed?
Answer: There is a related issue for this here. http://drupal.org/node/1352182.
What's happening is that drupal is storing the URL that is created when the page is first viewed after the cache is cleared. Normally that would be your site url, but sometimes it's not.
In the issue linked you see that some people fixed this using the Pathologic module.


Enviar arquivos para o MySQL no Blob

Question: bom dia.
Alguém sabe como posso enviar arquivos exe e csv para o MySQL usando o Delphi?
Não achei muito conteúdo sobre isso. Preciso guardar arquivos CSV na tabela mas quando faço a importação pelo teste abaixo o tamanho do arquivo é muito menor que o original.
imgfoto.Picture.LoadFromFile('C:\1\1.jpeg');

imagem := Tmemorystream.Create;

imgfoto.Picture.Graphic.SaveToStream(imagem);

FDQuery1.Open;

FDQuery1.First;

if FDQuery1.Locate('LJ_NOME', 'AAAAAAAA', []) then

begin

FDQuery1.Edit;

TBlobField(FDQuery1.FieldByName('LJ_BLOB')).LoadFromStream(imagem);

end;

Eu tentei converter o CSV e o EXE para JPEG e enviar via stream, ele não reconhece por não ser imagem. Testei via memo, mas ele carrega a primeira linha apenas.
Como faço para enviar os arquivos para o MySQL?
Answer: Utilize "LoadFromFile" do campo. Abaixo um exemplo da forma que utilizada.
Considerando a seguinte tabela:
CREATE TABLE `arquivos` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `arquivo` BLOB NULL DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8_bin'
ENGINE=InnoDB;

Eu fiz da seguinte forma:
FDQuery1.Insert;
FDQuery1arquivo.LoadFromFile('<Caminho para o arquivo>');
FDQuery1.Post;

Código de exemplo

Enviar arquivos para o MySQL no Blob


Can I use Plain PHP functions in tpl file?

Question: I have a tpl.php page for login form in my drupal site in which have 4 images.
I need to display only one of these 4 images randomly on each page load.
I can easily do this in less than 10 lines of code using the php rand() function.
But is it advisable to directly use such functions in tpl files.
Could this have some sort of security risk?
UPDATE:
The 4 images that I talked about. I have just uploaded them to sites/default/files/images folder and have included them in tpl file using following code:

I have a feeling that this is unsafe too. Please advise.
Comment: Security risk, not so much. But you will have problems with caching. Templates should be used for display only; all business logic should go elsewhere, namely in a template preprocess function
Comment: If someone has told you that showing the full path to an image located on a website is a security risk - stop listening to them :) Then get them to [read this](http://drupal.stackexchange.com/questions/237/how-can-i-obscure-the-fact-my-site-uses-drupal)
Comment: @Clive: Thanks. Also, Please see the updated question.
Comment: Your update falls under "not best practice", but why do you consider it to be unsafe? What attack vector do you feel you're introducing, or opening up?
Comment: I have read that when uploading a file file_save_upload may be used which gives the file a temporary status and these files are periodically cleaned. If I directly upload a file, could there be a similar issue?
Comment: No, Drupal only purges _managed_ files that have a temp status in the file_managed table. It won't touch anything you've uploaded manually
Comment: Also, a file uploaded from inside of drupal has URL like: `http://mysite.com/sites/default/files//styles/medium/public/image.gif?itok=_Hyz0SVE` but in my case my file has URL: `http://mysite.com/sites/default/files/images/image.jpg` which shows the complete directory structure
Comment: I'd rather display all the images in the template, then use javascript and css to do the random showing/hiding. You will get a page that can be cached by Drupal.
Answer: For the first part of question:
You may output as form item the output of your custom function, where contain logic to get random image:
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['img_item'] = array(
          '#type' => 'markup',
          '#markup' => my_random_image_output(),
          '#weight' => -50
        );
    }
}

function my_random_image_output() {
    $output = '';

    // your custom logic to output one image $output = ''

    return $output;
}


How to automate the Updating/Editing of Amazon Data Pipeline

Question: I want to use AWS Data Pipeline service and have created some using the manual JSON based mechanism which uses the AWS CLI to create, put and activate the pipeline.
My question is that how can I automate the editing or updating of the pipeline if something changes in the pipeline definition? Things that I can imagine changing could be schedule time, addition or removal of Activities or Preconditions, references to DataNodes, resources definition etc.
Once the pipeline is created, we cannot edit quite a few things as mentioned here in the official doc: http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-manage-pipeline-modify-console.html#dp-edit-pipeline-limits
This makes me believe that if I want to automate the updating of pipeline then I would have to delete and re-create/activate a new pipeline? If yes, then the next question is that how can I create a automated process which identifies the previous version's ID, deletes it and creates a new one? Essentially trying to build a release management flow for this where the configuration JSON file is released and deployed automatically.
Most commands like activate, delete, list-runs, put-pipeline-definition etc. take the pipeline-id which is not known until a new pipeline created. I am unable to find anything which remains constant across updates or recreation (the unique-id and name parameters of the createpipeline command are consistent but then I can't use them for the above mentioned tasks (I need pipeline-id for that.
Of course I can try writing shell scripts which grep and search the output and try to create a script but is there any other better way? Some other info that I am missing?
Thanks a lot.
Answer: You cannot edit schedules completely or change references so creating/deleting pipelines seems to be the best way for your scenario.
You'll need the pipeline-id to delete a pipeline. Is it not possible to keep a record of that somewhere? You can have a file with the last used id stored locally or in S3 for instance.
Some other ways I can think of are:

If you have only 1 pipeline in the account you can list-pipelines and
use the only result
If you have the pipeline name you can list-pipelines and find the id
Comment: Thanks. In face of no other way to this, option# 2 is what I am gearing towards as well. Though it does involved parsing output of a shell command which I was trying to avoid.
Comment: FWIW,  I also found this Pipewelder [link](http://pipewelder.readthedocs.org/en/latest/README.html#overview) which helps in at least automating the process.


Nonzero class in integral homology implies orientability

Question: Let $M^3$ be a compact, connected and oriented $3$-manifold with nonempty boundary and let $\Sigma^2$ be a compact and embedded surface such that $\Sigma \cap \partial M = \partial \Sigma$. If $\Sigma$ determines a nonzero class in $H_2(M, \partial M;\mathbb{Z})$, does it follow that $\Sigma$ is orientable?
Answer: Let me see if you agree with this answer. Let $\phi : (\Sigma, \partial \Sigma) \to (M, \partial M)$ be the embedding of $\Sigma$ into $M$. This induces a map $$\phi_* : H_2(\Sigma, \partial \Sigma; \mathbb{Z}) \to H_2(M, \partial M; \mathbb{Z})$$
in homology. Since $\Sigma$ determines a nonzero class in $H_2(M, \partial M; \mathbb{Z})$, this implies that there exists a nonzero class $\alpha \in H_2(\Sigma, \partial \Sigma; \mathbb{Z})$ such that $\phi_*(\alpha) \neq 0$. In particular, $H_2(\Sigma, \partial \Sigma; \mathbb{Z}) \neq 0$, which means precisely that $\Sigma$ is orientable.


Allow users to choose which layout to be applied

Question: Is there any way to allow users to choose which layout to be applied (Omit the given media queries) for the Omega theme?
For example, ESPN has a switcher for choosing the layout: When browsing in iPad, it has a link to switch to desktop.

Do you have any idea on how achieving such functionality with the Omega theme?
Answer: Responsive designs usually rely on media queries to apply the styles, but you could make a copy of those styles and prefix its selectors with body.desktop. Then, when you want iPad users to see different styles, just add the class to the body element (using jQuery). CSS preprocessors like SASS will help you mantain those styles without duplicating the code — Zen 7.x-5.x has awesome out-of-the-box support to SASS/Compass and responsive designs. See the Sassy module as well.
There is also the adaptive design approach: it relies on browser sniffing to return device-specific markup and styles. The mobile tools module will surely help should you choose this approach.
Comment: Thanks for the answer. But i think it does not address problem to my question. We are using Omega theme which already comes with media quieries and different stylesheets for each layout. The question is more on how to allow user MANUALLY switch stylesheet.
Comment: That's what I'm suggesting: put a widget that adds a class to the layout, use that class to trigger a layout change in CSS. You can't trigger media queries directly (afaik).


What does Atletico Madrid do tactically different since Diego Simeone took over?

Question: Atletico Madrid has beaten Barcelona 2-0 recently in the Champions League and they have always posed a serious threat. Other teams have floundered against Barcelona. Apart from utilising Antoine Griezmann's skills, what has Simeone done tactically since his arrival?
Comment: As there were some close votes, I've edited the question so that is can attract factual, not opinionated, answers.
Answer: Some of them are, all players are committed in defensive duties. Even players with offensive roles they try to recover balls. High pressure over the oponent. They practice a lot for corners and free shots and they have much better results on that now than before. They practice more and they are more prepared and are more effective at counterattacking
Comment: Could you provide some references for this answer?
Comment: you arent going to find much sources in english. Besides I am a native spanish speaking person. Here there is one in spanish http://tn.com.ar/deportes/esencial/antifutbol-no-es-pecado-jugar-con-el-estilo-del-cholo-simeone_671733 "I want an agressive, seasoned, strong, counterattacking team" one of his definitions
Comment: BTW; most of what I've written comes from spanish speaking ESPN commentators and people from other sport tv networks. I can't really give links for that :)
Comment: @Pablo you could still mention that in your answer, so people know where you got the info. :)
Answer: More than committed in defensive duties I'd say that most of the players are committed to their manager because they trust Simeone and all of them have given 200% of their potential.
Players like Griezmann didn't want to quit because they have learned a lot and improved their skills with Simeone.
Apart from Wenger, Simeone is the European trainer with more seasons in the same club in a row.
Answer: I don't know but I've heard someone say that there were 6 defenders in the match. SIX. And Barca's formation was 4-3-3 so 2 defenders can mark one attacker.
And since Griezmann is fast he can bypass the defense of Barca.
Oh, and It was the first match that messi haven't made a shot to the goal since 2011 : 0
Comment: I would like to play against teams who put 6 defenders on three attackers. My midfielders and full backs could have the time of their live
Comment: I've searched for formations and lineups of the match from the internet and found out that the 6-3-1 was just fake-talk, nothing much. They were in 4-1-4-1 formation.


Analysis limit proof

Question: The function
$\displaystyle f(x) = \frac{x^3-8}{x^2-4}$
is defined at every point of the interval $(0,\infty)$ except for the point 2. By applying the the fact that if I is an interval and c is a point of I, where f1 is a function defined and continuous on I, and f2 is defined everywhere on I except possibly c. Let $f1(x) = f2(x)$ for $x$ not equal to $c$, then the limit of f2 as x approaches c exists and equals f2(c). Prove that the limit as x approaches 2 f(x) exists, and find its value.
Will need this result:
if g is a function that is defined and continuous on an interval I and never takes the value 0 and f is another function that is defined and continuous on I, then f/g is continuous
(You may NOT use l'H^opital's Rule
since we have not proved it or even defined derivatives yet. Furthermore, such
an approach would be circular since the calculation involved in this problem is
similar to the ones that will be needed to justify derivative calculations later in
the course.)
Im not sure where to start on this problem, guidance would be appreciated.
Comment: Welcome to MSE! It really helps readability if you format your questions using [*MathJax*](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). I started it off for you. Regards
Comment: Guidance? Read your lecture notes.

(This site is not populated by homework gnomes that live to do people's homework for them!)
Comment: Nowhere did I ask for anyone to do my homework for me, I just asked for a tip to help me begin working on it.
Answer: Hint: Note that $$x^3-8=(x-2)(x^2+2x+4)$$ and $$x^2-4=(x-2)(x+2).$$ This should let you use the given fact.

Analysis limit proof


Is there is a way that I can download only a part of the dataset from huggingface?

Question: I'm trying to load (peoples speech) dataset, but it's way too big, is there's a way to download only a part of it?
from datasets import load_dataset

from datasets import load_dataset

train = load_dataset("MLCommons/peoples_speech", "clean",split="train[:10%]")
test = load_dataset("MLCommons/peoples_speech", "clean",split="test[:10%]")

Using ("train [: 10%]") didn't help, it still trying to download the entire dataset...
Answer: Did you consider using the stream feature in Datasets?
It allows you to stream data from HuggingFace's Hub without having to download the dataset locally.
from datasets import load_dataset
from torch.utils.data import DataLoader
# you get a dict of {"split": IterableDataset}
dataset = load_dataset("MLCommons/peoples_speech", "clean", streaming=True)
# your preprocessing and filtering
...
train_dataloader = DataLoader(dataset["train"], batch_size=4)
valid_dataloader = DataLoader(dataset["validation"], batch_size=4)
train_steps_per_epoch = 500
# training loop
for n in range(5):
    for i, batch in enumerate(train_dataloader):
        # if you only want to do a limited amount of optimization steps per epoch
        if i == train_steps_per_epoch:
            break
        # train step
        ...

I hope it helps.


Convert Null value retrieving from database into decimal data type

Question: Please check the Table below:

Scope is: I have to check in the database the top profileid and have to increase it by 1. If no data is there then it will fetch 0 and will increase it by 1.
I am getting the top value when there is data but in case the table is completely empty, I am getting exception. Code is as below.
        public Decimal GetTopProfileID()
        {
            Decimal topID = 0;
            var profileID = _dbContext.tblProfile.Max(n => n.profileid);
            try
            {
                if (profileID == null)
                {
                    topID = 1;
                }
                else
                {
                    topID = Convert.ToDecimal(profileID);
                    topID++;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return topID;
        }

Please help me find the solution. Ready for any question.
Thanks in advance !!
Comment: `.Max()` will throw an exception if there are no items in the collection.
Comment: First, get rid of the try/catch block - it's not doing you any good, but cluttering up your code. Secondly, what exception are you getting, and where? Please provide a stack trace.
Comment: check out TryParse method instead
Comment: What is the reason for this. I hope you not trying to set the ID when trying to insert a new record.
Answer:
When there's no record in the table and you try to get .Max() value,
  then it will throw an error, so its better to verify if any record
  exist or not.

Update your code as follows.
if (_dbContext.tblProfile.Any()) {
    //Verify records in tblProfile table, if there's any record exist or not

    return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
    try {
        if (profileID == null) {
            topID = 1;
        } else {
            topID = Convert.ToDecimal(profileID);
            topID++;
        }
    } catch (Exception) {
        throw;
    }

    return topID;
} else { //If there's no value in table then assuming it should return 1.
    return 1;
}

Update
Or you can make it more simpler:
if (_dbContext.tblProfile.Any()) {
        //Verify records in tblProfile table, if there's any record exist or not

        return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
    } else { //If there's no value in table then assuming it should return 1.
        return 1;
    }

Answer: You can use this code:
if (_dbContext.tblProfile.Any())
{
   //Verify records in tblProfile table, if there's any record exist or not
   var profileID = _dbContext.tblProfile.Max(n = > n.profileid) ?? 0;

   return profileID + 1;
}
else
  return 1;

Also if ProfileID is not nullable then don't need care about null value.
Then you can use below code:
return _dbContext.tblProfile.Any() ? _dbContext.tblProfile.Max(n = > n.profileid) + 1 : 1;

Comment: Max method can not return null as profileid is primary key. so you can eliminate it.
Comment: depends on type of profileId, if its nullable then can return null as well. So if it;s primary key so don't need to check with null at all
Answer:           var profileID = _dbContext.tblProfile.OrderByDescending(n => n.profileid).FirstOrDefault();
  Decimal topID = 1;
                            if (profileID != null)
                            {
                             decimal.TryParse(profileID.ProfileId, out topID);
                             topID++;
                            }

                        return topID;
            }

Above answer by Moksh Shah is correct, but in that case we are hitting Data Base twice,
I think this should produce the desired result.
Comment: Thanks for the correction. I will modify the solution.
Comment: You need to update slightly, `.FirstOrDefault();` will return object of `.tblProfile` not the `profileId`.
Answer: Use LastOrDefault() like this:
decimal variableName = Convert.ToDecimal(_dbContext.tblProfile.Select(x=> x.ProfileId).LastOrDefault() + 1);

Should work.
This is better than other solution as there is only one database call.


Adding quantity to a Commerce product's attribute

Question: I have a D7 Commerce Store. It will be selling to wholesales.
I have a Product that has multiple attributes. An example of the attributes is as follows;
T-Shirt Printing (Product)

Size (S, M, L, XL, etc)
Sides (1 Side, 2 Side)
Service Type (All over, Spot)

How can I allow the customer to add that 1 product with multiple of a particular attribute?
Example; Customer should be able to order, 10 Small, 15 Medium, 20 Large of that one product "Tshirt Printing".
The Image below is an example from jakprints.com. I would like to do something similar. How can I replicate this in commerce? Or instead of using sliders... + or - buttons.
Please provide a few different ideas or POV's towards achieving this.
Answer: Use the Commerce Add to Cart Extras module. It provides a new product reference field display formatter that does exactly what you need.
Comment: Ahh, nope, you're right - I missed that you wanted them to be selecting other attributes before the size. Perhaps expanding on my answer, then, I'd suggest that maybe instead of using attributes for specifying sides and service type, I'd use line item fields for those instead. Since those are details pertaining to the fulfillment of the order and don't necessitate a different SKU, it would be safe to model those as line item fields so long as the pricing for those selections is standard across all products. You can use that field data in your product pricing rules as need be.
Comment: I use that module for two of my stores. It doesn't affect the actual attribute. It only allows for you to add a field via views so that you can add multiple & Quantities of those products. Unless i'm mistaken and haven't used it to its fullest potential.


Bass clarinet notation in the Rite of Spring and other pieces

Question: I am a clarinettist so I am a little embarrassed to need to ask this.  I have not played the bass clarinet.  I am looking at a miniature score of Stravinsky's The Rite of Spring (Dover Miniature Scores).
Towards the end of The Ritual Action of the Ancestors, there are two bass clarinets playing.  The second part is written in the bass clef and the first switches to the bass clef at bar 143.  I thought that the bass clarinet was a transposing instrument (down a major 9th) and would be written in the treble clef.  As a player, how would I interpret the bass clef?  Would I now consider my instrument as only transposing by a major second?
More generally, what notation is used for the bass clarinet?
Answer: In this case, your intuition is correct: when the bass clarinet is written in the bass clef, it now only transposes by a major second instead of by a major ninth.
Transposing by a major ninth (i.e., written in treble clef) is far more common so as to allow the player to use the same fingerings as they do when playing the standard clarinet. But this bass-clef notation does occasionally appear.
But buckle up.
To make matters more confusing, the transposition level isn't fully standardized when the score briefly changes to treble clef. In the German style, the treble-clef notation is still only transposed by a major second. In the Russian style, however, treble-clef notation reverts to the standard major-ninth transposition.
Confused yet? But it gets even better: some Italian scores write the bass clarinet in bass clef but continue to transpose it by a major ninth (!).
In practice, it's best to remember the four traditions of bass-clarinet notation:

The standard (French) style, always written in treble clef transposed by major ninth;
the German style, in which all is transposed by major second;
the Russian style, in which treble-clef notation transposes by major ninth but bass-clef notation transposes by major second;
and the Italian style, in which all is transposed by major ninth (treble clef and bass clef).
Comment: @badjohn That I admit I'm less clear on. It's definitely five players, but the number of instruments may change if the performers choose to transpose the parts themselves and play on only one instrument.
Comment: @badjohn Good call, I was unclear, and I've now edited it: the French style only uses the treble clef, but the Italian style uses both treble and bass.
Comment: Thanks.  This is the first time that I have noticed the bass clarinet written in the bass clef.  I would have been less puzzled if it was consistently so.  The switch for just a few bars seemed odd.
Comment: Did I interpret the instrumentation correctly?  We need 5 players and 10 instruments?
Comment: Thanks for the enhanced answer.  As you would expect, your style 3 appears to be correct for this piece.  I was listening to it while following the score.  What's the difference between 1 and 4?
Comment: Yes, I expect that some players may transpose rather than have so many instruments e.g. a clarinet in D.  I have heard of players using only a B♭ and transposing when the part requires an A.  I don't fancy transposing on sight by a semitone but I guess that I could learn it.  I am familiar with transpoing by a major 2nd, major 6th, and major 9th (I also play the sax).
Comment: @PiedPiper one of the three clarinettists also doubles bass.  Does that clarinettist not need both B-flat and A clarinets in addition to the bass clarinet?  If so, I then count 11 instruments unless the players are sharing.  Also, if the bass clarinettist needs both B-flat and A instruments when serving as Cl IV, that would be 12 instruments.
Comment: @phoog It is a little confusing, I carefully transcribed the instrumentation page but it is a little hard to interpret.  I was not following the clarinets through the entire piece but, I think that PiedPiper is right, one player is dedicated to the bass.
Comment: @phoog So, I also count 10 instruments.  P1 D & E♭.  P1 B♭ & A.  P3 B♭, A & bass.  P4 B♭ & A.  P5 bass only.  The reference to Cl. IV is a little confusing.  It seems to number the B♭ & A players as I, II, and III and the bass as IV but the "small" clarinet gets no number.  Of course, I could be wrong.
Comment: @badjohn the list given in the question clearly shows that the second of the three "normal" clarinettists (call her Carol) sometimes plays a second bass clarinet and that the bass clarinettist sometimes plays as a fourth normal clarinettist. If Cl II and IV needs both A and B-flat clarinets in addition to the bass clarinet then those two players need three instruments. It seems unlikely, but the information available on this page does not rule it out.  I'll check to see whether I have a score handy.
Comment: @badjohn If your interpretation is correct then the notation "II = B. Cl II" is inconsistent with "= Cl. IV."  In one case, the equals sign means "also sometimes plays" while in the other case it means "is labeled as."  And labelling a bass clarinet as Cl. IV would indeed be rather odd.  The inconsistency is easily eliminated by interpreting the equals sign consistently as "also sometimes plays."
Comment: @PiedPiper then what is the meaning of "= Cl. IV"?
Comment: @phoog The Cl. IV is confusing.  I'll go through the score to check what is actually used but I won't get time today or maybe a few more days.  Yesterday, I had some time alone to listen and follow the score.  That luxury won't be available again for a while.
Comment: @Richard There are really two questions here: the bass clarinet notation and the instrumentation.  I'll split the question into two: I'll trim this back to just the bass clarinet notation since Richard answers that well.  I'll start a new question for the instrumentation.


$\sum^{\frac{k}{2} - 1}_{i=0} x_{2i} = \left \lceil{\sum^{k-1}_{i=1} \frac{x_{i}}{2} }\right \rceil$ true for a sequence with the step propery?

Question: Recall a step sequence is sequence with a sudden jump in its numbers. Formally:

I was trying to understand the  proof of the following lemma:

The first statement sort of makes sense to me. If there is no time when the sequence decreases by 1, then the sum of the even sequence is equal to the sum of the odd sequence which is equal to the sum the total sequence. This seems to only work for even numbers. For example if the sequence is {1,1,1} then, the even subsequence is {1,1} and the odd is {1} (assuming zero indexing) and the total of the whole is 3. Where 3/2 is not equal to 1 (the sum of the odd and even sequence).
Even when the length of the sequence is even, I can't make sense of the last statement. The proof isn't really a proof since it doesn't explain why those summations even hold...
Answer: The lemma is false. Suppose that $k=3$ and $x_0=x_1=x_2=2$. Then
$$\sum_{i=0}^2\frac{x_i}2=\sum_{i=0}^21=3\;,$$
but the sum of the even subsequence is $2+2=4\ne\lceil 3\rceil$, and the sum of the odd subsequence is $2\ne\lfloor 3\rfloor$. There is also a minor error in the expression purporting to be the sum of the even subsequence: the upper limit of summation should be $\left\lfloor\frac{k-1}2\right\rfloor$. (The upper limit of summation for the odd subsequence really ought to be $\left\lfloor\frac{k}2\right\rfloor-1$, but this isn't critical, since it's how a sum to $\frac{k}2-1$ is generally understood when $k$ can be odd.)
What is true is that either the sums of the even and odd subsequences will be equal, in which case each will be half the sum of the whole sequence, or the sum of the even subsequence will exceed the some of the odd sequence by $x_{k-1}$ or by $x_0-x_{k-1}$.


Chi-square contrast tests with R

Question: I have Group A, B, C.
My hypotheses are"
1) proportions of C are different from proportions of A (=independance)
2) proportions of C are different from proportions of B (=independance)
3) proportions of A are NOT different from proportions of B (=NO independance)
Is there something like post-hoc contrasts for chi-squared, so I can test all my hypotheses in ONE modell and not have alpha inflation?
Intuitively I would test C against a composite of A and B but that still doesnt test if A is different/independent
There is a post on Stackoverflow regarding this topic, but there wasn't an answer.
Comment: You might be interested in these questions and related pointers: [Multiple Chi-Squared Tests](http://stats.stackexchange.com/q/1133/930), [How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?](http://stats.stackexchange.com/q/9685/930), [Has anyone used the Marascuillo procedure for comparing multiple proportions?](http://stats.stackexchange.com/q/3526/930).
Answer: The R Package 'pairwise.prop.test()' does the post-hoc job. One can also define several methods of adjusting p-value. However, this is only a post-hoc test and no planned comparisons.

Chi-square contrast tests with R


What is our stance on questions about moving to a different part of the same country (e.g., moving to another state in the USA)?

Question: What is our stance on questions about moving to a different part of the same country (e.g., moving to another state in the USA)?  Are they on-topic or off-topic?
Example 1:

I have a Massachusetts driver's license and I moved to California:
how long do I have to get a California's driving
license?
I am a French citizen. I have a Massachusetts driver's license and I
moved to California: how long do I have to get a California's driving
license?

Example 2: How to exchange out-of-state license in NY State after 30 days of residency
Answer: These are definitely off-topic, as they do not have anything to do with expatriates.
Moving from one US State to another is just moving from one part of a country to another part of the same country. The government system is the same, the facilities are (basically) the same. The answer to the question asked above is "go to the DMV and ask", as it would have been if you had moved to Connecticut or New Hampshire.
For an expatriate, it's not the distance moved that's important, it's the differences in the way government departments work, difficulties with language and culture, all the things that are different for non-citizens rather than for citizens of the host country.
Comment: In the USA, states have their own laws, agencies, etc. It's a bit different than moving from London to Bath. However, I agree that changing states doesn't make you an expatriate, if we stick to the dictionary definition.
Comment: "The answer to the question asked above is _go to the DMV and ask_" -> that's not ideal as, in addition to be time-consuming, whatever the DMV tells you, eventually you are the one responsible to abide by the laws. If the DMV tells you something that is legally incorrect, it may help you in court if you can demonstrate the DMV told you something incorrect (hard to prove), but you'll still be responsible. [When is ignorance a legal defense?](https://law.stackexchange.com/q/32/31)
Comment: The government structure is the same though. There IS a DMV to go to. If you moved to Thailand, would you know where to go? And when you got there and found that everything is written in ภาษาไทย would you know how to go about it? Whereas moving to another part of the same country - you are familiar with everything.
Comment: I agree, there are fewer differences. Let's see where the others want to cut the line. I don't have any strong preference, however I would observe that as far as I know there isn't any other Stack Exchange website to accommodate state-specific questions in many cases (though in my example I think I could ask on law.SE).
Answer: This site is mainly for people who face extra challenges living in another country because of their nationality, and the questions should tie to these extra challenges. The question as stated does not have anything in particular for this regard, e.g. a local would have the exact same problem, hence it is off-topic.
However if the question is clearly around these extra complications, then they are definitely on topic, even in the context of moving from one state to another. For example I would deem the following question on-topic:

As a French citizen I just moved from Massachusetts to California. My passport is at the consulate however. Will I be able to exchange my licence to a Californian one without my passport?

However, while as stated the original question is most likely off-topic, if the question states that the asker is not a local citizen I usually prefer waiting a bit before closing the question. This is because there might be actual complications because of someone's nationality that are not apparent at first sight, and are only visible once someone answers and/or writes a comment proving this.
Comment: I also prefer to wait a bit on marginal questions like this because they might just get a sterling answer which would still be useful to visitors even if the question has been subsequently closed.
Answer: Many a times I felt foreign in my own country (and I'm not referring to instances of "re‑entry culture shock").
Therefore I posit the role of expatriate is subjective.

Language, take Switzerland:
Four languages are spoken in Switzerland.
If you move to a different canton at the other end of the country, you can feel like an expat although technically you are not.
Prior approval necessary, take China:
Historically, you (as a Chinese citizen) needed to apply to move between parts of the country.
Today, moving to Beijing and other "popular" cities still requires paperwork.
Citizenship is a heuristic yet no guaranty that you may move freely.
Substantial difference in governance, take the USA:
The legal system of the US is a trainwreck:
Legislative power is assigned to the federal government, state, county, city, essentially without doing some thorough legal studies you're lost.
In particular traffic law is state law, so moving across state lines can introduce a certain amount of unfamiliarity.
Amount of difficulties faced, take the State of Palestine.
Oppression will make you feel foreign.

In conclusion I suggest to make an assessment on a case-by-case basis and respect the poster's gut feelings (assume good faith principle).
Furthermore, any restrictions can be circumvented by merely claiming "I'm from a different country, so I'm definitely an expat."
Any regulation is therefore futile.


Qual código uso pra criar uma classe Validacao no AndroidStudio?

Question: Estou querendo criar uma classe pra verificar se os 2 campos EditText estão preenchidos, chamado Validacao. Queria chamar tipo:
if (Validacao(TextoA, TextoB) == true) {
    executa código;

Não estou sabendo como fica o código da classe Validacao. É preciso ter um construtor Validacao()? Como ficaria o código?
import android.widget.EditText;
import android.widget.Toast;

public class Validacao {
    private boolean x = true;
    private boolean y = true;
    private boolean z = true;
    private boolean a = false;

    public Validacao(EditText textA, EditText textB) {
        // Valida para ter todos os 2 campos preenchidos
        if ((textA.getText().toString().isEmpty()) && (textB.getText().toString().isEmpty())) {
            z = false;
            Toast toast = Toast.makeText(this, "Informe os números." , Toast.LENGTH_SHORT);
            toast.show();
        } else if (textA.getText().toString().isEmpty()) {
            x = false;
            Toast toast = Toast.makeText(this, "Informe o primeiro número." , Toast.LENGTH_SHORT);
            toast.show();
        } else if (textB.getText().toString().isEmpty()) {
            y = false;
            Toast toast = Toast.makeText(this, "Informe o segundo número." , Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    if (x && y && z)
        a = true;
    return a;
}

Comment: if(NomeDaVariavel.getText().toString().equals(" ")){ Toast.makeText(MainActivity.this,"Por favor preencher o texto", Toast.LENGTH_SHORT).show(); Não sei se essa era a dúvida, mas pra fazer a validação se o texto não está nulo é assim.
Answer: Quando definido uma função com o mesmo nome da classe, essa função será a função construtora dessa classe, e deve ser invocada através do operador new
Como você está criando uma classe de validação, sugiro que use funções estáticas e a lógica de verificar quantas variáveis são válidas seja feita aonde esses métodos sejam chamados
Por exemplo:
public class Validacao {
    public Validacao() {  }

    public static boolean isValid(EditText et, String msg, Context context) {
        if (et.getText().toString().isEmpty()) {
            Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
            toast.show();

            return false;
        } else {
            return true;
        }
    }
}

Para usar:
if (Validacao.isValid(x, "Informe o primeiro número", getApplicationContext()) && Validacao.isValid(y, , "Informe o segundo número", getApplicationContext()) && Validacao.isValid(z, "Informe o terceiro número", getApplicationContext())) {
    // Faz alguma coisa
}

Você também pode criar uma função personalizada pra cada variável
Comment: Não tá dando certo. Seria public static **boolean** isValid(EditText et, String msg) { ... }? Mesmo assim, dá erro na classe Validacao, isso no AndroidStudio.
Comment: Sim, faltou definir o tipo, faz um tempo que não mecho com java, esqueci de colocar, qual o erro que aparece? Acredito que o problema seja esse `this`, tente usar `getApplicationContext()`
Comment: @JoãoRicardo editei a pergunta, verifique se atende o que precisa
Comment: Obrigado Guilherme, mais já consegui rodar o exemplo


GNAT GPS on the fly syntax checking and getting the best out of the IDE

Question: I've started using GPS for coding Ada at work - does anyone have any tips for getting the best out of the IDE? or any plugins I should be aware of?
For example is there a way to enable on the fly syntax/type checking - of the sorts you get in eclipse/visual studio where errors are underlined as you go?
Also what are people's general opinions on GNAT Workbench compared to GPS?
thanks
Matt
Answer: I do not think that GPS has a form of background syntax checking like Eclipse does, at least I haven't found it.
I wrote a small sized terminal program in GPS as my first Ada program and my opinion of it is generally negative.
The browser is very confusing and it is hard to find items you are looking for.
The editor has the nasty habit of adding a column to the left and removing it dynamically based on the item under your mouse. What that does is when you are trying to select text with the mouse, your text switches right and left by one character as you move which makes precise selection a difficult thing to do
Getting in the debugger involves too many steps and it generally moves your files in the editor to the EOF position when you set breakpoints, so you will do a lot of scrolling to go back to the sections of interest.
The debugger output looks fancy with all the graphical elements but it is also cumbersome to operate.
GPS offers better help features for Ada libraries though, it's generally easier to browse the standard libraries and check them out than in Eclipse.
All in all, if Eclipse works for you, you might want to stick with it or perhaps open both on the same project and switch to GPS for things like help etc.
I had a related question out here which is on hold now (as I expect your question will soon be due to it's broad content) but I did some research and I am generally dissatisfied with what is out there in the Ada field. The language is great but it suffocates under bad tools.
One last tip: You might want to try Slick Edit as it's text editor and browsing features are quite good, although they too have flaws with Ada (for instance the beautifier).
Good luck with your venture
Comment: There's a lot of things unnecessarily awkward in GPS or GNAT Studio as the new version is called. Simple things like a tab that is a dead key by default, inadequate use of mouse functions, automatic indents when you never asked for them, a terrible default code font, inability to select several files to open in a project folder at once, a UI that's as exciting as a funeral-parlor, etc, etc. Some of these can be reconfigured of course. But some are there to stay.
Answer: The GPS does not have a from of background syntax checking and that is by design. The idea behind GPS is that it is the compiler who decides what code is correct and what code is not correct. It means that if you want to know if your code is correct or not you have to compile it. On a Windows computer the short cut key for that is SHIFT+F4 and will only compile the specification or body file you are currently editing. Pressing F4 will compile your whole project. You will save time by using SHIFT+F4.
Another interesting feature is that the GPS uses cross-reference (XREF) information when navigation through the code. For example, let's say you would like to find all the places in your code where a specific subprogram is called. In GPS (GNAT PRO), right click on the subprogram you are interested in a press Find references. In the GPS GNAT Libre version you don't have a menu when right clicking in your code. In this case go to the Navigate menu and click on Find references there. If the GPS does not find any references and you know that the subprogram is used in the application it means that the XREF information needs to be updated. You may compile the whole application by F4 since the XREF information will be generated along with the binary that is produced. If you go to Edit and click on Key shortcuts you can set up a short cut key to generate the XREF information only. You may also find several interesting features there that you can set up a short cut key for.
The cross-reference information (XREF) is also used for refactoring (GNAT PRO specific functionality). It often works well for changing variable and subprogram names. Just make sure the cross-reference information is up to date!
Code snippets in GPS are also useful. You use them by writing a keyword followed by CTRL+O (not zero, O as in Orwell). To see the code snippets you can choose between go to Edit and click on Aliases. You can also create your own Aliases and code snippets to become a more productive Ada Software Engineer.
Good luck!


C# Disable Right Click

Question: i'm looking for code to catch a right click in the background using a windows forms application using hooks.
I already have something for individual buttons, now I'm looking for hooks for the mouse, someone ideas?
Comment: Did you try anything yet? Do you have specific issue?
Comment: Have you tried to look at this post? [How to get a right click mouse event?](https://stackoverflow.com/questions/19448346/how-to-get-a-right-click-mouse-event-changing-eventargs-to-mouseeventargs-cause)
Comment: Does this answer your question? [How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?](https://stackoverflow.com/questions/19448346/how-to-get-a-right-click-mouse-event-changing-eventargs-to-mouseeventargs-cause)
Comment: thanks but yes, it illustrates all kleicks in the background, but how can I turn it off?
Answer: <code> Button.MouseClick += SomeMethod;
   private void SomeMethod(object sender, MouseEventArgs e)
   {
        if (!e.Button.Equals(System.Windows.Forms.MouseButtons.Right))
        {
            // do work
        }
   }
</code>
Comment: does this work permanently in the background? mh, test it afterwards

C# Disable Right Click


How many permutations of the letters "DATACLASSRULES" but the letters "DATA" must stay together in any order. Repeated letters are not unique.

Question: I've tried doing 10!4! ÷ 2!3!2! = 3628800. But I'm getting told I'm wrong. 4!÷2! for "DATA" multiplying to 10!÷2!3! for "CLASSRULES". What am I missing and how do I solve it?
Answer: There are two things missing in your answer.
First, where DATA will end up. (11 possiblilities)
Second, the fact that there is a third A. We'll consider them unique at first then divide the final answer by $6!$
Rearrange the letter DATA : $4!$
Rearrange CLASSRULES : $\dfrac{10!}{3!2!}$
Place DATA inside CLASSRULES : $11$
Rearrange the 3 A : $\div 3!$
Answer :
$$\frac{4!\times11\times10!}{3!\times2!\times3!}$$
Answer: Alain's solution is neat: here is an alternate way based on "building up" permutations with unmarked balls, which is often useful when the conventional method becomes difficult.

First build up a block of $4,\;$ placing the balls one by one, so $1\cdot2\cdot3\cdot4 =24,\;\;$ bind into an unordered block representing letters DATA

Then similarly place the remaining $10$ balls one by one, around the "DATA" block in $2\times 3\times\;\;...\;\;\times{11} = 11!$ ways

Finally, adjust for repeats of $AAA,\, SSS,\, LL$

Thus $Ans= \Large\frac{24\times 11!}{3!3!2!}$


Need help to fix a script with dynamic content

Question: I can't figure out why this is not working.  I'm trying to get different DIV tags to have different text content in a cycle loop.

Answer: Seems to be a bunch of syntax errors (text instead of text1/text2, no closing /div, etc. Works fine here: http://jsbin.com/obaqi4/3
Comment: Thank you...  here is the page:  http://www.myorphan.com/about.htm  how do eliminate the background from fading.  I only want he text to change.
Comment: Put the text you want to change inside a separate element. So for example, instead of `...`, use `...`, then target the javascript for #st1_inner, and apply all the styles to the outside div. This will ensure the external style sticks around while the text fades and changes.
Comment: BTW, the problem is that fade in/out fades the entire element by setting opacity. In order to just fade text (text by itself is not an element), you have to wrap it in an element that represents just the text.


How do you find range of values for a discontinuous function?

Question: Suppose I define the following function:
$$
F(x) = 1 + x \text{  for } x\in (-1, 0], 1-x \text{  for } x \in (0, 1] \text{ and } 0 \text{
 otherwise}
$$
And I want to find the range of values where $F(x) \geq F(x+1)$ and where $F(x) \geq 1 - F(x) - F(x+1)$.
How do I go about doing this?
I tried a graphical approach wherein I plot the curves but I ended up getting confused around how does the $F(x+1)$ term works over here.
Any help will be appreciated.
Answer: Graphical approach would work fine.
Let $G(x)=F(x+1)$ and replace as such in your expressions so you don't get confused.
$G(x) = x+2 \hspace{70pt}$ for $x+1 \in (-1, 0],$ i.e. $x \in (-2,1]$
$G(x) = 1-(x+1)=-x \hspace{18pt}$  for $x+1 \in (0,1],$ i.e. $x \in (-1,0]$
$G(x) = 0 \hspace{89pt}$ otherwise
Comment: And then how do I go about finding the range of values where $F(x)≥F(x+1)$ and where $F(x)≥1−F(x)−F(x+1)$?
Comment: "Graphical" Approach as you said: Draw the individual graphs, add/subtract them and compare them
Answer: The function $F$ is not discontinuous... In the picture you can see the graphics of $F(x)$ (blue) and $F(x+1)$ (Orange).
So, for instance, $F(x)\ge F(x+1)$ if and only if $x \ge -\frac 12$ or $x\leq -2$. Below you can find the graphics of $F(x)+F(x+1)$ and $1-F(x)-F(x+1)$.
Comment: @JashShah algebraically, you can just obtain the expression of $1-F(x)-F(x+1)$ on each interval of interest and solve the corresponding  inequality on each of those intervals.
Comment: Thanks @PierreCarre. A couple of follow up questions:
1. How do I find the range of values where $F(x)≥1−F(x)−F(x+1)$?

2. How does this work algebraically?
Comment: what would the graph for $1−F(x)−F(x+1)$ look like?


Angular .Net DLL Possible Integration

Question: Are there any frameworks enabling Angular to call a .net dll without making a service call.  We have created a dll for a DB to enable it to encrypt/decrypt SSN without making a web service call.  If the UI can call it too, that would eliminate the need to send unencrypted SSN's to the App server over the network to have the SSN encrypted.  The idea would be all 3 tiers could use the same dll.
Comment: To answer your question: No, you can't call into a dll (.net or native) from javascript (as angular is javascript framework built with Typescript, a superset of javascript, it also applies here). Javascript executes in a sandbox, if you really did want to pursue this route you would need to elevate permissions and find some library that could make the native call. Personally I would strongly discourage it.
Comment: Why not use an SSL certificate to encrypt the network channel? That is the standard accepted approach to encrypted communication from client (browser) to server.
Comment: Thank you @Igor.
Answer: You can give Blazor a try, because you can call a C# method from javascript:
From the link:
<code>// Define a very simple JavaScript function that just prints
// the input parameter to the browser's console
window.say = async (data) => {
   // Demonstrate how to call a C# method from JavaScript
   console.log(await DotNet.invokeMethodAsync('RestApi.Client', 'Concat',
              'Recieved call ', 'from C#. ', 'Here is the received parameter:'));

   console.dir(data);

  // Your function currently has to return something. For demo
  // purposes, we just return `true`.
  return true;
};
</code>
And the C# method:
<code>using Microsoft.JSInterop;
using System.Threading.Tasks;

namespace RestApi.Client.Pages
{
   public static class StringUtil
   {
       [JSInvokable]
       public static Task<string> Concat(string str1, string str2, string str3)
       {
           return Task.FromResult(string.Concat(str1, str2, str3));
       }
   }
 }
</code>
Now, keep in mind, that using Blazor may have a small learning curve and probably won't solve the security issue. Please read the documentation before using it for this particular purpose.

Angular .Net DLL Possible Integration