Distance between a point and the diagonal set.

Question: Problem:
Given a metric space $(M,d)$ and the diagonal set $\Delta:= \{(x,x)|x\in M\}$. Show that $$z = (x,y)\notin \Delta \implies d'(z, \Delta)>0,$$
where $d'$ is a metric associated with $M\times M$.
My thoughts:
My idea is to look for a term $c$, probably dependent of $d(x,y)$, where $d'(z, \Delta)>c>0$. How to find that $c$? There's another way to solve this problem?
Answer: $\Delta$ is a closed set because every metric space is Hausdorff.
Thus if $x_0 \in \Delta^c$ then exists $R>0$ such that $B(x_0,R) \cap \Delta=\emptyset \Longrightarrow B(x_0,R) \subset \Delta^c \Longrightarrow d'(x,y) \geq R ,\forall y \in \Delta \Longrightarrow d'(x,\Delta) \geq R$

Also note that:
$\textbf{Lemma}$ In a general metric space,if $A$ is closed and $B$ is compact then $\exists C>0$ such that $d(x,y) \geq C,\forall x \in A, \forall y \in B$

From this, with $A=\Delta$ and $B=\{x_0\}$ you have again the desired conclusion.
You can prove the lemma i mentioned as an exercise,if you want.
Comment: Sincerely, thank you very much for the answer! Saddly, we can't use topological concepts like closure or compactness yet. Some examples of concepts allowed are balls and limited sets (metric spaces where $d(x,y)$ is always less than a real number $c$.
Comment: Then  ignore the second part of the answer and pay attention at the first two lines
Comment: Alright, but how do I know that exists $R>0$ such that $B(x_{0}, R)\cap\Delta = \emptyset$ without using closure?
Comment: because the complement of a closed set is open and then we use the definition of an open set
Comment: Observe that $d(x,\Delta)=\inf\{d(x,y):y\in\Delta\}=0$, if and only if, for every $\varepsilon>0$ we have $B(x,\varepsilon)\cap\Delta=\{y\in\Delta:d(x,y)<\varepsilon\}\neq\emptyset$. So, $d(y,\Delta)>0$ implies the existence of some $r>0$ such that $B(y,r)\cap\Delta=\emptyset$. Although we haven't used "topology", it's ideias is clearly behind !
Answer: A direct proof, without appeal to general topology (I'm assuming we're using the supremum distance, i.e. $d'((a,b),(c,d))=\max\{d(a,c),d(b,d)\}$):
Let $r=d(x,y)$ and consider $B:=B(z,\frac{r}{3})$ in $M\times M$. We claim that $B\cap \Delta=\emptyset$.
Indeed, if $(w,w)\in B,$ then both $d(w,x)<\frac{r}{3}$ and $d(w,y)<\frac{r}{3}$. In particular, $d(x,y)\leq d'((x,x),z)\leq d'((x,x),(w,w))+d'((w,w),z)< \frac{2r}{3},$ which is a contradiction.
Comment: That's the problem... we don't have any distance/metric and can't use topological concepts like closure or compactness to solve this question. With a metric it would be much easier.
Comment: The question was literally to show that a certain distance was strictly positive?
Comment: Nope... Actually, I translated the book exercise in more detail. If you want the portuguese version: Seja $\Delta = \{(, ) |  \in \}$ a diagonal do produto $ \times $ onde $$ é um espaço métrico.
Se $ = (, ) \in \Delta$ então $(, \Delta) > 0.$
Comment: So the part in the question where it reads $z=(x,y)\not\in \Delta \Longrightarrow d'(z,\Delta)>0$ is a typo?
Comment: Oh, now I understand what you mean. No, isn't a typo. We have to show that $d'(z,\Delta)$ is strictly positive or, equivalently, that for some $\epsilon>0$, any $(w,w)\in\Delta$ is such that $d'((x,y),(w,w))>\epsilon$.
Comment: So, reading on, $d'$ is a metric, and so, we have a metric. You just didn't write out what it is. I'm just assuming it's the one stated above (it's the most natural in my opinion, but running both metrics through any norm on $\mathbb{R}$ works).
Comment: And in this case, we see that $\varepsilon=\frac{d(x,y)}{3}$ works by the proof above.
Comment: Ok, if you think it's natural, I'll assume the "max metric" (I guess the author forgot to mention). Thanks!
Comment: There is a family of metrics on $M\times M$ given by $d_p((a,b),(c,d))=(d(a,c)^p+d(c,d))^{1/p}$ (with the max metric in the case of $p=\infty$), and they're all equivalent, since all norms on $\mathbb{R}$ are equivalent.


Can't su to user other than root on CentOS

Question: I'm able to SSH to my server (CentOS 5.9) using an admin account with sudo privileges:
$ ssh admin@myserver
Last login: Wed Feb 27 19:23:11 2013 from [IP ADDRESS]
[admin@myserver ~]$

Then I can su to root:
[admin@myserver ~]$ sudo su root
[sudo] password for admin:
[root@myserver admin]#

But I can't su to another user, and the su command is not telling me why:
[admin@myserver ~]$ sudo su anotheruser
[admin@myserver ~]$ whoami
admin

Any idea why I can su to root, but not to other users?
How can I get su to tell me why it is not doing what I want it to do?
Comment: (Reason being is that it may not be desirable to know the target user's password. Sudo allows you to authenticate as yourself.)
Comment: Don't use `sudo`, just `su`. Try `su root`, then `su user` as root. Then for more details, try `su user` as admin.
Comment: @Chloe `sudo su anotheruser` most certainly can work.  It just needs to be granted in `/etc/sudoers`.
Comment: Why don't you just give those users permission to run commands as the other users in `/etc/sudoers` and forget this unnecessary indirection?
Answer: In case it's useful to someone else: I just ran into the same symptoms but the answer had nothing to do with sudo configuration.
Instead, it mattered which user I was trying to su to.  The target user was a service pseudo-user (jenkins) which had /bin/false as its shell.  The fix was to change the shell to a valid one (using chsh).
Answer: Check /var/log/security and /var/log/auth.log.
Why are you using sudo to use su?  You don't need to do that unless you change your standard ACLs.
If you use sudo, then the issue might be related to you sudoer file.  Verify you have it configured properly.
Comment: Reason to use `sudo su` over `su` is to use his own password instead of the target user.
Comment: `su` by itself requires you to use the target username's password, not your own.
Comment: Also, these logs don't exist in a default CentOS 5.9 installation.
Comment: On my other server (similar setup) by using sudo, I'm able to su using my own password.  When I su by itself with no sudo, it says "incorrect password".
Comment: Is it a specific user you're having issues with or all users other than root?  Also, can you show your sudoer's file?
Answer: What permissions are granted in /etc/sudoers to admin?
Also, as root, you could always su - anotheruser. An extra step perhaps, but without knowing anything about your sudoers file this will work.
Comment: You're going to need to look in `/var/log/secure`, then. Sudo / su log to the authpriv facility which generally goes to `/var/log/secure`.
Comment: My permissions in /etc/sudoers look like this:

`root    ALL=(ALL)       ALL`
`%admins ALL=(ALL)       ALL`

The admin user is in the admins group.
Comment: I would double (triple) check the group membership of admin user. Is it a local group or domain? Try adding the user by name to `/etc/sudoers` to test and eliminate a point of failure.
Comment: That's great feedback. I can see the su command working from admin to root in the /var/log/secure, but I find this for the admin user trying to su to anotheruser:

`Feb 28 10:03:38 myserver su: pam_unix(su-l:session): session opened for user anotheruser by admin(uid=0)

Feb 28 10:03:38 myserver su: pam_unix(su-l:session): session closed for user anotheruser`

I'm still not exactly sure what's going on except that it's opening a session and then immediately closing the session.
Comment: I've also added the admin user to the sudoers file just below root like this: `admin ALL=(ALL) ALL`. Still no luck.  The root user is also not able to su to another user account--not just the admin.  I can, however, su from root to admin and vice-versa.
Comment: I think something has been changed in PAM to deny this. Default settings permit it. (I've tested it on a workstation here.) Try verifying your `/etc/pam.d/su*` files with `rpm -V sudo` and `rpm -V coreutils`. (Look for `/etc/pam.d/su*` files in particular.) If you have another box load it up with a clean install and test there.
Comment: Hmm, it looks like after adding the `admin ALL=(ALL) ALL` to the sudoers file did the trick after all.  I'm not sure why it wasn't working at first (maybe the settings were cached).  It seems to be working now.


In winform, how to add sort column functionaity into listview columns?

Question: In winform, how to add sort column functionaity into listview columns ?
I could not find any properity for column which allows>
Thanks
Comment: Here's a nice article on MSDN that explains how to do this: [**Sorting ListView Items by Column Using Windows Forms**](http://msdn.microsoft.com/en-us/library/ms996467.aspx)
Answer: You have to write your own class that implements IComparer.
You then write a Compare method that Implements IComparer.Compare in this class.
Below is an example of one I wrote some time ago that sorts by number, date or string but you can modify this for your own use:
Public Class ListViewComparer
    Implements IComparer

    Private _columnNumber As Integer
    Private _sortOrder As SortOrder

    Public Sub New(ByVal colIndex As Integer, ByVal sortingOrder As SortOrder)
        _columnNumber = colIndex
        _sortOrder = sortingOrder
    End Sub

    ' Compare the items in the appropriate column
    ' for objects x and y.
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim itemX As ListViewItem = DirectCast(x, ListViewItem)
        Dim itemY As ListViewItem = DirectCast(y, ListViewItem)
        Dim stringX As String = "", stringY As String = ""
        ' Get the sub-item values.

        If itemX.SubItems.Count > _columnNumber Then stringX = itemX.SubItems(_columnNumber).Text
        If itemY.SubItems.Count > _columnNumber Then stringY = itemY.SubItems(_columnNumber).Text

        ' Compare them.
        If _sortOrder = SortOrder.Ascending Then
            If IsNumeric(stringX) And IsNumeric(stringY) Then
                Return CInt(stringX).CompareTo(CInt(stringY))
            ElseIf IsDate(stringX) And IsDate(stringY) Then
                Return DateTime.Parse(stringX).CompareTo(DateTime.Parse(stringY))
            Else
                Return String.Compare(stringX, stringY)
            End If
        Else
            If IsNumeric(stringX) And IsNumeric(stringY) Then
                Return CInt(stringY).CompareTo(CInt(stringX))
            ElseIf IsDate(stringX) And IsDate(stringY) Then
                Return DateTime.Parse(stringY).CompareTo(DateTime.Parse(stringX))
            Else
                Return String.Compare(stringY, stringX)
            End If
        End If
    End Function
End Class

Usage:
ListViewControl1.ListViewItemSorter = New ListViewComparer(2, SortOrder.Ascending)
ListViewControl1.Sort()

Comment: No, you will have to call the sort code in the ` ListView1.ColumnClick` event and pass in the `e.Column` value
Comment: ok, its working. But, how to manage ascending and descending both.. on related click.
Comment: you need to keep track of which direction you are currently sorting in and reverse it on a click of the same column. If you click a different column then set it back to ascending


Boyd & Vandenberghe, section 3.3.4 — Quasiconvexity of linear-fractional composition

Question: In Boyd & Vandenberghe, Section 3.3.4, it is stated that composition of a quasiconvex function with an affine-fractional transformation is quasiconvex. In specific, if $f(x)$ is quasiconvex, then
$$ g(x) = f\Big(\frac{Ax+b}{c^Tx + d}\Big)$$
is also quasiconvex on the domain of $f$ when the denominator of the fraction is positive. Here, $A$ is a matrix, $b$ and $c$ are vectors, and $d$ is a scalar.
I have tried to show this useful fact, but have been unable to. The simpler property that composition with an affine function preserves
quasiconvexity follows straightforwardly from the definition of a quasiconvex function, but all my attempts at generalizing to the fractional case have been fruitless.
Any ideas? Oddly I have not been able to find a proof anywhere.
Answer: Just notice $$\frac{A(\lambda x+(1-\lambda)y)+b}{c^T(\lambda x+(1-\lambda)y)+d}=\mu \frac{A x+b}{c^T x+d}+(1-\mu)\frac{A y+b}{c^T y+d},$$ where $\mu=\frac{\lambda (c^T x+d)}{\lambda (c^T x+d)+(1-\lambda) (c^T y+d)}.$ Hence $$g(\lambda x+(1-\lambda)y)=f(\mu \frac{A x+b}{c^T x+d}+(1-\mu)\frac{A y+b}{c^T y+d})\leq\max\{f(\frac{A x+b}{c^T x+d}),f(\frac{A y+b}{c^T y+d})\}.$$
Comment: This is very similar to the proof that a linear-fractional function is convex


getImageWritersByFormatName doesn't give proper values

Question: Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
if (!writers.hasNext()) {
    throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
}

net.sourceforge.tess4j.TesseractException: java.lang.RuntimeException
Need to install JAI Image I/O package. Exception is thrown because of hasNext().
The same web application works in my mac machine, but not on an ubuntu machine. I am using tomcat server. Any help?
Comment: Thanks! I figured out the mistake myself.. i had to set the classpath in tomcat/bin/setenv.sh
Comment: Is `TIFF_FORMAT == "TIFF"`? Just checking... :-) Most likely, this is a JAI installation issue. Either it's not there at all, or your Tomcat and/or web app is not picking it up. Do you install to the JRE's ext/lib folder or to Tomcat's shared/lib or common/lib folders?
Comment: yes, TIFF_FORMAT = "tiff" and JAI_IMAGE_WRITER_MESSAGE = "Need to install JAI Image I/O package.https://java.net/projects/jai-imageio/". I have the libs in the tomcat_home/lib folder
Comment: That seems to be the right place, given a fairly recent Tomcat. You could try to add an `ImageIO.scanForPlugins()` call (typically from a `ContextListener` or similar), if `ImageIO` somehow was initialized before Tomcat added it's shared classloader, to make the JARs in the lib folder available. If that doesn't help, I'd check the JAR files contents, to verify that they are correct.
Comment: Good. You should post that as an answer. :-)
Answer: Thanks! I figured out the mistake myself.. i had to set the classpath to the jai_imageio.jar file in tomcat/bin/setenv.sh


Por que dar new no atributo da classe?

Question: Estou saindo do C++ para o Java e gostaria de saber do porque de dar new já no atributo da classe?
public class ExemploPES2
{
    class y{

        int value;

    }

    class x{

        private y nova = new y();

    }

Não entendi o porque de eu dar new já no atributo. Serve para chamar qual construtor?
Comment: E porque não daria? É igual C++. Você realmente queria colocar uma classe dentro da outra?
Comment: O que está fazendo parece ser composição, quando um objeto é composto por outro objeto. Neste caso, o objeto interno é criado dentro do externo. Qual seria o código equivalente em C++?
Comment: Aliás, por quê definir classes dentro de uma classe?
Comment: Em Java, só se tem referências a objetos, por isso você precisa dar um new
Answer: O principal motivo de usá-lo é igual ao do C++, indicar que uma alocação no heap deve ser realizada para suportar aquele objeto, então a variável ali presente receberá um ponteiro para o objeto alocado, como em C++.
Claro que em Java você não tem o ponteiro exposto diretamente e não é possível optar por usar o new o u não, se é uma classe, sempre será um tipo por referência. Tão pouco pode personalizar o operador new para esta classe.
Em tipos primitivos isto não é necessário porque a alocação é feita dentro da própria classe, ou stack, o valor é colocado ali mesmo e não precisa de uma alocação adicional.
Em tese seria possível não ter esse operador já que toda classe precisa dele. Mas não deixa de ser uma informação extra para indicar que está chamando um construtor e não um método qualquer que retorna um objeto, dando mais legibilidade sobre a intenção do código. Infelizmente para a maioria dos programadores Java acabou se tornando só redundante porque poucos observam sobre a alocação e tempo de vida do objeto, ao contrário do que ocorre em C++.
No seu exemplo a variável y está sendo declarada como do tipo y (péssimo nome, deveria ser maiúsculo, melhor ainda se fosse um nome significativo), e está chamando o seu construtor para inicializá-lo.
Em tese é possível não chamar nada e não inicializar, assim a variável y passaria ter o valor null, mas nesse exemplo não serviria para muita coisa, ou todo exemplo não serve. Se não inicializar o campo (não gosto do termo atributo para isto) teria que criar um construtor que faça isto ou trabalhar com um membro potencialmente inválido até que de alguma forma ele seja inicializado.
O compilador do Java cria um construtor padrão sempre que você não forneça um construtor. Este construtor serve apenas para padronização de chamada da construção.
Em Java só dá para construir um objeto desta forma, não tem sintaxes alternativas como o C++ tem.
Coloquei no GitHub para referência futura.
Answer:
Não entendi o porque de eu dar new já no atributo.

Você não é obrigado a "dar new" na declaração do atributo.
A galera faz isso para evitar que exista uma instância com um atributo nulo.
Por exemplo:
public class Y {

    public void fazAlgumaCoisa() {
        //implementação
    }
}

public class X {

    private Y nova;

    public Y getNova() {
        return nova;
    }
}

public class Z {

    public void chamaMetodoDeY() {

        X meuX = new X();
        Y novaDeX = meuX.getNova();

        novaDeX.fazAlgumaCoisa(); //Uma NullPointerException é lançada nessa linha
    }
}

O "valor padrão" para variáveis de instância/atributos de tipos não primitivos é null.

Práticas para evitar esse cenário
Para evitar cenários como esses, são aplicadas soluções como:
Prática #1: Instanciar/inicializar os atributos na própria declaração (seu exemplo);
Prática #2: Receber uma instância (ou valor) pelo construtor de sua classe:
public class Y {

    public void fazAlgumaCoisa() {
        //implementação
    }
}

public class X {

    private Y nova;

    public X(Y nova) {
        this.nova = nova;
    }

    public Y getNova() {
        return nova;
    }
}

public class Z {

    public void chamaMetodoDeY() {

        X meuX = new X();
        Y novaDeX = meuX.getNova();

        novaDeX.fazAlgumaCoisa(); //Nenhuma Exception será lançada nessa linha
        //pois você receberá uma instância de Y pelo construtor
    }
}

Prática #3: Injeção de dependências:
Esse já é um tópico um pouco mais avançado.
Injeção de Dependências significa, basicamente, que algo ou alguém vai "injetar" uma dependência (instância) em seus atributos de forma automágica.
Normalmente temos um Container de Injeção de Dependências que é o responsável por injetá-las.
Um exemplo famoso é utilizando o framework Spring:
public class Y {

    public void fazAlgumaCoisa() {
        //implementação
    }
}

public class X {

    @Autowired //Anotação do Spring que injeta uma instância de Y quando for necessário
    private Y nova;

    public Y getNova() {
        return nova;
    }
}

public class Z {

    public void chamaMetodoDeY() {

        X meuX = new X();
        Y novaDeX = meuX.getNova();

        novaDeX.fazAlgumaCoisa(); //Nenhuma Exception será lançada nessa linha
        //pois o Spring injetará a instância necessária quando for necessário
    }
}

Obs: para que isso funcione são necessárias algumas (um punhado) de configurações prévias.

Serve para chamar qual construtor? (private Y nova = new Y();)

O construtor de Y é chamado.
Comment: Você respondeu a pergunta... eu não tinha entendido do porque de dar new no próprio atributo da classe, agora compreendi que serve para não declarar atributo nulo.
Answer: O uso do new implica na criação de uma instancia para a classe a direita da palavra reservada new, sobre qual construtor está sendo chamado nesse caso é o seguinte, no java, quando você não declara nenhum construtor o compilador do Java adiciona um construtor padrão, qual não possui nenhum argumento, no exemplo que você postou o construtor utilizado é o padrão.
Obs: Caso algum construtor seja declarado na classe o construtor padrão da mesma não é mais incluído pelo compilador e caso você queira utiliza-lo vai ter que inclui-lo manualmente na classe, como no código a seguir:
class Pessoa {
  String nome;

  public Pessoa() {}

  public Pessoa(String nome) {
    this.nome = nome;
  }
}

Por que dar new no atributo da classe?


STL - what is the problem of the following code?

Question: #include "stdafx.h"
#include <string>
#include <map>
using namespace std;

class NiftyEmailProgram {
private:
    typedef map<string, string> NicknameMap;
    NicknameMap nicknames;

public:
    void ShowEmailAddress(const string& nickname) const
    {
        NicknameMap::const_iterator i = nicknames.find(nickname);

        if ( i != nicknames.end() )
        {
        }
    }

};

int main(int argc, char* argv[])
{
    printf("Hello World!\n");
    return 0;
}

When I compile the above code in VC6.0, I have seen tons of warnings. If I use Warning Level 4 and treat all warnings as error, then the output error from STLFilt is as follows:
Compiling...
t3.cpp
c:\devstudio_6.0\vc98\include\xtree(118): error C2220: warning treated as error - no object file generated
    c:\devstudio_6.0\vc98\include\map(46): see reference to class template instantiation 'map<string,string>' being compiled
    C:\TEMP\t3\t3.cpp(12): see reference to class template instantiation 'map<string,string>' being compiled
Error executing cl.exe.

t3.exe - 1 error(s), 26 warning(s)
Tool returned code: 0

Now, what is the problem of this code and how do I fix it?
Thank you
Comment: Why are you using a 12 year old compiler?
Comment: You should ask them if they are planning to upgrade to Windows 98 while they're at it. Seeing as how it's contemporary with VC6.
Comment: The code reads just fine. VC 6.0 is most probably to blame.
Comment: VC 6 is to blame. VC 8 deprecates some perfectly valid STL functions (eg. `std::copy`). This annoys me everyday. You have to disable the warnings on a per case basis.
Comment: Hey everybody, don't pick on him for retaining an old compiler - sometimes you have libraries you depend on that can't be upgraded, or a large body of code that wouldn't be cost-effective to upgrade. P.S. I've made an addition to my answer, check it out.
Comment: I remember this occurring and simply ignored the warning. It would be good to know how to avoid the warning.
Comment: Remove `stdafx.h` from the includes?
Comment: @FredOverflow, because the company who pays my bill adopted, is adopting and will adopt VC6.0 as the main workhorse.
Comment: @Karl, you forget, for the workplace, it was Windows NT. What did NT stand for again!?!
Comment: @Nim: * **raising my hand up** * pick me, pick me! Nice try??!
Answer: Try to post the non-treated warnings.
However, I too remember that I got some level 4 warning from <xtree> in <map> , that could be safely ignored (IIRC it was C4702, which is harmless).
To avoid the warning, I put around the STL #includes some appropriate #pragma warning directives (enclosed in the correct #ifdefs to have them considered only on MSVC++, thanks to @Alexandre C. for reminding me of it):
#ifdef _MSC_VER
    //Disable the C4702 warning for the following headers
    #pragma warning(push)
    #pragma warning(disable:4702)
#endif // _MSC_VER
//map STL container
#include <map>
//list STL container
#include <list>
//vector STL container
#include <vector>
#ifdef _MSC_VER
    #pragma warning(pop)
#endif

You could also simply lower the warning level to 3 (or even lower) just in that section with:
#ifdef _MSC_VER
    // Lower the warning level to 3 just for this section
    #pragma warning(push, 3)
#endif
//map STL container
#include <map>
//list STL container
#include <list>
//vector STL container
#include <vector>
#ifdef _MSC_VER
    #pragma warning(pop)
#endif // _MSC_VER

For more info, see the documentation of #pragma warning.
Comment: For portability, you can segregate the `#pragma` s with `#ifdef _MSC_VER` ... `#endif`.
Comment: @Alexandre C.: Uh, you're perfectly right, I'll fix it right now.
Comment: Sorry for nitpicking, but while you're at it, take the habit of enabling it for a specific version since this is know to behave well on MSVC7.
Comment: @André Caron: I got that level 4 warning also on MSVC7.1, so I'd leave it as it is, also because, in general, you'd expect that the standard library headers are tested enough that the warnings you may get from them aren't important.
Answer: If I remember correctly, the mangled function names created by STL easily exceed some built-in limit, and this is what triggers the warning. It's unfortunate that you used STLFilt to keep us from seeing the actual warnings produced by the compiler.
The only work-around I found was to use typedefs and/or derived classes to shorten the names used in the template.
As the others have mentioned, the best and easiest fix would be to upgrade your compiler.
Edit: I tried this on my own VC6 and the error was exactly as I remembered:
c:\program files\microsoft visual studio\vc98\include\xtree(118) : warning C4786: 'std::_Tree<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::pair<std::basic_string<char,std::char_traits<char>,std::allocator<char> > const ,
std::basic_string<char,std::char_traits<char>,std::allocator<char> > >,std::map<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::less<std::basic_string<cha
r,std::char_traits<char>,std::allocator<char> > >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > >::_Kfn,std::less<std::basic_string<char,std::char_traits<char>,std::allocator<char> > >,std::allocator<std::basi
c_string<char,std::char_traits<char>,std::allocator<char> > > >' : identifier was truncated to '255' characters in the debug information
        c:\program files\microsoft visual studio\vc98\include\map(46) : see reference to class template instantiation 'std::_Tree<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::pair<std::basic_string<char,std::char_traits<
char>,std::allocator<char> > const ,std::basic_string<char,std::char_traits<char>,std::allocator<char> > >,std::map<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::basic_string<char,std::char_traits<char>,std::allocator<cha
r> >,std::less<std::basic_string<char,std::char_traits<char>,std::allocator<char> > >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > >::_Kfn,std::less<std::basic_string<char,std::char_traits<char>,std::allocato
r<char> > >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > >' being compiled

The workaround I mentioned earlier isn't enough, because with the shortest class name possible the name of an iterator still exceeds 255 characters. The solution is to put this before the #include <map>:
#pragma warning(disable:4786)

Comment: @q0987, I presume most of the warnings are duplicates, couldn't you post just one or two?
Comment: the total warning message is of size 60285, I am not allowed to post that big chunk of text here. thank you
Comment: @q0987: you may post it on pastebin or something like that.


How to Uninstall/Reinstall a custom module whithout losing the content?

Question: As we know : it's impossible to unsintall a module whithout being forced to remove all the data that's belongs to it.
The problem is, if we want to update a module we are obliged to uninstall it and then reinstall to get the changes work.
At developpement phase, it's ok , but what about being in a production site and having a big amount of data we don't want to loose, by just adding a field , or changing a type ....
Is there any best practises? Is there a process that could be advised? Is there any feedbacks of your own experience?
For example, I would guess : export data and then import data after the reinstall?
Thank you so much!
Comment: Why are you obliged to uninstall a module to update it?
Comment: There is no case that you have to uninstall a module before update.... unless there is no upgrade path for the contrib module.
Answer: You can update your database with

hook_update_xx

if your module define hook_shema
https://www.drupal.org/docs/8/api/update-api/updating-database-schema-andor-data-in-drupal-8
Comment: I had no idea of what are hooks :D , well I'll try, could give a links for drupal 8 tutorials. (I find tutorial for drupal 7 not 8 )
Answer: In order to make my changes take effect without removing all data -> uninstall -> reinstall the module .
Here the steps :

Make the changes (in my code , for exemple add a field in my entity class)
Add a hook_update_N() in yourmodule.install (yourmodule is your module name)
yourmodule.install is in the  root od your module, if not exist create it
Here the content of yourmodule.install
<?php
     /**
    * Document your changes
     */
     function yourmodule_update_8001() {
    \Drupal::entityDefinitionUpdateManager()->applyUpdates();
      }
Execute update.php et the change take effect in the database !

NB: I made my changes in my custom module code using BaseFieldDefinition, ...


Using Ajax, how can I populate a div with Database Content from a form select?

Question: This is what I have so far. I can populate the select field just fine, however when another option is selected I can not get the data to populate in the ajax callback div.
function product_comparison_menu(){
  $items = array();
  $items['design_product_comparison'] = array(
    'title'            => t('Product Comparison'),
    'menu_name' => 'menu-main-menu',
    'page callback'    => 'drupal_get_form',
    'access arguments' => array('access content'),
    'page arguments' => array('product_comparison_form'),
  );

  return $items;
}

/*
* Display output
*/
function product_comparison_form($form, &$form_state) {

  //Query DB for Rows
$query = db_select('product_comparison');
$query->fields('product_comparison', array('id', 'OtherCombo',));
$query->condition('DropdownCategory', 'Exit Devices');
$query->orderBy('OtherCombo', 'ASC');
$results = $query->execute();

    //define rows
$options = array();
foreach ($results as $result) {
    $options[$result->id] = $result->OtherCombo;
}

$form['Exit Devices']['OtherCombo'] = array(
    '#type' => 'select',
    '#title' => t('Exit Devices'),
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'product_comparison_ajax_wrapper',
      'callback' => 'product_comparison_form_ajax'
    ),
);

$form['results'] = array(
  '#type' => 'markup',
  '#prefix' => '
',
  '#suffix' => '
',
 );

 // If the form has been submitted, build up your results and display them
 if (isset($form_state['Exit Devices']['OtherCombo'])) {
   $row = db_select('product_comparison')
     ->fields('product_comparison', array('DesignHardware', 'DesignImg','DesignURL'))
 ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
     ->execute();

   $header = array();

   $form['results']['#markup'] = theme('table', array('header' => $header,'rows' => $rows));
  }
  else {
    $form['results']['#markup'] = '
The results will appear here when you change the dropdown option.
';
  }

 return $form;
}

function product_comparison_form_ajax($form, $form_state) {
  return $form['results'];
}

Answer: You need to populate data in the ajax callback product_comparison_form_ajax and then return $form['results'].
Your code should be as the following:
Product comparison form
function product_comparison_form($form, &$form_state) {

  //Query DB for Rows
  $query = db_select('product_comparison');
  $query->fields('product_comparison', array('id', 'OtherCombo',));
  $query->condition('DropdownCategory', 'Exit Devices');
  $query->orderBy('OtherCombo', 'ASC');
  $results = $query->execute();

  //define rows
  $options = array();
  foreach ($results as $result) {
    $options[$result->id] = $result->OtherCombo;
  }

  $form['Exit Devices']['OtherCombo'] = array(
    '#type' => 'select',
    '#title' => t('Exit Devices'),
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'product_comparison_ajax_wrapper',
      'callback' => 'product_comparison_form_ajax'
    ),
  );

  // removed result condition

  $form['results'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => '
The results will appear here when you change the dropdown option.
',
  );

  return $form;
}

Product comparison ajax callback
function product_comparison_form_ajax(&$form, &$form_state) {
  if (isset($form_state['Exit Devices']['OtherCombo'])) {
    $row = db_select('product_comparison')
      ->fields('product_comparison', array('DesignHardware', 'DesignImg','DesignURL'))
      ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
     ->execute();

    $header = array(
      array('data' => 'Design Hardware'),
      array('data' => 'Design Img'),
      array('data' => 'Design URL'),
    );

    $rows = array();
    foreach ($result as $row) {
      $rows[] = array('data' => (array) $row);
    }

    // assign result to markup
    $form['results']['#markup'] = theme('table',array('header' => $header, 'rows' => $rows));

  }

  return $form['results'];
}

Answer: 3 things to commment:

The variable $row is not the same the variable $rows that you pass in the theme function. I think it's a misspelling error.
Your $header variable is empty when you pass to theme table. I am not sure if it's necessary to send it with data.
To verify the table is empty, i've added a new variable called empty to your theme variables. The documentation fo theme_table() in theme.inc says:

empty: The message to display in an extra row if table does not have any
       rows.

I've changed 2 things in the next piece of code:
// If the form has been submitted, build up your results and display them
if (isset($form_state['Exit Devices']['OtherCombo'])) {
  $rows = db_select('product_comparison')
  ->fields('product_comparison',
    array('DesignHardware','DesignImg','DesignURL'))
  ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
  ->execute();

  $header = array();

  $form['results']['#markup'] = theme('table',
   array('header' => $header,'rows'=> $rows, 'empty' => 'empty table'));
  }else{
  $form['results']['#markup'] = '
The results will appear here when you  change the dropdown option.
';

}
Comment: Thanks Aboodred1 and Rufein using what you guys provided I was able to get this working. I am new to this forum and I am loving it so far, is there anything I can do to give you guys credit for this.
Comment: You are welcome @CodeWeaver. I recommend you to read the [faqs](http://drupal.stackexchange.com/faq) to understand how it works :)


How not show in a View certain taxonomy items if there are no associated nodes?

Question: I'm using a View to display all the items from a taxonomy term list I've setup. The taxonomy term is used as a field in my nodes. That's all fine.
Now, I created another view called 'all categories' that displays all the taxonomy terms (each term is only displayed once). When a user clicks the term they automatically go to the term page and see the nodes that are using that term.
The problem is that some of the terms haven't yet been used by any nodes so when the user clicks the term name for those it just takes them to a page that says [name] at the top with no other information. I'd rather just hide any categories that have no associated nodes, but I don't know how to do it. I'd also be open to other suggestions for alleviating this issue.
Note: if a term DOES have nodes associated with it and you click the term it takes you to a page with the term as the title and the associated nodes listed below the title.
Here's the settings I have for the 'All categories' view:
Show: Fields
Fields: Taxonomy term: Name (link this field to its taxonomy term page)
Filter Criteria: Taxonomy vocabulary: Machine name (=Category)

Answer: Easiest way is to add a relationship in the view to the node type that contains the taxonomy term reference field and make it mandatory. This will force Views to only return the taxonomy terms that are present on a node.

Edit your view
Expand "advanced" (if its not already expanded)
Click "Add" beside Relationships
Click "Taxonomy term: Representative node"
Click "Require this relationship"
Click "Apply"

Note: I used the representative node vs the content with term option for performance reasons, the former only retrieves a single node for each term vs matching every term to every node
Comment: I test your solution with my vocabulary and don't work as expected
Comment: @Adrian Cid Almaguer - this worked well for me as far as I can tell. How didn't it work for you?
Comment: @Sage I see now the reason, I have the i18n module and maybe with this module is necesary other configuration. You know it Jason Reid?
Answer: Go to the Advanced Settings in the view and click in the  Theme: Information

Search the Field Taxonomy term: Name (ID: name) section and select a name, in my case was views-view-field--temp.tpl.php
Go to the folder YOUR_SITE/sites/all/modules/views/theme and copy to your theme folder the file views-view-field.tpl.php and rename it to views-view-field--temp.tpl.php
Edit your new file views-view-field--temp.tpl.php and put inside only this code to eliminate the link:
The taxonomy_select_nodes() function will return an array of nids matching the query.
<?php

if(count(taxonomy_select_nodes($row->tid)) > 0) {
  print $output;
} else {
  print $row->taxonomy_term_data_name;
}

?>

In the View go to the bottom of the Information window and click Rescan template files and click OK, then save your View.

And go to see your result:
My example:

If you don't want to show the taxonomy items without associated nodes use this code:
<?php

if(count(taxonomy_select_nodes($row->tid)) > 0) {
  print $output;
}

?>

And your output will be this:

PS: You must copy your .tpl file to the folder of your active theme, then rename in this folder.
Comment: Thanks I appreciate your suggestions. I'm not I think naming my tpl file correctly because when it rescans it doesn't show a new template in the list and it also doesn't change my view.
Comment: @Sage you must copy your .tpl to the folder of your active theme, then rename in this folder.


Computing Absolute and Relative Error Using Double Precision

Question: Relevant definitions:
If $\tilde a$ is an approximation of $a$, then the absolute error of $a$ is
$$ |\tilde a - a| $$
and the relative error of $a$ is
$$ \frac{| \tilde a - a|}{a} .$$
Statement of the Problem:
Consider the function $f(x) = \sqrt{x+1} - 1$. Assume that we have a good implementation of square root, so that if $y = \sqrt{x}$, then the relative error in $\sqrt{x}$ is no bigger than the relative error in $x$ or $y$. That is, $\sqrt{x}$ can be computed as accurately as possible, given the scheme we are using for representing numbers on the computer.
Using double precision, roughly how accurately can a computer calculate $f(1)$? Give the absolute and relative error.
Where I Am:
I'm not sure what is being asked of me here. We have that using double precision numbers is roughly equivalent to working with $16$ significant digits in base $10$. Now, computing $f(1)$ to $16$ significant digits is
$$ f(1) = \sqrt{1+1} - 1 = \sqrt{2} - 1 \approx 0.414213562373095.  $$
So, am I just being asked to compute
$$ |\tilde a - a| = |0.414213562373095 - (\sqrt{2} - 1)  | $$
for the absolute error, and
$$ \frac{|\tilde a - a|}{a} = \frac{|0.414213562373095 - (\sqrt{2} - 1)  |}{\sqrt{2} - 1} $$
for the relative error?
If so, any method of computing it would involve, well, a computer that itself is likely only accurate enough to compute $f(1)$ to $16$ significant digits, so it seems somewhat pointless. Otherwise, just presenting the above results as a solution seems incomplete (and rather pointless in itself).
Perhaps someone more familiar with numerical analysis could help me out here.
Comment: dont forget parentheses when doing minus
Comment: @mathreadler Whoops! Thanks. Edited.
Comment: Other than that I think you are doing it right. It is probably just a warm up exercise to learn what absolute and relative errors are so you learn it.
Comment: @Hellen Is double precision not a type of floating point representation? (That I'm not sure should give you an idea of how little I know about this subject...)
Comment: Yes double precision is an IEEE floating point standard. 64 bits of which 52-53 something are mantissa. Slightly below 16 decimals precision since $\log_{10}(2^{53}) \approx 15.9$.
Answer: The point is that you computed $\sqrt 2$ to $16$ decimal digits, so the relative error is about $10^{-16}$.  When you subtracted $1$ the difference has only $15$ decimal digits, so the relative error is about $10^{-15}$.  This is not much of a loss in this case, but if you were to subtract an exact $1.41421$ from $\sqrt 2$ you would lose six digits and the relative error would increase by a factor of about a million.  Yes, you are being asked to compute just what you say.  I suspect that there is another exercise coming with much worse cancellation.  You will then be shown the advantage of removing the cancellation analytically.


Valor de variável diferente em sub-select

Question: Tenho a seguinte query:
SET @VAR = 'N';
SELECT 'TESTE1','OI',@VAR := 'S' AS T
UNION ALL
SELECT 'TESTE2','OI',@VAR AS T
UNION ALL
SELECT *  FROM (  SELECT 'TESTE3','OI',@VAR AS T ) AS TAB
UNION ALL
SELECT 'TESTE4','OI',@VAR AS T

Alguém pode me explicar o por quê de o valor de "TESTE3" ser "N" e para os demais, "S"? E também, como contornar o problema?
Answer: O motivo é simples, independente da ordem em você dispõe os select, o que esta dentro do parentese será executado primeiro, logo, não terá sofrido a alteração feita externamente. Neste caso banco de dados trabalha de maneira semelhante a nos na matemática executando o que esta dentro do parentese primeiro. Lembrando que isso acontece devido a plano de execução calculado pelo banco decidindo executar a consulta nesta ordem.
Você pode testar isso fazendo o seguinte select:
SET @VAR = 'Z';
SELECT 'TESTE1','OI',@VAR AS T
UNION ALL
SELECT 'TESTE2','OI',@VAR AS T
UNION ALL
SELECT *  FROM (  SELECT 'TESTE3','OI',@VAR := 'N' AS T ) AS TAB
UNION ALL
SELECT 'TESTE4','OI',@VAR AS T

Que retornara:
TESTE1  OI  N
TESTE2  OI  N
TESTE3  OI  N
TESTE4  OI  N

Ele te ajudará a notar que a alteração realizada dentro do parentese foi executada primeiro, por isso os demais registro sofrem a mesma alteração da variável.
Dito isso a maneira de contornar o problema, é entendendo este conceito e passando as alterações para o escopro interno, igual eu fiz no exemplo para te mostrar a solução, isso deve bastar para corrigir o problema.
Comment: Neste caso você deve colocar a alteração dentro de um subselect se possível. Deve sempre pensar no que quer que execute primeiro
Comment: @CleberGriff somei a solução de contorno a resposta da questão para deixa-la melhor explicada, atendendo sua duvida.
Comment: Perfeito! Devo esperar mais 21 horas para conceder a recompensa, mas já é sua. Obrigado!
Comment: shoooooooooooow
Comment: Boa, Luiz! Mas tem alguma sugestão para contornar o problema?


Is there a product.tpl.php for ALL product types in Drupal Commerce?

Question: Or do you need product-type1.tpl.php, product-type2.tpl.php, etc? I would like to theme every single product on the site but there are multiple product types.
Comment: Typically you would have a content type per product type for the sake of CMS. You can theme by content type.
Comment: Yeah product types are actually content types. Are you now saying you think product/content-type1.tpl.php is the only way to do it across all products?
Comment: Please see answer.
Answer: You could do the following in your theme processing...
<code>function YOURTHEME_process_node(&$vars) {

    //dsm($vars);
    //dsm($vars['theme_hook_suggestions']);

    // If some node type then...
    if ($vars['node']->type) {
                // add a template suggestion
        $vars['theme_hook_suggestions'][] = 'node__product';

    }

}
</code>
Then you add a template file 'node--product.tpl.php'.


Align the select and Input and Button HTML elements in one row

Question: Can some one help me lining Select Drop down, Input and Submit button in one row.
I am getting only Input and Button aligned in row but Select is going upside.
I tried below in CSS but didn't work
display : inline;

Can you please help to modify the CSS to align all in one row.
Demo
Answer: I found the solution ,I just need to make
inline-flex =>inline-flex makes the container inline while still retaining the flex layout properties.
display : inline-flex;

Answer: Your example is a bit everywhere. Also, "selecter" should be spelled "selector", but that is beside the point. Use more
 elements to wrap around smaller code segments. For example:

Hello

Stack

Overflow!

Normally, these
's would display underneath one another. However, if we add a styling rule similar to the one you're using, we will get the result of these three elements together on one line.
.item {
    display: inline-block;
}

Wrap your button elements in a
 container and style them with the above. Does this answer your question?


Direct integration of a complex integral

Question: In my homework there is a integral looks so strange, this is the first time that I see this kind of thing. So I have no idea what to do.
$\int_{0}^{-1+i\infty}(z+1)e^{iz}dz$
What does it mean the upper part of integral $-1+i \infty$? And how can i solve it?
I tried to take integral respect to $z$. Then i wrote $z=x+iy$ and put from $0$ to $-1$ for all x and put from $0$ to $\infty$ for all y. Am I right?
Comment: Observe that the function $(z+1)e^{iz}$ is analytic, so that the integral does not depend on a path. The simplest way is to use the antiderivative.
Answer: It is better to consider first
$$I_p=\int_{0}^{-1+ip}(z+1)\,e^{iz}\,dz$$ Expandin the integrand, one integration by parts gives the antiderivative and using the bounds
$$I_p=e^{-(p+i)} (p+1)-(1-i)$$ Now, take the limit when $p\to \infty$.
Comment: when p goes to $\infty$, $e^{-\infty}=0$ so left side is $0$ and $i-1$ is the answer, right? I found exactly the same with the method I said


String text alignment by decimal point (Swift)

Question: Is there a way to achieve such kind of alignment of numbers in multiple strings, preferably in interface builder? Please see the attached screenshot.
Comment: The easiest way would probably be to use a fix-width typeface, and pad out your numbers with spaces as necessary. Not sure of any better or more-proper ways.
Comment: You can make it work with a non-fixed width font by splitting each number into two labels - one for the whole number part and one for the decimal part.
Comment: SwiftUI or UIKit?
Comment: @JoakimDanielson Hey! UIKit.
Comment: @HangarRash I was thinking of something like that. But I then will need to use these figures for further calculations and I thought that splitting strings and putting them back together, as well as converting Int<->String multiple times would turn into a nightmare for me.
Comment: @CalebGates There would be none of that. Your data would be stored as `Int`. Those `Int` values would be used for all calculations. Only when displaying the aligned labels would you need to convert each `Int` into two `String` values to put in labels. The strings would never be used as data storage. There would never be a need to put them back together. You already need to convert each `Int` into one `String` for display in a label. I'm just suggesting using two string and two labels per `Int`. Small change.
Comment: @HangarRash Interesting. So should I use a horizontal stackview with three elements with the decimal dot in the middle? Thanks for the advise, will try it now
Comment: @HangarRash but how would I go about integers? I don't want to see a decimal in this case at all
Comment: I was thinking of using two vertical stack views side-by-side. The left stack for the integer portions and the right stack for the decimal portions. For integers you would just use an empty string for the 2nd string of the value.
Comment: What type(s) are the underlying values? What is the difference between the first and the third value in the screenshot, if the first is a floating number then how do you know it has two decimals?
Answer: One approach to achieve this is by using a table view and programmatically adding constraints to align the separator symbol. This method offers scalability as it only includes elements visible on the screen. An interesting aspect of this approach is that the separator's position may change based on the largest offset currently on the screen. Whether this behavior is desired or not depends on your specific requirements.
In this solution, I suggest splitting the string into three components and placing them into three separate labels: one for the content before the separator, one for the separator itself, and another for the content after the separator. Additionally, create an invisible reference view at the top level, which will be used to connect the separator label.
Although the following code is implemented programmatically for clarity in understanding constraint connections, it is recommended to move most of the code into the storyboard for better organization and maintainability.
I hope this code snippet helps you solve your problem.
<code>class OffsetNumberViewController: UIViewController {

    var values: [NSDecimalNumber] = [] {
        didSet {
            tableView.reloadData()
        }
    }

    private lazy var tableView: UITableView = {
        let view = UITableView()
        view.delegate = self
        view.dataSource = self
        return view
    }()

    private lazy var numberFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.decimalSeparator = "."
        formatter.usesGroupingSeparator = true
        formatter.groupingSeparator = ","
        formatter.groupingSize = 3
        formatter.maximumFractionDigits = 5
        return formatter
    }()

    private lazy var referenceView = {
        let view = UIView()
        view.isHidden = true
        self.view.addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        self.view.addConstraints([
            .init(item: view, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0.0),
            .init(item: view, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0.0),
            .init(item: view, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0.0)
        ])
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(NumberTableViewCell.self, forCellReuseIdentifier: "amountCell")
        tableView.frame = view.bounds
        view.addSubview(tableView)

        values = generateRandomValues(count: 1000)
    }

    private func generateRandomValues(count: Int) -> [NSDecimalNumber] {
        (0..<count).map { index in
            let startValue: Int = 1234567890
            let maximumDivision = 5

            let randomDivision: Int = 1<<Int.random(in: 0...maximumDivision)
            return .init(integerLiteral: startValue).dividing(by: .init(integerLiteral: randomDivision))
        }
    }

    private func formatValue(_ value: NSDecimalNumber) -> String {
        numberFormatter.string(for: value) ?? "NaN"
    }

}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension OffsetNumberViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        values.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "amountCell", for: indexPath) as? NumberTableViewCell {
            cell.setup(withNumberAsString: formatValue(values[indexPath.row]), decimalSeparator: numberFormatter.decimalSeparator)
            return cell
        } else {
            return UITableViewCell()
        }
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        (cell as? NumberTableViewCell)?.attachCenterTo(referenceView, parent: self.view)
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        (cell as? NumberTableViewCell)?.detachExternalConstraints()
    }

}

// MARK: - NumberTableViewCell

extension OffsetNumberViewController {

    class NumberTableViewCell: UITableViewCell {

        lazy private var leftSideLabel: UILabel = UILabel()
        lazy private var rightSideLabel: UILabel = UILabel()
        lazy private var separatorLabel: UILabel = UILabel()

        private var currentExternalConstraints: [NSLayoutConstraint] = []

        lazy private var stackView: UIStackView = {
            let stackView = UIStackView()
            stackView.translatesAutoresizingMaskIntoConstraints = false
            stackView.alignment = .fill
            stackView.axis = .horizontal
            stackView.distribution = .fill

            stackView.addArrangedSubview(leftSideLabel)
            stackView.addArrangedSubview(separatorLabel)
            stackView.addArrangedSubview(rightSideLabel)

            addSubview(stackView)

            addConstraints([
                .init(item: stackView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: -12.0),
                .init(item: stackView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0),
                .init(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0),
            ])

            return stackView
        }()

        func setup(withNumberAsString numberString: String, decimalSeparator: String) {
            let components = numberString.components(separatedBy: decimalSeparator)

            let _ = stackView

            separatorLabel.text = decimalSeparator
            if components.count == 1 {
                leftSideLabel.text = components[0]
                rightSideLabel.text = ""
                separatorLabel.alpha = 0
            } else if components.count == 2 {
                leftSideLabel.text = components[0]
                rightSideLabel.text = components[1]
                separatorLabel.alpha = 1
            } else {
                // Something went wrong
                leftSideLabel.text = ""
                rightSideLabel.text = "error"
                separatorLabel.alpha = 0
            }
        }

        func detachExternalConstraints() {
            currentExternalConstraints.forEach { constrain in
                constrain.isActive = false
            }
            currentExternalConstraints = []
        }

        func attachCenterTo(_ referenceView: UIView, parent: UIView) {
            currentExternalConstraints = [
                .init(item: separatorLabel,
                                           attribute: .centerX,
                                           relatedBy: .greaterThanOrEqual,
                                           toItem: referenceView,
                                           attribute: .centerX,
                                           multiplier: 1.0,
                                           constant: 0.0),
                .init(item: referenceView,
                                           attribute: .centerX,
                                           relatedBy: .greaterThanOrEqual,
                                           toItem: separatorLabel,
                                           attribute: .centerX,
                                           multiplier: 1.0,
                                           constant: 0.0)
            ]
            parent.addConstraints(currentExternalConstraints)
        }

    }

}
</code>
Comment: I suggest not hardcoding most of the number formatter settings. The code should handle any locale.


Apply function for objects from "yield from" statement in python

Question: # currently I have this code

def some_func():
    for match in re.finditer(regex, string):
        yield other_func(match)

I was wondering if there was a way to squash it into one line
# looking for something like

def some_func():
    yield from other_func(re.finditer(regex, string))

Answer: You can use map. The map accepts two parameters: a function and an iterable. It iterates the iterable and apply the function and returns an iterator (which yields mapped values - function(first item), function(seoncd item), ...)
def some_func():
    yield from map(other_func, re.finditer(regex, string))

yield from here is not necessary, because the map returns an iterator (in Python 3.x):
def some_func():
    return map(other_func, re.finditer(regex, string))

Example:
>>> import re
>>>
>>> def other_func(match):
...     return match.group()
...
>>> def some_func():
...     return map(other_func, re.finditer(regex, string))
...
>>> regex = '.'
>>> string = 'abc'
>>> list(some_func())
['a', 'b', 'c']

Answer: For something simple and short you can return a generator expression which basically is the same as yield,
def some_func():
    return (other_func(match) for match in re.finditer(regex, string))


Why does dependent random variables seem independent?

Question: The number of particles $N$ emitted by a radioactive source per a unit of time has a Poisson distribution with parameter $\lambda$. Next to the source there placed a Geiger counter that reveals every particle with probability $p$, independently. Let $M$ be the number of particles revealed by the counter. If we know that $n$ particles were emitted, find the probability that $k$ of them were revealed, that is to say, find: $p(M=k|N=n)$.
The answers only say: Bin$(k,n)$. I stated: ${p(A\cap B)\over p(B)}={{e^{-\lambda}{\lambda}^{n}\over n!}\cdot {n\choose k}p^k{(1-p)^{n-k}}\over {e^{-\lambda}{\lambda}^{n}\over n!}}=$Bin$(k,n)$, but wouldn't that mean $p(A|B)=P(A)$? Here $A=(M=k)$ and it cannot happen without using $N$. There is something here I miscomprehend, and I would appreciate it if you gave me an explanatory perspective on it.
Comment: Is it right, that $P(A|B)=P(A)$. Therefore $P(A\cap B)=P(A)\cdot P(B)$.
Answer: $P(A)$ is stated incorrectly. For a fixed value of $k$ you need to sum over the appropriate values of $n$.
Addition:  Here are the relevant equations:
$$p(A|B)=p(M=k|N=n)={n\choose k}p^{k} (1-p)^{n-k}$$
$$p(B)=p(N=n)=e^{-\lambda} \lambda^{n}/n!$$
$$p(A)=p(M=k)=\sum_{k=n}^{\infty} p(M=k|N=n)p(N=n)=e^{-p\lambda} (p\lambda)^{k}/k!$$
So the marginal distribution of $M$ is a Poisson with mean $p\lambda$.
Comment: You are correct. Is the overall computation to find the conditional probability correct, though?


MapView and Autocomplete Can't get layout to work

Question: I can not get the layout to work for this.
I have a mapview that works fine with this layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/rel_layout_mapview">

 <org.osmdroid.views.MapView
      xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
     />

<ImageView android:id="@+id/drag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ss_pin"
android:visibility="gone"
 />

No problems, but as soon as I try to get a autocomplete above it, it does not work.
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<AutoCompleteTextView android:id="@+id/autocomplete_country"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@+id/rel_layout_mapview">

<org.osmdroid.views.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
     />

<ImageView android:id="@+id/drag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ss_pin"
android:visibility="gone"
/>

</RelativeLayout>

</LinearLayout>

Can someone point me in the right direction of how to do a layout with a mapview and a autocomplete above it.  The mapview must be in it's OWN relative view, because I have a lot of code specific to referancing the parent of the mapview for calculations.
Thanks!
Answer: I was able to solve it simply by setting the margins.
<FrameLayout   xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
  <LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
         android:layout_height="50dip" >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <AutoCompleteTextView
        android:id="@+id/locationsearch2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter zipcode or address"
        tools:context=".AutoCompleteDynamic" />

</RelativeLayout>

  </LinearLayout>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/rel_layout_mapview"
  android:layout_marginTop="50dip">

   <org.osmdroid.views.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
         />

<ImageView android:id="@+id/drag"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ss_pin"
    android:visibility="gone"
  />
</RelativeLayout>

</FrameLayout>


How to prove that $2x$ is integer too?

Question: Let  $x , y, z$ are rational and  $x^2+y^2+z ,\ y^2+z^2+x,\ x^2+z^2+y$ are integers.
How to prove that $2x$ is integer too?
I know that $$(z-y)(z+y-1)=a,\ (y-x)(y+x-1) = b,\ (x-z)(x+z-1)=c$$
such that  $a,b,c \in \mathbb{Z}$.
Comment: I don't know if it helps, but I'd try the following change of variables: $x=x'+\frac{1}{2}, y=y'+\frac{1}{2}, z=z'+\frac{1}{2}$. I feel like this would make things easier.
Answer: For simplicity, for a prime $p$, Let $\mbox{ord}_p(x)$ be an integer such that $p^{-\mbox{ord}_p(x)}\cdot x$ does not contain factor $p$ both in numerator and denominator. The question is equivalent to saying that $\mbox{ord}_p(x) \geq 0$ for any odd prime $p$ and $\mbox{ord}_2(x) \geq -1$ (the same for $y$ and $z$, by symmetry).
Suppose $p$ is an odd prime such that $\min\{\mbox{ord}_p(x),\mbox{ord}_p(y),\mbox{ord}_p(z)\} = -n < 0$. There exists a $d \in \mathbb Z$; $p\!\not | d$ such that $x' := dp^nx$, $y' := dp^ny$ and $z' := dp^nz$ are integers. Observe that $p|(x'^2 + y'^2)$, $p|(y'^2 + z'^2)$ and $p|(z'^2 + x'^2)$. This immediately implies $p|x'$, $p|y'$ and $p|z'$ which leads to a contradiction.
Similarly, if we consider the case $p = 2$, and suppose that $\min\{\mbox{ord}_2(x),\mbox{ord}_2(y),\mbox{ord}_2(z)\} = -n < -1$. There exists a $d \in \mathbb Z$; $2\!\not | d$ such that $x' := d2^nx$, $y' := d2^ny$ and $z' := d2^nz$ are integers. Then $4|(x'^2 + y'^2)$, $4|(y'^2 + z'^2)$ and $4|(z'^2 + x'^2)$. This immediately implies $2|x'$, $2|y'$ and $2|z'$ which leads to a contradiction.
Comment: In the last sentence of the first paragraph, shouldn't it be $\mathrm{ord}_p(x)\leq 0$ and $\mathrm{ord}_2(x)\leq 1$?
Comment: Thanks for pointing out. The definition had a typo, and I corrected it. It should be something like $\mbox{ord}_3(9) = 2$ and $\mbox{ord}_3(5/54)=-3$.

How to prove that $2x$ is integer too?


Adding more than 20 CNAMES/custom domains to point to a Firebase hosting endpoint

Question: We currently have a self-hosted solution that allows our customers to add CNAMES to access their content through their own domains.
We're moving the entire stack to Google Cloud, with the main product residing on a Firebase Hosting deployment, with serverless functions, storage and Firestore databases.
I am aware that we can manually and programatically add CNAMES to our Firebase hosting account, but there is a hard limit of 20 on Firebase.
My question: does GCP offer a solution where we can programatically add CNAMES, generate a self signed certificate, and point them via a proxy to our Firebase hosting URL, while retaining the originating CNAME, but serving our Firebase content? Or recommended approaches for this stack?
Things we don't want to do:

have multiple Firebase deployments with 20 domains each
Add any hosted solutions (compute engine etc) as an intermediary
Move away from Firebase

We have reached out to the Firebase team but was recommended point 1 above, split them between multiple deployments as they had no visibility to other GCP products.
Comment: I don't see how anyone other than GCP/Firebase can know what solutions GCP/FIrebase are offering.
Comment: Host your own Authoritive DNS and add anything you want.
Comment: The best place to ask what solutions GCP offer would be at GCP support.
Comment: @Overmind - your comment is incorrect. Firebase custom domains must be configured. Anything else will fail. The reason is that most GCP services are fronted by GFE/Load Balancer which uses the HTTP Host header to direct traffic. Unconfigured host names are considered invalid.
Comment: Thanks Jenny, GCP support points us to Firebase, Firebase points us to GCP. ¯\_(ツ)_/¯
Comment: Hi Overmind, CNAMES not added to Firebase hosting, does not resolve. We cannot just simply add a CNAME and point it to our Firebase hosting. Or am I missing your suggestion?
Comment: I have been experimenting with GCP since I asked yesterday and came up with a workable solution:

1. Deploy our site code to a Cloud Run container
2. Change our Firebase rewrite config to point to the cloud container, and not the serverless function it currently points to
3. Programatically map new domains and CNAMES using the Cloud Run API for domain mappings.

We cannot find any hard limits on domain mappings within the Cloud Run documentation, as you are able to point multiple domains to a single service.

Any areas of concern with an approach like this?
Comment: Cloud Run is in beta. I am not aware of a published metric for the number of custom domains that you can configure. However, I expect that Cloud Run will have the same limits that Firebase does when the service reaches GA. The reason is that neither Firebase nor Cloud Run manage the custom domains. This is performed by the GFE/Load Balancer which is implemented globally for many Google Cloud services. I have started a deep dive article series on my website covering Cloud Run. In my first article, I discuss the Cloud Run components including GFE. https://www.jhanley.com
Comment: I have indeed found your articles and will def read a little deeper. Many thanks for your inputs.
Comment: This is a specific feature of a specific service. There's not much you can do about it's limitations. As I said, if you want to do what you want you should have a completely different approach and not use a service that has such limitations.
Comment: @Overmind My question is not regarding skirting Firebase limits, but what *other* GCP tool we can use to accomplish this. Apologies if not clear.
Comment: Yes, but product recommendations are unfortunately offtopic; why not simply ask some cloud service providers for a solution ?
Answer: The answer to your question is not how many hostnames Firebase can support, but how many hostnames SSL can support.
The SSL certificate recommendation is that no more than 20 entries be placed in the SAN field of an SSL certificate. This is called SSL certificate minting limits. Some SSL certificates do support up to 100*, but Firebase supports 20. The more entries, the more overhead to process each connection. Each time you add a new domain to the certificate all of the existing domains have to reverified as a new certificate is issued.
Note: I am not including wildcard (*.example.com)
*Note: RFC 5280 does not specify a maximum for SubjectAltNames. Microsoft imposes a maximum size of an encoded extension to be 4KB (link).
Comment: Thanks John, as mentioned in my original post, we're aware of the hard limit, but your explanation makes it clear *why* there is a limit.
Comment: Can you provide a citation as to the "technical limit" of 100 subjectAltName entries in a single TLS certificate?


Show $\alpha$ is selfadjoint.

Question: Question: Let $V$ be an inner product space finitely generated over $\Bbb C$ and let $\alpha$ be an endomorphism of $V$ satisfying $\alpha \alpha^* = \alpha^2$. Show that $\alpha$ is selfadjoint.
**Edited after more thought:
I know that in order to be selfadjoint $\alpha^*=\alpha$. Becuase this inner product space is over $\Bbb C$ does it change the proof?
Or, can I show selfadjoint for $\Bbb R$ and then state the proposition that for an inner product space over $\Bbb C$ and an End$(V)$, If $\langle{\alpha(v), v}\rangle \in \Bbb R$ for all $v \in V$, then $\alpha$ is selfadjoint.
Answer: Let $v,\:w\in V$, and so we have,
$$ \big\langle (\alpha^*)^2(v), w\big\rangle=\big\langle v,\alpha^2(w) \big\rangle=\big\langle v,\alpha\alpha^*(w)\big\rangle,$$
which implies that $\alpha^2=(\alpha^*)^2=\alpha\alpha^*$. Now we claim that $\alpha\alpha^*=\alpha^*\alpha$.
This is because
 $$\big\langle(\alpha^*\alpha-\alpha\alpha^*)(v),(\alpha^*\alpha-\alpha\alpha^*)(v)\big\rangle=$$
$$\langle\alpha^*\alpha(v),\alpha^*\alpha(v)\rangle+\langle\alpha\alpha^*(v),\alpha\alpha^*(v)\rangle-\langle\alpha^*\alpha(v),\alpha\alpha^*(v)\rangle-\langle\alpha\alpha^*(v),\alpha^*\alpha(v)\rangle=0$$
Thus,
 $$\alpha\alpha^*=\alpha^*\alpha.$$
Now, as
$$\big{\langle}(\alpha-\alpha^*)(v),(\alpha-\alpha^*)(v)\big\rangle=$$
$$\langle\alpha(v),\alpha(v)\rangle+\langle\alpha^*(v),\alpha^*(v)\rangle-\langle\alpha^*(v),\alpha(v)\rangle-\langle\alpha(v),\alpha^*(v)\rangle=0,$$ we get, $\alpha=\alpha^*.$
Answer: Given $\alpha^*\alpha=\alpha^2$
\begin{align}
\langle{\alpha^*\alpha(v),v}\rangle & =\langle{\alpha^2(v),v}\rangle \\
&=\langle{\alpha(v),\alpha(v)}\rangle \\
&=\langle{v,\alpha\alpha^*(v)}\rangle
\end{align}
Therefore, $\alpha^*\alpha=\alpha^2=\alpha\alpha^*$ and $\alpha=\alpha^*$ over $\Bbb R$.
Now, since V is an inner product space over $\Bbb C$, $\alpha \in End(V)$ has an adjoint, and we hae shown that if $\langle{\alpha(v), v}\rangle \in \Bbb R$
 for all $v \in V$, then we can say that $\alpha$ is selfadjoint. (Taken from Golan, The linear algebra a beginning graduate student ought to know, Proposition 17.2).
Check and constructive criticism greatly appreciated.
Comment: How did you imply that $\alpha=\alpha^*$?
Comment: I took either side of the equation and divided by $\alpha$

Show $\alpha$ is selfadjoint.


Odd behavior when fetching 100K rows from MySQL via PHP

Question: Looking for some ideas here... I have a MySQL table that has 100K rows of test data in it.
I am using a PHP script to fetch rows out of that table, and in this test case, the script is fetching all 100,000 rows (doing some profiling and optimization for large datasets).
I connect to the DB, and execute an unbuffered query:
$result = mysql_unbuffered_query("SELECT * FROM TestTable", $connection) or die('Errant query:  ' . $query);

Then I iterate over the results with:
if ($result) {
    while($tweet = mysql_fetch_assoc($result)) {
        $ctr++;

        if ($ctr > $kMAX_RECORDS) {
            $masterCount += $ctr;
            processResults($results);
            $results = array();
            $ctr = 1;
        }

        $results[] = array('tweet' => $tweet);
    }

    echo "
FINISHED GATHERING RESULTS";
}

function processResults($resultSet) {
    echo "
PROCESSED " . count($resultSet) . " RECORDS";
}

$kMAX_RECORDS = 40000 right now, so I would expect to see output like:

PROCESSED 40000 RECORDS PROCESSED 40000 RECORDS PROCESSED
  20000 RECORDS  FINISHED GATHERING RESULTS

However, I am consistently seeing:

PROCESSED 39999 RECORDS
  PROCESSED 40000 RECORDS

  FINISHED GATHERING RESULTS

If I add the output of $ctr right after $ctr++, I get the full 100K records, so it seems to me to be some sort of timing issue or problem with fetching the data from the back-end with MYSQL_FETCH_ASSOC.
On a related note, the code in the while loop is there because prior to breaking up the $results array like this the while loop would just fall over at around 45000 records (same place every time).  Is this due to a setting somewhere that I have missed?
Thanks for any input... just need some thoughts on where to look for the answer to this.
Cheers!
Comment: Please stop writing new code with the ancient `mysql_*` functions. They are no longer maintained and community has begun the [deprecation process](http://goo.gl/KJveJ) . Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you cannot decide, [this article](http://goo.gl/3gqF9) will help to choose. If you care to learn, [here is a good PDO-related tutorial](http://goo.gl/vFWnC).
Comment: Does this have anything to do with the question?  I don't need the pedantic comments, but rather some insight into the issue being raised.
Comment: Not really, hence its a comment not an answer. It's not pedantic (or not meant to be), there is some interesting reading there that I thought may help. Take it or leave it its up to you.
Answer: You're building an array of results, and counting that new array's members. So yes, it is expected behavior that after fetching the first row, you'll get "1 result", then "2 results", etc...
If you want to get the total number of rows expected, you'll need to use mysql_num_rows()
Comment: Aren't you missing the obligatory scolding for using mysql_?  lol :)
Comment: No, I don't bother to harp on that. If you know what you're doing, writing with the mysql_ functions is as safe (or even safer) than using pdo/mysqli.
Comment: I'm with you brother....as well as that other standard "You need to redesign everything you've ever done on everything you've got to do it the right way", lol
Comment: @MarcB To get mysql_* style code on the same level of security as, for example, PDO, would take *tons* of code. Furthermore, the mysql_* functions are explicitly discouraged from being used on php.net, and have already been subject to numerous talks of imminent deprecation. Promoting use of those functions is not a good idea, regardless of how you feel their security compares to more modern APIs.
Comment: Yes, well, the mysql_ functions are going to be Windows XP of PHP - hangling on farrrrrr past when they should've been executed. there's just too much code out there depending on it. And using PDO is absolutely no guarantee of writing "safe" queries. An idiot can inject themselves just as badly with PDO as they can with any other DB interface.
Comment: No, not missing any scolding.  :)  This is some down-and-dirty testing, not production code.  Although, even in a production situation I will generally roll my own DBI.
Comment: @Raconteur Testing using something completely different from what you are actually going to use is not testing at all.  This is a very poor excuse for using mysql_*.
Answer: When you start going through your result $ctr has no value and doing first incrementation will evaluate it to 0. But when reaching $kMAX_RECORDS you reset it to 1 instead of 0. I don't know however why you see 1 row less in the first time of calling processResults(). I think it should be one more.
As to missing last 20000 rows notice that you are running processResults() only after $ctr exceeds $kMAX_RECORDS
Comment: Thanks Zefiryn, got the counter problems squared away, and now getting expected results.  Any ideas on why the while loop would just fall over after 45000 or so records?
Comment: @Raconteur You could be hitting [memory_limit](http://www.php.net/manual/en/ini.core.php#ini.memory-limit) or [max_execution_time](http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time)
Comment: Cheers, vasco, will check those out.
Comment: memory_limit @ 128M, max_execution_time = 60.  It falls over after about 10s, and always at the 42563rd record (which has no special characteristics), which is around 6MB in the array.
Comment: try setting ini_set('display_errors', 1); and see if there are any errors reporting. Or look into error logs


chrome notification não aparece

Question: Boa noite, estou executando um código para apresentar uma notificação:
if(Notification.permission === 'granted' && !this._active) {
    let n = new Notification(this._activeContact.name,{
       icon : this._activeContact.photo,
       body : data.content
    });

Mas nenhuma notificação está aparecendo!
O que pode estar acontecendo?
A permissão já está positiva
*****editado****
o código q pede a permissão é esse:
alias, não está funcionando no edge...
checkNotifications(){
    // debugger
    if (typeof Notification === 'function'){
        if (Notification.permission !== 'granted'){
            this.el.alertNotificationPermission.show()
        } else {
            this.el.alertNotificationPermission.hide()
        }

        this.el.alertNotificationPermission.on('click', e=> {
            Notification.requestPermission(permission => {
                if (permission === 'granted') {
                    this.el.alertNotificationPermission.hide()
                    console.info('notificações permitidas!')
                }
            })
        })
    }
}

Answer: Já tentou fazer a chamada dele usando requestPermission?
Notification.requestPermission()

Comment: sim lucas, eu tenho um método que está fazendo isso... vou editar a pergunta pra mostrar!!

chrome notification não aparece


Data Transfer From JavaScript App to Rails Server

Question: I have a JavaScript app that produces a string. I want to transfer this string back to my server and assign it to a particular attribute. Apparently AJAX can accomplish this. Unfortunately, I'm a novice with both Rails and AJAX, and I can't find any clear instructions on how to implement the transfer. Is there a simple, standard way to send a string to a Rails server and assign it to a model attribute?
At the moment, the code is inserted directly in my JavaScript function. It looks like this:
<code>$.ajax({
  type: 'POST',
  url: '/bookcases/'+window.location.href.split('/')[4],
  data: {'_method':'put', 'bookcase[imagemap]':mapcode},
  dataType: 'html',
  success: function() {alert( "Data Saved" );}
});
</code>
Firebug gives me a 404 Not Found error. I've tinkered with the URL a bit, replacing 'edit' with likely candidates like the name of the attribute and POST. I've also removed 'edit' all together. So far I consistently get the same error. The only exception is when I set the URL to '/', at which point the success message pops up. Unfortunately, the mapcode data has not actually been implanted.
Comment: You should improve the question with something you've tried and didn't work. Questions that show you've tried something are more likely to be answered
Comment: Question is too broad, have you been able to create an AJAX request yet?
Comment: I haven't, though I have a sense of what the code would look like based on [this link](http://guides.rubyonrails.org/ajax_on_rails.html) and [this link](http://www.activars.com/2009/04/13/pass-javascript-variables-to-rails-controller/). I'm unsure where to insert this code, though.
Comment: I've updated the question with a code snippet. I'm basing this code on a question I found [here](http://stackoverflow.com/questions/5512744/ajax-call-is-only-sending-last-item-and-not-entire-array).
Comment: Question. Is the "Javascript App" and the Rails App two completely different thing? Or are you just trying to implement a javascript action in your rails app?
Comment: The JavaScript is not in the asset pipeline, but executed directly from a Rails view. (Bad practice, I know, but putting it in the pipeline was causing a whole host of errors.)
Comment: I believe I'm on the right path. After reading Stevo's comment [here](http://apidock.com/rails/ActionView/Helpers/FormTagHelper/select_tag), I think I've got the right parameters plugged in. I'm still getting the 404 error, but I think it might be due to something in my routes.rb file. If you think that's the case, I'll post it. Right now, the bookcase route is generically set at "resources :bookcases".
Answer: Got it! Apparently, the above code was working just fine. I just needed to add an update method to my controller. For those working through a similar issue, Firefox's Firebug is invaluable. If you're encountering an error in JavaScript, Firebug will show you what the cause is. I couldn't have figured this out without it.


how to weight means based on data set size

Question: Let's say I have a list of lists of integers, all of a large variance in length, and I want to get the weighted mean of each record. How would I go about doing that?
For example:
<code>record_a = [1];
record_b = [8, 7, 5, 6, 7, 2, 9];
record_c = [8];
record_d = [8, 4, 5];
record_e = [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,]
</code>
There will always be under 10,000 records in this list
To clarify, for instance if I want to compare the mean of record E and record A there is a large difference in data and I am not sure how to weight to account for that.
Comment: Hi Aria. Welcome to CV. When you say "weighted mean", what are you weighting by?
Comment: If you just want the mean, and some measure of uncertainty, you can take the mean and standard error of each `record_i` (noting that the SE doesn't exist if you only have one number in a record such as `a` and `c`)
Comment: @AlexJ Sorry for the confusion, I am basically calculating win-rates for a game based on a unique team. Some teams have 1 games, while others have many games and so it seems unfair to compare the means of the two straight up knowing ones data set is much more vast.

I am wondering how I could say compare the winrate of a team with 2 games, and the a team with 100 games while making sure its balanced.
Comment: Also I should note I am not extremely math literate, so sorry if this is a silly question to begin with.
Answer: Use the mean and standard error for each record.
For example, record b: the mean is 6.29 and the standard error ($=\frac{\text{sample standard deviation}}{\sqrt{n}}$) is 0.87. Contrast this to record d: the mean is 5.67 and the standard error is 1.3. So, if we wanted to compare them, we can say we are a lot more certain about the win rate for team b, compared with that for team d.
There is a lot of available information on standard errors on the Internet.
Comment: Awesome thanks!


Parallel transport on the Group manifold

Question:
We think of the group as a manifold G (called a Group manifold), whose points are the elements of our Lie group. More generally, we could think of any manifold H on which the elements act
as smooth transformation
The infinitesimal group elements are to be pictured as particular vector fields on G (or, indeed, H). That is, we think of 'moving G' infinitesimally along the relevant vector field $\zeta$ on G, in order to express the transformation that corresponds to pre-multiplying each element of the group by the infinitesimal element
represented by $\zeta$.

...
The relevant notion of 'parallelism' comes from the group action, supplying the needed notion of 'parallel transport', which
actually gives a connection with torsion but no curvature.
Page-312, 313 Roger Penrose's Road to Reality

Could someone explain what Penrose is meaning by the bolded part? I understand the group action is to move the points under flow of vector field but what does mean for the parallelism to come from it?
I have read these answers but found the discussion to be too algebraic. Could a more visual understanding of what's going on be provided?
Comment: How about Alexander Thumm's answer in the linked question?  I think this answer follows the definition of parallel transport in a more friendly way
Comment: Helpful, but I felt that it doesn't really a give a geometric picture for how the parallel transport or curvature is considered here @onriv
Answer: The connection that Penrose is referencing is called the Maurer-Cartan connection, defined by the Maurer-Cartan form $\theta\in\Omega^1(G,\mathfrak{g})$. The assertion that the connection has no curvature is known as the Maurer-Cartan equation, which states that
$$d\theta+\frac{1}{2}[\theta,\theta]=0$$
Edit: The Maurer-Cartan form is defined in the most natural way you could imagine, since we have a group structure on $G$. Denote left multiplication with $g$ by $L_g$, which is a map $G\to G$. We define the $1$-form as $\theta_g(v):=dL_{g^{-1}}v\in T_eG=\mathfrak{g}$, which gives rise to a Lie algebra valued $1$-form. This allows us to identify the fibres of the tangent bundle with one another, which is equivalent to the data of a connection which we denote $\nabla$. A vector field $X$ is called "parallel" or "horizontal" along a curve $\gamma:I\to G$ if it satisfies
$$\nabla_{\dot{\gamma}}X=0$$
The way in which one might think about this geometrically, is as follows. On Euclidean space, it is quite clear when we should call a function flat in a certain direction: when its directional derivative vanishes. However, on vector bundles over manifolds, there is generally no canonical way to choose a directional derivative, i.e. a way to differentiate sections along vector fields. This is what a connection does. The way we can think about parallel sections, then, is by thinking about them as being constant with respect to the chosen connection.
On a Lie group, we have a canonical way of choosing such a connection, because the (left or right) invariant vector fields give us a trivialisation of $TG$, and this connection is the Maurer-Cartan connection. Perhaps even more concretely, the connection is defined by declaring that the invariant vector fields are its flat/parallel sections. The connection is determined by this, using the Leibniz rule and the trivialisation of $TG$ by invariant vector fields. Note: the Maurer-Cartan connection typically does not coincide with the trivial connection on a trivial bundle $G\times\mathbb{R}^k$, although both connections are flat. For example, work out the cases $G=(\mathbb{R},+)$ and $G=(\mathbb{R}_{>0},\times)$, which are isomorphic as Lie groups. Draw the flat sections, as functions $f:\mathbb{R}\to\mathbb{R}$ in each case.
Comment: @onriv Yes: Since left-invariant vector fields are parallel, so are all left-invariant tensors, including all left-invariant metrics.
Comment: Thank you for sharing your knowledge. Could you please add more about how to think about the connetion and the underlying geometric intuition of it, if any?
Comment: I have updated the answer to reflect more geometric intuition, I hope that helps.
Comment: Is the Maurer-Cartan connection a metric connection?
Answer: It's also helpful to contrast with the situation on an arbitrary smooth manifold $M=M^n$. In the category of smooth manifolds, every smooth manifold $M$ has an associated tangent bundle $TM$, where each tangent space $T_xM \cong \mathbb R^n$, but there is not a canonical isomorphism of tangent spaces $T_xM\cong T_yM$.
In Riemannian geometry, we add a Riemannian metric to $M$ (i.e. a certain two-form with some conditions imposed on it) to allow us to measure the angles and distances between vectors in the tangent space to $M$. We can go even further by equipping $M$ with an affine connection $\nabla$, and an associated parallel-transport map $P_{x\to y}:T_xM\cong T_yM$, which we remember is determined by the extra data of the connection $\nabla$. The parallel-transport map is a canonical isomorphism of tangent spaces, but only up to the choice of a connection $\nabla$. It would be especially nice if there were a natural canonical choice for a canonical isomorphism of tangent spaces.
Any Lie group $G$, which is a smooth manifold with a smoothly compatible group structure, does have a natural notion of parallelism (i.e. natural identification of tangent spaces) which is described nicely in the other answer.


Hide/Show Toolbar programmatically on CoordinatorLayout

Question: When I scroll my RecycleView ToolBar hide or show (with animation).

How I can return ToolBar back programmatically?
Answer: If your toolbar is inside an AppBarLayout which is probably inside your CoordinatorLayout then something like this should work.
AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.appBar);
            appBarLayout.setExpanded(true, true);

Or to collapse it
AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.appBar);
            appBarLayout.setExpanded(false, true);

Here is the definition
setExpanded(boolean expanded, boolean animate)

Take note that this method is available from v23 of the support library, here is some documentation for reference, the key thing to note is "As with AppBarLayout's scrolling, this method relies on this layout being a direct child of a CoordinatorLayout."
Comment: I have tried these, still not working.  better solution is show and hide the CollapsingToolbar  and set the AppBarLayout params dynamically.

Do this when ever you show/hide the CollapsingToolbarLayout

mAppBar.setLayoutParams(new CoordinatorLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
Answer: Is that what you looking for?
Toolbar toolbar = findViewById(R.id.toolbar);  // or however you need to do it for your code
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
params.setScrollFlags(0);  // clear all scroll flags

link: How to enable/disable toolbar scrolling programmatically when using design support library
In order to hide the Toolbar your can just do something like this:
toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();

If you want to show it again you call:
toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();

Comment: @johnarao07 hi man! Thanks for answer but it doesn't work for me. And this solution disable hiding/showing for toolbar. I want just show/hide whithout disabling
Comment: @ArtemShevchenko did you solve your problem? I am facing similar issue
Answer: My problem was very similar to @Artem I tried many fix but none of them worked for me. @Jraco11's answer is correct when you use AppBarLayout. @johnrao07 not worked for me. But I found a perfect solution for this problem when we use Toolbar.
To hide Toolbar programatically
if (toolbar.getParent() instanceof AppBarLayout){
                    ((AppBarLayout)toolbar.getParent()).setExpanded(false,true);
                }

To show Toolbar programatically
if (toolbar.getParent() instanceof AppBarLayout){
                        ((AppBarLayout)toolbar.getParent()).setExpanded(true,true);

Refer original answer(answer by @Android HHT):- programmatically-show-toolbar-after-hidden-by-scrolling-android-design-library


C# XSD schema - how to get main properties values?

Question: I have the XSD schema definition loaded (XDocument variable type) I can't figure out how to get the someProperty value. Any ideas ?
<xsd:form-definition xmlns:xsd="http://url/lorem.xsd"
     xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     ...
     someProperty="ABC">
 ...
</xsd:form-definition>

Answer: Simple with LINQ to XML:
var attributes = (from n in xml.Root.Attributes("someProperty")
                        select n.Value).ToList();


Change 3D view in matlab

Question: I would like to change the view of a 3D plot in matlab such that the y-axis points upward and the z-axis points to left. For example, consider the following plot:

Here the x-axis points forward, the y-axis points to the right and the z-axis points upward.
I would like to have the y-axis points upward and the z-axis points to the left instead. I tried to rotate the plot (using the figure window toolbar rotate button) but I could not get it to work. (It should just be a simple 90 degrees rotation about the x-axis)
Code to generate the plot:
  membrane
  view(100,50)
  xlabel('x-axis');
  ylabel('y-axis');
  zlabel('z-axis');
  grid on

Answer: Try using view. I don't have MATLAB available so I can't test it, but I think it can do what you want.
Example from the documentation:

Set the view along the y-axis, with the x-axis extending horizontally
  and the z-axis extending vertically in the figure.
view([0 0]);

EDIT:
Try using three inputs to the view function. I can't experiment myself, but you should be able to do it if you choose the right values here.
From documentation:

view([x,y,z]) sets the view direction to the Cartesian coordinates x,
  y, and z. The magnitude of (x,y,z) is ignored.

EDIT 2:
Check out camroll. I think camroll(90) (possibly in combination with view) will work.
From documentation:

camroll(dtheta) rotates the camera around the camera viewing axis by
  the amounts specified in dtheta (in degrees). The viewing axis is the
  line passing through the camera position and the camera target.
Comment: Thanks, but this seems not to achieve what I wanted.. Now I get a 2D-view, with the `x`-axis pointing to the right and the `z`-axis pointing upward.. I need a 3D view as in the figure in my question.
Comment: Ok I will try that.. but which values should i choose for `x`, `y` and `z`?
Comment: I have tried these values: `[1 0 0; 0 1 0; 0 0 1; 1 1 0; 1 0 1; 0 1 1]` but none of them seem to work..
Comment: Thanks, `camroll` did work :) .. There seem to be some problems with labelling of the axis though..
Comment: Here is the result: http://imgur.com/pPuTb9T Note that the labelling of the axis are really strange..
Comment: @HåkonHægland: I'm sorry but I can't help you. I suggest you ask a new question showing how you rotate the plot, include the picture, and ask if it's possible to adjust the labels. I guess you will have a better chance of getting an answer that way.
Answer: This was posted a while ago, but in case someone else is looking for ways to set y-axis as the vertical one here is a possible fix.
Manually: In the command window type cameratoolbar('show') which will open an interactive toolbar in your plot from which you could change the view. One of the options is to set a principle axis to x, y, or z.
Or in you script you could use cameratoolbar('SetCoordSys',coordsys) command which sets the principal axis of the camera motion. coordsys can be: x, y, z, or none.
http://uk.mathworks.com/help/matlab/ref/cameratoolbar.html

Change 3D view in matlab


Are $P(\min(X_iY_i)-\min( X_i) \min (Y_i) \leq x)$ and $P(\min (X_iZ_i)-\min (X_i) \min (Z_i)\leq x)$ equivalent?

Question: Imagine I have three independent random variables $X, Y, Z$ and each with positive support;
Now imagine I have an iid sample of each random variable, namely $X_1,...,X_n$, $Y_1,...,Y_n$ and $Z_1,...,Z_n$;
I want to know whether it holds that
$\mathbb P \hspace{-1mm} \left(\min\limits_{i=1,...,n}(X_iY_i)\hspace{-1mm}-\hspace{-1mm}\min\limits_{i=1,...,n}( X_i)\hspace{-1mm} \min\limits_{i=1,...,n} (Y_i) \leq x \right) \hspace{-1mm}= \hspace{-1mm}c \  \mathbb P \hspace{-1mm} \left(\min\limits_{i=1,...,n} (X_iZ_i)\hspace{-1mm}-\hspace{-1mm}\min\limits_{i=1,...,n} (X_i)\hspace{-1mm} \min\limits_{i=1,...,n} (Z_i)\leq x\right)$
So if these probabilities are in some sense equivalent
Comment: First of all $F(x)=cG(x)$ for all $x$ implies $c=1$ (for any two distribution functions $F$ and $G$. Secondly, I see absolutey no reason for the two probabilities to be comparable. Can you expalin why you think the two are connected?
Comment: Ahm that is right - well the idea I had is the following: If we consider the minimum and have postive support the question is how fast the minimum goes to zero in some sense, right? Now considering $Y$ and considering it is independent of $X$ I look for the common minimum of $ X \cdot Y$ but sice I substract the minimum of $Y$ it seems like it is somehow independent on how fast the minimum of $Y$ converges to zero and hence can be replaced by some other random variable $Z$
Answer: Surely not. Consider $Y$ being deterministic, that means $P(Y=d)=1$ for some $d > 0$. Then
$$\min\limits_{i=1,...,n}(X_iY_i)-\min\limits_{i=1,...,n}( X_i) \min\limits_{i=1,...,n} (Y_i) = \min\limits_{i=1,...,n}(X_id)-\min\limits_{i=1,...,n}( X_i) d = 0.$$
OTOH, if $X$ and $Z$ are non-deterministic, then
$$\min\limits_{i=1,...,n} (X_iZ_i)-\min\limits_{i=1,...,n} (X_i) \min\limits_{i=1,...,n} (Z_i)$$
can take values above $0$ with probability > $0$ (if $n > 1$), as there is a greater than $0$ probability that $X_i$ and $Z_i$ attain their minimums on different indices.
I'd say that unless you have very strong similiarity between the distributions of $Y$ and $Z$, it is a hopeless endavour to try to prove anything of that sort.
Comment: Would it help if $Z=Y_1Y_2$ with $Y_1$ and $Y_2$ independent and distributed as $Y$?
Comment: I don't think so. Make a few simulations with easy distributions (uniform on some interval or just a 2-point distribution) and I guess you will see that there is nothing like the conjectured relation.
Am I right that this is something that you'd like to be true because it would simplify something you do?
Comment: Exactly, it would greatly simplify things if it holds :-)  I only know that supp$(X/Y/Z)=\mathbb R_+$, continuity and $Z=Y_1*Y_2$
Comment: But it is a good idea to rum some simulation - thank you :-)
Comment: I am not sure if you are interested but I realized the following: When considering $\min\limits_{i=1,...,n} (X_iZ_i)-\min\limits_{i=1,...,n} (X_i) \min\limits_{i=1,...,n} (Z_i)$ then the second part becomes asymptotically negligible in terms of the first one; This shows that my statement can't be correct for most cases, even e.g $Z=Y_1*Y_2$ and I assume that $Y_1$ and $Y_2$ is regularly varying at zero with exponent $\alpha$, $Z$ is not regularly varying with that same exponent $\alpha$, so it can't hold (I dont know if $Z$ being r.v. at 0 with the same $\alpha$ would be sufficient)