Erro com persistence.xml e EclipseLink no glassfish

Question: Olá pessoal estou com esse problema depois que migrei o projeto para outra maquina, estou utilizando GlassFish com EclipseLink na base de dados utilizo o Postgres 9.4 se alguém já se deparou com esse erro poderia me ajudar não consegui resolver.
Já refiz toda a configuração e me deparo com mesmo erro.

"Caused by: javax.naming.NamingException: Lookup failed for
  'PostgresDB'"

Console:
 Informações:   [EL Info]: 2015-11-04 02:44:01.713--ServerSession(1551564778)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
    Advertência:   StandardWrapperValve[default]: Servlet.service() for servlet default threw exception
    javax.enterprise.event.ObserverException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
        at java.lang.Class.newInstance(Class.java:442)
        at org.jboss.weld.security.NewInstanceAction.run(NewInstanceAction.java:33)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.jboss.weld.injection.Exceptions.rethrowException(Exceptions.java:40)
        at org.jboss.weld.injection.Exceptions.rethrowException(Exceptions.java:78)
        at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:98)
        at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:271)
        at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:258)
        at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:237)
        at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:174)
        at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:170)
        at org.jboss.weld.event.TransactionalObserverNotifier.notifyObserver(TransactionalObserverNotifier.java:46)
        at org.jboss.weld.event.ObserverNotifier.notifyObservers(ObserverNotifier.java:124)
        at org.jboss.weld.event.EventImpl.fire(EventImpl.java:84)
        at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:78)
        at br.com.caelum.vraptor.interceptor.DefaultSimpleInterceptorStack.next(DefaultSimpleInterceptorStack.java:49)
        at br.com.caelum.vraptor.interceptor.DefaultSimpleInterceptorStack$Proxy$_$$_WeldClientProxy.next(Unknown Source)
        at br.com.caelum.vraptor.interceptor.InterceptorExecutor.executeAround(InterceptorExecutor.java:77)
        at br.com.caelum.vraptor.interceptor.InterceptorExecutor$Proxy$_$$_WeldClientProxy.executeAround(Unknown Source)
        at br.com.caelum.vraptor.interceptor.AspectStyleInterceptorHandler.execute(AspectStyleInterceptorHandler.java:85)
        at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:83)
        at br.com.caelum.vraptor.interceptor.FlashInterceptor.intercept(FlashInterceptor.java:98)
        at br.com.caelum.vraptor.interceptor.FlashInterceptor$Proxy$_$$_WeldClientProxy.intercept(Unknown Source)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler$1.call(ToInstantiateInterceptorHandler.java:71)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler$1.call(ToInstantiateInterceptorHandler.java:68)
        at br.com.caelum.vraptor.core.Try.run(Try.java:18)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.executeSafely(ToInstantiateInterceptorHandler.java:68)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:61)
        at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:83)
        at br.com.caelum.vraptor.interceptor.ExceptionHandlerInterceptor.intercept(ExceptionHandlerInterceptor.java:75)
        at br.com.caelum.vraptor.interceptor.ExceptionHandlerInterceptor$Proxy$_$$_WeldClientProxy.intercept(Unknown Source)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler$1.call(ToInstantiateInterceptorHandler.java:71)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler$1.call(ToInstantiateInterceptorHandler.java:68)
        at br.com.caelum.vraptor.core.Try.run(Try.java:18)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.executeSafely(ToInstantiateInterceptorHandler.java:68)
        at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:61)
        at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:83)
        at br.com.caelum.vraptor.core.DefaultInterceptorStack.start(DefaultInterceptorStack.java:93)
        at br.com.caelum.vraptor.core.DefaultInterceptorStack$Proxy$_$$_WeldClientProxy.start(Unknown Source)
        at br.com.caelum.vraptor.observer.RequestHandlerObserver.handle(RequestHandlerObserver.java:93)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:90)
        at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:271)
        at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:258)
        at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:237)
        at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:174)
        at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:170)
        at org.jboss.weld.event.TransactionalObserverNotifier.notifyObserver(TransactionalObserverNotifier.java:46)
        at org.jboss.weld.event.ObserverNotifier.notifyObservers(ObserverNotifier.java:124)
        at org.jboss.weld.event.EventImpl.fire(EventImpl.java:84)
        at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:123)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
        at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
        at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
        at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
        at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
        at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
        at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.ExceptionInInitializerError
        at com.ratossi.portifolio.model.Persistence.ArtesaoDAOJPA.salvar(ArtesaoDAOJPA.java:19)
        at com.ratossi.portifolio.controllers.CadastroController.save(CadastroController.java:33)
        at com.ratossi.portifolio.controllers.CadastroController$Proxy$_$$_WeldClientProxy.save(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at net.vidageek.mirror.provider.java.PureJavaMethodReflectionProvider.invoke(PureJavaMethodReflectionProvider.java:38)
        at net.vidageek.mirror.invoke.MethodHandlerByMethod.withArgs(MethodHandlerByMethod.java:54)
        at br.com.caelum.vraptor.core.DefaultReflectionProvider.invoke(DefaultReflectionProvider.java:42)
        at br.com.caelum.vraptor.core.DefaultReflectionProvider$Proxy$_$$_WeldClientProxy.invoke(Unknown Source)
        at br.com.caelum.vraptor.observer.ExecuteMethod$1.call(ExecuteMethod.java:82)
        at br.com.caelum.vraptor.observer.ExecuteMethod$1.call(ExecuteMethod.java:72)
        at br.com.caelum.vraptor.core.Try.run(Try.java:18)
        at br.com.caelum.vraptor.observer.ExecuteMethod.execute(ExecuteMethod.java:72)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:90)
        ... 77 more
    Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
    Exception Description: Cannot acquire data source [PostgresDB].
    Internal Exception: javax.naming.NamingException: Lookup failed for 'PostgresDB' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: PostgresDB not found]
        at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:766)
        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204)
        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:182)
        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:527)
        at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:140)
        at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
        at com.ratossi.portifolio.model.dao.Facabrica.<clinit>(Facabrica.java:20)
        ... 97 more
    Caused by: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
    Exception Description: Cannot acquire data source [PostgresDB].
    Internal Exception: javax.naming.NamingException: Lookup failed for 'PostgresDB' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: PostgresDB not found]
        at org.eclipse.persistence.exceptions.ValidationException.cannotAcquireDataSource(ValidationException.java:520)
        at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:109)
        at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162)
        at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.setOrDetectDatasource(DatabaseSessionImpl.java:204)
        at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:741)
        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:239)
        at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:685)
        ... 105 more
    Caused by: javax.naming.NamingException: Lookup failed for 'PostgresDB' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: PostgresDB not found]
        at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
        at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
        at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:622)
        at javax.naming.InitialContext.lookup(InitialContext.java:421)
        at javax.naming.InitialContext.lookup(InitialContext.java:421)
        at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:103)
        ... 110 more
    Caused by: javax.naming.NameNotFoundException: PostgresDB not found
        at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237)
        at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204)
        at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66)
        at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114)
        at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478)
        ... 115 more

    Informações:   [EL Severe]: ejb: 2015-11-04 02:44:01.715--ServerSession(1551564778)--Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
    Exception Description: Cannot acquire data source [PostgresDB].
    Internal Exception: javax.naming.NamingException: Lookup failed for 'PostgresDB' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: PostgresDB not found]

persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="com.ratossi_portifolio_war_1.0-SNAPSHOTPU" transaction-type="JTA">
    <jta-data-source>PostgresDB</jta-data-source>
    <class>com.ratossi.portifolio.model.Artesanato</class>
    <class>com.ratossi.portifolio.model.Artesao</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

glassfish-resources.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_portifolio_postgresPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="5432"/>
        <property name="databaseName" value="portifolio"/>
        <property name="User" value="postgres"/>
        <property name="Password" value="1234"/>
        <property name="URL" value="jdbc:postgresql://localhost:5432/portifolio"/>
        <property name="driverClass" value="org.postgresql.Driver"/>
    </jdbc-connection-pool>

    <jdbc-resource enabled="true" jndi-name="PostgresDB" object-type="user" pool-name="post-gre-sql_portifolio_postgresPool"/>
</resources>

pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ratossi</groupId>
    <artifactId>portifolio</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>portifolio</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>br.com.caelum</groupId>
            <artifactId>vraptor</artifactId>
            <version>4.2.0-RC2</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
                <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>unknown-jars-temp-repo</id>
            <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
            <url>file:${project.basedir}/lib</url>
        </repository>
    </repositories>
</project>

Comment: No glassfish todos os recursos JNDI estão em `java:comp/env` e o padrão quando você publica um JDBC é que inicie com `jdbc`, então no seu caso, para manter o padrão, use `jdbc/PostgresDB`. Caso não possa, teste no seu `persistence.xml` usar `java:comp/env/PostgresDB` ou também `java:comp/env/jdbc/PostgresDB`. Veja o log do servidor também, ele lista os recursos ao iniciar.
Comment: Fiz as mudanças que você falou, mas continuou com o mesmo erro.
Comment: E existe o recurso no glassfish? Se não existe, não está sendo publicado. Verificou no log e no console de administração?
Comment: Irei verifica o Log, devo procura por `java:comp/env` ?
Answer: eu acabei achando uma solução simples para este problema.
Este erro ocorre devido alguns bugs no Glassfish 4.1 que já vem com Netbeans,a solução simples e você baixa direto do Site do GlassFish a versão instável.
Espero ajudar aqueles que tenha o mesmo problema que eu.
Obrigado um bom dia a todos.


Prove that $\frac{ab}{a + b + 2} \le \sqrt{2} - 1$

Question: $a$ and $b$ are real non-negative numbers, for which $a^2 + b^2 = 4$. What is the easiest way to prove the following inequality (without using any fancy inequalities like Jensen's or Muirhead's)?
$\frac{ab}{a + b + 2} \le \sqrt{2} - 1$
Answer: Since $$((a+b)-2)((a+b)+2)=(a^2+b^2+2ab-4)=2ab,$$ we have $$\frac{ab}{a+b+2}=\frac{a+b-2}{2}=\frac{a+b}{2}-1.$$ Note that it is a circle and question is related with the maximum value of $$2\cos\theta+2\sin\theta$$ which is $2\sqrt 2$.
Comment: Great answer! $+1$
Answer: You may use the fact that $a^2+b^2=4$ is the equation of a circle while $ab=(\sqrt{2}-1)(a+b+2)$ is the equation of a rectangular hyperbola, and both conic sections go through the point $(\sqrt{2},\sqrt{2})$, but with different curvatures. In particular, the line with equation $a+b=2\sqrt{2}$ is tangent to both curves, and
$$a^2+b^2=4,\quad a,b\geq 0$$
implies $a+b\leq 2\sqrt{2}$, that implies $ab\leq(\sqrt{2}-1)(a+b+2)$.


Get text of input in Protractor

Question: How do I get text of input and use it in my test? The code bellow returs an Protractor Object and not the text.

var typed  = element(by.css(css + ' input')).getAttribute('value');
if (typed === 'something') { // doSomething() }
Comment: possible duplicate of [How to getText on an input in protractor](http://stackoverflow.com/questions/20310442/how-to-gettext-on-an-input-in-protractor)
Comment: its not necessarily a duplicate but it is very easy, to find out that you need to resolve promises with a then callback, with a simple google search or search on this site.
Answer: The function getAttribute returns a promise. To access the value you can do so in a then calback
element(by.css(css + ' input')).getAttribute('value').then(function(value) {
  console.log(value);
});

You don't mention what you need it for, but note that expect can handle promises passed to it, so for a lot of cases you don't need the then callback.
expect(element(by.css(css + ' input')).getAttribute('value')).toEqual('some-value');

Get text of input in Protractor


random effects variance meaning

Question: I am trying to better understand the output for a multi-level mixed effects model. Specifically, I am confused on how to interpret the random-effects parameters, and the random effects variance. Is there something I should look for here to confirm the model is working as it should? And should I report this value in an output table, or is it more of an embellishment to include?
Answer: Parameters for _cons being a random effect means that the model assumes it to be a Gaussian random variable with a mean equal to zero and variance equal to var(_cons). The parameters for each of the levels of _cons are assumed to be realizations of this random variable. So this is what the model estimates. Check the What is the difference between fixed effect, random effect and mixed effect models? thread or one of many books for more details. The variance would be "wrong" if it would be zero, infinite, or not a number, but otherwise, the values would depend on your model and the data.
Comment: Thank you for those references! I guess, a follow up question I have is: is there significance / readily interpretable meaning that this is much higher than the coefficients for variables specified in the model?

random effects variance meaning


Hilbert-Poincaré Series of Finite-Dimensional Graded Algebras

Question: Suppose I have two finite-dimensional $\mathbb{Z}_{\geq 0}$-graded $\mathbb{C}$-algebras $A = \bigoplus_{k \geq 0} A_{k}$ and $B = \bigoplus_{k \geq 0} B_{k}$ with Hilbert-Poincaré series, $P_{A}(t) = \sum_{k \geq 0} \dim A_{k} \ t^{k}$ and $P_{B}(t) = \sum_{k \geq 0} \dim B_{k} \ t^{k}$, respectively.
When is it true that $A$ and $B$ are isomorphic as graded $\mathbb{C}$-algebras if $P_{A} = P_{B}$? Suppose that $P_{A} \neq P_{B}$ but $P_{A}(1) = P_{B}(1)$, what can be said about $A$ and $B$ in this case? Are they isomorphic as $\mathbb{C}$-algebras but not as graded $\mathbb{C}$-algebras?
The algebras that brought me to ask these questions are all of the form $\mathbb{C} \{ z_1, \dots, z_n \} / J$, where $J$ is a finitely generated ideal of partial derivatives of a complex analytic function $f$ with an isolated critical point at the origin.
Comment: ??? two algebras may have the same Hilbert series and *not* be isomorphic as algebras.  Example: $A=k[x]/x^3$ with $x$ of degree one, $B=k[x,y]/(x^2,y^2,xy)$ with $x$ in degree one, $y$ in degree two.
Comment: Dear mt, I first thought you had made a mistake and that's why I decided to write an answer  . But I hadn't seen that you slily took $y$ to have degree$2$ and so your remark is perfectly correct. Nice trick that !
Comment: This is the kind of questions that answers itself upon the consideration of a couple of examples :)
Comment: Of course, it is still very useful to know that two Poincare series are equal! Because if you have an actual (graded) map (of algebras if you want) $A \rightarrow B$ and you can show it's either injective or surjective, then it's an isomorphism by the equality of the Poincare polynomials. Very useful.
Answer: Your claim that equality of Hilbert-Poincaré series implies equality of algebras is false.
Take $A=\mathbb C [X,Y]/(X^2)$
and   $B=\mathbb C [X,Y]/(X^2+Y^2)$
with their quotient  gradings.
We have $P_{A}(t)=P_{B}(t) =1+2t+2t^2+2t^3+2t^4+\ldots=\frac{1+t}{1-t}$ .
But $A$ and $B$ are not isomorphic as rings (and thus certainly not as graded algebras), since $A$ has a non-zero nilpotent element (the class of $X$),  whereas $B$ is reduced i.e. has zero as only nilpotent element.
Generalization If you consider a homogeneous polynomial of degree $d$ in $n$ variables $f(X_1,\ldots,X_n)\in \mathbb C [X_1,\ldots,X_n]$, then the algebra
$A(f)=\mathbb C [X_1,\ldots,X_n]/\lt f(X_1,\ldots,X_n)\gt$ has a Hilbert-Poincaré series independent of $f$, namely (combinatorists: please combine!)
$$P(t)=\sum_{k\geq 0}\binom{k+n-1}{n-1}t^k-\sum_{k\geq d}\binom{k-d+n-1}{n-1}t^k$$
However the rings $A(f)$ strongly depend on $f$. This is evident geometrically because the hypersurfaces $Z(f)=\{ x \in  \mathbb C^n|f(x)=0\}$ vary a lot with $f$: they may be irreducible or not, smooth or not, etc. And so their rings of functions $A(f)$ differ a lot too and are not in general  isomorphic for different $f\;$'s.
Edit I had overlooked that the OP wanted finite-dimensional examples. It is easy to modify the above examples by killing off all monomials of sufficiently high degree. Geometrically, this means looking at the intersection or the hypersurface $Z(f)$ with a sufficiently large infinitesimal neighbourhood of the origin. Let me do this explicitly for the first example and kill all monomials of degree $\geq 3$:
Put  $A'=\mathbb C [X,Y]/(X^2,XY^2,Y^3)=\mathbb C [x,y ]\;$ and  $B'=\mathbb C [U,V]/(U^2+V^2,U^3,V^3)=\mathbb C [u,v]$  .
Then  $P_{A'}(t)=P_{B'}(t) =1+2t+2t^2 \;$.
However the algebras $A'$ and $ B'$are not isomorphic: for example, their spaces of solutions of the equation $\xi^2=0$  have dimensions $3$ and $2$ respectively over $\mathbb C$. Namely,  these spaces are:
$Nil_2(A')=\mathbb C . x\oplus \mathbb C .xy \oplus \mathbb C .y^2$ and $Nil_2(B')=\mathbb C . u^2 \oplus \mathbb C .uv$
Comment: Your example looks right, but the OP did ask for *finite dimensional* algebras.  I left a finite dimensional counterexample in the comments.
Comment: Ah, yes, you are right @mt and user 02138. But the examples can easily be modified so as to make them finite-dimensional : just divide the algebras by the ideal generated by all  monomials of sufficiently high degree . I've written an "Edit" detailing this procedure.
Comment: I really like the geometric interpretation Georges -- I'd never seen that before.
Comment: Yes, I am aware of these examples. However, the original question is about _finite dimensional_ graded algebras in which the Hilbert-Poincare series are actually _polynomials_.
Answer: Asking "does $P_A=P_B$ imply $A \cong B$?" is like asking "does $|G|=|H|$ imply $G \cong H$?": the answer is no, except in certain very special  circumstances.  If $P_A = 1$, or $1+t^{57}$, or $1+t^2+t^7$ etc. the answer is yes, but in general it is no: given a series $P_A$ simply construct an algebra with the same graded pieces as $A$ but with trivial multiplication.  This will not normally be isomorphic to $A$.
If $P_A(1) = P_B(1)$ you have much less information.  If they are both 2 you can say something, but I doubt you can get much more without restricting the class of algebras
Answer: The simplest counterexample is, I think, this:
$$A=A_0=\mathbb C\times\mathbb C,\quad B=B_0=\mathbb C[X]/(X^2).$$


Curve length and line integral, irrelevancy of parametrization proof

Question: I'm trying to prove that
$$\int_c^d ||\tilde{\mathbf{r}}'(t)||\, \mathrm{d}t = \int_a^b ||{\mathbf{r}}'(t)||\, \mathrm{d}t$$
where $\tilde{r}: [c,d] \to \mathbb{R}^n$ is a reparametrization of a $C^1$-curve $r:[a,b] \to \mathbb{R}^n$. (The definition of a reparametrization in my textbook is that the bijective function $\phi: [c,d] \to [a,b]$ that lets $r(\phi(u)) = \tilde{r}(u)$ $\forall u \in [c,d]$ and its inverse $\phi^{-1}$ are continuous).
I'm also trying to prove that a similar thing applies to the line integral of a continuous vector field $V: \Omega \to \mathbb{R}^n$
$$ \int_c^d \mathbf{V}(\tilde{\mathbf{r}}(t)) \cdot \tilde{\mathbf{r}}'(t)\, \mathrm{d}t = \int_a^b \mathbf{V}(\mathbf{r}(t)) \cdot \mathbf{r}'(t)\, \mathrm{d}t $$
I honestly have no idea where to even start. I could imagine that maybe using the chain rule on $(r \circ \phi)'$ would give me somewhere but I can't seem to put it all together.
Answer: Suppose $\phi :[c,d]\to [a,b]$ is a $C^1$ increasing bijection. Then $\int_a^b|r'(t)|dt = \int_c^d|r'(\phi(s))|\phi'(s)ds.$ That's just a standard change of variables. In the second integral, the integrand is precisely $|\tilde {r}'(s)|.$ That idea should work for you second problem too.
Comment: So if we perform integration by substitution on the second integral by setting $u=\phi(s)$ so $du = \phi'(s) ds$ we get that $\int_c^d |r'(\phi(s))|\phi'(s) ds = \int_{\phi(c)=a}^{\phi(d)=b} |r'(u)| du$?
Comment: Sure. That would be true of any continuous (actually any Lebesgue integrable) function on $[a,b].$ Here we have the continuous function $t\to |r'(t)|.$


CSS :not pseudo class

Question: I would like to apply a certain style to all descendants of an element except some.
Here is an example of what I'm trying to achieve : http://jsfiddle.net/f8FLe/
.root * :not(.nested) {
    color: green;
}

    Span 1

        Span 2.1
        Span 2.2

    Span 3

In this example, I try to color all fonts to green except those that are descendants of the div element with 'nested' class.
In that purpose, I tried to use the ":not" pseudo element but it doesn't work.
Do someone know why ?
Comment: Color is inherited. You'd need to override the color of the parent by setting a color on the child.
Comment: it does not work here because color is inherited from parent, add somewhere a class .nested and give it the color you wish it to keep.
Comment: removing the `*` may work as what you want (the span 1 and span 3 should be colored as `green`)
Answer: Because your inner s... they are :not(.nested), because they don't have that class.
One thing I like to do - particularly with lists, is something like this:

Item 1

Item 2.1

Item 2.2

Item 3

With that structure (which is very similar to what you have, by the way), you can do this:
.root>li {color:green}
.root ul>li {color:blue} /* nested list */
/* you can also do... */
.root>li>ul>li {color:red} /* specifically one level of nesting */

Comment: Even when I try to put 'nested' class on my 's , that doesn't work .. :-/
Comment: @RianaRambonimanana [Really?](http://jsfiddle.net/f8FLe/1/) Try [the right selector](http://jsfiddle.net/f8FLe/2/)
Comment: set a color to .nested and it will not take parent's color :)
Comment: Thanks Niet, the selector you suggested works indeed, but in my actual problem, I do not want to put '.nested' class in all div.nested descendants ... I would like to write something like :not(.nested *), but it doesn't work ..
Comment: That why I suggested the use of the `>` combinator.
Comment: The > combinator is not enough as I have to select ALL descendants of the element with '.nested' class and I do not know in advance what kind of elements they are ..
Comment: In your original HTML, just `.root>span` would be perfectly adequate to make your target spans green without affecting the nested ``.
Comment: Yes but it was just an example to expose the problem and I choose a simple one .. In my real case, I must be able to exclude all descendants of an element.
Answer: its about inheritance and about sibling the right tags.
You rules says , if class = . nested , do not apply color.
inside div.nested , you have 2 span with no class.
either you do not wrap text in tags http://jsfiddle.net/f8FLe/6/, or you give the nested class to each tag you do not want to apply color http://jsfiddle.net/f8FLe/5/.

.root * :not(.nested) {
    color: green;
}

playground HTML:

        not nested
        nested
         nested
         nested
         nested

Comment: The parent has no colour either. It's not inheriting from anything.
Comment: child are not being selected by the rule, they do not have the class .nested , confusing indeed.
Answer: With your tag structure I would use something like this:
.root *{
    color: green;
}
.nested span{
    color: black;
}

http://jsfiddle.net/f8FLe/7/
Your problem is the spans contained by .nested don't have the .nested class (as Niet the Dark Absol says)
Comment: Smart workaround ! I'll try it on my problem, thanks :-)
Answer: This works: http://jsfiddle.net/f8FLe/8/
.root > *:not(.nested) {
    color: green;
}

CSS :not pseudo class


Problema no envio de email em PHP

Question: Preciso de ajuda num formulário em PHP complexo, pois além de enviar email para administradores, envia também para o cliente. O email é em html e cria automaticamente um pdf através de html2pdf.
Então é assim, ele está a funcionar, pois cria o PDF, envia o email com link para o PDF, mas não está a pegar nos valores inseridos no formulário.
Processo do formulário, criação do PDF, envio do email, e um contador:
<?php
require_once(dirname(__FILE__).'/html2pdf/html2pdf.class.php');
?>
    <?php
    if(isset($_POST['email'])) {

        // EDIT THE 2 LINES BELOW AS REQUIRED
        $email_to = "firstname.lastname@example.com,firstname.lastname@example.com";
    $email_client = $_POST['email'];

    $email_subject = "3Compare Booking";

    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted.";
        echo "These errors appear below.

";
        echo $error."

";
        echo "Please go back and fix these errors.

";
        die();
    }

    // validation expected data exists
    if(!isset($_POST['name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['number']) ||
        !isset($_POST['optionsRadios']))
         {
        died('We are sorry, but there appears to be a problem with the form you submitted.');

    $name = $_POST['name']; // required
    $email = $_POST['email']; // required
    $number = $_POST['number']; // required
    $optionsAreas = $_POST['optionsAreas']; // not required
    $optionsRadios = $_POST['optionsRadios']; // not required
    $newsletter = $_POST['newsletter'];
    $ref = $_POST['ref'];

}

    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email)) {
    $error_message .= "The Email Address you entered does not appear to be valid.
";
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.
';
  }
  if(strlen($number) < 2) {
    $error_message .= 'The Last Name you entered does not appear to be valid.
';
  }
  if(!preg_match($string_exp,$optionsRadios)) {
    $error_message .= 'The Comments you entered do not appear to be valid.
';
  }
  if(!preg_match($string_exp,$newsletter)) {
    $error_message .= 'The Comments you entered do not appear to be valid.
';
  }

  function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
    $datei = fopen("library/countlog.txt","r");
$count = fgets($datei,1000);
fclose($datei);
$ref="3COMPAREWLC".$count."-".date('ymd');
$numlink = '3COMPAREWLC'.$count.'-'.date('ymd');
    $email_message ="

New Reservation

A new reservation was made on the website 3COMPARE

                               Personal Info

                               Reference: ".clean_string($ref)."

                                Name: ". $_POST['name']."

                                Email: ".$_POST['email']."

                                Mobile Number: ".$_POST['number']."

                                Payment Method: ".$_POST['optionsRadios']."

                                Newsletter: ".$_POST['newsletter']."

Laser Hair Loss Therapy:

30-minute session per week for three months, with 13 sessions in total.

".$optionsAreas."

                            Click here to download and print your voucher

3COMPARE

";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers = "Content-Type: text/html; charset=utf-8\r\n";
@mail($email_to, $email_subject, $email_message, $headers);
@mail($email_client, $email_subject, $email_message, $headers);
ob_start();
    $num = '3COMPAREWLC'.$count.'-'.date('ymd');
    $nom = $name;
    $date = '2014/07/31';
?>

<page format="100x200" orientation="L" backcolor="#f0a804" style="font: arial;">

        This is your e-ticket to present at the Clinic

                        <?php echo $nom; ?>

                        Weight Loss Clinic

                        Reference : <?php echo $num; ?>

                        Booked at : <?php echo date('d/m/Y à H:i:s'); ?>

VOUCHER

                        Valid until <?php echo $date; ?>

                    <?php echo $_POST['optionsAreas']?>

                    Personal Info

                                Name: <?php echo $_POST['name']?>

                                Email: <?php echo $_POST['email']?>

                                Mobile Number: <?php echo $_POST['number']?>

                                Payment Method: <?php echo $_POST['optionsRadios']?>

Laser Hair Loss Therapy:

30-minute session per week for three months, with 13 sessions in total.

</page>
<?php
     $content = ob_get_clean();

    // convert
    try
    {
        $html2pdf = new HTML2PDF('P', 'A4', 'fr', true, 'UTF-8', 0);
        $html2pdf->pdf->SetDisplayMode('fullpage');
        $html2pdf->writeHTML($content, isset($_GET['vuehtml']));
        $html2pdf->Output('voucher/ticket'.$num.'.pdf','F');
    }
    catch(HTML2PDF_exception $e) {
        echo $e;
        exit;
    }
?>

Thank you <?php echo $_POST['name']?> for booking at 3COMPARE. We will be in touch with you very soon. <a class="btn btn-warning btn-shadow" href="<?php echo 'voucher/ticket'.$num.'.pdf'?>">Download your Voucher

      <?php
/* counter */

//opens countlog.txt to read the number of hits
$datei = fopen("library/countlog.txt","r");
$count = fgets($datei,1000);
fclose($datei);
$count=$count + 1 ;

// opens countlog.txt to change new hit number
$datei = fopen("library/countlog.txt","w");
fwrite($datei, $count);
fclose($datei);

?>

<?php
}
?>

Formulário:
    <form class="form-horizontal marginform" role="form" method="post" action="<?php $_SERVER['PHP_SELF']; ?>" name="frm1" id="frm1">

          <?php
            $onearea .= "Order Details

                                Duration: 45 mins

                                Employee: Cristina @ HDC

                                SubTotal: £85.00

                                Total: £85.00

                                Valid until: 2014-07-31
";

    $twoareas .= "Order Details

                                Duration: 45 mins

                                Employee: Cristina @ HDC

                                SubTotal: £165.00

                                Total: £165.00

                                Valid until: 2014-07-31
";
                ?>

Order Details

              One Area
              <input type="radio" name="optionsAreas" id="optionsAreas1" value="<?php echo ($onearea); ?>">

            Two Areas
              <input type="radio" name="optionsAreas" id="optionsAreas2" value="<?php echo ($twoareas); ?>">

Cryogenic Lipolysis Therapy
45-minute session per week for three months, with 13 sessions in total.

One Area

Duration

45 mins

Employee

Cristina @ HDC

SUBTOTAL

£85.00

TOTAL

£85.00

Two Areas

Duration

45 mins

Employee

Cristina @ HDC

SUBTOTAL

£165.00

TOTAL

£165.00

Payment method:

              <input type="radio" name="optionsRadios" id="optionsRadios1" value="Pay At Clinic" checked>Pay At Clinic

              <input type="radio" name="optionsRadios" id="optionsRadios2" value="Other Way" class="hidden">

Available until: 2014-07-31

            <input name="ref" type="hidden" value="<?php $datei = fopen("library/countlog.txt","r");
$count = fgets($datei,1000);
fclose($datei);echo "3COMPAREWLC".$count."-".date('ymd');?>">

Your contact details

    Your full name*

      <input type="text" name="name" class="form-control" id="inputEmail3" placeholder="Full Name" value="<?php echo $name; ?>" required>

    Your email address*

      <input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email" required>

    Mobile Number*

      <input type="tel" name="number" class="form-control" id="number" placeholder="Mobile Number" required>

      <button type="submit" name="submit" class="btn btn-lg btn-danger btn-shadow" value="Send">

      Click Here to
Complete Your Order

      </button>

          <input type="checkbox" name="newsletter" value="Yes" id="newsletter" checked> Keep me in the loop about special offers and the latest community news

        <input type="checkbox" class="hidden" name="newsletter" value="No" id="newsletter1">

</form>

O problema está no formulário, pois ele não está a pegar os valores inseridos, logo, envia o email sem os dados.
UPDATE:
Já consigo enviar os dados, menos os dados da OptionsAreas e não está a enviar email para o cliente. Outro problema é que a OptionsAreas não está a esconder os valores no formulário. Se seleciono uma área, a outra não deveria aparecer.
Alguém ajuda por favor
Comment: Tente debugar o seu script, se você der um echo $_POST['name'], ele aparece algo ?
Comment: Obrigado. Consigo através de echo $_POST['name'] fazer com que pegasse nos valores à excepção da Options Areas. Continuo sem conseguir enviar email para o cliente
Answer: Testei aqui o seu script e funcionou 'perfeitamente', gerou o pdf na pasta voucher, contou a visita para gerar o código do voucher, e gerou os dois e-mails também. Como eu testo localmente no XAMPP, são gerados dois arquivos com os e-mail na pasta mailoutput, indicando assim que funciona, abri os arquivos e estão OK.
Para não deixar dúvida coloquei on-line e também enviou os emails bem como gerou o pdf. Já com relação aos Options, confesso que ainda não entendi sua dúvida.
Será que o JQuery Validation não resolve seu problema?
E ao invés de utilizar o echo $_POST['nome'], que tal usar o print_r($_POST).
Faça o teste on-line

Problema no envio de email em PHP


Routes don't work in production of react website

Question: I have a question.
I created a react website and everything works perfectly on local development.
So if I go to localhost:8080/about I get on the about page.
When I build the website only an index.html gets made.
When I navigate the website from the index page, it all works, also the urls changes to /about when I go to the about page through the menu.
But when I go to www.website.com/about by typing in the address I get an error page.
Who can help me with this?
JayD
Comment: Where are you deploying it at ?
Comment: have you created a page with this route?
Comment: Please share the part of the code where you have routed/called this
Comment: @DevGuy I have my own server at Strato.de
Comment: @FatemehQasemkhani Yes, and on local development everything works just fine
Comment: @mw509

`

`
Comment: Its not about code, its about server in my opinion. I had similiar issue with S3 bucket when ive landed on homepage and click links everything was working, and if i write link directly wouldnt work saying forbidden access.
Comment: @DevGuy That seems the problem, how did you fixed this?
Comment: Using url rewrite .and redirect. But ive forgot exactly as it was long time ago.
Answer: You need to setup your react router accordingly. Usually you need to add one extra file in your build files. Below is the tutorial on how to setup react router using fierbase and netlify. If you deploy somewhere else, please let me know. I can help you with that.
Firebase
Netlify
Comment: I have my own server at Strato.de
Comment: @JayD i think this tutorial will help you https://medium.com/@aforamitrai/how-to-deploy-react-app-on-shared-hosting-cpanel-d682b0342424
Comment: Thank you so much, this helped me with my problem.


Confusion about mixing major and minor pentatonic

Question: I'm trying to figure out something I don't know.
I'm an elementary guitar player. I know how to improvise, I know chord progressions, the circle of fourths/fifths, intervals, etc.
I know I7/IV7/V7, I know that I can mix them. But I realized a problem when I saw John Mayer's "Gravity."
This is my question: Why G major and not G7? Why does he use G minor pentatonic?
https://youtu.be/owFFVQYW1p8?t=2m32s
Answer: There are several common ways of approaching a blues or a 'bluesy' song. For a 'sweet' effect you can go hard on the sixth, take it easy on the flat seventh and bend up to the major third.  If you want more 'mean/mistreated' you go with the  flat seventh, flat fifth and flat third. Or you can mix them up. In this tune John Mayer mixes them up and also rides the major seventh hard at one point. So, the answer to your question is that the blues gives you licence to milk the tension between major and minor, and that goes for the seventh degree as well.
Answer: It's the age old thing - while playing over a major/seventh chord sequence, one can and does use both the major and minor pents, it's not a problem.  It's the same with maj and min blues - with just an added note in each case. It all works, and good players will be in and out of both in most solos.


setNativeDialogHandler to handle ie11 access Clipboard

Question: I have a test that initiates a copy to clipboard.  in ie11 that generates a dialog https://i.stack.imgur.com/VSEIT.jpg
I can't clear it.  Here is my code
fixture.only`Downloads`
    .page`${page.page}`
    .beforeEach(async (t) => {
        await t
            .maximizeWindow()
            .setNativeDialogHandler((type, text, url) => {
                if (type === 'confirm') { return false } return true
            })
        await page.loginAdmin()
    })
    .afterEach(async (t) => {
        await t.setNativeDialogHandler(null)
    })

But it won't clear the dialog.  I have also tried
.setNativeDialogHandler(() => true)

but the dialog remains and the test times out
Comment: Try the solution from the thread below: IE -> Internet Options -> Security -> Internet zone -> Custom Level -> Allow programmatic clipboard access.
https://edumanual.pbworks.com/w/page/61242170/Clipboard%20Access%20for%20Internet%20Explorer.
Comment: thanks.  that will solve the dialog showing up.  I need then to determine how to configure IE that way.  I can snapshot a testVM configured like that for local testing... I'll have to look in to how I can get saucelabs (browser testing service) to give me an ie11 with that configuration
Comment: In this case, I suggest you wait for TestCafe to support Clipboard out of the box: https://github.com/DevExpress/testcafe/issues/2668
Answer: You can use the following approach for Clipboard interaction:

const overrideClipboardCopy = ClientFunction(() => {
    const execCommand = document.execCommand;

    document.execCommand = (action, ...args) => {
        if (action === 'copy') {
            //handle copy here
        }
        else
            return execCommand.call(document, ...args);
    }
});

See also: Allow to use HTML5 Clipboard API in tests


How can I solve this limit of a function defined in $R^2$?

Question: I have to find out for which $\alpha>0$ this limit equals to $0$:
$$\lim\limits_{(x, y) \to (0, 0)}\frac{1+\sin(|x|^\alpha y)-\cos(x^2+y^4)}{(x^2+y^4)^{3/2}}$$
I tried to separate it in two parts:
$$\lim\limits_{(x, y) \to (0, 0)}\frac{1-\cos(x^2+y^4)}{(x^2+y^4)^{3/2}}+\frac{\sin(|x|^\alpha y)}{(x^2+y^4)^{3/2}}$$
Now the first term doesn't depend on $\alpha$ and it is asymptotic to:
$$\frac{1-1+\frac{(x^2+y^4)^2}{2}}{(x^2+y^4)^{3/2}}=\frac{(x^2+y^4)^{1/2}}{2}$$
So this term tends to $0$ when $(x, y)$ tends to $(0, 0)$.
Then I tried to study the other term using the squeeze theorem in this way:
$$0\le \left \vert \frac{\sin(|x|^\alpha y)}{(x^2+y^4)^{3/2}} \right\vert \le \left \vert \frac{|x|^\alpha y}{(x^2+(y^2)^2)^{3/2}} \right\vert \le \left \vert \frac{|x|^\alpha y}{(2|x||y|^2)^{3/2}} \right\vert \le \frac{|x|^{\alpha-3/2}}{|y|^2} $$
At this point I thought that if x goes to $0$ faster than y, then the whole thing tends to $0$: meaning, I set $\alpha - \frac{3}{2} > 2$ and therefore $\alpha > \frac{7}{2}$.
Honestly I see so many possible mistakes in this procedure, but I couldn't find another way to solve this problem, so I'd like to know if this is correct, and if not, how should I have done it?
Answer: It results that
$\lim\limits_{(x,y)\to(0,0)}\dfrac{1+\sin(|x|^\alpha y)-\cos(x^2+y^4)}{(x^2+y^4)^{3/2}}=$
$=\lim\limits_{(x,y)\to(0,0)}\dfrac{1-\cos(x^2+y^4)}{(x^2+y^4)^{3/2}}+ \lim\limits_{(x,y)\to(0,0)}\dfrac{\sin(|x|^\alpha y)}{(x^2+y^4)^{3/2}}=$
$=\lim\limits_{(x,y)\to(0,0)}\sqrt{x^2+y^4}\cdot\!\!\lim\limits_{(x,y)\to(0,0)}\dfrac{1-\cos(x^2+y^4)}{(x^2+y^4)^2}+\\[3pt]\quad+ \lim\limits_{(x,y)\to(0,0)}\dfrac{\sin(|x|^\alpha y)}{|x|^\alpha y}\cdot\!\lim\limits_{(x,y)\to(0,0)}\dfrac{|x|^\alpha y}{(x^2+y^4)^{3/2}}\,.$
By using the following notable limits
$\lim\limits_{z\to0}\dfrac{1-\cos z}{z^2}=\dfrac12\;\;$ and $\;\;\lim\limits_{z\to0}\dfrac{\sin z}z=1\;,\;$ we get that
$\lim\limits_{(x,y)\to(0,0)}\!\!\!\dfrac{1-\cos(x^2+y^4)}{(x^2+y^4)^2}=\dfrac12\;$ and $\lim\limits_{(x,y)\to(0,0)}\!\!\!\dfrac{\sin(|x|^\alpha y)}{|x|^\alpha y}=1\;,$
moreover, it is easy to show that
$\lim\limits_{(x,y)\to(0,0)}\sqrt{x^2+y^4}=0\;.$
Let $\;\varphi:(-\infty,+\infty)\to\Bbb R\;$ be the function defined as follows :
$\varphi(z)=\dfrac z{\left(1+z^4\right)^{3/2}}\quad$ for any $\;z\in\Bbb R\,.$
It results that
$\begin{align}\big|\varphi(z)\big|&=\dfrac{|z|}{\left(1+z^4\right)^{3/2}}=\sqrt{\dfrac{z^2}{\left(1+z^4\right)^3}}\leqslant\sqrt{\dfrac{\frac12\left(1+z^4\right)}{\left(1+z^4\right)^3}}=\\&=\dfrac{\sqrt{\frac12}}{1+z^4}\leqslant\sqrt{\dfrac12}<1\;\;,\quad\text{ for any }z\in\Bbb R\,.\end{align}$
Now, we will prove that
$\lim\limits_{(x,y)\to(0,0)}\dfrac{|x|^\alpha y}{(x^2+y^4)^{3/2}}=\begin{cases}\text{does not exist}&\text{if }\,0<\alpha\leqslant\dfrac52\\[3pt]0&\text{if }\,\alpha>\dfrac52\;\;.\end{cases}$
It results that
$\begin{align}\dfrac{|x|^\alpha y}{(x^2+y^4)^{3/2}}&=\dfrac{|x|^\alpha y}{\left|x\right|^3\left(1+\frac{y^4}{x^2}\right)^{3/2}}=\dfrac{|x|^{\alpha-\frac52}\frac y{\sqrt{|x|}}}{\left[1+\left(\!\frac y{\sqrt{|x|}}\!\right)^{\!4}\right]^{3/2}}=\\[3pt]&\!\!\!\!\!\!\!\!\!\!\!\!\!\!=|x|^{\alpha-\frac52}\!\cdot\!\varphi\left(\!\frac y{\sqrt{|x|}}\!\right)\;\;\text{ for any }\,x,y\in\Bbb R\,\land\,x\neq0\;.\end{align}$
If $\;0<\alpha\leqslant\dfrac52\,,\;$ then
$\lim\limits_{(x,y)\to(0,0)\\y=\pm\sqrt{|x|}}\dfrac{|x|^\alpha y}{(x^2+y^4)^{3/2}}=\begin{cases}\;\pm\infty&\text{if }\,0<\alpha<\dfrac52\\[3pt]\varphi(\pm1)=\pm\dfrac1{2^{3/2}}&\text{if }\,\alpha=\dfrac52\end{cases}$
consequently,
$\lim\limits_{(x,y)\to(0,0)}\dfrac{|x|^\alpha y}{(x^2+y^4)^{3/2}}\quad$ does not exists if $\;0<\alpha\leqslant\dfrac52\,.$
On the other hand, if $\;\alpha>\dfrac52\,,\;$ then
$\left|\dfrac{|x|^\alpha y}{(x^2+y^4)^{3/2}}\right|=\begin{cases}|x|^{\alpha-\frac52}\!\cdot\!\left|\varphi\left(\!\frac y{\sqrt{|x|}}\!\right)\right|<|x|^{\alpha-\frac52}&\text{if }\,x\neq0\\[3pt]\;0&\text{if }\,x=0\end{cases}$
and, since $\,\lim\limits_{(x,y)\to(0,0)}|x|^{\alpha-\frac52}=0\;,\;$ by using Squeeze Theorem, we get that
$\lim\limits_{(x,y)\to(0,0)}\dfrac{|x|^\alpha y}{(x^2+y^4)^{3/2}}=0\,.$
Hence ,
$\lim\limits_{(x,y)\to(0,0)}\!\!\!\!\dfrac{1+\sin(|x|^\alpha y)-\cos(x^2+y^4)}{(x^2+y^4)^{3/2}}=0\;\;$ for any $\,\alpha>\dfrac52\,.$
Comment: congrats for hitting 9k
Comment: @SineoftheTime, thank you very much !
Comment: @Angelo thank you very much, you explanation was very clear and it really helped


Magento; Modifying a payment module changing name in "method" field

Question: Modifying a payment module I'm not having any success changing the "payment name" that is placed in table sales_flat_order_payment in field "method".
For example if payment is check, it is populated with checkmo.
I've tried changing
protected $_code  = '.........'; in payment.php with no success.
I'm guessing this name may need changing in multiple places?
I have researched this but any answers I can find are assuming I have the skill level to know how to duplicate or modify the extension.
magento ver 188.8.131.52
more info; I'm using a Western Union payment extension as a Bpay payment extension and that field method is used to SMS payment type to me (and it would be more elegant it said what it really was!)
Answer: It's better to have a separate payment method for  this. You can duplicate some existing method, and use your custom name.
Comment: Thanks Roman, this was EXACTLY my question, all the research I read said this "You can duplicate some existing method, and use your custom name". Where do I change the name to change this in method?
Answer: Create a new payment module by duplicate one of your other payment module that closest matches what you are trying to do.
If you are trying to create a payment module for check then take a look at create a new payment method
Comment: Thanks for your reply, I was hoping that instead of creating an entirely new module I could change the field name in one (or more places) and save building a module with (knowing my skills) many errors!


SFTP authentication with credentials in Wordpress MySQL database?

Question: I'm trying to find a solution that will allow for a user to connect to a server via SFTP using a provided username/key combination (stored in a Wordpress installation's MySQL database), without needing to constantly keep two or more separate systems in sync.
I asked this question on Stackoverflow, but I feel that it would be better answered here.
This is the MySQL query that gets two columns that have the username of a user and the api key, which the user would type in to their SFTP client as their password:
<code>SELECT m.meta_value, u.user_login
FROM wp_users AS u, wp_usermeta AS m
WHERE m.user_id = u.ID AND m.meta_key = "user_apikey";
</code>
As far as the file system goes, there is a folder which has the same name as a user's username for each user, all in the same directory. This user's folder may or may not already exist. When a user makes an SFTP connection to the server, they should be shown only the contents of that folder once authenticated.
Hopefully someone knows of a simple solution to this problem. The only limitation I have is that this must run on a CentOS box, but I'm pretty open to any tools and languages.
Comment: I know proftpd can use mysql as a source for authentication.  It also has a sftp plugin.
Comment: just for future reference, there are instructions for using [proftpd authentication using mysql](http://www.khoosys.net/single.htm?ipg=848)
Answer: You can replace the backends of PAM and the Name Service Switch (NSS) with a MySQL backend. You will need pam-mysql and libnss-mysql.
Might be overkill just to get one app to use MySQL, but figured I should mention it.


How to efficiently select partial data from RDBMS tables in Pyspark

Question: Let's assume I have an employee table like this:
| employee_id | employee_name | department | created_at          | updated_at          |
|-------------|---------------|------------|---------------------|---------------------|
| 1           | Jessica       | Finance    | 2020-10-10 12:00:00 | 2020-10-10 12:00:00 |
| 2           | Michael       | IT         | 2020-10-10 15:00:00 | 2020-10-10 15:00:00 |
| 3           | Sheila        | HR         | 2020-10-11 17:00:00 | 2020-10-11 17:00:00 |
| ...         | ...           | ...        | ...                 | ...                 |
| 1000        | Emily         | IT         | 2020-10-20 20:00:00 | 2020-10-20 20:00:00 |

Usually, I can batch the data in Pyspark using JDBC connection and write to GCS like this:
df = spark.read.format("jdbc") \
    .option("url", "jdbc:postgresql://{ip_address}/{database}") \
    .option("dbtable", table_source) \
    .option("user", user_source) \
    .option("password", password_source) \
    .option("driver", "org.postgresql.Driver") \
    .load()

df.write.parquet("gs://{bucket_name}/{target_directory}/")

When I create df like my code above and using .load(), does the data still in the database server or spark download all the data from the table and move it to spark cluster (assuming the database and spark cluster placed on different server).
And if I need to get specific data in time range let's say I need the data where created_at > 2020-10-15 00:00:00
does the code below enough? because I found it really slow when the data size reach more than 25 GB
df = spark.read.format("jdbc") \
    .option("url", "jdbc:postgresql://{ip_address}/{database}") \
    .option("dbtable", table_source) \
    .option("user", user_source) \
    .option("password", password_source) \
    .option("driver", "org.postgresql.Driver") \
    .load()

df.createOrReplaceTempView("get_specific_data")

get_specific_data = spark.sql('''
                        SELECT employee_id, employee_name, department, created_at, updated_at
                        FROM get_specific_data
                        WHERE created_at > '2020-10-15 00:00:00'
                        '''

get_specific_data.write.parquet("gs://{bucket_name}/{target_directory}/")

My question is more like how to efficiently get specific data in Pyspark if I know what data I need to retrieve by column created_date (or any other column, by ID, or something else). Do I need spark sql for this? or using another tools? (for the purpose of to batch the data daily)
Answer: Turns out if I specify only the table name in table_source it will load all the data into spark cluster.
To select specific data that I need, I can use something just like this:
last_update = '2020-10-15 00:00:00'
table_source = "(SELECT employee_id, employee_name, department, created_at, updated_at " \
               "FROM get_specific_data WHERE created_at > '{0}') t1".format(last_update)

df = spark.read.format("jdbc") \
    .option("url", "jdbc:postgresql://{ip_address}/{database}") \
    .option("dbtable", table_source) \
    .option("user", user_source) \
    .option("password", password_source) \
    .option("driver", "org.postgresql.Driver") \
    .load()

# And then write the data to parquet file
get_specific_data.write.parquet("gs://{bucket_name}/{target_directory}/")

Comment: it's actually `option("query", table_source)`


Select all occurrences of a word in WebStorm

Question: Simple question: I am looking for the shortcut in WebStorm to select all the occurrences of a word and then replace them
e.g in my CSS file I want to select all the 'phone' variables at once and change them to 'tab-port'
Answer: Use Ctrl+ R for find and replace. This will open up a dialog at the top of the file that will look similar to the following: (depending on your IDE theme)
Answer: If you want to select all occurrences directly in the code, you can select all of them with the next shortcut:
Ctrl + Cmd + G on Mac OS X or
Ctrl + Alt + Shift + J on Windows
If you want to replace all occurrences, you can make as chazsolo said.


Finding absolute minimum and maximum of a multi-variable function

Question: Find the absolute maximum and minimum values of the function:
$$
f(x,y) = \sqrt{(x-1)^2+y^2}-x^2+2x
$$
restricted to the area
$$
D =  \{ (x,y): \sqrt{(x-1)^2+y^2} \leq (1/2)\}
$$
I've already found the critical points of f, being ((3/2),0) and ((1/2),0) by taking the partial derivatives, setting them to zero and substituting them back in.
Would appreciate some help on how I can go onwards to find the min/max. Thanks!
Comment: Hint: You have to study the boundary.
Comment: The boundary of the area? I've drawn the area as a circle with center in (1,0), and r=1/2. And then tried putting in the (x,y) of the extremas in the original function f. Each time I got the same values; 1.25.
Answer: You found some critical points, but they are not in the interior of $D$. In this case the extrema will occur at the boundary of $D$. There you can use Lagrange multipliers or just notice that on the boundary you have that $f(x,y)=\frac 12 -x^2+2x$ and $x \in [\frac 12, \frac 32]$. The minimum is attained at $x = \frac 12, \frac 32$ and the maximum at $x = 1$.
We conclude that the global minimum is
$$
m = f(\frac 12,0) = f(\frac 32, 0) = \frac 54
$$
and the global maximum is
$$
M = f(1,\frac 12) = f(1,-\frac 12) = \frac 32.
$$
Comment: Thanks for the comment! I've already tried what you said; writing f(x,y) as you said and I then drew the area (which I saw was a circle with x from 0.5 to 1.5). I then tried putting the values I saw in the original function, but the values I got were all the same; 1.25. I'm submitting the answers on an online platform, where I can "verify" my answers, and 1.25 isn't correct for neither maxima nor minima. I'm not good with the Lagrange multipliers, although I've looked around and I see there's a way to solve my problem with that, as you suggested.
Comment: @MartinPham I don't understand the problem...  There are no critical points in the interior of $D$, so the max/min are attained at the boundary. Since on the boundary $f=\frac 12 -x^2 +2x$, the min is attained when $x = \frac 12, \frac 32$ (the points from before), and the maximum is attained when $x =1$ ( with $y = \pm \frac 12$). The minimum is attained at $(\frac 12 ,0)$ and $(\frac 32, 0)$ and the maximum is attained  at $(1,\frac 12)$ and $(1,-\frac 12)$.
Answer: Attempt:
Domain is a circle center $(1,0)$, radius 1/2.
$f(x)=$
$\sqrt{(x-1)^2+y^2}-(x-1)^2+1$;
Maximum:
at $x=1$, $y=\pm 1/2$;
$f_{max}=1/2+1=3/2$.
Minimum: Set $y=0$;
$f=|x-1|-(x-1)^2+1=-[(|x-1|^2-|x-1|)+1=$
$-[|x-1|-1/2]^2+1/4+1$ ;
$f_{min}= 5/4$; at $y=0$, $|x-1|=1/2$, i.e. at $y=0 $, $x_1=3/2$; $x_2=1/2$;


Behavior of $\sum a_n x^n$ given $\sum |a_n - a_{n-1}| < \infty$

Question: Let $(a_n)_{n=0}^{\infty}$  be a sequence of real numbers satisfying $\sum_{1}^{\infty} |a_n - a_{n-1}| < \infty$
Which of the following conclusions must then be true?
The series $\sum a_nx^n$ converges

Nowhere on $ \mathbb{R}$
Everywhere on $  \mathbb{R}$
On some interval containing $(-1,1)$
Only on $(-1,1)$

What I have tried is Make an inequality with $|a -b| \leq |a| +|b|$ .. but i cant proceed further .. Any sort of help will be deeply appreciable .
Comment: *Hint.* You have $$(1-x)\sum_{n=0}^{\infty} a_n x^n = a_0 + \sum_{n=1}^{\infty} (a_n - a_{n-1}) x^n $$ whenever the series $\sum_{n=0}^{\infty} a_n x^n$ converges.
Comment: How to proceed further with this
Answer: Let $K=\sum_{n=1}^{\infty}|a_n-a_{n-1}|.$ For $n\geq 1$ we have $$|a_n|\leq |a_0|+|a_n-a_0|= |a_0|+|\sum_{j=0}^{n-1}(a_j-a_{j+1})|\leq |a_0|+\sum_{j=0}^{n-1}|a_j-a_{j+1}| \leq |a_0|+K.$$
So $\sup \{|a_n|:n\geq 0\}\leq |a_0|+K<\infty.$
Therefore $\sum_{n=0}^{\infty} a_nx^n $ converges whenever $|x|<1,$ by comparison to the (absolutely convergent) geometric series $\sum_{n=0}^{\infty}(|a_0|+K)|x|^n.$
The correct answer is #3. Case #4 is false if $a_n=0$ for every $n$ .(Case #4 is also false if $a_n=1/n!$ for every $n$, when the power series converges for all $x.$)  Case #2 is false if $a_n=1$ for every $n,$ and $x=1$. (Case #2 is also false if $a_n=1+\frac {1}{n+1}$ for every $n,$ and $|x|\geq 1.$)


How do I solve $\frac {(x^3-4x^2+5x-6)}{(x^2-x-6)}$ using long division?

Question: I tried to solve $\frac {(x^3-4x^2+5x-6)}{(x^2-x-6)}$ using long division...
$x^2-x-6$ / $x^3 -4x^2+5x-6$ \ $x-3 $
$\underline{x^3 - x^2 - 6x}$    -
$-3x^2$
$\underline{-3x^2-3x-18}$ -
$4x+12$

I made some mistake here... How do I solve this step-by-step?
Comment: @amWhy are you sure that is correct? See also Alijah's answer.
Comment: I spotted a later error, and tried to correct your subsequent work. Alijah found an earlier error that I missed, and correctly went on from there.
Answer: Please see the image below for the long division process - sign changes due to subtraction are highlighted in red.


Visual Studio 2022 ASP.NET Core 6 Default application and Add folder to workspace in Chrome DevTools is not working anymore

Question: After some update to either Visual Studio (I have the same issue in both VS2019 and VS2022) or Chrome I can no longer update the CSS in DevTools and have it reflect and persist the changes to site.css file in my project. Instead when I try to change a CSS property I get the following in the DevTools console:
Unable to find a stylesheet to update. Updating all local css files.
15:54:01.800 aspnetcore-browser-refresh.js:82

And the green dot disappears from my CSS pane immediately after I hit the up or down arrow on my keyboard to try and change the CSS value.
Why is that? It used to work not too long ago. I think it's been broken for me for half a year or so now.
I've been googling but haven't find any good resources. Or maybe I'm the only one coding directly in Chrome? :) Surely this can't be the case?
If anyone knows a workaround please share because I'm really frustrated atm :)
Answer: Disabling "Enable CSS Auto-Sync" seems to do the trick.

Update 1: The above no longer works for me for some reason. I managed to find another fix on SO: https://stackoverflow.com/a/70096917/687549
And here are some screenshots:

Update 2: Update 1 works when you only need to update the CSS directly in Chrome. It's better to have Hot Reload enabled and the set the following setting to None - then you'll get the best of both worlds (Hot Reload + Edit CSS directly in Chrome using workspaces): https://stackoverflow.com/a/68954979/687549
Update 3: I'm now using VSCode. If none of the above works try the following (block .js file in Network tab in Chrome DevTools): https://stackoverflow.com/a/68966524/687549


Is Paley-13 graph a unit distance graph in 3D space?

Question: The 13-node Paley graph has vertices 1 to 13 that are connected by an edge when their difference is one of the values
$(1,3,4,9,10,12)$
Can this graph be put into 3D space so that all edges have length 1, making it a unit distance graph?  The graph has chromatic number 5, so this would be a nice object for the 3D Hadwiger–Nelson problem.
Comment: A dimension count makes it seem unlikely.  13 vertices in Euclidean space have $3V - 6 = 33$ degrees of freedom (modulo isometries of $\mathbb{R}^3$).  The Paley-13 graph has $39$ edges, so generically we shouldn't get to decide all of the edge lengths.
Comment: Actually, I think my dimension count argument above is completely unconvincing.  The same argument holds for *any* deltahedron of genus one: since such a polyhedron must satisfy $2E=3F$ and $V-E+F=0$, we always get $3V - E=0$.  But of course deltahedra of genus one do exist.
Comment: I like this question.  See [here](http://www.weddslist.com/groups/genus/1/t13.png) for a nice drawing of this graph on a torus.
Comment: If it were embeddable, it would be a be a non-convex [deltahedron](http://en.wikipedia.org/wiki/Deltahedron) of [genus one](http://en.wikipedia.org/wiki/Toroidal_polyhedron).
Comment: By the way, according to [Wikipedia](http://en.wikipedia.org/wiki/Hadwiger%E2%80%93Nelson_problem#Variations_of_the_problem), it is known that the chromatic number of 3D space is at least six.  Doesn't that make this graph irrelevant to the Hadwiger-Nelson problem?
Comment: I'm trying to compile unit distance graphs with chromatic number 5. I'm hoping I can use them to build a graph with chromatic number 6, and that can be used to bump the lower bound to 7.
Answer: No such embedding exists. The proof below is not fully rigorous, but should be convincing enough.
Number the vertices like this:

As in this answer I am going to explicitly construct the graph's vertices starting from a few parameters. The following parameters suffice in this case:

The angles $\angle1,0,3$, $\angle3,0,9$, $\angle9,0,1$. All must lie in $(0,2\pi/3]$ (otherwise the points $4,12,10$ cannot be constructed) and they must satisfy the triangle inequality.
Whether the points $4,12,10$ are constructed "above" ($+$) or "below" $(-)$ the $0,1,3,9$ plane (just like there are in general two solutions for a point at unit distance from two other points in the plane, so there are in general two solutions for a point at unit distance from three other points in 3D space).

By symmetry we can reduce the eight possibilities for the second set of parameters to four: $+++,++-,+--,---$. Without loss of generality we can also fix $0=(0,0,0)$, $1=(1,0,0)$, point $3$ in the $xy$-plane and point $9$ with positive $z$-coordinate – the parameters above then fix points $4,12,10$.
The remaining six points are uniquely determined. To see this, note that $0$ and $2$ are both adjacent to $1,3,12$; with all distances identical and the requirement that vertices not coincide it is easy to deduce that point $2$ must be the reflection of point $0$ in the $1,3,12$ plane. A similar argument applies by rotating the diagram above for the other five "outer" points.

To actually show the non-existence of a 3D unit-distance embedding for Paley-13 we sample over all possible combinations of parameters. For each sample we compute the sum of absolute deviations from $1$ of the nine remaining edges:
$$\{(2, 11), (8, 5), (6, 7), (2, 6), (8, 11), (6, 5), (11, 7), (5, 2), (7, 8)\}$$
If Paley-13 had a unit-distance embedding we would expect some samples to have a deviation sum close to zero, but sampling the continuous parameters using a dense lattice yields the following minimal sums for each sign pattern:
$$+++:1.2676384880260365\\
++-:1.6056266375770387\\
+--:1.2143797215919396\\
---:1.5513409497822102$$
All are far from zero, so we conclude that the Paley graph of order $13$ has no 3D unit-distance embedding.

This is the program I used to derive the minimal deviation sums above.
<code>#!/usr/bin/env python3
import numpy as np

L = 2*np.pi/3
eps = 1e-6
res = 200
coord = np.linspace(eps, L-eps, res+1)
A, B, C = np.meshgrid(coord, coord, coord, indexing="ij")

def tripod(p, q):
    # Construct the point at distance 1 from 0, p and q
    # such that from its perspective the vertices 0-p-q
    # run counterclockwise. Assume |p| = |q| = 1.
    diff = q-p
    d = (diff*diff).sum(axis=-1)[...,np.newaxis]
    k = diff / np.linalg.norm(diff, axis=-1)[...,np.newaxis]
    v = -(p+q) / 2
    kxv = np.cross(k, v)
    kdv = (k*v).sum(axis=-1)[...,np.newaxis]
    return 2 * (np.sqrt(3-d)*kxv + kdv*k - v) / (4-d)

def reflect(p, q, r):
    # Construct the reflection of the origin in the plane
    # defined by p, q, r.
    n = np.cross(q-p, r-p)
    proj = (n*p).sum(axis=-1) / (n*n).sum(axis=-1)
    return 2 * proj[...,np.newaxis] * n

def paleymin(signs):
    K0 = np.zeros_like(A)
    K1 = np.ones_like(A)
    p0 = np.stack([K0, K0, K0], axis=-1)
    p1 = np.stack([K1, K0, K0], axis=-1)
    p3 = np.stack([np.cos(C), np.sin(C), K0], axis=-1)
    dh = (np.cos(A) - np.cos(B)*np.cos(C)) / (np.sin(B)*np.sin(C))
    np.clip(dh, -1, 1, dh)
    p9 = np.stack([np.cos(B), dh*np.sin(B), np.sqrt(1-dh**2)*np.sin(B)], axis=-1)
    p4 = tripod(p1, p3) if signs < 1 else tripod(p3, p1)
    p12 = tripod(p3, p9) if signs < 2 else tripod(p9, p3)
    p10 = tripod(p9, p1) if signs < 3 else tripod(p1, p9)
    p2 = reflect(p1, p3, p12)
    p8 = reflect(p4, p12, p9)
    p6 = reflect(p3, p9, p10)
    p11 = reflect(p12, p10, p1)
    p5 = reflect(p9, p1, p4)
    p7 = reflect(p10, p4, p3)
    pts = [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12]
    test_edges = ((2, 11), (8, 5), (6, 7), (2, 6), (8, 11), (6, 5), (11, 7), (5, 2), (7, 8))
    distances = sum(abs(np.linalg.norm(pts[i]-pts[j], axis=-1) - 1) for (i,j) in test_edges)
    return distances.min()

for s in range(4):
    print(s, paleymin(s))
</code>
Comment: I wonder whether the following idea works: it is known that the 13-vertex Paley graph needs at least six dimensions for an embedding that is as symmetric as the graph. Can you show by some of your arguments in the first part that if there is a 3-dimensional embedding, then it must be essentially unique (because then it would be highly symmetric, which is not possible in 3D)? Or maybe you can argue directly that a unit distance embedding must be highly symmetric. If so, then we could skip the computational part.


Tornar token do Facebook permanente

Question: Fiz uma configuração para integraçao com Facebook e a API está ativa mas quando vai se processada dá o erro.

Graph returned an error Usuario: (#200) The user hasn't authorized the
  application to perform this action.

Já fui no developers do Face e ta tudo OK com a configuração e extensão do Token.
O que pode gerar isso?
Há algum jeito de deixar o Token permanente para não perder a integração?
Se troco a senha do facebook o token é desabilitado?
Comment: Que eu saiba esse token do FB tem prazo de validade, só não sei de quanto tempo, fora as medidas de segurança de desativam o token em certos casos..
Comment: Por que essa última pergunta? Você trocou a senha?
Answer: Amigo, essa mensagem indica que o usuário não deu a(s) autorizações necessárias a APP. Sugiro que vc delete a APP no facebook e faça login novamente que as permissões serão pedidas novamente.

Tornar token do Facebook permanente


Change "global" datasource dynamically

Question: I usually set application-wide datasource name in the Application.cfc first rows:
<code><cfscript>THIS.datasource="mydsn";</cfscript>
</code>
What if I need to change it in certain part of my code?
To be specific, I mean:

if the cgi.server_name equals "www.firsturl.com"  => this.datasource = "firstdsn"
if the cgi.server_name equals "www.secondurl.com" => this.datasource = "seconddsn"

Can I do that for each request?
Comment: This would be pretty easy for you to simply test and see what happens, surely?  Just put a conditional around your declaration of `this.datasource` in your Application.cfc...
Answer: OK, my comment on your original post notwithstanding - that the best way to find out these things is just try it and see what happens, the answer is: yes.
Application.cfc is poorly named, because it implies it's kind of application-specific, but in reality the entire thing is instantiated every request.  That some of the event handlers only run in given situations (onApplicationStart / onSessionStart etc) is neither here nor there: the whole thing runs every request.  So as with any CFC being instantiated, the pseudo-constructor code (where you make your this-scoped variable declarations) is also run every request.
This means that yes you can conditionally set any of those variables based on REQUEST-specific information (request, CGI, URL, FORM etc; but not APPLICATION or SESSION).  So your condition based on a CGI variable will work just fine.
But don't take my word for it: try it!  Always try these things.
Finally, just to plug myself slightly, I discuss when things run in Application.cfc in some depth on my blog, in this article.  Maybe give it a read, and perhaps look at the other articles on Application.cfc whilst you're there.
Comment: Yeah, there's some weirdness (and not what one would necessarily expect).  Too much (and not on topic) to go through, but I cover it on my blog: http://adamcameroncoldfusion.blogspot.co.uk/2012/09/curious-behaviour-with-this-scoped.html
Comment: I haven't tested this, but I would presume that care is required using this method if any queries are happening inside of onSessionEnd, since the CGI scope wont have the expected values.

Change "global" datasource dynamically


Django : How to add/remove/update translation phrases (in po files) in django admin area?

Question: How can we manage translation phrases stored in local\fa\LC_MESSAGES\django.po files by Django Admin area ?
I am looking for a package which able to update and compile django translation files like updating models in django Admin area
I am using Django 1.10
edited for Mohsen's replay
I am exactly looking for package like this :
this image in designed in photoshop
Answer: Every content that exists in *.po files is not directly related to models, for example if you sets verbose_name of model field by django ugettext this content exist on the *.po file, but other thins such as template trans tag content also exist on these files.
You can use models translation apps such as django-modeltranslation to translate models on the admin but you cant translations that not used directly definitioned on the models fields.
Comment: thanks mohsen, this is not what i am looking for. i am looking for django translation online editor in django admin panel
Comment: Ok, but translation must compile after change and django server reload to new translations applied. by this reasons i think you cant find any django app that made for this aim.
Comment: thanks mohsen, for one of my project i designed a django middle-ware to do that, but it seems there is no django package for this problem


Scrolling floating/sliding sidebar issue

Question: I've looked through all stuff in here related to what I'm facing, but still can't get it fixed.
What I'm trying to do:

Get a sidebar navigation to float as the user scrolls up/down the page.
To have the sidebar centrally stopping so that all elements can be seen and clicked.

What I'm getting:

Sidebar follows scrolling just fine when scrolling down (centralised view), but when scrolling up, only half of the sidebar is displayed when the page is scrolled up too fast.
When scrolling down the page, the sidebar will push the footer further below without end.
The sidebar will not lock back into its original position when the page is scrolled all the way up from the bottom. There seems to be a slight gap.

Demo Link
Here is the script (modded from the generous Jordon Mears):
<code><script type="text/javascript">
function animate_box() {
var offset = -15; /* set this to the starting margin-top in the css */
var element = document.getElementById('animate_box');

if(element) {
    var top = Number(String(element.style.marginTop).substring(0,String(element.style.marginTop).indexOf('px')));

    try {
        if(document.body.scrollTop > 500) {
            var difference = (document.body.scrollTop + offset);
        } else if(document.documentElement.scrollTop > 0) {
            var difference = (document.documentElement.scrollTop + offset);

        } else {
            var difference = offset;
        }
    } catch(e) {
        var difference = offset;
    }

    difference = difference - top;

    if(difference > 200) {
        element.style.marginTop = (top + Math.abs(Math.ceil(difference / 30))) + 'px';
    } else if(difference < 190) {
        element.style.marginTop = (top - Math.abs(Math.ceil(difference / 30))) + 'px';
    }
}
}
window.setInterval(animate_box, 50);
</script>
</code>
Comment: How exactly do you want it to float? Haha, I was gonna say the same @PraveenKumar
Comment: True @PraveenKumar Main reason why I asked about how he wants it to float is because if he's using Javascript, then there must be some floaty effect he wants, cuz this should have been easy to implement otherwise.
Comment: Why do you wanna animate? Why can't you use `position: fixed;`?
Comment: @Andy Any basic web developer would ask this, if the OP is not going to code this for `IE 6`.
Comment: My apologies, silly of me not to include the sample site: http://demo.blufroge.com/index.php?m=main&c=show_shopping_details_all&subCateId=2
Comment: See the sidebar there? So the 'animated' that I mentioned is just that: it moves according to where the user scrolls. Sorry, am just an amateur coder >.<
Answer: I suggest a different approach:

save the starting position of the element (.offset().top)
when scroll happens:
if the window scroll offset (.scrollTop()) is more than the starting position, then change the position of the sidebar to "fixed" with "top: 0"
if it goes under the starting position change it back to static (default position).

Something like this:
<code>$(function() {
    var backup_position_toolbar = $('#sidebar').offset().top;
    $(window).scroll(function() {
        if ( $('#sidebar').offset().top - $(window).scrollTop() < 0) $('#sidebar').addClass('fixed');
        if ( $(window).scrollTop() < backup_position_toolbar ) $('#sidebar').removeClass('fixed');
    });
});
</code>

Note that I use a "fixed" class defined as follows:
    .fixed {
        position: fixed;
        top: 0;
    }
This makes the menu more usable.
If you want to block the sidebar at a certain point you can add a little more logic (ie when bottom is too close).
In this way you don't need to set numeric values (500, 200 etc).
HOWEVER if you want something more with no effort try bootstrap with "affix" (look at the left menu, is what you want)
http://twitter.github.com/bootstrap/javascript.html#affix
Comment: Thanks! I'll go experiment with it :)


Number of combinations leading to ties between the second and third places in the FIFA World Cup

Question: I read on Wikipedia that the number of combinations leading to a tie between the second and third place in an initial group (of four teams) in the FIFA World Cup is $207$.  How is this calculated?
I understand that if we consider all possible outcomes (win, draw, loss) for all six matches in a group of four teams, there are $3^{6}$ combinations possible. Only one team out of the four in the group can win all three games, and so score $9$ points ($3$ points are allocated for a win, $1$ for a draw and $0$ for a loss). Let's say one team in this group loses all three its games, and the remaining two teams each has one win and one draw, then we have a tie between second and third place, and there are twelve ways this can happen.
Similarly, the winning team in the group (say $t_0$) could win two games (beating $t_2$ and $t_3$ say) and draw one (with $t_1$).  If there was a draw between $t_2$ and $t_3$, $t_1$ beat $t_2$ and $t_3$ beat $t_1$, $t_1$ and $t_3$ end up in a tie for second and third place with four points each.  There are again twelve ways this can happen.
I can't quite get to 207 though?
Comment: So it's second and third place in the initial groups, not in the world cup as a whole, maybe you should make that a little clearer.
Comment: I think there are $36$ ways you can have 1 team with two wins one draw, 2 teams with one win one draw one loss, and 1 team with one draw two losses (a slight expansion of your second example).  Overall I see $14$ points distributions leading to your second/third place issue and indeed $207$ overall possibilities out of the $40$ points distributions with $729$ in total
Comment: What number did you get to, and how?
Answer: I doubt that you can avoid a rather tedious case-by-case analysis, which is best checked with a computer.
Suppose the teams are called A, B, C, D, and that we list the games in the order A–B, A–C, A–D, B–C, B–D, C–D. Then, for example, the results 11XX11, 1X11X1 and X1121X (and no others) lead to the teams A, B, C, D obtaining 7, 4, 4, 1 points, respectively. This then tells you all the ways of getting a table where the best team has 7 points, the second and third are tied at 4 points, and the last team has 1 point, namely you can choose which teams that should "play the roles of A and D" above, and this can be done in 4·3=12 ways. For each of these 12 choices, you have the three scenarios above, so you get 3·12=36 ways of having a tied situation with the distribution of points (7,4,4,1).
Below is the complete list of possible outcomes with a tie for second and third place. The listed game results are the ones that will result in A, B, C, D (in that order) having the points listed, and then you have to multiply that number of cases by the suitable combinatorial factor to get the stated total number of ways of getting that distribution of points with the teams in any order.

XXXXXX (3,3,3,3) 1 way
12X1XX / 21X2XX (4,4,4,3) 8 ways
1X21X1 / 21XX21 / X1221X / X2112X / 12XX12 / 2X12X2 / 2X12X2 (4,4,4,4) 6 ways
XX1XXX (5,3,3,2) 12 ways
1XX1X1 / X1X21X (5,4,4,2) 24 ways
XX1121 / XX1212 (5,4,4,3) 24 ways
XX1X11 (5,5,5,0) 4 ways
1211XX / 2112XX (6,4,4,2) 24 ways
112X11 / 211X21 / 121X12 (6,4,4,3) 36 ways
121111 / 211211 (6,6,6,0) 8 ways
11XX11 / 1X11X1 / X1121X (7,4,4,1) 36 ways
111XXX (9,2,2,2) 4 ways
111121 / 111212 (9,3,3,3) 8 ways
111X11 (9,4,4,0) 12 ways

In all, 1+8+6+12+24+24+4+24+36+8+36+4+8+12 = 207 ways.


How to convert a dot product of two vectors to the angle between the vectors.

Question: I am currently learning to use normalized vectors in the computer games I'm creating.
I've learned that in order to know "the angle" between two vectors, I need to use Dot Product. This gives me a value between $1$ and $-1$. $1$ means they're parallel to each other, facing same direction (aka the angle between them is $0^\circ$). $-1$ means they're parallel and facing opposite directions ($180^\circ$). And $0$ means the angle between them is $90^\circ$.
But I want to know, how to convert the dot product of two vectors, to an actual angle in degrees.
For example, if the dot product of two vectors is $0.28$. How can I convert it to an actual angle, between $0^\circ$ to $360^\circ$?
Thank you
Comment: @user3150201: No this is precisely *not* what he said. In order to get the angle between two vectors you need to take the arccos of the dot product.
Comment: From your setting it seems that the vectors are of length one. Then  the angle $\theta$ is just $\cos\theta = (v_1\cdot v_2)$. I am more interested in what games you are playing though.
Comment: I meant games I'm *making* :) . And yes, I'm talking about normalized vectors with length 1.
So you're saying that in order to get the angle between two vectors, I don't even need their dot product?
Answer: The dot product of two normalized vectors is equal to the cosine of the angle between them. In general
$$\cos \phi = \frac{a\cdot b}{|a||b|},$$
since your vectors are normalized, $|a|=|b|=1$ and $\phi = \arccos(a\cdot b)$
Comment: Worth noting is that the angle yielded would currently be in radians and is the range is the absolute `[0,pi]` angle between the vectors, not the `[0,2pi)` angle you need to do a planar rotation in the same direction to get from `a` to `b`. To reconstruct the full range you need to determine whether to pick the small or the complementary large angle between the vectors.
Comment: So what you're saying is that the angle between two normalized vectors, is the arccos of their dot product?
Comment: @5xum and how exactly can I determine if the angle should be small or complementary? I mean, in e.g. a computer program that should return the angle from `[0, 2pi)` range for any two given `a` and `b` vectors?
Comment: That is exactly what I am saying. If they aren't normalized, just divide the dot product by their norms.
Answer: Because you want an answer in the range [0,2pi) and not [0,pi], I think that the question's title is misleading.  I think that you are asking, "How can I calculate the angle that will change the direction from vector a to vector b?"
I would not use the arccos formula for dot products, but instead use the arctan2 function for both vectors and subtract the angles.  The arctan2 function is given both x and y of the vector so that it can give an angle in the full range [0,2pi) and not just [-pi,pi] which is typical for arctan.
The angle you are looing for would be given by:
<code>arctan2(b_y, b_x) - arctan2(a_y, a_x)
</code>
The result may be a negative angle, but at least it will go from vector a to vector b.  If you want only positive angles, then add 2pi when the angle is negative.
Beware that arctan2 takes y then x.  This is to be similar to arctan which takes y/x as input.
Comment: If you came looking for how to work out camera angles in shader code, this was the right answer


Using locale (language+country) in URL for Symfony2

Question: I'm building an international website in Symfony2. My URL looks likes this:
www.test.com/en_HK
This should display english text and prices in HongKong dollars. The english text part is already working. Is there a Symfony function available to get the country-code from the locale?
The locale contains the "languagecode_COUNTRYCODE". Or should i write some lines of code the distract the countrycode from the locale?
Answer: No, there's no function to do this directly because locales can be 2 letters:
ex. en, fr, de
SonataIntlBundle provides some ISO Code expansion, but not what you're looking for
http://sonata-project.org/bundles/intl/master/doc/reference/locale.html
The Locale component comes close, with that you can do:
<code>$countryCodes = Locale::getCountries('en_HK');
</code>
It should be fairly trivial to write a service to do this:
<code>class CountryCodeExtractor
{
    function fromLocale($locale)
    {
        if(strlen($locale) == 4){
            return substr($locale, -2);
        }
        else throw new \Exception("Invalid locale passed");
    }
</code>
something similar to that. Obviously you'll want better validation of the input locale.


If $G$ be an open set, then show that $H=\{xy: x, y \in G \}$ is open in $\mathbb{R}$

Question: Let $G$ be an open subset of $\mathbb{R}$.

If $0 \notin G$ then show that $H=\{xy: x, y \in G \}$ is an open subset in $\mathbb{R}$.
If $0 \in G$ and if $x+y \in G$, for every $x, y \in G$ then show that $G = \mathbb{R}$.

Attempt:

$G$ being open, $\forall x \in G$, $\ \exists \epsilon>0$, such that $(x-\epsilon, x+ \epsilon) \subset G$.

Let $T = \{zy: z\in (x- \epsilon, x+\epsilon), y \in \mathbb{R} \setminus \{0\} \}$. $T$ is clearly a connected and an open set, since when $y>0$, $ \ x- \epsilon<z < x+\epsilon \implies xy-y \epsilon<zy<xy+y \epsilon$, similarly the case in $y<0$.
Now, $H= \displaystyle[\bigcup_{0<y  \in G} {(xy-y \epsilon,xy+y \epsilon)}] \displaystyle\bigcup[\bigcup_{0>y  \in G} {(xy+y \epsilon,xy-y \epsilon)}]$
Clearly, $H$ is open, being an infinite union of open sets.

Since $0$ is in $G$ and the set is open, $\exists$ some $\epsilon>0$ such that $(-\epsilon, \epsilon) \subset G$.

Now, $ -\epsilon< s, r < \epsilon  \implies -2 \epsilon < s+r < 2 \epsilon.$. By the Archimedean property, any $N \in \mathbb{R}$ can be made less than $n \epsilon$ by suitable choice of $n \in \mathbb{N}$, i.e. $(-N,N) \subset (-n \epsilon, n \epsilon)$ $\forall N \in \mathbb{R^+}$. Hence, $G = \mathbb{R}$.
Please verify.
Comment: For (1), a simpler proof: $H=\bigcup_{x\in G} xG$, being a union of open sets, hence open.
Comment: @YuiToCheng: $0G$ is not open.
Comment: @copper.hat The OP excludes $0$ from $G$ (You must be reading too fast...)
Comment: @YuiToCheng: I was being too general :-). Even if $0 \in G$ the set $G \cdot G$ is still open.
Comment: @copper.hat You have a point.
Answer: If $y \neq 0$ then $\{yx \}_{x \in G}$ is open. Hence $\cup_{y \in G, y \neq 0} \{yx \}_{x \in G}$ is open.
If $0 \notin G$, then it is clear that $\{xy\}_{x,y \in G}$ is open.
If $0 \in G$, then $(-\epsilon, \epsilon) \subset G$ for some $\epsilon>0$ and so
$0 \in {1 \over 2} \epsilon \cdot (-\epsilon, \epsilon) \subset {1 \over 2} \epsilon \cdot
 G$, and so
$0 \in \cup_{y \in G, y \neq 0} \{yx \}_{x \in G}$ and so
$\cup_{y \in G} \{yx \}_{x \in G} = \cup_{y \in G, y \neq 0} \{yx \}_{x \in G}$ and hence it is open.
In the latter case, since $n G \subset G+\cdots + G = G$, we see that $(-n\epsilon, n \epsilon) \subset G$ for all $n$.
Comment: The second question?
Comment: @YuiToCheng: I don't have a better proof than that of the OP :-(.
Comment: Is my proof enough (1st one?)
Comment: @SubhasisBiswas: I can't follow your proof for 1. I don't see how $T$ plays a part in the proof.
Comment: Yours is a good one .
Comment: T is practically useless in that proof.
Comment: I used it to show that upon multiplication by a real, an open interval remains open
Comment: @SubhasisBiswas: It would suffice to show that $x \mapsto yx$ has a continuous inverse $x \mapsto {1 \over y} x$. Then either function maps open sets to open sets. (I just took it for granted, sorry :-).)
Comment: :( missed it.  Now I have another question for you to verify. It has gone unanswered.
Comment: https://math.stackexchange.com/q/3195987/389992
Comment: @SubhasisBiswas: Will look tomorrow, bedtime for me now :-).
Comment: Sure! Just remember to check that out